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.

274692 lines
7.3MB

  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_WINDOWS && JUCE_32BIT) || JUCE_PPC) // 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_BitArray.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_BitArray.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_Variant.cpp ***/
  3142. BEGIN_JUCE_NAMESPACE
  3143. var::var() throw()
  3144. : type (voidType)
  3145. {
  3146. value.doubleValue = 0;
  3147. }
  3148. var::~var() throw()
  3149. {
  3150. if (type == stringType)
  3151. delete value.stringValue;
  3152. else if (type == objectType && value.objectValue != 0)
  3153. value.objectValue->decReferenceCount();
  3154. }
  3155. const var var::null;
  3156. var::var (const var& valueToCopy)
  3157. : type (valueToCopy.type),
  3158. value (valueToCopy.value)
  3159. {
  3160. if (type == stringType)
  3161. value.stringValue = new String (*(value.stringValue));
  3162. else if (type == objectType && value.objectValue != 0)
  3163. value.objectValue->incReferenceCount();
  3164. }
  3165. var::var (const int value_) throw()
  3166. : type (intType)
  3167. {
  3168. value.intValue = value_;
  3169. }
  3170. var::var (const bool value_) throw()
  3171. : type (boolType)
  3172. {
  3173. value.boolValue = value_;
  3174. }
  3175. var::var (const double value_) throw()
  3176. : type (doubleType)
  3177. {
  3178. value.doubleValue = value_;
  3179. }
  3180. var::var (const String& value_)
  3181. : type (stringType)
  3182. {
  3183. value.stringValue = new String (value_);
  3184. }
  3185. var::var (const char* const value_)
  3186. : type (stringType)
  3187. {
  3188. value.stringValue = new String (value_);
  3189. }
  3190. var::var (const juce_wchar* const value_)
  3191. : type (stringType)
  3192. {
  3193. value.stringValue = new String (value_);
  3194. }
  3195. var::var (DynamicObject* const object)
  3196. : type (objectType)
  3197. {
  3198. value.objectValue = object;
  3199. if (object != 0)
  3200. object->incReferenceCount();
  3201. }
  3202. var::var (MethodFunction method_) throw()
  3203. : type (methodType)
  3204. {
  3205. value.methodValue = method_;
  3206. }
  3207. void var::swapWith (var& other) throw()
  3208. {
  3209. swapVariables (type, other.type);
  3210. swapVariables (value, other.value);
  3211. }
  3212. var& var::operator= (const var& value_) { var newValue (value_); swapWith (newValue); return *this; }
  3213. var& var::operator= (int value_) { var newValue (value_); swapWith (newValue); return *this; }
  3214. var& var::operator= (bool value_) { var newValue (value_); swapWith (newValue); return *this; }
  3215. var& var::operator= (double value_) { var newValue (value_); swapWith (newValue); return *this; }
  3216. var& var::operator= (const char* value_) { var newValue (value_); swapWith (newValue); return *this; }
  3217. var& var::operator= (const juce_wchar* value_) { var newValue (value_); swapWith (newValue); return *this; }
  3218. var& var::operator= (const String& value_) { var newValue (value_); swapWith (newValue); return *this; }
  3219. var& var::operator= (DynamicObject* value_) { var newValue (value_); swapWith (newValue); return *this; }
  3220. var& var::operator= (MethodFunction value_) { var newValue (value_); swapWith (newValue); return *this; }
  3221. var::operator int() const
  3222. {
  3223. switch (type)
  3224. {
  3225. case voidType: break;
  3226. case intType: return value.intValue;
  3227. case boolType: return value.boolValue ? 1 : 0;
  3228. case doubleType: return static_cast <int> (value.doubleValue);
  3229. case stringType: return value.stringValue->getIntValue();
  3230. case objectType: break;
  3231. default: jassertfalse; break;
  3232. }
  3233. return 0;
  3234. }
  3235. var::operator bool() const
  3236. {
  3237. switch (type)
  3238. {
  3239. case voidType: break;
  3240. case intType: return value.intValue != 0;
  3241. case boolType: return value.boolValue;
  3242. case doubleType: return value.doubleValue != 0;
  3243. case stringType: return value.stringValue->getIntValue() != 0
  3244. || value.stringValue->trim().equalsIgnoreCase ("true")
  3245. || value.stringValue->trim().equalsIgnoreCase ("yes");
  3246. case objectType: return value.objectValue != 0;
  3247. default: jassertfalse; break;
  3248. }
  3249. return false;
  3250. }
  3251. var::operator float() const
  3252. {
  3253. return (float) operator double();
  3254. }
  3255. var::operator double() const
  3256. {
  3257. switch (type)
  3258. {
  3259. case voidType: break;
  3260. case intType: return value.intValue;
  3261. case boolType: return value.boolValue ? 1.0 : 0.0;
  3262. case doubleType: return value.doubleValue;
  3263. case stringType: return value.stringValue->getDoubleValue();
  3264. case objectType: break;
  3265. default: jassertfalse; break;
  3266. }
  3267. return 0.0;
  3268. }
  3269. const String var::toString() const
  3270. {
  3271. switch (type)
  3272. {
  3273. case voidType: return String::empty;
  3274. case intType: return String (value.intValue);
  3275. case boolType: return String::charToString (value.boolValue ? '1' : '0');
  3276. case doubleType: return String (value.doubleValue);
  3277. case stringType: return *(value.stringValue);
  3278. case objectType: return "Object 0x" + String::toHexString ((int) (pointer_sized_int) value.objectValue);
  3279. case methodType: return "Method";
  3280. default: jassertfalse; break;
  3281. }
  3282. return String::empty;
  3283. }
  3284. var::operator const String() const
  3285. {
  3286. return toString();
  3287. }
  3288. DynamicObject* var::getObject() const
  3289. {
  3290. return type == objectType ? value.objectValue : 0;
  3291. }
  3292. bool var::equals (const var& other) const throw()
  3293. {
  3294. switch (type)
  3295. {
  3296. case voidType: return other.isVoid();
  3297. case intType: return value.intValue == static_cast <int> (other);
  3298. case boolType: return value.boolValue == static_cast <bool> (other);
  3299. case doubleType: return value.doubleValue == static_cast <double> (other);
  3300. case stringType: return (*(value.stringValue)) == other.toString();
  3301. case objectType: return value.objectValue == other.getObject();
  3302. case methodType: return value.methodValue == other.value.methodValue && other.isMethod();
  3303. default: jassertfalse; break;
  3304. }
  3305. return false;
  3306. }
  3307. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3308. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3309. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3310. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3311. void var::writeToStream (OutputStream& output) const
  3312. {
  3313. switch (type)
  3314. {
  3315. case voidType: output.writeCompressedInt (0); break;
  3316. case intType: output.writeCompressedInt (5); output.writeByte (1); output.writeInt (value.intValue); break;
  3317. case boolType: output.writeCompressedInt (1); output.writeByte (value.boolValue ? 2 : 3); break;
  3318. case doubleType: output.writeCompressedInt (9); output.writeByte (4); output.writeDouble (value.doubleValue); break;
  3319. case stringType:
  3320. {
  3321. const int len = value.stringValue->getNumBytesAsUTF8() + 1;
  3322. output.writeCompressedInt (len + 1);
  3323. output.writeByte (5);
  3324. HeapBlock<char> temp (len);
  3325. value.stringValue->copyToUTF8 (temp, len);
  3326. output.write (temp, len);
  3327. break;
  3328. }
  3329. case objectType:
  3330. case methodType: output.writeCompressedInt (0); jassertfalse; break; // Can't write an object to a stream!
  3331. default: jassertfalse; break; // Is this a corrupted object?
  3332. }
  3333. }
  3334. const var var::readFromStream (InputStream& input)
  3335. {
  3336. const int numBytes = input.readCompressedInt();
  3337. if (numBytes > 0)
  3338. {
  3339. switch (input.readByte())
  3340. {
  3341. case 1: return var (input.readInt());
  3342. case 2: return var (true);
  3343. case 3: return var (false);
  3344. case 4: return var (input.readDouble());
  3345. case 5:
  3346. {
  3347. MemoryBlock mb;
  3348. input.readIntoMemoryBlock (mb, numBytes - 1);
  3349. return var (String::fromUTF8 (static_cast <const char*> (mb.getData()), (int) mb.getSize()));
  3350. }
  3351. default: input.skipNextBytes (numBytes - 1); break;
  3352. }
  3353. }
  3354. return var::null;
  3355. }
  3356. const var var::operator[] (const var::identifier& propertyName) const
  3357. {
  3358. if (type == objectType && value.objectValue != 0)
  3359. return value.objectValue->getProperty (propertyName);
  3360. return var::null;
  3361. }
  3362. const var var::invoke (const var::identifier& method, const var* arguments, int numArguments) const
  3363. {
  3364. if (type == objectType && value.objectValue != 0)
  3365. return value.objectValue->invokeMethod (method, arguments, numArguments);
  3366. return var::null;
  3367. }
  3368. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3369. {
  3370. if (isMethod())
  3371. {
  3372. DynamicObject* const target = targetObject.getObject();
  3373. if (target != 0)
  3374. return (target->*(value.methodValue)) (arguments, numArguments);
  3375. }
  3376. return var::null;
  3377. }
  3378. const var var::call (const var::identifier& method) const
  3379. {
  3380. return invoke (method, 0, 0);
  3381. }
  3382. const var var::call (const var::identifier& method, const var& arg1) const
  3383. {
  3384. return invoke (method, &arg1, 1);
  3385. }
  3386. const var var::call (const var::identifier& method, const var& arg1, const var& arg2) const
  3387. {
  3388. var args[] = { arg1, arg2 };
  3389. return invoke (method, args, 2);
  3390. }
  3391. const var var::call (const var::identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3392. {
  3393. var args[] = { arg1, arg2, arg3 };
  3394. return invoke (method, args, 3);
  3395. }
  3396. const var var::call (const var::identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3397. {
  3398. var args[] = { arg1, arg2, arg3, arg4 };
  3399. return invoke (method, args, 4);
  3400. }
  3401. const var var::call (const var::identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3402. {
  3403. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3404. return invoke (method, args, 5);
  3405. }
  3406. var::identifier::identifier() throw()
  3407. : hashCode (0)
  3408. {
  3409. }
  3410. var::identifier::identifier (const String& name_)
  3411. : name (name_),
  3412. hashCode (name_.hashCode())
  3413. {
  3414. /* An identifier string must be suitable for use as a script variable or XML
  3415. attribute, so it can only contain this limited set of characters.. */
  3416. jassert (name.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name.isNotEmpty());
  3417. }
  3418. var::identifier::identifier (const char* const name_)
  3419. : name (name_),
  3420. hashCode (name.hashCode())
  3421. {
  3422. /* An identifier string must be suitable for use as a script variable or XML
  3423. attribute, so it can only contain this limited set of characters.. */
  3424. jassert (name.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name.isNotEmpty());
  3425. }
  3426. var::identifier::~identifier()
  3427. {
  3428. }
  3429. END_JUCE_NAMESPACE
  3430. /*** End of inlined file: juce_Variant.cpp ***/
  3431. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3432. BEGIN_JUCE_NAMESPACE
  3433. NamedValueSet::NamedValue::NamedValue() throw()
  3434. {
  3435. }
  3436. inline NamedValueSet::NamedValue::NamedValue (const var::identifier& name_, const var& value_)
  3437. : name (name_), value (value_)
  3438. {
  3439. }
  3440. NamedValueSet::NamedValueSet() throw()
  3441. {
  3442. }
  3443. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3444. : values (other.values)
  3445. {
  3446. }
  3447. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3448. {
  3449. values = other.values;
  3450. return *this;
  3451. }
  3452. NamedValueSet::~NamedValueSet()
  3453. {
  3454. }
  3455. int NamedValueSet::size() const throw()
  3456. {
  3457. return values.size();
  3458. }
  3459. const var& NamedValueSet::operator[] (const var::identifier& name) const
  3460. {
  3461. for (int i = values.size(); --i >= 0;)
  3462. {
  3463. const NamedValue& v = values.getReference(i);
  3464. if (v.name == name)
  3465. return v.value;
  3466. }
  3467. return var::null;
  3468. }
  3469. const var NamedValueSet::getWithDefault (const var::identifier& name, const var& defaultReturnValue) const
  3470. {
  3471. const var* v = getItem (name);
  3472. return v != 0 ? *v : defaultReturnValue;
  3473. }
  3474. var* NamedValueSet::getItem (const var::identifier& name) const
  3475. {
  3476. for (int i = values.size(); --i >= 0;)
  3477. {
  3478. NamedValue& v = values.getReference(i);
  3479. if (v.name == name)
  3480. return &(v.value);
  3481. }
  3482. return 0;
  3483. }
  3484. bool NamedValueSet::set (const var::identifier& name, const var& newValue)
  3485. {
  3486. for (int i = values.size(); --i >= 0;)
  3487. {
  3488. NamedValue& v = values.getReference(i);
  3489. if (v.name == name)
  3490. {
  3491. if (v.value == newValue)
  3492. return false;
  3493. v.value = newValue;
  3494. return true;
  3495. }
  3496. }
  3497. values.add (NamedValue (name, newValue));
  3498. return true;
  3499. }
  3500. bool NamedValueSet::contains (const var::identifier& name) const
  3501. {
  3502. return getItem (name) != 0;
  3503. }
  3504. bool NamedValueSet::remove (const var::identifier& name)
  3505. {
  3506. for (int i = values.size(); --i >= 0;)
  3507. {
  3508. if (values.getReference(i).name == name)
  3509. {
  3510. values.remove (i);
  3511. return true;
  3512. }
  3513. }
  3514. return false;
  3515. }
  3516. const var::identifier NamedValueSet::getName (const int index) const
  3517. {
  3518. jassert (((unsigned int) index) < (unsigned int) values.size());
  3519. return values [index].name;
  3520. }
  3521. const var NamedValueSet::getValueAt (const int index) const
  3522. {
  3523. jassert (((unsigned int) index) < (unsigned int) values.size());
  3524. return values [index].value;
  3525. }
  3526. void NamedValueSet::clear()
  3527. {
  3528. values.clear();
  3529. }
  3530. END_JUCE_NAMESPACE
  3531. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3532. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3533. BEGIN_JUCE_NAMESPACE
  3534. DynamicObject::DynamicObject()
  3535. {
  3536. }
  3537. DynamicObject::~DynamicObject()
  3538. {
  3539. }
  3540. bool DynamicObject::hasProperty (const var::identifier& propertyName) const
  3541. {
  3542. var* const v = properties.getItem (propertyName);
  3543. return v != 0 && ! v->isMethod();
  3544. }
  3545. const var DynamicObject::getProperty (const var::identifier& propertyName) const
  3546. {
  3547. return properties [propertyName];
  3548. }
  3549. void DynamicObject::setProperty (const var::identifier& propertyName, const var& newValue)
  3550. {
  3551. properties.set (propertyName, newValue);
  3552. }
  3553. void DynamicObject::removeProperty (const var::identifier& propertyName)
  3554. {
  3555. properties.remove (propertyName);
  3556. }
  3557. bool DynamicObject::hasMethod (const var::identifier& methodName) const
  3558. {
  3559. return getProperty (methodName).isMethod();
  3560. }
  3561. const var DynamicObject::invokeMethod (const var::identifier& methodName,
  3562. const var* parameters,
  3563. int numParameters)
  3564. {
  3565. return properties [methodName].invoke (var (this), parameters, numParameters);
  3566. }
  3567. void DynamicObject::setMethod (const var::identifier& name,
  3568. var::MethodFunction methodFunction)
  3569. {
  3570. properties.set (name, var (methodFunction));
  3571. }
  3572. void DynamicObject::clear()
  3573. {
  3574. properties.clear();
  3575. }
  3576. END_JUCE_NAMESPACE
  3577. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3578. /*** Start of inlined file: juce_BlowFish.cpp ***/
  3579. BEGIN_JUCE_NAMESPACE
  3580. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  3581. {
  3582. jassert (keyData != 0);
  3583. jassert (keyBytes > 0);
  3584. static const uint32 initialPValues [18] =
  3585. {
  3586. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  3587. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  3588. 0x9216d5d9, 0x8979fb1b
  3589. };
  3590. static const uint32 initialSValues [4 * 256] =
  3591. {
  3592. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  3593. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  3594. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  3595. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  3596. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  3597. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  3598. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  3599. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  3600. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  3601. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  3602. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  3603. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  3604. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  3605. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  3606. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  3607. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  3608. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  3609. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  3610. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  3611. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  3612. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  3613. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  3614. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  3615. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  3616. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  3617. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  3618. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  3619. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  3620. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  3621. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  3622. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  3623. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  3624. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  3625. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  3626. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  3627. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  3628. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  3629. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  3630. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  3631. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  3632. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  3633. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  3634. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  3635. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  3636. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  3637. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  3638. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  3639. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  3640. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  3641. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  3642. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  3643. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  3644. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  3645. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  3646. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  3647. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  3648. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  3649. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  3650. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  3651. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  3652. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  3653. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  3654. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  3655. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  3656. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  3657. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  3658. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  3659. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  3660. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  3661. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  3662. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  3663. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  3664. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  3665. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  3666. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  3667. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  3668. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  3669. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  3670. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  3671. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  3672. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  3673. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  3674. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  3675. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  3676. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  3677. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  3678. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  3679. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  3680. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  3681. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  3682. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  3683. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  3684. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  3685. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  3686. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  3687. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  3688. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  3689. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  3690. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  3691. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  3692. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  3693. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  3694. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  3695. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  3696. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  3697. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  3698. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  3699. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  3700. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  3701. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  3702. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  3703. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  3704. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  3705. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  3706. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  3707. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  3708. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  3709. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  3710. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  3711. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  3712. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  3713. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  3714. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  3715. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  3716. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  3717. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  3718. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  3719. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  3720. };
  3721. memcpy (p, initialPValues, sizeof (p));
  3722. int i, j = 0;
  3723. for (i = 4; --i >= 0;)
  3724. {
  3725. s[i].malloc (256);
  3726. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  3727. }
  3728. for (i = 0; i < 18; ++i)
  3729. {
  3730. uint32 d = 0;
  3731. for (int k = 0; k < 4; ++k)
  3732. {
  3733. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  3734. if (++j >= keyBytes)
  3735. j = 0;
  3736. }
  3737. p[i] = initialPValues[i] ^ d;
  3738. }
  3739. uint32 l = 0, r = 0;
  3740. for (i = 0; i < 18; i += 2)
  3741. {
  3742. encrypt (l, r);
  3743. p[i] = l;
  3744. p[i + 1] = r;
  3745. }
  3746. for (i = 0; i < 4; ++i)
  3747. {
  3748. for (j = 0; j < 256; j += 2)
  3749. {
  3750. encrypt (l, r);
  3751. s[i][j] = l;
  3752. s[i][j + 1] = r;
  3753. }
  3754. }
  3755. }
  3756. BlowFish::BlowFish (const BlowFish& other)
  3757. {
  3758. for (int i = 4; --i >= 0;)
  3759. s[i].malloc (256);
  3760. operator= (other);
  3761. }
  3762. BlowFish& BlowFish::operator= (const BlowFish& other)
  3763. {
  3764. memcpy (p, other.p, sizeof (p));
  3765. for (int i = 4; --i >= 0;)
  3766. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  3767. return *this;
  3768. }
  3769. BlowFish::~BlowFish()
  3770. {
  3771. }
  3772. uint32 BlowFish::F (const uint32 x) const throw()
  3773. {
  3774. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  3775. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  3776. }
  3777. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  3778. {
  3779. uint32 l = data1;
  3780. uint32 r = data2;
  3781. for (int i = 0; i < 16; ++i)
  3782. {
  3783. l ^= p[i];
  3784. r ^= F(l);
  3785. swapVariables (l, r);
  3786. }
  3787. data1 = r ^ p[17];
  3788. data2 = l ^ p[16];
  3789. }
  3790. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  3791. {
  3792. uint32 l = data1;
  3793. uint32 r = data2;
  3794. for (int i = 17; i > 1; --i)
  3795. {
  3796. l ^= p[i];
  3797. r ^= F(l);
  3798. swapVariables (l, r);
  3799. }
  3800. data1 = r ^ p[0];
  3801. data2 = l ^ p[1];
  3802. }
  3803. END_JUCE_NAMESPACE
  3804. /*** End of inlined file: juce_BlowFish.cpp ***/
  3805. /*** Start of inlined file: juce_MD5.cpp ***/
  3806. BEGIN_JUCE_NAMESPACE
  3807. MD5::MD5()
  3808. {
  3809. zerostruct (result);
  3810. }
  3811. MD5::MD5 (const MD5& other)
  3812. {
  3813. memcpy (result, other.result, sizeof (result));
  3814. }
  3815. MD5& MD5::operator= (const MD5& other)
  3816. {
  3817. memcpy (result, other.result, sizeof (result));
  3818. return *this;
  3819. }
  3820. MD5::MD5 (const MemoryBlock& data)
  3821. {
  3822. ProcessContext context;
  3823. context.processBlock (data.getData(), data.getSize());
  3824. context.finish (result);
  3825. }
  3826. MD5::MD5 (const void* data, const size_t numBytes)
  3827. {
  3828. ProcessContext context;
  3829. context.processBlock (data, numBytes);
  3830. context.finish (result);
  3831. }
  3832. MD5::MD5 (const String& text)
  3833. {
  3834. ProcessContext context;
  3835. const int len = text.length();
  3836. const juce_wchar* const t = text;
  3837. for (int i = 0; i < len; ++i)
  3838. {
  3839. // force the string into integer-sized unicode characters, to try to make it
  3840. // get the same results on all platforms + compilers.
  3841. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t[i]);
  3842. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  3843. }
  3844. context.finish (result);
  3845. }
  3846. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  3847. {
  3848. ProcessContext context;
  3849. if (numBytesToRead < 0)
  3850. numBytesToRead = std::numeric_limits<int64>::max();
  3851. while (numBytesToRead > 0)
  3852. {
  3853. uint8 tempBuffer [512];
  3854. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  3855. if (bytesRead <= 0)
  3856. break;
  3857. numBytesToRead -= bytesRead;
  3858. context.processBlock (tempBuffer, bytesRead);
  3859. }
  3860. context.finish (result);
  3861. }
  3862. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  3863. {
  3864. processStream (input, numBytesToRead);
  3865. }
  3866. MD5::MD5 (const File& file)
  3867. {
  3868. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  3869. if (fin != 0)
  3870. processStream (*fin, -1);
  3871. else
  3872. zerostruct (result);
  3873. }
  3874. MD5::~MD5()
  3875. {
  3876. }
  3877. namespace MD5Functions
  3878. {
  3879. static void encode (void* const output, const void* const input, const int numBytes) throw()
  3880. {
  3881. for (int i = 0; i < (numBytes >> 2); ++i)
  3882. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  3883. }
  3884. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  3885. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  3886. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  3887. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  3888. static inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  3889. static void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3890. {
  3891. a += F (b, c, d) + x + ac;
  3892. a = rotateLeft (a, s) + b;
  3893. }
  3894. static void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3895. {
  3896. a += G (b, c, d) + x + ac;
  3897. a = rotateLeft (a, s) + b;
  3898. }
  3899. static void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3900. {
  3901. a += H (b, c, d) + x + ac;
  3902. a = rotateLeft (a, s) + b;
  3903. }
  3904. static void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3905. {
  3906. a += I (b, c, d) + x + ac;
  3907. a = rotateLeft (a, s) + b;
  3908. }
  3909. }
  3910. MD5::ProcessContext::ProcessContext()
  3911. {
  3912. state[0] = 0x67452301;
  3913. state[1] = 0xefcdab89;
  3914. state[2] = 0x98badcfe;
  3915. state[3] = 0x10325476;
  3916. count[0] = 0;
  3917. count[1] = 0;
  3918. }
  3919. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  3920. {
  3921. int bufferPos = ((count[0] >> 3) & 0x3F);
  3922. count[0] += (uint32) (dataSize << 3);
  3923. if (count[0] < ((uint32) dataSize << 3))
  3924. count[1]++;
  3925. count[1] += (uint32) (dataSize >> 29);
  3926. const size_t spaceLeft = 64 - bufferPos;
  3927. size_t i = 0;
  3928. if (dataSize >= spaceLeft)
  3929. {
  3930. memcpy (buffer + bufferPos, data, spaceLeft);
  3931. transform (buffer);
  3932. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  3933. transform (static_cast <const char*> (data) + i);
  3934. bufferPos = 0;
  3935. }
  3936. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  3937. }
  3938. void MD5::ProcessContext::finish (void* const result)
  3939. {
  3940. unsigned char encodedLength[8];
  3941. MD5Functions::encode (encodedLength, count, 8);
  3942. // Pad out to 56 mod 64.
  3943. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  3944. const int paddingLength = (index < 56) ? (56 - index)
  3945. : (120 - index);
  3946. uint8 paddingBuffer [64];
  3947. zeromem (paddingBuffer, paddingLength);
  3948. paddingBuffer [0] = 0x80;
  3949. processBlock (paddingBuffer, paddingLength);
  3950. processBlock (encodedLength, 8);
  3951. MD5Functions::encode (result, state, 16);
  3952. zerostruct (buffer);
  3953. }
  3954. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  3955. {
  3956. using namespace MD5Functions;
  3957. uint32 a = state[0];
  3958. uint32 b = state[1];
  3959. uint32 c = state[2];
  3960. uint32 d = state[3];
  3961. uint32 x[16];
  3962. encode (x, bufferToTransform, 64);
  3963. enum Constants
  3964. {
  3965. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  3966. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  3967. };
  3968. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  3969. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  3970. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  3971. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  3972. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  3973. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  3974. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  3975. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  3976. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  3977. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  3978. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  3979. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  3980. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  3981. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  3982. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  3983. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  3984. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  3985. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  3986. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  3987. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  3988. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  3989. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  3990. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  3991. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  3992. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  3993. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  3994. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  3995. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  3996. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  3997. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  3998. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  3999. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  4000. state[0] += a;
  4001. state[1] += b;
  4002. state[2] += c;
  4003. state[3] += d;
  4004. zerostruct (x);
  4005. }
  4006. const MemoryBlock MD5::getRawChecksumData() const
  4007. {
  4008. return MemoryBlock (result, sizeof (result));
  4009. }
  4010. const String MD5::toHexString() const
  4011. {
  4012. return String::toHexString (result, sizeof (result), 0);
  4013. }
  4014. bool MD5::operator== (const MD5& other) const
  4015. {
  4016. return memcmp (result, other.result, sizeof (result)) == 0;
  4017. }
  4018. bool MD5::operator!= (const MD5& other) const
  4019. {
  4020. return ! operator== (other);
  4021. }
  4022. END_JUCE_NAMESPACE
  4023. /*** End of inlined file: juce_MD5.cpp ***/
  4024. /*** Start of inlined file: juce_Primes.cpp ***/
  4025. BEGIN_JUCE_NAMESPACE
  4026. namespace PrimesHelpers
  4027. {
  4028. static void createSmallSieve (const int numBits, BigInteger& result)
  4029. {
  4030. result.setBit (numBits);
  4031. result.clearBit (numBits); // to enlarge the array
  4032. result.setBit (0);
  4033. int n = 2;
  4034. do
  4035. {
  4036. for (int i = n + n; i < numBits; i += n)
  4037. result.setBit (i);
  4038. n = result.findNextClearBit (n + 1);
  4039. }
  4040. while (n <= (numBits >> 1));
  4041. }
  4042. static void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  4043. const BigInteger& smallSieve, const int smallSieveSize)
  4044. {
  4045. jassert (! base[0]); // must be even!
  4046. result.setBit (numBits);
  4047. result.clearBit (numBits); // to enlarge the array
  4048. int index = smallSieve.findNextClearBit (0);
  4049. do
  4050. {
  4051. const int prime = (index << 1) + 1;
  4052. BigInteger r (base), remainder;
  4053. r.divideBy (prime, remainder);
  4054. int i = prime - remainder.getBitRangeAsInt (0, 32);
  4055. if (r.isZero())
  4056. i += prime;
  4057. if ((i & 1) == 0)
  4058. i += prime;
  4059. i = (i - 1) >> 1;
  4060. while (i < numBits)
  4061. {
  4062. result.setBit (i);
  4063. i += prime;
  4064. }
  4065. index = smallSieve.findNextClearBit (index + 1);
  4066. }
  4067. while (index < smallSieveSize);
  4068. }
  4069. static bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  4070. const int numBits, BigInteger& result, const int certainty)
  4071. {
  4072. for (int i = 0; i < numBits; ++i)
  4073. {
  4074. if (! sieve[i])
  4075. {
  4076. result = base + (unsigned int) ((i << 1) + 1);
  4077. if (Primes::isProbablyPrime (result, certainty))
  4078. return true;
  4079. }
  4080. }
  4081. return false;
  4082. }
  4083. static bool passesMillerRabin (const BigInteger& n, int iterations)
  4084. {
  4085. const BigInteger one (1), two (2);
  4086. const BigInteger nMinusOne (n - one);
  4087. BigInteger d (nMinusOne);
  4088. const int s = d.findNextSetBit (0);
  4089. d >>= s;
  4090. BigInteger smallPrimes;
  4091. int numBitsInSmallPrimes = 0;
  4092. for (;;)
  4093. {
  4094. numBitsInSmallPrimes += 256;
  4095. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  4096. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  4097. if (numPrimesFound > iterations + 1)
  4098. break;
  4099. }
  4100. int smallPrime = 2;
  4101. while (--iterations >= 0)
  4102. {
  4103. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  4104. BigInteger r (smallPrime);
  4105. r.exponentModulo (d, n);
  4106. if (r != one && r != nMinusOne)
  4107. {
  4108. for (int j = 0; j < s; ++j)
  4109. {
  4110. r.exponentModulo (two, n);
  4111. if (r == nMinusOne)
  4112. break;
  4113. }
  4114. if (r != nMinusOne)
  4115. return false;
  4116. }
  4117. }
  4118. return true;
  4119. }
  4120. }
  4121. const BigInteger Primes::createProbablePrime (const int bitLength,
  4122. const int certainty,
  4123. const int* randomSeeds,
  4124. int numRandomSeeds)
  4125. {
  4126. using namespace PrimesHelpers;
  4127. int defaultSeeds [16];
  4128. if (numRandomSeeds <= 0)
  4129. {
  4130. randomSeeds = defaultSeeds;
  4131. numRandomSeeds = numElementsInArray (defaultSeeds);
  4132. Random r (0);
  4133. for (int j = 10; --j >= 0;)
  4134. {
  4135. r.setSeedRandomly();
  4136. for (int i = numRandomSeeds; --i >= 0;)
  4137. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  4138. }
  4139. }
  4140. BigInteger smallSieve;
  4141. const int smallSieveSize = 15000;
  4142. createSmallSieve (smallSieveSize, smallSieve);
  4143. BigInteger p;
  4144. for (int i = numRandomSeeds; --i >= 0;)
  4145. {
  4146. BigInteger p2;
  4147. Random r (randomSeeds[i]);
  4148. r.fillBitsRandomly (p2, 0, bitLength);
  4149. p ^= p2;
  4150. }
  4151. p.setBit (bitLength - 1);
  4152. p.clearBit (0);
  4153. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  4154. while (p.getHighestBit() < bitLength)
  4155. {
  4156. p += 2 * searchLen;
  4157. BigInteger sieve;
  4158. bigSieve (p, searchLen, sieve,
  4159. smallSieve, smallSieveSize);
  4160. BigInteger candidate;
  4161. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  4162. return candidate;
  4163. }
  4164. jassertfalse
  4165. return BigInteger();
  4166. }
  4167. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  4168. {
  4169. using namespace PrimesHelpers;
  4170. if (! number[0])
  4171. return false;
  4172. if (number.getHighestBit() <= 10)
  4173. {
  4174. const int num = number.getBitRangeAsInt (0, 10);
  4175. for (int i = num / 2; --i > 1;)
  4176. if (num % i == 0)
  4177. return false;
  4178. return true;
  4179. }
  4180. else
  4181. {
  4182. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  4183. return false;
  4184. return passesMillerRabin (number, certainty);
  4185. }
  4186. }
  4187. END_JUCE_NAMESPACE
  4188. /*** End of inlined file: juce_Primes.cpp ***/
  4189. /*** Start of inlined file: juce_RSAKey.cpp ***/
  4190. BEGIN_JUCE_NAMESPACE
  4191. RSAKey::RSAKey()
  4192. {
  4193. }
  4194. RSAKey::RSAKey (const String& s)
  4195. {
  4196. if (s.containsChar (','))
  4197. {
  4198. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  4199. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  4200. }
  4201. else
  4202. {
  4203. // the string needs to be two hex numbers, comma-separated..
  4204. jassertfalse;
  4205. }
  4206. }
  4207. RSAKey::~RSAKey()
  4208. {
  4209. }
  4210. const String RSAKey::toString() const
  4211. {
  4212. return part1.toString (16) + "," + part2.toString (16);
  4213. }
  4214. bool RSAKey::applyToValue (BigInteger& value) const
  4215. {
  4216. if (part1.isZero() || part2.isZero() || value <= 0)
  4217. {
  4218. jassertfalse // using an uninitialised key
  4219. value.clear();
  4220. return false;
  4221. }
  4222. BigInteger result;
  4223. while (! value.isZero())
  4224. {
  4225. result *= part2;
  4226. BigInteger remainder;
  4227. value.divideBy (part2, remainder);
  4228. remainder.exponentModulo (part1, part2);
  4229. result += remainder;
  4230. }
  4231. value.swapWith (result);
  4232. return true;
  4233. }
  4234. static const BigInteger findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  4235. {
  4236. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  4237. // are fast to divide + multiply
  4238. for (int i = 2; i <= 65536; i *= 2)
  4239. {
  4240. const BigInteger e (1 + i);
  4241. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  4242. return e;
  4243. }
  4244. BigInteger e (4);
  4245. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  4246. ++e;
  4247. return e;
  4248. }
  4249. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  4250. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  4251. {
  4252. jassert (numBits > 16); // not much point using less than this..
  4253. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds));
  4254. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds, numRandomSeeds));
  4255. const BigInteger n (p * q);
  4256. const BigInteger m (--p * --q);
  4257. const BigInteger e (findBestCommonDivisor (p, q));
  4258. BigInteger d (e);
  4259. d.inverseModulo (m);
  4260. publicKey.part1 = e;
  4261. publicKey.part2 = n;
  4262. privateKey.part1 = d;
  4263. privateKey.part2 = n;
  4264. }
  4265. END_JUCE_NAMESPACE
  4266. /*** End of inlined file: juce_RSAKey.cpp ***/
  4267. /*** Start of inlined file: juce_InputStream.cpp ***/
  4268. BEGIN_JUCE_NAMESPACE
  4269. char InputStream::readByte()
  4270. {
  4271. char temp = 0;
  4272. read (&temp, 1);
  4273. return temp;
  4274. }
  4275. bool InputStream::readBool()
  4276. {
  4277. return readByte() != 0;
  4278. }
  4279. short InputStream::readShort()
  4280. {
  4281. char temp[2];
  4282. if (read (temp, 2) == 2)
  4283. return (short) ByteOrder::littleEndianShort (temp);
  4284. return 0;
  4285. }
  4286. short InputStream::readShortBigEndian()
  4287. {
  4288. char temp[2];
  4289. if (read (temp, 2) == 2)
  4290. return (short) ByteOrder::bigEndianShort (temp);
  4291. return 0;
  4292. }
  4293. int InputStream::readInt()
  4294. {
  4295. char temp[4];
  4296. if (read (temp, 4) == 4)
  4297. return (int) ByteOrder::littleEndianInt (temp);
  4298. return 0;
  4299. }
  4300. int InputStream::readIntBigEndian()
  4301. {
  4302. char temp[4];
  4303. if (read (temp, 4) == 4)
  4304. return (int) ByteOrder::bigEndianInt (temp);
  4305. return 0;
  4306. }
  4307. int InputStream::readCompressedInt()
  4308. {
  4309. const unsigned char sizeByte = readByte();
  4310. if (sizeByte == 0)
  4311. return 0;
  4312. const int numBytes = (sizeByte & 0x7f);
  4313. if (numBytes > 4)
  4314. {
  4315. jassertfalse // trying to read corrupt data - this method must only be used
  4316. // to read data that was written by OutputStream::writeCompressedInt()
  4317. return 0;
  4318. }
  4319. char bytes[4] = { 0, 0, 0, 0 };
  4320. if (read (bytes, numBytes) != numBytes)
  4321. return 0;
  4322. const int num = (int) ByteOrder::littleEndianInt (bytes);
  4323. return (sizeByte >> 7) ? -num : num;
  4324. }
  4325. int64 InputStream::readInt64()
  4326. {
  4327. union { uint8 asBytes[8]; uint64 asInt64; } n;
  4328. if (read (n.asBytes, 8) == 8)
  4329. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  4330. return 0;
  4331. }
  4332. int64 InputStream::readInt64BigEndian()
  4333. {
  4334. union { uint8 asBytes[8]; uint64 asInt64; } n;
  4335. if (read (n.asBytes, 8) == 8)
  4336. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  4337. return 0;
  4338. }
  4339. float InputStream::readFloat()
  4340. {
  4341. // the union below relies on these types being the same size...
  4342. static_jassert (sizeof (int32) == sizeof (float));
  4343. union { int32 asInt; float asFloat; } n;
  4344. n.asInt = (int32) readInt();
  4345. return n.asFloat;
  4346. }
  4347. float InputStream::readFloatBigEndian()
  4348. {
  4349. union { int32 asInt; float asFloat; } n;
  4350. n.asInt = (int32) readIntBigEndian();
  4351. return n.asFloat;
  4352. }
  4353. double InputStream::readDouble()
  4354. {
  4355. union { int64 asInt; double asDouble; } n;
  4356. n.asInt = readInt64();
  4357. return n.asDouble;
  4358. }
  4359. double InputStream::readDoubleBigEndian()
  4360. {
  4361. union { int64 asInt; double asDouble; } n;
  4362. n.asInt = readInt64BigEndian();
  4363. return n.asDouble;
  4364. }
  4365. const String InputStream::readString()
  4366. {
  4367. MemoryBlock buffer (256);
  4368. char* data = static_cast<char*> (buffer.getData());
  4369. size_t i = 0;
  4370. while ((data[i] = readByte()) != 0)
  4371. {
  4372. if (++i >= buffer.getSize())
  4373. {
  4374. buffer.setSize (buffer.getSize() + 512);
  4375. data = static_cast<char*> (buffer.getData());
  4376. }
  4377. }
  4378. return String::fromUTF8 (data, (int) i);
  4379. }
  4380. const String InputStream::readNextLine()
  4381. {
  4382. MemoryBlock buffer (256);
  4383. char* data = static_cast<char*> (buffer.getData());
  4384. size_t i = 0;
  4385. while ((data[i] = readByte()) != 0)
  4386. {
  4387. if (data[i] == '\n')
  4388. break;
  4389. if (data[i] == '\r')
  4390. {
  4391. const int64 lastPos = getPosition();
  4392. if (readByte() != '\n')
  4393. setPosition (lastPos);
  4394. break;
  4395. }
  4396. if (++i >= buffer.getSize())
  4397. {
  4398. buffer.setSize (buffer.getSize() + 512);
  4399. data = static_cast<char*> (buffer.getData());
  4400. }
  4401. }
  4402. return String::fromUTF8 (data, (int) i);
  4403. }
  4404. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  4405. {
  4406. const int64 totalLength = getTotalLength();
  4407. if (totalLength >= 0)
  4408. {
  4409. const int totalBytesRemaining = (int) jmin ((int64) 0x7fffffff,
  4410. totalLength - getPosition());
  4411. if (numBytes < 0)
  4412. numBytes = totalBytesRemaining;
  4413. else if (numBytes > 0)
  4414. numBytes = jmin (numBytes, totalBytesRemaining);
  4415. else
  4416. return 0;
  4417. }
  4418. const size_t originalBlockSize = block.getSize();
  4419. int totalBytesRead = 0;
  4420. if (numBytes > 0)
  4421. {
  4422. // know how many bytes we want, so we can resize the block first..
  4423. block.setSize (originalBlockSize + numBytes, false);
  4424. totalBytesRead = read (static_cast<char*> (block.getData()) + originalBlockSize, numBytes);
  4425. }
  4426. else
  4427. {
  4428. // read until end of stram..
  4429. const int chunkSize = 32768;
  4430. for (;;)
  4431. {
  4432. block.ensureSize (originalBlockSize + totalBytesRead + chunkSize, false);
  4433. const int bytesJustIn = read (static_cast<char*> (block.getData())
  4434. + originalBlockSize
  4435. + totalBytesRead,
  4436. chunkSize);
  4437. if (bytesJustIn == 0)
  4438. break;
  4439. totalBytesRead += bytesJustIn;
  4440. }
  4441. }
  4442. // trim off any excess left at the end
  4443. block.setSize (originalBlockSize + totalBytesRead, false);
  4444. return totalBytesRead;
  4445. }
  4446. const String InputStream::readEntireStreamAsString()
  4447. {
  4448. MemoryBlock mb;
  4449. const int size = readIntoMemoryBlock (mb);
  4450. return String::createStringFromData (static_cast<const char*> (mb.getData()), size);
  4451. }
  4452. void InputStream::skipNextBytes (int64 numBytesToSkip)
  4453. {
  4454. if (numBytesToSkip > 0)
  4455. {
  4456. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  4457. HeapBlock<char> temp (skipBufferSize);
  4458. while (numBytesToSkip > 0 && ! isExhausted())
  4459. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  4460. }
  4461. }
  4462. END_JUCE_NAMESPACE
  4463. /*** End of inlined file: juce_InputStream.cpp ***/
  4464. /*** Start of inlined file: juce_OutputStream.cpp ***/
  4465. BEGIN_JUCE_NAMESPACE
  4466. #if JUCE_DEBUG
  4467. static CriticalSection activeStreamLock;
  4468. static VoidArray activeStreams;
  4469. void juce_CheckForDanglingStreams()
  4470. {
  4471. /*
  4472. It's always a bad idea to leak any object, but if you're leaking output
  4473. streams, then there's a good chance that you're failing to flush a file
  4474. to disk properly, which could result in corrupted data and other similar
  4475. nastiness..
  4476. */
  4477. jassert (activeStreams.size() == 0);
  4478. };
  4479. #endif
  4480. OutputStream::OutputStream()
  4481. {
  4482. #if JUCE_DEBUG
  4483. const ScopedLock sl (activeStreamLock);
  4484. activeStreams.add (this);
  4485. #endif
  4486. }
  4487. OutputStream::~OutputStream()
  4488. {
  4489. #if JUCE_DEBUG
  4490. const ScopedLock sl (activeStreamLock);
  4491. activeStreams.removeValue (this);
  4492. #endif
  4493. }
  4494. void OutputStream::writeBool (const bool b)
  4495. {
  4496. writeByte (b ? (char) 1
  4497. : (char) 0);
  4498. }
  4499. void OutputStream::writeByte (char byte)
  4500. {
  4501. write (&byte, 1);
  4502. }
  4503. void OutputStream::writeShort (short value)
  4504. {
  4505. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  4506. write (&v, 2);
  4507. }
  4508. void OutputStream::writeShortBigEndian (short value)
  4509. {
  4510. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  4511. write (&v, 2);
  4512. }
  4513. void OutputStream::writeInt (int value)
  4514. {
  4515. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  4516. write (&v, 4);
  4517. }
  4518. void OutputStream::writeIntBigEndian (int value)
  4519. {
  4520. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  4521. write (&v, 4);
  4522. }
  4523. void OutputStream::writeCompressedInt (int value)
  4524. {
  4525. unsigned int un = (value < 0) ? (unsigned int) -value
  4526. : (unsigned int) value;
  4527. uint8 data[5];
  4528. int num = 0;
  4529. while (un > 0)
  4530. {
  4531. data[++num] = (uint8) un;
  4532. un >>= 8;
  4533. }
  4534. data[0] = (uint8) num;
  4535. if (value < 0)
  4536. data[0] |= 0x80;
  4537. write (data, num + 1);
  4538. }
  4539. void OutputStream::writeInt64 (int64 value)
  4540. {
  4541. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  4542. write (&v, 8);
  4543. }
  4544. void OutputStream::writeInt64BigEndian (int64 value)
  4545. {
  4546. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  4547. write (&v, 8);
  4548. }
  4549. void OutputStream::writeFloat (float value)
  4550. {
  4551. union { int asInt; float asFloat; } n;
  4552. n.asFloat = value;
  4553. writeInt (n.asInt);
  4554. }
  4555. void OutputStream::writeFloatBigEndian (float value)
  4556. {
  4557. union { int asInt; float asFloat; } n;
  4558. n.asFloat = value;
  4559. writeIntBigEndian (n.asInt);
  4560. }
  4561. void OutputStream::writeDouble (double value)
  4562. {
  4563. union { int64 asInt; double asDouble; } n;
  4564. n.asDouble = value;
  4565. writeInt64 (n.asInt);
  4566. }
  4567. void OutputStream::writeDoubleBigEndian (double value)
  4568. {
  4569. union { int64 asInt; double asDouble; } n;
  4570. n.asDouble = value;
  4571. writeInt64BigEndian (n.asInt);
  4572. }
  4573. void OutputStream::writeString (const String& text)
  4574. {
  4575. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  4576. // if lots of large, persistent strings were to be written to streams).
  4577. const int numBytes = text.getNumBytesAsUTF8() + 1;
  4578. HeapBlock<char> temp (numBytes);
  4579. text.copyToUTF8 (temp, numBytes);
  4580. write (temp, numBytes);
  4581. }
  4582. void OutputStream::writeText (const String& text, const bool asUnicode,
  4583. const bool writeUnicodeHeaderBytes)
  4584. {
  4585. if (asUnicode)
  4586. {
  4587. if (writeUnicodeHeaderBytes)
  4588. write ("\x0ff\x0fe", 2);
  4589. const juce_wchar* src = text;
  4590. bool lastCharWasReturn = false;
  4591. while (*src != 0)
  4592. {
  4593. if (*src == L'\n' && ! lastCharWasReturn)
  4594. writeShort ((short) L'\r');
  4595. lastCharWasReturn = (*src == L'\r');
  4596. writeShort ((short) *src++);
  4597. }
  4598. }
  4599. else
  4600. {
  4601. const char* src = text.toUTF8();
  4602. const char* t = src;
  4603. for (;;)
  4604. {
  4605. if (*t == '\n')
  4606. {
  4607. if (t > src)
  4608. write (src, (int) (t - src));
  4609. write ("\r\n", 2);
  4610. src = t + 1;
  4611. }
  4612. else if (*t == '\r')
  4613. {
  4614. if (t[1] == '\n')
  4615. ++t;
  4616. }
  4617. else if (*t == 0)
  4618. {
  4619. if (t > src)
  4620. write (src, (int) (t - src));
  4621. break;
  4622. }
  4623. ++t;
  4624. }
  4625. }
  4626. }
  4627. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  4628. {
  4629. if (numBytesToWrite < 0)
  4630. numBytesToWrite = std::numeric_limits<int64>::max();
  4631. int numWritten = 0;
  4632. while (numBytesToWrite > 0 && ! source.isExhausted())
  4633. {
  4634. char buffer [8192];
  4635. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  4636. if (num <= 0)
  4637. break;
  4638. write (buffer, num);
  4639. numBytesToWrite -= num;
  4640. numWritten += num;
  4641. }
  4642. return numWritten;
  4643. }
  4644. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  4645. {
  4646. return stream << String (number);
  4647. }
  4648. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  4649. {
  4650. return stream << String (number);
  4651. }
  4652. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  4653. {
  4654. stream.writeByte (character);
  4655. return stream;
  4656. }
  4657. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  4658. {
  4659. stream.write (text, (int) strlen (text));
  4660. return stream;
  4661. }
  4662. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  4663. {
  4664. stream.write (data.getData(), (int) data.getSize());
  4665. return stream;
  4666. }
  4667. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  4668. {
  4669. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  4670. if (in != 0)
  4671. stream.writeFromInputStream (*in, -1);
  4672. return stream;
  4673. }
  4674. END_JUCE_NAMESPACE
  4675. /*** End of inlined file: juce_OutputStream.cpp ***/
  4676. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  4677. BEGIN_JUCE_NAMESPACE
  4678. DirectoryIterator::DirectoryIterator (const File& directory,
  4679. bool isRecursive_,
  4680. const String& wildCard_,
  4681. const int whatToLookFor_)
  4682. : fileFinder (directory, isRecursive ? "*" : wildCard_),
  4683. wildCard (wildCard_),
  4684. path (File::addTrailingSeparator (directory.getFullPathName())),
  4685. index (-1),
  4686. totalNumFiles (-1),
  4687. whatToLookFor (whatToLookFor_),
  4688. isRecursive (isRecursive_)
  4689. {
  4690. // you have to specify the type of files you're looking for!
  4691. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  4692. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  4693. }
  4694. DirectoryIterator::~DirectoryIterator()
  4695. {
  4696. }
  4697. bool DirectoryIterator::next()
  4698. {
  4699. return next (0, 0, 0, 0, 0, 0);
  4700. }
  4701. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  4702. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  4703. {
  4704. if (subIterator != 0)
  4705. {
  4706. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  4707. return true;
  4708. subIterator = 0;
  4709. }
  4710. String filename;
  4711. bool isDirectory, isHidden;
  4712. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  4713. {
  4714. ++index;
  4715. if (! filename.containsOnly ("."))
  4716. {
  4717. const File fileFound (path + filename, 0);
  4718. bool matches = false;
  4719. if (isDirectory)
  4720. {
  4721. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  4722. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  4723. matches = (whatToLookFor & File::findDirectories) != 0;
  4724. }
  4725. else
  4726. {
  4727. matches = (whatToLookFor & File::findFiles) != 0;
  4728. }
  4729. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  4730. if (matches && isRecursive)
  4731. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  4732. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  4733. matches = ! isHidden;
  4734. if (matches)
  4735. {
  4736. currentFile = fileFound;
  4737. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  4738. if (isDirResult != 0) *isDirResult = isDirectory;
  4739. return true;
  4740. }
  4741. else if (subIterator != 0)
  4742. {
  4743. return next();
  4744. }
  4745. }
  4746. }
  4747. return false;
  4748. }
  4749. const File DirectoryIterator::getFile() const
  4750. {
  4751. if (subIterator != 0)
  4752. return subIterator->getFile();
  4753. return currentFile;
  4754. }
  4755. float DirectoryIterator::getEstimatedProgress() const
  4756. {
  4757. if (totalNumFiles < 0)
  4758. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  4759. if (totalNumFiles <= 0)
  4760. return 0.0f;
  4761. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  4762. : (float) index;
  4763. return detailedIndex / totalNumFiles;
  4764. }
  4765. END_JUCE_NAMESPACE
  4766. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  4767. /*** Start of inlined file: juce_File.cpp ***/
  4768. #if ! JUCE_WINDOWS
  4769. #include <pwd.h>
  4770. #endif
  4771. BEGIN_JUCE_NAMESPACE
  4772. File::File (const String& fullPathName)
  4773. : fullPath (parseAbsolutePath (fullPathName))
  4774. {
  4775. }
  4776. File::File (const String& path, int)
  4777. : fullPath (path)
  4778. {
  4779. }
  4780. const File File::createFileWithoutCheckingPath (const String& path)
  4781. {
  4782. return File (path, 0);
  4783. }
  4784. File::File (const File& other)
  4785. : fullPath (other.fullPath)
  4786. {
  4787. }
  4788. File& File::operator= (const String& newPath)
  4789. {
  4790. fullPath = parseAbsolutePath (newPath);
  4791. return *this;
  4792. }
  4793. File& File::operator= (const File& other)
  4794. {
  4795. fullPath = other.fullPath;
  4796. return *this;
  4797. }
  4798. const File File::nonexistent;
  4799. const String File::parseAbsolutePath (const String& p)
  4800. {
  4801. if (p.isEmpty())
  4802. return String::empty;
  4803. #if JUCE_WINDOWS
  4804. // Windows..
  4805. String path (p.replaceCharacter ('/', '\\'));
  4806. if (path.startsWithChar (File::separator))
  4807. {
  4808. if (path[1] != File::separator)
  4809. {
  4810. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4811. If you're trying to parse a string that may be either a relative path or an absolute path,
  4812. you MUST provide a context against which the partial path can be evaluated - you can do
  4813. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4814. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4815. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4816. */
  4817. jassertfalse
  4818. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  4819. }
  4820. }
  4821. else if (! path.containsChar (':'))
  4822. {
  4823. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4824. If you're trying to parse a string that may be either a relative path or an absolute path,
  4825. you MUST provide a context against which the partial path can be evaluated - you can do
  4826. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4827. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4828. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4829. */
  4830. jassertfalse
  4831. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4832. }
  4833. #else
  4834. // Mac or Linux..
  4835. String path (p.replaceCharacter ('\\', '/'));
  4836. if (path.startsWithChar ('~'))
  4837. {
  4838. if (path[1] == File::separator || path[1] == 0)
  4839. {
  4840. // expand a name of the form "~/abc"
  4841. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  4842. + path.substring (1);
  4843. }
  4844. else
  4845. {
  4846. // expand a name of type "~dave/abc"
  4847. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  4848. struct passwd* const pw = getpwnam (userName.toUTF8());
  4849. if (pw != 0)
  4850. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  4851. }
  4852. }
  4853. else if (! path.startsWithChar (File::separator))
  4854. {
  4855. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4856. If you're trying to parse a string that may be either a relative path or an absolute path,
  4857. you MUST provide a context against which the partial path can be evaluated - you can do
  4858. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4859. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4860. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4861. */
  4862. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  4863. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4864. }
  4865. #endif
  4866. return path.trimCharactersAtEnd (separatorString);
  4867. }
  4868. const String File::addTrailingSeparator (const String& path)
  4869. {
  4870. return path.endsWithChar (File::separator) ? path
  4871. : path + File::separator;
  4872. }
  4873. #if JUCE_LINUX
  4874. #define NAMES_ARE_CASE_SENSITIVE 1
  4875. #endif
  4876. bool File::areFileNamesCaseSensitive()
  4877. {
  4878. #if NAMES_ARE_CASE_SENSITIVE
  4879. return true;
  4880. #else
  4881. return false;
  4882. #endif
  4883. }
  4884. bool File::operator== (const File& other) const
  4885. {
  4886. #if NAMES_ARE_CASE_SENSITIVE
  4887. return fullPath == other.fullPath;
  4888. #else
  4889. return fullPath.equalsIgnoreCase (other.fullPath);
  4890. #endif
  4891. }
  4892. bool File::operator!= (const File& other) const
  4893. {
  4894. return ! operator== (other);
  4895. }
  4896. bool File::operator< (const File& other) const
  4897. {
  4898. #if NAMES_ARE_CASE_SENSITIVE
  4899. return fullPath < other.fullPath;
  4900. #else
  4901. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  4902. #endif
  4903. }
  4904. bool File::operator> (const File& other) const
  4905. {
  4906. #if NAMES_ARE_CASE_SENSITIVE
  4907. return fullPath > other.fullPath;
  4908. #else
  4909. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  4910. #endif
  4911. }
  4912. bool File::setReadOnly (const bool shouldBeReadOnly,
  4913. const bool applyRecursively) const
  4914. {
  4915. bool worked = true;
  4916. if (applyRecursively && isDirectory())
  4917. {
  4918. Array <File> subFiles;
  4919. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  4920. for (int i = subFiles.size(); --i >= 0;)
  4921. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  4922. }
  4923. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  4924. }
  4925. bool File::deleteRecursively() const
  4926. {
  4927. bool worked = true;
  4928. if (isDirectory())
  4929. {
  4930. Array<File> subFiles;
  4931. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  4932. for (int i = subFiles.size(); --i >= 0;)
  4933. worked = subFiles.getReference(i).deleteRecursively() && worked;
  4934. }
  4935. return deleteFile() && worked;
  4936. }
  4937. bool File::moveFileTo (const File& newFile) const
  4938. {
  4939. if (newFile.fullPath == fullPath)
  4940. return true;
  4941. #if ! NAMES_ARE_CASE_SENSITIVE
  4942. if (*this != newFile)
  4943. #endif
  4944. if (! newFile.deleteFile())
  4945. return false;
  4946. return moveInternal (newFile);
  4947. }
  4948. bool File::copyFileTo (const File& newFile) const
  4949. {
  4950. return (*this == newFile)
  4951. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  4952. }
  4953. bool File::copyDirectoryTo (const File& newDirectory) const
  4954. {
  4955. if (isDirectory() && newDirectory.createDirectory())
  4956. {
  4957. Array<File> subFiles;
  4958. findChildFiles (subFiles, File::findFiles, false);
  4959. int i;
  4960. for (i = 0; i < subFiles.size(); ++i)
  4961. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  4962. return false;
  4963. subFiles.clear();
  4964. findChildFiles (subFiles, File::findDirectories, false);
  4965. for (i = 0; i < subFiles.size(); ++i)
  4966. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  4967. return false;
  4968. return true;
  4969. }
  4970. return false;
  4971. }
  4972. const String File::getPathUpToLastSlash() const
  4973. {
  4974. const int lastSlash = fullPath.lastIndexOfChar (separator);
  4975. if (lastSlash > 0)
  4976. return fullPath.substring (0, lastSlash);
  4977. else if (lastSlash == 0)
  4978. return separatorString;
  4979. else
  4980. return fullPath;
  4981. }
  4982. const File File::getParentDirectory() const
  4983. {
  4984. return File (getPathUpToLastSlash());
  4985. }
  4986. const String File::getFileName() const
  4987. {
  4988. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  4989. }
  4990. int File::hashCode() const
  4991. {
  4992. return fullPath.hashCode();
  4993. }
  4994. int64 File::hashCode64() const
  4995. {
  4996. return fullPath.hashCode64();
  4997. }
  4998. const String File::getFileNameWithoutExtension() const
  4999. {
  5000. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  5001. const int lastDot = fullPath.lastIndexOfChar ('.');
  5002. if (lastDot > lastSlash)
  5003. return fullPath.substring (lastSlash, lastDot);
  5004. else
  5005. return fullPath.substring (lastSlash);
  5006. }
  5007. bool File::isAChildOf (const File& potentialParent) const
  5008. {
  5009. if (potentialParent == File::nonexistent)
  5010. return false;
  5011. const String ourPath (getPathUpToLastSlash());
  5012. #if NAMES_ARE_CASE_SENSITIVE
  5013. if (potentialParent.fullPath == ourPath)
  5014. #else
  5015. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5016. #endif
  5017. {
  5018. return true;
  5019. }
  5020. else if (potentialParent.fullPath.length() >= ourPath.length())
  5021. {
  5022. return false;
  5023. }
  5024. else
  5025. {
  5026. return getParentDirectory().isAChildOf (potentialParent);
  5027. }
  5028. }
  5029. bool File::isAbsolutePath (const String& path)
  5030. {
  5031. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  5032. #if JUCE_WINDOWS
  5033. || (path.isNotEmpty() && path[1] == ':');
  5034. #else
  5035. || path.startsWithChar ('~');
  5036. #endif
  5037. }
  5038. const File File::getChildFile (String relativePath) const
  5039. {
  5040. if (isAbsolutePath (relativePath))
  5041. {
  5042. // the path is really absolute..
  5043. return File (relativePath);
  5044. }
  5045. else
  5046. {
  5047. // it's relative, so remove any ../ or ./ bits at the start.
  5048. String path (fullPath);
  5049. if (relativePath[0] == '.')
  5050. {
  5051. #if JUCE_WINDOWS
  5052. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  5053. #else
  5054. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  5055. #endif
  5056. while (relativePath[0] == '.')
  5057. {
  5058. if (relativePath[1] == '.')
  5059. {
  5060. if (relativePath [2] == 0 || relativePath[2] == separator)
  5061. {
  5062. const int lastSlash = path.lastIndexOfChar (separator);
  5063. if (lastSlash >= 0)
  5064. path = path.substring (0, lastSlash);
  5065. relativePath = relativePath.substring (3);
  5066. }
  5067. else
  5068. {
  5069. break;
  5070. }
  5071. }
  5072. else if (relativePath[1] == separator)
  5073. {
  5074. relativePath = relativePath.substring (2);
  5075. }
  5076. else
  5077. {
  5078. break;
  5079. }
  5080. }
  5081. }
  5082. return File (addTrailingSeparator (path) + relativePath);
  5083. }
  5084. }
  5085. const File File::getSiblingFile (const String& fileName) const
  5086. {
  5087. return getParentDirectory().getChildFile (fileName);
  5088. }
  5089. const String File::descriptionOfSizeInBytes (const int64 bytes)
  5090. {
  5091. if (bytes == 1)
  5092. {
  5093. return "1 byte";
  5094. }
  5095. else if (bytes < 1024)
  5096. {
  5097. return String ((int) bytes) + " bytes";
  5098. }
  5099. else if (bytes < 1024 * 1024)
  5100. {
  5101. return String (bytes / 1024.0, 1) + " KB";
  5102. }
  5103. else if (bytes < 1024 * 1024 * 1024)
  5104. {
  5105. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  5106. }
  5107. else
  5108. {
  5109. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  5110. }
  5111. }
  5112. bool File::create() const
  5113. {
  5114. if (exists())
  5115. return true;
  5116. {
  5117. const File parentDir (getParentDirectory());
  5118. if (parentDir == *this || ! parentDir.createDirectory())
  5119. return false;
  5120. FileOutputStream fo (*this, 8);
  5121. }
  5122. return exists();
  5123. }
  5124. bool File::createDirectory() const
  5125. {
  5126. if (! isDirectory())
  5127. {
  5128. const File parentDir (getParentDirectory());
  5129. if (parentDir == *this || ! parentDir.createDirectory())
  5130. return false;
  5131. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  5132. return isDirectory();
  5133. }
  5134. return true;
  5135. }
  5136. const Time File::getCreationTime() const
  5137. {
  5138. int64 m, a, c;
  5139. getFileTimesInternal (m, a, c);
  5140. return Time (c);
  5141. }
  5142. const Time File::getLastModificationTime() const
  5143. {
  5144. int64 m, a, c;
  5145. getFileTimesInternal (m, a, c);
  5146. return Time (m);
  5147. }
  5148. const Time File::getLastAccessTime() const
  5149. {
  5150. int64 m, a, c;
  5151. getFileTimesInternal (m, a, c);
  5152. return Time (a);
  5153. }
  5154. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  5155. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  5156. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  5157. bool File::loadFileAsData (MemoryBlock& destBlock) const
  5158. {
  5159. if (! existsAsFile())
  5160. return false;
  5161. FileInputStream in (*this);
  5162. return getSize() == in.readIntoMemoryBlock (destBlock);
  5163. }
  5164. const String File::loadFileAsString() const
  5165. {
  5166. if (! existsAsFile())
  5167. return String::empty;
  5168. FileInputStream in (*this);
  5169. return in.readEntireStreamAsString();
  5170. }
  5171. bool File::fileTypeMatches (const int whatToLookFor, const bool isDir, const bool isHidden)
  5172. {
  5173. return (whatToLookFor & (isDir ? findDirectories
  5174. : findFiles)) != 0
  5175. && ((! isHidden) || (whatToLookFor & File::ignoreHiddenFiles) == 0);
  5176. }
  5177. int File::findChildFiles (Array<File>& results,
  5178. const int whatToLookFor,
  5179. const bool searchRecursively,
  5180. const String& wildCardPattern) const
  5181. {
  5182. // you have to specify the type of files you're looking for!
  5183. jassert ((whatToLookFor & (findFiles | findDirectories)) != 0);
  5184. int total = 0;
  5185. if (isDirectory())
  5186. {
  5187. // find child files or directories in this directory first..
  5188. String path (addTrailingSeparator (fullPath)), filename;
  5189. bool itemIsDirectory, itemIsHidden;
  5190. DirectoryIterator::NativeIterator i (path, wildCardPattern);
  5191. while (i.next (filename, &itemIsDirectory, &itemIsHidden, 0, 0, 0, 0))
  5192. {
  5193. if (! filename.containsOnly ("."))
  5194. {
  5195. const File fileFound (path + filename, 0);
  5196. if (fileTypeMatches (whatToLookFor, itemIsDirectory, itemIsHidden))
  5197. {
  5198. results.add (fileFound);
  5199. ++total;
  5200. }
  5201. if (searchRecursively && itemIsDirectory
  5202. && fileTypeMatches (whatToLookFor | findDirectories, true, itemIsHidden))
  5203. {
  5204. total += fileFound.findChildFiles (results, whatToLookFor, true, wildCardPattern);
  5205. }
  5206. }
  5207. }
  5208. }
  5209. return total;
  5210. }
  5211. int File::getNumberOfChildFiles (const int whatToLookFor,
  5212. const String& wildCardPattern) const
  5213. {
  5214. // you have to specify the type of files you're looking for!
  5215. jassert (whatToLookFor > 0 && whatToLookFor <= 3);
  5216. int count = 0;
  5217. if (isDirectory())
  5218. {
  5219. String filename;
  5220. bool itemIsDirectory, itemIsHidden;
  5221. DirectoryIterator::NativeIterator i (*this, wildCardPattern);
  5222. while (i.next (filename, &itemIsDirectory, &itemIsHidden, 0, 0, 0, 0))
  5223. if (fileTypeMatches (whatToLookFor, itemIsDirectory, itemIsHidden)
  5224. && ! filename.containsOnly ("."))
  5225. ++count;
  5226. }
  5227. else
  5228. {
  5229. // trying to search for files inside a non-directory?
  5230. jassertfalse
  5231. }
  5232. return count;
  5233. }
  5234. bool File::containsSubDirectories() const
  5235. {
  5236. if (isDirectory())
  5237. {
  5238. String filename;
  5239. bool itemIsDirectory;
  5240. DirectoryIterator::NativeIterator i (*this, "*");
  5241. while (i.next (filename, &itemIsDirectory, 0, 0, 0, 0, 0))
  5242. if (itemIsDirectory)
  5243. return true;
  5244. }
  5245. return false;
  5246. }
  5247. const File File::getNonexistentChildFile (const String& prefix_,
  5248. const String& suffix,
  5249. bool putNumbersInBrackets) const
  5250. {
  5251. File f (getChildFile (prefix_ + suffix));
  5252. if (f.exists())
  5253. {
  5254. int num = 2;
  5255. String prefix (prefix_);
  5256. // remove any bracketed numbers that may already be on the end..
  5257. if (prefix.trim().endsWithChar (')'))
  5258. {
  5259. putNumbersInBrackets = true;
  5260. const int openBracks = prefix.lastIndexOfChar ('(');
  5261. const int closeBracks = prefix.lastIndexOfChar (')');
  5262. if (openBracks > 0
  5263. && closeBracks > openBracks
  5264. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  5265. {
  5266. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  5267. prefix = prefix.substring (0, openBracks);
  5268. }
  5269. }
  5270. // also use brackets if it ends in a digit.
  5271. putNumbersInBrackets = putNumbersInBrackets
  5272. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  5273. do
  5274. {
  5275. if (putNumbersInBrackets)
  5276. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  5277. else
  5278. f = getChildFile (prefix + String (num++) + suffix);
  5279. } while (f.exists());
  5280. }
  5281. return f;
  5282. }
  5283. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  5284. {
  5285. if (exists())
  5286. {
  5287. return getParentDirectory()
  5288. .getNonexistentChildFile (getFileNameWithoutExtension(),
  5289. getFileExtension(),
  5290. putNumbersInBrackets);
  5291. }
  5292. else
  5293. {
  5294. return *this;
  5295. }
  5296. }
  5297. const String File::getFileExtension() const
  5298. {
  5299. String ext;
  5300. if (! isDirectory())
  5301. {
  5302. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  5303. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  5304. ext = fullPath.substring (indexOfDot);
  5305. }
  5306. return ext;
  5307. }
  5308. bool File::hasFileExtension (const String& possibleSuffix) const
  5309. {
  5310. if (possibleSuffix.isEmpty())
  5311. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  5312. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  5313. if (semicolon >= 0)
  5314. {
  5315. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  5316. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  5317. }
  5318. else
  5319. {
  5320. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  5321. {
  5322. if (possibleSuffix.startsWithChar ('.'))
  5323. return true;
  5324. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  5325. if (dotPos >= 0)
  5326. return fullPath [dotPos] == '.';
  5327. }
  5328. }
  5329. return false;
  5330. }
  5331. const File File::withFileExtension (const String& newExtension) const
  5332. {
  5333. if (fullPath.isEmpty())
  5334. return File::nonexistent;
  5335. String filePart (getFileName());
  5336. int i = filePart.lastIndexOfChar ('.');
  5337. if (i >= 0)
  5338. filePart = filePart.substring (0, i);
  5339. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  5340. filePart << '.';
  5341. return getSiblingFile (filePart + newExtension);
  5342. }
  5343. bool File::startAsProcess (const String& parameters) const
  5344. {
  5345. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  5346. }
  5347. FileInputStream* File::createInputStream() const
  5348. {
  5349. if (existsAsFile())
  5350. return new FileInputStream (*this);
  5351. return 0;
  5352. }
  5353. FileOutputStream* File::createOutputStream (const int bufferSize) const
  5354. {
  5355. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  5356. if (out->failedToOpen())
  5357. return 0;
  5358. return out.release();
  5359. }
  5360. bool File::appendData (const void* const dataToAppend,
  5361. const int numberOfBytes) const
  5362. {
  5363. if (numberOfBytes > 0)
  5364. {
  5365. const ScopedPointer <FileOutputStream> out (createOutputStream());
  5366. if (out == 0)
  5367. return false;
  5368. out->write (dataToAppend, numberOfBytes);
  5369. }
  5370. return true;
  5371. }
  5372. bool File::replaceWithData (const void* const dataToWrite,
  5373. const int numberOfBytes) const
  5374. {
  5375. jassert (numberOfBytes >= 0); // a negative number of bytes??
  5376. if (numberOfBytes <= 0)
  5377. return deleteFile();
  5378. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  5379. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  5380. return tempFile.overwriteTargetFileWithTemporary();
  5381. }
  5382. bool File::appendText (const String& text,
  5383. const bool asUnicode,
  5384. const bool writeUnicodeHeaderBytes) const
  5385. {
  5386. const ScopedPointer <FileOutputStream> out (createOutputStream());
  5387. if (out != 0)
  5388. {
  5389. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  5390. return true;
  5391. }
  5392. return false;
  5393. }
  5394. bool File::replaceWithText (const String& textToWrite,
  5395. const bool asUnicode,
  5396. const bool writeUnicodeHeaderBytes) const
  5397. {
  5398. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  5399. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  5400. return tempFile.overwriteTargetFileWithTemporary();
  5401. }
  5402. const String File::createLegalPathName (const String& original)
  5403. {
  5404. String s (original);
  5405. String start;
  5406. if (s[1] == ':')
  5407. {
  5408. start = s.substring (0, 2);
  5409. s = s.substring (2);
  5410. }
  5411. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  5412. .substring (0, 1024);
  5413. }
  5414. const String File::createLegalFileName (const String& original)
  5415. {
  5416. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  5417. const int maxLength = 128; // only the length of the filename, not the whole path
  5418. const int len = s.length();
  5419. if (len > maxLength)
  5420. {
  5421. const int lastDot = s.lastIndexOfChar ('.');
  5422. if (lastDot > jmax (0, len - 12))
  5423. {
  5424. s = s.substring (0, maxLength - (len - lastDot))
  5425. + s.substring (lastDot);
  5426. }
  5427. else
  5428. {
  5429. s = s.substring (0, maxLength);
  5430. }
  5431. }
  5432. return s;
  5433. }
  5434. const String File::getRelativePathFrom (const File& dir) const
  5435. {
  5436. String thisPath (fullPath);
  5437. {
  5438. int len = thisPath.length();
  5439. while (--len >= 0 && thisPath [len] == File::separator)
  5440. thisPath [len] = 0;
  5441. }
  5442. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  5443. : dir.fullPath));
  5444. const int len = jmin (thisPath.length(), dirPath.length());
  5445. int commonBitLength = 0;
  5446. for (int i = 0; i < len; ++i)
  5447. {
  5448. #if NAMES_ARE_CASE_SENSITIVE
  5449. if (thisPath[i] != dirPath[i])
  5450. #else
  5451. if (CharacterFunctions::toLowerCase (thisPath[i])
  5452. != CharacterFunctions::toLowerCase (dirPath[i]))
  5453. #endif
  5454. {
  5455. break;
  5456. }
  5457. ++commonBitLength;
  5458. }
  5459. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  5460. --commonBitLength;
  5461. // if the only common bit is the root, then just return the full path..
  5462. if (commonBitLength <= 0
  5463. || (commonBitLength == 1 && thisPath [1] == File::separator))
  5464. return fullPath;
  5465. thisPath = thisPath.substring (commonBitLength);
  5466. dirPath = dirPath.substring (commonBitLength);
  5467. while (dirPath.isNotEmpty())
  5468. {
  5469. #if JUCE_WINDOWS
  5470. thisPath = "..\\" + thisPath;
  5471. #else
  5472. thisPath = "../" + thisPath;
  5473. #endif
  5474. const int sep = dirPath.indexOfChar (separator);
  5475. if (sep >= 0)
  5476. dirPath = dirPath.substring (sep + 1);
  5477. else
  5478. dirPath = String::empty;
  5479. }
  5480. return thisPath;
  5481. }
  5482. const File File::createTempFile (const String& fileNameEnding)
  5483. {
  5484. const File tempFile (getSpecialLocation (tempDirectory)
  5485. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  5486. .withFileExtension (fileNameEnding));
  5487. if (tempFile.exists())
  5488. return createTempFile (fileNameEnding);
  5489. else
  5490. return tempFile;
  5491. }
  5492. END_JUCE_NAMESPACE
  5493. /*** End of inlined file: juce_File.cpp ***/
  5494. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  5495. BEGIN_JUCE_NAMESPACE
  5496. void* juce_fileOpen (const File& file, bool forWriting);
  5497. void juce_fileClose (void* handle);
  5498. int juce_fileRead (void* handle, void* buffer, int size);
  5499. int64 juce_fileSetPosition (void* handle, int64 pos);
  5500. FileInputStream::FileInputStream (const File& f)
  5501. : file (f),
  5502. currentPosition (0),
  5503. needToSeek (true)
  5504. {
  5505. totalSize = f.getSize();
  5506. fileHandle = juce_fileOpen (f, false);
  5507. }
  5508. FileInputStream::~FileInputStream()
  5509. {
  5510. juce_fileClose (fileHandle);
  5511. }
  5512. int64 FileInputStream::getTotalLength()
  5513. {
  5514. return totalSize;
  5515. }
  5516. int FileInputStream::read (void* buffer, int bytesToRead)
  5517. {
  5518. int num = 0;
  5519. if (needToSeek)
  5520. {
  5521. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  5522. return 0;
  5523. needToSeek = false;
  5524. }
  5525. num = juce_fileRead (fileHandle, buffer, bytesToRead);
  5526. currentPosition += num;
  5527. return num;
  5528. }
  5529. bool FileInputStream::isExhausted()
  5530. {
  5531. return currentPosition >= totalSize;
  5532. }
  5533. int64 FileInputStream::getPosition()
  5534. {
  5535. return currentPosition;
  5536. }
  5537. bool FileInputStream::setPosition (int64 pos)
  5538. {
  5539. pos = jlimit ((int64) 0, totalSize, pos);
  5540. needToSeek |= (currentPosition != pos);
  5541. currentPosition = pos;
  5542. return true;
  5543. }
  5544. END_JUCE_NAMESPACE
  5545. /*** End of inlined file: juce_FileInputStream.cpp ***/
  5546. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  5547. BEGIN_JUCE_NAMESPACE
  5548. void* juce_fileOpen (const File& file, bool forWriting);
  5549. void juce_fileClose (void* handle);
  5550. int juce_fileWrite (void* handle, const void* buffer, int size);
  5551. int64 juce_fileSetPosition (void* handle, int64 pos);
  5552. FileOutputStream::FileOutputStream (const File& f,
  5553. const int bufferSize_)
  5554. : file (f),
  5555. bufferSize (bufferSize_),
  5556. bytesInBuffer (0)
  5557. {
  5558. fileHandle = juce_fileOpen (f, true);
  5559. if (fileHandle != 0)
  5560. {
  5561. currentPosition = getPositionInternal();
  5562. if (currentPosition < 0)
  5563. {
  5564. jassertfalse
  5565. juce_fileClose (fileHandle);
  5566. fileHandle = 0;
  5567. }
  5568. }
  5569. buffer.malloc (jmax (bufferSize_, 16));
  5570. }
  5571. FileOutputStream::~FileOutputStream()
  5572. {
  5573. flush();
  5574. juce_fileClose (fileHandle);
  5575. }
  5576. int64 FileOutputStream::getPosition()
  5577. {
  5578. return currentPosition;
  5579. }
  5580. bool FileOutputStream::setPosition (int64 newPosition)
  5581. {
  5582. if (newPosition != currentPosition)
  5583. {
  5584. flush();
  5585. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  5586. }
  5587. return newPosition == currentPosition;
  5588. }
  5589. void FileOutputStream::flush()
  5590. {
  5591. if (bytesInBuffer > 0)
  5592. {
  5593. juce_fileWrite (fileHandle, buffer, bytesInBuffer);
  5594. bytesInBuffer = 0;
  5595. }
  5596. flushInternal();
  5597. }
  5598. bool FileOutputStream::write (const void* const src, const int numBytes)
  5599. {
  5600. if (bytesInBuffer + numBytes < bufferSize)
  5601. {
  5602. memcpy (buffer + bytesInBuffer, src, numBytes);
  5603. bytesInBuffer += numBytes;
  5604. currentPosition += numBytes;
  5605. }
  5606. else
  5607. {
  5608. if (bytesInBuffer > 0)
  5609. {
  5610. // flush the reservoir
  5611. const bool wroteOk = (juce_fileWrite (fileHandle, buffer, bytesInBuffer) == bytesInBuffer);
  5612. bytesInBuffer = 0;
  5613. if (! wroteOk)
  5614. return false;
  5615. }
  5616. if (numBytes < bufferSize)
  5617. {
  5618. memcpy (buffer + bytesInBuffer, src, numBytes);
  5619. bytesInBuffer += numBytes;
  5620. currentPosition += numBytes;
  5621. }
  5622. else
  5623. {
  5624. const int bytesWritten = juce_fileWrite (fileHandle, src, numBytes);
  5625. currentPosition += bytesWritten;
  5626. return bytesWritten == numBytes;
  5627. }
  5628. }
  5629. return true;
  5630. }
  5631. END_JUCE_NAMESPACE
  5632. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  5633. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  5634. BEGIN_JUCE_NAMESPACE
  5635. FileSearchPath::FileSearchPath()
  5636. {
  5637. }
  5638. FileSearchPath::FileSearchPath (const String& path)
  5639. {
  5640. init (path);
  5641. }
  5642. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  5643. : directories (other.directories)
  5644. {
  5645. }
  5646. FileSearchPath::~FileSearchPath()
  5647. {
  5648. }
  5649. FileSearchPath& FileSearchPath::operator= (const String& path)
  5650. {
  5651. init (path);
  5652. return *this;
  5653. }
  5654. void FileSearchPath::init (const String& path)
  5655. {
  5656. directories.clear();
  5657. directories.addTokens (path, ";", "\"");
  5658. directories.trim();
  5659. directories.removeEmptyStrings();
  5660. for (int i = directories.size(); --i >= 0;)
  5661. directories.set (i, directories[i].unquoted());
  5662. }
  5663. int FileSearchPath::getNumPaths() const
  5664. {
  5665. return directories.size();
  5666. }
  5667. const File FileSearchPath::operator[] (const int index) const
  5668. {
  5669. return File (directories [index]);
  5670. }
  5671. const String FileSearchPath::toString() const
  5672. {
  5673. StringArray directories2 (directories);
  5674. for (int i = directories2.size(); --i >= 0;)
  5675. if (directories2[i].containsChar (';'))
  5676. directories2.set (i, directories2[i].quoted());
  5677. return directories2.joinIntoString (";");
  5678. }
  5679. void FileSearchPath::add (const File& dir, const int insertIndex)
  5680. {
  5681. directories.insert (insertIndex, dir.getFullPathName());
  5682. }
  5683. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  5684. {
  5685. for (int i = 0; i < directories.size(); ++i)
  5686. if (File (directories[i]) == dir)
  5687. return;
  5688. add (dir);
  5689. }
  5690. void FileSearchPath::remove (const int index)
  5691. {
  5692. directories.remove (index);
  5693. }
  5694. void FileSearchPath::addPath (const FileSearchPath& other)
  5695. {
  5696. for (int i = 0; i < other.getNumPaths(); ++i)
  5697. addIfNotAlreadyThere (other[i]);
  5698. }
  5699. void FileSearchPath::removeRedundantPaths()
  5700. {
  5701. for (int i = directories.size(); --i >= 0;)
  5702. {
  5703. const File d1 (directories[i]);
  5704. for (int j = directories.size(); --j >= 0;)
  5705. {
  5706. const File d2 (directories[j]);
  5707. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  5708. {
  5709. directories.remove (i);
  5710. break;
  5711. }
  5712. }
  5713. }
  5714. }
  5715. void FileSearchPath::removeNonExistentPaths()
  5716. {
  5717. for (int i = directories.size(); --i >= 0;)
  5718. if (! File (directories[i]).isDirectory())
  5719. directories.remove (i);
  5720. }
  5721. int FileSearchPath::findChildFiles (Array<File>& results,
  5722. const int whatToLookFor,
  5723. const bool searchRecursively,
  5724. const String& wildCardPattern) const
  5725. {
  5726. int total = 0;
  5727. for (int i = 0; i < directories.size(); ++i)
  5728. total += operator[] (i).findChildFiles (results,
  5729. whatToLookFor,
  5730. searchRecursively,
  5731. wildCardPattern);
  5732. return total;
  5733. }
  5734. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  5735. const bool checkRecursively) const
  5736. {
  5737. for (int i = directories.size(); --i >= 0;)
  5738. {
  5739. const File d (directories[i]);
  5740. if (checkRecursively)
  5741. {
  5742. if (fileToCheck.isAChildOf (d))
  5743. return true;
  5744. }
  5745. else
  5746. {
  5747. if (fileToCheck.getParentDirectory() == d)
  5748. return true;
  5749. }
  5750. }
  5751. return false;
  5752. }
  5753. END_JUCE_NAMESPACE
  5754. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  5755. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  5756. BEGIN_JUCE_NAMESPACE
  5757. NamedPipe::NamedPipe()
  5758. : internal (0)
  5759. {
  5760. }
  5761. NamedPipe::~NamedPipe()
  5762. {
  5763. close();
  5764. }
  5765. bool NamedPipe::openExisting (const String& pipeName)
  5766. {
  5767. currentPipeName = pipeName;
  5768. return openInternal (pipeName, false);
  5769. }
  5770. bool NamedPipe::createNewPipe (const String& pipeName)
  5771. {
  5772. currentPipeName = pipeName;
  5773. return openInternal (pipeName, true);
  5774. }
  5775. bool NamedPipe::isOpen() const
  5776. {
  5777. return internal != 0;
  5778. }
  5779. const String NamedPipe::getName() const
  5780. {
  5781. return currentPipeName;
  5782. }
  5783. // other methods for this class are implemented in the platform-specific files
  5784. END_JUCE_NAMESPACE
  5785. /*** End of inlined file: juce_NamedPipe.cpp ***/
  5786. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  5787. BEGIN_JUCE_NAMESPACE
  5788. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  5789. {
  5790. createTempFile (File::getSpecialLocation (File::tempDirectory),
  5791. "temp_" + String (Random::getSystemRandom().nextInt()),
  5792. suffix,
  5793. optionFlags);
  5794. }
  5795. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  5796. : targetFile (targetFile_)
  5797. {
  5798. // If you use this constructor, you need to give it a valid target file!
  5799. jassert (targetFile != File::nonexistent);
  5800. createTempFile (targetFile.getParentDirectory(),
  5801. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  5802. targetFile.getFileExtension(),
  5803. optionFlags);
  5804. }
  5805. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  5806. const String& suffix, const int optionFlags)
  5807. {
  5808. if ((optionFlags & useHiddenFile) != 0)
  5809. name = "." + name;
  5810. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  5811. }
  5812. TemporaryFile::~TemporaryFile()
  5813. {
  5814. // Have a few attempts at deleting the file before giving up..
  5815. for (int i = 5; --i >= 0;)
  5816. {
  5817. if (temporaryFile.deleteFile())
  5818. return;
  5819. Thread::sleep (50);
  5820. }
  5821. // Failed to delete our temporary file! Check that you've deleted all the
  5822. // file output streams that were using it!
  5823. jassertfalse;
  5824. }
  5825. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  5826. {
  5827. // This method only works if you created this object with the constructor
  5828. // that takes a target file!
  5829. jassert (targetFile != File::nonexistent);
  5830. if (temporaryFile.exists())
  5831. {
  5832. // Have a few attempts at overwriting the file before giving up..
  5833. for (int i = 5; --i >= 0;)
  5834. {
  5835. if (temporaryFile.moveFileTo (targetFile))
  5836. return true;
  5837. Thread::sleep (100);
  5838. }
  5839. }
  5840. else
  5841. {
  5842. // There's no temporary file to use. If your write failed, you should
  5843. // probably check, and not bother calling this method.
  5844. jassertfalse
  5845. }
  5846. return false;
  5847. }
  5848. END_JUCE_NAMESPACE
  5849. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  5850. /*** Start of inlined file: juce_Socket.cpp ***/
  5851. #if JUCE_WINDOWS
  5852. #include <winsock2.h>
  5853. #if JUCE_MSVC
  5854. #pragma warning (push)
  5855. #pragma warning (disable : 4127 4389 4018)
  5856. #endif
  5857. #else
  5858. #if JUCE_LINUX
  5859. #include <sys/types.h>
  5860. #include <sys/socket.h>
  5861. #include <sys/errno.h>
  5862. #include <unistd.h>
  5863. #include <netinet/in.h>
  5864. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IPHONE
  5865. #include <CoreServices/CoreServices.h>
  5866. #endif
  5867. #include <fcntl.h>
  5868. #include <netdb.h>
  5869. #include <arpa/inet.h>
  5870. #include <netinet/tcp.h>
  5871. #endif
  5872. BEGIN_JUCE_NAMESPACE
  5873. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IPHONE)
  5874. typedef socklen_t juce_socklen_t;
  5875. #else
  5876. typedef int juce_socklen_t;
  5877. #endif
  5878. #if JUCE_WINDOWS
  5879. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  5880. juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  5881. static void initWin32Sockets()
  5882. {
  5883. static CriticalSection lock;
  5884. const ScopedLock sl (lock);
  5885. if (juce_CloseWin32SocketLib == 0)
  5886. {
  5887. WSADATA wsaData;
  5888. const WORD wVersionRequested = MAKEWORD (1, 1);
  5889. WSAStartup (wVersionRequested, &wsaData);
  5890. juce_CloseWin32SocketLib = &WSACleanup;
  5891. }
  5892. }
  5893. #endif
  5894. static bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  5895. {
  5896. const int sndBufSize = 65536;
  5897. const int rcvBufSize = 65536;
  5898. const int one = 1;
  5899. return handle > 0
  5900. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  5901. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  5902. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  5903. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  5904. }
  5905. static bool bindSocketToPort (const int handle, const int port) throw()
  5906. {
  5907. if (handle <= 0 || port <= 0)
  5908. return false;
  5909. struct sockaddr_in servTmpAddr;
  5910. zerostruct (servTmpAddr);
  5911. servTmpAddr.sin_family = PF_INET;
  5912. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  5913. servTmpAddr.sin_port = htons ((uint16) port);
  5914. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  5915. }
  5916. static int readSocket (const int handle,
  5917. void* const destBuffer, const int maxBytesToRead,
  5918. bool volatile& connected,
  5919. const bool blockUntilSpecifiedAmountHasArrived) throw()
  5920. {
  5921. int bytesRead = 0;
  5922. while (bytesRead < maxBytesToRead)
  5923. {
  5924. int bytesThisTime;
  5925. #if JUCE_WINDOWS
  5926. bytesThisTime = recv (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  5927. #else
  5928. while ((bytesThisTime = (int) ::read (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead)) < 0
  5929. && errno == EINTR
  5930. && connected)
  5931. {
  5932. }
  5933. #endif
  5934. if (bytesThisTime <= 0 || ! connected)
  5935. {
  5936. if (bytesRead == 0)
  5937. bytesRead = -1;
  5938. break;
  5939. }
  5940. bytesRead += bytesThisTime;
  5941. if (! blockUntilSpecifiedAmountHasArrived)
  5942. break;
  5943. }
  5944. return bytesRead;
  5945. }
  5946. static int waitForReadiness (const int handle, const bool forReading,
  5947. const int timeoutMsecs) throw()
  5948. {
  5949. struct timeval timeout;
  5950. struct timeval* timeoutp;
  5951. if (timeoutMsecs >= 0)
  5952. {
  5953. timeout.tv_sec = timeoutMsecs / 1000;
  5954. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  5955. timeoutp = &timeout;
  5956. }
  5957. else
  5958. {
  5959. timeoutp = 0;
  5960. }
  5961. fd_set rset, wset;
  5962. FD_ZERO (&rset);
  5963. FD_SET (handle, &rset);
  5964. FD_ZERO (&wset);
  5965. FD_SET (handle, &wset);
  5966. fd_set* const prset = forReading ? &rset : 0;
  5967. fd_set* const pwset = forReading ? 0 : &wset;
  5968. #if JUCE_WINDOWS
  5969. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  5970. return -1;
  5971. #else
  5972. {
  5973. int result;
  5974. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  5975. && errno == EINTR)
  5976. {
  5977. }
  5978. if (result < 0)
  5979. return -1;
  5980. }
  5981. #endif
  5982. {
  5983. int opt;
  5984. juce_socklen_t len = sizeof (opt);
  5985. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  5986. || opt != 0)
  5987. return -1;
  5988. }
  5989. if ((forReading && FD_ISSET (handle, &rset))
  5990. || ((! forReading) && FD_ISSET (handle, &wset)))
  5991. return 1;
  5992. return 0;
  5993. }
  5994. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  5995. {
  5996. #if JUCE_WINDOWS
  5997. u_long nonBlocking = shouldBlock ? 0 : 1;
  5998. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  5999. return false;
  6000. #else
  6001. int socketFlags = fcntl (handle, F_GETFL, 0);
  6002. if (socketFlags == -1)
  6003. return false;
  6004. if (shouldBlock)
  6005. socketFlags &= ~O_NONBLOCK;
  6006. else
  6007. socketFlags |= O_NONBLOCK;
  6008. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  6009. return false;
  6010. #endif
  6011. return true;
  6012. }
  6013. static bool connectSocket (int volatile& handle,
  6014. const bool isDatagram,
  6015. void** serverAddress,
  6016. const String& hostName,
  6017. const int portNumber,
  6018. const int timeOutMillisecs) throw()
  6019. {
  6020. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  6021. if (hostEnt == 0)
  6022. return false;
  6023. struct in_addr targetAddress;
  6024. memcpy (&targetAddress.s_addr,
  6025. *(hostEnt->h_addr_list),
  6026. sizeof (targetAddress.s_addr));
  6027. struct sockaddr_in servTmpAddr;
  6028. zerostruct (servTmpAddr);
  6029. servTmpAddr.sin_family = PF_INET;
  6030. servTmpAddr.sin_addr = targetAddress;
  6031. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6032. if (handle < 0)
  6033. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  6034. if (handle < 0)
  6035. return false;
  6036. if (isDatagram)
  6037. {
  6038. *serverAddress = new struct sockaddr_in();
  6039. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  6040. return true;
  6041. }
  6042. setSocketBlockingState (handle, false);
  6043. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  6044. if (result < 0)
  6045. {
  6046. #if JUCE_WINDOWS
  6047. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  6048. #else
  6049. if (errno == EINPROGRESS)
  6050. #endif
  6051. {
  6052. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  6053. {
  6054. setSocketBlockingState (handle, true);
  6055. return false;
  6056. }
  6057. }
  6058. }
  6059. setSocketBlockingState (handle, true);
  6060. resetSocketOptions (handle, false, false);
  6061. return true;
  6062. }
  6063. StreamingSocket::StreamingSocket()
  6064. : portNumber (0),
  6065. handle (-1),
  6066. connected (false),
  6067. isListener (false)
  6068. {
  6069. #if JUCE_WINDOWS
  6070. initWin32Sockets();
  6071. #endif
  6072. }
  6073. StreamingSocket::StreamingSocket (const String& hostName_,
  6074. const int portNumber_,
  6075. const int handle_)
  6076. : hostName (hostName_),
  6077. portNumber (portNumber_),
  6078. handle (handle_),
  6079. connected (true),
  6080. isListener (false)
  6081. {
  6082. #if JUCE_WINDOWS
  6083. initWin32Sockets();
  6084. #endif
  6085. resetSocketOptions (handle_, false, false);
  6086. }
  6087. StreamingSocket::~StreamingSocket()
  6088. {
  6089. close();
  6090. }
  6091. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6092. {
  6093. return (connected && ! isListener) ? readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6094. : -1;
  6095. }
  6096. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6097. {
  6098. if (isListener || ! connected)
  6099. return -1;
  6100. #if JUCE_WINDOWS
  6101. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  6102. #else
  6103. int result;
  6104. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  6105. && errno == EINTR)
  6106. {
  6107. }
  6108. return result;
  6109. #endif
  6110. }
  6111. int StreamingSocket::waitUntilReady (const bool readyForReading,
  6112. const int timeoutMsecs) const
  6113. {
  6114. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  6115. : -1;
  6116. }
  6117. bool StreamingSocket::bindToPort (const int port)
  6118. {
  6119. return bindSocketToPort (handle, port);
  6120. }
  6121. bool StreamingSocket::connect (const String& remoteHostName,
  6122. const int remotePortNumber,
  6123. const int timeOutMillisecs)
  6124. {
  6125. if (isListener)
  6126. {
  6127. jassertfalse // a listener socket can't connect to another one!
  6128. return false;
  6129. }
  6130. if (connected)
  6131. close();
  6132. hostName = remoteHostName;
  6133. portNumber = remotePortNumber;
  6134. isListener = false;
  6135. connected = connectSocket (handle, false, 0, remoteHostName,
  6136. remotePortNumber, timeOutMillisecs);
  6137. if (! (connected && resetSocketOptions (handle, false, false)))
  6138. {
  6139. close();
  6140. return false;
  6141. }
  6142. return true;
  6143. }
  6144. void StreamingSocket::close()
  6145. {
  6146. #if JUCE_WINDOWS
  6147. if (handle != SOCKET_ERROR || connected)
  6148. closesocket (handle);
  6149. connected = false;
  6150. #else
  6151. if (connected)
  6152. {
  6153. connected = false;
  6154. if (isListener)
  6155. {
  6156. // need to do this to interrupt the accept() function..
  6157. StreamingSocket temp;
  6158. temp.connect ("localhost", portNumber, 1000);
  6159. }
  6160. }
  6161. if (handle != -1)
  6162. ::close (handle);
  6163. #endif
  6164. hostName = String::empty;
  6165. portNumber = 0;
  6166. handle = -1;
  6167. isListener = false;
  6168. }
  6169. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  6170. {
  6171. if (connected)
  6172. close();
  6173. hostName = "listener";
  6174. portNumber = newPortNumber;
  6175. isListener = true;
  6176. struct sockaddr_in servTmpAddr;
  6177. zerostruct (servTmpAddr);
  6178. servTmpAddr.sin_family = PF_INET;
  6179. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6180. if (localHostName.isNotEmpty())
  6181. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  6182. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6183. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  6184. if (handle < 0)
  6185. return false;
  6186. const int reuse = 1;
  6187. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  6188. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  6189. || listen (handle, SOMAXCONN) < 0)
  6190. {
  6191. close();
  6192. return false;
  6193. }
  6194. connected = true;
  6195. return true;
  6196. }
  6197. StreamingSocket* StreamingSocket::waitForNextConnection() const
  6198. {
  6199. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  6200. // prepare this socket as a listener.
  6201. if (connected && isListener)
  6202. {
  6203. struct sockaddr address;
  6204. juce_socklen_t len = sizeof (sockaddr);
  6205. const int newSocket = (int) accept (handle, &address, &len);
  6206. if (newSocket >= 0 && connected)
  6207. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6208. portNumber, newSocket);
  6209. }
  6210. return 0;
  6211. }
  6212. bool StreamingSocket::isLocal() const throw()
  6213. {
  6214. return hostName == "127.0.0.1";
  6215. }
  6216. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  6217. : portNumber (0),
  6218. handle (-1),
  6219. connected (true),
  6220. allowBroadcast (allowBroadcast_),
  6221. serverAddress (0)
  6222. {
  6223. #if JUCE_WINDOWS
  6224. initWin32Sockets();
  6225. #endif
  6226. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  6227. bindToPort (localPortNumber);
  6228. }
  6229. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  6230. const int handle_, const int localPortNumber)
  6231. : hostName (hostName_),
  6232. portNumber (portNumber_),
  6233. handle (handle_),
  6234. connected (true),
  6235. allowBroadcast (false),
  6236. serverAddress (0)
  6237. {
  6238. #if JUCE_WINDOWS
  6239. initWin32Sockets();
  6240. #endif
  6241. resetSocketOptions (handle_, true, allowBroadcast);
  6242. bindToPort (localPortNumber);
  6243. }
  6244. DatagramSocket::~DatagramSocket()
  6245. {
  6246. close();
  6247. delete ((struct sockaddr_in*) serverAddress);
  6248. serverAddress = 0;
  6249. }
  6250. void DatagramSocket::close()
  6251. {
  6252. #if JUCE_WINDOWS
  6253. closesocket (handle);
  6254. connected = false;
  6255. #else
  6256. connected = false;
  6257. ::close (handle);
  6258. #endif
  6259. hostName = String::empty;
  6260. portNumber = 0;
  6261. handle = -1;
  6262. }
  6263. bool DatagramSocket::bindToPort (const int port)
  6264. {
  6265. return bindSocketToPort (handle, port);
  6266. }
  6267. bool DatagramSocket::connect (const String& remoteHostName,
  6268. const int remotePortNumber,
  6269. const int timeOutMillisecs)
  6270. {
  6271. if (connected)
  6272. close();
  6273. hostName = remoteHostName;
  6274. portNumber = remotePortNumber;
  6275. connected = connectSocket (handle, true, &serverAddress,
  6276. remoteHostName, remotePortNumber,
  6277. timeOutMillisecs);
  6278. if (! (connected && resetSocketOptions (handle, true, allowBroadcast)))
  6279. {
  6280. close();
  6281. return false;
  6282. }
  6283. return true;
  6284. }
  6285. DatagramSocket* DatagramSocket::waitForNextConnection() const
  6286. {
  6287. struct sockaddr address;
  6288. juce_socklen_t len = sizeof (sockaddr);
  6289. while (waitUntilReady (true, -1) == 1)
  6290. {
  6291. char buf[1];
  6292. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  6293. {
  6294. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6295. ntohs (((struct sockaddr_in*) &address)->sin_port),
  6296. -1, -1);
  6297. }
  6298. }
  6299. return 0;
  6300. }
  6301. int DatagramSocket::waitUntilReady (const bool readyForReading,
  6302. const int timeoutMsecs) const
  6303. {
  6304. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  6305. : -1;
  6306. }
  6307. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6308. {
  6309. return connected ? readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6310. : -1;
  6311. }
  6312. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6313. {
  6314. // You need to call connect() first to set the server address..
  6315. jassert (serverAddress != 0 && connected);
  6316. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  6317. numBytesToWrite, 0,
  6318. (const struct sockaddr*) serverAddress,
  6319. sizeof (struct sockaddr_in))
  6320. : -1;
  6321. }
  6322. bool DatagramSocket::isLocal() const throw()
  6323. {
  6324. return hostName == "127.0.0.1";
  6325. }
  6326. #if JUCE_MSVC
  6327. #pragma warning (pop)
  6328. #endif
  6329. END_JUCE_NAMESPACE
  6330. /*** End of inlined file: juce_Socket.cpp ***/
  6331. /*** Start of inlined file: juce_URL.cpp ***/
  6332. BEGIN_JUCE_NAMESPACE
  6333. URL::URL()
  6334. {
  6335. }
  6336. URL::URL (const String& url_)
  6337. : url (url_)
  6338. {
  6339. int i = url.indexOfChar ('?');
  6340. if (i >= 0)
  6341. {
  6342. do
  6343. {
  6344. const int nextAmp = url.indexOfChar (i + 1, '&');
  6345. const int equalsPos = url.indexOfChar (i + 1, '=');
  6346. if (equalsPos > i + 1)
  6347. {
  6348. if (nextAmp < 0)
  6349. {
  6350. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6351. removeEscapeChars (url.substring (equalsPos + 1)));
  6352. }
  6353. else if (nextAmp > 0 && equalsPos < nextAmp)
  6354. {
  6355. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6356. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  6357. }
  6358. }
  6359. i = nextAmp;
  6360. }
  6361. while (i >= 0);
  6362. url = url.upToFirstOccurrenceOf ("?", false, false);
  6363. }
  6364. }
  6365. URL::URL (const URL& other)
  6366. : url (other.url),
  6367. postData (other.postData),
  6368. parameters (other.parameters),
  6369. filesToUpload (other.filesToUpload),
  6370. mimeTypes (other.mimeTypes)
  6371. {
  6372. }
  6373. URL& URL::operator= (const URL& other)
  6374. {
  6375. url = other.url;
  6376. postData = other.postData;
  6377. parameters = other.parameters;
  6378. filesToUpload = other.filesToUpload;
  6379. mimeTypes = other.mimeTypes;
  6380. return *this;
  6381. }
  6382. URL::~URL()
  6383. {
  6384. }
  6385. static const String getMangledParameters (const StringPairArray& parameters)
  6386. {
  6387. String p;
  6388. for (int i = 0; i < parameters.size(); ++i)
  6389. {
  6390. if (i > 0)
  6391. p += '&';
  6392. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  6393. << '='
  6394. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  6395. }
  6396. return p;
  6397. }
  6398. const String URL::toString (const bool includeGetParameters) const
  6399. {
  6400. if (includeGetParameters && parameters.size() > 0)
  6401. return url + "?" + getMangledParameters (parameters);
  6402. else
  6403. return url;
  6404. }
  6405. bool URL::isWellFormed() const
  6406. {
  6407. //xxx TODO
  6408. return url.isNotEmpty();
  6409. }
  6410. static int findStartOfDomain (const String& url)
  6411. {
  6412. int i = 0;
  6413. while (CharacterFunctions::isLetterOrDigit (url[i])
  6414. || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0)
  6415. ++i;
  6416. return url[i] == ':' ? i + 1 : 0;
  6417. }
  6418. const String URL::getDomain() const
  6419. {
  6420. int start = findStartOfDomain (url);
  6421. while (url[start] == '/')
  6422. ++start;
  6423. const int end1 = url.indexOfChar (start, '/');
  6424. const int end2 = url.indexOfChar (start, ':');
  6425. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  6426. : jmin (end1, end2);
  6427. return url.substring (start, end);
  6428. }
  6429. const String URL::getSubPath() const
  6430. {
  6431. int start = findStartOfDomain (url);
  6432. while (url[start] == '/')
  6433. ++start;
  6434. const int startOfPath = url.indexOfChar (start, '/') + 1;
  6435. return startOfPath <= 0 ? String::empty
  6436. : url.substring (startOfPath);
  6437. }
  6438. const String URL::getScheme() const
  6439. {
  6440. return url.substring (0, findStartOfDomain (url) - 1);
  6441. }
  6442. const URL URL::withNewSubPath (const String& newPath) const
  6443. {
  6444. int start = findStartOfDomain (url);
  6445. while (url[start] == '/')
  6446. ++start;
  6447. const int startOfPath = url.indexOfChar (start, '/') + 1;
  6448. URL u (*this);
  6449. if (startOfPath > 0)
  6450. u.url = url.substring (0, startOfPath);
  6451. if (! u.url.endsWithChar ('/'))
  6452. u.url << '/';
  6453. if (newPath.startsWithChar ('/'))
  6454. u.url << newPath.substring (1);
  6455. else
  6456. u.url << newPath;
  6457. return u;
  6458. }
  6459. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  6460. {
  6461. if (possibleURL.startsWithIgnoreCase ("http:")
  6462. || possibleURL.startsWithIgnoreCase ("ftp:"))
  6463. return true;
  6464. if (possibleURL.startsWithIgnoreCase ("file:")
  6465. || possibleURL.containsChar ('@')
  6466. || possibleURL.endsWithChar ('.')
  6467. || (! possibleURL.containsChar ('.')))
  6468. return false;
  6469. if (possibleURL.startsWithIgnoreCase ("www.")
  6470. && possibleURL.substring (5).containsChar ('.'))
  6471. return true;
  6472. const char* commonTLDs[] = { "com", "net", "org", "uk", "de", "fr", "jp" };
  6473. for (int i = 0; i < numElementsInArray (commonTLDs); ++i)
  6474. if ((possibleURL + "/").containsIgnoreCase ("." + String (commonTLDs[i]) + "/"))
  6475. return true;
  6476. return false;
  6477. }
  6478. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  6479. {
  6480. const int atSign = possibleEmailAddress.indexOfChar ('@');
  6481. return atSign > 0
  6482. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  6483. && (! possibleEmailAddress.endsWithChar ('.'));
  6484. }
  6485. void* juce_openInternetFile (const String& url,
  6486. const String& headers,
  6487. const MemoryBlock& optionalPostData,
  6488. const bool isPost,
  6489. URL::OpenStreamProgressCallback* callback,
  6490. void* callbackContext,
  6491. int timeOutMs);
  6492. void juce_closeInternetFile (void* handle);
  6493. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  6494. int juce_seekInInternetFile (void* handle, int newPosition);
  6495. int64 juce_getInternetFileContentLength (void* handle);
  6496. class WebInputStream : public InputStream
  6497. {
  6498. public:
  6499. WebInputStream (const URL& url,
  6500. const bool isPost_,
  6501. URL::OpenStreamProgressCallback* const progressCallback_,
  6502. void* const progressCallbackContext_,
  6503. const String& extraHeaders,
  6504. int timeOutMs_)
  6505. : position (0),
  6506. finished (false),
  6507. isPost (isPost_),
  6508. progressCallback (progressCallback_),
  6509. progressCallbackContext (progressCallbackContext_),
  6510. timeOutMs (timeOutMs_)
  6511. {
  6512. server = url.toString (! isPost);
  6513. if (isPost_)
  6514. createHeadersAndPostData (url);
  6515. headers += extraHeaders;
  6516. if (! headers.endsWithChar ('\n'))
  6517. headers << "\r\n";
  6518. handle = juce_openInternetFile (server, headers, postData, isPost,
  6519. progressCallback_, progressCallbackContext_,
  6520. timeOutMs);
  6521. }
  6522. ~WebInputStream()
  6523. {
  6524. juce_closeInternetFile (handle);
  6525. }
  6526. bool isError() const { return handle == 0; }
  6527. int64 getTotalLength() { return juce_getInternetFileContentLength (handle); }
  6528. bool isExhausted() { return finished; }
  6529. int64 getPosition() { return position; }
  6530. int read (void* dest, int bytes)
  6531. {
  6532. if (finished || isError())
  6533. {
  6534. return 0;
  6535. }
  6536. else
  6537. {
  6538. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  6539. position += bytesRead;
  6540. if (bytesRead == 0)
  6541. finished = true;
  6542. return bytesRead;
  6543. }
  6544. }
  6545. bool setPosition (int64 wantedPos)
  6546. {
  6547. if (wantedPos != position)
  6548. {
  6549. finished = false;
  6550. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  6551. if (actualPos == wantedPos)
  6552. {
  6553. position = wantedPos;
  6554. }
  6555. else
  6556. {
  6557. if (wantedPos < position)
  6558. {
  6559. juce_closeInternetFile (handle);
  6560. position = 0;
  6561. finished = false;
  6562. handle = juce_openInternetFile (server, headers, postData, isPost,
  6563. progressCallback, progressCallbackContext,
  6564. timeOutMs);
  6565. }
  6566. skipNextBytes (wantedPos - position);
  6567. }
  6568. }
  6569. return true;
  6570. }
  6571. juce_UseDebuggingNewOperator
  6572. private:
  6573. String server, headers;
  6574. MemoryBlock postData;
  6575. int64 position;
  6576. bool finished;
  6577. const bool isPost;
  6578. void* handle;
  6579. URL::OpenStreamProgressCallback* const progressCallback;
  6580. void* const progressCallbackContext;
  6581. const int timeOutMs;
  6582. void createHeadersAndPostData (const URL& url)
  6583. {
  6584. MemoryOutputStream data (256, 256, &postData);
  6585. if (url.getFilesToUpload().size() > 0)
  6586. {
  6587. // need to upload some files, so do it as multi-part...
  6588. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  6589. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  6590. data << "--" << boundary;
  6591. int i;
  6592. for (i = 0; i < url.getParameters().size(); ++i)
  6593. {
  6594. data << "\r\nContent-Disposition: form-data; name=\""
  6595. << url.getParameters().getAllKeys() [i]
  6596. << "\"\r\n\r\n"
  6597. << url.getParameters().getAllValues() [i]
  6598. << "\r\n--"
  6599. << boundary;
  6600. }
  6601. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  6602. {
  6603. const File file (url.getFilesToUpload().getAllValues() [i]);
  6604. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  6605. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  6606. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  6607. const String mimeType (url.getMimeTypesOfUploadFiles()
  6608. .getValue (paramName, String::empty));
  6609. if (mimeType.isNotEmpty())
  6610. data << "Content-Type: " << mimeType << "\r\n";
  6611. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  6612. << file << "\r\n--" << boundary;
  6613. }
  6614. data << "--\r\n";
  6615. }
  6616. else
  6617. {
  6618. data << getMangledParameters (url.getParameters())
  6619. << url.getPostData();
  6620. // just a short text attachment, so use simple url encoding..
  6621. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  6622. + String ((unsigned int) postData.getSize())
  6623. + "\r\n";
  6624. }
  6625. }
  6626. WebInputStream (const WebInputStream&);
  6627. WebInputStream& operator= (const WebInputStream&);
  6628. };
  6629. InputStream* URL::createInputStream (const bool usePostCommand,
  6630. OpenStreamProgressCallback* const progressCallback,
  6631. void* const progressCallbackContext,
  6632. const String& extraHeaders,
  6633. const int timeOutMs) const
  6634. {
  6635. ScopedPointer <WebInputStream> wi (new WebInputStream (*this, usePostCommand,
  6636. progressCallback, progressCallbackContext,
  6637. extraHeaders,
  6638. timeOutMs));
  6639. return wi->isError() ? 0 : wi.release();
  6640. }
  6641. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  6642. const bool usePostCommand) const
  6643. {
  6644. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  6645. if (in != 0)
  6646. {
  6647. in->readIntoMemoryBlock (destData, -1);
  6648. return true;
  6649. }
  6650. return false;
  6651. }
  6652. const String URL::readEntireTextStream (const bool usePostCommand) const
  6653. {
  6654. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  6655. if (in != 0)
  6656. return in->readEntireStreamAsString();
  6657. return String::empty;
  6658. }
  6659. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  6660. {
  6661. XmlDocument doc (readEntireTextStream (usePostCommand));
  6662. return doc.getDocumentElement();
  6663. }
  6664. const URL URL::withParameter (const String& parameterName,
  6665. const String& parameterValue) const
  6666. {
  6667. URL u (*this);
  6668. u.parameters.set (parameterName, parameterValue);
  6669. return u;
  6670. }
  6671. const URL URL::withFileToUpload (const String& parameterName,
  6672. const File& fileToUpload,
  6673. const String& mimeType) const
  6674. {
  6675. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  6676. URL u (*this);
  6677. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  6678. u.mimeTypes.set (parameterName, mimeType);
  6679. return u;
  6680. }
  6681. const URL URL::withPOSTData (const String& postData_) const
  6682. {
  6683. URL u (*this);
  6684. u.postData = postData_;
  6685. return u;
  6686. }
  6687. const StringPairArray& URL::getParameters() const
  6688. {
  6689. return parameters;
  6690. }
  6691. const StringPairArray& URL::getFilesToUpload() const
  6692. {
  6693. return filesToUpload;
  6694. }
  6695. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  6696. {
  6697. return mimeTypes;
  6698. }
  6699. const String URL::removeEscapeChars (const String& s)
  6700. {
  6701. String result (s.replaceCharacter ('+', ' '));
  6702. int nextPercent = 0;
  6703. for (;;)
  6704. {
  6705. nextPercent = result.indexOfChar (nextPercent, '%');
  6706. if (nextPercent < 0)
  6707. break;
  6708. juce_wchar replacementChar = (juce_wchar) result.substring (nextPercent + 1, nextPercent + 3).getHexValue32();
  6709. result = result.replaceSection (nextPercent, 3, String::charToString (replacementChar));
  6710. ++nextPercent;
  6711. }
  6712. return result;
  6713. }
  6714. const String URL::addEscapeChars (const String& s, const bool isParameter)
  6715. {
  6716. String result;
  6717. result.preallocateStorage (s.length() + 8);
  6718. const char* utf8 = s.toUTF8();
  6719. const char* legalChars = isParameter ? "_-.*!'()"
  6720. : "_-$.*!'(),";
  6721. while (*utf8 != 0)
  6722. {
  6723. const char c = *utf8++;
  6724. if (CharacterFunctions::isLetterOrDigit (c)
  6725. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0)
  6726. {
  6727. result << c;
  6728. }
  6729. else
  6730. {
  6731. const int v = (int) (uint8) c;
  6732. result << (v < 0x10 ? "%0" : "%") << String::toHexString (v);
  6733. }
  6734. }
  6735. return result;
  6736. }
  6737. bool URL::launchInDefaultBrowser() const
  6738. {
  6739. String u (toString (true));
  6740. if (u.containsChar ('@') && ! u.containsChar (':'))
  6741. u = "mailto:" + u;
  6742. return PlatformUtilities::openDocument (u, String::empty);
  6743. }
  6744. END_JUCE_NAMESPACE
  6745. /*** End of inlined file: juce_URL.cpp ***/
  6746. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  6747. BEGIN_JUCE_NAMESPACE
  6748. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  6749. const int bufferSize_,
  6750. const bool deleteSourceWhenDestroyed)
  6751. : source (source_),
  6752. sourceToDelete (deleteSourceWhenDestroyed ? source_ : 0),
  6753. bufferSize (jmax (256, bufferSize_)),
  6754. position (source_->getPosition()),
  6755. lastReadPos (0),
  6756. bufferOverlap (128)
  6757. {
  6758. const int sourceSize = (int) source_->getTotalLength();
  6759. if (sourceSize >= 0)
  6760. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  6761. bufferStart = position;
  6762. buffer.malloc (bufferSize);
  6763. }
  6764. BufferedInputStream::~BufferedInputStream()
  6765. {
  6766. }
  6767. int64 BufferedInputStream::getTotalLength()
  6768. {
  6769. return source->getTotalLength();
  6770. }
  6771. int64 BufferedInputStream::getPosition()
  6772. {
  6773. return position;
  6774. }
  6775. bool BufferedInputStream::setPosition (int64 newPosition)
  6776. {
  6777. position = jmax ((int64) 0, newPosition);
  6778. return true;
  6779. }
  6780. bool BufferedInputStream::isExhausted()
  6781. {
  6782. return (position >= lastReadPos)
  6783. && source->isExhausted();
  6784. }
  6785. void BufferedInputStream::ensureBuffered()
  6786. {
  6787. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  6788. if (position < bufferStart || position >= bufferEndOverlap)
  6789. {
  6790. int bytesRead;
  6791. if (position < lastReadPos
  6792. && position >= bufferEndOverlap
  6793. && position >= bufferStart)
  6794. {
  6795. const int bytesToKeep = (int) (lastReadPos - position);
  6796. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  6797. bufferStart = position;
  6798. bytesRead = source->read (buffer + bytesToKeep,
  6799. bufferSize - bytesToKeep);
  6800. lastReadPos += bytesRead;
  6801. bytesRead += bytesToKeep;
  6802. }
  6803. else
  6804. {
  6805. bufferStart = position;
  6806. source->setPosition (bufferStart);
  6807. bytesRead = source->read (buffer, bufferSize);
  6808. lastReadPos = bufferStart + bytesRead;
  6809. }
  6810. while (bytesRead < bufferSize)
  6811. buffer [bytesRead++] = 0;
  6812. }
  6813. }
  6814. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  6815. {
  6816. if (position >= bufferStart
  6817. && position + maxBytesToRead <= lastReadPos)
  6818. {
  6819. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  6820. position += maxBytesToRead;
  6821. return maxBytesToRead;
  6822. }
  6823. else
  6824. {
  6825. if (position < bufferStart || position >= lastReadPos)
  6826. ensureBuffered();
  6827. int bytesRead = 0;
  6828. while (maxBytesToRead > 0)
  6829. {
  6830. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  6831. if (bytesAvailable > 0)
  6832. {
  6833. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  6834. maxBytesToRead -= bytesAvailable;
  6835. bytesRead += bytesAvailable;
  6836. position += bytesAvailable;
  6837. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  6838. }
  6839. const int64 oldLastReadPos = lastReadPos;
  6840. ensureBuffered();
  6841. if (oldLastReadPos == lastReadPos)
  6842. break; // if ensureBuffered() failed to read any more data, bail out
  6843. if (isExhausted())
  6844. break;
  6845. }
  6846. return bytesRead;
  6847. }
  6848. }
  6849. const String BufferedInputStream::readString()
  6850. {
  6851. if (position >= bufferStart
  6852. && position < lastReadPos)
  6853. {
  6854. const int maxChars = (int) (lastReadPos - position);
  6855. const char* const src = buffer + (int) (position - bufferStart);
  6856. for (int i = 0; i < maxChars; ++i)
  6857. {
  6858. if (src[i] == 0)
  6859. {
  6860. position += i + 1;
  6861. return String::fromUTF8 (src, i);
  6862. }
  6863. }
  6864. }
  6865. return InputStream::readString();
  6866. }
  6867. END_JUCE_NAMESPACE
  6868. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  6869. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  6870. BEGIN_JUCE_NAMESPACE
  6871. FileInputSource::FileInputSource (const File& file_)
  6872. : file (file_)
  6873. {
  6874. }
  6875. FileInputSource::~FileInputSource()
  6876. {
  6877. }
  6878. InputStream* FileInputSource::createInputStream()
  6879. {
  6880. return file.createInputStream();
  6881. }
  6882. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  6883. {
  6884. return file.getSiblingFile (relatedItemPath).createInputStream();
  6885. }
  6886. int64 FileInputSource::hashCode() const
  6887. {
  6888. return file.hashCode();
  6889. }
  6890. END_JUCE_NAMESPACE
  6891. /*** End of inlined file: juce_FileInputSource.cpp ***/
  6892. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  6893. BEGIN_JUCE_NAMESPACE
  6894. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  6895. const size_t sourceDataSize,
  6896. const bool keepInternalCopy)
  6897. : data (static_cast <const char*> (sourceData)),
  6898. dataSize (sourceDataSize),
  6899. position (0)
  6900. {
  6901. if (keepInternalCopy)
  6902. {
  6903. internalCopy.append (data, sourceDataSize);
  6904. data = static_cast <const char*> (internalCopy.getData());
  6905. }
  6906. }
  6907. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  6908. const bool keepInternalCopy)
  6909. : data (static_cast <const char*> (sourceData.getData())),
  6910. dataSize (sourceData.getSize()),
  6911. position (0)
  6912. {
  6913. if (keepInternalCopy)
  6914. {
  6915. internalCopy = sourceData;
  6916. data = static_cast <const char*> (internalCopy.getData());
  6917. }
  6918. }
  6919. MemoryInputStream::~MemoryInputStream()
  6920. {
  6921. }
  6922. int64 MemoryInputStream::getTotalLength()
  6923. {
  6924. return dataSize;
  6925. }
  6926. int MemoryInputStream::read (void* const buffer, const int howMany)
  6927. {
  6928. jassert (howMany >= 0);
  6929. const int num = jmin (howMany, (int) (dataSize - position));
  6930. memcpy (buffer, data + position, num);
  6931. position += num;
  6932. return (int) num;
  6933. }
  6934. bool MemoryInputStream::isExhausted()
  6935. {
  6936. return (position >= dataSize);
  6937. }
  6938. bool MemoryInputStream::setPosition (const int64 pos)
  6939. {
  6940. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  6941. return true;
  6942. }
  6943. int64 MemoryInputStream::getPosition()
  6944. {
  6945. return position;
  6946. }
  6947. END_JUCE_NAMESPACE
  6948. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  6949. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  6950. BEGIN_JUCE_NAMESPACE
  6951. MemoryOutputStream::MemoryOutputStream (const size_t initialSize,
  6952. const size_t blockSizeToIncreaseBy,
  6953. MemoryBlock* const memoryBlockToWriteTo)
  6954. : data (memoryBlockToWriteTo),
  6955. position (0),
  6956. size (0),
  6957. blockSize (jmax ((size_t) 16, blockSizeToIncreaseBy))
  6958. {
  6959. if (data == 0)
  6960. dataToDelete = data = new MemoryBlock (initialSize);
  6961. else
  6962. data->setSize (initialSize, false);
  6963. }
  6964. MemoryOutputStream::~MemoryOutputStream()
  6965. {
  6966. flush();
  6967. }
  6968. void MemoryOutputStream::flush()
  6969. {
  6970. if (dataToDelete == 0)
  6971. data->setSize (size, false);
  6972. }
  6973. void MemoryOutputStream::reset() throw()
  6974. {
  6975. position = 0;
  6976. size = 0;
  6977. }
  6978. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  6979. {
  6980. if (howMany > 0)
  6981. {
  6982. size_t storageNeeded = position + howMany;
  6983. if (storageNeeded >= data->getSize())
  6984. {
  6985. // if we need more space, increase the block by at least 10%..
  6986. storageNeeded += jmax (blockSize, storageNeeded / 10);
  6987. storageNeeded = storageNeeded - (storageNeeded % blockSize) + blockSize;
  6988. data->ensureSize (storageNeeded);
  6989. }
  6990. data->copyFrom (buffer, (int) position, howMany);
  6991. position += howMany;
  6992. size = jmax (size, position);
  6993. }
  6994. return true;
  6995. }
  6996. const char* MemoryOutputStream::getData() const throw()
  6997. {
  6998. char* const d = static_cast <char*> (data->getData());
  6999. if (data->getSize() > size)
  7000. d [size] = 0;
  7001. return d;
  7002. }
  7003. bool MemoryOutputStream::setPosition (int64 newPosition)
  7004. {
  7005. if (newPosition <= (int64) size)
  7006. {
  7007. // ok to seek backwards
  7008. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  7009. return true;
  7010. }
  7011. else
  7012. {
  7013. // trying to make it bigger isn't a good thing to do..
  7014. return false;
  7015. }
  7016. }
  7017. const String MemoryOutputStream::toUTF8() const
  7018. {
  7019. return String (getData(), getDataSize());
  7020. }
  7021. END_JUCE_NAMESPACE
  7022. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  7023. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  7024. BEGIN_JUCE_NAMESPACE
  7025. SubregionStream::SubregionStream (InputStream* const sourceStream,
  7026. const int64 startPositionInSourceStream_,
  7027. const int64 lengthOfSourceStream_,
  7028. const bool deleteSourceWhenDestroyed) throw()
  7029. : source (sourceStream),
  7030. startPositionInSourceStream (startPositionInSourceStream_),
  7031. lengthOfSourceStream (lengthOfSourceStream_)
  7032. {
  7033. if (deleteSourceWhenDestroyed)
  7034. sourceToDelete = source;
  7035. setPosition (0);
  7036. }
  7037. SubregionStream::~SubregionStream() throw()
  7038. {
  7039. }
  7040. int64 SubregionStream::getTotalLength()
  7041. {
  7042. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  7043. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  7044. : srcLen;
  7045. }
  7046. int64 SubregionStream::getPosition()
  7047. {
  7048. return source->getPosition() - startPositionInSourceStream;
  7049. }
  7050. bool SubregionStream::setPosition (int64 newPosition)
  7051. {
  7052. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  7053. }
  7054. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  7055. {
  7056. if (lengthOfSourceStream < 0)
  7057. {
  7058. return source->read (destBuffer, maxBytesToRead);
  7059. }
  7060. else
  7061. {
  7062. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  7063. if (maxBytesToRead <= 0)
  7064. return 0;
  7065. return source->read (destBuffer, maxBytesToRead);
  7066. }
  7067. }
  7068. bool SubregionStream::isExhausted()
  7069. {
  7070. if (lengthOfSourceStream >= 0)
  7071. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  7072. else
  7073. return source->isExhausted();
  7074. }
  7075. END_JUCE_NAMESPACE
  7076. /*** End of inlined file: juce_SubregionStream.cpp ***/
  7077. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  7078. BEGIN_JUCE_NAMESPACE
  7079. PerformanceCounter::PerformanceCounter (const String& name_,
  7080. int runsPerPrintout,
  7081. const File& loggingFile)
  7082. : name (name_),
  7083. numRuns (0),
  7084. runsPerPrint (runsPerPrintout),
  7085. totalTime (0),
  7086. outputFile (loggingFile)
  7087. {
  7088. if (outputFile != File::nonexistent)
  7089. {
  7090. String s ("**** Counter for \"");
  7091. s << name_ << "\" started at: "
  7092. << Time::getCurrentTime().toString (true, true)
  7093. << "\r\n";
  7094. outputFile.appendText (s, false, false);
  7095. }
  7096. }
  7097. PerformanceCounter::~PerformanceCounter()
  7098. {
  7099. printStatistics();
  7100. }
  7101. void PerformanceCounter::start()
  7102. {
  7103. started = Time::getHighResolutionTicks();
  7104. }
  7105. void PerformanceCounter::stop()
  7106. {
  7107. const int64 now = Time::getHighResolutionTicks();
  7108. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  7109. if (++numRuns == runsPerPrint)
  7110. printStatistics();
  7111. }
  7112. void PerformanceCounter::printStatistics()
  7113. {
  7114. if (numRuns > 0)
  7115. {
  7116. String s ("Performance count for \"");
  7117. s << name << "\" - average over " << numRuns << " run(s) = ";
  7118. const int micros = (int) (totalTime * (1000.0 / numRuns));
  7119. if (micros > 10000)
  7120. s << (micros/1000) << " millisecs";
  7121. else
  7122. s << micros << " microsecs";
  7123. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  7124. Logger::outputDebugString (s);
  7125. s << "\r\n";
  7126. if (outputFile != File::nonexistent)
  7127. outputFile.appendText (s, false, false);
  7128. numRuns = 0;
  7129. totalTime = 0;
  7130. }
  7131. }
  7132. END_JUCE_NAMESPACE
  7133. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  7134. /*** Start of inlined file: juce_Uuid.cpp ***/
  7135. BEGIN_JUCE_NAMESPACE
  7136. Uuid::Uuid()
  7137. {
  7138. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  7139. // to make it very very unlikely that two UUIDs will ever be the same..
  7140. static int64 macAddresses[2];
  7141. static bool hasCheckedMacAddresses = false;
  7142. if (! hasCheckedMacAddresses)
  7143. {
  7144. hasCheckedMacAddresses = true;
  7145. SystemStats::getMACAddresses (macAddresses, 2);
  7146. }
  7147. value.asInt64[0] = macAddresses[0];
  7148. value.asInt64[1] = macAddresses[1];
  7149. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  7150. // whose seed will carry over between calls to this method.
  7151. Random r (macAddresses[0] ^ macAddresses[1]
  7152. ^ Random::getSystemRandom().nextInt64());
  7153. for (int i = 4; --i >= 0;)
  7154. {
  7155. r.setSeedRandomly(); // calling this repeatedly improves randomness
  7156. value.asInt[i] ^= r.nextInt();
  7157. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  7158. }
  7159. }
  7160. Uuid::~Uuid() throw()
  7161. {
  7162. }
  7163. Uuid::Uuid (const Uuid& other)
  7164. : value (other.value)
  7165. {
  7166. }
  7167. Uuid& Uuid::operator= (const Uuid& other)
  7168. {
  7169. value = other.value;
  7170. return *this;
  7171. }
  7172. bool Uuid::operator== (const Uuid& other) const
  7173. {
  7174. return value.asInt64[0] == other.value.asInt64[0]
  7175. && value.asInt64[1] == other.value.asInt64[1];
  7176. }
  7177. bool Uuid::operator!= (const Uuid& other) const
  7178. {
  7179. return ! operator== (other);
  7180. }
  7181. bool Uuid::isNull() const throw()
  7182. {
  7183. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  7184. }
  7185. const String Uuid::toString() const
  7186. {
  7187. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  7188. }
  7189. Uuid::Uuid (const String& uuidString)
  7190. {
  7191. operator= (uuidString);
  7192. }
  7193. Uuid& Uuid::operator= (const String& uuidString)
  7194. {
  7195. MemoryBlock mb;
  7196. mb.loadFromHexString (uuidString);
  7197. mb.ensureSize (sizeof (value.asBytes), true);
  7198. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  7199. return *this;
  7200. }
  7201. Uuid::Uuid (const uint8* const rawData)
  7202. {
  7203. operator= (rawData);
  7204. }
  7205. Uuid& Uuid::operator= (const uint8* const rawData)
  7206. {
  7207. if (rawData != 0)
  7208. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  7209. else
  7210. zeromem (value.asBytes, sizeof (value.asBytes));
  7211. return *this;
  7212. }
  7213. END_JUCE_NAMESPACE
  7214. /*** End of inlined file: juce_Uuid.cpp ***/
  7215. /*** Start of inlined file: juce_ZipFile.cpp ***/
  7216. BEGIN_JUCE_NAMESPACE
  7217. class ZipFile::ZipEntryInfo
  7218. {
  7219. public:
  7220. ZipFile::ZipEntry entry;
  7221. int streamOffset;
  7222. int compressedSize;
  7223. bool compressed;
  7224. };
  7225. class ZipFile::ZipInputStream : public InputStream
  7226. {
  7227. public:
  7228. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  7229. : file (file_),
  7230. zipEntryInfo (zei),
  7231. pos (0),
  7232. headerSize (0),
  7233. inputStream (0)
  7234. {
  7235. inputStream = file_.inputStream;
  7236. if (file_.inputSource != 0)
  7237. {
  7238. inputStream = file.inputSource->createInputStream();
  7239. }
  7240. else
  7241. {
  7242. #if JUCE_DEBUG
  7243. file_.numOpenStreams++;
  7244. #endif
  7245. }
  7246. char buffer [30];
  7247. if (inputStream != 0
  7248. && inputStream->setPosition (zei.streamOffset)
  7249. && inputStream->read (buffer, 30) == 30
  7250. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  7251. {
  7252. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  7253. + ByteOrder::littleEndianShort (buffer + 28);
  7254. }
  7255. }
  7256. ~ZipInputStream() throw()
  7257. {
  7258. #if JUCE_DEBUG
  7259. if (inputStream != 0 && inputStream == file.inputStream)
  7260. file.numOpenStreams--;
  7261. #endif
  7262. if (inputStream != file.inputStream)
  7263. delete inputStream;
  7264. }
  7265. int64 getTotalLength() throw()
  7266. {
  7267. return zipEntryInfo.compressedSize;
  7268. }
  7269. int read (void* buffer, int howMany) throw()
  7270. {
  7271. if (headerSize <= 0)
  7272. return 0;
  7273. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  7274. if (inputStream == 0)
  7275. return 0;
  7276. int num;
  7277. if (inputStream == file.inputStream)
  7278. {
  7279. const ScopedLock sl (file.lock);
  7280. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7281. num = inputStream->read (buffer, howMany);
  7282. }
  7283. else
  7284. {
  7285. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7286. num = inputStream->read (buffer, howMany);
  7287. }
  7288. pos += num;
  7289. return num;
  7290. }
  7291. bool isExhausted() throw()
  7292. {
  7293. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  7294. }
  7295. int64 getPosition() throw()
  7296. {
  7297. return pos;
  7298. }
  7299. bool setPosition (int64 newPos) throw()
  7300. {
  7301. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  7302. return true;
  7303. }
  7304. private:
  7305. ZipFile& file;
  7306. ZipEntryInfo zipEntryInfo;
  7307. int64 pos;
  7308. int headerSize;
  7309. InputStream* inputStream;
  7310. ZipInputStream (const ZipInputStream&);
  7311. ZipInputStream& operator= (const ZipInputStream&);
  7312. };
  7313. ZipFile::ZipFile (InputStream* const source_,
  7314. const bool deleteStreamWhenDestroyed) throw()
  7315. : inputStream (source_)
  7316. #if JUCE_DEBUG
  7317. , numOpenStreams (0)
  7318. #endif
  7319. {
  7320. if (deleteStreamWhenDestroyed)
  7321. streamToDelete = inputStream;
  7322. init();
  7323. }
  7324. ZipFile::ZipFile (const File& file)
  7325. : inputStream (0)
  7326. #if JUCE_DEBUG
  7327. , numOpenStreams (0)
  7328. #endif
  7329. {
  7330. inputSource = new FileInputSource (file);
  7331. init();
  7332. }
  7333. ZipFile::ZipFile (InputSource* const inputSource_)
  7334. : inputStream (0),
  7335. inputSource (inputSource_)
  7336. #if JUCE_DEBUG
  7337. , numOpenStreams (0)
  7338. #endif
  7339. {
  7340. init();
  7341. }
  7342. ZipFile::~ZipFile() throw()
  7343. {
  7344. #if JUCE_DEBUG
  7345. entries.clear();
  7346. // If you hit this assertion, it means you've created a stream to read
  7347. // one of the items in the zipfile, but you've forgotten to delete that
  7348. // stream object before deleting the file.. Streams can't be kept open
  7349. // after the file is deleted because they need to share the input
  7350. // stream that the file uses to read itself.
  7351. jassert (numOpenStreams == 0);
  7352. #endif
  7353. }
  7354. int ZipFile::getNumEntries() const throw()
  7355. {
  7356. return entries.size();
  7357. }
  7358. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  7359. {
  7360. ZipEntryInfo* const zei = entries [index];
  7361. return zei != 0 ? &(zei->entry) : 0;
  7362. }
  7363. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  7364. {
  7365. for (int i = 0; i < entries.size(); ++i)
  7366. if (entries.getUnchecked (i)->entry.filename == fileName)
  7367. return i;
  7368. return -1;
  7369. }
  7370. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  7371. {
  7372. return getEntry (getIndexOfFileName (fileName));
  7373. }
  7374. InputStream* ZipFile::createStreamForEntry (const int index)
  7375. {
  7376. ZipEntryInfo* const zei = entries[index];
  7377. InputStream* stream = 0;
  7378. if (zei != 0)
  7379. {
  7380. stream = new ZipInputStream (*this, *zei);
  7381. if (zei->compressed)
  7382. {
  7383. stream = new GZIPDecompressorInputStream (stream, true, true,
  7384. zei->entry.uncompressedSize);
  7385. // (much faster to unzip in big blocks using a buffer..)
  7386. stream = new BufferedInputStream (stream, 32768, true);
  7387. }
  7388. }
  7389. return stream;
  7390. }
  7391. class ZipFile::ZipFilenameComparator
  7392. {
  7393. public:
  7394. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  7395. {
  7396. return first->entry.filename.compare (second->entry.filename);
  7397. }
  7398. };
  7399. void ZipFile::sortEntriesByFilename()
  7400. {
  7401. ZipFilenameComparator sorter;
  7402. entries.sort (sorter);
  7403. }
  7404. void ZipFile::init()
  7405. {
  7406. ScopedPointer <InputStream> toDelete;
  7407. InputStream* in = inputStream;
  7408. if (inputSource != 0)
  7409. {
  7410. in = inputSource->createInputStream();
  7411. toDelete = in;
  7412. }
  7413. if (in != 0)
  7414. {
  7415. int numEntries = 0;
  7416. int pos = findEndOfZipEntryTable (in, numEntries);
  7417. if (pos >= 0 && pos < in->getTotalLength())
  7418. {
  7419. const int size = (int) (in->getTotalLength() - pos);
  7420. in->setPosition (pos);
  7421. MemoryBlock headerData;
  7422. if (in->readIntoMemoryBlock (headerData, size) == size)
  7423. {
  7424. pos = 0;
  7425. for (int i = 0; i < numEntries; ++i)
  7426. {
  7427. if (pos + 46 > size)
  7428. break;
  7429. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  7430. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  7431. if (pos + 46 + fileNameLen > size)
  7432. break;
  7433. ZipEntryInfo* const zei = new ZipEntryInfo();
  7434. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  7435. const int time = ByteOrder::littleEndianShort (buffer + 12);
  7436. const int date = ByteOrder::littleEndianShort (buffer + 14);
  7437. const int year = 1980 + (date >> 9);
  7438. const int month = ((date >> 5) & 15) - 1;
  7439. const int day = date & 31;
  7440. const int hours = time >> 11;
  7441. const int minutes = (time >> 5) & 63;
  7442. const int seconds = (time & 31) << 1;
  7443. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  7444. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  7445. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  7446. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  7447. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  7448. entries.add (zei);
  7449. pos += 46 + fileNameLen
  7450. + ByteOrder::littleEndianShort (buffer + 30)
  7451. + ByteOrder::littleEndianShort (buffer + 32);
  7452. }
  7453. }
  7454. }
  7455. }
  7456. }
  7457. int ZipFile::findEndOfZipEntryTable (InputStream* input, int& numEntries)
  7458. {
  7459. BufferedInputStream in (input, 8192, false);
  7460. in.setPosition (in.getTotalLength());
  7461. int64 pos = in.getPosition();
  7462. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  7463. char buffer [32];
  7464. zeromem (buffer, sizeof (buffer));
  7465. while (pos > lowestPos)
  7466. {
  7467. in.setPosition (pos - 22);
  7468. pos = in.getPosition();
  7469. memcpy (buffer + 22, buffer, 4);
  7470. if (in.read (buffer, 22) != 22)
  7471. return 0;
  7472. for (int i = 0; i < 22; ++i)
  7473. {
  7474. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  7475. {
  7476. in.setPosition (pos + i);
  7477. in.read (buffer, 22);
  7478. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  7479. return ByteOrder::littleEndianInt (buffer + 16);
  7480. }
  7481. }
  7482. }
  7483. return 0;
  7484. }
  7485. void ZipFile::uncompressTo (const File& targetDirectory,
  7486. const bool shouldOverwriteFiles)
  7487. {
  7488. for (int i = 0; i < entries.size(); ++i)
  7489. {
  7490. const ZipEntry& zei = entries.getUnchecked(i)->entry;
  7491. const File targetFile (targetDirectory.getChildFile (zei.filename));
  7492. if (zei.filename.endsWithChar ('/'))
  7493. {
  7494. targetFile.createDirectory(); // (entry is a directory, not a file)
  7495. }
  7496. else
  7497. {
  7498. ScopedPointer <InputStream> in (createStreamForEntry (i));
  7499. if (in != 0)
  7500. {
  7501. if (shouldOverwriteFiles)
  7502. targetFile.deleteFile();
  7503. if ((! targetFile.exists())
  7504. && targetFile.getParentDirectory().createDirectory())
  7505. {
  7506. ScopedPointer <FileOutputStream> out (targetFile.createOutputStream());
  7507. if (out != 0)
  7508. {
  7509. out->writeFromInputStream (*in, -1);
  7510. out = 0;
  7511. targetFile.setCreationTime (zei.fileTime);
  7512. targetFile.setLastModificationTime (zei.fileTime);
  7513. targetFile.setLastAccessTime (zei.fileTime);
  7514. }
  7515. }
  7516. }
  7517. }
  7518. }
  7519. }
  7520. END_JUCE_NAMESPACE
  7521. /*** End of inlined file: juce_ZipFile.cpp ***/
  7522. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  7523. #if JUCE_MSVC
  7524. #pragma warning (push)
  7525. #pragma warning (disable: 4514 4996)
  7526. #endif
  7527. #include <cwctype>
  7528. #include <cctype>
  7529. #include <ctime>
  7530. BEGIN_JUCE_NAMESPACE
  7531. int CharacterFunctions::length (const char* const s) throw()
  7532. {
  7533. return (int) strlen (s);
  7534. }
  7535. int CharacterFunctions::length (const juce_wchar* const s) throw()
  7536. {
  7537. return (int) wcslen (s);
  7538. }
  7539. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  7540. {
  7541. strncpy (dest, src, maxChars);
  7542. }
  7543. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  7544. {
  7545. wcsncpy (dest, src, maxChars);
  7546. }
  7547. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  7548. {
  7549. mbstowcs (dest, src, maxChars);
  7550. }
  7551. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  7552. {
  7553. wcstombs (dest, src, maxChars);
  7554. }
  7555. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  7556. {
  7557. return (int) wcstombs (0, src, 0);
  7558. }
  7559. void CharacterFunctions::append (char* dest, const char* src) throw()
  7560. {
  7561. strcat (dest, src);
  7562. }
  7563. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  7564. {
  7565. wcscat (dest, src);
  7566. }
  7567. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  7568. {
  7569. return strcmp (s1, s2);
  7570. }
  7571. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  7572. {
  7573. jassert (s1 != 0 && s2 != 0);
  7574. return wcscmp (s1, s2);
  7575. }
  7576. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  7577. {
  7578. jassert (s1 != 0 && s2 != 0);
  7579. return strncmp (s1, s2, maxChars);
  7580. }
  7581. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7582. {
  7583. jassert (s1 != 0 && s2 != 0);
  7584. return wcsncmp (s1, s2, maxChars);
  7585. }
  7586. int CharacterFunctions::compare (const juce_wchar* s1, const char* s2) throw()
  7587. {
  7588. jassert (s1 != 0 && s2 != 0);
  7589. for (;;)
  7590. {
  7591. const int diff = (int) (*s1 - (juce_wchar) (unsigned char) *s2);
  7592. if (diff != 0)
  7593. return diff;
  7594. else if (*s1 == 0)
  7595. break;
  7596. ++s1;
  7597. ++s2;
  7598. }
  7599. return 0;
  7600. }
  7601. int CharacterFunctions::compare (const char* s1, const juce_wchar* s2) throw()
  7602. {
  7603. return -compare (s2, s1);
  7604. }
  7605. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  7606. {
  7607. jassert (s1 != 0 && s2 != 0);
  7608. #if JUCE_WIN32
  7609. return stricmp (s1, s2);
  7610. #else
  7611. return strcasecmp (s1, s2);
  7612. #endif
  7613. }
  7614. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  7615. {
  7616. jassert (s1 != 0 && s2 != 0);
  7617. #if JUCE_WIN32
  7618. return _wcsicmp (s1, s2);
  7619. #else
  7620. for (;;)
  7621. {
  7622. if (*s1 != *s2)
  7623. {
  7624. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7625. if (diff != 0)
  7626. return diff < 0 ? -1 : 1;
  7627. }
  7628. else if (*s1 == 0)
  7629. break;
  7630. ++s1;
  7631. ++s2;
  7632. }
  7633. return 0;
  7634. #endif
  7635. }
  7636. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const char* s2) throw()
  7637. {
  7638. jassert (s1 != 0 && s2 != 0);
  7639. for (;;)
  7640. {
  7641. if (*s1 != *s2)
  7642. {
  7643. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7644. if (diff != 0)
  7645. return diff < 0 ? -1 : 1;
  7646. }
  7647. else if (*s1 == 0)
  7648. break;
  7649. ++s1;
  7650. ++s2;
  7651. }
  7652. return 0;
  7653. }
  7654. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  7655. {
  7656. jassert (s1 != 0 && s2 != 0);
  7657. #if JUCE_WIN32
  7658. return strnicmp (s1, s2, maxChars);
  7659. #else
  7660. return strncasecmp (s1, s2, maxChars);
  7661. #endif
  7662. }
  7663. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7664. {
  7665. jassert (s1 != 0 && s2 != 0);
  7666. #if JUCE_WIN32
  7667. return _wcsnicmp (s1, s2, maxChars);
  7668. #else
  7669. while (--maxChars >= 0)
  7670. {
  7671. if (*s1 != *s2)
  7672. {
  7673. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7674. if (diff != 0)
  7675. return diff < 0 ? -1 : 1;
  7676. }
  7677. else if (*s1 == 0)
  7678. break;
  7679. ++s1;
  7680. ++s2;
  7681. }
  7682. return 0;
  7683. #endif
  7684. }
  7685. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  7686. {
  7687. return strstr (haystack, needle);
  7688. }
  7689. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  7690. {
  7691. return wcsstr (haystack, needle);
  7692. }
  7693. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  7694. {
  7695. if (haystack != 0)
  7696. {
  7697. int i = 0;
  7698. if (ignoreCase)
  7699. {
  7700. const char n1 = toLowerCase (needle);
  7701. const char n2 = toUpperCase (needle);
  7702. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7703. {
  7704. while (haystack[i] != 0)
  7705. {
  7706. if (haystack[i] == n1 || haystack[i] == n2)
  7707. return i;
  7708. ++i;
  7709. }
  7710. return -1;
  7711. }
  7712. jassert (n1 == needle);
  7713. }
  7714. while (haystack[i] != 0)
  7715. {
  7716. if (haystack[i] == needle)
  7717. return i;
  7718. ++i;
  7719. }
  7720. }
  7721. return -1;
  7722. }
  7723. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  7724. {
  7725. if (haystack != 0)
  7726. {
  7727. int i = 0;
  7728. if (ignoreCase)
  7729. {
  7730. const juce_wchar n1 = toLowerCase (needle);
  7731. const juce_wchar n2 = toUpperCase (needle);
  7732. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7733. {
  7734. while (haystack[i] != 0)
  7735. {
  7736. if (haystack[i] == n1 || haystack[i] == n2)
  7737. return i;
  7738. ++i;
  7739. }
  7740. return -1;
  7741. }
  7742. jassert (n1 == needle);
  7743. }
  7744. while (haystack[i] != 0)
  7745. {
  7746. if (haystack[i] == needle)
  7747. return i;
  7748. ++i;
  7749. }
  7750. }
  7751. return -1;
  7752. }
  7753. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  7754. {
  7755. jassert (haystack != 0);
  7756. int i = 0;
  7757. while (haystack[i] != 0)
  7758. {
  7759. if (haystack[i] == needle)
  7760. return i;
  7761. ++i;
  7762. }
  7763. return -1;
  7764. }
  7765. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  7766. {
  7767. jassert (haystack != 0);
  7768. int i = 0;
  7769. while (haystack[i] != 0)
  7770. {
  7771. if (haystack[i] == needle)
  7772. return i;
  7773. ++i;
  7774. }
  7775. return -1;
  7776. }
  7777. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  7778. {
  7779. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  7780. }
  7781. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  7782. {
  7783. if (allowedChars == 0)
  7784. return 0;
  7785. int i = 0;
  7786. for (;;)
  7787. {
  7788. if (indexOfCharFast (allowedChars, text[i]) < 0)
  7789. break;
  7790. ++i;
  7791. }
  7792. return i;
  7793. }
  7794. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  7795. {
  7796. return (int) strftime (dest, maxChars, format, tm);
  7797. }
  7798. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  7799. {
  7800. return (int) wcsftime (dest, maxChars, format, tm);
  7801. }
  7802. int CharacterFunctions::getIntValue (const char* const s) throw()
  7803. {
  7804. return atoi (s);
  7805. }
  7806. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  7807. {
  7808. #if JUCE_WIN32
  7809. return _wtoi (s);
  7810. #else
  7811. int v = 0;
  7812. while (isWhitespace (*s))
  7813. ++s;
  7814. const bool isNeg = *s == '-';
  7815. if (isNeg)
  7816. ++s;
  7817. for (;;)
  7818. {
  7819. const wchar_t c = *s++;
  7820. if (c >= '0' && c <= '9')
  7821. v = v * 10 + (int) (c - '0');
  7822. else
  7823. break;
  7824. }
  7825. return isNeg ? -v : v;
  7826. #endif
  7827. }
  7828. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  7829. {
  7830. #if JUCE_LINUX
  7831. return atoll (s);
  7832. #elif defined (JUCE_WIN32)
  7833. return _atoi64 (s);
  7834. #else
  7835. int64 v = 0;
  7836. while (isWhitespace (*s))
  7837. ++s;
  7838. const bool isNeg = *s == '-';
  7839. if (isNeg)
  7840. ++s;
  7841. for (;;)
  7842. {
  7843. const char c = *s++;
  7844. if (c >= '0' && c <= '9')
  7845. v = v * 10 + (int64) (c - '0');
  7846. else
  7847. break;
  7848. }
  7849. return isNeg ? -v : v;
  7850. #endif
  7851. }
  7852. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  7853. {
  7854. #if JUCE_WIN32
  7855. return _wtoi64 (s);
  7856. #else
  7857. int64 v = 0;
  7858. while (isWhitespace (*s))
  7859. ++s;
  7860. const bool isNeg = *s == '-';
  7861. if (isNeg)
  7862. ++s;
  7863. for (;;)
  7864. {
  7865. const juce_wchar c = *s++;
  7866. if (c >= '0' && c <= '9')
  7867. v = v * 10 + (int64) (c - '0');
  7868. else
  7869. break;
  7870. }
  7871. return isNeg ? -v : v;
  7872. #endif
  7873. }
  7874. static double juce_mulexp10 (const double value, int exponent) throw()
  7875. {
  7876. if (exponent == 0)
  7877. return value;
  7878. if (value == 0)
  7879. return 0;
  7880. const bool negative = (exponent < 0);
  7881. if (negative)
  7882. exponent = -exponent;
  7883. double result = 1.0, power = 10.0;
  7884. for (int bit = 1; exponent != 0; bit <<= 1)
  7885. {
  7886. if ((exponent & bit) != 0)
  7887. {
  7888. exponent ^= bit;
  7889. result *= power;
  7890. if (exponent == 0)
  7891. break;
  7892. }
  7893. power *= power;
  7894. }
  7895. return negative ? (value / result) : (value * result);
  7896. }
  7897. template <class CharType>
  7898. double juce_atof (const CharType* const original) throw()
  7899. {
  7900. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  7901. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  7902. int exponent = 0, decPointIndex = 0, digit = 0;
  7903. int lastDigit = 0, numSignificantDigits = 0;
  7904. bool isNegative = false, digitsFound = false;
  7905. const int maxSignificantDigits = 15 + 2;
  7906. const CharType* s = original;
  7907. while (CharacterFunctions::isWhitespace (*s))
  7908. ++s;
  7909. switch (*s)
  7910. {
  7911. case '-': isNegative = true; // fall-through..
  7912. case '+': ++s;
  7913. }
  7914. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  7915. return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF
  7916. for (;;)
  7917. {
  7918. if (CharacterFunctions::isDigit (*s))
  7919. {
  7920. lastDigit = digit;
  7921. digit = *s++ - '0';
  7922. digitsFound = true;
  7923. if (decPointIndex != 0)
  7924. exponentAdjustment[1]++;
  7925. if (numSignificantDigits == 0 && digit == 0)
  7926. continue;
  7927. if (++numSignificantDigits > maxSignificantDigits)
  7928. {
  7929. if (digit > 5)
  7930. ++accumulator [decPointIndex];
  7931. else if (digit == 5 && (lastDigit & 1) != 0)
  7932. ++accumulator [decPointIndex];
  7933. if (decPointIndex > 0)
  7934. exponentAdjustment[1]--;
  7935. else
  7936. exponentAdjustment[0]++;
  7937. while (CharacterFunctions::isDigit (*s))
  7938. {
  7939. ++s;
  7940. if (decPointIndex == 0)
  7941. exponentAdjustment[0]++;
  7942. }
  7943. }
  7944. else
  7945. {
  7946. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  7947. if (accumulator [decPointIndex] > maxAccumulatorValue)
  7948. {
  7949. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  7950. + accumulator [decPointIndex];
  7951. accumulator [decPointIndex] = 0;
  7952. exponentAccumulator [decPointIndex] = 0;
  7953. }
  7954. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  7955. exponentAccumulator [decPointIndex]++;
  7956. }
  7957. }
  7958. else if (decPointIndex == 0 && *s == '.')
  7959. {
  7960. ++s;
  7961. decPointIndex = 1;
  7962. if (numSignificantDigits > maxSignificantDigits)
  7963. {
  7964. while (CharacterFunctions::isDigit (*s))
  7965. ++s;
  7966. break;
  7967. }
  7968. }
  7969. else
  7970. {
  7971. break;
  7972. }
  7973. }
  7974. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  7975. if (decPointIndex != 0)
  7976. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  7977. if ((*s == 'e' || *s == 'E') && digitsFound)
  7978. {
  7979. bool negativeExponent = false;
  7980. switch (*++s)
  7981. {
  7982. case '-': negativeExponent = true; // fall-through..
  7983. case '+': ++s;
  7984. }
  7985. while (CharacterFunctions::isDigit (*s))
  7986. exponent = (exponent * 10) + (*s++ - '0');
  7987. if (negativeExponent)
  7988. exponent = -exponent;
  7989. }
  7990. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  7991. if (decPointIndex != 0)
  7992. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  7993. return isNegative ? -r : r;
  7994. }
  7995. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  7996. {
  7997. return juce_atof <char> (s);
  7998. }
  7999. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  8000. {
  8001. return juce_atof <juce_wchar> (s);
  8002. }
  8003. char CharacterFunctions::toUpperCase (const char character) throw()
  8004. {
  8005. return (char) toupper (character);
  8006. }
  8007. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  8008. {
  8009. return towupper (character);
  8010. }
  8011. void CharacterFunctions::toUpperCase (char* s) throw()
  8012. {
  8013. #if JUCE_WIN32
  8014. strupr (s);
  8015. #else
  8016. while (*s != 0)
  8017. {
  8018. *s = toUpperCase (*s);
  8019. ++s;
  8020. }
  8021. #endif
  8022. }
  8023. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  8024. {
  8025. #if JUCE_WIN32
  8026. _wcsupr (s);
  8027. #else
  8028. while (*s != 0)
  8029. {
  8030. *s = toUpperCase (*s);
  8031. ++s;
  8032. }
  8033. #endif
  8034. }
  8035. bool CharacterFunctions::isUpperCase (const char character) throw()
  8036. {
  8037. return isupper (character) != 0;
  8038. }
  8039. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  8040. {
  8041. #if JUCE_WIN32
  8042. return iswupper (character) != 0;
  8043. #else
  8044. return toLowerCase (character) != character;
  8045. #endif
  8046. }
  8047. char CharacterFunctions::toLowerCase (const char character) throw()
  8048. {
  8049. return (char) tolower (character);
  8050. }
  8051. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  8052. {
  8053. return towlower (character);
  8054. }
  8055. void CharacterFunctions::toLowerCase (char* s) throw()
  8056. {
  8057. #if JUCE_WIN32
  8058. strlwr (s);
  8059. #else
  8060. while (*s != 0)
  8061. {
  8062. *s = toLowerCase (*s);
  8063. ++s;
  8064. }
  8065. #endif
  8066. }
  8067. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  8068. {
  8069. #if JUCE_WIN32
  8070. _wcslwr (s);
  8071. #else
  8072. while (*s != 0)
  8073. {
  8074. *s = toLowerCase (*s);
  8075. ++s;
  8076. }
  8077. #endif
  8078. }
  8079. bool CharacterFunctions::isLowerCase (const char character) throw()
  8080. {
  8081. return islower (character) != 0;
  8082. }
  8083. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  8084. {
  8085. #if JUCE_WIN32
  8086. return iswlower (character) != 0;
  8087. #else
  8088. return toUpperCase (character) != character;
  8089. #endif
  8090. }
  8091. bool CharacterFunctions::isWhitespace (const char character) throw()
  8092. {
  8093. return character == ' ' || (character <= 13 && character >= 9);
  8094. }
  8095. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  8096. {
  8097. return iswspace (character) != 0;
  8098. }
  8099. bool CharacterFunctions::isDigit (const char character) throw()
  8100. {
  8101. return (character >= '0' && character <= '9');
  8102. }
  8103. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  8104. {
  8105. return iswdigit (character) != 0;
  8106. }
  8107. bool CharacterFunctions::isLetter (const char character) throw()
  8108. {
  8109. return (character >= 'a' && character <= 'z')
  8110. || (character >= 'A' && character <= 'Z');
  8111. }
  8112. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  8113. {
  8114. return iswalpha (character) != 0;
  8115. }
  8116. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  8117. {
  8118. return (character >= 'a' && character <= 'z')
  8119. || (character >= 'A' && character <= 'Z')
  8120. || (character >= '0' && character <= '9');
  8121. }
  8122. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  8123. {
  8124. return iswalnum (character) != 0;
  8125. }
  8126. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  8127. {
  8128. if (digit >= '0' && digit <= '9')
  8129. return digit - '0';
  8130. else if (digit >= 'a' && digit <= 'f')
  8131. return digit - ('a' - 10);
  8132. else if (digit >= 'A' && digit <= 'F')
  8133. return digit - ('A' - 10);
  8134. return -1;
  8135. }
  8136. #if JUCE_MSVC
  8137. #pragma warning (pop)
  8138. #endif
  8139. END_JUCE_NAMESPACE
  8140. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  8141. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  8142. BEGIN_JUCE_NAMESPACE
  8143. LocalisedStrings::LocalisedStrings (const String& fileContents)
  8144. {
  8145. loadFromText (fileContents);
  8146. }
  8147. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  8148. {
  8149. loadFromText (fileToLoad.loadFileAsString());
  8150. }
  8151. LocalisedStrings::~LocalisedStrings()
  8152. {
  8153. }
  8154. const String LocalisedStrings::translate (const String& text) const
  8155. {
  8156. return translations.getValue (text, text);
  8157. }
  8158. static int findCloseQuote (const String& text, int startPos)
  8159. {
  8160. juce_wchar lastChar = 0;
  8161. for (;;)
  8162. {
  8163. const juce_wchar c = text [startPos];
  8164. if (c == 0 || (c == '"' && lastChar != '\\'))
  8165. break;
  8166. lastChar = c;
  8167. ++startPos;
  8168. }
  8169. return startPos;
  8170. }
  8171. static const String unescapeString (const String& s)
  8172. {
  8173. return s.replace ("\\\"", "\"")
  8174. .replace ("\\\'", "\'")
  8175. .replace ("\\t", "\t")
  8176. .replace ("\\r", "\r")
  8177. .replace ("\\n", "\n");
  8178. }
  8179. void LocalisedStrings::loadFromText (const String& fileContents)
  8180. {
  8181. StringArray lines;
  8182. lines.addLines (fileContents);
  8183. for (int i = 0; i < lines.size(); ++i)
  8184. {
  8185. String line (lines[i].trim());
  8186. if (line.startsWithChar ('"'))
  8187. {
  8188. int closeQuote = findCloseQuote (line, 1);
  8189. const String originalText (unescapeString (line.substring (1, closeQuote)));
  8190. if (originalText.isNotEmpty())
  8191. {
  8192. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  8193. closeQuote = findCloseQuote (line, openingQuote + 1);
  8194. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  8195. if (newText.isNotEmpty())
  8196. translations.set (originalText, newText);
  8197. }
  8198. }
  8199. else if (line.startsWithIgnoreCase ("language:"))
  8200. {
  8201. languageName = line.substring (9).trim();
  8202. }
  8203. else if (line.startsWithIgnoreCase ("countries:"))
  8204. {
  8205. countryCodes.addTokens (line.substring (10).trim(), true);
  8206. countryCodes.trim();
  8207. countryCodes.removeEmptyStrings();
  8208. }
  8209. }
  8210. }
  8211. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  8212. {
  8213. translations.setIgnoresCase (shouldIgnoreCase);
  8214. }
  8215. static CriticalSection currentMappingsLock;
  8216. static LocalisedStrings* currentMappings = 0;
  8217. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  8218. {
  8219. const ScopedLock sl (currentMappingsLock);
  8220. delete currentMappings;
  8221. currentMappings = newTranslations;
  8222. }
  8223. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  8224. {
  8225. return currentMappings;
  8226. }
  8227. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  8228. {
  8229. const ScopedLock sl (currentMappingsLock);
  8230. if (currentMappings != 0)
  8231. return currentMappings->translate (text);
  8232. return text;
  8233. }
  8234. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  8235. {
  8236. return translateWithCurrentMappings (String (text));
  8237. }
  8238. END_JUCE_NAMESPACE
  8239. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  8240. /*** Start of inlined file: juce_String.cpp ***/
  8241. #if JUCE_MSVC
  8242. #pragma warning (push)
  8243. #pragma warning (disable: 4514)
  8244. #endif
  8245. #include <locale>
  8246. BEGIN_JUCE_NAMESPACE
  8247. #if JUCE_MSVC
  8248. #pragma warning (pop)
  8249. #endif
  8250. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  8251. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  8252. #endif
  8253. class StringHolder
  8254. {
  8255. public:
  8256. StringHolder()
  8257. : refCount (0x3fffffff), allocatedNumChars (0)
  8258. {
  8259. text[0] = 0;
  8260. }
  8261. static juce_wchar* createUninitialised (const size_t numChars)
  8262. {
  8263. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  8264. s->refCount.value = 0;
  8265. s->allocatedNumChars = numChars;
  8266. return &(s->text[0]);
  8267. }
  8268. static juce_wchar* createCopy (const juce_wchar* const src, const size_t numChars)
  8269. {
  8270. juce_wchar* const dest = createUninitialised (numChars);
  8271. copyChars (dest, src, numChars);
  8272. return dest;
  8273. }
  8274. static juce_wchar* createCopy (const char* const src, const size_t numChars)
  8275. {
  8276. juce_wchar* const dest = createUninitialised (numChars);
  8277. CharacterFunctions::copy (dest, src, (int) numChars);
  8278. dest [numChars] = 0;
  8279. return dest;
  8280. }
  8281. static inline juce_wchar* getEmpty() throw()
  8282. {
  8283. return &(empty.text[0]);
  8284. }
  8285. static void retain (juce_wchar* const text) throw()
  8286. {
  8287. ++(bufferFromText (text)->refCount);
  8288. }
  8289. static inline void release (StringHolder* const b) throw()
  8290. {
  8291. if (--(b->refCount) == -1 && b != &empty)
  8292. delete[] reinterpret_cast <char*> (b);
  8293. }
  8294. static void release (juce_wchar* const text) throw()
  8295. {
  8296. release (bufferFromText (text));
  8297. }
  8298. static juce_wchar* makeUnique (juce_wchar* const text)
  8299. {
  8300. StringHolder* const b = bufferFromText (text);
  8301. if (b->refCount.get() <= 0)
  8302. return text;
  8303. juce_wchar* const newText = createCopy (text, b->allocatedNumChars);
  8304. release (b);
  8305. return newText;
  8306. }
  8307. static juce_wchar* makeUniqueWithSize (juce_wchar* const text, size_t numChars)
  8308. {
  8309. StringHolder* const b = bufferFromText (text);
  8310. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  8311. return text;
  8312. juce_wchar* const newText = createUninitialised (jmax (b->allocatedNumChars, numChars));
  8313. copyChars (newText, text, b->allocatedNumChars);
  8314. release (b);
  8315. return newText;
  8316. }
  8317. static size_t getAllocatedNumChars (juce_wchar* const text) throw()
  8318. {
  8319. return bufferFromText (text)->allocatedNumChars;
  8320. }
  8321. static void copyChars (juce_wchar* const dest, const juce_wchar* const src, const size_t numChars) throw()
  8322. {
  8323. memcpy (dest, src, numChars * sizeof (juce_wchar));
  8324. dest [numChars] = 0;
  8325. }
  8326. Atomic<int> refCount;
  8327. size_t allocatedNumChars;
  8328. juce_wchar text[1];
  8329. static StringHolder empty;
  8330. private:
  8331. static inline StringHolder* bufferFromText (void* const text) throw()
  8332. {
  8333. // (Can't use offsetof() here because of warnings about this not being a POD)
  8334. return reinterpret_cast <StringHolder*> (static_cast <char*> (text)
  8335. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  8336. }
  8337. };
  8338. StringHolder StringHolder::empty;
  8339. const String String::empty;
  8340. void String::createInternal (const juce_wchar* const t, const size_t numChars)
  8341. {
  8342. jassert (t[numChars] == 0); // must have a null terminator
  8343. text = StringHolder::createCopy (t, numChars);
  8344. }
  8345. void String::appendInternal (const juce_wchar* const newText, const int numExtraChars)
  8346. {
  8347. if (numExtraChars > 0)
  8348. {
  8349. const int oldLen = length();
  8350. const int newTotalLen = oldLen + numExtraChars;
  8351. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  8352. StringHolder::copyChars (text + oldLen, newText, numExtraChars);
  8353. }
  8354. }
  8355. void String::preallocateStorage (const size_t numChars)
  8356. {
  8357. text = StringHolder::makeUniqueWithSize (text, numChars);
  8358. }
  8359. String::String() throw()
  8360. : text (StringHolder::getEmpty())
  8361. {
  8362. }
  8363. String::~String() throw()
  8364. {
  8365. StringHolder::release (text);
  8366. }
  8367. String::String (const String& other) throw()
  8368. : text (other.text)
  8369. {
  8370. StringHolder::retain (text);
  8371. }
  8372. void String::swapWith (String& other) throw()
  8373. {
  8374. swapVariables (text, other.text);
  8375. }
  8376. String& String::operator= (const String& other) throw()
  8377. {
  8378. juce_wchar* const newText = other.text;
  8379. StringHolder::retain (newText);
  8380. StringHolder::release (reinterpret_cast <Atomic<juce_wchar*>*> (&text)->exchange (newText));
  8381. return *this;
  8382. }
  8383. String::String (const size_t numChars, const int /*dummyVariable*/)
  8384. : text (StringHolder::createUninitialised (numChars))
  8385. {
  8386. }
  8387. String::String (const String& stringToCopy, const size_t charsToAllocate)
  8388. {
  8389. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  8390. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  8391. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  8392. }
  8393. String::String (const char* const t)
  8394. {
  8395. if (t != 0 && *t != 0)
  8396. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  8397. else
  8398. text = StringHolder::getEmpty();
  8399. }
  8400. String::String (const juce_wchar* const t)
  8401. {
  8402. if (t != 0 && *t != 0)
  8403. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  8404. else
  8405. text = StringHolder::getEmpty();
  8406. }
  8407. String::String (const char* const t, const size_t maxChars)
  8408. {
  8409. int i;
  8410. for (i = 0; (size_t) i < maxChars; ++i)
  8411. if (t[i] == 0)
  8412. break;
  8413. if (i > 0)
  8414. text = StringHolder::createCopy (t, i);
  8415. else
  8416. text = StringHolder::getEmpty();
  8417. }
  8418. String::String (const juce_wchar* const t, const size_t maxChars)
  8419. {
  8420. int i;
  8421. for (i = 0; (size_t) i < maxChars; ++i)
  8422. if (t[i] == 0)
  8423. break;
  8424. if (i > 0)
  8425. text = StringHolder::createCopy (t, i);
  8426. else
  8427. text = StringHolder::getEmpty();
  8428. }
  8429. const String String::charToString (const juce_wchar character)
  8430. {
  8431. String result ((size_t) 1, (int) 0);
  8432. result.text[0] = character;
  8433. result.text[1] = 0;
  8434. return result;
  8435. }
  8436. namespace NumberToStringConverters
  8437. {
  8438. // pass in a pointer to the END of a buffer..
  8439. static juce_wchar* int64ToString (juce_wchar* t, const int64 n) throw()
  8440. {
  8441. *--t = 0;
  8442. int64 v = (n >= 0) ? n : -n;
  8443. do
  8444. {
  8445. *--t = (juce_wchar) ('0' + (int) (v % 10));
  8446. v /= 10;
  8447. } while (v > 0);
  8448. if (n < 0)
  8449. *--t = '-';
  8450. return t;
  8451. }
  8452. static juce_wchar* uint64ToString (juce_wchar* t, int64 v) throw()
  8453. {
  8454. *--t = 0;
  8455. do
  8456. {
  8457. *--t = (juce_wchar) ('0' + (int) (v % 10));
  8458. v /= 10;
  8459. } while (v > 0);
  8460. return t;
  8461. }
  8462. static juce_wchar* intToString (juce_wchar* t, const int n) throw()
  8463. {
  8464. if (n == (int) 0x80000000) // (would cause an overflow)
  8465. return int64ToString (t, n);
  8466. *--t = 0;
  8467. int v = abs (n);
  8468. do
  8469. {
  8470. *--t = (juce_wchar) ('0' + (v % 10));
  8471. v /= 10;
  8472. } while (v > 0);
  8473. if (n < 0)
  8474. *--t = '-';
  8475. return t;
  8476. }
  8477. static juce_wchar* uintToString (juce_wchar* t, unsigned int v) throw()
  8478. {
  8479. *--t = 0;
  8480. do
  8481. {
  8482. *--t = (juce_wchar) ('0' + (v % 10));
  8483. v /= 10;
  8484. } while (v > 0);
  8485. return t;
  8486. }
  8487. static juce_wchar getDecimalPoint()
  8488. {
  8489. #if JUCE_WINDOWS && _MSC_VER < 1400
  8490. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  8491. #else
  8492. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  8493. #endif
  8494. return dp;
  8495. }
  8496. static juce_wchar* doubleToString (juce_wchar* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  8497. {
  8498. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  8499. {
  8500. juce_wchar* const end = buffer + numChars;
  8501. juce_wchar* t = end;
  8502. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  8503. *--t = (juce_wchar) 0;
  8504. while (numDecPlaces >= 0 || v > 0)
  8505. {
  8506. if (numDecPlaces == 0)
  8507. *--t = getDecimalPoint();
  8508. *--t = (juce_wchar) ('0' + (v % 10));
  8509. v /= 10;
  8510. --numDecPlaces;
  8511. }
  8512. if (n < 0)
  8513. *--t = '-';
  8514. len = end - t - 1;
  8515. return t;
  8516. }
  8517. else
  8518. {
  8519. #if JUCE_WIN32
  8520. #if _MSC_VER <= 1400
  8521. len = _snwprintf (buffer, numChars, L"%.9g", n);
  8522. #else
  8523. len = _snwprintf_s (buffer, numChars, _TRUNCATE, L"%.9g", n);
  8524. #endif
  8525. #else
  8526. len = swprintf (buffer, numChars, L"%.9g", n);
  8527. #endif
  8528. return buffer;
  8529. }
  8530. }
  8531. }
  8532. String::String (const int number)
  8533. {
  8534. juce_wchar buffer [16];
  8535. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8536. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  8537. createInternal (start, end - start - 1);
  8538. }
  8539. String::String (const unsigned int number)
  8540. {
  8541. juce_wchar buffer [16];
  8542. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8543. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  8544. createInternal (start, end - start - 1);
  8545. }
  8546. String::String (const short number)
  8547. {
  8548. juce_wchar buffer [16];
  8549. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8550. juce_wchar* const start = NumberToStringConverters::intToString (end, (int) number);
  8551. createInternal (start, end - start - 1);
  8552. }
  8553. String::String (const unsigned short number)
  8554. {
  8555. juce_wchar buffer [16];
  8556. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8557. juce_wchar* const start = NumberToStringConverters::uintToString (end, (unsigned int) number);
  8558. createInternal (start, end - start - 1);
  8559. }
  8560. String::String (const int64 number)
  8561. {
  8562. juce_wchar buffer [32];
  8563. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8564. juce_wchar* const start = NumberToStringConverters::int64ToString (end, number);
  8565. createInternal (start, end - start - 1);
  8566. }
  8567. String::String (const uint64 number)
  8568. {
  8569. juce_wchar buffer [32];
  8570. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8571. juce_wchar* const start = NumberToStringConverters::uint64ToString (end, number);
  8572. createInternal (start, end - start - 1);
  8573. }
  8574. String::String (const float number, const int numberOfDecimalPlaces)
  8575. {
  8576. juce_wchar buffer [48];
  8577. size_t len;
  8578. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  8579. createInternal (start, len);
  8580. }
  8581. String::String (const double number, const int numberOfDecimalPlaces)
  8582. {
  8583. juce_wchar buffer [48];
  8584. size_t len;
  8585. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), number, numberOfDecimalPlaces, len);
  8586. createInternal (start, len);
  8587. }
  8588. int String::length() const throw()
  8589. {
  8590. return CharacterFunctions::length (text);
  8591. }
  8592. int String::hashCode() const throw()
  8593. {
  8594. const juce_wchar* t = text;
  8595. int result = 0;
  8596. while (*t != (juce_wchar) 0)
  8597. result = 31 * result + *t++;
  8598. return result;
  8599. }
  8600. int64 String::hashCode64() const throw()
  8601. {
  8602. const juce_wchar* t = text;
  8603. int64 result = 0;
  8604. while (*t != (juce_wchar) 0)
  8605. result = 101 * result + *t++;
  8606. return result;
  8607. }
  8608. bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw()
  8609. {
  8610. return string1.compare (string2) == 0;
  8611. }
  8612. bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw()
  8613. {
  8614. return string1.compare (string2) == 0;
  8615. }
  8616. bool JUCE_CALLTYPE operator== (const String& string1, const juce_wchar* string2) throw()
  8617. {
  8618. return string1.compare (string2) == 0;
  8619. }
  8620. bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw()
  8621. {
  8622. return string1.compare (string2) != 0;
  8623. }
  8624. bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw()
  8625. {
  8626. return string1.compare (string2) != 0;
  8627. }
  8628. bool JUCE_CALLTYPE operator!= (const String& string1, const juce_wchar* string2) throw()
  8629. {
  8630. return string1.compare (string2) != 0;
  8631. }
  8632. bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw()
  8633. {
  8634. return string1.compare (string2) > 0;
  8635. }
  8636. bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw()
  8637. {
  8638. return string1.compare (string2) < 0;
  8639. }
  8640. bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw()
  8641. {
  8642. return string1.compare (string2) >= 0;
  8643. }
  8644. bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw()
  8645. {
  8646. return string1.compare (string2) <= 0;
  8647. }
  8648. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  8649. {
  8650. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  8651. : isEmpty();
  8652. }
  8653. bool String::equalsIgnoreCase (const char* t) const throw()
  8654. {
  8655. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  8656. : isEmpty();
  8657. }
  8658. bool String::equalsIgnoreCase (const String& other) const throw()
  8659. {
  8660. return text == other.text
  8661. || CharacterFunctions::compareIgnoreCase (text, other.text) == 0;
  8662. }
  8663. int String::compare (const String& other) const throw()
  8664. {
  8665. return (text == other.text) ? 0 : CharacterFunctions::compare (text, other.text);
  8666. }
  8667. int String::compare (const char* other) const throw()
  8668. {
  8669. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  8670. }
  8671. int String::compare (const juce_wchar* other) const throw()
  8672. {
  8673. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  8674. }
  8675. int String::compareIgnoreCase (const String& other) const throw()
  8676. {
  8677. return (text == other.text) ? 0 : CharacterFunctions::compareIgnoreCase (text, other.text);
  8678. }
  8679. int String::compareLexicographically (const String& other) const throw()
  8680. {
  8681. const juce_wchar* s1 = text;
  8682. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  8683. ++s1;
  8684. const juce_wchar* s2 = other.text;
  8685. while (*s2 != 0 && ! CharacterFunctions::isLetterOrDigit (*s2))
  8686. ++s2;
  8687. return CharacterFunctions::compareIgnoreCase (s1, s2);
  8688. }
  8689. String& String::operator+= (const juce_wchar* const t)
  8690. {
  8691. if (t != 0)
  8692. appendInternal (t, CharacterFunctions::length (t));
  8693. return *this;
  8694. }
  8695. String& String::operator+= (const String& other)
  8696. {
  8697. if (isEmpty())
  8698. operator= (other);
  8699. else
  8700. appendInternal (other.text, other.length());
  8701. return *this;
  8702. }
  8703. String& String::operator+= (const char ch)
  8704. {
  8705. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  8706. return operator+= (static_cast <const juce_wchar*> (asString));
  8707. }
  8708. String& String::operator+= (const juce_wchar ch)
  8709. {
  8710. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  8711. return operator+= (static_cast <const juce_wchar*> (asString));
  8712. }
  8713. String& String::operator+= (const int number)
  8714. {
  8715. juce_wchar buffer [16];
  8716. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8717. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  8718. appendInternal (start, (int) (end - start));
  8719. return *this;
  8720. }
  8721. String& String::operator+= (const unsigned int number)
  8722. {
  8723. juce_wchar buffer [16];
  8724. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8725. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  8726. appendInternal (start, (int) (end - start));
  8727. return *this;
  8728. }
  8729. void String::append (const juce_wchar* const other, const int howMany)
  8730. {
  8731. if (howMany > 0)
  8732. {
  8733. int i;
  8734. for (i = 0; i < howMany; ++i)
  8735. if (other[i] == 0)
  8736. break;
  8737. appendInternal (other, i);
  8738. }
  8739. }
  8740. const String JUCE_CALLTYPE operator+ (const char* const string1, const String& string2)
  8741. {
  8742. String s (string1);
  8743. return s += string2;
  8744. }
  8745. const String JUCE_CALLTYPE operator+ (const juce_wchar* const string1, const String& string2)
  8746. {
  8747. String s (string1);
  8748. return s += string2;
  8749. }
  8750. const String JUCE_CALLTYPE operator+ (const char string1, const String& string2)
  8751. {
  8752. return String::charToString (string1) + string2;
  8753. }
  8754. const String JUCE_CALLTYPE operator+ (const juce_wchar string1, const String& string2)
  8755. {
  8756. return String::charToString (string1) + string2;
  8757. }
  8758. const String JUCE_CALLTYPE operator+ (String string1, const String& string2)
  8759. {
  8760. return string1 += string2;
  8761. }
  8762. const String JUCE_CALLTYPE operator+ (String string1, const char* const string2)
  8763. {
  8764. return string1 += string2;
  8765. }
  8766. const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar* const string2)
  8767. {
  8768. return string1 += string2;
  8769. }
  8770. const String JUCE_CALLTYPE operator+ (String string1, const char string2)
  8771. {
  8772. return string1 += string2;
  8773. }
  8774. const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar string2)
  8775. {
  8776. return string1 += string2;
  8777. }
  8778. String& JUCE_CALLTYPE operator<< (String& string1, const char characterToAppend)
  8779. {
  8780. return string1 += characterToAppend;
  8781. }
  8782. String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar characterToAppend)
  8783. {
  8784. return string1 += characterToAppend;
  8785. }
  8786. String& JUCE_CALLTYPE operator<< (String& string1, const char* const string2)
  8787. {
  8788. return string1 += string2;
  8789. }
  8790. String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar* const string2)
  8791. {
  8792. return string1 += string2;
  8793. }
  8794. String& JUCE_CALLTYPE operator<< (String& string1, const String& string2)
  8795. {
  8796. return string1 += string2;
  8797. }
  8798. String& JUCE_CALLTYPE operator<< (String& string1, const short number)
  8799. {
  8800. return string1 += (int) number;
  8801. }
  8802. String& JUCE_CALLTYPE operator<< (String& string1, const int number)
  8803. {
  8804. return string1 += number;
  8805. }
  8806. String& JUCE_CALLTYPE operator<< (String& string1, const unsigned int number)
  8807. {
  8808. return string1 += number;
  8809. }
  8810. String& JUCE_CALLTYPE operator<< (String& string1, const long number)
  8811. {
  8812. return string1 += (int) number;
  8813. }
  8814. String& JUCE_CALLTYPE operator<< (String& string1, const unsigned long number)
  8815. {
  8816. return string1 += (unsigned int) number;
  8817. }
  8818. String& JUCE_CALLTYPE operator<< (String& string1, const float number)
  8819. {
  8820. return string1 += String (number);
  8821. }
  8822. String& JUCE_CALLTYPE operator<< (String& string1, const double number)
  8823. {
  8824. return string1 += String (number);
  8825. }
  8826. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text)
  8827. {
  8828. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  8829. // if lots of large, persistent strings were to be written to streams).
  8830. const int numBytes = text.getNumBytesAsUTF8();
  8831. HeapBlock<char> temp (numBytes + 1);
  8832. text.copyToUTF8 (temp, numBytes + 1);
  8833. stream.write (temp, numBytes);
  8834. return stream;
  8835. }
  8836. int String::indexOfChar (const juce_wchar character) const throw()
  8837. {
  8838. const juce_wchar* t = text;
  8839. for (;;)
  8840. {
  8841. if (*t == character)
  8842. return (int) (t - text);
  8843. if (*t++ == 0)
  8844. return -1;
  8845. }
  8846. }
  8847. int String::lastIndexOfChar (const juce_wchar character) const throw()
  8848. {
  8849. for (int i = length(); --i >= 0;)
  8850. if (text[i] == character)
  8851. return i;
  8852. return -1;
  8853. }
  8854. int String::indexOf (const String& t) const throw()
  8855. {
  8856. const juce_wchar* const r = CharacterFunctions::find (text, t.text);
  8857. return r == 0 ? -1 : (int) (r - text);
  8858. }
  8859. int String::indexOfChar (const int startIndex,
  8860. const juce_wchar character) const throw()
  8861. {
  8862. if (startIndex > 0 && startIndex >= length())
  8863. return -1;
  8864. const juce_wchar* t = text + jmax (0, startIndex);
  8865. for (;;)
  8866. {
  8867. if (*t == character)
  8868. return (int) (t - text);
  8869. if (*t == 0)
  8870. return -1;
  8871. ++t;
  8872. }
  8873. }
  8874. int String::indexOfAnyOf (const String& charactersToLookFor,
  8875. const int startIndex,
  8876. const bool ignoreCase) const throw()
  8877. {
  8878. if (startIndex > 0 && startIndex >= length())
  8879. return -1;
  8880. const juce_wchar* t = text + jmax (0, startIndex);
  8881. while (*t != 0)
  8882. {
  8883. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, *t, ignoreCase) >= 0)
  8884. return (int) (t - text);
  8885. ++t;
  8886. }
  8887. return -1;
  8888. }
  8889. int String::indexOf (const int startIndex, const String& other) const throw()
  8890. {
  8891. if (startIndex > 0 && startIndex >= length())
  8892. return -1;
  8893. const juce_wchar* const found = CharacterFunctions::find (text + jmax (0, startIndex), other.text);
  8894. return found == 0 ? -1 : (int) (found - text);
  8895. }
  8896. int String::indexOfIgnoreCase (const String& other) const throw()
  8897. {
  8898. if (other.isNotEmpty())
  8899. {
  8900. const int len = other.length();
  8901. const int end = length() - len;
  8902. for (int i = 0; i <= end; ++i)
  8903. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  8904. return i;
  8905. }
  8906. return -1;
  8907. }
  8908. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  8909. {
  8910. if (other.isNotEmpty())
  8911. {
  8912. const int len = other.length();
  8913. const int end = length() - len;
  8914. for (int i = jmax (0, startIndex); i <= end; ++i)
  8915. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  8916. return i;
  8917. }
  8918. return -1;
  8919. }
  8920. int String::lastIndexOf (const String& other) const throw()
  8921. {
  8922. if (other.isNotEmpty())
  8923. {
  8924. const int len = other.length();
  8925. int i = length() - len;
  8926. if (i >= 0)
  8927. {
  8928. const juce_wchar* n = text + i;
  8929. while (i >= 0)
  8930. {
  8931. if (CharacterFunctions::compare (n--, other.text, len) == 0)
  8932. return i;
  8933. --i;
  8934. }
  8935. }
  8936. }
  8937. return -1;
  8938. }
  8939. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  8940. {
  8941. if (other.isNotEmpty())
  8942. {
  8943. const int len = other.length();
  8944. int i = length() - len;
  8945. if (i >= 0)
  8946. {
  8947. const juce_wchar* n = text + i;
  8948. while (i >= 0)
  8949. {
  8950. if (CharacterFunctions::compareIgnoreCase (n--, other.text, len) == 0)
  8951. return i;
  8952. --i;
  8953. }
  8954. }
  8955. }
  8956. return -1;
  8957. }
  8958. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  8959. {
  8960. for (int i = length(); --i >= 0;)
  8961. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, text[i], ignoreCase) >= 0)
  8962. return i;
  8963. return -1;
  8964. }
  8965. bool String::contains (const String& other) const throw()
  8966. {
  8967. return indexOf (other) >= 0;
  8968. }
  8969. bool String::containsChar (const juce_wchar character) const throw()
  8970. {
  8971. const juce_wchar* t = text;
  8972. for (;;)
  8973. {
  8974. if (*t == 0)
  8975. return false;
  8976. if (*t == character)
  8977. return true;
  8978. ++t;
  8979. }
  8980. }
  8981. bool String::containsIgnoreCase (const String& t) const throw()
  8982. {
  8983. return indexOfIgnoreCase (t) >= 0;
  8984. }
  8985. int String::indexOfWholeWord (const String& word) const throw()
  8986. {
  8987. if (word.isNotEmpty())
  8988. {
  8989. const int wordLen = word.length();
  8990. const int end = length() - wordLen;
  8991. const juce_wchar* t = text;
  8992. for (int i = 0; i <= end; ++i)
  8993. {
  8994. if (CharacterFunctions::compare (t, word.text, wordLen) == 0
  8995. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  8996. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  8997. {
  8998. return i;
  8999. }
  9000. ++t;
  9001. }
  9002. }
  9003. return -1;
  9004. }
  9005. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  9006. {
  9007. if (word.isNotEmpty())
  9008. {
  9009. const int wordLen = word.length();
  9010. const int end = length() - wordLen;
  9011. const juce_wchar* t = text;
  9012. for (int i = 0; i <= end; ++i)
  9013. {
  9014. if (CharacterFunctions::compareIgnoreCase (t, word.text, wordLen) == 0
  9015. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9016. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9017. {
  9018. return i;
  9019. }
  9020. ++t;
  9021. }
  9022. }
  9023. return -1;
  9024. }
  9025. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  9026. {
  9027. return indexOfWholeWord (wordToLookFor) >= 0;
  9028. }
  9029. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  9030. {
  9031. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  9032. }
  9033. static int indexOfMatch (const juce_wchar* const wildcard,
  9034. const juce_wchar* const test,
  9035. const bool ignoreCase) throw()
  9036. {
  9037. int start = 0;
  9038. while (test [start] != 0)
  9039. {
  9040. int i = 0;
  9041. for (;;)
  9042. {
  9043. const juce_wchar wc = wildcard [i];
  9044. const juce_wchar c = test [i + start];
  9045. if (wc == c
  9046. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9047. || (wc == '?' && c != 0))
  9048. {
  9049. if (wc == 0)
  9050. return start;
  9051. ++i;
  9052. }
  9053. else
  9054. {
  9055. if (wc == '*' && (wildcard [i + 1] == 0
  9056. || indexOfMatch (wildcard + i + 1,
  9057. test + start + i,
  9058. ignoreCase) >= 0))
  9059. {
  9060. return start;
  9061. }
  9062. break;
  9063. }
  9064. }
  9065. ++start;
  9066. }
  9067. return -1;
  9068. }
  9069. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  9070. {
  9071. int i = 0;
  9072. for (;;)
  9073. {
  9074. const juce_wchar wc = wildcard.text [i];
  9075. const juce_wchar c = text [i];
  9076. if (wc == c
  9077. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9078. || (wc == '?' && c != 0))
  9079. {
  9080. if (wc == 0)
  9081. return true;
  9082. ++i;
  9083. }
  9084. else
  9085. {
  9086. return wc == '*' && (wildcard [i + 1] == 0
  9087. || indexOfMatch (wildcard.text + i + 1,
  9088. text + i,
  9089. ignoreCase) >= 0);
  9090. }
  9091. }
  9092. }
  9093. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  9094. {
  9095. const int len = stringToRepeat.length();
  9096. String result ((size_t) (len * numberOfTimesToRepeat + 1), (int) 0);
  9097. juce_wchar* n = result.text;
  9098. *n = 0;
  9099. while (--numberOfTimesToRepeat >= 0)
  9100. {
  9101. StringHolder::copyChars (n, stringToRepeat.text, len);
  9102. n += len;
  9103. }
  9104. return result;
  9105. }
  9106. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  9107. {
  9108. jassert (padCharacter != 0);
  9109. const int len = length();
  9110. if (len >= minimumLength || padCharacter == 0)
  9111. return *this;
  9112. String result ((size_t) minimumLength + 1, (int) 0);
  9113. juce_wchar* n = result.text;
  9114. minimumLength -= len;
  9115. while (--minimumLength >= 0)
  9116. *n++ = padCharacter;
  9117. StringHolder::copyChars (n, text, len);
  9118. return result;
  9119. }
  9120. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  9121. {
  9122. jassert (padCharacter != 0);
  9123. const int len = length();
  9124. if (len >= minimumLength || padCharacter == 0)
  9125. return *this;
  9126. String result (*this, (size_t) minimumLength);
  9127. juce_wchar* n = result.text + len;
  9128. minimumLength -= len;
  9129. while (--minimumLength >= 0)
  9130. *n++ = padCharacter;
  9131. *n = 0;
  9132. return result;
  9133. }
  9134. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  9135. {
  9136. if (index < 0)
  9137. {
  9138. // a negative index to replace from?
  9139. jassertfalse
  9140. index = 0;
  9141. }
  9142. if (numCharsToReplace < 0)
  9143. {
  9144. // replacing a negative number of characters?
  9145. numCharsToReplace = 0;
  9146. jassertfalse;
  9147. }
  9148. const int len = length();
  9149. if (index + numCharsToReplace > len)
  9150. {
  9151. if (index > len)
  9152. {
  9153. // replacing beyond the end of the string?
  9154. index = len;
  9155. jassertfalse
  9156. }
  9157. numCharsToReplace = len - index;
  9158. }
  9159. const int newStringLen = stringToInsert.length();
  9160. const int newTotalLen = len + newStringLen - numCharsToReplace;
  9161. if (newTotalLen <= 0)
  9162. return String::empty;
  9163. String result ((size_t) newTotalLen, (int) 0);
  9164. StringHolder::copyChars (result.text, text, index);
  9165. if (newStringLen > 0)
  9166. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  9167. const int endStringLen = newTotalLen - (index + newStringLen);
  9168. if (endStringLen > 0)
  9169. StringHolder::copyChars (result.text + (index + newStringLen),
  9170. text + (index + numCharsToReplace),
  9171. endStringLen);
  9172. return result;
  9173. }
  9174. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  9175. {
  9176. const int stringToReplaceLen = stringToReplace.length();
  9177. const int stringToInsertLen = stringToInsert.length();
  9178. int i = 0;
  9179. String result (*this);
  9180. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  9181. : result.indexOf (i, stringToReplace))) >= 0)
  9182. {
  9183. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  9184. i += stringToInsertLen;
  9185. }
  9186. return result;
  9187. }
  9188. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  9189. {
  9190. const int index = indexOfChar (charToReplace);
  9191. if (index < 0)
  9192. return *this;
  9193. String result (*this, size_t());
  9194. juce_wchar* t = result.text + index;
  9195. while (*t != 0)
  9196. {
  9197. if (*t == charToReplace)
  9198. *t = charToInsert;
  9199. ++t;
  9200. }
  9201. return result;
  9202. }
  9203. const String String::replaceCharacters (const String& charactersToReplace,
  9204. const String& charactersToInsertInstead) const
  9205. {
  9206. String result (*this, size_t());
  9207. juce_wchar* t = result.text;
  9208. const int len2 = charactersToInsertInstead.length();
  9209. // the two strings passed in are supposed to be the same length!
  9210. jassert (len2 == charactersToReplace.length());
  9211. while (*t != 0)
  9212. {
  9213. const int index = charactersToReplace.indexOfChar (*t);
  9214. if (((unsigned int) index) < (unsigned int) len2)
  9215. *t = charactersToInsertInstead [index];
  9216. ++t;
  9217. }
  9218. return result;
  9219. }
  9220. bool String::startsWith (const String& other) const throw()
  9221. {
  9222. return CharacterFunctions::compare (text, other.text, other.length()) == 0;
  9223. }
  9224. bool String::startsWithIgnoreCase (const String& other) const throw()
  9225. {
  9226. return CharacterFunctions::compareIgnoreCase (text, other.text, other.length()) == 0;
  9227. }
  9228. bool String::startsWithChar (const juce_wchar character) const throw()
  9229. {
  9230. jassert (character != 0); // strings can't contain a null character!
  9231. return text[0] == character;
  9232. }
  9233. bool String::endsWithChar (const juce_wchar character) const throw()
  9234. {
  9235. jassert (character != 0); // strings can't contain a null character!
  9236. return text[0] != 0
  9237. && text [length() - 1] == character;
  9238. }
  9239. bool String::endsWith (const String& other) const throw()
  9240. {
  9241. const int thisLen = length();
  9242. const int otherLen = other.length();
  9243. return thisLen >= otherLen
  9244. && CharacterFunctions::compare (text + thisLen - otherLen, other.text) == 0;
  9245. }
  9246. bool String::endsWithIgnoreCase (const String& other) const throw()
  9247. {
  9248. const int thisLen = length();
  9249. const int otherLen = other.length();
  9250. return thisLen >= otherLen
  9251. && CharacterFunctions::compareIgnoreCase (text + thisLen - otherLen, other.text) == 0;
  9252. }
  9253. const String String::toUpperCase() const
  9254. {
  9255. String result (*this, size_t());
  9256. CharacterFunctions::toUpperCase (result.text);
  9257. return result;
  9258. }
  9259. const String String::toLowerCase() const
  9260. {
  9261. String result (*this, size_t());
  9262. CharacterFunctions::toLowerCase (result.text);
  9263. return result;
  9264. }
  9265. juce_wchar& String::operator[] (const int index)
  9266. {
  9267. jassert (((unsigned int) index) <= (unsigned int) length());
  9268. text = StringHolder::makeUnique (text);
  9269. return text [index];
  9270. }
  9271. juce_wchar String::getLastCharacter() const throw()
  9272. {
  9273. return isEmpty() ? juce_wchar() : text [length() - 1];
  9274. }
  9275. const String String::substring (int start, int end) const
  9276. {
  9277. if (start < 0)
  9278. start = 0;
  9279. else if (end <= start)
  9280. return empty;
  9281. int len = 0;
  9282. while (len <= end && text [len] != 0)
  9283. ++len;
  9284. if (end >= len)
  9285. {
  9286. if (start == 0)
  9287. return *this;
  9288. end = len;
  9289. }
  9290. return String (text + start, end - start);
  9291. }
  9292. const String String::substring (const int start) const
  9293. {
  9294. if (start <= 0)
  9295. return *this;
  9296. const int len = length();
  9297. if (start >= len)
  9298. return empty;
  9299. return String (text + start, len - start);
  9300. }
  9301. const String String::dropLastCharacters (const int numberToDrop) const
  9302. {
  9303. return String (text, jmax (0, length() - numberToDrop));
  9304. }
  9305. const String String::getLastCharacters (const int numCharacters) const
  9306. {
  9307. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  9308. }
  9309. const String String::fromFirstOccurrenceOf (const String& sub,
  9310. const bool includeSubString,
  9311. const bool ignoreCase) const
  9312. {
  9313. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9314. : indexOf (sub);
  9315. if (i < 0)
  9316. return empty;
  9317. return substring (includeSubString ? i : i + sub.length());
  9318. }
  9319. const String String::fromLastOccurrenceOf (const String& sub,
  9320. const bool includeSubString,
  9321. const bool ignoreCase) const
  9322. {
  9323. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9324. : lastIndexOf (sub);
  9325. if (i < 0)
  9326. return *this;
  9327. return substring (includeSubString ? i : i + sub.length());
  9328. }
  9329. const String String::upToFirstOccurrenceOf (const String& sub,
  9330. const bool includeSubString,
  9331. const bool ignoreCase) const
  9332. {
  9333. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9334. : indexOf (sub);
  9335. if (i < 0)
  9336. return *this;
  9337. return substring (0, includeSubString ? i + sub.length() : i);
  9338. }
  9339. const String String::upToLastOccurrenceOf (const String& sub,
  9340. const bool includeSubString,
  9341. const bool ignoreCase) const
  9342. {
  9343. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9344. : lastIndexOf (sub);
  9345. if (i < 0)
  9346. return *this;
  9347. return substring (0, includeSubString ? i + sub.length() : i);
  9348. }
  9349. bool String::isQuotedString() const
  9350. {
  9351. const String trimmed (trimStart());
  9352. return trimmed[0] == '"'
  9353. || trimmed[0] == '\'';
  9354. }
  9355. const String String::unquoted() const
  9356. {
  9357. String s (*this);
  9358. if (s.text[0] == '"' || s.text[0] == '\'')
  9359. s = s.substring (1);
  9360. const int lastCharIndex = s.length() - 1;
  9361. if (lastCharIndex >= 0
  9362. && (s [lastCharIndex] == '"' || s[lastCharIndex] == '\''))
  9363. s [lastCharIndex] = 0;
  9364. return s;
  9365. }
  9366. const String String::quoted (const juce_wchar quoteCharacter) const
  9367. {
  9368. if (isEmpty())
  9369. return charToString (quoteCharacter) + quoteCharacter;
  9370. String t (*this);
  9371. if (! t.startsWithChar (quoteCharacter))
  9372. t = charToString (quoteCharacter) + t;
  9373. if (! t.endsWithChar (quoteCharacter))
  9374. t += quoteCharacter;
  9375. return t;
  9376. }
  9377. const String String::trim() const
  9378. {
  9379. if (isEmpty())
  9380. return empty;
  9381. int start = 0;
  9382. while (CharacterFunctions::isWhitespace (text [start]))
  9383. ++start;
  9384. const int len = length();
  9385. int end = len - 1;
  9386. while ((end >= start) && CharacterFunctions::isWhitespace (text [end]))
  9387. --end;
  9388. ++end;
  9389. if (end <= start)
  9390. return empty;
  9391. else if (start > 0 || end < len)
  9392. return String (text + start, end - start);
  9393. return *this;
  9394. }
  9395. const String String::trimStart() const
  9396. {
  9397. if (isEmpty())
  9398. return empty;
  9399. const juce_wchar* t = text;
  9400. while (CharacterFunctions::isWhitespace (*t))
  9401. ++t;
  9402. if (t == text)
  9403. return *this;
  9404. return String (t);
  9405. }
  9406. const String String::trimEnd() const
  9407. {
  9408. if (isEmpty())
  9409. return empty;
  9410. const juce_wchar* endT = text + (length() - 1);
  9411. while ((endT >= text) && CharacterFunctions::isWhitespace (*endT))
  9412. --endT;
  9413. return String (text, (int) (++endT - text));
  9414. }
  9415. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  9416. {
  9417. const juce_wchar* t = text;
  9418. while (charactersToTrim.containsChar (*t))
  9419. ++t;
  9420. return t == text ? *this : String (t);
  9421. }
  9422. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  9423. {
  9424. if (isEmpty())
  9425. return empty;
  9426. const int len = length();
  9427. const juce_wchar* endT = text + (len - 1);
  9428. int numToRemove = 0;
  9429. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  9430. {
  9431. ++numToRemove;
  9432. --endT;
  9433. }
  9434. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  9435. }
  9436. const String String::retainCharacters (const String& charactersToRetain) const
  9437. {
  9438. if (isEmpty())
  9439. return empty;
  9440. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  9441. juce_wchar* dst = result.text;
  9442. const juce_wchar* src = text;
  9443. while (*src != 0)
  9444. {
  9445. if (charactersToRetain.containsChar (*src))
  9446. *dst++ = *src;
  9447. ++src;
  9448. }
  9449. *dst = 0;
  9450. return result;
  9451. }
  9452. const String String::removeCharacters (const String& charactersToRemove) const
  9453. {
  9454. if (isEmpty())
  9455. return empty;
  9456. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  9457. juce_wchar* dst = result.text;
  9458. const juce_wchar* src = text;
  9459. while (*src != 0)
  9460. {
  9461. if (! charactersToRemove.containsChar (*src))
  9462. *dst++ = *src;
  9463. ++src;
  9464. }
  9465. *dst = 0;
  9466. return result;
  9467. }
  9468. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  9469. {
  9470. int i = 0;
  9471. for (;;)
  9472. {
  9473. if (! permittedCharacters.containsChar (text[i]))
  9474. break;
  9475. ++i;
  9476. }
  9477. return substring (0, i);
  9478. }
  9479. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  9480. {
  9481. const juce_wchar* const t = text;
  9482. int i = 0;
  9483. while (t[i] != 0)
  9484. {
  9485. if (charactersToStopAt.containsChar (t[i]))
  9486. return String (text, i);
  9487. ++i;
  9488. }
  9489. return empty;
  9490. }
  9491. bool String::containsOnly (const String& chars) const throw()
  9492. {
  9493. const juce_wchar* t = text;
  9494. while (*t != 0)
  9495. if (! chars.containsChar (*t++))
  9496. return false;
  9497. return true;
  9498. }
  9499. bool String::containsAnyOf (const String& chars) const throw()
  9500. {
  9501. const juce_wchar* t = text;
  9502. while (*t != 0)
  9503. if (chars.containsChar (*t++))
  9504. return true;
  9505. return false;
  9506. }
  9507. bool String::containsNonWhitespaceChars() const throw()
  9508. {
  9509. const juce_wchar* t = text;
  9510. while (*t != 0)
  9511. if (! CharacterFunctions::isWhitespace (*t++))
  9512. return true;
  9513. return false;
  9514. }
  9515. const String String::formatted (const juce_wchar* const pf, ... )
  9516. {
  9517. jassert (pf != 0);
  9518. va_list args;
  9519. va_start (args, pf);
  9520. size_t bufferSize = 256;
  9521. String result (bufferSize, (int) 0);
  9522. result.text[0] = 0;
  9523. for (;;)
  9524. {
  9525. #if JUCE_LINUX && JUCE_64BIT
  9526. va_list tempArgs;
  9527. va_copy (tempArgs, args);
  9528. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, tempArgs);
  9529. va_end (tempArgs);
  9530. #elif JUCE_WINDOWS
  9531. #if JUCE_MSVC
  9532. #pragma warning (push)
  9533. #pragma warning (disable: 4996)
  9534. #endif
  9535. const int num = (int) _vsnwprintf (result.text, bufferSize - 1, pf, args);
  9536. #if JUCE_MSVC
  9537. #pragma warning (pop)
  9538. #endif
  9539. #else
  9540. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, args);
  9541. #endif
  9542. if (num > 0)
  9543. return result;
  9544. bufferSize += 256;
  9545. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  9546. break; // returns -1 because of an error rather than because it needs more space.
  9547. result.preallocateStorage (bufferSize);
  9548. }
  9549. return empty;
  9550. }
  9551. int String::getIntValue() const throw()
  9552. {
  9553. return CharacterFunctions::getIntValue (text);
  9554. }
  9555. int String::getTrailingIntValue() const throw()
  9556. {
  9557. int n = 0;
  9558. int mult = 1;
  9559. const juce_wchar* t = text + length();
  9560. while (--t >= text)
  9561. {
  9562. const juce_wchar c = *t;
  9563. if (! CharacterFunctions::isDigit (c))
  9564. {
  9565. if (c == '-')
  9566. n = -n;
  9567. break;
  9568. }
  9569. n += mult * (c - '0');
  9570. mult *= 10;
  9571. }
  9572. return n;
  9573. }
  9574. int64 String::getLargeIntValue() const throw()
  9575. {
  9576. return CharacterFunctions::getInt64Value (text);
  9577. }
  9578. float String::getFloatValue() const throw()
  9579. {
  9580. return (float) CharacterFunctions::getDoubleValue (text);
  9581. }
  9582. double String::getDoubleValue() const throw()
  9583. {
  9584. return CharacterFunctions::getDoubleValue (text);
  9585. }
  9586. static const juce_wchar* const hexDigits = T("0123456789abcdef");
  9587. const String String::toHexString (const int number)
  9588. {
  9589. juce_wchar buffer[32];
  9590. juce_wchar* const end = buffer + 32;
  9591. juce_wchar* t = end;
  9592. *--t = 0;
  9593. unsigned int v = (unsigned int) number;
  9594. do
  9595. {
  9596. *--t = hexDigits [v & 15];
  9597. v >>= 4;
  9598. } while (v != 0);
  9599. return String (t, (int) (((char*) end) - (char*) t) - 1);
  9600. }
  9601. const String String::toHexString (const int64 number)
  9602. {
  9603. juce_wchar buffer[32];
  9604. juce_wchar* const end = buffer + 32;
  9605. juce_wchar* t = end;
  9606. *--t = 0;
  9607. uint64 v = (uint64) number;
  9608. do
  9609. {
  9610. *--t = hexDigits [(int) (v & 15)];
  9611. v >>= 4;
  9612. } while (v != 0);
  9613. return String (t, (int) (((char*) end) - (char*) t));
  9614. }
  9615. const String String::toHexString (const short number)
  9616. {
  9617. return toHexString ((int) (unsigned short) number);
  9618. }
  9619. const String String::toHexString (const unsigned char* data,
  9620. const int size,
  9621. const int groupSize)
  9622. {
  9623. if (size <= 0)
  9624. return empty;
  9625. int numChars = (size * 2) + 2;
  9626. if (groupSize > 0)
  9627. numChars += size / groupSize;
  9628. String s ((size_t) numChars, (int) 0);
  9629. juce_wchar* d = s.text;
  9630. for (int i = 0; i < size; ++i)
  9631. {
  9632. *d++ = hexDigits [(*data) >> 4];
  9633. *d++ = hexDigits [(*data) & 0xf];
  9634. ++data;
  9635. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  9636. *d++ = ' ';
  9637. }
  9638. *d = 0;
  9639. return s;
  9640. }
  9641. int String::getHexValue32() const throw()
  9642. {
  9643. int result = 0;
  9644. const juce_wchar* c = text;
  9645. for (;;)
  9646. {
  9647. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9648. if (hexValue >= 0)
  9649. result = (result << 4) | hexValue;
  9650. else if (*c == 0)
  9651. break;
  9652. ++c;
  9653. }
  9654. return result;
  9655. }
  9656. int64 String::getHexValue64() const throw()
  9657. {
  9658. int64 result = 0;
  9659. const juce_wchar* c = text;
  9660. for (;;)
  9661. {
  9662. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9663. if (hexValue >= 0)
  9664. result = (result << 4) | hexValue;
  9665. else if (*c == 0)
  9666. break;
  9667. ++c;
  9668. }
  9669. return result;
  9670. }
  9671. const String String::createStringFromData (const void* const data_, const int size)
  9672. {
  9673. const char* const data = static_cast <const char*> (data_);
  9674. if (size <= 0 || data == 0)
  9675. {
  9676. return empty;
  9677. }
  9678. else if (size < 2)
  9679. {
  9680. return charToString (data[0]);
  9681. }
  9682. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  9683. || (data[0] == (char)-1 && data[1] == (char)-2))
  9684. {
  9685. // assume it's 16-bit unicode
  9686. const bool bigEndian = (data[0] == (char)-2);
  9687. const int numChars = size / 2 - 1;
  9688. String result;
  9689. result.preallocateStorage (numChars + 2);
  9690. const uint16* const src = (const uint16*) (data + 2);
  9691. juce_wchar* const dst = const_cast <juce_wchar*> (static_cast <const juce_wchar*> (result));
  9692. if (bigEndian)
  9693. {
  9694. for (int i = 0; i < numChars; ++i)
  9695. dst[i] = (juce_wchar) ByteOrder::swapIfLittleEndian (src[i]);
  9696. }
  9697. else
  9698. {
  9699. for (int i = 0; i < numChars; ++i)
  9700. dst[i] = (juce_wchar) ByteOrder::swapIfBigEndian (src[i]);
  9701. }
  9702. dst [numChars] = 0;
  9703. return result;
  9704. }
  9705. else
  9706. {
  9707. return String::fromUTF8 (data, size);
  9708. }
  9709. }
  9710. const char* String::toUTF8() const
  9711. {
  9712. if (isEmpty())
  9713. {
  9714. return reinterpret_cast <const char*> (text);
  9715. }
  9716. else
  9717. {
  9718. const int currentLen = length() + 1;
  9719. const int utf8BytesNeeded = getNumBytesAsUTF8();
  9720. String* const mutableThis = const_cast <String*> (this);
  9721. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, currentLen + 1 + utf8BytesNeeded / sizeof (juce_wchar));
  9722. char* const otherCopy = reinterpret_cast <char*> (mutableThis->text + currentLen);
  9723. copyToUTF8 (otherCopy, std::numeric_limits<int>::max());
  9724. return otherCopy;
  9725. }
  9726. }
  9727. int String::copyToUTF8 (char* const buffer, const int maxBufferSizeBytes) const throw()
  9728. {
  9729. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  9730. int num = 0, index = 0;
  9731. for (;;)
  9732. {
  9733. const uint32 c = (uint32) text [index++];
  9734. if (c >= 0x80)
  9735. {
  9736. int numExtraBytes = 1;
  9737. if (c >= 0x800)
  9738. {
  9739. ++numExtraBytes;
  9740. if (c >= 0x10000)
  9741. {
  9742. ++numExtraBytes;
  9743. if (c >= 0x200000)
  9744. {
  9745. ++numExtraBytes;
  9746. if (c >= 0x4000000)
  9747. ++numExtraBytes;
  9748. }
  9749. }
  9750. }
  9751. if (buffer != 0)
  9752. {
  9753. if (num + numExtraBytes >= maxBufferSizeBytes)
  9754. {
  9755. buffer [num++] = 0;
  9756. break;
  9757. }
  9758. else
  9759. {
  9760. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  9761. while (--numExtraBytes >= 0)
  9762. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  9763. }
  9764. }
  9765. else
  9766. {
  9767. num += numExtraBytes + 1;
  9768. }
  9769. }
  9770. else
  9771. {
  9772. if (buffer != 0)
  9773. {
  9774. if (num + 1 >= maxBufferSizeBytes)
  9775. {
  9776. buffer [num++] = 0;
  9777. break;
  9778. }
  9779. buffer [num] = (uint8) c;
  9780. }
  9781. ++num;
  9782. }
  9783. if (c == 0)
  9784. break;
  9785. }
  9786. return num;
  9787. }
  9788. int String::getNumBytesAsUTF8() const throw()
  9789. {
  9790. int num = 0;
  9791. const juce_wchar* t = text;
  9792. for (;;)
  9793. {
  9794. const uint32 c = (uint32) *t;
  9795. if (c >= 0x80)
  9796. {
  9797. ++num;
  9798. if (c >= 0x800)
  9799. {
  9800. ++num;
  9801. if (c >= 0x10000)
  9802. {
  9803. ++num;
  9804. if (c >= 0x200000)
  9805. {
  9806. ++num;
  9807. if (c >= 0x4000000)
  9808. ++num;
  9809. }
  9810. }
  9811. }
  9812. }
  9813. else if (c == 0)
  9814. break;
  9815. ++num;
  9816. ++t;
  9817. }
  9818. return num;
  9819. }
  9820. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  9821. {
  9822. if (buffer == 0)
  9823. return empty;
  9824. if (bufferSizeBytes < 0)
  9825. bufferSizeBytes = std::numeric_limits<int>::max();
  9826. size_t numBytes;
  9827. for (numBytes = 0; numBytes < (size_t) bufferSizeBytes; ++numBytes)
  9828. if (buffer [numBytes] == 0)
  9829. break;
  9830. String result ((size_t) numBytes + 1, (int) 0);
  9831. juce_wchar* dest = result.text;
  9832. size_t i = 0;
  9833. while (i < numBytes)
  9834. {
  9835. const char c = buffer [i++];
  9836. if (c < 0)
  9837. {
  9838. unsigned int mask = 0x7f;
  9839. int bit = 0x40;
  9840. int numExtraValues = 0;
  9841. while (bit != 0 && (c & bit) != 0)
  9842. {
  9843. bit >>= 1;
  9844. mask >>= 1;
  9845. ++numExtraValues;
  9846. }
  9847. int n = (mask & (unsigned char) c);
  9848. while (--numExtraValues >= 0 && i < (size_t) bufferSizeBytes)
  9849. {
  9850. const char nextByte = buffer[i];
  9851. if ((nextByte & 0xc0) != 0x80)
  9852. break;
  9853. n <<= 6;
  9854. n |= (nextByte & 0x3f);
  9855. ++i;
  9856. }
  9857. *dest++ = (juce_wchar) n;
  9858. }
  9859. else
  9860. {
  9861. *dest++ = (juce_wchar) c;
  9862. }
  9863. }
  9864. *dest = 0;
  9865. return result;
  9866. }
  9867. const char* String::toCString() const
  9868. {
  9869. if (isEmpty())
  9870. {
  9871. return reinterpret_cast <const char*> (text);
  9872. }
  9873. else
  9874. {
  9875. const int len = length();
  9876. String* const mutableThis = const_cast <String*> (this);
  9877. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, (len + 1) * 2);
  9878. char* otherCopy = reinterpret_cast <char*> (mutableThis->text + len + 1);
  9879. CharacterFunctions::copy (otherCopy, text, len);
  9880. otherCopy [len] = 0;
  9881. return otherCopy;
  9882. }
  9883. }
  9884. #if JUCE_MSVC
  9885. #pragma warning (push)
  9886. #pragma warning (disable: 4514 4996)
  9887. #endif
  9888. int String::getNumBytesAsCString() const throw()
  9889. {
  9890. return (int) wcstombs (0, text, 0);
  9891. }
  9892. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  9893. {
  9894. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  9895. if (destBuffer != 0 && numBytes >= 0)
  9896. destBuffer [numBytes] = 0;
  9897. return numBytes;
  9898. }
  9899. #if JUCE_MSVC
  9900. #pragma warning (pop)
  9901. #endif
  9902. void String::copyToUnicode (juce_wchar* const destBuffer, const int maxCharsToCopy) const throw()
  9903. {
  9904. StringHolder::copyChars (destBuffer, text, jmin (maxCharsToCopy, length()));
  9905. }
  9906. String::Concatenator::Concatenator (String& stringToAppendTo)
  9907. : result (stringToAppendTo),
  9908. nextIndex (stringToAppendTo.length())
  9909. {
  9910. }
  9911. String::Concatenator::~Concatenator()
  9912. {
  9913. }
  9914. void String::Concatenator::append (const String& s)
  9915. {
  9916. const int len = s.length();
  9917. if (len > 0)
  9918. {
  9919. result.preallocateStorage (nextIndex + len);
  9920. s.copyToUnicode (static_cast <juce_wchar*> (result) + nextIndex, len);
  9921. nextIndex += len;
  9922. }
  9923. }
  9924. END_JUCE_NAMESPACE
  9925. /*** End of inlined file: juce_String.cpp ***/
  9926. /*** Start of inlined file: juce_StringArray.cpp ***/
  9927. BEGIN_JUCE_NAMESPACE
  9928. StringArray::StringArray() throw()
  9929. {
  9930. }
  9931. StringArray::StringArray (const StringArray& other)
  9932. : strings (other.strings)
  9933. {
  9934. }
  9935. StringArray::StringArray (const String& firstValue)
  9936. {
  9937. strings.add (firstValue);
  9938. }
  9939. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  9940. const int numberOfStrings)
  9941. {
  9942. for (int i = 0; i < numberOfStrings; ++i)
  9943. strings.add (initialStrings [i]);
  9944. }
  9945. StringArray::StringArray (const char* const* const initialStrings,
  9946. const int numberOfStrings)
  9947. {
  9948. for (int i = 0; i < numberOfStrings; ++i)
  9949. strings.add (initialStrings [i]);
  9950. }
  9951. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  9952. {
  9953. int i = 0;
  9954. while (initialStrings[i] != 0)
  9955. strings.add (initialStrings [i++]);
  9956. }
  9957. StringArray::StringArray (const char* const* const initialStrings)
  9958. {
  9959. int i = 0;
  9960. while (initialStrings[i] != 0)
  9961. strings.add (initialStrings [i++]);
  9962. }
  9963. StringArray& StringArray::operator= (const StringArray& other)
  9964. {
  9965. strings = other.strings;
  9966. return *this;
  9967. }
  9968. StringArray::~StringArray()
  9969. {
  9970. }
  9971. bool StringArray::operator== (const StringArray& other) const throw()
  9972. {
  9973. if (other.size() != size())
  9974. return false;
  9975. for (int i = size(); --i >= 0;)
  9976. if (other.strings.getReference(i) != strings.getReference(i))
  9977. return false;
  9978. return true;
  9979. }
  9980. bool StringArray::operator!= (const StringArray& other) const throw()
  9981. {
  9982. return ! operator== (other);
  9983. }
  9984. void StringArray::clear()
  9985. {
  9986. strings.clear();
  9987. }
  9988. const String& StringArray::operator[] (const int index) const throw()
  9989. {
  9990. if (((unsigned int) index) < (unsigned int) strings.size())
  9991. return strings.getReference (index);
  9992. return String::empty;
  9993. }
  9994. String& StringArray::getReference (const int index) throw()
  9995. {
  9996. jassert (((unsigned int) index) < (unsigned int) strings.size());
  9997. return strings.getReference (index);
  9998. }
  9999. void StringArray::add (const String& newString)
  10000. {
  10001. strings.add (newString);
  10002. }
  10003. void StringArray::insert (const int index, const String& newString)
  10004. {
  10005. strings.insert (index, newString);
  10006. }
  10007. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  10008. {
  10009. if (! contains (newString, ignoreCase))
  10010. add (newString);
  10011. }
  10012. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  10013. {
  10014. if (startIndex < 0)
  10015. {
  10016. jassertfalse
  10017. startIndex = 0;
  10018. }
  10019. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  10020. numElementsToAdd = otherArray.size() - startIndex;
  10021. while (--numElementsToAdd >= 0)
  10022. strings.add (otherArray.strings.getReference (startIndex++));
  10023. }
  10024. void StringArray::set (const int index, const String& newString)
  10025. {
  10026. strings.set (index, newString);
  10027. }
  10028. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  10029. {
  10030. if (ignoreCase)
  10031. {
  10032. for (int i = size(); --i >= 0;)
  10033. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  10034. return true;
  10035. }
  10036. else
  10037. {
  10038. for (int i = size(); --i >= 0;)
  10039. if (stringToLookFor == strings.getReference(i))
  10040. return true;
  10041. }
  10042. return false;
  10043. }
  10044. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  10045. {
  10046. if (i < 0)
  10047. i = 0;
  10048. const int numElements = size();
  10049. if (ignoreCase)
  10050. {
  10051. while (i < numElements)
  10052. {
  10053. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  10054. return i;
  10055. ++i;
  10056. }
  10057. }
  10058. else
  10059. {
  10060. while (i < numElements)
  10061. {
  10062. if (stringToLookFor == strings.getReference (i))
  10063. return i;
  10064. ++i;
  10065. }
  10066. }
  10067. return -1;
  10068. }
  10069. void StringArray::remove (const int index)
  10070. {
  10071. strings.remove (index);
  10072. }
  10073. void StringArray::removeString (const String& stringToRemove,
  10074. const bool ignoreCase)
  10075. {
  10076. if (ignoreCase)
  10077. {
  10078. for (int i = size(); --i >= 0;)
  10079. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  10080. strings.remove (i);
  10081. }
  10082. else
  10083. {
  10084. for (int i = size(); --i >= 0;)
  10085. if (stringToRemove == strings.getReference (i))
  10086. strings.remove (i);
  10087. }
  10088. }
  10089. void StringArray::removeRange (int startIndex, int numberToRemove)
  10090. {
  10091. strings.removeRange (startIndex, numberToRemove);
  10092. }
  10093. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  10094. {
  10095. if (removeWhitespaceStrings)
  10096. {
  10097. for (int i = size(); --i >= 0;)
  10098. if (! strings.getReference(i).containsNonWhitespaceChars())
  10099. strings.remove (i);
  10100. }
  10101. else
  10102. {
  10103. for (int i = size(); --i >= 0;)
  10104. if (strings.getReference(i).isEmpty())
  10105. strings.remove (i);
  10106. }
  10107. }
  10108. void StringArray::trim()
  10109. {
  10110. for (int i = size(); --i >= 0;)
  10111. {
  10112. String& s = strings.getReference(i);
  10113. s = s.trim();
  10114. }
  10115. }
  10116. class InternalStringArrayComparator_CaseSensitive
  10117. {
  10118. public:
  10119. static int compareElements (String& first, String& second) { return first.compare (second); }
  10120. };
  10121. class InternalStringArrayComparator_CaseInsensitive
  10122. {
  10123. public:
  10124. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  10125. };
  10126. void StringArray::sort (const bool ignoreCase)
  10127. {
  10128. if (ignoreCase)
  10129. {
  10130. InternalStringArrayComparator_CaseInsensitive comp;
  10131. strings.sort (comp);
  10132. }
  10133. else
  10134. {
  10135. InternalStringArrayComparator_CaseSensitive comp;
  10136. strings.sort (comp);
  10137. }
  10138. }
  10139. void StringArray::move (const int currentIndex, int newIndex) throw()
  10140. {
  10141. strings.move (currentIndex, newIndex);
  10142. }
  10143. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  10144. {
  10145. const int last = (numberToJoin < 0) ? size()
  10146. : jmin (size(), start + numberToJoin);
  10147. if (start < 0)
  10148. start = 0;
  10149. if (start >= last)
  10150. return String::empty;
  10151. if (start == last - 1)
  10152. return strings.getReference (start);
  10153. const int separatorLen = separator.length();
  10154. int charsNeeded = separatorLen * (last - start - 1);
  10155. for (int i = start; i < last; ++i)
  10156. charsNeeded += strings.getReference(i).length();
  10157. String result;
  10158. result.preallocateStorage (charsNeeded);
  10159. juce_wchar* dest = result;
  10160. while (start < last)
  10161. {
  10162. const String& s = strings.getReference (start);
  10163. const int len = s.length();
  10164. if (len > 0)
  10165. {
  10166. s.copyToUnicode (dest, len);
  10167. dest += len;
  10168. }
  10169. if (++start < last && separatorLen > 0)
  10170. {
  10171. separator.copyToUnicode (dest, separatorLen);
  10172. dest += separatorLen;
  10173. }
  10174. }
  10175. *dest = 0;
  10176. return result;
  10177. }
  10178. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  10179. {
  10180. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  10181. }
  10182. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  10183. {
  10184. int num = 0;
  10185. if (text.isNotEmpty())
  10186. {
  10187. bool insideQuotes = false;
  10188. juce_wchar currentQuoteChar = 0;
  10189. int i = 0;
  10190. int tokenStart = 0;
  10191. for (;;)
  10192. {
  10193. const juce_wchar c = text[i];
  10194. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  10195. if (! isBreak)
  10196. {
  10197. if (quoteCharacters.containsChar (c))
  10198. {
  10199. if (insideQuotes)
  10200. {
  10201. // only break out of quotes-mode if we find a matching quote to the
  10202. // one that we opened with..
  10203. if (currentQuoteChar == c)
  10204. insideQuotes = false;
  10205. }
  10206. else
  10207. {
  10208. insideQuotes = true;
  10209. currentQuoteChar = c;
  10210. }
  10211. }
  10212. }
  10213. else
  10214. {
  10215. add (String (static_cast <const juce_wchar*> (text) + tokenStart, i - tokenStart));
  10216. ++num;
  10217. tokenStart = i + 1;
  10218. }
  10219. if (c == 0)
  10220. break;
  10221. ++i;
  10222. }
  10223. }
  10224. return num;
  10225. }
  10226. int StringArray::addLines (const String& sourceText)
  10227. {
  10228. int numLines = 0;
  10229. const juce_wchar* text = sourceText;
  10230. while (*text != 0)
  10231. {
  10232. const juce_wchar* const startOfLine = text;
  10233. while (*text != 0)
  10234. {
  10235. if (*text == '\r')
  10236. {
  10237. ++text;
  10238. if (*text == '\n')
  10239. ++text;
  10240. break;
  10241. }
  10242. if (*text == '\n')
  10243. {
  10244. ++text;
  10245. break;
  10246. }
  10247. ++text;
  10248. }
  10249. const juce_wchar* endOfLine = text;
  10250. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  10251. --endOfLine;
  10252. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  10253. --endOfLine;
  10254. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  10255. ++numLines;
  10256. }
  10257. return numLines;
  10258. }
  10259. void StringArray::removeDuplicates (const bool ignoreCase)
  10260. {
  10261. for (int i = 0; i < size() - 1; ++i)
  10262. {
  10263. const String s (strings.getReference(i));
  10264. int nextIndex = i + 1;
  10265. for (;;)
  10266. {
  10267. nextIndex = indexOf (s, ignoreCase, nextIndex);
  10268. if (nextIndex < 0)
  10269. break;
  10270. strings.remove (nextIndex);
  10271. }
  10272. }
  10273. }
  10274. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  10275. const bool appendNumberToFirstInstance,
  10276. const juce_wchar* preNumberString,
  10277. const juce_wchar* postNumberString)
  10278. {
  10279. if (preNumberString == 0)
  10280. preNumberString = L" (";
  10281. if (postNumberString == 0)
  10282. postNumberString = L")";
  10283. for (int i = 0; i < size() - 1; ++i)
  10284. {
  10285. String& s = strings.getReference(i);
  10286. int nextIndex = indexOf (s, ignoreCase, i + 1);
  10287. if (nextIndex >= 0)
  10288. {
  10289. const String original (s);
  10290. int number = 0;
  10291. if (appendNumberToFirstInstance)
  10292. s = original + preNumberString + String (++number) + postNumberString;
  10293. else
  10294. ++number;
  10295. while (nextIndex >= 0)
  10296. {
  10297. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  10298. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  10299. }
  10300. }
  10301. }
  10302. }
  10303. void StringArray::minimiseStorageOverheads()
  10304. {
  10305. strings.minimiseStorageOverheads();
  10306. }
  10307. END_JUCE_NAMESPACE
  10308. /*** End of inlined file: juce_StringArray.cpp ***/
  10309. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  10310. BEGIN_JUCE_NAMESPACE
  10311. StringPairArray::StringPairArray (const bool ignoreCase_)
  10312. : ignoreCase (ignoreCase_)
  10313. {
  10314. }
  10315. StringPairArray::StringPairArray (const StringPairArray& other)
  10316. : keys (other.keys),
  10317. values (other.values),
  10318. ignoreCase (other.ignoreCase)
  10319. {
  10320. }
  10321. StringPairArray::~StringPairArray()
  10322. {
  10323. }
  10324. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  10325. {
  10326. keys = other.keys;
  10327. values = other.values;
  10328. return *this;
  10329. }
  10330. bool StringPairArray::operator== (const StringPairArray& other) const
  10331. {
  10332. for (int i = keys.size(); --i >= 0;)
  10333. if (other [keys[i]] != values[i])
  10334. return false;
  10335. return true;
  10336. }
  10337. bool StringPairArray::operator!= (const StringPairArray& other) const
  10338. {
  10339. return ! operator== (other);
  10340. }
  10341. const String& StringPairArray::operator[] (const String& key) const
  10342. {
  10343. return values [keys.indexOf (key, ignoreCase)];
  10344. }
  10345. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  10346. {
  10347. const int i = keys.indexOf (key, ignoreCase);
  10348. if (i >= 0)
  10349. return values[i];
  10350. return defaultReturnValue;
  10351. }
  10352. void StringPairArray::set (const String& key, const String& value)
  10353. {
  10354. const int i = keys.indexOf (key, ignoreCase);
  10355. if (i >= 0)
  10356. {
  10357. values.set (i, value);
  10358. }
  10359. else
  10360. {
  10361. keys.add (key);
  10362. values.add (value);
  10363. }
  10364. }
  10365. void StringPairArray::addArray (const StringPairArray& other)
  10366. {
  10367. for (int i = 0; i < other.size(); ++i)
  10368. set (other.keys[i], other.values[i]);
  10369. }
  10370. void StringPairArray::clear()
  10371. {
  10372. keys.clear();
  10373. values.clear();
  10374. }
  10375. void StringPairArray::remove (const String& key)
  10376. {
  10377. remove (keys.indexOf (key, ignoreCase));
  10378. }
  10379. void StringPairArray::remove (const int index)
  10380. {
  10381. keys.remove (index);
  10382. values.remove (index);
  10383. }
  10384. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  10385. {
  10386. ignoreCase = shouldIgnoreCase;
  10387. }
  10388. const String StringPairArray::getDescription() const
  10389. {
  10390. String s;
  10391. for (int i = 0; i < keys.size(); ++i)
  10392. {
  10393. s << keys[i] << " = " << values[i];
  10394. if (i < keys.size())
  10395. s << ", ";
  10396. }
  10397. return s;
  10398. }
  10399. void StringPairArray::minimiseStorageOverheads()
  10400. {
  10401. keys.minimiseStorageOverheads();
  10402. values.minimiseStorageOverheads();
  10403. }
  10404. END_JUCE_NAMESPACE
  10405. /*** End of inlined file: juce_StringPairArray.cpp ***/
  10406. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  10407. BEGIN_JUCE_NAMESPACE
  10408. XmlDocument::XmlDocument (const String& documentText)
  10409. : originalText (documentText),
  10410. ignoreEmptyTextElements (true)
  10411. {
  10412. }
  10413. XmlDocument::XmlDocument (const File& file)
  10414. : ignoreEmptyTextElements (true)
  10415. {
  10416. inputSource = new FileInputSource (file);
  10417. }
  10418. XmlDocument::~XmlDocument()
  10419. {
  10420. }
  10421. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  10422. {
  10423. inputSource = newSource;
  10424. }
  10425. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  10426. {
  10427. ignoreEmptyTextElements = shouldBeIgnored;
  10428. }
  10429. bool XmlDocument::isXmlIdentifierCharSlow (const juce_wchar c) throw()
  10430. {
  10431. return CharacterFunctions::isLetterOrDigit (c)
  10432. || c == '_' || c == '-' || c == ':' || c == '.';
  10433. }
  10434. inline bool XmlDocument::isXmlIdentifierChar (const juce_wchar c) const throw()
  10435. {
  10436. return (c > 0 && c <= 127) ? identifierLookupTable [(int) c]
  10437. : isXmlIdentifierCharSlow (c);
  10438. }
  10439. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  10440. {
  10441. String textToParse (originalText);
  10442. if (textToParse.isEmpty() && inputSource != 0)
  10443. {
  10444. ScopedPointer <InputStream> in (inputSource->createInputStream());
  10445. if (in != 0)
  10446. {
  10447. MemoryBlock data;
  10448. in->readIntoMemoryBlock (data, onlyReadOuterDocumentElement ? 8192 : -1);
  10449. if (data.getSize() >= 2
  10450. && ((data[0] == (char)-2 && data[1] == (char)-1)
  10451. || (data[0] == (char)-1 && data[1] == (char)-2)))
  10452. {
  10453. textToParse = String::createStringFromData (static_cast <const char*> (data.getData()), (int) data.getSize());
  10454. }
  10455. else
  10456. {
  10457. textToParse = String::fromUTF8 (static_cast <const char*> (data.getData()), (int) data.getSize());
  10458. }
  10459. if (! onlyReadOuterDocumentElement)
  10460. originalText = textToParse;
  10461. }
  10462. }
  10463. input = textToParse;
  10464. lastError = String::empty;
  10465. errorOccurred = false;
  10466. outOfData = false;
  10467. needToLoadDTD = true;
  10468. for (int i = 0; i < 128; ++i)
  10469. identifierLookupTable[i] = isXmlIdentifierCharSlow ((juce_wchar) i);
  10470. if (textToParse.isEmpty())
  10471. {
  10472. lastError = "not enough input";
  10473. }
  10474. else
  10475. {
  10476. skipHeader();
  10477. if (input != 0)
  10478. {
  10479. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  10480. if (! errorOccurred)
  10481. return result.release();
  10482. }
  10483. else
  10484. {
  10485. lastError = "incorrect xml header";
  10486. }
  10487. }
  10488. return 0;
  10489. }
  10490. const String& XmlDocument::getLastParseError() const throw()
  10491. {
  10492. return lastError;
  10493. }
  10494. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  10495. {
  10496. lastError = desc;
  10497. errorOccurred = ! carryOn;
  10498. }
  10499. const String XmlDocument::getFileContents (const String& filename) const
  10500. {
  10501. if (inputSource != 0)
  10502. {
  10503. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  10504. if (in != 0)
  10505. return in->readEntireStreamAsString();
  10506. }
  10507. return String::empty;
  10508. }
  10509. juce_wchar XmlDocument::readNextChar() throw()
  10510. {
  10511. if (*input != 0)
  10512. {
  10513. return *input++;
  10514. }
  10515. else
  10516. {
  10517. outOfData = true;
  10518. return 0;
  10519. }
  10520. }
  10521. int XmlDocument::findNextTokenLength() throw()
  10522. {
  10523. int len = 0;
  10524. juce_wchar c = *input;
  10525. while (isXmlIdentifierChar (c))
  10526. c = input [++len];
  10527. return len;
  10528. }
  10529. void XmlDocument::skipHeader()
  10530. {
  10531. const juce_wchar* const found = CharacterFunctions::find (input, T("<?xml"));
  10532. if (found != 0)
  10533. {
  10534. input = found;
  10535. input = CharacterFunctions::find (input, T("?>"));
  10536. if (input == 0)
  10537. return;
  10538. input += 2;
  10539. }
  10540. skipNextWhiteSpace();
  10541. const juce_wchar* docType = CharacterFunctions::find (input, T("<!DOCTYPE"));
  10542. if (docType == 0)
  10543. return;
  10544. input = docType + 9;
  10545. int n = 1;
  10546. while (n > 0)
  10547. {
  10548. const juce_wchar c = readNextChar();
  10549. if (outOfData)
  10550. return;
  10551. if (c == '<')
  10552. ++n;
  10553. else if (c == '>')
  10554. --n;
  10555. }
  10556. docType += 9;
  10557. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  10558. }
  10559. void XmlDocument::skipNextWhiteSpace()
  10560. {
  10561. for (;;)
  10562. {
  10563. juce_wchar c = *input;
  10564. while (CharacterFunctions::isWhitespace (c))
  10565. c = *++input;
  10566. if (c == 0)
  10567. {
  10568. outOfData = true;
  10569. break;
  10570. }
  10571. else if (c == '<')
  10572. {
  10573. if (input[1] == '!'
  10574. && input[2] == '-'
  10575. && input[3] == '-')
  10576. {
  10577. const juce_wchar* const closeComment = CharacterFunctions::find (input, T("-->"));
  10578. if (closeComment == 0)
  10579. {
  10580. outOfData = true;
  10581. break;
  10582. }
  10583. input = closeComment + 3;
  10584. continue;
  10585. }
  10586. else if (input[1] == '?')
  10587. {
  10588. const juce_wchar* const closeBracket = CharacterFunctions::find (input, T("?>"));
  10589. if (closeBracket == 0)
  10590. {
  10591. outOfData = true;
  10592. break;
  10593. }
  10594. input = closeBracket + 2;
  10595. continue;
  10596. }
  10597. }
  10598. break;
  10599. }
  10600. }
  10601. void XmlDocument::readQuotedString (String& result)
  10602. {
  10603. const juce_wchar quote = readNextChar();
  10604. while (! outOfData)
  10605. {
  10606. const juce_wchar c = readNextChar();
  10607. if (c == quote)
  10608. break;
  10609. if (c == '&')
  10610. {
  10611. --input;
  10612. readEntity (result);
  10613. }
  10614. else
  10615. {
  10616. --input;
  10617. const juce_wchar* const start = input;
  10618. for (;;)
  10619. {
  10620. const juce_wchar character = *input;
  10621. if (character == quote)
  10622. {
  10623. result.append (start, (int) (input - start));
  10624. ++input;
  10625. return;
  10626. }
  10627. else if (character == '&')
  10628. {
  10629. result.append (start, (int) (input - start));
  10630. break;
  10631. }
  10632. else if (character == 0)
  10633. {
  10634. outOfData = true;
  10635. setLastError ("unmatched quotes", false);
  10636. break;
  10637. }
  10638. ++input;
  10639. }
  10640. }
  10641. }
  10642. }
  10643. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  10644. {
  10645. XmlElement* node = 0;
  10646. skipNextWhiteSpace();
  10647. if (outOfData)
  10648. return 0;
  10649. input = CharacterFunctions::find (input, T("<"));
  10650. if (input != 0)
  10651. {
  10652. ++input;
  10653. int tagLen = findNextTokenLength();
  10654. if (tagLen == 0)
  10655. {
  10656. // no tag name - but allow for a gap after the '<' before giving an error
  10657. skipNextWhiteSpace();
  10658. tagLen = findNextTokenLength();
  10659. if (tagLen == 0)
  10660. {
  10661. setLastError ("tag name missing", false);
  10662. return node;
  10663. }
  10664. }
  10665. node = new XmlElement (String (input, tagLen));
  10666. input += tagLen;
  10667. XmlElement::XmlAttributeNode* lastAttribute = 0;
  10668. // look for attributes
  10669. for (;;)
  10670. {
  10671. skipNextWhiteSpace();
  10672. const juce_wchar c = *input;
  10673. // empty tag..
  10674. if (c == '/' && input[1] == '>')
  10675. {
  10676. input += 2;
  10677. break;
  10678. }
  10679. // parse the guts of the element..
  10680. if (c == '>')
  10681. {
  10682. ++input;
  10683. skipNextWhiteSpace();
  10684. if (alsoParseSubElements)
  10685. readChildElements (node);
  10686. break;
  10687. }
  10688. // get an attribute..
  10689. if (isXmlIdentifierChar (c))
  10690. {
  10691. const int attNameLen = findNextTokenLength();
  10692. if (attNameLen > 0)
  10693. {
  10694. const juce_wchar* attNameStart = input;
  10695. input += attNameLen;
  10696. skipNextWhiteSpace();
  10697. if (readNextChar() == '=')
  10698. {
  10699. skipNextWhiteSpace();
  10700. const juce_wchar nextChar = *input;
  10701. if (nextChar == '"' || nextChar == '\'')
  10702. {
  10703. XmlElement::XmlAttributeNode* const newAtt
  10704. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  10705. String::empty);
  10706. readQuotedString (newAtt->value);
  10707. if (lastAttribute == 0)
  10708. node->attributes = newAtt;
  10709. else
  10710. lastAttribute->next = newAtt;
  10711. lastAttribute = newAtt;
  10712. continue;
  10713. }
  10714. }
  10715. }
  10716. }
  10717. else
  10718. {
  10719. if (! outOfData)
  10720. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  10721. }
  10722. break;
  10723. }
  10724. }
  10725. return node;
  10726. }
  10727. void XmlDocument::readChildElements (XmlElement* parent)
  10728. {
  10729. XmlElement* lastChildNode = 0;
  10730. for (;;)
  10731. {
  10732. skipNextWhiteSpace();
  10733. if (outOfData)
  10734. {
  10735. setLastError ("unmatched tags", false);
  10736. break;
  10737. }
  10738. if (*input == '<')
  10739. {
  10740. if (input[1] == '/')
  10741. {
  10742. // our close tag..
  10743. input = CharacterFunctions::find (input, T(">"));
  10744. ++input;
  10745. break;
  10746. }
  10747. else if (input[1] == '!'
  10748. && input[2] == '['
  10749. && input[3] == 'C'
  10750. && input[4] == 'D'
  10751. && input[5] == 'A'
  10752. && input[6] == 'T'
  10753. && input[7] == 'A'
  10754. && input[8] == '[')
  10755. {
  10756. input += 9;
  10757. const juce_wchar* const inputStart = input;
  10758. int len = 0;
  10759. for (;;)
  10760. {
  10761. if (*input == 0)
  10762. {
  10763. setLastError ("unterminated CDATA section", false);
  10764. outOfData = true;
  10765. break;
  10766. }
  10767. else if (input[0] == ']'
  10768. && input[1] == ']'
  10769. && input[2] == '>')
  10770. {
  10771. input += 3;
  10772. break;
  10773. }
  10774. ++input;
  10775. ++len;
  10776. }
  10777. XmlElement* const e = new XmlElement ((int) 0);
  10778. e->setText (String (inputStart, len));
  10779. if (lastChildNode != 0)
  10780. lastChildNode->nextElement = e;
  10781. else
  10782. parent->addChildElement (e);
  10783. lastChildNode = e;
  10784. }
  10785. else
  10786. {
  10787. // this is some other element, so parse and add it..
  10788. XmlElement* const n = readNextElement (true);
  10789. if (n != 0)
  10790. {
  10791. if (lastChildNode == 0)
  10792. parent->addChildElement (n);
  10793. else
  10794. lastChildNode->nextElement = n;
  10795. lastChildNode = n;
  10796. }
  10797. else
  10798. {
  10799. return;
  10800. }
  10801. }
  10802. }
  10803. else
  10804. {
  10805. // read character block..
  10806. XmlElement* const e = new XmlElement ((int)0);
  10807. if (lastChildNode != 0)
  10808. lastChildNode->nextElement = e;
  10809. else
  10810. parent->addChildElement (e);
  10811. lastChildNode = e;
  10812. String textElementContent;
  10813. for (;;)
  10814. {
  10815. const juce_wchar c = *input;
  10816. if (c == '<')
  10817. break;
  10818. if (c == 0)
  10819. {
  10820. setLastError ("unmatched tags", false);
  10821. outOfData = true;
  10822. return;
  10823. }
  10824. if (c == '&')
  10825. {
  10826. String entity;
  10827. readEntity (entity);
  10828. if (entity.startsWithChar ('<') && entity [1] != 0)
  10829. {
  10830. const juce_wchar* const oldInput = input;
  10831. const bool oldOutOfData = outOfData;
  10832. input = entity;
  10833. outOfData = false;
  10834. for (;;)
  10835. {
  10836. XmlElement* const n = readNextElement (true);
  10837. if (n == 0)
  10838. break;
  10839. if (lastChildNode == 0)
  10840. parent->addChildElement (n);
  10841. else
  10842. lastChildNode->nextElement = n;
  10843. lastChildNode = n;
  10844. }
  10845. input = oldInput;
  10846. outOfData = oldOutOfData;
  10847. }
  10848. else
  10849. {
  10850. textElementContent += entity;
  10851. }
  10852. }
  10853. else
  10854. {
  10855. const juce_wchar* start = input;
  10856. int len = 0;
  10857. for (;;)
  10858. {
  10859. const juce_wchar nextChar = *input;
  10860. if (nextChar == '<' || nextChar == '&')
  10861. {
  10862. break;
  10863. }
  10864. else if (nextChar == 0)
  10865. {
  10866. setLastError ("unmatched tags", false);
  10867. outOfData = true;
  10868. return;
  10869. }
  10870. ++input;
  10871. ++len;
  10872. }
  10873. textElementContent.append (start, len);
  10874. }
  10875. }
  10876. if (ignoreEmptyTextElements ? textElementContent.containsNonWhitespaceChars()
  10877. : textElementContent.isNotEmpty())
  10878. e->setText (textElementContent);
  10879. }
  10880. }
  10881. }
  10882. void XmlDocument::readEntity (String& result)
  10883. {
  10884. // skip over the ampersand
  10885. ++input;
  10886. if (CharacterFunctions::compareIgnoreCase (input, T("amp;"), 4) == 0)
  10887. {
  10888. input += 4;
  10889. result += '&';
  10890. }
  10891. else if (CharacterFunctions::compareIgnoreCase (input, T("quot;"), 5) == 0)
  10892. {
  10893. input += 5;
  10894. result += '"';
  10895. }
  10896. else if (CharacterFunctions::compareIgnoreCase (input, T("apos;"), 5) == 0)
  10897. {
  10898. input += 5;
  10899. result += '\'';
  10900. }
  10901. else if (CharacterFunctions::compareIgnoreCase (input, T("lt;"), 3) == 0)
  10902. {
  10903. input += 3;
  10904. result += '<';
  10905. }
  10906. else if (CharacterFunctions::compareIgnoreCase (input, T("gt;"), 3) == 0)
  10907. {
  10908. input += 3;
  10909. result += '>';
  10910. }
  10911. else if (*input == '#')
  10912. {
  10913. int charCode = 0;
  10914. ++input;
  10915. if (*input == 'x' || *input == 'X')
  10916. {
  10917. ++input;
  10918. int numChars = 0;
  10919. while (input[0] != ';')
  10920. {
  10921. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  10922. if (hexValue < 0 || ++numChars > 8)
  10923. {
  10924. setLastError ("illegal escape sequence", true);
  10925. break;
  10926. }
  10927. charCode = (charCode << 4) | hexValue;
  10928. ++input;
  10929. }
  10930. ++input;
  10931. }
  10932. else if (input[0] >= '0' && input[0] <= '9')
  10933. {
  10934. int numChars = 0;
  10935. while (input[0] != ';')
  10936. {
  10937. if (++numChars > 12)
  10938. {
  10939. setLastError ("illegal escape sequence", true);
  10940. break;
  10941. }
  10942. charCode = charCode * 10 + (input[0] - '0');
  10943. ++input;
  10944. }
  10945. ++input;
  10946. }
  10947. else
  10948. {
  10949. setLastError ("illegal escape sequence", true);
  10950. result += '&';
  10951. return;
  10952. }
  10953. result << (juce_wchar) charCode;
  10954. }
  10955. else
  10956. {
  10957. const juce_wchar* const entityNameStart = input;
  10958. const juce_wchar* const closingSemiColon = CharacterFunctions::find (input, T(";"));
  10959. if (closingSemiColon == 0)
  10960. {
  10961. outOfData = true;
  10962. result += '&';
  10963. }
  10964. else
  10965. {
  10966. input = closingSemiColon + 1;
  10967. result += expandExternalEntity (String (entityNameStart,
  10968. (int) (closingSemiColon - entityNameStart)));
  10969. }
  10970. }
  10971. }
  10972. const String XmlDocument::expandEntity (const String& ent)
  10973. {
  10974. if (ent.equalsIgnoreCase ("amp"))
  10975. return String::charToString ('&');
  10976. if (ent.equalsIgnoreCase ("quot"))
  10977. return String::charToString ('"');
  10978. if (ent.equalsIgnoreCase ("apos"))
  10979. return String::charToString ('\'');
  10980. if (ent.equalsIgnoreCase ("lt"))
  10981. return String::charToString ('<');
  10982. if (ent.equalsIgnoreCase ("gt"))
  10983. return String::charToString ('>');
  10984. if (ent[0] == '#')
  10985. {
  10986. if (ent[1] == 'x' || ent[1] == 'X')
  10987. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  10988. if (ent[1] >= '0' && ent[1] <= '9')
  10989. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  10990. setLastError ("illegal escape sequence", false);
  10991. return String::charToString ('&');
  10992. }
  10993. return expandExternalEntity (ent);
  10994. }
  10995. const String XmlDocument::expandExternalEntity (const String& entity)
  10996. {
  10997. if (needToLoadDTD)
  10998. {
  10999. if (dtdText.isNotEmpty())
  11000. {
  11001. dtdText = dtdText.trimCharactersAtEnd (">");
  11002. tokenisedDTD.addTokens (dtdText, true);
  11003. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  11004. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  11005. {
  11006. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  11007. tokenisedDTD.clear();
  11008. tokenisedDTD.addTokens (getFileContents (fn), true);
  11009. }
  11010. else
  11011. {
  11012. tokenisedDTD.clear();
  11013. const int openBracket = dtdText.indexOfChar ('[');
  11014. if (openBracket > 0)
  11015. {
  11016. const int closeBracket = dtdText.lastIndexOfChar (']');
  11017. if (closeBracket > openBracket)
  11018. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  11019. closeBracket), true);
  11020. }
  11021. }
  11022. for (int i = tokenisedDTD.size(); --i >= 0;)
  11023. {
  11024. if (tokenisedDTD[i].startsWithChar ('%')
  11025. && tokenisedDTD[i].endsWithChar (';'))
  11026. {
  11027. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  11028. StringArray newToks;
  11029. newToks.addTokens (parsed, true);
  11030. tokenisedDTD.remove (i);
  11031. for (int j = newToks.size(); --j >= 0;)
  11032. tokenisedDTD.insert (i, newToks[j]);
  11033. }
  11034. }
  11035. }
  11036. needToLoadDTD = false;
  11037. }
  11038. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11039. {
  11040. if (tokenisedDTD[i] == entity)
  11041. {
  11042. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  11043. {
  11044. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  11045. // check for sub-entities..
  11046. int ampersand = ent.indexOfChar ('&');
  11047. while (ampersand >= 0)
  11048. {
  11049. const int semiColon = ent.indexOf (i + 1, ";");
  11050. if (semiColon < 0)
  11051. {
  11052. setLastError ("entity without terminating semi-colon", false);
  11053. break;
  11054. }
  11055. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  11056. ent = ent.substring (0, ampersand)
  11057. + resolved
  11058. + ent.substring (semiColon + 1);
  11059. ampersand = ent.indexOfChar (semiColon + 1, '&');
  11060. }
  11061. return ent;
  11062. }
  11063. }
  11064. }
  11065. setLastError ("unknown entity", true);
  11066. return entity;
  11067. }
  11068. const String XmlDocument::getParameterEntity (const String& entity)
  11069. {
  11070. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11071. {
  11072. if (tokenisedDTD[i] == entity)
  11073. {
  11074. if (tokenisedDTD [i - 1] == "%"
  11075. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  11076. {
  11077. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  11078. if (ent.equalsIgnoreCase ("system"))
  11079. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  11080. else
  11081. return ent.trim().unquoted();
  11082. }
  11083. }
  11084. }
  11085. return entity;
  11086. }
  11087. END_JUCE_NAMESPACE
  11088. /*** End of inlined file: juce_XmlDocument.cpp ***/
  11089. /*** Start of inlined file: juce_XmlElement.cpp ***/
  11090. BEGIN_JUCE_NAMESPACE
  11091. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  11092. : name (other.name),
  11093. value (other.value),
  11094. next (0)
  11095. {
  11096. }
  11097. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  11098. : name (name_),
  11099. value (value_),
  11100. next (0)
  11101. {
  11102. }
  11103. XmlElement::XmlElement (const String& tagName_) throw()
  11104. : tagName (tagName_),
  11105. firstChildElement (0),
  11106. nextElement (0),
  11107. attributes (0)
  11108. {
  11109. // the tag name mustn't be empty, or it'll look like a text element!
  11110. jassert (tagName_.containsNonWhitespaceChars())
  11111. // The tag can't contain spaces or other characters that would create invalid XML!
  11112. jassert (! tagName_.containsAnyOf (" <>/&"));
  11113. }
  11114. XmlElement::XmlElement (int /*dummy*/) throw()
  11115. : firstChildElement (0),
  11116. nextElement (0),
  11117. attributes (0)
  11118. {
  11119. }
  11120. XmlElement::XmlElement (const XmlElement& other) throw()
  11121. : tagName (other.tagName),
  11122. firstChildElement (0),
  11123. nextElement (0),
  11124. attributes (0)
  11125. {
  11126. copyChildrenAndAttributesFrom (other);
  11127. }
  11128. XmlElement& XmlElement::operator= (const XmlElement& other) throw()
  11129. {
  11130. if (this != &other)
  11131. {
  11132. removeAllAttributes();
  11133. deleteAllChildElements();
  11134. tagName = other.tagName;
  11135. copyChildrenAndAttributesFrom (other);
  11136. }
  11137. return *this;
  11138. }
  11139. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other) throw()
  11140. {
  11141. XmlElement* child = other.firstChildElement;
  11142. XmlElement* lastChild = 0;
  11143. while (child != 0)
  11144. {
  11145. XmlElement* const copiedChild = new XmlElement (*child);
  11146. if (lastChild != 0)
  11147. lastChild->nextElement = copiedChild;
  11148. else
  11149. firstChildElement = copiedChild;
  11150. lastChild = copiedChild;
  11151. child = child->nextElement;
  11152. }
  11153. const XmlAttributeNode* att = other.attributes;
  11154. XmlAttributeNode* lastAtt = 0;
  11155. while (att != 0)
  11156. {
  11157. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  11158. if (lastAtt != 0)
  11159. lastAtt->next = newAtt;
  11160. else
  11161. attributes = newAtt;
  11162. lastAtt = newAtt;
  11163. att = att->next;
  11164. }
  11165. }
  11166. XmlElement::~XmlElement() throw()
  11167. {
  11168. XmlElement* child = firstChildElement;
  11169. while (child != 0)
  11170. {
  11171. XmlElement* const nextChild = child->nextElement;
  11172. delete child;
  11173. child = nextChild;
  11174. }
  11175. XmlAttributeNode* att = attributes;
  11176. while (att != 0)
  11177. {
  11178. XmlAttributeNode* const nextAtt = att->next;
  11179. delete att;
  11180. att = nextAtt;
  11181. }
  11182. }
  11183. namespace XmlOutputFunctions
  11184. {
  11185. /*static bool isLegalXmlCharSlow (const juce_wchar character) throw()
  11186. {
  11187. if ((character >= 'a' && character <= 'z')
  11188. || (character >= 'A' && character <= 'Z')
  11189. || (character >= '0' && character <= '9'))
  11190. return true;
  11191. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}";
  11192. do
  11193. {
  11194. if (((juce_wchar) (uint8) *t) == character)
  11195. return true;
  11196. }
  11197. while (*++t != 0);
  11198. return false;
  11199. }
  11200. static void generateLegalCharConstants()
  11201. {
  11202. uint8 n[32];
  11203. zerostruct (n);
  11204. for (int i = 0; i < 256; ++i)
  11205. if (isLegalXmlCharSlow (i))
  11206. n[i >> 3] |= (1 << (i & 7));
  11207. String s;
  11208. for (int i = 0; i < 32; ++i)
  11209. s << (int) n[i] << ", ";
  11210. DBG (s);
  11211. }*/
  11212. static bool isLegalXmlChar (const uint32 c) throw()
  11213. {
  11214. static const unsigned char legalChars[] = { 0, 0, 0, 0, 171, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 111 };
  11215. return c < sizeof (legalChars) * 8
  11216. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  11217. }
  11218. static void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  11219. {
  11220. const juce_wchar* t = text;
  11221. for (;;)
  11222. {
  11223. const juce_wchar character = *t++;
  11224. if (character == 0)
  11225. {
  11226. break;
  11227. }
  11228. else if (isLegalXmlChar ((uint32) character))
  11229. {
  11230. outputStream << (char) character;
  11231. }
  11232. else
  11233. {
  11234. switch (character)
  11235. {
  11236. case '&': outputStream << "&amp;"; break;
  11237. case '"': outputStream << "&quot;"; break;
  11238. case '>': outputStream << "&gt;"; break;
  11239. case '<': outputStream << "&lt;"; break;
  11240. case '\n':
  11241. if (changeNewLines)
  11242. outputStream << "&#10;";
  11243. else
  11244. outputStream << (char) character;
  11245. break;
  11246. case '\r':
  11247. if (changeNewLines)
  11248. outputStream << "&#13;";
  11249. else
  11250. outputStream << (char) character;
  11251. break;
  11252. default:
  11253. outputStream << "&#" << ((int) (unsigned int) character) << ';';
  11254. break;
  11255. }
  11256. }
  11257. }
  11258. }
  11259. static void writeSpaces (OutputStream& out, int numSpaces)
  11260. {
  11261. if (numSpaces > 0)
  11262. {
  11263. const char* const blanks = " ";
  11264. const int blankSize = (int) sizeof (blanks) - 1;
  11265. while (numSpaces > blankSize)
  11266. {
  11267. out.write (blanks, blankSize);
  11268. numSpaces -= blankSize;
  11269. }
  11270. out.write (blanks, numSpaces);
  11271. }
  11272. }
  11273. }
  11274. void XmlElement::writeElementAsText (OutputStream& outputStream,
  11275. const int indentationLevel,
  11276. const int lineWrapLength) const
  11277. {
  11278. using namespace XmlOutputFunctions;
  11279. writeSpaces (outputStream, indentationLevel);
  11280. if (! isTextElement())
  11281. {
  11282. outputStream.writeByte ('<');
  11283. outputStream << tagName;
  11284. const int attIndent = indentationLevel + tagName.length() + 1;
  11285. int lineLen = 0;
  11286. const XmlAttributeNode* att = attributes;
  11287. while (att != 0)
  11288. {
  11289. if (lineLen > lineWrapLength && indentationLevel >= 0)
  11290. {
  11291. outputStream.write ("\r\n", 2);
  11292. writeSpaces (outputStream, attIndent);
  11293. lineLen = 0;
  11294. }
  11295. const int64 startPos = outputStream.getPosition();
  11296. outputStream.writeByte (' ');
  11297. outputStream << att->name;
  11298. outputStream.write ("=\"", 2);
  11299. escapeIllegalXmlChars (outputStream, att->value, true);
  11300. outputStream.writeByte ('"');
  11301. lineLen += (int) (outputStream.getPosition() - startPos);
  11302. att = att->next;
  11303. }
  11304. if (firstChildElement != 0)
  11305. {
  11306. XmlElement* child = firstChildElement;
  11307. if (child->nextElement == 0 && child->isTextElement())
  11308. {
  11309. outputStream.writeByte ('>');
  11310. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11311. }
  11312. else
  11313. {
  11314. if (indentationLevel >= 0)
  11315. outputStream.write (">\r\n", 3);
  11316. else
  11317. outputStream.writeByte ('>');
  11318. bool lastWasTextNode = false;
  11319. while (child != 0)
  11320. {
  11321. if (child->isTextElement())
  11322. {
  11323. if ((! lastWasTextNode) && (indentationLevel >= 0))
  11324. writeSpaces (outputStream, indentationLevel + 2);
  11325. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11326. lastWasTextNode = true;
  11327. }
  11328. else
  11329. {
  11330. if (indentationLevel >= 0)
  11331. {
  11332. if (lastWasTextNode)
  11333. outputStream.write ("\r\n", 2);
  11334. child->writeElementAsText (outputStream, indentationLevel + 2, lineWrapLength);
  11335. }
  11336. else
  11337. {
  11338. child->writeElementAsText (outputStream, indentationLevel, lineWrapLength);
  11339. }
  11340. lastWasTextNode = false;
  11341. }
  11342. child = child->nextElement;
  11343. }
  11344. if (indentationLevel >= 0)
  11345. {
  11346. if (lastWasTextNode)
  11347. outputStream.write ("\r\n", 2);
  11348. writeSpaces (outputStream, indentationLevel);
  11349. }
  11350. }
  11351. outputStream.write ("</", 2);
  11352. outputStream << tagName;
  11353. if (indentationLevel >= 0)
  11354. outputStream.write (">\r\n", 3);
  11355. else
  11356. outputStream.writeByte ('>');
  11357. }
  11358. else
  11359. {
  11360. if (indentationLevel >= 0)
  11361. outputStream.write ("/>\r\n", 4);
  11362. else
  11363. outputStream.write ("/>", 2);
  11364. }
  11365. }
  11366. else
  11367. {
  11368. if (indentationLevel >= 0)
  11369. writeSpaces (outputStream, indentationLevel + 2);
  11370. escapeIllegalXmlChars (outputStream, getText(), false);
  11371. }
  11372. }
  11373. const String XmlElement::createDocument (const String& dtdToUse,
  11374. const bool allOnOneLine,
  11375. const bool includeXmlHeader,
  11376. const String& encodingType,
  11377. const int lineWrapLength) const
  11378. {
  11379. MemoryOutputStream mem (2048, 4096);
  11380. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  11381. return mem.toUTF8();
  11382. }
  11383. void XmlElement::writeToStream (OutputStream& output,
  11384. const String& dtdToUse,
  11385. const bool allOnOneLine,
  11386. const bool includeXmlHeader,
  11387. const String& encodingType,
  11388. const int lineWrapLength) const
  11389. {
  11390. if (includeXmlHeader)
  11391. output << "<?xml version=\"1.0\" encoding=\"" << encodingType
  11392. << (allOnOneLine ? "\"?> " : "\"?>\r\n\r\n");
  11393. if (dtdToUse.isNotEmpty())
  11394. output << dtdToUse << (allOnOneLine ? " " : "\r\n");
  11395. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  11396. }
  11397. bool XmlElement::writeToFile (const File& file,
  11398. const String& dtdToUse,
  11399. const String& encodingType,
  11400. const int lineWrapLength) const
  11401. {
  11402. if (file.hasWriteAccess())
  11403. {
  11404. TemporaryFile tempFile (file);
  11405. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  11406. if (out != 0)
  11407. {
  11408. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  11409. out = 0;
  11410. return tempFile.overwriteTargetFileWithTemporary();
  11411. }
  11412. }
  11413. return false;
  11414. }
  11415. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  11416. {
  11417. #if JUCE_DEBUG
  11418. // if debugging, check that the case is actually the same, because
  11419. // valid xml is case-sensitive, and although this lets it pass, it's
  11420. // better not to..
  11421. if (tagName.equalsIgnoreCase (tagNameWanted))
  11422. {
  11423. jassert (tagName == tagNameWanted);
  11424. return true;
  11425. }
  11426. else
  11427. {
  11428. return false;
  11429. }
  11430. #else
  11431. return tagName.equalsIgnoreCase (tagNameWanted);
  11432. #endif
  11433. }
  11434. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  11435. {
  11436. XmlElement* e = nextElement;
  11437. while (e != 0 && ! e->hasTagName (requiredTagName))
  11438. e = e->nextElement;
  11439. return e;
  11440. }
  11441. int XmlElement::getNumAttributes() const throw()
  11442. {
  11443. const XmlAttributeNode* att = attributes;
  11444. int count = 0;
  11445. while (att != 0)
  11446. {
  11447. att = att->next;
  11448. ++count;
  11449. }
  11450. return count;
  11451. }
  11452. const String& XmlElement::getAttributeName (const int index) const throw()
  11453. {
  11454. const XmlAttributeNode* att = attributes;
  11455. int count = 0;
  11456. while (att != 0)
  11457. {
  11458. if (count == index)
  11459. return att->name;
  11460. att = att->next;
  11461. ++count;
  11462. }
  11463. return String::empty;
  11464. }
  11465. const String& XmlElement::getAttributeValue (const int index) const throw()
  11466. {
  11467. const XmlAttributeNode* att = attributes;
  11468. int count = 0;
  11469. while (att != 0)
  11470. {
  11471. if (count == index)
  11472. return att->value;
  11473. att = att->next;
  11474. ++count;
  11475. }
  11476. return String::empty;
  11477. }
  11478. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  11479. {
  11480. const XmlAttributeNode* att = attributes;
  11481. while (att != 0)
  11482. {
  11483. if (att->name.equalsIgnoreCase (attributeName))
  11484. return true;
  11485. att = att->next;
  11486. }
  11487. return false;
  11488. }
  11489. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  11490. {
  11491. const XmlAttributeNode* att = attributes;
  11492. while (att != 0)
  11493. {
  11494. if (att->name.equalsIgnoreCase (attributeName))
  11495. return att->value;
  11496. att = att->next;
  11497. }
  11498. return String::empty;
  11499. }
  11500. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  11501. {
  11502. const XmlAttributeNode* att = attributes;
  11503. while (att != 0)
  11504. {
  11505. if (att->name.equalsIgnoreCase (attributeName))
  11506. return att->value;
  11507. att = att->next;
  11508. }
  11509. return defaultReturnValue;
  11510. }
  11511. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  11512. {
  11513. const XmlAttributeNode* att = attributes;
  11514. while (att != 0)
  11515. {
  11516. if (att->name.equalsIgnoreCase (attributeName))
  11517. return att->value.getIntValue();
  11518. att = att->next;
  11519. }
  11520. return defaultReturnValue;
  11521. }
  11522. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  11523. {
  11524. const XmlAttributeNode* att = attributes;
  11525. while (att != 0)
  11526. {
  11527. if (att->name.equalsIgnoreCase (attributeName))
  11528. return att->value.getDoubleValue();
  11529. att = att->next;
  11530. }
  11531. return defaultReturnValue;
  11532. }
  11533. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  11534. {
  11535. const XmlAttributeNode* att = attributes;
  11536. while (att != 0)
  11537. {
  11538. if (att->name.equalsIgnoreCase (attributeName))
  11539. {
  11540. juce_wchar firstChar = att->value[0];
  11541. if (CharacterFunctions::isWhitespace (firstChar))
  11542. firstChar = att->value.trimStart() [0];
  11543. return firstChar == '1'
  11544. || firstChar == 't'
  11545. || firstChar == 'y'
  11546. || firstChar == 'T'
  11547. || firstChar == 'Y';
  11548. }
  11549. att = att->next;
  11550. }
  11551. return defaultReturnValue;
  11552. }
  11553. bool XmlElement::compareAttribute (const String& attributeName,
  11554. const String& stringToCompareAgainst,
  11555. const bool ignoreCase) const throw()
  11556. {
  11557. const XmlAttributeNode* att = attributes;
  11558. while (att != 0)
  11559. {
  11560. if (att->name.equalsIgnoreCase (attributeName))
  11561. {
  11562. if (ignoreCase)
  11563. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  11564. else
  11565. return att->value == stringToCompareAgainst;
  11566. }
  11567. att = att->next;
  11568. }
  11569. return false;
  11570. }
  11571. void XmlElement::setAttribute (const String& attributeName, const String& value)
  11572. {
  11573. #if JUCE_DEBUG
  11574. // check the identifier being passed in is legal..
  11575. const juce_wchar* t = attributeName;
  11576. while (*t != 0)
  11577. {
  11578. jassert (CharacterFunctions::isLetterOrDigit (*t)
  11579. || *t == '_'
  11580. || *t == '-'
  11581. || *t == ':');
  11582. ++t;
  11583. }
  11584. #endif
  11585. if (attributes == 0)
  11586. {
  11587. attributes = new XmlAttributeNode (attributeName, value);
  11588. }
  11589. else
  11590. {
  11591. XmlAttributeNode* att = attributes;
  11592. for (;;)
  11593. {
  11594. if (att->name.equalsIgnoreCase (attributeName))
  11595. {
  11596. att->value = value;
  11597. break;
  11598. }
  11599. else if (att->next == 0)
  11600. {
  11601. att->next = new XmlAttributeNode (attributeName, value);
  11602. break;
  11603. }
  11604. att = att->next;
  11605. }
  11606. }
  11607. }
  11608. void XmlElement::setAttribute (const String& attributeName, const int number)
  11609. {
  11610. setAttribute (attributeName, String (number));
  11611. }
  11612. void XmlElement::setAttribute (const String& attributeName, const double number)
  11613. {
  11614. setAttribute (attributeName, String (number));
  11615. }
  11616. void XmlElement::removeAttribute (const String& attributeName) throw()
  11617. {
  11618. XmlAttributeNode* att = attributes;
  11619. XmlAttributeNode* lastAtt = 0;
  11620. while (att != 0)
  11621. {
  11622. if (att->name.equalsIgnoreCase (attributeName))
  11623. {
  11624. if (lastAtt == 0)
  11625. attributes = att->next;
  11626. else
  11627. lastAtt->next = att->next;
  11628. delete att;
  11629. break;
  11630. }
  11631. lastAtt = att;
  11632. att = att->next;
  11633. }
  11634. }
  11635. void XmlElement::removeAllAttributes() throw()
  11636. {
  11637. while (attributes != 0)
  11638. {
  11639. XmlAttributeNode* const nextAtt = attributes->next;
  11640. delete attributes;
  11641. attributes = nextAtt;
  11642. }
  11643. }
  11644. int XmlElement::getNumChildElements() const throw()
  11645. {
  11646. int count = 0;
  11647. const XmlElement* child = firstChildElement;
  11648. while (child != 0)
  11649. {
  11650. ++count;
  11651. child = child->nextElement;
  11652. }
  11653. return count;
  11654. }
  11655. XmlElement* XmlElement::getChildElement (const int index) const throw()
  11656. {
  11657. int count = 0;
  11658. XmlElement* child = firstChildElement;
  11659. while (child != 0 && count < index)
  11660. {
  11661. child = child->nextElement;
  11662. ++count;
  11663. }
  11664. return child;
  11665. }
  11666. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  11667. {
  11668. XmlElement* child = firstChildElement;
  11669. while (child != 0)
  11670. {
  11671. if (child->hasTagName (childName))
  11672. break;
  11673. child = child->nextElement;
  11674. }
  11675. return child;
  11676. }
  11677. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  11678. {
  11679. if (newNode != 0)
  11680. {
  11681. if (firstChildElement == 0)
  11682. {
  11683. firstChildElement = newNode;
  11684. }
  11685. else
  11686. {
  11687. XmlElement* child = firstChildElement;
  11688. while (child->nextElement != 0)
  11689. child = child->nextElement;
  11690. child->nextElement = newNode;
  11691. // if this is non-zero, then something's probably
  11692. // gone wrong..
  11693. jassert (newNode->nextElement == 0);
  11694. }
  11695. }
  11696. }
  11697. void XmlElement::insertChildElement (XmlElement* const newNode,
  11698. int indexToInsertAt) throw()
  11699. {
  11700. if (newNode != 0)
  11701. {
  11702. removeChildElement (newNode, false);
  11703. if (indexToInsertAt == 0)
  11704. {
  11705. newNode->nextElement = firstChildElement;
  11706. firstChildElement = newNode;
  11707. }
  11708. else
  11709. {
  11710. if (firstChildElement == 0)
  11711. {
  11712. firstChildElement = newNode;
  11713. }
  11714. else
  11715. {
  11716. if (indexToInsertAt < 0)
  11717. indexToInsertAt = std::numeric_limits<int>::max();
  11718. XmlElement* child = firstChildElement;
  11719. while (child->nextElement != 0 && --indexToInsertAt > 0)
  11720. child = child->nextElement;
  11721. newNode->nextElement = child->nextElement;
  11722. child->nextElement = newNode;
  11723. }
  11724. }
  11725. }
  11726. }
  11727. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  11728. {
  11729. XmlElement* const newElement = new XmlElement (childTagName);
  11730. addChildElement (newElement);
  11731. return newElement;
  11732. }
  11733. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  11734. XmlElement* const newNode) throw()
  11735. {
  11736. if (newNode != 0)
  11737. {
  11738. XmlElement* child = firstChildElement;
  11739. XmlElement* previousNode = 0;
  11740. while (child != 0)
  11741. {
  11742. if (child == currentChildElement)
  11743. {
  11744. if (child != newNode)
  11745. {
  11746. if (previousNode == 0)
  11747. firstChildElement = newNode;
  11748. else
  11749. previousNode->nextElement = newNode;
  11750. newNode->nextElement = child->nextElement;
  11751. delete child;
  11752. }
  11753. return true;
  11754. }
  11755. previousNode = child;
  11756. child = child->nextElement;
  11757. }
  11758. }
  11759. return false;
  11760. }
  11761. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  11762. const bool shouldDeleteTheChild) throw()
  11763. {
  11764. if (childToRemove != 0)
  11765. {
  11766. if (firstChildElement == childToRemove)
  11767. {
  11768. firstChildElement = childToRemove->nextElement;
  11769. childToRemove->nextElement = 0;
  11770. }
  11771. else
  11772. {
  11773. XmlElement* child = firstChildElement;
  11774. XmlElement* last = 0;
  11775. while (child != 0)
  11776. {
  11777. if (child == childToRemove)
  11778. {
  11779. if (last == 0)
  11780. firstChildElement = child->nextElement;
  11781. else
  11782. last->nextElement = child->nextElement;
  11783. childToRemove->nextElement = 0;
  11784. break;
  11785. }
  11786. last = child;
  11787. child = child->nextElement;
  11788. }
  11789. }
  11790. if (shouldDeleteTheChild)
  11791. delete childToRemove;
  11792. }
  11793. }
  11794. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  11795. const bool ignoreOrderOfAttributes) const throw()
  11796. {
  11797. if (this != other)
  11798. {
  11799. if (other == 0 || tagName != other->tagName)
  11800. {
  11801. return false;
  11802. }
  11803. if (ignoreOrderOfAttributes)
  11804. {
  11805. int totalAtts = 0;
  11806. const XmlAttributeNode* att = attributes;
  11807. while (att != 0)
  11808. {
  11809. if (! other->compareAttribute (att->name, att->value))
  11810. return false;
  11811. att = att->next;
  11812. ++totalAtts;
  11813. }
  11814. if (totalAtts != other->getNumAttributes())
  11815. return false;
  11816. }
  11817. else
  11818. {
  11819. const XmlAttributeNode* thisAtt = attributes;
  11820. const XmlAttributeNode* otherAtt = other->attributes;
  11821. for (;;)
  11822. {
  11823. if (thisAtt == 0 || otherAtt == 0)
  11824. {
  11825. if (thisAtt == otherAtt) // both 0, so it's a match
  11826. break;
  11827. return false;
  11828. }
  11829. if (thisAtt->name != otherAtt->name
  11830. || thisAtt->value != otherAtt->value)
  11831. {
  11832. return false;
  11833. }
  11834. thisAtt = thisAtt->next;
  11835. otherAtt = otherAtt->next;
  11836. }
  11837. }
  11838. const XmlElement* thisChild = firstChildElement;
  11839. const XmlElement* otherChild = other->firstChildElement;
  11840. for (;;)
  11841. {
  11842. if (thisChild == 0 || otherChild == 0)
  11843. {
  11844. if (thisChild == otherChild) // both 0, so it's a match
  11845. break;
  11846. return false;
  11847. }
  11848. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  11849. return false;
  11850. thisChild = thisChild->nextElement;
  11851. otherChild = otherChild->nextElement;
  11852. }
  11853. }
  11854. return true;
  11855. }
  11856. void XmlElement::deleteAllChildElements() throw()
  11857. {
  11858. while (firstChildElement != 0)
  11859. {
  11860. XmlElement* const nextChild = firstChildElement->nextElement;
  11861. delete firstChildElement;
  11862. firstChildElement = nextChild;
  11863. }
  11864. }
  11865. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  11866. {
  11867. XmlElement* child = firstChildElement;
  11868. while (child != 0)
  11869. {
  11870. if (child->hasTagName (name))
  11871. {
  11872. XmlElement* const nextChild = child->nextElement;
  11873. removeChildElement (child, true);
  11874. child = nextChild;
  11875. }
  11876. else
  11877. {
  11878. child = child->nextElement;
  11879. }
  11880. }
  11881. }
  11882. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  11883. {
  11884. const XmlElement* child = firstChildElement;
  11885. while (child != 0)
  11886. {
  11887. if (child == possibleChild)
  11888. return true;
  11889. child = child->nextElement;
  11890. }
  11891. return false;
  11892. }
  11893. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  11894. {
  11895. if (this == elementToLookFor || elementToLookFor == 0)
  11896. return 0;
  11897. XmlElement* child = firstChildElement;
  11898. while (child != 0)
  11899. {
  11900. if (elementToLookFor == child)
  11901. return this;
  11902. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  11903. if (found != 0)
  11904. return found;
  11905. child = child->nextElement;
  11906. }
  11907. return 0;
  11908. }
  11909. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  11910. {
  11911. XmlElement* e = firstChildElement;
  11912. while (e != 0)
  11913. {
  11914. *elems++ = e;
  11915. e = e->nextElement;
  11916. }
  11917. }
  11918. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  11919. {
  11920. XmlElement* e = firstChildElement = elems[0];
  11921. for (int i = 1; i < num; ++i)
  11922. {
  11923. e->nextElement = elems[i];
  11924. e = e->nextElement;
  11925. }
  11926. e->nextElement = 0;
  11927. }
  11928. bool XmlElement::isTextElement() const throw()
  11929. {
  11930. return tagName.isEmpty();
  11931. }
  11932. static const juce_wchar* const juce_xmltextContentAttributeName = L"text";
  11933. const String XmlElement::getText() const throw()
  11934. {
  11935. jassert (isTextElement()); // you're trying to get the text from an element that
  11936. // isn't actually a text element.. If this contains text sub-nodes, you
  11937. // probably want to use getAllSubText instead.
  11938. return getStringAttribute (juce_xmltextContentAttributeName);
  11939. }
  11940. void XmlElement::setText (const String& newText) throw()
  11941. {
  11942. if (isTextElement())
  11943. {
  11944. setAttribute (juce_xmltextContentAttributeName, newText);
  11945. }
  11946. else
  11947. {
  11948. jassertfalse // you can only change the text in a text element, not a normal one.
  11949. }
  11950. }
  11951. const String XmlElement::getAllSubText() const throw()
  11952. {
  11953. String result;
  11954. String::Concatenator concatenator (result);
  11955. const XmlElement* child = firstChildElement;
  11956. while (child != 0)
  11957. {
  11958. if (child->isTextElement())
  11959. concatenator.append (child->getText());
  11960. child = child->nextElement;
  11961. }
  11962. return result;
  11963. }
  11964. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  11965. const String& defaultReturnValue) const throw()
  11966. {
  11967. const XmlElement* const child = getChildByName (childTagName);
  11968. if (child != 0)
  11969. return child->getAllSubText();
  11970. return defaultReturnValue;
  11971. }
  11972. XmlElement* XmlElement::createTextElement (const String& text) throw()
  11973. {
  11974. XmlElement* const e = new XmlElement ((int) 0);
  11975. e->setAttribute (juce_xmltextContentAttributeName, text);
  11976. return e;
  11977. }
  11978. void XmlElement::addTextElement (const String& text) throw()
  11979. {
  11980. addChildElement (createTextElement (text));
  11981. }
  11982. void XmlElement::deleteAllTextElements() throw()
  11983. {
  11984. XmlElement* child = firstChildElement;
  11985. while (child != 0)
  11986. {
  11987. XmlElement* const next = child->nextElement;
  11988. if (child->isTextElement())
  11989. removeChildElement (child, true);
  11990. child = next;
  11991. }
  11992. }
  11993. END_JUCE_NAMESPACE
  11994. /*** End of inlined file: juce_XmlElement.cpp ***/
  11995. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  11996. BEGIN_JUCE_NAMESPACE
  11997. ReadWriteLock::ReadWriteLock() throw()
  11998. : numWaitingWriters (0),
  11999. numWriters (0),
  12000. writerThreadId (0)
  12001. {
  12002. }
  12003. ReadWriteLock::~ReadWriteLock() throw()
  12004. {
  12005. jassert (readerThreads.size() == 0);
  12006. jassert (numWriters == 0);
  12007. }
  12008. void ReadWriteLock::enterRead() const throw()
  12009. {
  12010. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12011. const ScopedLock sl (accessLock);
  12012. for (;;)
  12013. {
  12014. jassert (readerThreads.size() % 2 == 0);
  12015. int i;
  12016. for (i = 0; i < readerThreads.size(); i += 2)
  12017. if (readerThreads.getUnchecked(i) == threadId)
  12018. break;
  12019. if (i < readerThreads.size()
  12020. || numWriters + numWaitingWriters == 0
  12021. || (threadId == writerThreadId && numWriters > 0))
  12022. {
  12023. if (i < readerThreads.size())
  12024. {
  12025. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  12026. }
  12027. else
  12028. {
  12029. readerThreads.add (threadId);
  12030. readerThreads.add ((Thread::ThreadID) 1);
  12031. }
  12032. return;
  12033. }
  12034. const ScopedUnlock ul (accessLock);
  12035. waitEvent.wait (100);
  12036. }
  12037. }
  12038. void ReadWriteLock::exitRead() const throw()
  12039. {
  12040. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12041. const ScopedLock sl (accessLock);
  12042. for (int i = 0; i < readerThreads.size(); i += 2)
  12043. {
  12044. if (readerThreads.getUnchecked(i) == threadId)
  12045. {
  12046. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  12047. if (newCount == 0)
  12048. {
  12049. readerThreads.removeRange (i, 2);
  12050. waitEvent.signal();
  12051. }
  12052. else
  12053. {
  12054. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  12055. }
  12056. return;
  12057. }
  12058. }
  12059. jassertfalse // unlocking a lock that wasn't locked..
  12060. }
  12061. void ReadWriteLock::enterWrite() const throw()
  12062. {
  12063. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12064. const ScopedLock sl (accessLock);
  12065. for (;;)
  12066. {
  12067. if (readerThreads.size() + numWriters == 0
  12068. || threadId == writerThreadId
  12069. || (readerThreads.size() == 2
  12070. && readerThreads.getUnchecked(0) == threadId))
  12071. {
  12072. writerThreadId = threadId;
  12073. ++numWriters;
  12074. break;
  12075. }
  12076. ++numWaitingWriters;
  12077. accessLock.exit();
  12078. waitEvent.wait (100);
  12079. accessLock.enter();
  12080. --numWaitingWriters;
  12081. }
  12082. }
  12083. bool ReadWriteLock::tryEnterWrite() const throw()
  12084. {
  12085. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12086. const ScopedLock sl (accessLock);
  12087. if (readerThreads.size() + numWriters == 0
  12088. || threadId == writerThreadId
  12089. || (readerThreads.size() == 2
  12090. && readerThreads.getUnchecked(0) == threadId))
  12091. {
  12092. writerThreadId = threadId;
  12093. ++numWriters;
  12094. return true;
  12095. }
  12096. return false;
  12097. }
  12098. void ReadWriteLock::exitWrite() const throw()
  12099. {
  12100. const ScopedLock sl (accessLock);
  12101. // check this thread actually had the lock..
  12102. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  12103. if (--numWriters == 0)
  12104. {
  12105. writerThreadId = 0;
  12106. waitEvent.signal();
  12107. }
  12108. }
  12109. END_JUCE_NAMESPACE
  12110. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  12111. /*** Start of inlined file: juce_Thread.cpp ***/
  12112. BEGIN_JUCE_NAMESPACE
  12113. // these functions are implemented in the platform-specific code.
  12114. void* juce_createThread (void* userData);
  12115. void juce_killThread (void* handle);
  12116. bool juce_setThreadPriority (void* handle, int priority);
  12117. void juce_setCurrentThreadName (const String& name);
  12118. #if JUCE_WIN32
  12119. void juce_CloseThreadHandle (void* handle);
  12120. #endif
  12121. void Thread::threadEntryPoint (Thread* const thread)
  12122. {
  12123. {
  12124. const ScopedLock sl (runningThreadsLock);
  12125. runningThreads.add (thread);
  12126. }
  12127. JUCE_TRY
  12128. {
  12129. thread->threadId_ = Thread::getCurrentThreadId();
  12130. if (thread->threadName_.isNotEmpty())
  12131. juce_setCurrentThreadName (thread->threadName_);
  12132. if (thread->startSuspensionEvent_.wait (10000))
  12133. {
  12134. if (thread->affinityMask_ != 0)
  12135. setCurrentThreadAffinityMask (thread->affinityMask_);
  12136. thread->run();
  12137. }
  12138. }
  12139. JUCE_CATCH_ALL_ASSERT
  12140. {
  12141. const ScopedLock sl (runningThreadsLock);
  12142. jassert (runningThreads.contains (thread));
  12143. runningThreads.removeValue (thread);
  12144. }
  12145. #if JUCE_WIN32
  12146. juce_CloseThreadHandle (thread->threadHandle_);
  12147. #endif
  12148. thread->threadHandle_ = 0;
  12149. thread->threadId_ = 0;
  12150. }
  12151. // used to wrap the incoming call from the platform-specific code
  12152. void JUCE_API juce_threadEntryPoint (void* userData)
  12153. {
  12154. Thread::threadEntryPoint (static_cast <Thread*> (userData));
  12155. }
  12156. Thread::Thread (const String& threadName)
  12157. : threadName_ (threadName),
  12158. threadHandle_ (0),
  12159. threadPriority_ (5),
  12160. threadId_ (0),
  12161. affinityMask_ (0),
  12162. threadShouldExit_ (false)
  12163. {
  12164. }
  12165. Thread::~Thread()
  12166. {
  12167. stopThread (100);
  12168. }
  12169. void Thread::startThread()
  12170. {
  12171. const ScopedLock sl (startStopLock);
  12172. threadShouldExit_ = false;
  12173. if (threadHandle_ == 0)
  12174. {
  12175. threadHandle_ = juce_createThread (this);
  12176. juce_setThreadPriority (threadHandle_, threadPriority_);
  12177. startSuspensionEvent_.signal();
  12178. }
  12179. }
  12180. void Thread::startThread (const int priority)
  12181. {
  12182. const ScopedLock sl (startStopLock);
  12183. if (threadHandle_ == 0)
  12184. {
  12185. threadPriority_ = priority;
  12186. startThread();
  12187. }
  12188. else
  12189. {
  12190. setPriority (priority);
  12191. }
  12192. }
  12193. bool Thread::isThreadRunning() const
  12194. {
  12195. return threadHandle_ != 0;
  12196. }
  12197. void Thread::signalThreadShouldExit()
  12198. {
  12199. threadShouldExit_ = true;
  12200. }
  12201. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  12202. {
  12203. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  12204. jassert (getThreadId() != getCurrentThreadId());
  12205. const int sleepMsPerIteration = 5;
  12206. int count = timeOutMilliseconds / sleepMsPerIteration;
  12207. while (isThreadRunning())
  12208. {
  12209. if (timeOutMilliseconds > 0 && --count < 0)
  12210. return false;
  12211. sleep (sleepMsPerIteration);
  12212. }
  12213. return true;
  12214. }
  12215. void Thread::stopThread (const int timeOutMilliseconds)
  12216. {
  12217. // agh! You can't stop the thread that's calling this method! How on earth
  12218. // would that work??
  12219. jassert (getCurrentThreadId() != getThreadId());
  12220. const ScopedLock sl (startStopLock);
  12221. if (isThreadRunning())
  12222. {
  12223. signalThreadShouldExit();
  12224. notify();
  12225. if (timeOutMilliseconds != 0)
  12226. waitForThreadToExit (timeOutMilliseconds);
  12227. if (isThreadRunning())
  12228. {
  12229. // very bad karma if this point is reached, as
  12230. // there are bound to be locks and events left in
  12231. // silly states when a thread is killed by force..
  12232. jassertfalse
  12233. Logger::writeToLog ("!! killing thread by force !!");
  12234. juce_killThread (threadHandle_);
  12235. threadHandle_ = 0;
  12236. threadId_ = 0;
  12237. const ScopedLock sl2 (runningThreadsLock);
  12238. runningThreads.removeValue (this);
  12239. }
  12240. }
  12241. }
  12242. bool Thread::setPriority (const int priority)
  12243. {
  12244. const ScopedLock sl (startStopLock);
  12245. const bool worked = juce_setThreadPriority (threadHandle_, priority);
  12246. if (worked)
  12247. threadPriority_ = priority;
  12248. return worked;
  12249. }
  12250. bool Thread::setCurrentThreadPriority (const int priority)
  12251. {
  12252. return juce_setThreadPriority (0, priority);
  12253. }
  12254. void Thread::setAffinityMask (const uint32 affinityMask)
  12255. {
  12256. affinityMask_ = affinityMask;
  12257. }
  12258. bool Thread::wait (const int timeOutMilliseconds) const
  12259. {
  12260. return defaultEvent_.wait (timeOutMilliseconds);
  12261. }
  12262. void Thread::notify() const
  12263. {
  12264. defaultEvent_.signal();
  12265. }
  12266. int Thread::getNumRunningThreads()
  12267. {
  12268. return runningThreads.size();
  12269. }
  12270. Thread* Thread::getCurrentThread()
  12271. {
  12272. const ThreadID thisId = getCurrentThreadId();
  12273. const ScopedLock sl (runningThreadsLock);
  12274. for (int i = runningThreads.size(); --i >= 0;)
  12275. {
  12276. Thread* const t = runningThreads.getUnchecked(i);
  12277. if (t->threadId_ == thisId)
  12278. return t;
  12279. }
  12280. return 0;
  12281. }
  12282. void Thread::stopAllThreads (const int timeOutMilliseconds)
  12283. {
  12284. {
  12285. const ScopedLock sl (runningThreadsLock);
  12286. for (int i = runningThreads.size(); --i >= 0;)
  12287. runningThreads.getUnchecked(i)->signalThreadShouldExit();
  12288. }
  12289. for (;;)
  12290. {
  12291. Thread* firstThread;
  12292. {
  12293. const ScopedLock sl (runningThreadsLock);
  12294. firstThread = runningThreads.getFirst();
  12295. }
  12296. if (firstThread == 0)
  12297. break;
  12298. firstThread->stopThread (timeOutMilliseconds);
  12299. }
  12300. }
  12301. Array<Thread*> Thread::runningThreads;
  12302. CriticalSection Thread::runningThreadsLock;
  12303. END_JUCE_NAMESPACE
  12304. /*** End of inlined file: juce_Thread.cpp ***/
  12305. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  12306. BEGIN_JUCE_NAMESPACE
  12307. ThreadPoolJob::ThreadPoolJob (const String& name)
  12308. : jobName (name),
  12309. pool (0),
  12310. shouldStop (false),
  12311. isActive (false),
  12312. shouldBeDeleted (false)
  12313. {
  12314. }
  12315. ThreadPoolJob::~ThreadPoolJob()
  12316. {
  12317. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  12318. // to remove it first!
  12319. jassert (pool == 0 || ! pool->contains (this));
  12320. }
  12321. const String ThreadPoolJob::getJobName() const
  12322. {
  12323. return jobName;
  12324. }
  12325. void ThreadPoolJob::setJobName (const String& newName)
  12326. {
  12327. jobName = newName;
  12328. }
  12329. void ThreadPoolJob::signalJobShouldExit()
  12330. {
  12331. shouldStop = true;
  12332. }
  12333. class ThreadPool::ThreadPoolThread : public Thread
  12334. {
  12335. public:
  12336. ThreadPoolThread (ThreadPool& pool_)
  12337. : Thread ("Pool"),
  12338. pool (pool_),
  12339. busy (false)
  12340. {
  12341. }
  12342. ~ThreadPoolThread()
  12343. {
  12344. }
  12345. void run()
  12346. {
  12347. while (! threadShouldExit())
  12348. {
  12349. if (! pool.runNextJob())
  12350. wait (500);
  12351. }
  12352. }
  12353. private:
  12354. ThreadPool& pool;
  12355. bool volatile busy;
  12356. ThreadPoolThread (const ThreadPoolThread&);
  12357. ThreadPoolThread& operator= (const ThreadPoolThread&);
  12358. };
  12359. ThreadPool::ThreadPool (const int numThreads,
  12360. const bool startThreadsOnlyWhenNeeded,
  12361. const int stopThreadsWhenNotUsedTimeoutMs)
  12362. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  12363. priority (5)
  12364. {
  12365. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  12366. for (int i = jmax (1, numThreads); --i >= 0;)
  12367. threads.add (new ThreadPoolThread (*this));
  12368. if (! startThreadsOnlyWhenNeeded)
  12369. for (int i = threads.size(); --i >= 0;)
  12370. threads.getUnchecked(i)->startThread (priority);
  12371. }
  12372. ThreadPool::~ThreadPool()
  12373. {
  12374. removeAllJobs (true, 4000);
  12375. int i;
  12376. for (i = threads.size(); --i >= 0;)
  12377. threads.getUnchecked(i)->signalThreadShouldExit();
  12378. for (i = threads.size(); --i >= 0;)
  12379. threads.getUnchecked(i)->stopThread (500);
  12380. }
  12381. void ThreadPool::addJob (ThreadPoolJob* const job)
  12382. {
  12383. jassert (job != 0);
  12384. jassert (job->pool == 0);
  12385. if (job->pool == 0)
  12386. {
  12387. job->pool = this;
  12388. job->shouldStop = false;
  12389. job->isActive = false;
  12390. {
  12391. const ScopedLock sl (lock);
  12392. jobs.add (job);
  12393. int numRunning = 0;
  12394. for (int i = threads.size(); --i >= 0;)
  12395. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  12396. ++numRunning;
  12397. if (numRunning < threads.size())
  12398. {
  12399. bool startedOne = false;
  12400. int n = 1000;
  12401. while (--n >= 0 && ! startedOne)
  12402. {
  12403. for (int i = threads.size(); --i >= 0;)
  12404. {
  12405. if (! threads.getUnchecked(i)->isThreadRunning())
  12406. {
  12407. threads.getUnchecked(i)->startThread (priority);
  12408. startedOne = true;
  12409. break;
  12410. }
  12411. }
  12412. if (! startedOne)
  12413. Thread::sleep (2);
  12414. }
  12415. }
  12416. }
  12417. for (int i = threads.size(); --i >= 0;)
  12418. threads.getUnchecked(i)->notify();
  12419. }
  12420. }
  12421. int ThreadPool::getNumJobs() const
  12422. {
  12423. return jobs.size();
  12424. }
  12425. ThreadPoolJob* ThreadPool::getJob (const int index) const
  12426. {
  12427. const ScopedLock sl (lock);
  12428. return jobs [index];
  12429. }
  12430. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  12431. {
  12432. const ScopedLock sl (lock);
  12433. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  12434. }
  12435. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  12436. {
  12437. const ScopedLock sl (lock);
  12438. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  12439. }
  12440. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  12441. const int timeOutMs) const
  12442. {
  12443. if (job != 0)
  12444. {
  12445. const uint32 start = Time::getMillisecondCounter();
  12446. while (contains (job))
  12447. {
  12448. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12449. return false;
  12450. jobFinishedSignal.wait (2);
  12451. }
  12452. }
  12453. return true;
  12454. }
  12455. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  12456. const bool interruptIfRunning,
  12457. const int timeOutMs)
  12458. {
  12459. bool dontWait = true;
  12460. if (job != 0)
  12461. {
  12462. const ScopedLock sl (lock);
  12463. if (jobs.contains (job))
  12464. {
  12465. if (job->isActive)
  12466. {
  12467. if (interruptIfRunning)
  12468. job->signalJobShouldExit();
  12469. dontWait = false;
  12470. }
  12471. else
  12472. {
  12473. jobs.removeValue (job);
  12474. }
  12475. }
  12476. }
  12477. return dontWait || waitForJobToFinish (job, timeOutMs);
  12478. }
  12479. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  12480. const int timeOutMs,
  12481. const bool deleteInactiveJobs,
  12482. ThreadPool::JobSelector* selectedJobsToRemove)
  12483. {
  12484. Array <ThreadPoolJob*> jobsToWaitFor;
  12485. {
  12486. const ScopedLock sl (lock);
  12487. for (int i = jobs.size(); --i >= 0;)
  12488. {
  12489. ThreadPoolJob* const job = jobs.getUnchecked(i);
  12490. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  12491. {
  12492. if (job->isActive)
  12493. {
  12494. jobsToWaitFor.add (job);
  12495. if (interruptRunningJobs)
  12496. job->signalJobShouldExit();
  12497. }
  12498. else
  12499. {
  12500. jobs.remove (i);
  12501. if (deleteInactiveJobs)
  12502. delete job;
  12503. }
  12504. }
  12505. }
  12506. }
  12507. const uint32 start = Time::getMillisecondCounter();
  12508. for (;;)
  12509. {
  12510. for (int i = jobsToWaitFor.size(); --i >= 0;)
  12511. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  12512. jobsToWaitFor.remove (i);
  12513. if (jobsToWaitFor.size() == 0)
  12514. break;
  12515. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12516. return false;
  12517. jobFinishedSignal.wait (20);
  12518. }
  12519. return true;
  12520. }
  12521. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  12522. {
  12523. StringArray s;
  12524. const ScopedLock sl (lock);
  12525. for (int i = 0; i < jobs.size(); ++i)
  12526. {
  12527. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  12528. if (job->isActive || ! onlyReturnActiveJobs)
  12529. s.add (job->getJobName());
  12530. }
  12531. return s;
  12532. }
  12533. bool ThreadPool::setThreadPriorities (const int newPriority)
  12534. {
  12535. bool ok = true;
  12536. if (priority != newPriority)
  12537. {
  12538. priority = newPriority;
  12539. for (int i = threads.size(); --i >= 0;)
  12540. if (! threads.getUnchecked(i)->setPriority (newPriority))
  12541. ok = false;
  12542. }
  12543. return ok;
  12544. }
  12545. bool ThreadPool::runNextJob()
  12546. {
  12547. ThreadPoolJob* job = 0;
  12548. {
  12549. const ScopedLock sl (lock);
  12550. for (int i = 0; i < jobs.size(); ++i)
  12551. {
  12552. job = jobs[i];
  12553. if (job != 0 && ! (job->isActive || job->shouldStop))
  12554. break;
  12555. job = 0;
  12556. }
  12557. if (job != 0)
  12558. job->isActive = true;
  12559. }
  12560. if (job != 0)
  12561. {
  12562. JUCE_TRY
  12563. {
  12564. ThreadPoolJob::JobStatus result = job->runJob();
  12565. lastJobEndTime = Time::getApproximateMillisecondCounter();
  12566. const ScopedLock sl (lock);
  12567. if (jobs.contains (job))
  12568. {
  12569. job->isActive = false;
  12570. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  12571. {
  12572. job->pool = 0;
  12573. job->shouldStop = true;
  12574. jobs.removeValue (job);
  12575. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  12576. delete job;
  12577. jobFinishedSignal.signal();
  12578. }
  12579. else
  12580. {
  12581. // move the job to the end of the queue if it wants another go
  12582. jobs.move (jobs.indexOf (job), -1);
  12583. }
  12584. }
  12585. }
  12586. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  12587. catch (...)
  12588. {
  12589. const ScopedLock sl (lock);
  12590. jobs.removeValue (job);
  12591. }
  12592. #endif
  12593. }
  12594. else
  12595. {
  12596. if (threadStopTimeout > 0
  12597. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  12598. {
  12599. const ScopedLock sl (lock);
  12600. if (jobs.size() == 0)
  12601. for (int i = threads.size(); --i >= 0;)
  12602. threads.getUnchecked(i)->signalThreadShouldExit();
  12603. }
  12604. else
  12605. {
  12606. return false;
  12607. }
  12608. }
  12609. return true;
  12610. }
  12611. END_JUCE_NAMESPACE
  12612. /*** End of inlined file: juce_ThreadPool.cpp ***/
  12613. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  12614. BEGIN_JUCE_NAMESPACE
  12615. TimeSliceThread::TimeSliceThread (const String& threadName)
  12616. : Thread (threadName),
  12617. index (0),
  12618. clientBeingCalled (0),
  12619. clientsChanged (false)
  12620. {
  12621. }
  12622. TimeSliceThread::~TimeSliceThread()
  12623. {
  12624. stopThread (2000);
  12625. }
  12626. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  12627. {
  12628. const ScopedLock sl (listLock);
  12629. clients.addIfNotAlreadyThere (client);
  12630. clientsChanged = true;
  12631. notify();
  12632. }
  12633. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  12634. {
  12635. const ScopedLock sl1 (listLock);
  12636. clientsChanged = true;
  12637. // if there's a chance we're in the middle of calling this client, we need to
  12638. // also lock the outer lock..
  12639. if (clientBeingCalled == client)
  12640. {
  12641. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  12642. const ScopedLock sl2 (callbackLock);
  12643. const ScopedLock sl3 (listLock);
  12644. clients.removeValue (client);
  12645. }
  12646. else
  12647. {
  12648. clients.removeValue (client);
  12649. }
  12650. }
  12651. int TimeSliceThread::getNumClients() const
  12652. {
  12653. return clients.size();
  12654. }
  12655. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  12656. {
  12657. const ScopedLock sl (listLock);
  12658. return clients [i];
  12659. }
  12660. void TimeSliceThread::run()
  12661. {
  12662. int numCallsSinceBusy = 0;
  12663. while (! threadShouldExit())
  12664. {
  12665. int timeToWait = 500;
  12666. {
  12667. const ScopedLock sl (callbackLock);
  12668. {
  12669. const ScopedLock sl2 (listLock);
  12670. if (clients.size() > 0)
  12671. {
  12672. index = (index + 1) % clients.size();
  12673. clientBeingCalled = clients [index];
  12674. }
  12675. else
  12676. {
  12677. index = 0;
  12678. clientBeingCalled = 0;
  12679. }
  12680. if (clientsChanged)
  12681. {
  12682. clientsChanged = false;
  12683. numCallsSinceBusy = 0;
  12684. }
  12685. }
  12686. if (clientBeingCalled != 0)
  12687. {
  12688. if (clientBeingCalled->useTimeSlice())
  12689. numCallsSinceBusy = 0;
  12690. else
  12691. ++numCallsSinceBusy;
  12692. if (numCallsSinceBusy >= clients.size())
  12693. timeToWait = 500;
  12694. else if (index == 0)
  12695. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  12696. else
  12697. timeToWait = 0;
  12698. }
  12699. }
  12700. if (timeToWait > 0)
  12701. wait (timeToWait);
  12702. }
  12703. }
  12704. END_JUCE_NAMESPACE
  12705. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  12706. #endif
  12707. #if JUCE_BUILD_MISC
  12708. /*** Start of inlined file: juce_ValueTree.cpp ***/
  12709. BEGIN_JUCE_NAMESPACE
  12710. class ValueTree::SetPropertyAction : public UndoableAction
  12711. {
  12712. public:
  12713. SetPropertyAction (const SharedObjectPtr& target_, const var::identifier& name_,
  12714. const var& newValue_, const var& oldValue_,
  12715. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  12716. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  12717. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  12718. {
  12719. }
  12720. ~SetPropertyAction() {}
  12721. bool perform()
  12722. {
  12723. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  12724. if (isDeletingProperty)
  12725. target->removeProperty (name, 0);
  12726. else
  12727. target->setProperty (name, newValue, 0);
  12728. return true;
  12729. }
  12730. bool undo()
  12731. {
  12732. if (isAddingNewProperty)
  12733. target->removeProperty (name, 0);
  12734. else
  12735. target->setProperty (name, oldValue, 0);
  12736. return true;
  12737. }
  12738. int getSizeInUnits()
  12739. {
  12740. return (int) sizeof (*this); //xxx should be more accurate
  12741. }
  12742. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  12743. {
  12744. if (! (isAddingNewProperty || isDeletingProperty))
  12745. {
  12746. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  12747. if (next != 0 && next->target == target && next->name == name
  12748. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  12749. {
  12750. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  12751. }
  12752. }
  12753. return 0;
  12754. }
  12755. private:
  12756. const SharedObjectPtr target;
  12757. const var::identifier name;
  12758. const var newValue;
  12759. var oldValue;
  12760. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  12761. SetPropertyAction (const SetPropertyAction&);
  12762. SetPropertyAction& operator= (const SetPropertyAction&);
  12763. };
  12764. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  12765. {
  12766. public:
  12767. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  12768. const SharedObjectPtr& newChild_)
  12769. : target (target_),
  12770. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  12771. childIndex (childIndex_),
  12772. isDeleting (newChild_ == 0)
  12773. {
  12774. jassert (child != 0);
  12775. }
  12776. ~AddOrRemoveChildAction() {}
  12777. bool perform()
  12778. {
  12779. if (isDeleting)
  12780. target->removeChild (childIndex, 0);
  12781. else
  12782. target->addChild (child, childIndex, 0);
  12783. return true;
  12784. }
  12785. bool undo()
  12786. {
  12787. if (isDeleting)
  12788. {
  12789. target->addChild (child, childIndex, 0);
  12790. }
  12791. else
  12792. {
  12793. // If you hit this, it seems that your object's state is getting confused - probably
  12794. // because you've interleaved some undoable and non-undoable operations?
  12795. jassert (childIndex < target->children.size());
  12796. target->removeChild (childIndex, 0);
  12797. }
  12798. return true;
  12799. }
  12800. int getSizeInUnits()
  12801. {
  12802. return (int) sizeof (*this); //xxx should be more accurate
  12803. }
  12804. private:
  12805. const SharedObjectPtr target, child;
  12806. const int childIndex;
  12807. const bool isDeleting;
  12808. AddOrRemoveChildAction (const AddOrRemoveChildAction&);
  12809. AddOrRemoveChildAction& operator= (const AddOrRemoveChildAction&);
  12810. };
  12811. class ValueTree::MoveChildAction : public UndoableAction
  12812. {
  12813. public:
  12814. MoveChildAction (const SharedObjectPtr& target_,
  12815. const int startIndex_, const int endIndex_)
  12816. : target (target_),
  12817. startIndex (startIndex_),
  12818. endIndex (endIndex_)
  12819. {
  12820. }
  12821. ~MoveChildAction() {}
  12822. bool perform()
  12823. {
  12824. target->moveChild (startIndex, endIndex, 0);
  12825. return true;
  12826. }
  12827. bool undo()
  12828. {
  12829. target->moveChild (endIndex, startIndex, 0);
  12830. return true;
  12831. }
  12832. int getSizeInUnits()
  12833. {
  12834. return (int) sizeof (*this); //xxx should be more accurate
  12835. }
  12836. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  12837. {
  12838. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  12839. if (next != 0 && next->target == target && next->child == child)
  12840. return new MoveChildAction (target, startIndex, next->endIndex);
  12841. return 0;
  12842. }
  12843. private:
  12844. const SharedObjectPtr target, child;
  12845. const int startIndex, endIndex;
  12846. MoveChildAction (const MoveChildAction&);
  12847. MoveChildAction& operator= (const MoveChildAction&);
  12848. };
  12849. ValueTree::SharedObject::SharedObject (const String& type_)
  12850. : type (type_), parent (0)
  12851. {
  12852. }
  12853. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  12854. : type (other.type), properties (other.properties), parent (0)
  12855. {
  12856. for (int i = 0; i < other.children.size(); ++i)
  12857. {
  12858. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  12859. child->parent = this;
  12860. children.add (child);
  12861. }
  12862. }
  12863. ValueTree::SharedObject::~SharedObject()
  12864. {
  12865. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  12866. for (int i = children.size(); --i >= 0;)
  12867. {
  12868. const SharedObjectPtr c (children.getUnchecked(i));
  12869. c->parent = 0;
  12870. children.remove (i);
  12871. c->sendParentChangeMessage();
  12872. }
  12873. }
  12874. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const var::identifier& property)
  12875. {
  12876. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  12877. {
  12878. ValueTree* const v = valueTreesWithListeners[i];
  12879. if (v != 0)
  12880. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  12881. }
  12882. }
  12883. void ValueTree::SharedObject::sendPropertyChangeMessage (const var::identifier& property)
  12884. {
  12885. ValueTree tree (this);
  12886. ValueTree::SharedObject* t = this;
  12887. while (t != 0)
  12888. {
  12889. t->sendPropertyChangeMessage (tree, property);
  12890. t = t->parent;
  12891. }
  12892. }
  12893. void ValueTree::SharedObject::sendChildChangeMessage (ValueTree& tree)
  12894. {
  12895. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  12896. {
  12897. ValueTree* const v = valueTreesWithListeners[i];
  12898. if (v != 0)
  12899. v->listeners.call (&ValueTree::Listener::valueTreeChildrenChanged, tree);
  12900. }
  12901. }
  12902. void ValueTree::SharedObject::sendChildChangeMessage()
  12903. {
  12904. ValueTree tree (this);
  12905. ValueTree::SharedObject* t = this;
  12906. while (t != 0)
  12907. {
  12908. t->sendChildChangeMessage (tree);
  12909. t = t->parent;
  12910. }
  12911. }
  12912. void ValueTree::SharedObject::sendParentChangeMessage()
  12913. {
  12914. ValueTree tree (this);
  12915. int i;
  12916. for (i = children.size(); --i >= 0;)
  12917. {
  12918. SharedObject* const t = children[i];
  12919. if (t != 0)
  12920. t->sendParentChangeMessage();
  12921. }
  12922. for (i = valueTreesWithListeners.size(); --i >= 0;)
  12923. {
  12924. ValueTree* const v = valueTreesWithListeners[i];
  12925. if (v != 0)
  12926. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  12927. }
  12928. }
  12929. const var& ValueTree::SharedObject::getProperty (const var::identifier& name) const
  12930. {
  12931. return properties [name];
  12932. }
  12933. const var ValueTree::SharedObject::getProperty (const var::identifier& name, const var& defaultReturnValue) const
  12934. {
  12935. return properties.getWithDefault (name, defaultReturnValue);
  12936. }
  12937. void ValueTree::SharedObject::setProperty (const var::identifier& name, const var& newValue, UndoManager* const undoManager)
  12938. {
  12939. if (undoManager == 0)
  12940. {
  12941. if (properties.set (name, newValue))
  12942. sendPropertyChangeMessage (name);
  12943. }
  12944. else
  12945. {
  12946. var* const existingValue = properties.getItem (name);
  12947. if (existingValue != 0)
  12948. {
  12949. if (*existingValue != newValue)
  12950. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  12951. }
  12952. else
  12953. {
  12954. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  12955. }
  12956. }
  12957. }
  12958. bool ValueTree::SharedObject::hasProperty (const var::identifier& name) const
  12959. {
  12960. return properties.contains (name);
  12961. }
  12962. void ValueTree::SharedObject::removeProperty (const var::identifier& name, UndoManager* const undoManager)
  12963. {
  12964. if (undoManager == 0)
  12965. {
  12966. if (properties.remove (name))
  12967. sendPropertyChangeMessage (name);
  12968. }
  12969. else
  12970. {
  12971. if (properties.contains (name))
  12972. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  12973. }
  12974. }
  12975. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  12976. {
  12977. if (undoManager == 0)
  12978. {
  12979. while (properties.size() > 0)
  12980. {
  12981. const var::identifier name (properties.getName (properties.size() - 1));
  12982. properties.remove (name);
  12983. sendPropertyChangeMessage (name);
  12984. }
  12985. }
  12986. else
  12987. {
  12988. for (int i = properties.size(); --i >= 0;)
  12989. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  12990. }
  12991. }
  12992. ValueTree ValueTree::SharedObject::getChildWithName (const String& typeToMatch) const
  12993. {
  12994. for (int i = 0; i < children.size(); ++i)
  12995. if (children.getUnchecked(i)->type == typeToMatch)
  12996. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  12997. return ValueTree::invalid;
  12998. }
  12999. ValueTree ValueTree::SharedObject::getChildWithProperty (const var::identifier& propertyName, const var& propertyValue) const
  13000. {
  13001. for (int i = 0; i < children.size(); ++i)
  13002. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  13003. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  13004. return ValueTree::invalid;
  13005. }
  13006. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  13007. {
  13008. const SharedObject* p = parent;
  13009. while (p != 0)
  13010. {
  13011. if (p == possibleParent)
  13012. return true;
  13013. p = p->parent;
  13014. }
  13015. return false;
  13016. }
  13017. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  13018. {
  13019. return children.indexOf (child.object);
  13020. }
  13021. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  13022. {
  13023. if (child != 0 && child->parent != this)
  13024. {
  13025. if (child != this && ! isAChildOf (child))
  13026. {
  13027. // You should always make sure that a child is removed from its previous parent before
  13028. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  13029. // undomanager should be used when removing it from its current parent..
  13030. jassert (child->parent == 0);
  13031. if (child->parent != 0)
  13032. {
  13033. jassert (child->parent->children.indexOf (child) >= 0);
  13034. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  13035. }
  13036. if (undoManager == 0)
  13037. {
  13038. children.insert (index, child);
  13039. child->parent = this;
  13040. sendChildChangeMessage();
  13041. child->sendParentChangeMessage();
  13042. }
  13043. else
  13044. {
  13045. if (index < 0)
  13046. index = children.size();
  13047. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  13048. }
  13049. }
  13050. else
  13051. {
  13052. // You're attempting to create a recursive loop! A node
  13053. // can't be a child of one of its own children!
  13054. jassertfalse
  13055. }
  13056. }
  13057. }
  13058. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  13059. {
  13060. const SharedObjectPtr child (children [childIndex]);
  13061. if (child != 0)
  13062. {
  13063. if (undoManager == 0)
  13064. {
  13065. children.remove (childIndex);
  13066. child->parent = 0;
  13067. sendChildChangeMessage();
  13068. child->sendParentChangeMessage();
  13069. }
  13070. else
  13071. {
  13072. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  13073. }
  13074. }
  13075. }
  13076. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  13077. {
  13078. while (children.size() > 0)
  13079. removeChild (children.size() - 1, undoManager);
  13080. }
  13081. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  13082. {
  13083. // The source index must be a valid index!
  13084. jassert (((unsigned int) currentIndex) < (unsigned int) children.size());
  13085. if (currentIndex != newIndex
  13086. && ((unsigned int) currentIndex) < (unsigned int) children.size())
  13087. {
  13088. if (undoManager == 0)
  13089. {
  13090. children.move (currentIndex, newIndex);
  13091. sendChildChangeMessage();
  13092. }
  13093. else
  13094. {
  13095. if (((unsigned int) newIndex) >= (unsigned int) children.size())
  13096. newIndex = children.size() - 1;
  13097. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  13098. }
  13099. }
  13100. }
  13101. ValueTree::ValueTree() throw()
  13102. : object (0)
  13103. {
  13104. }
  13105. const ValueTree ValueTree::invalid;
  13106. ValueTree::ValueTree (const String& type_)
  13107. : object (new ValueTree::SharedObject (type_))
  13108. {
  13109. jassert (type_.isNotEmpty()); // All objects should be given a sensible type name!
  13110. }
  13111. ValueTree::ValueTree (SharedObject* const object_)
  13112. : object (object_)
  13113. {
  13114. }
  13115. ValueTree::ValueTree (const ValueTree& other)
  13116. : object (other.object)
  13117. {
  13118. }
  13119. ValueTree& ValueTree::operator= (const ValueTree& other)
  13120. {
  13121. if (listeners.size() > 0)
  13122. {
  13123. if (object != 0)
  13124. object->valueTreesWithListeners.removeValue (this);
  13125. if (other.object != 0)
  13126. other.object->valueTreesWithListeners.add (this);
  13127. }
  13128. object = other.object;
  13129. return *this;
  13130. }
  13131. ValueTree::~ValueTree()
  13132. {
  13133. if (listeners.size() > 0 && object != 0)
  13134. object->valueTreesWithListeners.removeValue (this);
  13135. }
  13136. bool ValueTree::operator== (const ValueTree& other) const
  13137. {
  13138. return object == other.object;
  13139. }
  13140. bool ValueTree::operator!= (const ValueTree& other) const
  13141. {
  13142. return object != other.object;
  13143. }
  13144. ValueTree ValueTree::createCopy() const
  13145. {
  13146. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  13147. }
  13148. bool ValueTree::hasType (const String& typeName) const
  13149. {
  13150. return object != 0 && object->type == typeName;
  13151. }
  13152. const String ValueTree::getType() const
  13153. {
  13154. return object != 0 ? object->type : String::empty;
  13155. }
  13156. ValueTree ValueTree::getParent() const
  13157. {
  13158. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  13159. }
  13160. const var& ValueTree::operator[] (const var::identifier& name) const
  13161. {
  13162. return object == 0 ? var::null : object->getProperty (name);
  13163. }
  13164. const var& ValueTree::getProperty (const var::identifier& name) const
  13165. {
  13166. return object == 0 ? var::null : object->getProperty (name);
  13167. }
  13168. const var ValueTree::getProperty (const var::identifier& name, const var& defaultReturnValue) const
  13169. {
  13170. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  13171. }
  13172. void ValueTree::setProperty (const var::identifier& name, const var& newValue, UndoManager* const undoManager)
  13173. {
  13174. jassert (name.name.isNotEmpty());
  13175. if (object != 0 && name.name.isNotEmpty())
  13176. object->setProperty (name, newValue, undoManager);
  13177. }
  13178. bool ValueTree::hasProperty (const var::identifier& name) const
  13179. {
  13180. return object != 0 && object->hasProperty (name);
  13181. }
  13182. void ValueTree::removeProperty (const var::identifier& name, UndoManager* const undoManager)
  13183. {
  13184. if (object != 0)
  13185. object->removeProperty (name, undoManager);
  13186. }
  13187. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  13188. {
  13189. if (object != 0)
  13190. object->removeAllProperties (undoManager);
  13191. }
  13192. int ValueTree::getNumProperties() const
  13193. {
  13194. return object == 0 ? 0 : object->properties.size();
  13195. }
  13196. const var::identifier ValueTree::getPropertyName (const int index) const
  13197. {
  13198. return object == 0 ? var::identifier()
  13199. : object->properties.getName (index);
  13200. }
  13201. class ValueTreePropertyValueSource : public Value::ValueSource,
  13202. public ValueTree::Listener
  13203. {
  13204. public:
  13205. ValueTreePropertyValueSource (const ValueTree& tree_,
  13206. const var::identifier& property_,
  13207. UndoManager* const undoManager_)
  13208. : tree (tree_),
  13209. property (property_),
  13210. undoManager (undoManager_)
  13211. {
  13212. tree.addListener (this);
  13213. }
  13214. ~ValueTreePropertyValueSource()
  13215. {
  13216. tree.removeListener (this);
  13217. }
  13218. const var getValue() const
  13219. {
  13220. return tree [property];
  13221. }
  13222. void setValue (const var& newValue)
  13223. {
  13224. tree.setProperty (property, newValue, undoManager);
  13225. }
  13226. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const var::identifier& changedProperty)
  13227. {
  13228. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  13229. sendChangeMessage (false);
  13230. }
  13231. void valueTreeChildrenChanged (ValueTree&) {}
  13232. void valueTreeParentChanged (ValueTree&) {}
  13233. private:
  13234. ValueTree tree;
  13235. const var::identifier property;
  13236. UndoManager* const undoManager;
  13237. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  13238. };
  13239. Value ValueTree::getPropertyAsValue (const var::identifier& name, UndoManager* const undoManager) const
  13240. {
  13241. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  13242. }
  13243. int ValueTree::getNumChildren() const
  13244. {
  13245. return object == 0 ? 0 : object->children.size();
  13246. }
  13247. ValueTree ValueTree::getChild (int index) const
  13248. {
  13249. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  13250. }
  13251. ValueTree ValueTree::getChildWithName (const String& type) const
  13252. {
  13253. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  13254. }
  13255. ValueTree ValueTree::getChildWithProperty (const var::identifier& propertyName, const var& propertyValue) const
  13256. {
  13257. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  13258. }
  13259. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  13260. {
  13261. return object != 0 && object->isAChildOf (possibleParent.object);
  13262. }
  13263. int ValueTree::indexOf (const ValueTree& child) const
  13264. {
  13265. return object != 0 ? object->indexOf (child) : -1;
  13266. }
  13267. void ValueTree::addChild (ValueTree child, int index, UndoManager* const undoManager)
  13268. {
  13269. if (object != 0)
  13270. object->addChild (child.object, index, undoManager);
  13271. }
  13272. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  13273. {
  13274. if (object != 0)
  13275. object->removeChild (childIndex, undoManager);
  13276. }
  13277. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  13278. {
  13279. if (object != 0)
  13280. object->removeChild (object->children.indexOf (child.object), undoManager);
  13281. }
  13282. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  13283. {
  13284. if (object != 0)
  13285. object->removeAllChildren (undoManager);
  13286. }
  13287. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  13288. {
  13289. if (object != 0)
  13290. object->moveChild (currentIndex, newIndex, undoManager);
  13291. }
  13292. void ValueTree::addListener (Listener* listener)
  13293. {
  13294. if (listener != 0)
  13295. {
  13296. if (listeners.size() == 0 && object != 0)
  13297. object->valueTreesWithListeners.add (this);
  13298. listeners.add (listener);
  13299. }
  13300. }
  13301. void ValueTree::removeListener (Listener* listener)
  13302. {
  13303. listeners.remove (listener);
  13304. if (listeners.size() == 0 && object != 0)
  13305. object->valueTreesWithListeners.removeValue (this);
  13306. }
  13307. XmlElement* ValueTree::SharedObject::createXml() const
  13308. {
  13309. XmlElement* xml = new XmlElement (type);
  13310. int i;
  13311. for (i = 0; i < properties.size(); ++i)
  13312. {
  13313. var::identifier name (properties.getName(i));
  13314. const var& v = properties [name];
  13315. jassert (! v.isObject()); // DynamicObjects can't be stored as XML!
  13316. xml->setAttribute (name.name, v.toString());
  13317. }
  13318. for (i = 0; i < children.size(); ++i)
  13319. xml->addChildElement (children.getUnchecked(i)->createXml());
  13320. return xml;
  13321. }
  13322. XmlElement* ValueTree::createXml() const
  13323. {
  13324. return object != 0 ? object->createXml() : 0;
  13325. }
  13326. ValueTree ValueTree::fromXml (const XmlElement& xml)
  13327. {
  13328. ValueTree v (xml.getTagName());
  13329. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  13330. for (int i = 0; i < numAtts; ++i)
  13331. v.setProperty (xml.getAttributeName (i), var (xml.getAttributeValue (i)), 0);
  13332. forEachXmlChildElement (xml, e)
  13333. {
  13334. v.addChild (fromXml (*e), -1, 0);
  13335. }
  13336. return v;
  13337. }
  13338. void ValueTree::writeToStream (OutputStream& output)
  13339. {
  13340. output.writeString (getType());
  13341. const int numProps = getNumProperties();
  13342. output.writeCompressedInt (numProps);
  13343. int i;
  13344. for (i = 0; i < numProps; ++i)
  13345. {
  13346. const var::identifier name (getPropertyName(i));
  13347. output.writeString (name.name);
  13348. getProperty(name).writeToStream (output);
  13349. }
  13350. const int numChildren = getNumChildren();
  13351. output.writeCompressedInt (numChildren);
  13352. for (i = 0; i < numChildren; ++i)
  13353. getChild (i).writeToStream (output);
  13354. }
  13355. ValueTree ValueTree::readFromStream (InputStream& input)
  13356. {
  13357. const String type (input.readString());
  13358. if (type.isEmpty())
  13359. return ValueTree::invalid;
  13360. ValueTree v (type);
  13361. const int numProps = input.readCompressedInt();
  13362. if (numProps < 0)
  13363. {
  13364. jassertfalse // trying to read corrupted data!
  13365. return v;
  13366. }
  13367. int i;
  13368. for (i = 0; i < numProps; ++i)
  13369. {
  13370. const String name (input.readString());
  13371. jassert (name.isNotEmpty());
  13372. const var value (var::readFromStream (input));
  13373. v.setProperty (name, value, 0);
  13374. }
  13375. const int numChildren = input.readCompressedInt();
  13376. for (i = 0; i < numChildren; ++i)
  13377. v.addChild (readFromStream (input), -1, 0);
  13378. return v;
  13379. }
  13380. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  13381. {
  13382. MemoryInputStream in (data, numBytes, false);
  13383. return readFromStream (in);
  13384. }
  13385. END_JUCE_NAMESPACE
  13386. /*** End of inlined file: juce_ValueTree.cpp ***/
  13387. /*** Start of inlined file: juce_Value.cpp ***/
  13388. BEGIN_JUCE_NAMESPACE
  13389. Value::ValueSource::ValueSource()
  13390. {
  13391. }
  13392. Value::ValueSource::~ValueSource()
  13393. {
  13394. }
  13395. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  13396. {
  13397. if (synchronous)
  13398. {
  13399. for (int i = valuesWithListeners.size(); --i >= 0;)
  13400. {
  13401. Value* const v = valuesWithListeners[i];
  13402. if (v != 0)
  13403. v->callListeners();
  13404. }
  13405. }
  13406. else
  13407. {
  13408. triggerAsyncUpdate();
  13409. }
  13410. }
  13411. void Value::ValueSource::handleAsyncUpdate()
  13412. {
  13413. sendChangeMessage (true);
  13414. }
  13415. class SimpleValueSource : public Value::ValueSource
  13416. {
  13417. public:
  13418. SimpleValueSource()
  13419. {
  13420. }
  13421. SimpleValueSource (const var& initialValue)
  13422. : value (initialValue)
  13423. {
  13424. }
  13425. ~SimpleValueSource()
  13426. {
  13427. }
  13428. const var getValue() const
  13429. {
  13430. return value;
  13431. }
  13432. void setValue (const var& newValue)
  13433. {
  13434. if (newValue != value)
  13435. {
  13436. value = newValue;
  13437. sendChangeMessage (false);
  13438. }
  13439. }
  13440. private:
  13441. var value;
  13442. SimpleValueSource (const SimpleValueSource&);
  13443. SimpleValueSource& operator= (const SimpleValueSource&);
  13444. };
  13445. Value::Value()
  13446. : value (new SimpleValueSource())
  13447. {
  13448. }
  13449. Value::Value (ValueSource* const value_)
  13450. : value (value_)
  13451. {
  13452. jassert (value_ != 0);
  13453. }
  13454. Value::Value (const var& initialValue)
  13455. : value (new SimpleValueSource (initialValue))
  13456. {
  13457. }
  13458. Value::Value (const Value& other)
  13459. : value (other.value)
  13460. {
  13461. }
  13462. Value& Value::operator= (const Value& other)
  13463. {
  13464. value = other.value;
  13465. return *this;
  13466. }
  13467. Value::~Value()
  13468. {
  13469. if (listeners.size() > 0)
  13470. value->valuesWithListeners.removeValue (this);
  13471. }
  13472. const var Value::getValue() const
  13473. {
  13474. return value->getValue();
  13475. }
  13476. Value::operator const var() const
  13477. {
  13478. return getValue();
  13479. }
  13480. void Value::setValue (const var& newValue)
  13481. {
  13482. value->setValue (newValue);
  13483. }
  13484. const String Value::toString() const
  13485. {
  13486. return value->getValue().toString();
  13487. }
  13488. Value& Value::operator= (const var& newValue)
  13489. {
  13490. value->setValue (newValue);
  13491. return *this;
  13492. }
  13493. void Value::referTo (const Value& valueToReferTo)
  13494. {
  13495. if (valueToReferTo.value != value)
  13496. {
  13497. if (listeners.size() > 0)
  13498. {
  13499. value->valuesWithListeners.removeValue (this);
  13500. valueToReferTo.value->valuesWithListeners.add (this);
  13501. }
  13502. value = valueToReferTo.value;
  13503. callListeners();
  13504. }
  13505. }
  13506. bool Value::refersToSameSourceAs (const Value& other) const
  13507. {
  13508. return value == other.value;
  13509. }
  13510. bool Value::operator== (const Value& other) const
  13511. {
  13512. return value == other.value || value->getValue() == other.getValue();
  13513. }
  13514. bool Value::operator!= (const Value& other) const
  13515. {
  13516. return value != other.value && value->getValue() != other.getValue();
  13517. }
  13518. void Value::addListener (Listener* const listener)
  13519. {
  13520. if (listener != 0)
  13521. {
  13522. if (listeners.size() == 0)
  13523. value->valuesWithListeners.add (this);
  13524. listeners.add (listener);
  13525. }
  13526. }
  13527. void Value::removeListener (Listener* const listener)
  13528. {
  13529. listeners.remove (listener);
  13530. if (listeners.size() == 0)
  13531. value->valuesWithListeners.removeValue (this);
  13532. }
  13533. void Value::callListeners()
  13534. {
  13535. Value v (*this); // (create a copy in case this gets deleted by a callback)
  13536. listeners.call (&Listener::valueChanged, v);
  13537. }
  13538. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  13539. {
  13540. return stream << value.toString();
  13541. }
  13542. END_JUCE_NAMESPACE
  13543. /*** End of inlined file: juce_Value.cpp ***/
  13544. /*** Start of inlined file: juce_Application.cpp ***/
  13545. #if JUCE_MSVC
  13546. #pragma warning (push)
  13547. #pragma warning (disable: 4245 4514 4100)
  13548. #include <crtdbg.h>
  13549. #pragma warning (pop)
  13550. #endif
  13551. BEGIN_JUCE_NAMESPACE
  13552. void juce_setCurrentThreadName (const String& name);
  13553. static JUCEApplication* appInstance = 0;
  13554. JUCEApplication::JUCEApplication()
  13555. : appReturnValue (0),
  13556. stillInitialising (true)
  13557. {
  13558. }
  13559. JUCEApplication::~JUCEApplication()
  13560. {
  13561. if (appLock != 0)
  13562. {
  13563. appLock->exit();
  13564. appLock = 0;
  13565. }
  13566. }
  13567. JUCEApplication* JUCEApplication::getInstance() throw()
  13568. {
  13569. return appInstance;
  13570. }
  13571. bool JUCEApplication::isInitialising() const throw()
  13572. {
  13573. return stillInitialising;
  13574. }
  13575. const String JUCEApplication::getApplicationVersion()
  13576. {
  13577. return String::empty;
  13578. }
  13579. bool JUCEApplication::moreThanOneInstanceAllowed()
  13580. {
  13581. return true;
  13582. }
  13583. void JUCEApplication::anotherInstanceStarted (const String&)
  13584. {
  13585. }
  13586. void JUCEApplication::systemRequestedQuit()
  13587. {
  13588. quit();
  13589. }
  13590. void JUCEApplication::quit()
  13591. {
  13592. MessageManager::getInstance()->stopDispatchLoop();
  13593. }
  13594. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  13595. {
  13596. appReturnValue = newReturnValue;
  13597. }
  13598. void JUCEApplication::unhandledException (const std::exception*,
  13599. const String&,
  13600. const int)
  13601. {
  13602. jassertfalse
  13603. }
  13604. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  13605. const char* const sourceFile,
  13606. const int lineNumber)
  13607. {
  13608. if (appInstance != 0)
  13609. appInstance->unhandledException (e, sourceFile, lineNumber);
  13610. }
  13611. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  13612. {
  13613. return 0;
  13614. }
  13615. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  13616. {
  13617. commands.add (StandardApplicationCommandIDs::quit);
  13618. }
  13619. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  13620. {
  13621. if (commandID == StandardApplicationCommandIDs::quit)
  13622. {
  13623. result.setInfo (TRANS("Quit"),
  13624. TRANS("Quits the application"),
  13625. "Application",
  13626. 0);
  13627. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  13628. }
  13629. }
  13630. bool JUCEApplication::perform (const InvocationInfo& info)
  13631. {
  13632. if (info.commandID == StandardApplicationCommandIDs::quit)
  13633. {
  13634. systemRequestedQuit();
  13635. return true;
  13636. }
  13637. return false;
  13638. }
  13639. int JUCEApplication::main (String& commandLine, JUCEApplication* const app)
  13640. {
  13641. if (! app->initialiseApp (commandLine))
  13642. return 0;
  13643. // now loop until a quit message is received..
  13644. JUCE_TRY
  13645. {
  13646. MessageManager::getInstance()->runDispatchLoop();
  13647. }
  13648. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13649. catch (const std::exception& e)
  13650. {
  13651. app->unhandledException (&e, __FILE__, __LINE__);
  13652. }
  13653. catch (...)
  13654. {
  13655. app->unhandledException (0, __FILE__, __LINE__);
  13656. }
  13657. #endif
  13658. return shutdownAppAndClearUp();
  13659. }
  13660. bool JUCEApplication::initialiseApp (String& commandLine)
  13661. {
  13662. jassert (appInstance == 0);
  13663. appInstance = this;
  13664. commandLineParameters = commandLine.trim();
  13665. commandLine = String::empty;
  13666. initialiseJuce_GUI();
  13667. #if ! JUCE_IPHONE
  13668. jassert (appLock == 0); // initialiseApp must only be called once!
  13669. if (! moreThanOneInstanceAllowed())
  13670. {
  13671. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  13672. if (! appLock->enter(0))
  13673. {
  13674. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  13675. delete appInstance;
  13676. appInstance = 0;
  13677. DBG ("Another instance is running - quitting...");
  13678. return false;
  13679. }
  13680. }
  13681. #endif
  13682. // let the app do its setting-up..
  13683. initialise (commandLineParameters);
  13684. // register for broadcast new app messages
  13685. MessageManager::getInstance()->registerBroadcastListener (this);
  13686. stillInitialising = false;
  13687. return true;
  13688. }
  13689. int JUCEApplication::shutdownAppAndClearUp()
  13690. {
  13691. jassert (appInstance != 0);
  13692. ScopedPointer<JUCEApplication> app (appInstance);
  13693. int returnValue = 0;
  13694. MessageManager::getInstance()->deregisterBroadcastListener (static_cast <JUCEApplication*> (app));
  13695. static bool reentrancyCheck = false;
  13696. if (! reentrancyCheck)
  13697. {
  13698. reentrancyCheck = true;
  13699. JUCE_TRY
  13700. {
  13701. // give the app a chance to clean up..
  13702. app->shutdown();
  13703. }
  13704. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13705. catch (const std::exception& e)
  13706. {
  13707. app->unhandledException (&e, __FILE__, __LINE__);
  13708. }
  13709. catch (...)
  13710. {
  13711. app->unhandledException (0, __FILE__, __LINE__);
  13712. }
  13713. #endif
  13714. JUCE_TRY
  13715. {
  13716. shutdownJuce_GUI();
  13717. returnValue = app->getApplicationReturnValue();
  13718. appInstance = 0;
  13719. app = 0;
  13720. }
  13721. JUCE_CATCH_ALL_ASSERT
  13722. reentrancyCheck = false;
  13723. }
  13724. return returnValue;
  13725. }
  13726. #if JUCE_IPHONE
  13727. extern int juce_IPhoneMain (int argc, const char* argv[], JUCEApplication* app);
  13728. #endif
  13729. #if ! JUCE_WINDOWS
  13730. extern const char* juce_Argv0;
  13731. #endif
  13732. int JUCEApplication::main (int argc, const char* argv[], JUCEApplication* const newApp)
  13733. {
  13734. #if ! JUCE_WINDOWS
  13735. juce_Argv0 = argv[0];
  13736. #endif
  13737. #if JUCE_IPHONE
  13738. const ScopedAutoReleasePool pool;
  13739. return juce_IPhoneMain (argc, argv, newApp);
  13740. #else
  13741. #if JUCE_MAC
  13742. const ScopedAutoReleasePool pool;
  13743. #endif
  13744. String cmd;
  13745. for (int i = 1; i < argc; ++i)
  13746. cmd << argv[i] << ' ';
  13747. return JUCEApplication::main (cmd, newApp);
  13748. #endif
  13749. }
  13750. void JUCEApplication::actionListenerCallback (const String& message)
  13751. {
  13752. if (message.startsWith (getApplicationName() + "/"))
  13753. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  13754. }
  13755. static bool juceInitialisedGUI = false;
  13756. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI()
  13757. {
  13758. if (! juceInitialisedGUI)
  13759. {
  13760. #if JUCE_MAC || JUCE_IPHONE
  13761. const ScopedAutoReleasePool pool;
  13762. #endif
  13763. juceInitialisedGUI = true;
  13764. initialiseJuce_NonGUI();
  13765. MessageManager::getInstance();
  13766. LookAndFeel::setDefaultLookAndFeel (0);
  13767. juce_setCurrentThreadName ("Juce Message Thread");
  13768. #if JUCE_WINDOWS && JUCE_DEBUG
  13769. // This section is just for catching people who mess up their project settings and
  13770. // turn RTTI off..
  13771. try
  13772. {
  13773. TextButton tb (String::empty);
  13774. Component* c = &tb;
  13775. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  13776. c = dynamic_cast <Button*> (c);
  13777. }
  13778. catch (...)
  13779. {
  13780. // Ended up here? If so, TURN ON RTTI in your compiler settings!! And if you
  13781. // got as far as this catch statement, then why haven't you got exception catching
  13782. // turned on in the debugger???
  13783. jassertfalse
  13784. }
  13785. #endif
  13786. }
  13787. }
  13788. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI()
  13789. {
  13790. if (juceInitialisedGUI)
  13791. {
  13792. #if JUCE_MAC
  13793. const ScopedAutoReleasePool pool;
  13794. #endif
  13795. {
  13796. DeletedAtShutdown::deleteAll();
  13797. LookAndFeel::clearDefaultLookAndFeel();
  13798. }
  13799. delete MessageManager::getInstance();
  13800. shutdownJuce_NonGUI();
  13801. juceInitialisedGUI = false;
  13802. }
  13803. }
  13804. END_JUCE_NAMESPACE
  13805. /*** End of inlined file: juce_Application.cpp ***/
  13806. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  13807. BEGIN_JUCE_NAMESPACE
  13808. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  13809. : commandID (commandID_),
  13810. flags (0)
  13811. {
  13812. }
  13813. void ApplicationCommandInfo::setInfo (const String& shortName_,
  13814. const String& description_,
  13815. const String& categoryName_,
  13816. const int flags_) throw()
  13817. {
  13818. shortName = shortName_;
  13819. description = description_;
  13820. categoryName = categoryName_;
  13821. flags = flags_;
  13822. }
  13823. void ApplicationCommandInfo::setActive (const bool b) throw()
  13824. {
  13825. if (b)
  13826. flags &= ~isDisabled;
  13827. else
  13828. flags |= isDisabled;
  13829. }
  13830. void ApplicationCommandInfo::setTicked (const bool b) throw()
  13831. {
  13832. if (b)
  13833. flags |= isTicked;
  13834. else
  13835. flags &= ~isTicked;
  13836. }
  13837. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  13838. {
  13839. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  13840. }
  13841. END_JUCE_NAMESPACE
  13842. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  13843. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  13844. BEGIN_JUCE_NAMESPACE
  13845. ApplicationCommandManager::ApplicationCommandManager()
  13846. : firstTarget (0)
  13847. {
  13848. keyMappings = new KeyPressMappingSet (this);
  13849. Desktop::getInstance().addFocusChangeListener (this);
  13850. }
  13851. ApplicationCommandManager::~ApplicationCommandManager()
  13852. {
  13853. Desktop::getInstance().removeFocusChangeListener (this);
  13854. keyMappings = 0;
  13855. }
  13856. void ApplicationCommandManager::clearCommands()
  13857. {
  13858. commands.clear();
  13859. keyMappings->clearAllKeyPresses();
  13860. triggerAsyncUpdate();
  13861. }
  13862. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  13863. {
  13864. // zero isn't a valid command ID!
  13865. jassert (newCommand.commandID != 0);
  13866. // the name isn't optional!
  13867. jassert (newCommand.shortName.isNotEmpty());
  13868. if (getCommandForID (newCommand.commandID) == 0)
  13869. {
  13870. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  13871. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  13872. commands.add (newInfo);
  13873. keyMappings->resetToDefaultMapping (newCommand.commandID);
  13874. triggerAsyncUpdate();
  13875. }
  13876. else
  13877. {
  13878. // trying to re-register the same command with different parameters?
  13879. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  13880. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  13881. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  13882. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  13883. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  13884. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  13885. }
  13886. }
  13887. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  13888. {
  13889. if (target != 0)
  13890. {
  13891. Array <CommandID> commandIDs;
  13892. target->getAllCommands (commandIDs);
  13893. for (int i = 0; i < commandIDs.size(); ++i)
  13894. {
  13895. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  13896. target->getCommandInfo (info.commandID, info);
  13897. registerCommand (info);
  13898. }
  13899. }
  13900. }
  13901. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  13902. {
  13903. for (int i = commands.size(); --i >= 0;)
  13904. {
  13905. if (commands.getUnchecked (i)->commandID == commandID)
  13906. {
  13907. commands.remove (i);
  13908. triggerAsyncUpdate();
  13909. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  13910. for (int j = keys.size(); --j >= 0;)
  13911. keyMappings->removeKeyPress (keys.getReference (j));
  13912. }
  13913. }
  13914. }
  13915. void ApplicationCommandManager::commandStatusChanged()
  13916. {
  13917. triggerAsyncUpdate();
  13918. }
  13919. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  13920. {
  13921. for (int i = commands.size(); --i >= 0;)
  13922. if (commands.getUnchecked(i)->commandID == commandID)
  13923. return commands.getUnchecked(i);
  13924. return 0;
  13925. }
  13926. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  13927. {
  13928. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  13929. return (ci != 0) ? ci->shortName : String::empty;
  13930. }
  13931. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  13932. {
  13933. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  13934. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  13935. : String::empty;
  13936. }
  13937. const StringArray ApplicationCommandManager::getCommandCategories() const throw()
  13938. {
  13939. StringArray s;
  13940. for (int i = 0; i < commands.size(); ++i)
  13941. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  13942. return s;
  13943. }
  13944. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const throw()
  13945. {
  13946. Array <CommandID> results;
  13947. for (int i = 0; i < commands.size(); ++i)
  13948. if (commands.getUnchecked(i)->categoryName == categoryName)
  13949. results.add (commands.getUnchecked(i)->commandID);
  13950. return results;
  13951. }
  13952. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  13953. {
  13954. ApplicationCommandTarget::InvocationInfo info (commandID);
  13955. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  13956. return invoke (info, asynchronously);
  13957. }
  13958. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  13959. {
  13960. // This call isn't thread-safe for use from a non-UI thread without locking the message
  13961. // manager first..
  13962. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  13963. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  13964. if (target == 0)
  13965. return false;
  13966. ApplicationCommandInfo commandInfo (0);
  13967. target->getCommandInfo (info_.commandID, commandInfo);
  13968. ApplicationCommandTarget::InvocationInfo info (info_);
  13969. info.commandFlags = commandInfo.flags;
  13970. sendListenerInvokeCallback (info);
  13971. const bool ok = target->invoke (info, asynchronously);
  13972. commandStatusChanged();
  13973. return ok;
  13974. }
  13975. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  13976. {
  13977. return firstTarget != 0 ? firstTarget
  13978. : findDefaultComponentTarget();
  13979. }
  13980. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  13981. {
  13982. firstTarget = newTarget;
  13983. }
  13984. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  13985. ApplicationCommandInfo& upToDateInfo)
  13986. {
  13987. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  13988. if (target == 0)
  13989. target = JUCEApplication::getInstance();
  13990. if (target != 0)
  13991. target = target->getTargetForCommand (commandID);
  13992. if (target != 0)
  13993. target->getCommandInfo (commandID, upToDateInfo);
  13994. return target;
  13995. }
  13996. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  13997. {
  13998. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  13999. if (target == 0 && c != 0)
  14000. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  14001. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  14002. return target;
  14003. }
  14004. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  14005. {
  14006. Component* c = Component::getCurrentlyFocusedComponent();
  14007. if (c == 0)
  14008. {
  14009. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  14010. if (activeWindow != 0)
  14011. {
  14012. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  14013. if (c == 0)
  14014. c = activeWindow;
  14015. }
  14016. }
  14017. if (c == 0 && Process::isForegroundProcess())
  14018. {
  14019. // getting a bit desperate now - try all desktop comps..
  14020. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  14021. {
  14022. ApplicationCommandTarget* const target
  14023. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  14024. ->getPeer()->getLastFocusedSubcomponent());
  14025. if (target != 0)
  14026. return target;
  14027. }
  14028. }
  14029. if (c != 0)
  14030. {
  14031. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  14032. // if we're focused on a ResizableWindow, chances are that it's the content
  14033. // component that really should get the event. And if not, the event will
  14034. // still be passed up to the top level window anyway, so let's send it to the
  14035. // content comp.
  14036. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  14037. c = resizableWindow->getContentComponent();
  14038. ApplicationCommandTarget* const target = findTargetForComponent (c);
  14039. if (target != 0)
  14040. return target;
  14041. }
  14042. return JUCEApplication::getInstance();
  14043. }
  14044. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener) throw()
  14045. {
  14046. listeners.add (listener);
  14047. }
  14048. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener) throw()
  14049. {
  14050. listeners.remove (listener);
  14051. }
  14052. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  14053. {
  14054. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  14055. }
  14056. void ApplicationCommandManager::handleAsyncUpdate()
  14057. {
  14058. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  14059. }
  14060. void ApplicationCommandManager::globalFocusChanged (Component*)
  14061. {
  14062. commandStatusChanged();
  14063. }
  14064. END_JUCE_NAMESPACE
  14065. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  14066. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  14067. BEGIN_JUCE_NAMESPACE
  14068. ApplicationCommandTarget::ApplicationCommandTarget()
  14069. {
  14070. }
  14071. ApplicationCommandTarget::~ApplicationCommandTarget()
  14072. {
  14073. messageInvoker = 0;
  14074. }
  14075. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  14076. {
  14077. if (isCommandActive (info.commandID))
  14078. {
  14079. if (async)
  14080. {
  14081. if (messageInvoker == 0)
  14082. messageInvoker = new CommandTargetMessageInvoker (this);
  14083. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  14084. return true;
  14085. }
  14086. else
  14087. {
  14088. const bool success = perform (info);
  14089. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  14090. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  14091. // returns the command's info.
  14092. return success;
  14093. }
  14094. }
  14095. return false;
  14096. }
  14097. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  14098. {
  14099. Component* c = dynamic_cast <Component*> (this);
  14100. if (c != 0)
  14101. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  14102. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  14103. return 0;
  14104. }
  14105. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  14106. {
  14107. ApplicationCommandTarget* target = this;
  14108. int depth = 0;
  14109. while (target != 0)
  14110. {
  14111. Array <CommandID> commandIDs;
  14112. target->getAllCommands (commandIDs);
  14113. if (commandIDs.contains (commandID))
  14114. return target;
  14115. target = target->getNextCommandTarget();
  14116. ++depth;
  14117. jassert (depth < 100); // could be a recursive command chain??
  14118. jassert (target != this); // definitely a recursive command chain!
  14119. if (depth > 100 || target == this)
  14120. break;
  14121. }
  14122. if (target == 0)
  14123. {
  14124. target = JUCEApplication::getInstance();
  14125. if (target != 0)
  14126. {
  14127. Array <CommandID> commandIDs;
  14128. target->getAllCommands (commandIDs);
  14129. if (commandIDs.contains (commandID))
  14130. return target;
  14131. }
  14132. }
  14133. return 0;
  14134. }
  14135. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  14136. {
  14137. ApplicationCommandInfo info (commandID);
  14138. info.flags = ApplicationCommandInfo::isDisabled;
  14139. getCommandInfo (commandID, info);
  14140. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  14141. }
  14142. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  14143. {
  14144. ApplicationCommandTarget* target = this;
  14145. int depth = 0;
  14146. while (target != 0)
  14147. {
  14148. if (target->tryToInvoke (info, async))
  14149. return true;
  14150. target = target->getNextCommandTarget();
  14151. ++depth;
  14152. jassert (depth < 100); // could be a recursive command chain??
  14153. jassert (target != this); // definitely a recursive command chain!
  14154. if (depth > 100 || target == this)
  14155. break;
  14156. }
  14157. if (target == 0)
  14158. {
  14159. target = JUCEApplication::getInstance();
  14160. if (target != 0)
  14161. return target->tryToInvoke (info, async);
  14162. }
  14163. return false;
  14164. }
  14165. bool ApplicationCommandTarget::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. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_) throw()
  14172. : commandID (commandID_),
  14173. commandFlags (0),
  14174. invocationMethod (direct),
  14175. originatingComponent (0),
  14176. isKeyDown (false),
  14177. millisecsSinceKeyPressed (0)
  14178. {
  14179. }
  14180. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  14181. : owner (owner_)
  14182. {
  14183. }
  14184. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  14185. {
  14186. }
  14187. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  14188. {
  14189. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  14190. owner->tryToInvoke (*info, false);
  14191. }
  14192. END_JUCE_NAMESPACE
  14193. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  14194. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  14195. BEGIN_JUCE_NAMESPACE
  14196. juce_ImplementSingleton (ApplicationProperties)
  14197. ApplicationProperties::ApplicationProperties() throw()
  14198. : msBeforeSaving (3000),
  14199. options (PropertiesFile::storeAsBinary),
  14200. commonSettingsAreReadOnly (0)
  14201. {
  14202. }
  14203. ApplicationProperties::~ApplicationProperties()
  14204. {
  14205. closeFiles();
  14206. clearSingletonInstance();
  14207. }
  14208. void ApplicationProperties::setStorageParameters (const String& applicationName,
  14209. const String& fileNameSuffix,
  14210. const String& folderName_,
  14211. const int millisecondsBeforeSaving,
  14212. const int propertiesFileOptions) throw()
  14213. {
  14214. appName = applicationName;
  14215. fileSuffix = fileNameSuffix;
  14216. folderName = folderName_;
  14217. msBeforeSaving = millisecondsBeforeSaving;
  14218. options = propertiesFileOptions;
  14219. }
  14220. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  14221. const bool testCommonSettings,
  14222. const bool showWarningDialogOnFailure)
  14223. {
  14224. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  14225. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  14226. if (! (userOk && commonOk))
  14227. {
  14228. if (showWarningDialogOnFailure)
  14229. {
  14230. String filenames;
  14231. if (userProps != 0 && ! userOk)
  14232. filenames << '\n' << userProps->getFile().getFullPathName();
  14233. if (commonProps != 0 && ! commonOk)
  14234. filenames << '\n' << commonProps->getFile().getFullPathName();
  14235. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14236. appName + TRANS(" - Unable to save settings"),
  14237. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  14238. + appName + TRANS(" needs to be able to write to the following files:\n")
  14239. + filenames
  14240. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  14241. }
  14242. return false;
  14243. }
  14244. return true;
  14245. }
  14246. void ApplicationProperties::openFiles() throw()
  14247. {
  14248. // You need to call setStorageParameters() before trying to get hold of the
  14249. // properties!
  14250. jassert (appName.isNotEmpty());
  14251. if (appName.isNotEmpty())
  14252. {
  14253. if (userProps == 0)
  14254. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  14255. false, msBeforeSaving, options);
  14256. if (commonProps == 0)
  14257. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  14258. true, msBeforeSaving, options);
  14259. userProps->setFallbackPropertySet (commonProps);
  14260. }
  14261. }
  14262. PropertiesFile* ApplicationProperties::getUserSettings() throw()
  14263. {
  14264. if (userProps == 0)
  14265. openFiles();
  14266. return userProps;
  14267. }
  14268. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly) throw()
  14269. {
  14270. if (commonProps == 0)
  14271. openFiles();
  14272. if (returnUserPropsIfReadOnly)
  14273. {
  14274. if (commonSettingsAreReadOnly == 0)
  14275. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  14276. if (commonSettingsAreReadOnly > 0)
  14277. return userProps;
  14278. }
  14279. return commonProps;
  14280. }
  14281. bool ApplicationProperties::saveIfNeeded()
  14282. {
  14283. return (userProps == 0 || userProps->saveIfNeeded())
  14284. && (commonProps == 0 || commonProps->saveIfNeeded());
  14285. }
  14286. void ApplicationProperties::closeFiles()
  14287. {
  14288. userProps = 0;
  14289. commonProps = 0;
  14290. }
  14291. END_JUCE_NAMESPACE
  14292. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  14293. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  14294. BEGIN_JUCE_NAMESPACE
  14295. static VoidArray objectsToDelete;
  14296. static CriticalSection lock;
  14297. DeletedAtShutdown::DeletedAtShutdown()
  14298. {
  14299. const ScopedLock sl (lock);
  14300. objectsToDelete.add (this);
  14301. }
  14302. DeletedAtShutdown::~DeletedAtShutdown()
  14303. {
  14304. const ScopedLock sl (lock);
  14305. objectsToDelete.removeValue (this);
  14306. }
  14307. void DeletedAtShutdown::deleteAll()
  14308. {
  14309. // make a local copy of the array, so it can't get into a loop if something
  14310. // creates another DeletedAtShutdown object during its destructor.
  14311. VoidArray localCopy;
  14312. {
  14313. const ScopedLock sl (lock);
  14314. localCopy = objectsToDelete;
  14315. }
  14316. for (int i = localCopy.size(); --i >= 0;)
  14317. {
  14318. JUCE_TRY
  14319. {
  14320. DeletedAtShutdown* deletee = static_cast <DeletedAtShutdown*> (localCopy.getUnchecked(i));
  14321. // double-check that it's not already been deleted during another object's destructor.
  14322. {
  14323. const ScopedLock sl (lock);
  14324. if (! objectsToDelete.contains (deletee))
  14325. deletee = 0;
  14326. }
  14327. delete deletee;
  14328. }
  14329. JUCE_CATCH_EXCEPTION
  14330. }
  14331. // if no objects got re-created during shutdown, this should have been emptied by their
  14332. // destructors
  14333. jassert (objectsToDelete.size() == 0);
  14334. objectsToDelete.clear(); // just to make sure the array doesn't have any memory still allocated
  14335. }
  14336. END_JUCE_NAMESPACE
  14337. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  14338. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  14339. BEGIN_JUCE_NAMESPACE
  14340. namespace PropertyFileConstants
  14341. {
  14342. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  14343. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  14344. static const char* const fileTag = "PROPERTIES";
  14345. static const char* const valueTag = "VALUE";
  14346. static const char* const nameAttribute = "name";
  14347. static const char* const valueAttribute = "val";
  14348. }
  14349. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  14350. const int options_, InterProcessLock* const processLock_)
  14351. : PropertySet (ignoreCaseOfKeyNames),
  14352. file (f),
  14353. timerInterval (millisecondsBeforeSaving),
  14354. options (options_),
  14355. loadedOk (false),
  14356. needsWriting (false),
  14357. processLock (processLock_)
  14358. {
  14359. // You need to correctly specify just one storage format for the file
  14360. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  14361. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  14362. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  14363. ProcessScopedLock pl (createProcessLock());
  14364. if (pl != 0 && ! pl->isLocked())
  14365. return; // locking failure..
  14366. ScopedPointer<InputStream> fileStream (f.createInputStream());
  14367. if (fileStream != 0)
  14368. {
  14369. int magicNumber = fileStream->readInt();
  14370. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  14371. {
  14372. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  14373. magicNumber = PropertyFileConstants::magicNumber;
  14374. }
  14375. if (magicNumber == PropertyFileConstants::magicNumber)
  14376. {
  14377. loadedOk = true;
  14378. BufferedInputStream in (fileStream.release(), 2048, true);
  14379. int numValues = in.readInt();
  14380. while (--numValues >= 0 && ! in.isExhausted())
  14381. {
  14382. const String key (in.readString());
  14383. const String value (in.readString());
  14384. jassert (key.isNotEmpty());
  14385. if (key.isNotEmpty())
  14386. getAllProperties().set (key, value);
  14387. }
  14388. }
  14389. else
  14390. {
  14391. // Not a binary props file - let's see if it's XML..
  14392. fileStream = 0;
  14393. XmlDocument parser (f);
  14394. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  14395. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  14396. {
  14397. doc = parser.getDocumentElement();
  14398. if (doc != 0)
  14399. {
  14400. loadedOk = true;
  14401. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  14402. {
  14403. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  14404. if (name.isNotEmpty())
  14405. {
  14406. getAllProperties().set (name,
  14407. e->getFirstChildElement() != 0
  14408. ? e->getFirstChildElement()->createDocument (String::empty, true)
  14409. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  14410. }
  14411. }
  14412. }
  14413. else
  14414. {
  14415. // must be a pretty broken XML file we're trying to parse here,
  14416. // or a sign that this object needs an InterProcessLock,
  14417. // or just a failure reading the file. This last reason is why
  14418. // we don't jassertfalse here.
  14419. }
  14420. }
  14421. }
  14422. }
  14423. else
  14424. {
  14425. loadedOk = ! f.exists();
  14426. }
  14427. }
  14428. PropertiesFile::~PropertiesFile()
  14429. {
  14430. if (! saveIfNeeded())
  14431. jassertfalse;
  14432. }
  14433. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  14434. {
  14435. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  14436. }
  14437. bool PropertiesFile::saveIfNeeded()
  14438. {
  14439. const ScopedLock sl (getLock());
  14440. return (! needsWriting) || save();
  14441. }
  14442. bool PropertiesFile::needsToBeSaved() const
  14443. {
  14444. const ScopedLock sl (getLock());
  14445. return needsWriting;
  14446. }
  14447. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  14448. {
  14449. const ScopedLock sl (getLock());
  14450. needsWriting = needsToBeSaved_;
  14451. }
  14452. bool PropertiesFile::save()
  14453. {
  14454. const ScopedLock sl (getLock());
  14455. stopTimer();
  14456. if (file == File::nonexistent
  14457. || file.isDirectory()
  14458. || ! file.getParentDirectory().createDirectory())
  14459. return false;
  14460. if ((options & storeAsXML) != 0)
  14461. {
  14462. XmlElement doc (PropertyFileConstants::fileTag);
  14463. for (int i = 0; i < getAllProperties().size(); ++i)
  14464. {
  14465. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  14466. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  14467. // if the value seems to contain xml, store it as such..
  14468. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  14469. XmlElement* const childElement = xmlContent.getDocumentElement();
  14470. if (childElement != 0)
  14471. e->addChildElement (childElement);
  14472. else
  14473. e->setAttribute (PropertyFileConstants::valueAttribute,
  14474. getAllProperties().getAllValues() [i]);
  14475. }
  14476. ProcessScopedLock pl (createProcessLock());
  14477. if (pl != 0 && ! pl->isLocked())
  14478. return false; // locking failure..
  14479. if (doc.writeToFile (file, String::empty))
  14480. {
  14481. needsWriting = false;
  14482. return true;
  14483. }
  14484. }
  14485. else
  14486. {
  14487. ProcessScopedLock pl (createProcessLock());
  14488. if (pl != 0 && ! pl->isLocked())
  14489. return false; // locking failure..
  14490. TemporaryFile tempFile (file);
  14491. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  14492. if (out != 0)
  14493. {
  14494. if ((options & storeAsCompressedBinary) != 0)
  14495. {
  14496. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  14497. out->flush();
  14498. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  14499. }
  14500. else
  14501. {
  14502. // have you set up the storage option flags correctly?
  14503. jassert ((options & storeAsBinary) != 0);
  14504. out->writeInt (PropertyFileConstants::magicNumber);
  14505. }
  14506. const int numProperties = getAllProperties().size();
  14507. out->writeInt (numProperties);
  14508. for (int i = 0; i < numProperties; ++i)
  14509. {
  14510. out->writeString (getAllProperties().getAllKeys() [i]);
  14511. out->writeString (getAllProperties().getAllValues() [i]);
  14512. }
  14513. out = 0;
  14514. if (tempFile.overwriteTargetFileWithTemporary())
  14515. {
  14516. needsWriting = false;
  14517. return true;
  14518. }
  14519. }
  14520. }
  14521. return false;
  14522. }
  14523. void PropertiesFile::timerCallback()
  14524. {
  14525. saveIfNeeded();
  14526. }
  14527. void PropertiesFile::propertyChanged()
  14528. {
  14529. sendChangeMessage (this);
  14530. needsWriting = true;
  14531. if (timerInterval > 0)
  14532. startTimer (timerInterval);
  14533. else if (timerInterval == 0)
  14534. saveIfNeeded();
  14535. }
  14536. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  14537. const String& fileNameSuffix,
  14538. const String& folderName,
  14539. const bool commonToAllUsers)
  14540. {
  14541. // mustn't have illegal characters in this name..
  14542. jassert (applicationName == File::createLegalFileName (applicationName));
  14543. #if JUCE_MAC || JUCE_IPHONE
  14544. File dir (commonToAllUsers ? "/Library/Preferences"
  14545. : "~/Library/Preferences");
  14546. if (folderName.isNotEmpty())
  14547. dir = dir.getChildFile (folderName);
  14548. #endif
  14549. #ifdef JUCE_LINUX
  14550. const File dir ((commonToAllUsers ? "/var/" : "~/")
  14551. + (folderName.isNotEmpty() ? folderName
  14552. : ("." + applicationName)));
  14553. #endif
  14554. #if JUCE_WIN32
  14555. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  14556. : File::userApplicationDataDirectory));
  14557. if (dir == File::nonexistent)
  14558. return File::nonexistent;
  14559. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  14560. : applicationName);
  14561. #endif
  14562. return dir.getChildFile (applicationName)
  14563. .withFileExtension (fileNameSuffix);
  14564. }
  14565. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  14566. const String& fileNameSuffix,
  14567. const String& folderName,
  14568. const bool commonToAllUsers,
  14569. const int millisecondsBeforeSaving,
  14570. const int propertiesFileOptions,
  14571. InterProcessLock* processLock_)
  14572. {
  14573. const File file (getDefaultAppSettingsFile (applicationName,
  14574. fileNameSuffix,
  14575. folderName,
  14576. commonToAllUsers));
  14577. jassert (file != File::nonexistent);
  14578. if (file == File::nonexistent)
  14579. return 0;
  14580. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  14581. }
  14582. END_JUCE_NAMESPACE
  14583. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  14584. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  14585. BEGIN_JUCE_NAMESPACE
  14586. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  14587. const String& fileWildcard_,
  14588. const String& openFileDialogTitle_,
  14589. const String& saveFileDialogTitle_)
  14590. : changedSinceSave (false),
  14591. fileExtension (fileExtension_),
  14592. fileWildcard (fileWildcard_),
  14593. openFileDialogTitle (openFileDialogTitle_),
  14594. saveFileDialogTitle (saveFileDialogTitle_)
  14595. {
  14596. }
  14597. FileBasedDocument::~FileBasedDocument()
  14598. {
  14599. }
  14600. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  14601. {
  14602. if (changedSinceSave != hasChanged)
  14603. {
  14604. changedSinceSave = hasChanged;
  14605. sendChangeMessage (this);
  14606. }
  14607. }
  14608. void FileBasedDocument::changed()
  14609. {
  14610. changedSinceSave = true;
  14611. sendChangeMessage (this);
  14612. }
  14613. void FileBasedDocument::setFile (const File& newFile)
  14614. {
  14615. if (documentFile != newFile)
  14616. {
  14617. documentFile = newFile;
  14618. changed();
  14619. }
  14620. }
  14621. bool FileBasedDocument::loadFrom (const File& newFile,
  14622. const bool showMessageOnFailure)
  14623. {
  14624. MouseCursor::showWaitCursor();
  14625. const File oldFile (documentFile);
  14626. documentFile = newFile;
  14627. String error;
  14628. if (newFile.existsAsFile())
  14629. {
  14630. error = loadDocument (newFile);
  14631. if (error.isEmpty())
  14632. {
  14633. setChangedFlag (false);
  14634. MouseCursor::hideWaitCursor();
  14635. setLastDocumentOpened (newFile);
  14636. return true;
  14637. }
  14638. }
  14639. else
  14640. {
  14641. error = "The file doesn't exist";
  14642. }
  14643. documentFile = oldFile;
  14644. MouseCursor::hideWaitCursor();
  14645. if (showMessageOnFailure)
  14646. {
  14647. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14648. TRANS("Failed to open file..."),
  14649. TRANS("There was an error while trying to load the file:\n\n")
  14650. + newFile.getFullPathName()
  14651. + "\n\n"
  14652. + error);
  14653. }
  14654. return false;
  14655. }
  14656. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  14657. {
  14658. FileChooser fc (openFileDialogTitle,
  14659. getLastDocumentOpened(),
  14660. fileWildcard);
  14661. if (fc.browseForFileToOpen())
  14662. return loadFrom (fc.getResult(), showMessageOnFailure);
  14663. return false;
  14664. }
  14665. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  14666. const bool showMessageOnFailure)
  14667. {
  14668. return saveAs (documentFile,
  14669. false,
  14670. askUserForFileIfNotSpecified,
  14671. showMessageOnFailure);
  14672. }
  14673. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  14674. const bool warnAboutOverwritingExistingFiles,
  14675. const bool askUserForFileIfNotSpecified,
  14676. const bool showMessageOnFailure)
  14677. {
  14678. if (newFile == File::nonexistent)
  14679. {
  14680. if (askUserForFileIfNotSpecified)
  14681. {
  14682. return saveAsInteractive (true);
  14683. }
  14684. else
  14685. {
  14686. // can't save to an unspecified file
  14687. jassertfalse
  14688. return failedToWriteToFile;
  14689. }
  14690. }
  14691. if (warnAboutOverwritingExistingFiles && newFile.exists())
  14692. {
  14693. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  14694. TRANS("File already exists"),
  14695. TRANS("There's already a file called:\n\n")
  14696. + newFile.getFullPathName()
  14697. + TRANS("\n\nAre you sure you want to overwrite it?"),
  14698. TRANS("overwrite"),
  14699. TRANS("cancel")))
  14700. {
  14701. return userCancelledSave;
  14702. }
  14703. }
  14704. MouseCursor::showWaitCursor();
  14705. const File oldFile (documentFile);
  14706. documentFile = newFile;
  14707. String error (saveDocument (newFile));
  14708. if (error.isEmpty())
  14709. {
  14710. setChangedFlag (false);
  14711. MouseCursor::hideWaitCursor();
  14712. return savedOk;
  14713. }
  14714. documentFile = oldFile;
  14715. MouseCursor::hideWaitCursor();
  14716. if (showMessageOnFailure)
  14717. {
  14718. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14719. TRANS("Error writing to file..."),
  14720. TRANS("An error occurred while trying to save \"")
  14721. + getDocumentTitle()
  14722. + TRANS("\" to the file:\n\n")
  14723. + newFile.getFullPathName()
  14724. + "\n\n"
  14725. + error);
  14726. }
  14727. return failedToWriteToFile;
  14728. }
  14729. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  14730. {
  14731. if (! hasChangedSinceSaved())
  14732. return savedOk;
  14733. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  14734. TRANS("Closing document..."),
  14735. TRANS("Do you want to save the changes to \"")
  14736. + getDocumentTitle() + "\"?",
  14737. TRANS("save"),
  14738. TRANS("discard changes"),
  14739. TRANS("cancel"));
  14740. if (r == 1)
  14741. {
  14742. // save changes
  14743. return save (true, true);
  14744. }
  14745. else if (r == 2)
  14746. {
  14747. // discard changes
  14748. return savedOk;
  14749. }
  14750. return userCancelledSave;
  14751. }
  14752. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  14753. {
  14754. File f;
  14755. if (documentFile.existsAsFile())
  14756. f = documentFile;
  14757. else
  14758. f = getLastDocumentOpened();
  14759. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  14760. if (legalFilename.isEmpty())
  14761. legalFilename = "unnamed";
  14762. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  14763. f = f.getSiblingFile (legalFilename);
  14764. else
  14765. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  14766. f = f.withFileExtension (fileExtension)
  14767. .getNonexistentSibling (true);
  14768. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  14769. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  14770. {
  14771. setLastDocumentOpened (fc.getResult());
  14772. File chosen (fc.getResult());
  14773. if (chosen.getFileExtension().isEmpty())
  14774. {
  14775. chosen = chosen.withFileExtension (fileExtension);
  14776. if (chosen.exists())
  14777. {
  14778. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  14779. TRANS("File already exists"),
  14780. TRANS("There's already a file called:")
  14781. + "\n\n" + chosen.getFullPathName()
  14782. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  14783. TRANS("overwrite"),
  14784. TRANS("cancel")))
  14785. {
  14786. return userCancelledSave;
  14787. }
  14788. }
  14789. }
  14790. return saveAs (chosen, false, false, true);
  14791. }
  14792. return userCancelledSave;
  14793. }
  14794. END_JUCE_NAMESPACE
  14795. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  14796. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  14797. BEGIN_JUCE_NAMESPACE
  14798. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  14799. : maxNumberOfItems (10)
  14800. {
  14801. }
  14802. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  14803. {
  14804. }
  14805. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  14806. {
  14807. maxNumberOfItems = jmax (1, newMaxNumber);
  14808. while (getNumFiles() > maxNumberOfItems)
  14809. files.remove (getNumFiles() - 1);
  14810. }
  14811. int RecentlyOpenedFilesList::getNumFiles() const
  14812. {
  14813. return files.size();
  14814. }
  14815. const File RecentlyOpenedFilesList::getFile (const int index) const
  14816. {
  14817. return File (files [index]);
  14818. }
  14819. void RecentlyOpenedFilesList::clear()
  14820. {
  14821. files.clear();
  14822. }
  14823. void RecentlyOpenedFilesList::addFile (const File& file)
  14824. {
  14825. const String path (file.getFullPathName());
  14826. files.removeString (path, true);
  14827. files.insert (0, path);
  14828. setMaxNumberOfItems (maxNumberOfItems);
  14829. }
  14830. void RecentlyOpenedFilesList::removeNonExistentFiles()
  14831. {
  14832. for (int i = getNumFiles(); --i >= 0;)
  14833. if (! getFile(i).exists())
  14834. files.remove (i);
  14835. }
  14836. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  14837. const int baseItemId,
  14838. const bool showFullPaths,
  14839. const bool dontAddNonExistentFiles,
  14840. const File** filesToAvoid)
  14841. {
  14842. int num = 0;
  14843. for (int i = 0; i < getNumFiles(); ++i)
  14844. {
  14845. const File f (getFile(i));
  14846. if ((! dontAddNonExistentFiles) || f.exists())
  14847. {
  14848. bool needsAvoiding = false;
  14849. if (filesToAvoid != 0)
  14850. {
  14851. const File** avoid = filesToAvoid;
  14852. while (*avoid != 0)
  14853. {
  14854. if (f == **avoid)
  14855. {
  14856. needsAvoiding = true;
  14857. break;
  14858. }
  14859. ++avoid;
  14860. }
  14861. }
  14862. if (! needsAvoiding)
  14863. {
  14864. menuToAddTo.addItem (baseItemId + i,
  14865. showFullPaths ? f.getFullPathName()
  14866. : f.getFileName());
  14867. ++num;
  14868. }
  14869. }
  14870. }
  14871. return num;
  14872. }
  14873. const String RecentlyOpenedFilesList::toString() const
  14874. {
  14875. return files.joinIntoString ("\n");
  14876. }
  14877. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  14878. {
  14879. clear();
  14880. files.addLines (stringifiedVersion);
  14881. setMaxNumberOfItems (maxNumberOfItems);
  14882. }
  14883. END_JUCE_NAMESPACE
  14884. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  14885. /*** Start of inlined file: juce_UndoManager.cpp ***/
  14886. BEGIN_JUCE_NAMESPACE
  14887. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  14888. const int minimumTransactions)
  14889. : totalUnitsStored (0),
  14890. nextIndex (0),
  14891. newTransaction (true),
  14892. reentrancyCheck (false)
  14893. {
  14894. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  14895. minimumTransactions);
  14896. }
  14897. UndoManager::~UndoManager()
  14898. {
  14899. clearUndoHistory();
  14900. }
  14901. void UndoManager::clearUndoHistory()
  14902. {
  14903. transactions.clear();
  14904. transactionNames.clear();
  14905. totalUnitsStored = 0;
  14906. nextIndex = 0;
  14907. sendChangeMessage (this);
  14908. }
  14909. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  14910. {
  14911. return totalUnitsStored;
  14912. }
  14913. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  14914. const int minimumTransactions)
  14915. {
  14916. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  14917. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  14918. }
  14919. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  14920. {
  14921. if (command_ != 0)
  14922. {
  14923. ScopedPointer<UndoableAction> command (command_);
  14924. if (actionName.isNotEmpty())
  14925. currentTransactionName = actionName;
  14926. if (reentrancyCheck)
  14927. {
  14928. jassertfalse // don't call perform() recursively from the UndoableAction::perform() or
  14929. // undo() methods, or else these actions won't actually get done.
  14930. return false;
  14931. }
  14932. else if (command->perform())
  14933. {
  14934. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  14935. if (commandSet != 0 && ! newTransaction)
  14936. {
  14937. UndoableAction* lastAction = commandSet->getLast();
  14938. if (lastAction != 0)
  14939. {
  14940. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  14941. if (coalescedAction != 0)
  14942. {
  14943. command = coalescedAction;
  14944. totalUnitsStored -= lastAction->getSizeInUnits();
  14945. commandSet->removeLast();
  14946. }
  14947. }
  14948. }
  14949. else
  14950. {
  14951. commandSet = new OwnedArray<UndoableAction>();
  14952. transactions.insert (nextIndex, commandSet);
  14953. transactionNames.insert (nextIndex, currentTransactionName);
  14954. ++nextIndex;
  14955. }
  14956. totalUnitsStored += command->getSizeInUnits();
  14957. commandSet->add (command.release());
  14958. newTransaction = false;
  14959. while (nextIndex < transactions.size())
  14960. {
  14961. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  14962. for (int i = lastSet->size(); --i >= 0;)
  14963. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  14964. transactions.removeLast();
  14965. transactionNames.remove (transactionNames.size() - 1);
  14966. }
  14967. while (nextIndex > 0
  14968. && totalUnitsStored > maxNumUnitsToKeep
  14969. && transactions.size() > minimumTransactionsToKeep)
  14970. {
  14971. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  14972. for (int i = firstSet->size(); --i >= 0;)
  14973. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  14974. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  14975. transactions.remove (0);
  14976. transactionNames.remove (0);
  14977. --nextIndex;
  14978. }
  14979. sendChangeMessage (this);
  14980. return true;
  14981. }
  14982. }
  14983. return false;
  14984. }
  14985. void UndoManager::beginNewTransaction (const String& actionName)
  14986. {
  14987. newTransaction = true;
  14988. currentTransactionName = actionName;
  14989. }
  14990. void UndoManager::setCurrentTransactionName (const String& newName)
  14991. {
  14992. currentTransactionName = newName;
  14993. }
  14994. bool UndoManager::canUndo() const
  14995. {
  14996. return nextIndex > 0;
  14997. }
  14998. bool UndoManager::canRedo() const
  14999. {
  15000. return nextIndex < transactions.size();
  15001. }
  15002. const String UndoManager::getUndoDescription() const
  15003. {
  15004. return transactionNames [nextIndex - 1];
  15005. }
  15006. const String UndoManager::getRedoDescription() const
  15007. {
  15008. return transactionNames [nextIndex];
  15009. }
  15010. bool UndoManager::undo()
  15011. {
  15012. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15013. if (commandSet == 0)
  15014. return false;
  15015. reentrancyCheck = true;
  15016. bool failed = false;
  15017. for (int i = commandSet->size(); --i >= 0;)
  15018. {
  15019. if (! commandSet->getUnchecked(i)->undo())
  15020. {
  15021. jassertfalse
  15022. failed = true;
  15023. break;
  15024. }
  15025. }
  15026. reentrancyCheck = false;
  15027. if (failed)
  15028. clearUndoHistory();
  15029. else
  15030. --nextIndex;
  15031. beginNewTransaction();
  15032. sendChangeMessage (this);
  15033. return true;
  15034. }
  15035. bool UndoManager::redo()
  15036. {
  15037. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  15038. if (commandSet == 0)
  15039. return false;
  15040. reentrancyCheck = true;
  15041. bool failed = false;
  15042. for (int i = 0; i < commandSet->size(); ++i)
  15043. {
  15044. if (! commandSet->getUnchecked(i)->perform())
  15045. {
  15046. jassertfalse
  15047. failed = true;
  15048. break;
  15049. }
  15050. }
  15051. reentrancyCheck = false;
  15052. if (failed)
  15053. clearUndoHistory();
  15054. else
  15055. ++nextIndex;
  15056. beginNewTransaction();
  15057. sendChangeMessage (this);
  15058. return true;
  15059. }
  15060. bool UndoManager::undoCurrentTransactionOnly()
  15061. {
  15062. return newTransaction ? false : undo();
  15063. }
  15064. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  15065. {
  15066. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15067. if (commandSet != 0 && ! newTransaction)
  15068. {
  15069. for (int i = 0; i < commandSet->size(); ++i)
  15070. actionsFound.add (commandSet->getUnchecked(i));
  15071. }
  15072. }
  15073. int UndoManager::getNumActionsInCurrentTransaction() const
  15074. {
  15075. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15076. if (commandSet != 0 && ! newTransaction)
  15077. return commandSet->size();
  15078. return 0;
  15079. }
  15080. END_JUCE_NAMESPACE
  15081. /*** End of inlined file: juce_UndoManager.cpp ***/
  15082. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  15083. BEGIN_JUCE_NAMESPACE
  15084. static const char* const aiffFormatName = "AIFF file";
  15085. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  15086. class AiffAudioFormatReader : public AudioFormatReader
  15087. {
  15088. public:
  15089. int bytesPerFrame;
  15090. int64 dataChunkStart;
  15091. bool littleEndian;
  15092. AiffAudioFormatReader (InputStream* in)
  15093. : AudioFormatReader (in, TRANS (aiffFormatName))
  15094. {
  15095. if (input->readInt() == chunkName ("FORM"))
  15096. {
  15097. const int len = input->readIntBigEndian();
  15098. const int64 end = input->getPosition() + len;
  15099. const int nextType = input->readInt();
  15100. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  15101. {
  15102. bool hasGotVer = false;
  15103. bool hasGotData = false;
  15104. bool hasGotType = false;
  15105. while (input->getPosition() < end)
  15106. {
  15107. const int type = input->readInt();
  15108. const uint32 length = (uint32) input->readIntBigEndian();
  15109. const int64 chunkEnd = input->getPosition() + length;
  15110. if (type == chunkName ("FVER"))
  15111. {
  15112. hasGotVer = true;
  15113. const int ver = input->readIntBigEndian();
  15114. if (ver != 0 && ver != (int)0xa2805140)
  15115. break;
  15116. }
  15117. else if (type == chunkName ("COMM"))
  15118. {
  15119. hasGotType = true;
  15120. numChannels = (unsigned int)input->readShortBigEndian();
  15121. lengthInSamples = input->readIntBigEndian();
  15122. bitsPerSample = input->readShortBigEndian();
  15123. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  15124. unsigned char sampleRateBytes[10];
  15125. input->read (sampleRateBytes, 10);
  15126. const int byte0 = sampleRateBytes[0];
  15127. if ((byte0 & 0x80) != 0
  15128. || byte0 <= 0x3F || byte0 > 0x40
  15129. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  15130. break;
  15131. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  15132. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  15133. sampleRate = (int) sampRate;
  15134. if (length <= 18)
  15135. {
  15136. // some types don't have a chunk large enough to include a compression
  15137. // type, so assume it's just big-endian pcm
  15138. littleEndian = false;
  15139. }
  15140. else
  15141. {
  15142. const int compType = input->readInt();
  15143. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  15144. {
  15145. littleEndian = false;
  15146. }
  15147. else if (compType == chunkName ("sowt"))
  15148. {
  15149. littleEndian = true;
  15150. }
  15151. else
  15152. {
  15153. sampleRate = 0;
  15154. break;
  15155. }
  15156. }
  15157. }
  15158. else if (type == chunkName ("SSND"))
  15159. {
  15160. hasGotData = true;
  15161. const int offset = input->readIntBigEndian();
  15162. dataChunkStart = input->getPosition() + 4 + offset;
  15163. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  15164. }
  15165. else if ((hasGotVer && hasGotData && hasGotType)
  15166. || chunkEnd < input->getPosition()
  15167. || input->isExhausted())
  15168. {
  15169. break;
  15170. }
  15171. input->setPosition (chunkEnd);
  15172. }
  15173. }
  15174. }
  15175. }
  15176. ~AiffAudioFormatReader()
  15177. {
  15178. }
  15179. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  15180. int64 startSampleInFile, int numSamples)
  15181. {
  15182. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  15183. if (samplesAvailable < numSamples)
  15184. {
  15185. for (int i = numDestChannels; --i >= 0;)
  15186. if (destSamples[i] != 0)
  15187. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  15188. numSamples = (int) samplesAvailable;
  15189. }
  15190. if (numSamples <= 0)
  15191. return true;
  15192. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  15193. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  15194. char tempBuffer [tempBufSize];
  15195. while (numSamples > 0)
  15196. {
  15197. int* left = destSamples[0];
  15198. if (left != 0)
  15199. left += startOffsetInDestBuffer;
  15200. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  15201. if (right != 0)
  15202. right += startOffsetInDestBuffer;
  15203. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  15204. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  15205. if (bytesRead < numThisTime * bytesPerFrame)
  15206. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  15207. if (bitsPerSample == 16)
  15208. {
  15209. if (littleEndian)
  15210. {
  15211. const short* src = reinterpret_cast <const short*> (tempBuffer);
  15212. if (numChannels > 1)
  15213. {
  15214. if (left == 0)
  15215. {
  15216. for (int i = numThisTime; --i >= 0;)
  15217. {
  15218. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15219. ++src;
  15220. }
  15221. }
  15222. else if (right == 0)
  15223. {
  15224. for (int i = numThisTime; --i >= 0;)
  15225. {
  15226. ++src;
  15227. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15228. }
  15229. }
  15230. else
  15231. {
  15232. for (int i = numThisTime; --i >= 0;)
  15233. {
  15234. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15235. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15236. }
  15237. }
  15238. }
  15239. else
  15240. {
  15241. for (int i = numThisTime; --i >= 0;)
  15242. {
  15243. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15244. }
  15245. }
  15246. }
  15247. else
  15248. {
  15249. const char* src = tempBuffer;
  15250. if (numChannels > 1)
  15251. {
  15252. if (left == 0)
  15253. {
  15254. for (int i = numThisTime; --i >= 0;)
  15255. {
  15256. *right++ = ByteOrder::bigEndianShort (src) << 16;
  15257. src += 4;
  15258. }
  15259. }
  15260. else if (right == 0)
  15261. {
  15262. for (int i = numThisTime; --i >= 0;)
  15263. {
  15264. src += 2;
  15265. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15266. src += 2;
  15267. }
  15268. }
  15269. else
  15270. {
  15271. for (int i = numThisTime; --i >= 0;)
  15272. {
  15273. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15274. src += 2;
  15275. *right++ = ByteOrder::bigEndianShort (src) << 16;
  15276. src += 2;
  15277. }
  15278. }
  15279. }
  15280. else
  15281. {
  15282. for (int i = numThisTime; --i >= 0;)
  15283. {
  15284. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15285. src += 2;
  15286. }
  15287. }
  15288. }
  15289. }
  15290. else if (bitsPerSample == 24)
  15291. {
  15292. const char* src = (const char*)tempBuffer;
  15293. if (littleEndian)
  15294. {
  15295. if (numChannels > 1)
  15296. {
  15297. if (left == 0)
  15298. {
  15299. for (int i = numThisTime; --i >= 0;)
  15300. {
  15301. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  15302. src += 6;
  15303. }
  15304. }
  15305. else if (right == 0)
  15306. {
  15307. for (int i = numThisTime; --i >= 0;)
  15308. {
  15309. src += 3;
  15310. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15311. src += 3;
  15312. }
  15313. }
  15314. else
  15315. {
  15316. for (int i = numThisTime; --i >= 0;)
  15317. {
  15318. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15319. src += 3;
  15320. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  15321. src += 3;
  15322. }
  15323. }
  15324. }
  15325. else
  15326. {
  15327. for (int i = numThisTime; --i >= 0;)
  15328. {
  15329. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15330. src += 3;
  15331. }
  15332. }
  15333. }
  15334. else
  15335. {
  15336. if (numChannels > 1)
  15337. {
  15338. if (left == 0)
  15339. {
  15340. for (int i = numThisTime; --i >= 0;)
  15341. {
  15342. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  15343. src += 6;
  15344. }
  15345. }
  15346. else if (right == 0)
  15347. {
  15348. for (int i = numThisTime; --i >= 0;)
  15349. {
  15350. src += 3;
  15351. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15352. src += 3;
  15353. }
  15354. }
  15355. else
  15356. {
  15357. for (int i = numThisTime; --i >= 0;)
  15358. {
  15359. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15360. src += 3;
  15361. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  15362. src += 3;
  15363. }
  15364. }
  15365. }
  15366. else
  15367. {
  15368. for (int i = numThisTime; --i >= 0;)
  15369. {
  15370. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15371. src += 3;
  15372. }
  15373. }
  15374. }
  15375. }
  15376. else if (bitsPerSample == 32)
  15377. {
  15378. const unsigned int* src = reinterpret_cast <const unsigned int*> (tempBuffer);
  15379. unsigned int* l = reinterpret_cast <unsigned int*> (left);
  15380. unsigned int* r = reinterpret_cast <unsigned int*> (right);
  15381. if (littleEndian)
  15382. {
  15383. if (numChannels > 1)
  15384. {
  15385. if (l == 0)
  15386. {
  15387. for (int i = numThisTime; --i >= 0;)
  15388. {
  15389. ++src;
  15390. *r++ = ByteOrder::swapIfBigEndian (*src++);
  15391. }
  15392. }
  15393. else if (r == 0)
  15394. {
  15395. for (int i = numThisTime; --i >= 0;)
  15396. {
  15397. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15398. ++src;
  15399. }
  15400. }
  15401. else
  15402. {
  15403. for (int i = numThisTime; --i >= 0;)
  15404. {
  15405. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15406. *r++ = ByteOrder::swapIfBigEndian (*src++);
  15407. }
  15408. }
  15409. }
  15410. else
  15411. {
  15412. for (int i = numThisTime; --i >= 0;)
  15413. {
  15414. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15415. }
  15416. }
  15417. }
  15418. else
  15419. {
  15420. if (numChannels > 1)
  15421. {
  15422. if (l == 0)
  15423. {
  15424. for (int i = numThisTime; --i >= 0;)
  15425. {
  15426. ++src;
  15427. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  15428. }
  15429. }
  15430. else if (r == 0)
  15431. {
  15432. for (int i = numThisTime; --i >= 0;)
  15433. {
  15434. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15435. ++src;
  15436. }
  15437. }
  15438. else
  15439. {
  15440. for (int i = numThisTime; --i >= 0;)
  15441. {
  15442. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15443. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  15444. }
  15445. }
  15446. }
  15447. else
  15448. {
  15449. for (int i = numThisTime; --i >= 0;)
  15450. {
  15451. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15452. }
  15453. }
  15454. }
  15455. left = reinterpret_cast <int*> (l);
  15456. right = reinterpret_cast <int*> (r);
  15457. }
  15458. else if (bitsPerSample == 8)
  15459. {
  15460. const char* src = tempBuffer;
  15461. if (numChannels > 1)
  15462. {
  15463. if (left == 0)
  15464. {
  15465. for (int i = numThisTime; --i >= 0;)
  15466. {
  15467. *right++ = ((int) *src++) << 24;
  15468. ++src;
  15469. }
  15470. }
  15471. else if (right == 0)
  15472. {
  15473. for (int i = numThisTime; --i >= 0;)
  15474. {
  15475. ++src;
  15476. *left++ = ((int) *src++) << 24;
  15477. }
  15478. }
  15479. else
  15480. {
  15481. for (int i = numThisTime; --i >= 0;)
  15482. {
  15483. *left++ = ((int) *src++) << 24;
  15484. *right++ = ((int) *src++) << 24;
  15485. }
  15486. }
  15487. }
  15488. else
  15489. {
  15490. for (int i = numThisTime; --i >= 0;)
  15491. {
  15492. *left++ = ((int) *src++) << 24;
  15493. }
  15494. }
  15495. }
  15496. startOffsetInDestBuffer += numThisTime;
  15497. numSamples -= numThisTime;
  15498. }
  15499. if (numSamples > 0)
  15500. {
  15501. for (int i = numDestChannels; --i >= 0;)
  15502. if (destSamples[i] != 0)
  15503. zeromem (destSamples[i] + startOffsetInDestBuffer,
  15504. sizeof (int) * numSamples);
  15505. }
  15506. return true;
  15507. }
  15508. juce_UseDebuggingNewOperator
  15509. private:
  15510. AiffAudioFormatReader (const AiffAudioFormatReader&);
  15511. AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  15512. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  15513. };
  15514. class AiffAudioFormatWriter : public AudioFormatWriter
  15515. {
  15516. MemoryBlock tempBlock;
  15517. uint32 lengthInSamples, bytesWritten;
  15518. int64 headerPosition;
  15519. bool writeFailed;
  15520. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  15521. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  15522. AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  15523. void writeHeader()
  15524. {
  15525. const bool couldSeekOk = output->setPosition (headerPosition);
  15526. (void) couldSeekOk;
  15527. // if this fails, you've given it an output stream that can't seek! It needs
  15528. // to be able to seek back to write the header
  15529. jassert (couldSeekOk);
  15530. const int headerLen = 54;
  15531. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  15532. audioBytes += (audioBytes & 1);
  15533. output->writeInt (chunkName ("FORM"));
  15534. output->writeIntBigEndian (headerLen + audioBytes - 8);
  15535. output->writeInt (chunkName ("AIFF"));
  15536. output->writeInt (chunkName ("COMM"));
  15537. output->writeIntBigEndian (18);
  15538. output->writeShortBigEndian ((short) numChannels);
  15539. output->writeIntBigEndian (lengthInSamples);
  15540. output->writeShortBigEndian ((short) bitsPerSample);
  15541. uint8 sampleRateBytes[10];
  15542. zeromem (sampleRateBytes, 10);
  15543. if (sampleRate <= 1)
  15544. {
  15545. sampleRateBytes[0] = 0x3f;
  15546. sampleRateBytes[1] = 0xff;
  15547. sampleRateBytes[2] = 0x80;
  15548. }
  15549. else
  15550. {
  15551. int mask = 0x40000000;
  15552. sampleRateBytes[0] = 0x40;
  15553. if (sampleRate >= mask)
  15554. {
  15555. jassertfalse
  15556. sampleRateBytes[1] = 0x1d;
  15557. }
  15558. else
  15559. {
  15560. int n = (int) sampleRate;
  15561. int i;
  15562. for (i = 0; i <= 32 ; ++i)
  15563. {
  15564. if ((n & mask) != 0)
  15565. break;
  15566. mask >>= 1;
  15567. }
  15568. n = n << (i + 1);
  15569. sampleRateBytes[1] = (uint8) (29 - i);
  15570. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  15571. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  15572. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  15573. sampleRateBytes[5] = (uint8) (n & 0xff);
  15574. }
  15575. }
  15576. output->write (sampleRateBytes, 10);
  15577. output->writeInt (chunkName ("SSND"));
  15578. output->writeIntBigEndian (audioBytes + 8);
  15579. output->writeInt (0);
  15580. output->writeInt (0);
  15581. jassert (output->getPosition() == headerLen);
  15582. }
  15583. public:
  15584. AiffAudioFormatWriter (OutputStream* out,
  15585. const double sampleRate_,
  15586. const unsigned int chans,
  15587. const int bits)
  15588. : AudioFormatWriter (out,
  15589. TRANS (aiffFormatName),
  15590. sampleRate_,
  15591. chans,
  15592. bits),
  15593. lengthInSamples (0),
  15594. bytesWritten (0),
  15595. writeFailed (false)
  15596. {
  15597. headerPosition = out->getPosition();
  15598. writeHeader();
  15599. }
  15600. ~AiffAudioFormatWriter()
  15601. {
  15602. if ((bytesWritten & 1) != 0)
  15603. output->writeByte (0);
  15604. writeHeader();
  15605. }
  15606. bool write (const int** data, int numSamples)
  15607. {
  15608. if (writeFailed)
  15609. return false;
  15610. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  15611. tempBlock.ensureSize (bytes, false);
  15612. char* buffer = static_cast <char*> (tempBlock.getData());
  15613. const int* left = data[0];
  15614. const int* right = data[1];
  15615. if (right == 0)
  15616. right = left;
  15617. if (bitsPerSample == 16)
  15618. {
  15619. short* b = reinterpret_cast <short*> (buffer);
  15620. if (numChannels > 1)
  15621. {
  15622. for (int i = numSamples; --i >= 0;)
  15623. {
  15624. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  15625. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*right++ >> 16));
  15626. }
  15627. }
  15628. else
  15629. {
  15630. for (int i = numSamples; --i >= 0;)
  15631. {
  15632. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  15633. }
  15634. }
  15635. }
  15636. else if (bitsPerSample == 24)
  15637. {
  15638. char* b = buffer;
  15639. if (numChannels > 1)
  15640. {
  15641. for (int i = numSamples; --i >= 0;)
  15642. {
  15643. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  15644. b += 3;
  15645. ByteOrder::bigEndian24BitToChars (*right++ >> 8, b);
  15646. b += 3;
  15647. }
  15648. }
  15649. else
  15650. {
  15651. for (int i = numSamples; --i >= 0;)
  15652. {
  15653. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  15654. b += 3;
  15655. }
  15656. }
  15657. }
  15658. else if (bitsPerSample == 32)
  15659. {
  15660. uint32* b = reinterpret_cast <uint32*> (buffer);
  15661. if (numChannels > 1)
  15662. {
  15663. for (int i = numSamples; --i >= 0;)
  15664. {
  15665. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  15666. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *right++);
  15667. }
  15668. }
  15669. else
  15670. {
  15671. for (int i = numSamples; --i >= 0;)
  15672. {
  15673. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  15674. }
  15675. }
  15676. }
  15677. else if (bitsPerSample == 8)
  15678. {
  15679. char* b = buffer;
  15680. if (numChannels > 1)
  15681. {
  15682. for (int i = numSamples; --i >= 0;)
  15683. {
  15684. *b++ = (char) (*left++ >> 24);
  15685. *b++ = (char) (*right++ >> 24);
  15686. }
  15687. }
  15688. else
  15689. {
  15690. for (int i = numSamples; --i >= 0;)
  15691. {
  15692. *b++ = (char) (*left++ >> 24);
  15693. }
  15694. }
  15695. }
  15696. if (bytesWritten + bytes >= (uint32) 0xfff00000
  15697. || ! output->write (buffer, bytes))
  15698. {
  15699. // failed to write to disk, so let's try writing the header.
  15700. // If it's just run out of disk space, then if it does manage
  15701. // to write the header, we'll still have a useable file..
  15702. writeHeader();
  15703. writeFailed = true;
  15704. return false;
  15705. }
  15706. else
  15707. {
  15708. bytesWritten += bytes;
  15709. lengthInSamples += numSamples;
  15710. return true;
  15711. }
  15712. }
  15713. juce_UseDebuggingNewOperator
  15714. };
  15715. AiffAudioFormat::AiffAudioFormat()
  15716. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  15717. {
  15718. }
  15719. AiffAudioFormat::~AiffAudioFormat()
  15720. {
  15721. }
  15722. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  15723. {
  15724. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  15725. return Array <int> (rates);
  15726. }
  15727. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  15728. {
  15729. const int depths[] = { 8, 16, 24, 0 };
  15730. return Array <int> (depths);
  15731. }
  15732. bool AiffAudioFormat::canDoStereo()
  15733. {
  15734. return true;
  15735. }
  15736. bool AiffAudioFormat::canDoMono()
  15737. {
  15738. return true;
  15739. }
  15740. #if JUCE_MAC
  15741. bool AiffAudioFormat::canHandleFile (const File& f)
  15742. {
  15743. if (AudioFormat::canHandleFile (f))
  15744. return true;
  15745. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  15746. return type == 'AIFF' || type == 'AIFC'
  15747. || type == 'aiff' || type == 'aifc';
  15748. }
  15749. #endif
  15750. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream,
  15751. const bool deleteStreamIfOpeningFails)
  15752. {
  15753. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  15754. if (w->sampleRate != 0)
  15755. return w.release();
  15756. if (! deleteStreamIfOpeningFails)
  15757. w->input = 0;
  15758. return 0;
  15759. }
  15760. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  15761. double sampleRate,
  15762. unsigned int chans,
  15763. int bitsPerSample,
  15764. const StringPairArray& /*metadataValues*/,
  15765. int /*qualityOptionIndex*/)
  15766. {
  15767. if (getPossibleBitDepths().contains (bitsPerSample))
  15768. {
  15769. return new AiffAudioFormatWriter (out,
  15770. sampleRate,
  15771. chans,
  15772. bitsPerSample);
  15773. }
  15774. return 0;
  15775. }
  15776. END_JUCE_NAMESPACE
  15777. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  15778. /*** Start of inlined file: juce_AudioCDReader.cpp ***/
  15779. BEGIN_JUCE_NAMESPACE
  15780. #if JUCE_MAC && JUCE_USE_CDREADER
  15781. // Mac version doesn't need any native code because it's all done with files..
  15782. // Windows + Linux versions are in the platform-dependent code sections.
  15783. static void findCDs (Array<File>& cds)
  15784. {
  15785. File volumes ("/Volumes");
  15786. volumes.findChildFiles (cds, File::findDirectories, false);
  15787. for (int i = cds.size(); --i >= 0;)
  15788. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  15789. cds.remove (i);
  15790. }
  15791. const StringArray AudioCDReader::getAvailableCDNames()
  15792. {
  15793. Array<File> cds;
  15794. findCDs (cds);
  15795. StringArray names;
  15796. for (int i = 0; i < cds.size(); ++i)
  15797. names.add (cds.getReference(i).getFileName());
  15798. return names;
  15799. }
  15800. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  15801. {
  15802. Array<File> cds;
  15803. findCDs (cds);
  15804. if (cds[index] != File::nonexistent)
  15805. return new AudioCDReader (cds[index]);
  15806. else
  15807. return 0;
  15808. }
  15809. AudioCDReader::AudioCDReader (const File& volume)
  15810. : AudioFormatReader (0, "CD Audio"),
  15811. volumeDir (volume),
  15812. currentReaderTrack (-1),
  15813. reader (0)
  15814. {
  15815. sampleRate = 44100.0;
  15816. bitsPerSample = 16;
  15817. numChannels = 2;
  15818. usesFloatingPointData = false;
  15819. refreshTrackLengths();
  15820. }
  15821. AudioCDReader::~AudioCDReader()
  15822. {
  15823. }
  15824. static int getTrackNumber (const File& file)
  15825. {
  15826. return file.getFileName()
  15827. .initialSectionContainingOnly ("0123456789")
  15828. .getIntValue();
  15829. }
  15830. int AudioCDReader::compareElements (const File& first, const File& second)
  15831. {
  15832. const int firstTrack = getTrackNumber (first);
  15833. const int secondTrack = getTrackNumber (second);
  15834. jassert (firstTrack > 0 && secondTrack > 0);
  15835. return firstTrack - secondTrack;
  15836. }
  15837. void AudioCDReader::refreshTrackLengths()
  15838. {
  15839. tracks.clear();
  15840. trackStartSamples.clear();
  15841. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  15842. tracks.sort (*this);
  15843. AiffAudioFormat format;
  15844. int sample = 0;
  15845. for (int i = 0; i < tracks.size(); ++i)
  15846. {
  15847. trackStartSamples.add (sample);
  15848. FileInputStream* const in = tracks.getReference(i).createInputStream();
  15849. if (in != 0)
  15850. {
  15851. ScopedPointer <AudioFormatReader> r (format.createReaderFor (in, true));
  15852. if (r != 0)
  15853. sample += (int) r->lengthInSamples;
  15854. }
  15855. }
  15856. trackStartSamples.add (sample);
  15857. lengthInSamples = sample;
  15858. }
  15859. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  15860. int64 startSampleInFile, int numSamples)
  15861. {
  15862. while (numSamples > 0)
  15863. {
  15864. int track = -1;
  15865. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  15866. {
  15867. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  15868. {
  15869. track = i;
  15870. break;
  15871. }
  15872. }
  15873. if (track < 0)
  15874. return false;
  15875. if (track != currentReaderTrack)
  15876. {
  15877. reader = 0;
  15878. FileInputStream* const in = tracks [track].createInputStream();
  15879. if (in != 0)
  15880. {
  15881. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  15882. AiffAudioFormat format;
  15883. reader = format.createReaderFor (bin, true);
  15884. if (reader == 0)
  15885. currentReaderTrack = -1;
  15886. else
  15887. currentReaderTrack = track;
  15888. }
  15889. }
  15890. if (reader == 0)
  15891. return false;
  15892. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  15893. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  15894. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  15895. numSamples -= numAvailable;
  15896. startSampleInFile += numAvailable;
  15897. }
  15898. return true;
  15899. }
  15900. bool AudioCDReader::isCDStillPresent() const
  15901. {
  15902. return volumeDir.exists();
  15903. }
  15904. int AudioCDReader::getNumTracks() const
  15905. {
  15906. return tracks.size();
  15907. }
  15908. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  15909. {
  15910. return trackStartSamples [trackNum];
  15911. }
  15912. bool AudioCDReader::isTrackAudio (int trackNum) const
  15913. {
  15914. return tracks [trackNum] != File::nonexistent;
  15915. }
  15916. void AudioCDReader::enableIndexScanning (bool b)
  15917. {
  15918. // any way to do this on a Mac??
  15919. }
  15920. int AudioCDReader::getLastIndex() const
  15921. {
  15922. return 0;
  15923. }
  15924. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  15925. {
  15926. return Array <int>();
  15927. }
  15928. int AudioCDReader::getCDDBId()
  15929. {
  15930. return 0; //xxx
  15931. }
  15932. #endif
  15933. END_JUCE_NAMESPACE
  15934. /*** End of inlined file: juce_AudioCDReader.cpp ***/
  15935. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  15936. BEGIN_JUCE_NAMESPACE
  15937. AudioFormatReader::AudioFormatReader (InputStream* const in,
  15938. const String& formatName_)
  15939. : sampleRate (0),
  15940. bitsPerSample (0),
  15941. lengthInSamples (0),
  15942. numChannels (0),
  15943. usesFloatingPointData (false),
  15944. input (in),
  15945. formatName (formatName_)
  15946. {
  15947. }
  15948. AudioFormatReader::~AudioFormatReader()
  15949. {
  15950. delete input;
  15951. }
  15952. bool AudioFormatReader::read (int** destSamples,
  15953. int numDestChannels,
  15954. int64 startSampleInSource,
  15955. int numSamplesToRead,
  15956. const bool fillLeftoverChannelsWithCopies)
  15957. {
  15958. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  15959. int startOffsetInDestBuffer = 0;
  15960. if (startSampleInSource < 0)
  15961. {
  15962. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  15963. for (int i = numDestChannels; --i >= 0;)
  15964. if (destSamples[i] != 0)
  15965. zeromem (destSamples[i], sizeof (int) * silence);
  15966. startOffsetInDestBuffer += silence;
  15967. numSamplesToRead -= silence;
  15968. startSampleInSource = 0;
  15969. }
  15970. if (numSamplesToRead <= 0)
  15971. return true;
  15972. if (! readSamples (destSamples, jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  15973. startSampleInSource, numSamplesToRead))
  15974. return false;
  15975. if (numDestChannels > (int) numChannels)
  15976. {
  15977. if (fillLeftoverChannelsWithCopies)
  15978. {
  15979. int* lastFullChannel = destSamples[0];
  15980. for (int i = numDestChannels; --i > 0;)
  15981. {
  15982. if (destSamples[i] != 0)
  15983. {
  15984. lastFullChannel = destSamples[i];
  15985. break;
  15986. }
  15987. }
  15988. if (lastFullChannel != 0)
  15989. for (int i = numChannels; i < numDestChannels; ++i)
  15990. if (destSamples[i] != 0)
  15991. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  15992. }
  15993. else
  15994. {
  15995. for (int i = numChannels; i < numDestChannels; ++i)
  15996. if (destSamples[i] != 0)
  15997. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  15998. }
  15999. }
  16000. return true;
  16001. }
  16002. static void findAudioBufferMaxMin (const float* const buffer, const int num, float& maxVal, float& minVal) throw()
  16003. {
  16004. float mn = buffer[0];
  16005. float mx = mn;
  16006. for (int i = 1; i < num; ++i)
  16007. {
  16008. const float s = buffer[i];
  16009. if (s > mx) mx = s;
  16010. if (s < mn) mn = s;
  16011. }
  16012. maxVal = mx;
  16013. minVal = mn;
  16014. }
  16015. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  16016. int64 numSamples,
  16017. float& lowestLeft, float& highestLeft,
  16018. float& lowestRight, float& highestRight)
  16019. {
  16020. if (numSamples <= 0)
  16021. {
  16022. lowestLeft = 0;
  16023. lowestRight = 0;
  16024. highestLeft = 0;
  16025. highestRight = 0;
  16026. return;
  16027. }
  16028. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  16029. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  16030. int* tempBuffer[3];
  16031. tempBuffer[0] = (int*) tempSpace.getData();
  16032. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  16033. tempBuffer[2] = 0;
  16034. if (usesFloatingPointData)
  16035. {
  16036. float lmin = 1.0e6f;
  16037. float lmax = -lmin;
  16038. float rmin = lmin;
  16039. float rmax = lmax;
  16040. while (numSamples > 0)
  16041. {
  16042. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16043. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  16044. numSamples -= numToDo;
  16045. startSampleInFile += numToDo;
  16046. float bufmin, bufmax;
  16047. findAudioBufferMaxMin ((float*) tempBuffer[0], numToDo, bufmax, bufmin);
  16048. lmin = jmin (lmin, bufmin);
  16049. lmax = jmax (lmax, bufmax);
  16050. if (numChannels > 1)
  16051. {
  16052. findAudioBufferMaxMin ((float*) tempBuffer[1], numToDo, bufmax, bufmin);
  16053. rmin = jmin (rmin, bufmin);
  16054. rmax = jmax (rmax, bufmax);
  16055. }
  16056. }
  16057. if (numChannels <= 1)
  16058. {
  16059. rmax = lmax;
  16060. rmin = lmin;
  16061. }
  16062. lowestLeft = lmin;
  16063. highestLeft = lmax;
  16064. lowestRight = rmin;
  16065. highestRight = rmax;
  16066. }
  16067. else
  16068. {
  16069. int lmax = std::numeric_limits<int>::min();
  16070. int lmin = std::numeric_limits<int>::max();
  16071. int rmax = std::numeric_limits<int>::min();
  16072. int rmin = std::numeric_limits<int>::max();
  16073. while (numSamples > 0)
  16074. {
  16075. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16076. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  16077. numSamples -= numToDo;
  16078. startSampleInFile += numToDo;
  16079. for (int j = numChannels; --j >= 0;)
  16080. {
  16081. int bufMax = std::numeric_limits<int>::min();
  16082. int bufMin = std::numeric_limits<int>::max();
  16083. const int* const b = tempBuffer[j];
  16084. for (int i = 0; i < numToDo; ++i)
  16085. {
  16086. const int samp = b[i];
  16087. if (samp < bufMin)
  16088. bufMin = samp;
  16089. if (samp > bufMax)
  16090. bufMax = samp;
  16091. }
  16092. if (j == 0)
  16093. {
  16094. lmax = jmax (lmax, bufMax);
  16095. lmin = jmin (lmin, bufMin);
  16096. }
  16097. else
  16098. {
  16099. rmax = jmax (rmax, bufMax);
  16100. rmin = jmin (rmin, bufMin);
  16101. }
  16102. }
  16103. }
  16104. if (numChannels <= 1)
  16105. {
  16106. rmax = lmax;
  16107. rmin = lmin;
  16108. }
  16109. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  16110. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  16111. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  16112. highestRight = rmax / (float) std::numeric_limits<int>::max();
  16113. }
  16114. }
  16115. int64 AudioFormatReader::searchForLevel (int64 startSample,
  16116. int64 numSamplesToSearch,
  16117. const double magnitudeRangeMinimum,
  16118. const double magnitudeRangeMaximum,
  16119. const int minimumConsecutiveSamples)
  16120. {
  16121. if (numSamplesToSearch == 0)
  16122. return -1;
  16123. const int bufferSize = 4096;
  16124. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  16125. int* tempBuffer[3];
  16126. tempBuffer[0] = (int*) tempSpace.getData();
  16127. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  16128. tempBuffer[2] = 0;
  16129. int consecutive = 0;
  16130. int64 firstMatchPos = -1;
  16131. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  16132. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  16133. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  16134. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  16135. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  16136. while (numSamplesToSearch != 0)
  16137. {
  16138. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  16139. int64 bufferStart = startSample;
  16140. if (numSamplesToSearch < 0)
  16141. bufferStart -= numThisTime;
  16142. if (bufferStart >= (int) lengthInSamples)
  16143. break;
  16144. read ((int**) tempBuffer, 2, bufferStart, numThisTime, false);
  16145. int num = numThisTime;
  16146. while (--num >= 0)
  16147. {
  16148. if (numSamplesToSearch < 0)
  16149. --startSample;
  16150. bool matches = false;
  16151. const int index = (int) (startSample - bufferStart);
  16152. if (usesFloatingPointData)
  16153. {
  16154. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  16155. if (sample1 >= magnitudeRangeMinimum
  16156. && sample1 <= magnitudeRangeMaximum)
  16157. {
  16158. matches = true;
  16159. }
  16160. else if (numChannels > 1)
  16161. {
  16162. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  16163. matches = (sample2 >= magnitudeRangeMinimum
  16164. && sample2 <= magnitudeRangeMaximum);
  16165. }
  16166. }
  16167. else
  16168. {
  16169. const int sample1 = abs (tempBuffer[0] [index]);
  16170. if (sample1 >= intMagnitudeRangeMinimum
  16171. && sample1 <= intMagnitudeRangeMaximum)
  16172. {
  16173. matches = true;
  16174. }
  16175. else if (numChannels > 1)
  16176. {
  16177. const int sample2 = abs (tempBuffer[1][index]);
  16178. matches = (sample2 >= intMagnitudeRangeMinimum
  16179. && sample2 <= intMagnitudeRangeMaximum);
  16180. }
  16181. }
  16182. if (matches)
  16183. {
  16184. if (firstMatchPos < 0)
  16185. firstMatchPos = startSample;
  16186. if (++consecutive >= minimumConsecutiveSamples)
  16187. {
  16188. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  16189. return -1;
  16190. return firstMatchPos;
  16191. }
  16192. }
  16193. else
  16194. {
  16195. consecutive = 0;
  16196. firstMatchPos = -1;
  16197. }
  16198. if (numSamplesToSearch > 0)
  16199. ++startSample;
  16200. }
  16201. if (numSamplesToSearch > 0)
  16202. numSamplesToSearch -= numThisTime;
  16203. else
  16204. numSamplesToSearch += numThisTime;
  16205. }
  16206. return -1;
  16207. }
  16208. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  16209. const String& formatName_,
  16210. const double rate,
  16211. const unsigned int numChannels_,
  16212. const unsigned int bitsPerSample_)
  16213. : sampleRate (rate),
  16214. numChannels (numChannels_),
  16215. bitsPerSample (bitsPerSample_),
  16216. usesFloatingPointData (false),
  16217. output (out),
  16218. formatName (formatName_)
  16219. {
  16220. }
  16221. AudioFormatWriter::~AudioFormatWriter()
  16222. {
  16223. delete output;
  16224. }
  16225. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  16226. int64 startSample,
  16227. int64 numSamplesToRead)
  16228. {
  16229. const int bufferSize = 16384;
  16230. const int maxChans = 128;
  16231. AudioSampleBuffer tempBuffer (reader.numChannels, bufferSize);
  16232. int* buffers [maxChans];
  16233. for (int i = maxChans; --i >= 0;)
  16234. buffers[i] = 0;
  16235. if (numSamplesToRead < 0)
  16236. numSamplesToRead = reader.lengthInSamples;
  16237. while (numSamplesToRead > 0)
  16238. {
  16239. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  16240. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  16241. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  16242. if (! reader.read (buffers, maxChans, startSample, numToDo, false))
  16243. return false;
  16244. if (reader.usesFloatingPointData != isFloatingPoint())
  16245. {
  16246. int** bufferChan = buffers;
  16247. while (*bufferChan != 0)
  16248. {
  16249. int* b = *bufferChan++;
  16250. if (isFloatingPoint())
  16251. {
  16252. // int -> float
  16253. const double factor = 1.0 / std::numeric_limits<int>::max();
  16254. for (int i = 0; i < numToDo; ++i)
  16255. ((float*) b)[i] = (float) (factor * b[i]);
  16256. }
  16257. else
  16258. {
  16259. // float -> int
  16260. for (int i = 0; i < numToDo; ++i)
  16261. {
  16262. const double samp = *(const float*) b;
  16263. if (samp <= -1.0)
  16264. *b++ = std::numeric_limits<int>::min();
  16265. else if (samp >= 1.0)
  16266. *b++ = std::numeric_limits<int>::max();
  16267. else
  16268. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  16269. }
  16270. }
  16271. }
  16272. }
  16273. if (! write ((const int**) buffers, numToDo))
  16274. return false;
  16275. numSamplesToRead -= numToDo;
  16276. startSample += numToDo;
  16277. }
  16278. return true;
  16279. }
  16280. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source,
  16281. int numSamplesToRead,
  16282. const int samplesPerBlock)
  16283. {
  16284. const int maxChans = 128;
  16285. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  16286. int* buffers [maxChans];
  16287. while (numSamplesToRead > 0)
  16288. {
  16289. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  16290. AudioSourceChannelInfo info;
  16291. info.buffer = &tempBuffer;
  16292. info.startSample = 0;
  16293. info.numSamples = numToDo;
  16294. info.clearActiveBufferRegion();
  16295. source.getNextAudioBlock (info);
  16296. int i;
  16297. for (i = maxChans; --i >= 0;)
  16298. buffers[i] = 0;
  16299. for (i = tempBuffer.getNumChannels(); --i >= 0;)
  16300. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  16301. if (! isFloatingPoint())
  16302. {
  16303. int** bufferChan = buffers;
  16304. while (*bufferChan != 0)
  16305. {
  16306. int* b = *bufferChan++;
  16307. // float -> int
  16308. for (int j = numToDo; --j >= 0;)
  16309. {
  16310. const double samp = *(const float*) b;
  16311. if (samp <= -1.0)
  16312. *b++ = std::numeric_limits<int>::min();
  16313. else if (samp >= 1.0)
  16314. *b++ = std::numeric_limits<int>::max();
  16315. else
  16316. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  16317. }
  16318. }
  16319. }
  16320. if (! write ((const int**) buffers, numToDo))
  16321. return false;
  16322. numSamplesToRead -= numToDo;
  16323. }
  16324. return true;
  16325. }
  16326. AudioFormat::AudioFormat (const String& name,
  16327. const StringArray& extensions)
  16328. : formatName (name),
  16329. fileExtensions (extensions)
  16330. {
  16331. }
  16332. AudioFormat::~AudioFormat()
  16333. {
  16334. }
  16335. const String& AudioFormat::getFormatName() const
  16336. {
  16337. return formatName;
  16338. }
  16339. const StringArray& AudioFormat::getFileExtensions() const
  16340. {
  16341. return fileExtensions;
  16342. }
  16343. bool AudioFormat::canHandleFile (const File& f)
  16344. {
  16345. for (int i = 0; i < fileExtensions.size(); ++i)
  16346. if (f.hasFileExtension (fileExtensions[i]))
  16347. return true;
  16348. return false;
  16349. }
  16350. bool AudioFormat::isCompressed()
  16351. {
  16352. return false;
  16353. }
  16354. const StringArray AudioFormat::getQualityOptions()
  16355. {
  16356. return StringArray();
  16357. }
  16358. END_JUCE_NAMESPACE
  16359. /*** End of inlined file: juce_AudioFormat.cpp ***/
  16360. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  16361. BEGIN_JUCE_NAMESPACE
  16362. AudioFormatManager::AudioFormatManager()
  16363. : defaultFormatIndex (0)
  16364. {
  16365. }
  16366. AudioFormatManager::~AudioFormatManager()
  16367. {
  16368. clearFormats();
  16369. clearSingletonInstance();
  16370. }
  16371. juce_ImplementSingleton (AudioFormatManager);
  16372. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  16373. const bool makeThisTheDefaultFormat)
  16374. {
  16375. jassert (newFormat != 0);
  16376. if (newFormat != 0)
  16377. {
  16378. #if JUCE_DEBUG
  16379. for (int i = getNumKnownFormats(); --i >= 0;)
  16380. {
  16381. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  16382. {
  16383. jassertfalse // trying to add the same format twice!
  16384. }
  16385. }
  16386. #endif
  16387. if (makeThisTheDefaultFormat)
  16388. defaultFormatIndex = getNumKnownFormats();
  16389. knownFormats.add (newFormat);
  16390. }
  16391. }
  16392. void AudioFormatManager::registerBasicFormats()
  16393. {
  16394. #if JUCE_MAC
  16395. registerFormat (new AiffAudioFormat(), true);
  16396. registerFormat (new WavAudioFormat(), false);
  16397. #else
  16398. registerFormat (new WavAudioFormat(), true);
  16399. registerFormat (new AiffAudioFormat(), false);
  16400. #endif
  16401. #if JUCE_USE_FLAC
  16402. registerFormat (new FlacAudioFormat(), false);
  16403. #endif
  16404. #if JUCE_USE_OGGVORBIS
  16405. registerFormat (new OggVorbisAudioFormat(), false);
  16406. #endif
  16407. }
  16408. void AudioFormatManager::clearFormats()
  16409. {
  16410. knownFormats.clear();
  16411. defaultFormatIndex = 0;
  16412. }
  16413. int AudioFormatManager::getNumKnownFormats() const
  16414. {
  16415. return knownFormats.size();
  16416. }
  16417. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  16418. {
  16419. return knownFormats [index];
  16420. }
  16421. AudioFormat* AudioFormatManager::getDefaultFormat() const
  16422. {
  16423. return getKnownFormat (defaultFormatIndex);
  16424. }
  16425. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  16426. {
  16427. String e (fileExtension);
  16428. if (! e.startsWithChar ('.'))
  16429. e = "." + e;
  16430. for (int i = 0; i < getNumKnownFormats(); ++i)
  16431. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  16432. return getKnownFormat(i);
  16433. return 0;
  16434. }
  16435. const String AudioFormatManager::getWildcardForAllFormats() const
  16436. {
  16437. StringArray allExtensions;
  16438. int i;
  16439. for (i = 0; i < getNumKnownFormats(); ++i)
  16440. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  16441. allExtensions.trim();
  16442. allExtensions.removeEmptyStrings();
  16443. String s;
  16444. for (i = 0; i < allExtensions.size(); ++i)
  16445. {
  16446. s << '*';
  16447. if (! allExtensions[i].startsWithChar ('.'))
  16448. s << '.';
  16449. s << allExtensions[i];
  16450. if (i < allExtensions.size() - 1)
  16451. s << ';';
  16452. }
  16453. return s;
  16454. }
  16455. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  16456. {
  16457. // you need to actually register some formats before the manager can
  16458. // use them to open a file!
  16459. jassert (getNumKnownFormats() > 0);
  16460. for (int i = 0; i < getNumKnownFormats(); ++i)
  16461. {
  16462. AudioFormat* const af = getKnownFormat(i);
  16463. if (af->canHandleFile (file))
  16464. {
  16465. InputStream* const in = file.createInputStream();
  16466. if (in != 0)
  16467. {
  16468. AudioFormatReader* const r = af->createReaderFor (in, true);
  16469. if (r != 0)
  16470. return r;
  16471. }
  16472. }
  16473. }
  16474. return 0;
  16475. }
  16476. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  16477. {
  16478. // you need to actually register some formats before the manager can
  16479. // use them to open a file!
  16480. jassert (getNumKnownFormats() > 0);
  16481. ScopedPointer <InputStream> in (audioFileStream);
  16482. if (in != 0)
  16483. {
  16484. const int64 originalStreamPos = in->getPosition();
  16485. for (int i = 0; i < getNumKnownFormats(); ++i)
  16486. {
  16487. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  16488. if (r != 0)
  16489. {
  16490. in.release();
  16491. return r;
  16492. }
  16493. in->setPosition (originalStreamPos);
  16494. // the stream that is passed-in must be capable of being repositioned so
  16495. // that all the formats can have a go at opening it.
  16496. jassert (in->getPosition() == originalStreamPos);
  16497. }
  16498. }
  16499. return 0;
  16500. }
  16501. END_JUCE_NAMESPACE
  16502. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  16503. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  16504. BEGIN_JUCE_NAMESPACE
  16505. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  16506. const int64 startSample_,
  16507. const int64 length_,
  16508. const bool deleteSourceWhenDeleted_)
  16509. : AudioFormatReader (0, source_->getFormatName()),
  16510. source (source_),
  16511. startSample (startSample_),
  16512. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  16513. {
  16514. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  16515. sampleRate = source->sampleRate;
  16516. bitsPerSample = source->bitsPerSample;
  16517. lengthInSamples = length;
  16518. numChannels = source->numChannels;
  16519. usesFloatingPointData = source->usesFloatingPointData;
  16520. }
  16521. AudioSubsectionReader::~AudioSubsectionReader()
  16522. {
  16523. if (deleteSourceWhenDeleted)
  16524. delete source;
  16525. }
  16526. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16527. int64 startSampleInFile, int numSamples)
  16528. {
  16529. if (startSampleInFile + numSamples > length)
  16530. {
  16531. for (int i = numDestChannels; --i >= 0;)
  16532. if (destSamples[i] != 0)
  16533. zeromem (destSamples[i], sizeof (int) * numSamples);
  16534. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  16535. if (numSamples <= 0)
  16536. return true;
  16537. }
  16538. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  16539. startSampleInFile + startSample, numSamples);
  16540. }
  16541. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  16542. int64 numSamples,
  16543. float& lowestLeft,
  16544. float& highestLeft,
  16545. float& lowestRight,
  16546. float& highestRight)
  16547. {
  16548. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  16549. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  16550. source->readMaxLevels (startSampleInFile + startSample,
  16551. numSamples,
  16552. lowestLeft,
  16553. highestLeft,
  16554. lowestRight,
  16555. highestRight);
  16556. }
  16557. END_JUCE_NAMESPACE
  16558. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  16559. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  16560. BEGIN_JUCE_NAMESPACE
  16561. const int timeBeforeDeletingReader = 2000;
  16562. struct AudioThumbnailDataFormat
  16563. {
  16564. char thumbnailMagic[4];
  16565. int samplesPerThumbSample;
  16566. int64 totalSamples; // source samples
  16567. int64 numFinishedSamples; // source samples
  16568. int numThumbnailSamples;
  16569. int numChannels;
  16570. int sampleRate;
  16571. char future[16];
  16572. char data[1];
  16573. void swapEndiannessIfNeeded() throw()
  16574. {
  16575. #if JUCE_BIG_ENDIAN
  16576. flip (samplesPerThumbSample);
  16577. flip (totalSamples);
  16578. flip (numFinishedSamples);
  16579. flip (numThumbnailSamples);
  16580. flip (numChannels);
  16581. flip (sampleRate);
  16582. #endif
  16583. }
  16584. private:
  16585. #if JUCE_BIG_ENDIAN
  16586. static void flip (int& n) { n = (int) ByteOrder::swap ((uint32) n); }
  16587. static void flip (int64& n) { n = (int64) ByteOrder::swap ((uint64) n); }
  16588. #endif
  16589. };
  16590. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  16591. AudioFormatManager& formatManagerToUse_,
  16592. AudioThumbnailCache& cacheToUse)
  16593. : formatManagerToUse (formatManagerToUse_),
  16594. cache (cacheToUse),
  16595. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_)
  16596. {
  16597. clear();
  16598. }
  16599. AudioThumbnail::~AudioThumbnail()
  16600. {
  16601. cache.removeThumbnail (this);
  16602. const ScopedLock sl (readerLock);
  16603. reader = 0;
  16604. }
  16605. void AudioThumbnail::setSource (InputSource* const newSource)
  16606. {
  16607. cache.removeThumbnail (this);
  16608. timerCallback(); // stops the timer and deletes the reader
  16609. source = newSource;
  16610. clear();
  16611. if (newSource != 0
  16612. && ! (cache.loadThumb (*this, newSource->hashCode())
  16613. && isFullyLoaded()))
  16614. {
  16615. {
  16616. const ScopedLock sl (readerLock);
  16617. reader = createReader();
  16618. }
  16619. if (reader != 0)
  16620. {
  16621. initialiseFromAudioFile (*reader);
  16622. cache.addThumbnail (this);
  16623. }
  16624. }
  16625. sendChangeMessage (this);
  16626. }
  16627. bool AudioThumbnail::useTimeSlice()
  16628. {
  16629. const ScopedLock sl (readerLock);
  16630. if (isFullyLoaded())
  16631. {
  16632. if (reader != 0)
  16633. startTimer (timeBeforeDeletingReader);
  16634. cache.removeThumbnail (this);
  16635. return false;
  16636. }
  16637. if (reader == 0)
  16638. reader = createReader();
  16639. if (reader != 0)
  16640. {
  16641. readNextBlockFromAudioFile (*reader);
  16642. stopTimer();
  16643. sendChangeMessage (this);
  16644. const bool justFinished = isFullyLoaded();
  16645. if (justFinished)
  16646. cache.storeThumb (*this, source->hashCode());
  16647. return ! justFinished;
  16648. }
  16649. return false;
  16650. }
  16651. AudioFormatReader* AudioThumbnail::createReader() const
  16652. {
  16653. if (source != 0)
  16654. {
  16655. InputStream* const audioFileStream = source->createInputStream();
  16656. if (audioFileStream != 0)
  16657. return formatManagerToUse.createReaderFor (audioFileStream);
  16658. }
  16659. return 0;
  16660. }
  16661. void AudioThumbnail::timerCallback()
  16662. {
  16663. stopTimer();
  16664. const ScopedLock sl (readerLock);
  16665. reader = 0;
  16666. }
  16667. void AudioThumbnail::clear()
  16668. {
  16669. data.setSize (sizeof (AudioThumbnailDataFormat) + 3);
  16670. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16671. d->thumbnailMagic[0] = 'j';
  16672. d->thumbnailMagic[1] = 'a';
  16673. d->thumbnailMagic[2] = 't';
  16674. d->thumbnailMagic[3] = 'm';
  16675. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  16676. d->totalSamples = 0;
  16677. d->numFinishedSamples = 0;
  16678. d->numThumbnailSamples = 0;
  16679. d->numChannels = 0;
  16680. d->sampleRate = 0;
  16681. numSamplesCached = 0;
  16682. cacheNeedsRefilling = true;
  16683. }
  16684. void AudioThumbnail::loadFrom (InputStream& input)
  16685. {
  16686. const ScopedLock sl (readerLock);
  16687. data.setSize (0);
  16688. input.readIntoMemoryBlock (data);
  16689. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16690. d->swapEndiannessIfNeeded();
  16691. if (! (d->thumbnailMagic[0] == 'j'
  16692. && d->thumbnailMagic[1] == 'a'
  16693. && d->thumbnailMagic[2] == 't'
  16694. && d->thumbnailMagic[3] == 'm'))
  16695. {
  16696. clear();
  16697. }
  16698. numSamplesCached = 0;
  16699. cacheNeedsRefilling = true;
  16700. }
  16701. void AudioThumbnail::saveTo (OutputStream& output) const
  16702. {
  16703. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16704. d->swapEndiannessIfNeeded();
  16705. output.write (data.getData(), (int) data.getSize());
  16706. d->swapEndiannessIfNeeded();
  16707. }
  16708. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& fileReader)
  16709. {
  16710. AudioThumbnailDataFormat* d = (AudioThumbnailDataFormat*) data.getData();
  16711. d->totalSamples = fileReader.lengthInSamples;
  16712. d->numChannels = jmin ((uint32) 2, fileReader.numChannels);
  16713. d->numFinishedSamples = 0;
  16714. d->sampleRate = roundToInt (fileReader.sampleRate);
  16715. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  16716. data.setSize (sizeof (AudioThumbnailDataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  16717. d = (AudioThumbnailDataFormat*) data.getData();
  16718. zeromem (&(d->data[0]), d->numThumbnailSamples * d->numChannels * 2);
  16719. return d->totalSamples > 0;
  16720. }
  16721. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& fileReader)
  16722. {
  16723. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16724. if (d->numFinishedSamples < d->totalSamples)
  16725. {
  16726. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  16727. generateSection (fileReader,
  16728. d->numFinishedSamples,
  16729. numToDo);
  16730. d->numFinishedSamples += numToDo;
  16731. }
  16732. cacheNeedsRefilling = true;
  16733. return (d->numFinishedSamples < d->totalSamples);
  16734. }
  16735. int AudioThumbnail::getNumChannels() const throw()
  16736. {
  16737. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16738. jassert (d != 0);
  16739. return d->numChannels;
  16740. }
  16741. double AudioThumbnail::getTotalLength() const throw()
  16742. {
  16743. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16744. jassert (d != 0);
  16745. if (d->sampleRate > 0)
  16746. return d->totalSamples / (double)d->sampleRate;
  16747. else
  16748. return 0.0;
  16749. }
  16750. void AudioThumbnail::generateSection (AudioFormatReader& fileReader,
  16751. int64 startSample,
  16752. int numSamples)
  16753. {
  16754. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16755. jassert (d != 0);
  16756. int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  16757. int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  16758. char* l = getChannelData (0);
  16759. char* r = getChannelData (1);
  16760. for (int i = firstDataPos; i < lastDataPos; ++i)
  16761. {
  16762. const int sourceStart = i * d->samplesPerThumbSample;
  16763. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  16764. float lowestLeft, highestLeft, lowestRight, highestRight;
  16765. fileReader.readMaxLevels (sourceStart,
  16766. sourceEnd - sourceStart,
  16767. lowestLeft,
  16768. highestLeft,
  16769. lowestRight,
  16770. highestRight);
  16771. int n = i * 2;
  16772. if (r != 0)
  16773. {
  16774. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16775. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  16776. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16777. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  16778. }
  16779. else
  16780. {
  16781. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16782. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16783. }
  16784. }
  16785. }
  16786. char* AudioThumbnail::getChannelData (int channel) const
  16787. {
  16788. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16789. jassert (d != 0);
  16790. if (channel >= 0 && channel < d->numChannels)
  16791. return d->data + (channel * 2 * d->numThumbnailSamples);
  16792. return 0;
  16793. }
  16794. bool AudioThumbnail::isFullyLoaded() const throw()
  16795. {
  16796. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16797. jassert (d != 0);
  16798. return d->numFinishedSamples >= d->totalSamples;
  16799. }
  16800. void AudioThumbnail::refillCache (const int numSamples,
  16801. double startTime,
  16802. const double timePerPixel)
  16803. {
  16804. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16805. jassert (d != 0);
  16806. if (numSamples <= 0
  16807. || timePerPixel <= 0.0
  16808. || d->sampleRate <= 0)
  16809. {
  16810. numSamplesCached = 0;
  16811. cacheNeedsRefilling = true;
  16812. return;
  16813. }
  16814. if (numSamples == numSamplesCached
  16815. && numChannelsCached == d->numChannels
  16816. && startTime == cachedStart
  16817. && timePerPixel == cachedTimePerPixel
  16818. && ! cacheNeedsRefilling)
  16819. {
  16820. return;
  16821. }
  16822. numSamplesCached = numSamples;
  16823. numChannelsCached = d->numChannels;
  16824. cachedStart = startTime;
  16825. cachedTimePerPixel = timePerPixel;
  16826. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  16827. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  16828. const ScopedLock sl (readerLock);
  16829. cacheNeedsRefilling = false;
  16830. if (needExtraDetail && reader == 0)
  16831. reader = createReader();
  16832. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  16833. {
  16834. startTimer (timeBeforeDeletingReader);
  16835. char* cacheData = static_cast <char*> (cachedLevels.getData());
  16836. int sample = roundToInt (startTime * d->sampleRate);
  16837. for (int i = numSamples; --i >= 0;)
  16838. {
  16839. const int nextSample = roundToInt ((startTime + timePerPixel) * d->sampleRate);
  16840. if (sample >= 0)
  16841. {
  16842. if (sample >= reader->lengthInSamples)
  16843. break;
  16844. float lmin, lmax, rmin, rmax;
  16845. reader->readMaxLevels (sample,
  16846. jmax (1, nextSample - sample),
  16847. lmin, lmax, rmin, rmax);
  16848. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  16849. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  16850. if (numChannelsCached > 1)
  16851. {
  16852. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  16853. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  16854. }
  16855. cacheData += 2 * numChannelsCached;
  16856. }
  16857. startTime += timePerPixel;
  16858. sample = nextSample;
  16859. }
  16860. }
  16861. else
  16862. {
  16863. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  16864. {
  16865. char* const channelData = getChannelData (channelNum);
  16866. char* cacheData = static_cast <char*> (cachedLevels.getData()) + channelNum * 2;
  16867. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  16868. startTime = cachedStart;
  16869. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  16870. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  16871. for (int i = numSamples; --i >= 0;)
  16872. {
  16873. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  16874. if (sample >= 0 && channelData != 0)
  16875. {
  16876. char mx = -128;
  16877. char mn = 127;
  16878. while (sample <= nextSample)
  16879. {
  16880. if (sample >= numFinished)
  16881. break;
  16882. const int n = sample << 1;
  16883. const char sampMin = channelData [n];
  16884. const char sampMax = channelData [n + 1];
  16885. if (sampMin < mn)
  16886. mn = sampMin;
  16887. if (sampMax > mx)
  16888. mx = sampMax;
  16889. ++sample;
  16890. }
  16891. if (mn <= mx)
  16892. {
  16893. cacheData[0] = mn;
  16894. cacheData[1] = mx;
  16895. }
  16896. else
  16897. {
  16898. cacheData[0] = 1;
  16899. cacheData[1] = 0;
  16900. }
  16901. }
  16902. else
  16903. {
  16904. cacheData[0] = 1;
  16905. cacheData[1] = 0;
  16906. }
  16907. cacheData += numChannelsCached * 2;
  16908. startTime += timePerPixel;
  16909. sample = nextSample;
  16910. }
  16911. }
  16912. }
  16913. }
  16914. void AudioThumbnail::drawChannel (Graphics& g,
  16915. int x, int y, int w, int h,
  16916. double startTime,
  16917. double endTime,
  16918. int channelNum,
  16919. const float verticalZoomFactor)
  16920. {
  16921. refillCache (w, startTime, (endTime - startTime) / w);
  16922. if (numSamplesCached >= w
  16923. && channelNum >= 0
  16924. && channelNum < numChannelsCached)
  16925. {
  16926. const float topY = (float) y;
  16927. const float bottomY = topY + h;
  16928. const float midY = topY + h * 0.5f;
  16929. const float vscale = verticalZoomFactor * h / 256.0f;
  16930. const Rectangle<int> clip (g.getClipBounds());
  16931. const int skipLeft = jlimit (0, w, clip.getX() - x);
  16932. w -= skipLeft;
  16933. x += skipLeft;
  16934. const char* cacheData = static_cast <const char*> (cachedLevels.getData())
  16935. + (channelNum << 1)
  16936. + skipLeft * (numChannelsCached << 1);
  16937. while (--w >= 0)
  16938. {
  16939. const char mn = cacheData[0];
  16940. const char mx = cacheData[1];
  16941. cacheData += numChannelsCached << 1;
  16942. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  16943. g.drawLine ((float) x, jmax (midY - mx * vscale - 0.3f, topY),
  16944. (float) x, jmin (midY - mn * vscale + 0.3f, bottomY));
  16945. ++x;
  16946. if (x >= clip.getRight())
  16947. break;
  16948. }
  16949. }
  16950. }
  16951. END_JUCE_NAMESPACE
  16952. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  16953. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  16954. BEGIN_JUCE_NAMESPACE
  16955. struct ThumbnailCacheEntry
  16956. {
  16957. int64 hash;
  16958. uint32 lastUsed;
  16959. MemoryBlock data;
  16960. juce_UseDebuggingNewOperator
  16961. };
  16962. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  16963. : TimeSliceThread ("thumb cache"),
  16964. maxNumThumbsToStore (maxNumThumbsToStore_)
  16965. {
  16966. startThread (2);
  16967. }
  16968. AudioThumbnailCache::~AudioThumbnailCache()
  16969. {
  16970. }
  16971. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  16972. {
  16973. for (int i = thumbs.size(); --i >= 0;)
  16974. {
  16975. if (thumbs[i]->hash == hashCode)
  16976. {
  16977. MemoryInputStream in (thumbs[i]->data, false);
  16978. thumb.loadFrom (in);
  16979. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  16980. return true;
  16981. }
  16982. }
  16983. return false;
  16984. }
  16985. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  16986. const int64 hashCode)
  16987. {
  16988. MemoryOutputStream out;
  16989. thumb.saveTo (out);
  16990. ThumbnailCacheEntry* te = 0;
  16991. for (int i = thumbs.size(); --i >= 0;)
  16992. {
  16993. if (thumbs[i]->hash == hashCode)
  16994. {
  16995. te = thumbs[i];
  16996. break;
  16997. }
  16998. }
  16999. if (te == 0)
  17000. {
  17001. te = new ThumbnailCacheEntry();
  17002. te->hash = hashCode;
  17003. if (thumbs.size() < maxNumThumbsToStore)
  17004. {
  17005. thumbs.add (te);
  17006. }
  17007. else
  17008. {
  17009. int oldest = 0;
  17010. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  17011. int i;
  17012. for (i = thumbs.size(); --i >= 0;)
  17013. if (thumbs[i]->lastUsed < oldestTime)
  17014. oldest = i;
  17015. thumbs.set (i, te);
  17016. }
  17017. }
  17018. te->lastUsed = Time::getMillisecondCounter();
  17019. te->data.setSize (0);
  17020. te->data.append (out.getData(), out.getDataSize());
  17021. }
  17022. void AudioThumbnailCache::clear()
  17023. {
  17024. thumbs.clear();
  17025. }
  17026. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  17027. {
  17028. addTimeSliceClient (thumb);
  17029. }
  17030. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  17031. {
  17032. removeTimeSliceClient (thumb);
  17033. }
  17034. END_JUCE_NAMESPACE
  17035. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  17036. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17037. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IPHONE)
  17038. #if ! JUCE_WINDOWS
  17039. #include <QuickTime/Movies.h>
  17040. #include <QuickTime/QTML.h>
  17041. #include <QuickTime/QuickTimeComponents.h>
  17042. #include <QuickTime/MediaHandlers.h>
  17043. #include <QuickTime/ImageCodec.h>
  17044. #else
  17045. #if JUCE_MSVC
  17046. #pragma warning (push)
  17047. #pragma warning (disable : 4100)
  17048. #endif
  17049. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  17050. add its header directory to your include path.
  17051. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  17052. flag in juce_Config.h
  17053. */
  17054. #include <Movies.h>
  17055. #include <QTML.h>
  17056. #include <QuickTimeComponents.h>
  17057. #include <MediaHandlers.h>
  17058. #include <ImageCodec.h>
  17059. #if JUCE_MSVC
  17060. #pragma warning (pop)
  17061. #endif
  17062. #endif
  17063. BEGIN_JUCE_NAMESPACE
  17064. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  17065. static const char* const quickTimeFormatName = "QuickTime file";
  17066. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", 0 };
  17067. class QTAudioReader : public AudioFormatReader
  17068. {
  17069. public:
  17070. QTAudioReader (InputStream* const input_, const int trackNum_)
  17071. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  17072. ok (false),
  17073. movie (0),
  17074. trackNum (trackNum_),
  17075. lastSampleRead (0),
  17076. lastThreadId (0),
  17077. extractor (0),
  17078. dataHandle (0)
  17079. {
  17080. bufferList.calloc (256, 1);
  17081. #ifdef WIN32
  17082. if (InitializeQTML (0) != noErr)
  17083. return;
  17084. #endif
  17085. if (EnterMovies() != noErr)
  17086. return;
  17087. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  17088. if (! opened)
  17089. return;
  17090. {
  17091. const int numTracks = GetMovieTrackCount (movie);
  17092. int trackCount = 0;
  17093. for (int i = 1; i <= numTracks; ++i)
  17094. {
  17095. track = GetMovieIndTrack (movie, i);
  17096. media = GetTrackMedia (track);
  17097. OSType mediaType;
  17098. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  17099. if (mediaType == SoundMediaType
  17100. && trackCount++ == trackNum_)
  17101. {
  17102. ok = true;
  17103. break;
  17104. }
  17105. }
  17106. }
  17107. if (! ok)
  17108. return;
  17109. ok = false;
  17110. lengthInSamples = GetMediaDecodeDuration (media);
  17111. usesFloatingPointData = false;
  17112. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  17113. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  17114. / GetMediaTimeScale (media);
  17115. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  17116. unsigned long output_layout_size;
  17117. err = MovieAudioExtractionGetPropertyInfo (extractor,
  17118. kQTPropertyClass_MovieAudioExtraction_Audio,
  17119. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17120. 0, &output_layout_size, 0);
  17121. if (err != noErr)
  17122. return;
  17123. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  17124. qt_audio_channel_layout.calloc (output_layout_size, 1);
  17125. err = MovieAudioExtractionGetProperty (extractor,
  17126. kQTPropertyClass_MovieAudioExtraction_Audio,
  17127. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17128. output_layout_size, qt_audio_channel_layout, 0);
  17129. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  17130. err = MovieAudioExtractionSetProperty (extractor,
  17131. kQTPropertyClass_MovieAudioExtraction_Audio,
  17132. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17133. output_layout_size,
  17134. qt_audio_channel_layout);
  17135. err = MovieAudioExtractionGetProperty (extractor,
  17136. kQTPropertyClass_MovieAudioExtraction_Audio,
  17137. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17138. sizeof (inputStreamDesc),
  17139. &inputStreamDesc, 0);
  17140. if (err != noErr)
  17141. return;
  17142. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  17143. | kAudioFormatFlagIsPacked
  17144. | kAudioFormatFlagsNativeEndian;
  17145. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  17146. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  17147. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  17148. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  17149. err = MovieAudioExtractionSetProperty (extractor,
  17150. kQTPropertyClass_MovieAudioExtraction_Audio,
  17151. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17152. sizeof (inputStreamDesc),
  17153. &inputStreamDesc);
  17154. if (err != noErr)
  17155. return;
  17156. Boolean allChannelsDiscrete = false;
  17157. err = MovieAudioExtractionSetProperty (extractor,
  17158. kQTPropertyClass_MovieAudioExtraction_Movie,
  17159. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  17160. sizeof (allChannelsDiscrete),
  17161. &allChannelsDiscrete);
  17162. if (err != noErr)
  17163. return;
  17164. bufferList->mNumberBuffers = 1;
  17165. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  17166. bufferList->mBuffers[0].mDataByteSize = (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16;
  17167. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  17168. bufferList->mBuffers[0].mData = dataBuffer;
  17169. sampleRate = inputStreamDesc.mSampleRate;
  17170. bitsPerSample = 16;
  17171. numChannels = inputStreamDesc.mChannelsPerFrame;
  17172. detachThread();
  17173. ok = true;
  17174. }
  17175. ~QTAudioReader()
  17176. {
  17177. if (dataHandle != 0)
  17178. DisposeHandle (dataHandle);
  17179. if (extractor != 0)
  17180. {
  17181. MovieAudioExtractionEnd (extractor);
  17182. extractor = 0;
  17183. }
  17184. checkThreadIsAttached();
  17185. DisposeMovie (movie);
  17186. #if JUCE_MAC
  17187. ExitMoviesOnThread ();
  17188. #endif
  17189. }
  17190. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17191. int64 startSampleInFile, int numSamples)
  17192. {
  17193. checkThreadIsAttached();
  17194. while (numSamples > 0)
  17195. {
  17196. if (! loadFrame ((int) startSampleInFile))
  17197. return false;
  17198. const int numToDo = jmin (numSamples, samplesPerFrame);
  17199. for (int j = numDestChannels; --j >= 0;)
  17200. {
  17201. if (destSamples[j] != 0)
  17202. {
  17203. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  17204. for (int i = 0; i < numToDo; ++i)
  17205. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  17206. }
  17207. }
  17208. startOffsetInDestBuffer += numToDo;
  17209. startSampleInFile += numToDo;
  17210. numSamples -= numToDo;
  17211. }
  17212. detachThread();
  17213. return true;
  17214. }
  17215. bool loadFrame (const int sampleNum)
  17216. {
  17217. if (lastSampleRead != sampleNum)
  17218. {
  17219. TimeRecord time;
  17220. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  17221. time.base = 0;
  17222. time.value.hi = 0;
  17223. time.value.lo = (UInt32) sampleNum;
  17224. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  17225. kQTPropertyClass_MovieAudioExtraction_Movie,
  17226. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  17227. sizeof (time), &time);
  17228. if (err != noErr)
  17229. return false;
  17230. }
  17231. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * samplesPerFrame;
  17232. UInt32 outFlags = 0;
  17233. UInt32 actualNumSamples = samplesPerFrame;
  17234. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumSamples,
  17235. bufferList, &outFlags);
  17236. lastSampleRead = sampleNum + samplesPerFrame;
  17237. return err == noErr;
  17238. }
  17239. juce_UseDebuggingNewOperator
  17240. bool ok;
  17241. private:
  17242. Movie movie;
  17243. Media media;
  17244. Track track;
  17245. const int trackNum;
  17246. double trackUnitsPerFrame;
  17247. int samplesPerFrame;
  17248. int lastSampleRead;
  17249. Thread::ThreadID lastThreadId;
  17250. MovieAudioExtractionRef extractor;
  17251. AudioStreamBasicDescription inputStreamDesc;
  17252. HeapBlock <AudioBufferList> bufferList;
  17253. HeapBlock <char> dataBuffer;
  17254. Handle dataHandle;
  17255. void checkThreadIsAttached()
  17256. {
  17257. #if JUCE_MAC
  17258. if (Thread::getCurrentThreadId() != lastThreadId)
  17259. EnterMoviesOnThread (0);
  17260. AttachMovieToCurrentThread (movie);
  17261. #endif
  17262. }
  17263. void detachThread()
  17264. {
  17265. #if JUCE_MAC
  17266. DetachMovieFromCurrentThread (movie);
  17267. #endif
  17268. }
  17269. QTAudioReader (const QTAudioReader&);
  17270. QTAudioReader& operator= (const QTAudioReader&);
  17271. };
  17272. QuickTimeAudioFormat::QuickTimeAudioFormat()
  17273. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  17274. {
  17275. }
  17276. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  17277. {
  17278. }
  17279. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates()
  17280. {
  17281. return Array<int>();
  17282. }
  17283. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths()
  17284. {
  17285. return Array<int>();
  17286. }
  17287. bool QuickTimeAudioFormat::canDoStereo()
  17288. {
  17289. return true;
  17290. }
  17291. bool QuickTimeAudioFormat::canDoMono()
  17292. {
  17293. return true;
  17294. }
  17295. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  17296. const bool deleteStreamIfOpeningFails)
  17297. {
  17298. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  17299. if (r->ok)
  17300. return r.release();
  17301. if (! deleteStreamIfOpeningFails)
  17302. r->input = 0;
  17303. return 0;
  17304. }
  17305. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  17306. double /*sampleRateToUse*/,
  17307. unsigned int /*numberOfChannels*/,
  17308. int /*bitsPerSample*/,
  17309. const StringPairArray& /*metadataValues*/,
  17310. int /*qualityOptionIndex*/)
  17311. {
  17312. jassertfalse // not yet implemented!
  17313. return 0;
  17314. }
  17315. END_JUCE_NAMESPACE
  17316. #endif
  17317. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17318. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  17319. BEGIN_JUCE_NAMESPACE
  17320. static const char* const wavFormatName = "WAV file";
  17321. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  17322. const char* const WavAudioFormat::bwavDescription = "bwav description";
  17323. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  17324. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  17325. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  17326. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  17327. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  17328. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  17329. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  17330. const String& originator,
  17331. const String& originatorRef,
  17332. const Time& date,
  17333. const int64 timeReferenceSamples,
  17334. const String& codingHistory)
  17335. {
  17336. StringPairArray m;
  17337. m.set (bwavDescription, description);
  17338. m.set (bwavOriginator, originator);
  17339. m.set (bwavOriginatorRef, originatorRef);
  17340. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  17341. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  17342. m.set (bwavTimeReference, String (timeReferenceSamples));
  17343. m.set (bwavCodingHistory, codingHistory);
  17344. return m;
  17345. }
  17346. #if JUCE_MSVC
  17347. #pragma pack (push, 1)
  17348. #define PACKED
  17349. #elif JUCE_GCC
  17350. #define PACKED __attribute__((packed))
  17351. #else
  17352. #define PACKED
  17353. #endif
  17354. struct BWAVChunk
  17355. {
  17356. char description [256];
  17357. char originator [32];
  17358. char originatorRef [32];
  17359. char originationDate [10];
  17360. char originationTime [8];
  17361. uint32 timeRefLow;
  17362. uint32 timeRefHigh;
  17363. uint16 version;
  17364. uint8 umid[64];
  17365. uint8 reserved[190];
  17366. char codingHistory[1];
  17367. void copyTo (StringPairArray& values) const
  17368. {
  17369. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  17370. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  17371. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  17372. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  17373. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  17374. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  17375. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  17376. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  17377. values.set (WavAudioFormat::bwavTimeReference, String (time));
  17378. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  17379. }
  17380. static MemoryBlock createFrom (const StringPairArray& values)
  17381. {
  17382. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  17383. MemoryBlock data ((sizeNeeded + 3) & ~3);
  17384. data.fillWith (0);
  17385. BWAVChunk* b = (BWAVChunk*) data.getData();
  17386. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  17387. // as they get called in the right order..
  17388. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  17389. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  17390. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  17391. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  17392. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  17393. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  17394. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  17395. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  17396. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  17397. if (b->description[0] != 0
  17398. || b->originator[0] != 0
  17399. || b->originationDate[0] != 0
  17400. || b->originationTime[0] != 0
  17401. || b->codingHistory[0] != 0
  17402. || time != 0)
  17403. {
  17404. return data;
  17405. }
  17406. return MemoryBlock();
  17407. }
  17408. } PACKED;
  17409. struct SMPLChunk
  17410. {
  17411. struct SampleLoop
  17412. {
  17413. uint32 identifier;
  17414. uint32 type;
  17415. uint32 start;
  17416. uint32 end;
  17417. uint32 fraction;
  17418. uint32 playCount;
  17419. } PACKED;
  17420. uint32 manufacturer;
  17421. uint32 product;
  17422. uint32 samplePeriod;
  17423. uint32 midiUnityNote;
  17424. uint32 midiPitchFraction;
  17425. uint32 smpteFormat;
  17426. uint32 smpteOffset;
  17427. uint32 numSampleLoops;
  17428. uint32 samplerData;
  17429. SampleLoop loops[1];
  17430. void copyTo (StringPairArray& values, const int totalSize) const
  17431. {
  17432. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  17433. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  17434. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  17435. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  17436. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  17437. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  17438. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  17439. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  17440. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  17441. for (uint32 i = 0; i < numSampleLoops; ++i)
  17442. {
  17443. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  17444. break;
  17445. const String prefix ("Loop" + String(i));
  17446. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  17447. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  17448. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  17449. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  17450. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  17451. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  17452. }
  17453. }
  17454. static MemoryBlock createFrom (const StringPairArray& values)
  17455. {
  17456. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  17457. if (numLoops <= 0)
  17458. return MemoryBlock();
  17459. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  17460. MemoryBlock data ((sizeNeeded + 3) & ~3);
  17461. data.fillWith (0);
  17462. SMPLChunk* s = (SMPLChunk*) data.getData();
  17463. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  17464. // as they get called in the right order..
  17465. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  17466. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  17467. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  17468. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  17469. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  17470. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  17471. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  17472. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  17473. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  17474. for (int i = 0; i < numLoops; ++i)
  17475. {
  17476. const String prefix ("Loop" + String(i));
  17477. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  17478. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  17479. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  17480. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  17481. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  17482. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  17483. }
  17484. return data;
  17485. }
  17486. } PACKED;
  17487. struct ExtensibleWavSubFormat
  17488. {
  17489. uint32 data1;
  17490. uint16 data2;
  17491. uint16 data3;
  17492. uint8 data4[8];
  17493. } PACKED;
  17494. #if JUCE_MSVC
  17495. #pragma pack (pop)
  17496. #endif
  17497. #undef PACKED
  17498. class WavAudioFormatReader : public AudioFormatReader
  17499. {
  17500. int bytesPerFrame;
  17501. int64 dataChunkStart, dataLength;
  17502. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  17503. WavAudioFormatReader (const WavAudioFormatReader&);
  17504. WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  17505. public:
  17506. int64 bwavChunkStart, bwavSize;
  17507. WavAudioFormatReader (InputStream* const in)
  17508. : AudioFormatReader (in, TRANS (wavFormatName)),
  17509. dataLength (0),
  17510. bwavChunkStart (0),
  17511. bwavSize (0)
  17512. {
  17513. if (input->readInt() == chunkName ("RIFF"))
  17514. {
  17515. const uint32 len = (uint32) input->readInt();
  17516. const int64 end = input->getPosition() + len;
  17517. bool hasGotType = false;
  17518. bool hasGotData = false;
  17519. if (input->readInt() == chunkName ("WAVE"))
  17520. {
  17521. while (input->getPosition() < end
  17522. && ! input->isExhausted())
  17523. {
  17524. const int chunkType = input->readInt();
  17525. uint32 length = (uint32) input->readInt();
  17526. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  17527. if (chunkType == chunkName ("fmt "))
  17528. {
  17529. // read the format chunk
  17530. const unsigned short format = input->readShort();
  17531. const short numChans = input->readShort();
  17532. sampleRate = input->readInt();
  17533. const int bytesPerSec = input->readInt();
  17534. numChannels = numChans;
  17535. bytesPerFrame = bytesPerSec / (int)sampleRate;
  17536. bitsPerSample = 8 * bytesPerFrame / numChans;
  17537. if (format == 3)
  17538. {
  17539. usesFloatingPointData = true;
  17540. }
  17541. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  17542. {
  17543. if (length < 40) // too short
  17544. {
  17545. bytesPerFrame = 0;
  17546. }
  17547. else
  17548. {
  17549. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  17550. ExtensibleWavSubFormat subFormat;
  17551. subFormat.data1 = input->readInt();
  17552. subFormat.data2 = input->readShort();
  17553. subFormat.data3 = input->readShort();
  17554. input->read (subFormat.data4, sizeof (subFormat.data4));
  17555. const ExtensibleWavSubFormat pcmFormat
  17556. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  17557. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  17558. {
  17559. const ExtensibleWavSubFormat ambisonicFormat
  17560. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  17561. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  17562. bytesPerFrame = 0;
  17563. }
  17564. }
  17565. }
  17566. else if (format != 1)
  17567. {
  17568. bytesPerFrame = 0;
  17569. }
  17570. hasGotType = true;
  17571. }
  17572. else if (chunkType == chunkName ("data"))
  17573. {
  17574. // get the data chunk's position
  17575. dataLength = length;
  17576. dataChunkStart = input->getPosition();
  17577. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  17578. hasGotData = true;
  17579. }
  17580. else if (chunkType == chunkName ("bext"))
  17581. {
  17582. bwavChunkStart = input->getPosition();
  17583. bwavSize = length;
  17584. // Broadcast-wav extension chunk..
  17585. HeapBlock <BWAVChunk> bwav;
  17586. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  17587. input->read (bwav, length);
  17588. bwav->copyTo (metadataValues);
  17589. }
  17590. else if (chunkType == chunkName ("smpl"))
  17591. {
  17592. HeapBlock <SMPLChunk> smpl;
  17593. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  17594. input->read (smpl, length);
  17595. smpl->copyTo (metadataValues, length);
  17596. }
  17597. else if (chunkEnd <= input->getPosition())
  17598. {
  17599. break;
  17600. }
  17601. input->setPosition (chunkEnd);
  17602. }
  17603. }
  17604. }
  17605. }
  17606. ~WavAudioFormatReader()
  17607. {
  17608. }
  17609. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17610. int64 startSampleInFile, int numSamples)
  17611. {
  17612. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  17613. if (samplesAvailable < numSamples)
  17614. {
  17615. for (int i = numDestChannels; --i >= 0;)
  17616. if (destSamples[i] != 0)
  17617. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  17618. numSamples = (int) samplesAvailable;
  17619. }
  17620. if (numSamples <= 0)
  17621. return true;
  17622. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  17623. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  17624. char tempBuffer [tempBufSize];
  17625. while (numSamples > 0)
  17626. {
  17627. int* left = destSamples[0];
  17628. if (left != 0)
  17629. left += startOffsetInDestBuffer;
  17630. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  17631. if (right != 0)
  17632. right += startOffsetInDestBuffer;
  17633. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  17634. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  17635. if (bytesRead < numThisTime * bytesPerFrame)
  17636. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  17637. if (bitsPerSample == 16)
  17638. {
  17639. const short* src = reinterpret_cast <const short*> (tempBuffer);
  17640. if (numChannels > 1)
  17641. {
  17642. if (left == 0)
  17643. {
  17644. for (int i = numThisTime; --i >= 0;)
  17645. {
  17646. ++src;
  17647. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17648. }
  17649. }
  17650. else if (right == 0)
  17651. {
  17652. for (int i = numThisTime; --i >= 0;)
  17653. {
  17654. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17655. ++src;
  17656. }
  17657. }
  17658. else
  17659. {
  17660. for (int i = numThisTime; --i >= 0;)
  17661. {
  17662. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17663. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17664. }
  17665. }
  17666. }
  17667. else
  17668. {
  17669. for (int i = numThisTime; --i >= 0;)
  17670. {
  17671. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17672. }
  17673. }
  17674. }
  17675. else if (bitsPerSample == 24)
  17676. {
  17677. const char* src = tempBuffer;
  17678. if (numChannels > 1)
  17679. {
  17680. if (left == 0)
  17681. {
  17682. for (int i = numThisTime; --i >= 0;)
  17683. {
  17684. src += 3;
  17685. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  17686. src += 3;
  17687. }
  17688. }
  17689. else if (right == 0)
  17690. {
  17691. for (int i = numThisTime; --i >= 0;)
  17692. {
  17693. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17694. src += 6;
  17695. }
  17696. }
  17697. else
  17698. {
  17699. for (int i = 0; i < numThisTime; ++i)
  17700. {
  17701. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17702. src += 3;
  17703. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  17704. src += 3;
  17705. }
  17706. }
  17707. }
  17708. else
  17709. {
  17710. for (int i = 0; i < numThisTime; ++i)
  17711. {
  17712. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17713. src += 3;
  17714. }
  17715. }
  17716. }
  17717. else if (bitsPerSample == 32)
  17718. {
  17719. const unsigned int* src = (const unsigned int*) tempBuffer;
  17720. unsigned int* l = (unsigned int*) left;
  17721. unsigned int* r = (unsigned int*) right;
  17722. if (numChannels > 1)
  17723. {
  17724. if (l == 0)
  17725. {
  17726. for (int i = numThisTime; --i >= 0;)
  17727. {
  17728. ++src;
  17729. *r++ = ByteOrder::swapIfBigEndian (*src++);
  17730. }
  17731. }
  17732. else if (r == 0)
  17733. {
  17734. for (int i = numThisTime; --i >= 0;)
  17735. {
  17736. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17737. ++src;
  17738. }
  17739. }
  17740. else
  17741. {
  17742. for (int i = numThisTime; --i >= 0;)
  17743. {
  17744. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17745. *r++ = ByteOrder::swapIfBigEndian (*src++);
  17746. }
  17747. }
  17748. }
  17749. else
  17750. {
  17751. for (int i = numThisTime; --i >= 0;)
  17752. {
  17753. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17754. }
  17755. }
  17756. left = (int*)l;
  17757. right = (int*)r;
  17758. }
  17759. else if (bitsPerSample == 8)
  17760. {
  17761. const unsigned char* src = (const unsigned char*) tempBuffer;
  17762. if (numChannels > 1)
  17763. {
  17764. if (left == 0)
  17765. {
  17766. for (int i = numThisTime; --i >= 0;)
  17767. {
  17768. ++src;
  17769. *right++ = ((int) *src++ - 128) << 24;
  17770. }
  17771. }
  17772. else if (right == 0)
  17773. {
  17774. for (int i = numThisTime; --i >= 0;)
  17775. {
  17776. *left++ = ((int) *src++ - 128) << 24;
  17777. ++src;
  17778. }
  17779. }
  17780. else
  17781. {
  17782. for (int i = numThisTime; --i >= 0;)
  17783. {
  17784. *left++ = ((int) *src++ - 128) << 24;
  17785. *right++ = ((int) *src++ - 128) << 24;
  17786. }
  17787. }
  17788. }
  17789. else
  17790. {
  17791. for (int i = numThisTime; --i >= 0;)
  17792. {
  17793. *left++ = ((int)*src++ - 128) << 24;
  17794. }
  17795. }
  17796. }
  17797. startOffsetInDestBuffer += numThisTime;
  17798. numSamples -= numThisTime;
  17799. }
  17800. if (numSamples > 0)
  17801. {
  17802. for (int i = numDestChannels; --i >= 0;)
  17803. if (destSamples[i] != 0)
  17804. zeromem (destSamples[i] + startOffsetInDestBuffer,
  17805. sizeof (int) * numSamples);
  17806. }
  17807. return true;
  17808. }
  17809. juce_UseDebuggingNewOperator
  17810. };
  17811. class WavAudioFormatWriter : public AudioFormatWriter
  17812. {
  17813. MemoryBlock tempBlock, bwavChunk, smplChunk;
  17814. uint32 lengthInSamples, bytesWritten;
  17815. int64 headerPosition;
  17816. bool writeFailed;
  17817. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  17818. WavAudioFormatWriter (const WavAudioFormatWriter&);
  17819. WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  17820. void writeHeader()
  17821. {
  17822. const bool seekedOk = output->setPosition (headerPosition);
  17823. (void) seekedOk;
  17824. // if this fails, you've given it an output stream that can't seek! It needs
  17825. // to be able to seek back to write the header
  17826. jassert (seekedOk);
  17827. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  17828. output->writeInt (chunkName ("RIFF"));
  17829. output->writeInt ((int) (lengthInSamples * bytesPerFrame
  17830. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36)));
  17831. output->writeInt (chunkName ("WAVE"));
  17832. output->writeInt (chunkName ("fmt "));
  17833. output->writeInt (16);
  17834. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  17835. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  17836. output->writeShort ((short) numChannels);
  17837. output->writeInt ((int) sampleRate);
  17838. output->writeInt (bytesPerFrame * (int) sampleRate);
  17839. output->writeShort ((short) bytesPerFrame);
  17840. output->writeShort ((short) bitsPerSample);
  17841. if (bwavChunk.getSize() > 0)
  17842. {
  17843. output->writeInt (chunkName ("bext"));
  17844. output->writeInt ((int) bwavChunk.getSize());
  17845. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  17846. }
  17847. if (smplChunk.getSize() > 0)
  17848. {
  17849. output->writeInt (chunkName ("smpl"));
  17850. output->writeInt ((int) smplChunk.getSize());
  17851. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  17852. }
  17853. output->writeInt (chunkName ("data"));
  17854. output->writeInt (lengthInSamples * bytesPerFrame);
  17855. usesFloatingPointData = (bitsPerSample == 32);
  17856. }
  17857. public:
  17858. WavAudioFormatWriter (OutputStream* const out,
  17859. const double sampleRate_,
  17860. const unsigned int numChannels_,
  17861. const int bits,
  17862. const StringPairArray& metadataValues)
  17863. : AudioFormatWriter (out,
  17864. TRANS (wavFormatName),
  17865. sampleRate_,
  17866. numChannels_,
  17867. bits),
  17868. lengthInSamples (0),
  17869. bytesWritten (0),
  17870. writeFailed (false)
  17871. {
  17872. if (metadataValues.size() > 0)
  17873. {
  17874. bwavChunk = BWAVChunk::createFrom (metadataValues);
  17875. smplChunk = SMPLChunk::createFrom (metadataValues);
  17876. }
  17877. headerPosition = out->getPosition();
  17878. writeHeader();
  17879. }
  17880. ~WavAudioFormatWriter()
  17881. {
  17882. writeHeader();
  17883. }
  17884. bool write (const int** data, int numSamples)
  17885. {
  17886. if (writeFailed)
  17887. return false;
  17888. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  17889. tempBlock.ensureSize (bytes, false);
  17890. char* buffer = static_cast <char*> (tempBlock.getData());
  17891. const int* left = data[0];
  17892. const int* right = data[1];
  17893. if (right == 0)
  17894. right = left;
  17895. if (bitsPerSample == 16)
  17896. {
  17897. short* b = (short*) buffer;
  17898. if (numChannels > 1)
  17899. {
  17900. for (int i = numSamples; --i >= 0;)
  17901. {
  17902. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17903. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*right++ >> 16));
  17904. }
  17905. }
  17906. else
  17907. {
  17908. for (int i = numSamples; --i >= 0;)
  17909. {
  17910. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17911. }
  17912. }
  17913. }
  17914. else if (bitsPerSample == 24)
  17915. {
  17916. char* b = buffer;
  17917. if (numChannels > 1)
  17918. {
  17919. for (int i = numSamples; --i >= 0;)
  17920. {
  17921. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  17922. b += 3;
  17923. ByteOrder::littleEndian24BitToChars ((*right++) >> 8, b);
  17924. b += 3;
  17925. }
  17926. }
  17927. else
  17928. {
  17929. for (int i = numSamples; --i >= 0;)
  17930. {
  17931. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  17932. b += 3;
  17933. }
  17934. }
  17935. }
  17936. else if (bitsPerSample == 32)
  17937. {
  17938. unsigned int* b = (unsigned int*) buffer;
  17939. if (numChannels > 1)
  17940. {
  17941. for (int i = numSamples; --i >= 0;)
  17942. {
  17943. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  17944. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *right++);
  17945. }
  17946. }
  17947. else
  17948. {
  17949. for (int i = numSamples; --i >= 0;)
  17950. {
  17951. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  17952. }
  17953. }
  17954. }
  17955. else if (bitsPerSample == 8)
  17956. {
  17957. unsigned char* b = (unsigned char*) buffer;
  17958. if (numChannels > 1)
  17959. {
  17960. for (int i = numSamples; --i >= 0;)
  17961. {
  17962. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17963. *b++ = (unsigned char) (128 + (*right++ >> 24));
  17964. }
  17965. }
  17966. else
  17967. {
  17968. for (int i = numSamples; --i >= 0;)
  17969. {
  17970. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17971. }
  17972. }
  17973. }
  17974. if (bytesWritten + bytes >= (uint32) 0xfff00000
  17975. || ! output->write (buffer, bytes))
  17976. {
  17977. // failed to write to disk, so let's try writing the header.
  17978. // If it's just run out of disk space, then if it does manage
  17979. // to write the header, we'll still have a useable file..
  17980. writeHeader();
  17981. writeFailed = true;
  17982. return false;
  17983. }
  17984. else
  17985. {
  17986. bytesWritten += bytes;
  17987. lengthInSamples += numSamples;
  17988. return true;
  17989. }
  17990. }
  17991. juce_UseDebuggingNewOperator
  17992. };
  17993. WavAudioFormat::WavAudioFormat()
  17994. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  17995. {
  17996. }
  17997. WavAudioFormat::~WavAudioFormat()
  17998. {
  17999. }
  18000. const Array <int> WavAudioFormat::getPossibleSampleRates()
  18001. {
  18002. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  18003. return Array <int> (rates);
  18004. }
  18005. const Array <int> WavAudioFormat::getPossibleBitDepths()
  18006. {
  18007. const int depths[] = { 8, 16, 24, 32, 0 };
  18008. return Array <int> (depths);
  18009. }
  18010. bool WavAudioFormat::canDoStereo()
  18011. {
  18012. return true;
  18013. }
  18014. bool WavAudioFormat::canDoMono()
  18015. {
  18016. return true;
  18017. }
  18018. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18019. const bool deleteStreamIfOpeningFails)
  18020. {
  18021. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18022. if (r->sampleRate != 0)
  18023. return r.release();
  18024. if (! deleteStreamIfOpeningFails)
  18025. r->input = 0;
  18026. return 0;
  18027. }
  18028. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  18029. double sampleRate,
  18030. unsigned int numChannels,
  18031. int bitsPerSample,
  18032. const StringPairArray& metadataValues,
  18033. int /*qualityOptionIndex*/)
  18034. {
  18035. if (getPossibleBitDepths().contains (bitsPerSample))
  18036. {
  18037. return new WavAudioFormatWriter (out,
  18038. sampleRate,
  18039. numChannels,
  18040. bitsPerSample,
  18041. metadataValues);
  18042. }
  18043. return 0;
  18044. }
  18045. static bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18046. {
  18047. TemporaryFile tempFile (file);
  18048. WavAudioFormat wav;
  18049. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18050. if (reader != 0)
  18051. {
  18052. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18053. if (outStream != 0)
  18054. {
  18055. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18056. reader->numChannels, reader->bitsPerSample,
  18057. metadata, 0));
  18058. if (writer != 0)
  18059. {
  18060. outStream.release();
  18061. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18062. writer = 0;
  18063. reader = 0;
  18064. return ok && tempFile.overwriteTargetFileWithTemporary();
  18065. }
  18066. }
  18067. }
  18068. return false;
  18069. }
  18070. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18071. {
  18072. ScopedPointer <WavAudioFormatReader> reader ((WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true));
  18073. if (reader != 0)
  18074. {
  18075. const int64 bwavPos = reader->bwavChunkStart;
  18076. const int64 bwavSize = reader->bwavSize;
  18077. reader = 0;
  18078. if (bwavSize > 0)
  18079. {
  18080. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  18081. if (chunk.getSize() <= (size_t) bwavSize)
  18082. {
  18083. // the new one will fit in the space available, so write it directly..
  18084. const int64 oldSize = wavFile.getSize();
  18085. {
  18086. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  18087. out->setPosition (bwavPos);
  18088. out->write (chunk.getData(), (int) chunk.getSize());
  18089. out->setPosition (oldSize);
  18090. }
  18091. jassert (wavFile.getSize() == oldSize);
  18092. return true;
  18093. }
  18094. }
  18095. }
  18096. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  18097. }
  18098. END_JUCE_NAMESPACE
  18099. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  18100. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18101. BEGIN_JUCE_NAMESPACE
  18102. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  18103. const bool deleteReaderWhenThisIsDeleted)
  18104. : reader (reader_),
  18105. deleteReader (deleteReaderWhenThisIsDeleted),
  18106. nextPlayPos (0),
  18107. looping (false)
  18108. {
  18109. jassert (reader != 0);
  18110. }
  18111. AudioFormatReaderSource::~AudioFormatReaderSource()
  18112. {
  18113. releaseResources();
  18114. if (deleteReader)
  18115. delete reader;
  18116. }
  18117. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  18118. {
  18119. nextPlayPos = newPosition;
  18120. }
  18121. void AudioFormatReaderSource::setLooping (const bool shouldLoop) throw()
  18122. {
  18123. looping = shouldLoop;
  18124. }
  18125. int AudioFormatReaderSource::getNextReadPosition() const
  18126. {
  18127. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  18128. : nextPlayPos;
  18129. }
  18130. int AudioFormatReaderSource::getTotalLength() const
  18131. {
  18132. return (int) reader->lengthInSamples;
  18133. }
  18134. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18135. double /*sampleRate*/)
  18136. {
  18137. }
  18138. void AudioFormatReaderSource::releaseResources()
  18139. {
  18140. }
  18141. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18142. {
  18143. if (info.numSamples > 0)
  18144. {
  18145. const int start = nextPlayPos;
  18146. if (looping)
  18147. {
  18148. const int newStart = start % (int) reader->lengthInSamples;
  18149. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  18150. if (newEnd > newStart)
  18151. {
  18152. info.buffer->readFromAudioReader (reader,
  18153. info.startSample,
  18154. newEnd - newStart,
  18155. newStart,
  18156. true, true);
  18157. }
  18158. else
  18159. {
  18160. const int endSamps = (int) reader->lengthInSamples - newStart;
  18161. info.buffer->readFromAudioReader (reader,
  18162. info.startSample,
  18163. endSamps,
  18164. newStart,
  18165. true, true);
  18166. info.buffer->readFromAudioReader (reader,
  18167. info.startSample + endSamps,
  18168. newEnd,
  18169. 0,
  18170. true, true);
  18171. }
  18172. nextPlayPos = newEnd;
  18173. }
  18174. else
  18175. {
  18176. info.buffer->readFromAudioReader (reader,
  18177. info.startSample,
  18178. info.numSamples,
  18179. start,
  18180. true, true);
  18181. nextPlayPos += info.numSamples;
  18182. }
  18183. }
  18184. }
  18185. END_JUCE_NAMESPACE
  18186. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18187. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  18188. BEGIN_JUCE_NAMESPACE
  18189. AudioSourcePlayer::AudioSourcePlayer()
  18190. : source (0),
  18191. sampleRate (0),
  18192. bufferSize (0),
  18193. tempBuffer (2, 8),
  18194. lastGain (1.0f),
  18195. gain (1.0f)
  18196. {
  18197. }
  18198. AudioSourcePlayer::~AudioSourcePlayer()
  18199. {
  18200. setSource (0);
  18201. }
  18202. void AudioSourcePlayer::setSource (AudioSource* newSource)
  18203. {
  18204. if (source != newSource)
  18205. {
  18206. AudioSource* const oldSource = source;
  18207. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  18208. newSource->prepareToPlay (bufferSize, sampleRate);
  18209. {
  18210. const ScopedLock sl (readLock);
  18211. source = newSource;
  18212. }
  18213. if (oldSource != 0)
  18214. oldSource->releaseResources();
  18215. }
  18216. }
  18217. void AudioSourcePlayer::setGain (const float newGain) throw()
  18218. {
  18219. gain = newGain;
  18220. }
  18221. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  18222. int totalNumInputChannels,
  18223. float** outputChannelData,
  18224. int totalNumOutputChannels,
  18225. int numSamples)
  18226. {
  18227. // these should have been prepared by audioDeviceAboutToStart()...
  18228. jassert (sampleRate > 0 && bufferSize > 0);
  18229. const ScopedLock sl (readLock);
  18230. if (source != 0)
  18231. {
  18232. AudioSourceChannelInfo info;
  18233. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  18234. // messy stuff needed to compact the channels down into an array
  18235. // of non-zero pointers..
  18236. for (i = 0; i < totalNumInputChannels; ++i)
  18237. {
  18238. if (inputChannelData[i] != 0)
  18239. {
  18240. inputChans [numInputs++] = inputChannelData[i];
  18241. if (numInputs >= numElementsInArray (inputChans))
  18242. break;
  18243. }
  18244. }
  18245. for (i = 0; i < totalNumOutputChannels; ++i)
  18246. {
  18247. if (outputChannelData[i] != 0)
  18248. {
  18249. outputChans [numOutputs++] = outputChannelData[i];
  18250. if (numOutputs >= numElementsInArray (outputChans))
  18251. break;
  18252. }
  18253. }
  18254. if (numInputs > numOutputs)
  18255. {
  18256. // if there aren't enough output channels for the number of
  18257. // inputs, we need to create some temporary extra ones (can't
  18258. // use the input data in case it gets written to)
  18259. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  18260. false, false, true);
  18261. for (i = 0; i < numOutputs; ++i)
  18262. {
  18263. channels[numActiveChans] = outputChans[i];
  18264. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18265. ++numActiveChans;
  18266. }
  18267. for (i = numOutputs; i < numInputs; ++i)
  18268. {
  18269. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  18270. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18271. ++numActiveChans;
  18272. }
  18273. }
  18274. else
  18275. {
  18276. for (i = 0; i < numInputs; ++i)
  18277. {
  18278. channels[numActiveChans] = outputChans[i];
  18279. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18280. ++numActiveChans;
  18281. }
  18282. for (i = numInputs; i < numOutputs; ++i)
  18283. {
  18284. channels[numActiveChans] = outputChans[i];
  18285. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  18286. ++numActiveChans;
  18287. }
  18288. }
  18289. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  18290. info.buffer = &buffer;
  18291. info.startSample = 0;
  18292. info.numSamples = numSamples;
  18293. source->getNextAudioBlock (info);
  18294. for (i = info.buffer->getNumChannels(); --i >= 0;)
  18295. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  18296. lastGain = gain;
  18297. }
  18298. else
  18299. {
  18300. for (int i = 0; i < totalNumOutputChannels; ++i)
  18301. if (outputChannelData[i] != 0)
  18302. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  18303. }
  18304. }
  18305. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  18306. {
  18307. sampleRate = device->getCurrentSampleRate();
  18308. bufferSize = device->getCurrentBufferSizeSamples();
  18309. zeromem (channels, sizeof (channels));
  18310. if (source != 0)
  18311. source->prepareToPlay (bufferSize, sampleRate);
  18312. }
  18313. void AudioSourcePlayer::audioDeviceStopped()
  18314. {
  18315. if (source != 0)
  18316. source->releaseResources();
  18317. sampleRate = 0.0;
  18318. bufferSize = 0;
  18319. tempBuffer.setSize (2, 8);
  18320. }
  18321. END_JUCE_NAMESPACE
  18322. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  18323. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  18324. BEGIN_JUCE_NAMESPACE
  18325. AudioTransportSource::AudioTransportSource()
  18326. : source (0),
  18327. resamplerSource (0),
  18328. bufferingSource (0),
  18329. positionableSource (0),
  18330. masterSource (0),
  18331. gain (1.0f),
  18332. lastGain (1.0f),
  18333. playing (false),
  18334. stopped (true),
  18335. sampleRate (44100.0),
  18336. sourceSampleRate (0.0),
  18337. blockSize (128),
  18338. readAheadBufferSize (0),
  18339. isPrepared (false),
  18340. inputStreamEOF (false)
  18341. {
  18342. }
  18343. AudioTransportSource::~AudioTransportSource()
  18344. {
  18345. setSource (0);
  18346. releaseResources();
  18347. }
  18348. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  18349. int readAheadBufferSize_,
  18350. double sourceSampleRateToCorrectFor)
  18351. {
  18352. if (source == newSource)
  18353. {
  18354. if (source == 0)
  18355. return;
  18356. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  18357. }
  18358. readAheadBufferSize = readAheadBufferSize_;
  18359. sourceSampleRate = sourceSampleRateToCorrectFor;
  18360. ResamplingAudioSource* newResamplerSource = 0;
  18361. BufferingAudioSource* newBufferingSource = 0;
  18362. PositionableAudioSource* newPositionableSource = 0;
  18363. AudioSource* newMasterSource = 0;
  18364. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  18365. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  18366. AudioSource* oldMasterSource = masterSource;
  18367. if (newSource != 0)
  18368. {
  18369. newPositionableSource = newSource;
  18370. if (readAheadBufferSize_ > 0)
  18371. newPositionableSource = newBufferingSource
  18372. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  18373. newPositionableSource->setNextReadPosition (0);
  18374. if (sourceSampleRateToCorrectFor != 0)
  18375. newMasterSource = newResamplerSource
  18376. = new ResamplingAudioSource (newPositionableSource, false);
  18377. else
  18378. newMasterSource = newPositionableSource;
  18379. if (isPrepared)
  18380. {
  18381. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  18382. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  18383. newMasterSource->prepareToPlay (blockSize, sampleRate);
  18384. }
  18385. }
  18386. {
  18387. const ScopedLock sl (callbackLock);
  18388. source = newSource;
  18389. resamplerSource = newResamplerSource;
  18390. bufferingSource = newBufferingSource;
  18391. masterSource = newMasterSource;
  18392. positionableSource = newPositionableSource;
  18393. playing = false;
  18394. }
  18395. if (oldMasterSource != 0)
  18396. oldMasterSource->releaseResources();
  18397. }
  18398. void AudioTransportSource::start()
  18399. {
  18400. if ((! playing) && masterSource != 0)
  18401. {
  18402. {
  18403. const ScopedLock sl (callbackLock);
  18404. playing = true;
  18405. stopped = false;
  18406. inputStreamEOF = false;
  18407. }
  18408. sendChangeMessage (this);
  18409. }
  18410. }
  18411. void AudioTransportSource::stop()
  18412. {
  18413. if (playing)
  18414. {
  18415. {
  18416. const ScopedLock sl (callbackLock);
  18417. playing = false;
  18418. }
  18419. int n = 500;
  18420. while (--n >= 0 && ! stopped)
  18421. Thread::sleep (2);
  18422. sendChangeMessage (this);
  18423. }
  18424. }
  18425. void AudioTransportSource::setPosition (double newPosition)
  18426. {
  18427. if (sampleRate > 0.0)
  18428. setNextReadPosition (roundToInt (newPosition * sampleRate));
  18429. }
  18430. double AudioTransportSource::getCurrentPosition() const
  18431. {
  18432. if (sampleRate > 0.0)
  18433. return getNextReadPosition() / sampleRate;
  18434. else
  18435. return 0.0;
  18436. }
  18437. void AudioTransportSource::setNextReadPosition (int newPosition)
  18438. {
  18439. if (positionableSource != 0)
  18440. {
  18441. if (sampleRate > 0 && sourceSampleRate > 0)
  18442. newPosition = roundToInt (newPosition * sourceSampleRate / sampleRate);
  18443. positionableSource->setNextReadPosition (newPosition);
  18444. }
  18445. }
  18446. int AudioTransportSource::getNextReadPosition() const
  18447. {
  18448. if (positionableSource != 0)
  18449. {
  18450. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  18451. return roundToInt (positionableSource->getNextReadPosition() * ratio);
  18452. }
  18453. return 0;
  18454. }
  18455. int AudioTransportSource::getTotalLength() const
  18456. {
  18457. const ScopedLock sl (callbackLock);
  18458. if (positionableSource != 0)
  18459. {
  18460. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  18461. return roundToInt (positionableSource->getTotalLength() * ratio);
  18462. }
  18463. return 0;
  18464. }
  18465. bool AudioTransportSource::isLooping() const
  18466. {
  18467. const ScopedLock sl (callbackLock);
  18468. return positionableSource != 0
  18469. && positionableSource->isLooping();
  18470. }
  18471. void AudioTransportSource::setGain (const float newGain) throw()
  18472. {
  18473. gain = newGain;
  18474. }
  18475. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  18476. double sampleRate_)
  18477. {
  18478. const ScopedLock sl (callbackLock);
  18479. sampleRate = sampleRate_;
  18480. blockSize = samplesPerBlockExpected;
  18481. if (masterSource != 0)
  18482. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18483. if (resamplerSource != 0 && sourceSampleRate != 0)
  18484. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  18485. isPrepared = true;
  18486. }
  18487. void AudioTransportSource::releaseResources()
  18488. {
  18489. const ScopedLock sl (callbackLock);
  18490. if (masterSource != 0)
  18491. masterSource->releaseResources();
  18492. isPrepared = false;
  18493. }
  18494. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18495. {
  18496. const ScopedLock sl (callbackLock);
  18497. inputStreamEOF = false;
  18498. if (masterSource != 0 && ! stopped)
  18499. {
  18500. masterSource->getNextAudioBlock (info);
  18501. if (! playing)
  18502. {
  18503. // just stopped playing, so fade out the last block..
  18504. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  18505. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  18506. if (info.numSamples > 256)
  18507. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  18508. }
  18509. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  18510. && ! positionableSource->isLooping())
  18511. {
  18512. playing = false;
  18513. inputStreamEOF = true;
  18514. sendChangeMessage (this);
  18515. }
  18516. stopped = ! playing;
  18517. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  18518. {
  18519. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  18520. lastGain, gain);
  18521. }
  18522. }
  18523. else
  18524. {
  18525. info.clearActiveBufferRegion();
  18526. stopped = true;
  18527. }
  18528. lastGain = gain;
  18529. }
  18530. END_JUCE_NAMESPACE
  18531. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  18532. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  18533. BEGIN_JUCE_NAMESPACE
  18534. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  18535. public Thread,
  18536. private Timer
  18537. {
  18538. public:
  18539. SharedBufferingAudioSourceThread()
  18540. : Thread ("Audio Buffer")
  18541. {
  18542. }
  18543. ~SharedBufferingAudioSourceThread()
  18544. {
  18545. stopThread (10000);
  18546. clearSingletonInstance();
  18547. }
  18548. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  18549. void addSource (BufferingAudioSource* source)
  18550. {
  18551. const ScopedLock sl (lock);
  18552. if (! sources.contains (source))
  18553. {
  18554. sources.add (source);
  18555. startThread();
  18556. stopTimer();
  18557. }
  18558. notify();
  18559. }
  18560. void removeSource (BufferingAudioSource* source)
  18561. {
  18562. const ScopedLock sl (lock);
  18563. sources.removeValue (source);
  18564. if (sources.size() == 0)
  18565. startTimer (5000);
  18566. }
  18567. private:
  18568. Array <BufferingAudioSource*> sources;
  18569. CriticalSection lock;
  18570. void run()
  18571. {
  18572. while (! threadShouldExit())
  18573. {
  18574. bool busy = false;
  18575. for (int i = sources.size(); --i >= 0;)
  18576. {
  18577. if (threadShouldExit())
  18578. return;
  18579. const ScopedLock sl (lock);
  18580. BufferingAudioSource* const b = sources[i];
  18581. if (b != 0 && b->readNextBufferChunk())
  18582. busy = true;
  18583. }
  18584. if (! busy)
  18585. wait (500);
  18586. }
  18587. }
  18588. void timerCallback()
  18589. {
  18590. stopTimer();
  18591. if (sources.size() == 0)
  18592. deleteInstance();
  18593. }
  18594. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  18595. SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  18596. };
  18597. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  18598. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  18599. const bool deleteSourceWhenDeleted_,
  18600. int numberOfSamplesToBuffer_)
  18601. : source (source_),
  18602. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18603. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  18604. buffer (2, 0),
  18605. bufferValidStart (0),
  18606. bufferValidEnd (0),
  18607. nextPlayPos (0),
  18608. wasSourceLooping (false)
  18609. {
  18610. jassert (source_ != 0);
  18611. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  18612. // not using a larger buffer..
  18613. }
  18614. BufferingAudioSource::~BufferingAudioSource()
  18615. {
  18616. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18617. if (thread != 0)
  18618. thread->removeSource (this);
  18619. if (deleteSourceWhenDeleted)
  18620. delete source;
  18621. }
  18622. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  18623. {
  18624. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  18625. sampleRate = sampleRate_;
  18626. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  18627. buffer.clear();
  18628. bufferValidStart = 0;
  18629. bufferValidEnd = 0;
  18630. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  18631. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  18632. buffer.getNumSamples() / 2))
  18633. {
  18634. SharedBufferingAudioSourceThread::getInstance()->notify();
  18635. Thread::sleep (5);
  18636. }
  18637. }
  18638. void BufferingAudioSource::releaseResources()
  18639. {
  18640. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18641. if (thread != 0)
  18642. thread->removeSource (this);
  18643. buffer.setSize (2, 0);
  18644. source->releaseResources();
  18645. }
  18646. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18647. {
  18648. const ScopedLock sl (bufferStartPosLock);
  18649. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  18650. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  18651. if (validStart == validEnd)
  18652. {
  18653. // total cache miss
  18654. info.clearActiveBufferRegion();
  18655. }
  18656. else
  18657. {
  18658. if (validStart > 0)
  18659. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  18660. if (validEnd < info.numSamples)
  18661. info.buffer->clear (info.startSample + validEnd,
  18662. info.numSamples - validEnd); // partial cache miss at end
  18663. if (validStart < validEnd)
  18664. {
  18665. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  18666. {
  18667. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  18668. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  18669. if (startBufferIndex < endBufferIndex)
  18670. {
  18671. info.buffer->copyFrom (chan, info.startSample + validStart,
  18672. buffer,
  18673. chan, startBufferIndex,
  18674. validEnd - validStart);
  18675. }
  18676. else
  18677. {
  18678. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  18679. info.buffer->copyFrom (chan, info.startSample + validStart,
  18680. buffer,
  18681. chan, startBufferIndex,
  18682. initialSize);
  18683. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  18684. buffer,
  18685. chan, 0,
  18686. (validEnd - validStart) - initialSize);
  18687. }
  18688. }
  18689. }
  18690. nextPlayPos += info.numSamples;
  18691. if (source->isLooping() && nextPlayPos > 0)
  18692. nextPlayPos %= source->getTotalLength();
  18693. }
  18694. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18695. if (thread != 0)
  18696. thread->notify();
  18697. }
  18698. int BufferingAudioSource::getNextReadPosition() const
  18699. {
  18700. return (source->isLooping() && nextPlayPos > 0)
  18701. ? nextPlayPos % source->getTotalLength()
  18702. : nextPlayPos;
  18703. }
  18704. void BufferingAudioSource::setNextReadPosition (int newPosition)
  18705. {
  18706. const ScopedLock sl (bufferStartPosLock);
  18707. nextPlayPos = newPosition;
  18708. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18709. if (thread != 0)
  18710. thread->notify();
  18711. }
  18712. bool BufferingAudioSource::readNextBufferChunk()
  18713. {
  18714. int newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  18715. {
  18716. const ScopedLock sl (bufferStartPosLock);
  18717. if (wasSourceLooping != isLooping())
  18718. {
  18719. wasSourceLooping = isLooping();
  18720. bufferValidStart = 0;
  18721. bufferValidEnd = 0;
  18722. }
  18723. newBVS = jmax (0, nextPlayPos);
  18724. newBVE = newBVS + buffer.getNumSamples() - 4;
  18725. sectionToReadStart = 0;
  18726. sectionToReadEnd = 0;
  18727. const int maxChunkSize = 2048;
  18728. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  18729. {
  18730. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  18731. sectionToReadStart = newBVS;
  18732. sectionToReadEnd = newBVE;
  18733. bufferValidStart = 0;
  18734. bufferValidEnd = 0;
  18735. }
  18736. else if (abs (newBVS - bufferValidStart) > 512
  18737. || abs (newBVE - bufferValidEnd) > 512)
  18738. {
  18739. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  18740. sectionToReadStart = bufferValidEnd;
  18741. sectionToReadEnd = newBVE;
  18742. bufferValidStart = newBVS;
  18743. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  18744. }
  18745. }
  18746. if (sectionToReadStart != sectionToReadEnd)
  18747. {
  18748. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  18749. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  18750. if (bufferIndexStart < bufferIndexEnd)
  18751. {
  18752. readBufferSection (sectionToReadStart,
  18753. sectionToReadEnd - sectionToReadStart,
  18754. bufferIndexStart);
  18755. }
  18756. else
  18757. {
  18758. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  18759. readBufferSection (sectionToReadStart,
  18760. initialSize,
  18761. bufferIndexStart);
  18762. readBufferSection (sectionToReadStart + initialSize,
  18763. (sectionToReadEnd - sectionToReadStart) - initialSize,
  18764. 0);
  18765. }
  18766. const ScopedLock sl2 (bufferStartPosLock);
  18767. bufferValidStart = newBVS;
  18768. bufferValidEnd = newBVE;
  18769. return true;
  18770. }
  18771. else
  18772. {
  18773. return false;
  18774. }
  18775. }
  18776. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  18777. {
  18778. if (source->getNextReadPosition() != start)
  18779. source->setNextReadPosition (start);
  18780. AudioSourceChannelInfo info;
  18781. info.buffer = &buffer;
  18782. info.startSample = bufferOffset;
  18783. info.numSamples = length;
  18784. source->getNextAudioBlock (info);
  18785. }
  18786. END_JUCE_NAMESPACE
  18787. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  18788. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  18789. BEGIN_JUCE_NAMESPACE
  18790. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  18791. const bool deleteSourceWhenDeleted_)
  18792. : requiredNumberOfChannels (2),
  18793. source (source_),
  18794. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18795. buffer (2, 16)
  18796. {
  18797. remappedInfo.buffer = &buffer;
  18798. remappedInfo.startSample = 0;
  18799. }
  18800. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  18801. {
  18802. if (deleteSourceWhenDeleted)
  18803. delete source;
  18804. }
  18805. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_) throw()
  18806. {
  18807. const ScopedLock sl (lock);
  18808. requiredNumberOfChannels = requiredNumberOfChannels_;
  18809. }
  18810. void ChannelRemappingAudioSource::clearAllMappings() throw()
  18811. {
  18812. const ScopedLock sl (lock);
  18813. remappedInputs.clear();
  18814. remappedOutputs.clear();
  18815. }
  18816. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex) throw()
  18817. {
  18818. const ScopedLock sl (lock);
  18819. while (remappedInputs.size() < destIndex)
  18820. remappedInputs.add (-1);
  18821. remappedInputs.set (destIndex, sourceIndex);
  18822. }
  18823. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex) throw()
  18824. {
  18825. const ScopedLock sl (lock);
  18826. while (remappedOutputs.size() < sourceIndex)
  18827. remappedOutputs.add (-1);
  18828. remappedOutputs.set (sourceIndex, destIndex);
  18829. }
  18830. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const throw()
  18831. {
  18832. const ScopedLock sl (lock);
  18833. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  18834. return remappedInputs.getUnchecked (inputChannelIndex);
  18835. return -1;
  18836. }
  18837. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const throw()
  18838. {
  18839. const ScopedLock sl (lock);
  18840. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  18841. return remappedOutputs .getUnchecked (outputChannelIndex);
  18842. return -1;
  18843. }
  18844. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18845. {
  18846. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18847. }
  18848. void ChannelRemappingAudioSource::releaseResources()
  18849. {
  18850. source->releaseResources();
  18851. }
  18852. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18853. {
  18854. const ScopedLock sl (lock);
  18855. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  18856. const int numChans = bufferToFill.buffer->getNumChannels();
  18857. int i;
  18858. for (i = 0; i < buffer.getNumChannels(); ++i)
  18859. {
  18860. const int remappedChan = getRemappedInputChannel (i);
  18861. if (remappedChan >= 0 && remappedChan < numChans)
  18862. {
  18863. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  18864. remappedChan,
  18865. bufferToFill.startSample,
  18866. bufferToFill.numSamples);
  18867. }
  18868. else
  18869. {
  18870. buffer.clear (i, 0, bufferToFill.numSamples);
  18871. }
  18872. }
  18873. remappedInfo.numSamples = bufferToFill.numSamples;
  18874. source->getNextAudioBlock (remappedInfo);
  18875. bufferToFill.clearActiveBufferRegion();
  18876. for (i = 0; i < requiredNumberOfChannels; ++i)
  18877. {
  18878. const int remappedChan = getRemappedOutputChannel (i);
  18879. if (remappedChan >= 0 && remappedChan < numChans)
  18880. {
  18881. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  18882. buffer, i, 0, bufferToFill.numSamples);
  18883. }
  18884. }
  18885. }
  18886. XmlElement* ChannelRemappingAudioSource::createXml() const throw()
  18887. {
  18888. XmlElement* e = new XmlElement ("MAPPINGS");
  18889. String ins, outs;
  18890. int i;
  18891. const ScopedLock sl (lock);
  18892. for (i = 0; i < remappedInputs.size(); ++i)
  18893. ins << remappedInputs.getUnchecked(i) << ' ';
  18894. for (i = 0; i < remappedOutputs.size(); ++i)
  18895. outs << remappedOutputs.getUnchecked(i) << ' ';
  18896. e->setAttribute ("inputs", ins.trimEnd());
  18897. e->setAttribute ("outputs", outs.trimEnd());
  18898. return e;
  18899. }
  18900. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e) throw()
  18901. {
  18902. if (e.hasTagName ("MAPPINGS"))
  18903. {
  18904. const ScopedLock sl (lock);
  18905. clearAllMappings();
  18906. StringArray ins, outs;
  18907. ins.addTokens (e.getStringAttribute ("inputs"), false);
  18908. outs.addTokens (e.getStringAttribute ("outputs"), false);
  18909. int i;
  18910. for (i = 0; i < ins.size(); ++i)
  18911. remappedInputs.add (ins[i].getIntValue());
  18912. for (i = 0; i < outs.size(); ++i)
  18913. remappedOutputs.add (outs[i].getIntValue());
  18914. }
  18915. }
  18916. END_JUCE_NAMESPACE
  18917. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  18918. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  18919. BEGIN_JUCE_NAMESPACE
  18920. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  18921. const bool deleteInputWhenDeleted_)
  18922. : input (inputSource),
  18923. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  18924. {
  18925. jassert (inputSource != 0);
  18926. for (int i = 2; --i >= 0;)
  18927. iirFilters.add (new IIRFilter());
  18928. }
  18929. IIRFilterAudioSource::~IIRFilterAudioSource()
  18930. {
  18931. if (deleteInputWhenDeleted)
  18932. delete input;
  18933. }
  18934. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  18935. {
  18936. for (int i = iirFilters.size(); --i >= 0;)
  18937. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  18938. }
  18939. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18940. {
  18941. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18942. for (int i = iirFilters.size(); --i >= 0;)
  18943. iirFilters.getUnchecked(i)->reset();
  18944. }
  18945. void IIRFilterAudioSource::releaseResources()
  18946. {
  18947. input->releaseResources();
  18948. }
  18949. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18950. {
  18951. input->getNextAudioBlock (bufferToFill);
  18952. const int numChannels = bufferToFill.buffer->getNumChannels();
  18953. while (numChannels > iirFilters.size())
  18954. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  18955. for (int i = 0; i < numChannels; ++i)
  18956. iirFilters.getUnchecked(i)
  18957. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  18958. bufferToFill.numSamples);
  18959. }
  18960. END_JUCE_NAMESPACE
  18961. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  18962. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  18963. BEGIN_JUCE_NAMESPACE
  18964. MixerAudioSource::MixerAudioSource()
  18965. : tempBuffer (2, 0),
  18966. currentSampleRate (0.0),
  18967. bufferSizeExpected (0)
  18968. {
  18969. }
  18970. MixerAudioSource::~MixerAudioSource()
  18971. {
  18972. removeAllInputs();
  18973. }
  18974. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  18975. {
  18976. if (input != 0 && ! inputs.contains (input))
  18977. {
  18978. double localRate;
  18979. int localBufferSize;
  18980. {
  18981. const ScopedLock sl (lock);
  18982. localRate = currentSampleRate;
  18983. localBufferSize = bufferSizeExpected;
  18984. }
  18985. if (localRate != 0.0)
  18986. input->prepareToPlay (localBufferSize, localRate);
  18987. const ScopedLock sl (lock);
  18988. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  18989. inputs.add (input);
  18990. }
  18991. }
  18992. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  18993. {
  18994. if (input != 0)
  18995. {
  18996. int index;
  18997. {
  18998. const ScopedLock sl (lock);
  18999. index = inputs.indexOf (input);
  19000. if (index >= 0)
  19001. {
  19002. inputsToDelete.shiftBits (index, 1);
  19003. inputs.remove (index);
  19004. }
  19005. }
  19006. if (index >= 0)
  19007. {
  19008. input->releaseResources();
  19009. if (deleteInput)
  19010. delete input;
  19011. }
  19012. }
  19013. }
  19014. void MixerAudioSource::removeAllInputs()
  19015. {
  19016. VoidArray inputsCopy;
  19017. BigInteger inputsToDeleteCopy;
  19018. {
  19019. const ScopedLock sl (lock);
  19020. inputsCopy = inputs;
  19021. inputsToDeleteCopy = inputsToDelete;
  19022. }
  19023. for (int i = inputsCopy.size(); --i >= 0;)
  19024. if (inputsToDeleteCopy[i])
  19025. delete (AudioSource*) inputsCopy[i];
  19026. }
  19027. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19028. {
  19029. tempBuffer.setSize (2, samplesPerBlockExpected);
  19030. const ScopedLock sl (lock);
  19031. currentSampleRate = sampleRate;
  19032. bufferSizeExpected = samplesPerBlockExpected;
  19033. for (int i = inputs.size(); --i >= 0;)
  19034. ((AudioSource*) inputs.getUnchecked(i))->prepareToPlay (samplesPerBlockExpected,
  19035. sampleRate);
  19036. }
  19037. void MixerAudioSource::releaseResources()
  19038. {
  19039. const ScopedLock sl (lock);
  19040. for (int i = inputs.size(); --i >= 0;)
  19041. ((AudioSource*) inputs.getUnchecked(i))->releaseResources();
  19042. tempBuffer.setSize (2, 0);
  19043. currentSampleRate = 0;
  19044. bufferSizeExpected = 0;
  19045. }
  19046. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19047. {
  19048. const ScopedLock sl (lock);
  19049. if (inputs.size() > 0)
  19050. {
  19051. ((AudioSource*) inputs.getUnchecked(0))->getNextAudioBlock (info);
  19052. if (inputs.size() > 1)
  19053. {
  19054. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  19055. info.buffer->getNumSamples());
  19056. AudioSourceChannelInfo info2;
  19057. info2.buffer = &tempBuffer;
  19058. info2.numSamples = info.numSamples;
  19059. info2.startSample = 0;
  19060. for (int i = 1; i < inputs.size(); ++i)
  19061. {
  19062. ((AudioSource*) inputs.getUnchecked(i))->getNextAudioBlock (info2);
  19063. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  19064. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  19065. }
  19066. }
  19067. }
  19068. else
  19069. {
  19070. info.clearActiveBufferRegion();
  19071. }
  19072. }
  19073. END_JUCE_NAMESPACE
  19074. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  19075. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  19076. BEGIN_JUCE_NAMESPACE
  19077. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  19078. const bool deleteInputWhenDeleted_)
  19079. : input (inputSource),
  19080. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  19081. ratio (1.0),
  19082. lastRatio (1.0),
  19083. buffer (2, 0),
  19084. sampsInBuffer (0)
  19085. {
  19086. jassert (input != 0);
  19087. }
  19088. ResamplingAudioSource::~ResamplingAudioSource()
  19089. {
  19090. if (deleteInputWhenDeleted)
  19091. delete input;
  19092. }
  19093. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  19094. {
  19095. jassert (samplesInPerOutputSample > 0);
  19096. const ScopedLock sl (ratioLock);
  19097. ratio = jmax (0.0, samplesInPerOutputSample);
  19098. }
  19099. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  19100. double sampleRate)
  19101. {
  19102. const ScopedLock sl (ratioLock);
  19103. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19104. buffer.setSize (2, roundToInt (samplesPerBlockExpected * ratio) + 32);
  19105. buffer.clear();
  19106. sampsInBuffer = 0;
  19107. bufferPos = 0;
  19108. subSampleOffset = 0.0;
  19109. createLowPass (ratio);
  19110. resetFilters();
  19111. }
  19112. void ResamplingAudioSource::releaseResources()
  19113. {
  19114. input->releaseResources();
  19115. buffer.setSize (2, 0);
  19116. }
  19117. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19118. {
  19119. const ScopedLock sl (ratioLock);
  19120. if (lastRatio != ratio)
  19121. {
  19122. createLowPass (ratio);
  19123. lastRatio = ratio;
  19124. }
  19125. const int sampsNeeded = roundToInt (info.numSamples * ratio) + 2;
  19126. int bufferSize = buffer.getNumSamples();
  19127. if (bufferSize < sampsNeeded + 8)
  19128. {
  19129. bufferPos %= bufferSize;
  19130. bufferSize = sampsNeeded + 32;
  19131. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  19132. }
  19133. bufferPos %= bufferSize;
  19134. int endOfBufferPos = bufferPos + sampsInBuffer;
  19135. while (sampsNeeded > sampsInBuffer)
  19136. {
  19137. endOfBufferPos %= bufferSize;
  19138. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  19139. bufferSize - endOfBufferPos);
  19140. AudioSourceChannelInfo readInfo;
  19141. readInfo.buffer = &buffer;
  19142. readInfo.numSamples = numToDo;
  19143. readInfo.startSample = endOfBufferPos;
  19144. input->getNextAudioBlock (readInfo);
  19145. if (ratio > 1.0001)
  19146. {
  19147. // for down-sampling, pre-apply the filter..
  19148. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  19149. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  19150. }
  19151. sampsInBuffer += numToDo;
  19152. endOfBufferPos += numToDo;
  19153. }
  19154. float* dl = info.buffer->getSampleData (0, info.startSample);
  19155. float* dr = (info.buffer->getNumChannels() > 1) ? info.buffer->getSampleData (1, info.startSample) : 0;
  19156. const float* const bl = buffer.getSampleData (0, 0);
  19157. const float* const br = buffer.getSampleData (1, 0);
  19158. int nextPos = (bufferPos + 1) % bufferSize;
  19159. for (int m = info.numSamples; --m >= 0;)
  19160. {
  19161. const float alpha = (float) subSampleOffset;
  19162. const float invAlpha = 1.0f - alpha;
  19163. *dl++ = bl [bufferPos] * invAlpha + bl [nextPos] * alpha;
  19164. if (dr != 0)
  19165. *dr++ = br [bufferPos] * invAlpha + br [nextPos] * alpha;
  19166. subSampleOffset += ratio;
  19167. jassert (sampsInBuffer > 0);
  19168. while (subSampleOffset >= 1.0)
  19169. {
  19170. if (++bufferPos >= bufferSize)
  19171. bufferPos = 0;
  19172. --sampsInBuffer;
  19173. nextPos = (bufferPos + 1) % bufferSize;
  19174. subSampleOffset -= 1.0;
  19175. }
  19176. }
  19177. if (ratio < 0.9999)
  19178. {
  19179. // for up-sampling, apply the filter after transposing..
  19180. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  19181. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  19182. }
  19183. else if (ratio <= 1.0001)
  19184. {
  19185. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  19186. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  19187. {
  19188. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  19189. FilterState& fs = filterStates[i];
  19190. if (info.numSamples > 1)
  19191. {
  19192. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  19193. }
  19194. else
  19195. {
  19196. fs.y2 = fs.y1;
  19197. fs.x2 = fs.x1;
  19198. }
  19199. fs.y1 = fs.x1 = *endOfBuffer;
  19200. }
  19201. }
  19202. jassert (sampsInBuffer >= 0);
  19203. }
  19204. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  19205. {
  19206. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  19207. : 0.5 * frequencyRatio;
  19208. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  19209. const double nSquared = n * n;
  19210. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  19211. setFilterCoefficients (c1,
  19212. c1 * 2.0f,
  19213. c1,
  19214. 1.0,
  19215. c1 * 2.0 * (1.0 - nSquared),
  19216. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  19217. }
  19218. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  19219. {
  19220. const double a = 1.0 / c4;
  19221. c1 *= a;
  19222. c2 *= a;
  19223. c3 *= a;
  19224. c5 *= a;
  19225. c6 *= a;
  19226. coefficients[0] = c1;
  19227. coefficients[1] = c2;
  19228. coefficients[2] = c3;
  19229. coefficients[3] = c4;
  19230. coefficients[4] = c5;
  19231. coefficients[5] = c6;
  19232. }
  19233. void ResamplingAudioSource::resetFilters()
  19234. {
  19235. zeromem (filterStates, sizeof (filterStates));
  19236. }
  19237. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  19238. {
  19239. while (--num >= 0)
  19240. {
  19241. const double in = *samples;
  19242. double out = coefficients[0] * in
  19243. + coefficients[1] * fs.x1
  19244. + coefficients[2] * fs.x2
  19245. - coefficients[4] * fs.y1
  19246. - coefficients[5] * fs.y2;
  19247. #if JUCE_INTEL
  19248. if (! (out < -1.0e-8 || out > 1.0e-8))
  19249. out = 0;
  19250. #endif
  19251. fs.x2 = fs.x1;
  19252. fs.x1 = in;
  19253. fs.y2 = fs.y1;
  19254. fs.y1 = out;
  19255. *samples++ = (float) out;
  19256. }
  19257. }
  19258. END_JUCE_NAMESPACE
  19259. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  19260. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  19261. BEGIN_JUCE_NAMESPACE
  19262. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  19263. : frequency (1000.0),
  19264. sampleRate (44100.0),
  19265. currentPhase (0.0),
  19266. phasePerSample (0.0),
  19267. amplitude (0.5f)
  19268. {
  19269. }
  19270. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  19271. {
  19272. }
  19273. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  19274. {
  19275. amplitude = newAmplitude;
  19276. }
  19277. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  19278. {
  19279. frequency = newFrequencyHz;
  19280. phasePerSample = 0.0;
  19281. }
  19282. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  19283. double sampleRate_)
  19284. {
  19285. currentPhase = 0.0;
  19286. phasePerSample = 0.0;
  19287. sampleRate = sampleRate_;
  19288. }
  19289. void ToneGeneratorAudioSource::releaseResources()
  19290. {
  19291. }
  19292. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19293. {
  19294. if (phasePerSample == 0.0)
  19295. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  19296. for (int i = 0; i < info.numSamples; ++i)
  19297. {
  19298. const float sample = amplitude * (float) std::sin (currentPhase);
  19299. currentPhase += phasePerSample;
  19300. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  19301. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  19302. }
  19303. }
  19304. END_JUCE_NAMESPACE
  19305. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  19306. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  19307. BEGIN_JUCE_NAMESPACE
  19308. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  19309. : sampleRate (0),
  19310. bufferSize (0),
  19311. useDefaultInputChannels (true),
  19312. useDefaultOutputChannels (true)
  19313. {
  19314. }
  19315. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  19316. {
  19317. return outputDeviceName == other.outputDeviceName
  19318. && inputDeviceName == other.inputDeviceName
  19319. && sampleRate == other.sampleRate
  19320. && bufferSize == other.bufferSize
  19321. && inputChannels == other.inputChannels
  19322. && useDefaultInputChannels == other.useDefaultInputChannels
  19323. && outputChannels == other.outputChannels
  19324. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  19325. }
  19326. AudioDeviceManager::AudioDeviceManager()
  19327. : currentAudioDevice (0),
  19328. numInputChansNeeded (0),
  19329. numOutputChansNeeded (2),
  19330. listNeedsScanning (true),
  19331. useInputNames (false),
  19332. inputLevelMeasurementEnabledCount (0),
  19333. inputLevel (0),
  19334. tempBuffer (2, 2),
  19335. defaultMidiOutput (0),
  19336. cpuUsageMs (0),
  19337. timeToCpuScale (0)
  19338. {
  19339. callbackHandler.owner = this;
  19340. }
  19341. AudioDeviceManager::~AudioDeviceManager()
  19342. {
  19343. currentAudioDevice = 0;
  19344. defaultMidiOutput = 0;
  19345. }
  19346. void AudioDeviceManager::createDeviceTypesIfNeeded()
  19347. {
  19348. if (availableDeviceTypes.size() == 0)
  19349. {
  19350. createAudioDeviceTypes (availableDeviceTypes);
  19351. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  19352. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  19353. if (availableDeviceTypes.size() > 0)
  19354. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  19355. }
  19356. }
  19357. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  19358. {
  19359. scanDevicesIfNeeded();
  19360. return availableDeviceTypes;
  19361. }
  19362. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  19363. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  19364. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  19365. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  19366. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  19367. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  19368. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  19369. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  19370. {
  19371. (void) list; // (to avoid 'unused param' warnings)
  19372. #if JUCE_WINDOWS
  19373. #if JUCE_WASAPI
  19374. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  19375. list.add (juce_createAudioIODeviceType_WASAPI());
  19376. #endif
  19377. #if JUCE_DIRECTSOUND
  19378. list.add (juce_createAudioIODeviceType_DirectSound());
  19379. #endif
  19380. #if JUCE_ASIO
  19381. list.add (juce_createAudioIODeviceType_ASIO());
  19382. #endif
  19383. #endif
  19384. #if JUCE_MAC
  19385. list.add (juce_createAudioIODeviceType_CoreAudio());
  19386. #endif
  19387. #if JUCE_IPHONE
  19388. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  19389. #endif
  19390. #if JUCE_LINUX && JUCE_ALSA
  19391. list.add (juce_createAudioIODeviceType_ALSA());
  19392. #endif
  19393. #if JUCE_LINUX && JUCE_JACK
  19394. list.add (juce_createAudioIODeviceType_JACK());
  19395. #endif
  19396. }
  19397. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  19398. const int numOutputChannelsNeeded,
  19399. const XmlElement* const e,
  19400. const bool selectDefaultDeviceOnFailure,
  19401. const String& preferredDefaultDeviceName,
  19402. const AudioDeviceSetup* preferredSetupOptions)
  19403. {
  19404. scanDevicesIfNeeded();
  19405. numInputChansNeeded = numInputChannelsNeeded;
  19406. numOutputChansNeeded = numOutputChannelsNeeded;
  19407. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  19408. {
  19409. lastExplicitSettings = new XmlElement (*e);
  19410. String error;
  19411. AudioDeviceSetup setup;
  19412. if (preferredSetupOptions != 0)
  19413. setup = *preferredSetupOptions;
  19414. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  19415. {
  19416. setup.inputDeviceName = setup.outputDeviceName
  19417. = e->getStringAttribute ("audioDeviceName");
  19418. }
  19419. else
  19420. {
  19421. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  19422. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  19423. }
  19424. currentDeviceType = e->getStringAttribute ("deviceType");
  19425. if (currentDeviceType.isEmpty())
  19426. {
  19427. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  19428. if (type != 0)
  19429. currentDeviceType = type->getTypeName();
  19430. else if (availableDeviceTypes.size() > 0)
  19431. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  19432. }
  19433. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  19434. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  19435. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  19436. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  19437. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  19438. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  19439. error = setAudioDeviceSetup (setup, true);
  19440. midiInsFromXml.clear();
  19441. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  19442. midiInsFromXml.add (c->getStringAttribute ("name"));
  19443. const StringArray allMidiIns (MidiInput::getDevices());
  19444. for (int i = allMidiIns.size(); --i >= 0;)
  19445. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  19446. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  19447. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  19448. false, preferredDefaultDeviceName);
  19449. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  19450. return error;
  19451. }
  19452. else
  19453. {
  19454. AudioDeviceSetup setup;
  19455. if (preferredSetupOptions != 0)
  19456. {
  19457. setup = *preferredSetupOptions;
  19458. }
  19459. else if (preferredDefaultDeviceName.isNotEmpty())
  19460. {
  19461. for (int j = availableDeviceTypes.size(); --j >= 0;)
  19462. {
  19463. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  19464. StringArray outs (type->getDeviceNames (false));
  19465. int i;
  19466. for (i = 0; i < outs.size(); ++i)
  19467. {
  19468. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  19469. {
  19470. setup.outputDeviceName = outs[i];
  19471. break;
  19472. }
  19473. }
  19474. StringArray ins (type->getDeviceNames (true));
  19475. for (i = 0; i < ins.size(); ++i)
  19476. {
  19477. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  19478. {
  19479. setup.inputDeviceName = ins[i];
  19480. break;
  19481. }
  19482. }
  19483. }
  19484. }
  19485. insertDefaultDeviceNames (setup);
  19486. return setAudioDeviceSetup (setup, false);
  19487. }
  19488. }
  19489. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  19490. {
  19491. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  19492. if (type != 0)
  19493. {
  19494. if (setup.outputDeviceName.isEmpty())
  19495. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  19496. if (setup.inputDeviceName.isEmpty())
  19497. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  19498. }
  19499. }
  19500. XmlElement* AudioDeviceManager::createStateXml() const
  19501. {
  19502. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  19503. }
  19504. void AudioDeviceManager::scanDevicesIfNeeded()
  19505. {
  19506. if (listNeedsScanning)
  19507. {
  19508. listNeedsScanning = false;
  19509. createDeviceTypesIfNeeded();
  19510. for (int i = availableDeviceTypes.size(); --i >= 0;)
  19511. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  19512. }
  19513. }
  19514. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  19515. {
  19516. scanDevicesIfNeeded();
  19517. for (int i = availableDeviceTypes.size(); --i >= 0;)
  19518. {
  19519. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  19520. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  19521. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  19522. {
  19523. return type;
  19524. }
  19525. }
  19526. return 0;
  19527. }
  19528. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  19529. {
  19530. setup = currentSetup;
  19531. }
  19532. void AudioDeviceManager::deleteCurrentDevice()
  19533. {
  19534. currentAudioDevice = 0;
  19535. currentSetup.inputDeviceName = String::empty;
  19536. currentSetup.outputDeviceName = String::empty;
  19537. }
  19538. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  19539. const bool treatAsChosenDevice)
  19540. {
  19541. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19542. {
  19543. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  19544. && currentDeviceType != type)
  19545. {
  19546. currentDeviceType = type;
  19547. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  19548. insertDefaultDeviceNames (s);
  19549. setAudioDeviceSetup (s, treatAsChosenDevice);
  19550. sendChangeMessage (this);
  19551. break;
  19552. }
  19553. }
  19554. }
  19555. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  19556. {
  19557. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19558. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  19559. return availableDeviceTypes[i];
  19560. return availableDeviceTypes[0];
  19561. }
  19562. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  19563. const bool treatAsChosenDevice)
  19564. {
  19565. jassert (&newSetup != &currentSetup); // this will have no effect
  19566. if (newSetup == currentSetup && currentAudioDevice != 0)
  19567. return String::empty;
  19568. if (! (newSetup == currentSetup))
  19569. sendChangeMessage (this);
  19570. stopDevice();
  19571. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  19572. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  19573. String error;
  19574. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  19575. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  19576. {
  19577. deleteCurrentDevice();
  19578. if (treatAsChosenDevice)
  19579. updateXml();
  19580. return String::empty;
  19581. }
  19582. if (currentSetup.inputDeviceName != newInputDeviceName
  19583. || currentSetup.outputDeviceName != newOutputDeviceName
  19584. || currentAudioDevice == 0)
  19585. {
  19586. deleteCurrentDevice();
  19587. scanDevicesIfNeeded();
  19588. if (newOutputDeviceName.isNotEmpty()
  19589. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  19590. {
  19591. return "No such device: " + newOutputDeviceName;
  19592. }
  19593. if (newInputDeviceName.isNotEmpty()
  19594. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  19595. {
  19596. return "No such device: " + newInputDeviceName;
  19597. }
  19598. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  19599. if (currentAudioDevice == 0)
  19600. error = "Can't open the audio device!\n\nThis may be because another application is currently using the same device - if so, you should close any other applications and try again!";
  19601. else
  19602. error = currentAudioDevice->getLastError();
  19603. if (error.isNotEmpty())
  19604. {
  19605. deleteCurrentDevice();
  19606. return error;
  19607. }
  19608. if (newSetup.useDefaultInputChannels)
  19609. {
  19610. inputChannels.clear();
  19611. inputChannels.setRange (0, numInputChansNeeded, true);
  19612. }
  19613. if (newSetup.useDefaultOutputChannels)
  19614. {
  19615. outputChannels.clear();
  19616. outputChannels.setRange (0, numOutputChansNeeded, true);
  19617. }
  19618. if (newInputDeviceName.isEmpty())
  19619. inputChannels.clear();
  19620. if (newOutputDeviceName.isEmpty())
  19621. outputChannels.clear();
  19622. }
  19623. if (! newSetup.useDefaultInputChannels)
  19624. inputChannels = newSetup.inputChannels;
  19625. if (! newSetup.useDefaultOutputChannels)
  19626. outputChannels = newSetup.outputChannels;
  19627. currentSetup = newSetup;
  19628. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  19629. error = currentAudioDevice->open (inputChannels,
  19630. outputChannels,
  19631. currentSetup.sampleRate,
  19632. currentSetup.bufferSize);
  19633. if (error.isEmpty())
  19634. {
  19635. currentDeviceType = currentAudioDevice->getTypeName();
  19636. currentAudioDevice->start (&callbackHandler);
  19637. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  19638. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  19639. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  19640. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  19641. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19642. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  19643. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  19644. if (treatAsChosenDevice)
  19645. updateXml();
  19646. }
  19647. else
  19648. {
  19649. deleteCurrentDevice();
  19650. }
  19651. return error;
  19652. }
  19653. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  19654. {
  19655. jassert (currentAudioDevice != 0);
  19656. if (rate > 0)
  19657. {
  19658. bool ok = false;
  19659. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  19660. {
  19661. const double sr = currentAudioDevice->getSampleRate (i);
  19662. if (sr == rate)
  19663. ok = true;
  19664. }
  19665. if (! ok)
  19666. rate = 0;
  19667. }
  19668. if (rate == 0)
  19669. {
  19670. double lowestAbove44 = 0.0;
  19671. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  19672. {
  19673. const double sr = currentAudioDevice->getSampleRate (i);
  19674. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  19675. lowestAbove44 = sr;
  19676. }
  19677. if (lowestAbove44 == 0.0)
  19678. rate = currentAudioDevice->getSampleRate (0);
  19679. else
  19680. rate = lowestAbove44;
  19681. }
  19682. return rate;
  19683. }
  19684. void AudioDeviceManager::stopDevice()
  19685. {
  19686. if (currentAudioDevice != 0)
  19687. currentAudioDevice->stop();
  19688. testSound = 0;
  19689. }
  19690. void AudioDeviceManager::closeAudioDevice()
  19691. {
  19692. stopDevice();
  19693. currentAudioDevice = 0;
  19694. }
  19695. void AudioDeviceManager::restartLastAudioDevice()
  19696. {
  19697. if (currentAudioDevice == 0)
  19698. {
  19699. if (currentSetup.inputDeviceName.isEmpty()
  19700. && currentSetup.outputDeviceName.isEmpty())
  19701. {
  19702. // This method will only reload the last device that was running
  19703. // before closeAudioDevice() was called - you need to actually open
  19704. // one first, with setAudioDevice().
  19705. jassertfalse
  19706. return;
  19707. }
  19708. AudioDeviceSetup s (currentSetup);
  19709. setAudioDeviceSetup (s, false);
  19710. }
  19711. }
  19712. void AudioDeviceManager::updateXml()
  19713. {
  19714. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  19715. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  19716. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  19717. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  19718. if (currentAudioDevice != 0)
  19719. {
  19720. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  19721. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  19722. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  19723. if (! currentSetup.useDefaultInputChannels)
  19724. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  19725. if (! currentSetup.useDefaultOutputChannels)
  19726. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  19727. }
  19728. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  19729. {
  19730. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  19731. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  19732. }
  19733. if (midiInsFromXml.size() > 0)
  19734. {
  19735. // Add any midi devices that have been enabled before, but which aren't currently
  19736. // open because the device has been disconnected.
  19737. const StringArray availableMidiDevices (MidiInput::getDevices());
  19738. for (int i = 0; i < midiInsFromXml.size(); ++i)
  19739. {
  19740. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  19741. {
  19742. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  19743. m->setAttribute ("name", midiInsFromXml[i]);
  19744. }
  19745. }
  19746. }
  19747. if (defaultMidiOutputName.isNotEmpty())
  19748. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  19749. }
  19750. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  19751. {
  19752. {
  19753. const ScopedLock sl (audioCallbackLock);
  19754. if (callbacks.contains (newCallback))
  19755. return;
  19756. }
  19757. if (currentAudioDevice != 0 && newCallback != 0)
  19758. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  19759. const ScopedLock sl (audioCallbackLock);
  19760. callbacks.add (newCallback);
  19761. }
  19762. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  19763. {
  19764. if (callback != 0)
  19765. {
  19766. bool needsDeinitialising = currentAudioDevice != 0;
  19767. {
  19768. const ScopedLock sl (audioCallbackLock);
  19769. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  19770. callbacks.removeValue (callback);
  19771. }
  19772. if (needsDeinitialising)
  19773. callback->audioDeviceStopped();
  19774. }
  19775. }
  19776. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  19777. int numInputChannels,
  19778. float** outputChannelData,
  19779. int numOutputChannels,
  19780. int numSamples)
  19781. {
  19782. const ScopedLock sl (audioCallbackLock);
  19783. if (inputLevelMeasurementEnabledCount > 0)
  19784. {
  19785. for (int j = 0; j < numSamples; ++j)
  19786. {
  19787. float s = 0;
  19788. for (int i = 0; i < numInputChannels; ++i)
  19789. s += std::abs (inputChannelData[i][j]);
  19790. s /= numInputChannels;
  19791. const double decayFactor = 0.99992;
  19792. if (s > inputLevel)
  19793. inputLevel = s;
  19794. else if (inputLevel > 0.001f)
  19795. inputLevel *= decayFactor;
  19796. else
  19797. inputLevel = 0;
  19798. }
  19799. }
  19800. if (callbacks.size() > 0)
  19801. {
  19802. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  19803. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  19804. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19805. outputChannelData, numOutputChannels, numSamples);
  19806. float** const tempChans = tempBuffer.getArrayOfChannels();
  19807. for (int i = callbacks.size(); --i > 0;)
  19808. {
  19809. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19810. tempChans, numOutputChannels, numSamples);
  19811. for (int chan = 0; chan < numOutputChannels; ++chan)
  19812. {
  19813. const float* const src = tempChans [chan];
  19814. float* const dst = outputChannelData [chan];
  19815. if (src != 0 && dst != 0)
  19816. for (int j = 0; j < numSamples; ++j)
  19817. dst[j] += src[j];
  19818. }
  19819. }
  19820. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  19821. const double filterAmount = 0.2;
  19822. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  19823. }
  19824. else
  19825. {
  19826. for (int i = 0; i < numOutputChannels; ++i)
  19827. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19828. }
  19829. if (testSound != 0)
  19830. {
  19831. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  19832. const float* const src = testSound->getSampleData (0, testSoundPosition);
  19833. for (int i = 0; i < numOutputChannels; ++i)
  19834. for (int j = 0; j < numSamps; ++j)
  19835. outputChannelData [i][j] += src[j];
  19836. testSoundPosition += numSamps;
  19837. if (testSoundPosition >= testSound->getNumSamples())
  19838. testSound = 0;
  19839. }
  19840. }
  19841. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  19842. {
  19843. cpuUsageMs = 0;
  19844. const double sampleRate = device->getCurrentSampleRate();
  19845. const int blockSize = device->getCurrentBufferSizeSamples();
  19846. if (sampleRate > 0.0 && blockSize > 0)
  19847. {
  19848. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  19849. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  19850. }
  19851. {
  19852. const ScopedLock sl (audioCallbackLock);
  19853. for (int i = callbacks.size(); --i >= 0;)
  19854. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  19855. }
  19856. sendChangeMessage (this);
  19857. }
  19858. void AudioDeviceManager::audioDeviceStoppedInt()
  19859. {
  19860. cpuUsageMs = 0;
  19861. timeToCpuScale = 0;
  19862. sendChangeMessage (this);
  19863. const ScopedLock sl (audioCallbackLock);
  19864. for (int i = callbacks.size(); --i >= 0;)
  19865. callbacks.getUnchecked(i)->audioDeviceStopped();
  19866. }
  19867. double AudioDeviceManager::getCpuUsage() const
  19868. {
  19869. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  19870. }
  19871. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  19872. const bool enabled)
  19873. {
  19874. if (enabled != isMidiInputEnabled (name))
  19875. {
  19876. if (enabled)
  19877. {
  19878. const int index = MidiInput::getDevices().indexOf (name);
  19879. if (index >= 0)
  19880. {
  19881. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  19882. if (min != 0)
  19883. {
  19884. enabledMidiInputs.add (min);
  19885. min->start();
  19886. }
  19887. }
  19888. }
  19889. else
  19890. {
  19891. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19892. if (enabledMidiInputs[i]->getName() == name)
  19893. enabledMidiInputs.remove (i);
  19894. }
  19895. updateXml();
  19896. sendChangeMessage (this);
  19897. }
  19898. }
  19899. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  19900. {
  19901. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19902. if (enabledMidiInputs[i]->getName() == name)
  19903. return true;
  19904. return false;
  19905. }
  19906. void AudioDeviceManager::addMidiInputCallback (const String& name,
  19907. MidiInputCallback* callback)
  19908. {
  19909. removeMidiInputCallback (name, callback);
  19910. if (name.isEmpty())
  19911. {
  19912. midiCallbacks.add (callback);
  19913. midiCallbackDevices.add (0);
  19914. }
  19915. else
  19916. {
  19917. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19918. {
  19919. if (enabledMidiInputs[i]->getName() == name)
  19920. {
  19921. const ScopedLock sl (midiCallbackLock);
  19922. midiCallbacks.add (callback);
  19923. midiCallbackDevices.add (enabledMidiInputs[i]);
  19924. break;
  19925. }
  19926. }
  19927. }
  19928. }
  19929. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  19930. MidiInputCallback* /*callback*/)
  19931. {
  19932. const ScopedLock sl (midiCallbackLock);
  19933. for (int i = midiCallbacks.size(); --i >= 0;)
  19934. {
  19935. String devName;
  19936. if (midiCallbackDevices.getUnchecked(i) != 0)
  19937. devName = midiCallbackDevices.getUnchecked(i)->getName();
  19938. if (devName == name)
  19939. {
  19940. midiCallbacks.remove (i);
  19941. midiCallbackDevices.remove (i);
  19942. }
  19943. }
  19944. }
  19945. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  19946. const MidiMessage& message)
  19947. {
  19948. if (! message.isActiveSense())
  19949. {
  19950. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  19951. const ScopedLock sl (midiCallbackLock);
  19952. for (int i = midiCallbackDevices.size(); --i >= 0;)
  19953. {
  19954. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  19955. if (md == source || (md == 0 && isDefaultSource))
  19956. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  19957. }
  19958. }
  19959. }
  19960. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  19961. {
  19962. if (defaultMidiOutputName != deviceName)
  19963. {
  19964. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  19965. {
  19966. const ScopedLock sl (audioCallbackLock);
  19967. oldCallbacks = callbacks;
  19968. callbacks.clear();
  19969. }
  19970. if (currentAudioDevice != 0)
  19971. for (int i = oldCallbacks.size(); --i >= 0;)
  19972. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  19973. defaultMidiOutput = 0;
  19974. defaultMidiOutputName = deviceName;
  19975. if (deviceName.isNotEmpty())
  19976. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  19977. if (currentAudioDevice != 0)
  19978. for (int i = oldCallbacks.size(); --i >= 0;)
  19979. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  19980. {
  19981. const ScopedLock sl (audioCallbackLock);
  19982. callbacks = oldCallbacks;
  19983. }
  19984. updateXml();
  19985. sendChangeMessage (this);
  19986. }
  19987. }
  19988. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  19989. int numInputChannels,
  19990. float** outputChannelData,
  19991. int numOutputChannels,
  19992. int numSamples)
  19993. {
  19994. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  19995. }
  19996. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  19997. {
  19998. owner->audioDeviceAboutToStartInt (device);
  19999. }
  20000. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  20001. {
  20002. owner->audioDeviceStoppedInt();
  20003. }
  20004. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  20005. {
  20006. owner->handleIncomingMidiMessageInt (source, message);
  20007. }
  20008. void AudioDeviceManager::playTestSound()
  20009. {
  20010. { // cunningly nested to swap, unlock and delete in that order.
  20011. ScopedPointer <AudioSampleBuffer> oldSound;
  20012. {
  20013. const ScopedLock sl (audioCallbackLock);
  20014. oldSound = testSound;
  20015. }
  20016. }
  20017. testSoundPosition = 0;
  20018. if (currentAudioDevice != 0)
  20019. {
  20020. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20021. const int soundLength = (int) sampleRate;
  20022. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20023. float* samples = newSound->getSampleData (0);
  20024. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20025. const float amplitude = 0.5f;
  20026. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20027. for (int i = 0; i < soundLength; ++i)
  20028. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  20029. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20030. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20031. const ScopedLock sl (audioCallbackLock);
  20032. testSound = newSound;
  20033. }
  20034. }
  20035. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20036. {
  20037. const ScopedLock sl (audioCallbackLock);
  20038. if (enableMeasurement)
  20039. ++inputLevelMeasurementEnabledCount;
  20040. else
  20041. --inputLevelMeasurementEnabledCount;
  20042. inputLevel = 0;
  20043. }
  20044. double AudioDeviceManager::getCurrentInputLevel() const
  20045. {
  20046. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  20047. return inputLevel;
  20048. }
  20049. END_JUCE_NAMESPACE
  20050. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  20051. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  20052. BEGIN_JUCE_NAMESPACE
  20053. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  20054. : name (deviceName),
  20055. typeName (typeName_)
  20056. {
  20057. }
  20058. AudioIODevice::~AudioIODevice()
  20059. {
  20060. }
  20061. bool AudioIODevice::hasControlPanel() const
  20062. {
  20063. return false;
  20064. }
  20065. bool AudioIODevice::showControlPanel()
  20066. {
  20067. jassertfalse // this should only be called for devices which return true from
  20068. // their hasControlPanel() method.
  20069. return false;
  20070. }
  20071. END_JUCE_NAMESPACE
  20072. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  20073. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  20074. BEGIN_JUCE_NAMESPACE
  20075. AudioIODeviceType::AudioIODeviceType (const String& name)
  20076. : typeName (name)
  20077. {
  20078. }
  20079. AudioIODeviceType::~AudioIODeviceType()
  20080. {
  20081. }
  20082. END_JUCE_NAMESPACE
  20083. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  20084. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  20085. BEGIN_JUCE_NAMESPACE
  20086. MidiOutput::MidiOutput()
  20087. : Thread ("midi out"),
  20088. internal (0),
  20089. firstMessage (0)
  20090. {
  20091. }
  20092. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  20093. const double sampleNumber)
  20094. : message (data, len, sampleNumber)
  20095. {
  20096. }
  20097. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  20098. const double millisecondCounterToStartAt,
  20099. double samplesPerSecondForBuffer)
  20100. {
  20101. // You've got to call startBackgroundThread() for this to actually work..
  20102. jassert (isThreadRunning());
  20103. // this needs to be a value in the future - RTFM for this method!
  20104. jassert (millisecondCounterToStartAt > 0);
  20105. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  20106. MidiBuffer::Iterator i (buffer);
  20107. const uint8* data;
  20108. int len, time;
  20109. while (i.getNextEvent (data, len, time))
  20110. {
  20111. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  20112. PendingMessage* const m
  20113. = new PendingMessage (data, len, eventTime);
  20114. const ScopedLock sl (lock);
  20115. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  20116. {
  20117. m->next = firstMessage;
  20118. firstMessage = m;
  20119. }
  20120. else
  20121. {
  20122. PendingMessage* mm = firstMessage;
  20123. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  20124. mm = mm->next;
  20125. m->next = mm->next;
  20126. mm->next = m;
  20127. }
  20128. }
  20129. notify();
  20130. }
  20131. void MidiOutput::clearAllPendingMessages()
  20132. {
  20133. const ScopedLock sl (lock);
  20134. while (firstMessage != 0)
  20135. {
  20136. PendingMessage* const m = firstMessage;
  20137. firstMessage = firstMessage->next;
  20138. delete m;
  20139. }
  20140. }
  20141. void MidiOutput::startBackgroundThread()
  20142. {
  20143. startThread (9);
  20144. }
  20145. void MidiOutput::stopBackgroundThread()
  20146. {
  20147. stopThread (5000);
  20148. }
  20149. void MidiOutput::run()
  20150. {
  20151. while (! threadShouldExit())
  20152. {
  20153. uint32 now = Time::getMillisecondCounter();
  20154. uint32 eventTime = 0;
  20155. uint32 timeToWait = 500;
  20156. PendingMessage* message;
  20157. {
  20158. const ScopedLock sl (lock);
  20159. message = firstMessage;
  20160. if (message != 0)
  20161. {
  20162. eventTime = roundToInt (message->message.getTimeStamp());
  20163. if (eventTime > now + 20)
  20164. {
  20165. timeToWait = eventTime - (now + 20);
  20166. message = 0;
  20167. }
  20168. else
  20169. {
  20170. firstMessage = message->next;
  20171. }
  20172. }
  20173. }
  20174. if (message != 0)
  20175. {
  20176. if (eventTime > now)
  20177. {
  20178. Time::waitForMillisecondCounter (eventTime);
  20179. if (threadShouldExit())
  20180. break;
  20181. }
  20182. if (eventTime > now - 200)
  20183. sendMessageNow (message->message);
  20184. delete message;
  20185. }
  20186. else
  20187. {
  20188. jassert (timeToWait < 1000 * 30);
  20189. wait (timeToWait);
  20190. }
  20191. }
  20192. clearAllPendingMessages();
  20193. }
  20194. END_JUCE_NAMESPACE
  20195. /*** End of inlined file: juce_MidiOutput.cpp ***/
  20196. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  20197. BEGIN_JUCE_NAMESPACE
  20198. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20199. {
  20200. const double maxVal = (double) 0x7fff;
  20201. char* intData = static_cast <char*> (dest);
  20202. if (dest != (void*) source || destBytesPerSample <= 4)
  20203. {
  20204. for (int i = 0; i < numSamples; ++i)
  20205. {
  20206. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20207. intData += destBytesPerSample;
  20208. }
  20209. }
  20210. else
  20211. {
  20212. intData += destBytesPerSample * numSamples;
  20213. for (int i = numSamples; --i >= 0;)
  20214. {
  20215. intData -= destBytesPerSample;
  20216. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20217. }
  20218. }
  20219. }
  20220. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20221. {
  20222. const double maxVal = (double) 0x7fff;
  20223. char* intData = static_cast <char*> (dest);
  20224. if (dest != (void*) source || destBytesPerSample <= 4)
  20225. {
  20226. for (int i = 0; i < numSamples; ++i)
  20227. {
  20228. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20229. intData += destBytesPerSample;
  20230. }
  20231. }
  20232. else
  20233. {
  20234. intData += destBytesPerSample * numSamples;
  20235. for (int i = numSamples; --i >= 0;)
  20236. {
  20237. intData -= destBytesPerSample;
  20238. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20239. }
  20240. }
  20241. }
  20242. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20243. {
  20244. const double maxVal = (double) 0x7fffff;
  20245. char* intData = static_cast <char*> (dest);
  20246. if (dest != (void*) source || destBytesPerSample <= 4)
  20247. {
  20248. for (int i = 0; i < numSamples; ++i)
  20249. {
  20250. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20251. intData += destBytesPerSample;
  20252. }
  20253. }
  20254. else
  20255. {
  20256. intData += destBytesPerSample * numSamples;
  20257. for (int i = numSamples; --i >= 0;)
  20258. {
  20259. intData -= destBytesPerSample;
  20260. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20261. }
  20262. }
  20263. }
  20264. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20265. {
  20266. const double maxVal = (double) 0x7fffff;
  20267. char* intData = static_cast <char*> (dest);
  20268. if (dest != (void*) source || destBytesPerSample <= 4)
  20269. {
  20270. for (int i = 0; i < numSamples; ++i)
  20271. {
  20272. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20273. intData += destBytesPerSample;
  20274. }
  20275. }
  20276. else
  20277. {
  20278. intData += destBytesPerSample * numSamples;
  20279. for (int i = numSamples; --i >= 0;)
  20280. {
  20281. intData -= destBytesPerSample;
  20282. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20283. }
  20284. }
  20285. }
  20286. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20287. {
  20288. const double maxVal = (double) 0x7fffffff;
  20289. char* intData = static_cast <char*> (dest);
  20290. if (dest != (void*) source || destBytesPerSample <= 4)
  20291. {
  20292. for (int i = 0; i < numSamples; ++i)
  20293. {
  20294. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20295. intData += destBytesPerSample;
  20296. }
  20297. }
  20298. else
  20299. {
  20300. intData += destBytesPerSample * numSamples;
  20301. for (int i = numSamples; --i >= 0;)
  20302. {
  20303. intData -= destBytesPerSample;
  20304. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20305. }
  20306. }
  20307. }
  20308. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20309. {
  20310. const double maxVal = (double) 0x7fffffff;
  20311. char* intData = static_cast <char*> (dest);
  20312. if (dest != (void*) source || destBytesPerSample <= 4)
  20313. {
  20314. for (int i = 0; i < numSamples; ++i)
  20315. {
  20316. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20317. intData += destBytesPerSample;
  20318. }
  20319. }
  20320. else
  20321. {
  20322. intData += destBytesPerSample * numSamples;
  20323. for (int i = numSamples; --i >= 0;)
  20324. {
  20325. intData -= destBytesPerSample;
  20326. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20327. }
  20328. }
  20329. }
  20330. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20331. {
  20332. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  20333. char* d = static_cast <char*> (dest);
  20334. for (int i = 0; i < numSamples; ++i)
  20335. {
  20336. *(float*) d = source[i];
  20337. #if JUCE_BIG_ENDIAN
  20338. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  20339. #endif
  20340. d += destBytesPerSample;
  20341. }
  20342. }
  20343. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20344. {
  20345. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  20346. char* d = static_cast <char*> (dest);
  20347. for (int i = 0; i < numSamples; ++i)
  20348. {
  20349. *(float*) d = source[i];
  20350. #if JUCE_LITTLE_ENDIAN
  20351. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  20352. #endif
  20353. d += destBytesPerSample;
  20354. }
  20355. }
  20356. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20357. {
  20358. const float scale = 1.0f / 0x7fff;
  20359. const char* intData = static_cast <const char*> (source);
  20360. if (source != (void*) dest || srcBytesPerSample >= 4)
  20361. {
  20362. for (int i = 0; i < numSamples; ++i)
  20363. {
  20364. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  20365. intData += srcBytesPerSample;
  20366. }
  20367. }
  20368. else
  20369. {
  20370. intData += srcBytesPerSample * numSamples;
  20371. for (int i = numSamples; --i >= 0;)
  20372. {
  20373. intData -= srcBytesPerSample;
  20374. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  20375. }
  20376. }
  20377. }
  20378. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20379. {
  20380. const float scale = 1.0f / 0x7fff;
  20381. const char* intData = static_cast <const char*> (source);
  20382. if (source != (void*) dest || srcBytesPerSample >= 4)
  20383. {
  20384. for (int i = 0; i < numSamples; ++i)
  20385. {
  20386. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  20387. intData += srcBytesPerSample;
  20388. }
  20389. }
  20390. else
  20391. {
  20392. intData += srcBytesPerSample * numSamples;
  20393. for (int i = numSamples; --i >= 0;)
  20394. {
  20395. intData -= srcBytesPerSample;
  20396. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  20397. }
  20398. }
  20399. }
  20400. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20401. {
  20402. const float scale = 1.0f / 0x7fffff;
  20403. const char* intData = static_cast <const char*> (source);
  20404. if (source != (void*) dest || srcBytesPerSample >= 4)
  20405. {
  20406. for (int i = 0; i < numSamples; ++i)
  20407. {
  20408. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  20409. intData += srcBytesPerSample;
  20410. }
  20411. }
  20412. else
  20413. {
  20414. intData += srcBytesPerSample * numSamples;
  20415. for (int i = numSamples; --i >= 0;)
  20416. {
  20417. intData -= srcBytesPerSample;
  20418. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  20419. }
  20420. }
  20421. }
  20422. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20423. {
  20424. const float scale = 1.0f / 0x7fffff;
  20425. const char* intData = static_cast <const char*> (source);
  20426. if (source != (void*) dest || srcBytesPerSample >= 4)
  20427. {
  20428. for (int i = 0; i < numSamples; ++i)
  20429. {
  20430. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  20431. intData += srcBytesPerSample;
  20432. }
  20433. }
  20434. else
  20435. {
  20436. intData += srcBytesPerSample * numSamples;
  20437. for (int i = numSamples; --i >= 0;)
  20438. {
  20439. intData -= srcBytesPerSample;
  20440. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  20441. }
  20442. }
  20443. }
  20444. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20445. {
  20446. const float scale = 1.0f / 0x7fffffff;
  20447. const char* intData = static_cast <const char*> (source);
  20448. if (source != (void*) dest || srcBytesPerSample >= 4)
  20449. {
  20450. for (int i = 0; i < numSamples; ++i)
  20451. {
  20452. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  20453. intData += srcBytesPerSample;
  20454. }
  20455. }
  20456. else
  20457. {
  20458. intData += srcBytesPerSample * numSamples;
  20459. for (int i = numSamples; --i >= 0;)
  20460. {
  20461. intData -= srcBytesPerSample;
  20462. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  20463. }
  20464. }
  20465. }
  20466. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20467. {
  20468. const float scale = 1.0f / 0x7fffffff;
  20469. const char* intData = static_cast <const char*> (source);
  20470. if (source != (void*) dest || srcBytesPerSample >= 4)
  20471. {
  20472. for (int i = 0; i < numSamples; ++i)
  20473. {
  20474. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  20475. intData += srcBytesPerSample;
  20476. }
  20477. }
  20478. else
  20479. {
  20480. intData += srcBytesPerSample * numSamples;
  20481. for (int i = numSamples; --i >= 0;)
  20482. {
  20483. intData -= srcBytesPerSample;
  20484. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  20485. }
  20486. }
  20487. }
  20488. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20489. {
  20490. const char* s = static_cast <const char*> (source);
  20491. for (int i = 0; i < numSamples; ++i)
  20492. {
  20493. dest[i] = *(float*)s;
  20494. #if JUCE_BIG_ENDIAN
  20495. uint32* const d = (uint32*) (dest + i);
  20496. *d = ByteOrder::swap (*d);
  20497. #endif
  20498. s += srcBytesPerSample;
  20499. }
  20500. }
  20501. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20502. {
  20503. const char* s = static_cast <const char*> (source);
  20504. for (int i = 0; i < numSamples; ++i)
  20505. {
  20506. dest[i] = *(float*)s;
  20507. #if JUCE_LITTLE_ENDIAN
  20508. uint32* const d = (uint32*) (dest + i);
  20509. *d = ByteOrder::swap (*d);
  20510. #endif
  20511. s += srcBytesPerSample;
  20512. }
  20513. }
  20514. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  20515. const float* const source,
  20516. void* const dest,
  20517. const int numSamples)
  20518. {
  20519. switch (destFormat)
  20520. {
  20521. case int16LE:
  20522. convertFloatToInt16LE (source, dest, numSamples);
  20523. break;
  20524. case int16BE:
  20525. convertFloatToInt16BE (source, dest, numSamples);
  20526. break;
  20527. case int24LE:
  20528. convertFloatToInt24LE (source, dest, numSamples);
  20529. break;
  20530. case int24BE:
  20531. convertFloatToInt24BE (source, dest, numSamples);
  20532. break;
  20533. case int32LE:
  20534. convertFloatToInt32LE (source, dest, numSamples);
  20535. break;
  20536. case int32BE:
  20537. convertFloatToInt32BE (source, dest, numSamples);
  20538. break;
  20539. case float32LE:
  20540. convertFloatToFloat32LE (source, dest, numSamples);
  20541. break;
  20542. case float32BE:
  20543. convertFloatToFloat32BE (source, dest, numSamples);
  20544. break;
  20545. default:
  20546. jassertfalse
  20547. break;
  20548. }
  20549. }
  20550. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  20551. const void* const source,
  20552. float* const dest,
  20553. const int numSamples)
  20554. {
  20555. switch (sourceFormat)
  20556. {
  20557. case int16LE:
  20558. convertInt16LEToFloat (source, dest, numSamples);
  20559. break;
  20560. case int16BE:
  20561. convertInt16BEToFloat (source, dest, numSamples);
  20562. break;
  20563. case int24LE:
  20564. convertInt24LEToFloat (source, dest, numSamples);
  20565. break;
  20566. case int24BE:
  20567. convertInt24BEToFloat (source, dest, numSamples);
  20568. break;
  20569. case int32LE:
  20570. convertInt32LEToFloat (source, dest, numSamples);
  20571. break;
  20572. case int32BE:
  20573. convertInt32BEToFloat (source, dest, numSamples);
  20574. break;
  20575. case float32LE:
  20576. convertFloat32LEToFloat (source, dest, numSamples);
  20577. break;
  20578. case float32BE:
  20579. convertFloat32BEToFloat (source, dest, numSamples);
  20580. break;
  20581. default:
  20582. jassertfalse
  20583. break;
  20584. }
  20585. }
  20586. void AudioDataConverters::interleaveSamples (const float** const source,
  20587. float* const dest,
  20588. const int numSamples,
  20589. const int numChannels)
  20590. {
  20591. for (int chan = 0; chan < numChannels; ++chan)
  20592. {
  20593. int i = chan;
  20594. const float* src = source [chan];
  20595. for (int j = 0; j < numSamples; ++j)
  20596. {
  20597. dest [i] = src [j];
  20598. i += numChannels;
  20599. }
  20600. }
  20601. }
  20602. void AudioDataConverters::deinterleaveSamples (const float* const source,
  20603. float** const dest,
  20604. const int numSamples,
  20605. const int numChannels)
  20606. {
  20607. for (int chan = 0; chan < numChannels; ++chan)
  20608. {
  20609. int i = chan;
  20610. float* dst = dest [chan];
  20611. for (int j = 0; j < numSamples; ++j)
  20612. {
  20613. dst [j] = source [i];
  20614. i += numChannels;
  20615. }
  20616. }
  20617. }
  20618. END_JUCE_NAMESPACE
  20619. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  20620. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  20621. BEGIN_JUCE_NAMESPACE
  20622. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  20623. const int numSamples) throw()
  20624. : numChannels (numChannels_),
  20625. size (numSamples)
  20626. {
  20627. jassert (numSamples >= 0);
  20628. jassert (numChannels_ > 0);
  20629. allocateData();
  20630. }
  20631. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  20632. : numChannels (other.numChannels),
  20633. size (other.size)
  20634. {
  20635. allocateData();
  20636. const size_t numBytes = size * sizeof (float);
  20637. for (int i = 0; i < numChannels; ++i)
  20638. memcpy (channels[i], other.channels[i], numBytes);
  20639. }
  20640. void AudioSampleBuffer::allocateData()
  20641. {
  20642. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  20643. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  20644. allocatedData.malloc (allocatedBytes);
  20645. channels = reinterpret_cast <float**> (allocatedData.getData());
  20646. float* chan = (float*) (allocatedData + channelListSize);
  20647. for (int i = 0; i < numChannels; ++i)
  20648. {
  20649. channels[i] = chan;
  20650. chan += size;
  20651. }
  20652. channels [numChannels] = 0;
  20653. }
  20654. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  20655. const int numChannels_,
  20656. const int numSamples) throw()
  20657. : numChannels (numChannels_),
  20658. size (numSamples),
  20659. allocatedBytes (0)
  20660. {
  20661. jassert (numChannels_ > 0);
  20662. allocateChannels (dataToReferTo);
  20663. }
  20664. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  20665. const int newNumChannels,
  20666. const int newNumSamples) throw()
  20667. {
  20668. jassert (newNumChannels > 0);
  20669. allocatedBytes = 0;
  20670. allocatedData.free();
  20671. numChannels = newNumChannels;
  20672. size = newNumSamples;
  20673. allocateChannels (dataToReferTo);
  20674. }
  20675. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  20676. {
  20677. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  20678. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  20679. {
  20680. channels = static_cast <float**> (preallocatedChannelSpace);
  20681. }
  20682. else
  20683. {
  20684. allocatedData.malloc (numChannels + 1, sizeof (float*));
  20685. channels = reinterpret_cast <float**> (allocatedData.getData());
  20686. }
  20687. for (int i = 0; i < numChannels; ++i)
  20688. {
  20689. // you have to pass in the same number of valid pointers as numChannels
  20690. jassert (dataToReferTo[i] != 0);
  20691. channels[i] = dataToReferTo[i];
  20692. }
  20693. channels [numChannels] = 0;
  20694. }
  20695. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  20696. {
  20697. if (this != &other)
  20698. {
  20699. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  20700. const size_t numBytes = size * sizeof (float);
  20701. for (int i = 0; i < numChannels; ++i)
  20702. memcpy (channels[i], other.channels[i], numBytes);
  20703. }
  20704. return *this;
  20705. }
  20706. AudioSampleBuffer::~AudioSampleBuffer() throw()
  20707. {
  20708. }
  20709. void AudioSampleBuffer::setSize (const int newNumChannels,
  20710. const int newNumSamples,
  20711. const bool keepExistingContent,
  20712. const bool clearExtraSpace,
  20713. const bool avoidReallocating) throw()
  20714. {
  20715. jassert (newNumChannels > 0);
  20716. if (newNumSamples != size || newNumChannels != numChannels)
  20717. {
  20718. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  20719. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  20720. if (keepExistingContent)
  20721. {
  20722. HeapBlock <char> newData;
  20723. newData.allocate (newTotalBytes, clearExtraSpace);
  20724. const int numChansToCopy = jmin (numChannels, newNumChannels);
  20725. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  20726. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  20727. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  20728. for (int i = 0; i < numChansToCopy; ++i)
  20729. {
  20730. memcpy (newChan, channels[i], numBytesToCopy);
  20731. newChannels[i] = newChan;
  20732. newChan += newNumSamples;
  20733. }
  20734. allocatedData.swapWith (newData);
  20735. allocatedBytes = (int) newTotalBytes;
  20736. channels = newChannels;
  20737. }
  20738. else
  20739. {
  20740. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  20741. {
  20742. if (clearExtraSpace)
  20743. zeromem (allocatedData, newTotalBytes);
  20744. }
  20745. else
  20746. {
  20747. allocatedBytes = newTotalBytes;
  20748. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  20749. channels = reinterpret_cast <float**> (allocatedData.getData());
  20750. }
  20751. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  20752. for (int i = 0; i < newNumChannels; ++i)
  20753. {
  20754. channels[i] = chan;
  20755. chan += newNumSamples;
  20756. }
  20757. }
  20758. channels [newNumChannels] = 0;
  20759. size = newNumSamples;
  20760. numChannels = newNumChannels;
  20761. }
  20762. }
  20763. void AudioSampleBuffer::clear() throw()
  20764. {
  20765. for (int i = 0; i < numChannels; ++i)
  20766. zeromem (channels[i], size * sizeof (float));
  20767. }
  20768. void AudioSampleBuffer::clear (const int startSample,
  20769. const int numSamples) throw()
  20770. {
  20771. jassert (startSample >= 0 && startSample + numSamples <= size);
  20772. for (int i = 0; i < numChannels; ++i)
  20773. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  20774. }
  20775. void AudioSampleBuffer::clear (const int channel,
  20776. const int startSample,
  20777. const int numSamples) throw()
  20778. {
  20779. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20780. jassert (startSample >= 0 && startSample + numSamples <= size);
  20781. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  20782. }
  20783. void AudioSampleBuffer::applyGain (const int channel,
  20784. const int startSample,
  20785. int numSamples,
  20786. const float gain) throw()
  20787. {
  20788. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20789. jassert (startSample >= 0 && startSample + numSamples <= size);
  20790. if (gain != 1.0f)
  20791. {
  20792. float* d = channels [channel] + startSample;
  20793. if (gain == 0.0f)
  20794. {
  20795. zeromem (d, sizeof (float) * numSamples);
  20796. }
  20797. else
  20798. {
  20799. while (--numSamples >= 0)
  20800. *d++ *= gain;
  20801. }
  20802. }
  20803. }
  20804. void AudioSampleBuffer::applyGainRamp (const int channel,
  20805. const int startSample,
  20806. int numSamples,
  20807. float startGain,
  20808. float endGain) throw()
  20809. {
  20810. if (startGain == endGain)
  20811. {
  20812. applyGain (channel, startSample, numSamples, startGain);
  20813. }
  20814. else
  20815. {
  20816. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20817. jassert (startSample >= 0 && startSample + numSamples <= size);
  20818. const float increment = (endGain - startGain) / numSamples;
  20819. float* d = channels [channel] + startSample;
  20820. while (--numSamples >= 0)
  20821. {
  20822. *d++ *= startGain;
  20823. startGain += increment;
  20824. }
  20825. }
  20826. }
  20827. void AudioSampleBuffer::applyGain (const int startSample,
  20828. const int numSamples,
  20829. const float gain) throw()
  20830. {
  20831. for (int i = 0; i < numChannels; ++i)
  20832. applyGain (i, startSample, numSamples, gain);
  20833. }
  20834. void AudioSampleBuffer::addFrom (const int destChannel,
  20835. const int destStartSample,
  20836. const AudioSampleBuffer& source,
  20837. const int sourceChannel,
  20838. const int sourceStartSample,
  20839. int numSamples,
  20840. const float gain) throw()
  20841. {
  20842. jassert (&source != this || sourceChannel != destChannel);
  20843. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20844. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20845. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20846. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20847. if (gain != 0.0f && numSamples > 0)
  20848. {
  20849. float* d = channels [destChannel] + destStartSample;
  20850. const float* s = source.channels [sourceChannel] + sourceStartSample;
  20851. if (gain != 1.0f)
  20852. {
  20853. while (--numSamples >= 0)
  20854. *d++ += gain * *s++;
  20855. }
  20856. else
  20857. {
  20858. while (--numSamples >= 0)
  20859. *d++ += *s++;
  20860. }
  20861. }
  20862. }
  20863. void AudioSampleBuffer::addFrom (const int destChannel,
  20864. const int destStartSample,
  20865. const float* source,
  20866. int numSamples,
  20867. const float gain) throw()
  20868. {
  20869. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20870. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20871. jassert (source != 0);
  20872. if (gain != 0.0f && numSamples > 0)
  20873. {
  20874. float* d = channels [destChannel] + destStartSample;
  20875. if (gain != 1.0f)
  20876. {
  20877. while (--numSamples >= 0)
  20878. *d++ += gain * *source++;
  20879. }
  20880. else
  20881. {
  20882. while (--numSamples >= 0)
  20883. *d++ += *source++;
  20884. }
  20885. }
  20886. }
  20887. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  20888. const int destStartSample,
  20889. const float* source,
  20890. int numSamples,
  20891. float startGain,
  20892. const float endGain) throw()
  20893. {
  20894. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20895. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20896. jassert (source != 0);
  20897. if (startGain == endGain)
  20898. {
  20899. addFrom (destChannel,
  20900. destStartSample,
  20901. source,
  20902. numSamples,
  20903. startGain);
  20904. }
  20905. else
  20906. {
  20907. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  20908. {
  20909. const float increment = (endGain - startGain) / numSamples;
  20910. float* d = channels [destChannel] + destStartSample;
  20911. while (--numSamples >= 0)
  20912. {
  20913. *d++ += startGain * *source++;
  20914. startGain += increment;
  20915. }
  20916. }
  20917. }
  20918. }
  20919. void AudioSampleBuffer::copyFrom (const int destChannel,
  20920. const int destStartSample,
  20921. const AudioSampleBuffer& source,
  20922. const int sourceChannel,
  20923. const int sourceStartSample,
  20924. int numSamples) throw()
  20925. {
  20926. jassert (&source != this || sourceChannel != destChannel);
  20927. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20928. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20929. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20930. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20931. if (numSamples > 0)
  20932. {
  20933. memcpy (channels [destChannel] + destStartSample,
  20934. source.channels [sourceChannel] + sourceStartSample,
  20935. sizeof (float) * numSamples);
  20936. }
  20937. }
  20938. void AudioSampleBuffer::copyFrom (const int destChannel,
  20939. const int destStartSample,
  20940. const float* source,
  20941. int numSamples) throw()
  20942. {
  20943. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20944. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20945. jassert (source != 0);
  20946. if (numSamples > 0)
  20947. {
  20948. memcpy (channels [destChannel] + destStartSample,
  20949. source,
  20950. sizeof (float) * numSamples);
  20951. }
  20952. }
  20953. void AudioSampleBuffer::copyFrom (const int destChannel,
  20954. const int destStartSample,
  20955. const float* source,
  20956. int numSamples,
  20957. const float gain) throw()
  20958. {
  20959. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20960. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20961. jassert (source != 0);
  20962. if (numSamples > 0)
  20963. {
  20964. float* d = channels [destChannel] + destStartSample;
  20965. if (gain != 1.0f)
  20966. {
  20967. if (gain == 0)
  20968. {
  20969. zeromem (d, sizeof (float) * numSamples);
  20970. }
  20971. else
  20972. {
  20973. while (--numSamples >= 0)
  20974. *d++ = gain * *source++;
  20975. }
  20976. }
  20977. else
  20978. {
  20979. memcpy (d, source, sizeof (float) * numSamples);
  20980. }
  20981. }
  20982. }
  20983. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  20984. const int destStartSample,
  20985. const float* source,
  20986. int numSamples,
  20987. float startGain,
  20988. float endGain) throw()
  20989. {
  20990. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20991. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20992. jassert (source != 0);
  20993. if (startGain == endGain)
  20994. {
  20995. copyFrom (destChannel,
  20996. destStartSample,
  20997. source,
  20998. numSamples,
  20999. startGain);
  21000. }
  21001. else
  21002. {
  21003. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21004. {
  21005. const float increment = (endGain - startGain) / numSamples;
  21006. float* d = channels [destChannel] + destStartSample;
  21007. while (--numSamples >= 0)
  21008. {
  21009. *d++ = startGain * *source++;
  21010. startGain += increment;
  21011. }
  21012. }
  21013. }
  21014. }
  21015. void AudioSampleBuffer::findMinMax (const int channel,
  21016. const int startSample,
  21017. int numSamples,
  21018. float& minVal,
  21019. float& maxVal) const throw()
  21020. {
  21021. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21022. jassert (startSample >= 0 && startSample + numSamples <= size);
  21023. if (numSamples <= 0)
  21024. {
  21025. minVal = 0.0f;
  21026. maxVal = 0.0f;
  21027. }
  21028. else
  21029. {
  21030. const float* d = channels [channel] + startSample;
  21031. float mn = *d++;
  21032. float mx = mn;
  21033. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  21034. {
  21035. const float samp = *d++;
  21036. if (samp > mx)
  21037. mx = samp;
  21038. if (samp < mn)
  21039. mn = samp;
  21040. }
  21041. maxVal = mx;
  21042. minVal = mn;
  21043. }
  21044. }
  21045. float AudioSampleBuffer::getMagnitude (const int channel,
  21046. const int startSample,
  21047. const int numSamples) const throw()
  21048. {
  21049. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21050. jassert (startSample >= 0 && startSample + numSamples <= size);
  21051. float mn, mx;
  21052. findMinMax (channel, startSample, numSamples, mn, mx);
  21053. return jmax (mn, -mn, mx, -mx);
  21054. }
  21055. float AudioSampleBuffer::getMagnitude (const int startSample,
  21056. const int numSamples) const throw()
  21057. {
  21058. float mag = 0.0f;
  21059. for (int i = 0; i < numChannels; ++i)
  21060. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  21061. return mag;
  21062. }
  21063. float AudioSampleBuffer::getRMSLevel (const int channel,
  21064. const int startSample,
  21065. const int numSamples) const throw()
  21066. {
  21067. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21068. jassert (startSample >= 0 && startSample + numSamples <= size);
  21069. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  21070. return 0.0f;
  21071. const float* const data = channels [channel] + startSample;
  21072. double sum = 0.0;
  21073. for (int i = 0; i < numSamples; ++i)
  21074. {
  21075. const float sample = data [i];
  21076. sum += sample * sample;
  21077. }
  21078. return (float) std::sqrt (sum / numSamples);
  21079. }
  21080. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  21081. const int startSample,
  21082. const int numSamples,
  21083. const int readerStartSample,
  21084. const bool useLeftChan,
  21085. const bool useRightChan) throw()
  21086. {
  21087. jassert (reader != 0);
  21088. jassert (startSample >= 0 && startSample + numSamples <= size);
  21089. if (numSamples > 0)
  21090. {
  21091. int* chans[3];
  21092. if (useLeftChan == useRightChan)
  21093. {
  21094. chans[0] = (int*) getSampleData (0, startSample);
  21095. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? (int*) getSampleData (1, startSample) : 0;
  21096. }
  21097. else if (useLeftChan || (reader->numChannels == 1))
  21098. {
  21099. chans[0] = (int*) getSampleData (0, startSample);
  21100. chans[1] = 0;
  21101. }
  21102. else if (useRightChan)
  21103. {
  21104. chans[0] = 0;
  21105. chans[1] = (int*) getSampleData (0, startSample);
  21106. }
  21107. chans[2] = 0;
  21108. reader->read (chans, 2, readerStartSample, numSamples, true);
  21109. if (! reader->usesFloatingPointData)
  21110. {
  21111. for (int j = 0; j < 2; ++j)
  21112. {
  21113. float* const d = reinterpret_cast <float*> (chans[j]);
  21114. if (d != 0)
  21115. {
  21116. const float multiplier = 1.0f / 0x7fffffff;
  21117. for (int i = 0; i < numSamples; ++i)
  21118. d[i] = *(int*)(d + i) * multiplier;
  21119. }
  21120. }
  21121. }
  21122. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  21123. {
  21124. // if this is a stereo buffer and the source was mono, dupe the first channel..
  21125. memcpy (getSampleData (1, startSample),
  21126. getSampleData (0, startSample),
  21127. sizeof (float) * numSamples);
  21128. }
  21129. }
  21130. }
  21131. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  21132. const int startSample,
  21133. const int numSamples) const throw()
  21134. {
  21135. jassert (startSample >= 0 && startSample + numSamples <= size);
  21136. if (numSamples > 0)
  21137. {
  21138. int* chans [3];
  21139. if (writer->isFloatingPoint())
  21140. {
  21141. chans[0] = (int*) getSampleData (0, startSample);
  21142. if (numChannels > 1)
  21143. chans[1] = (int*) getSampleData (1, startSample);
  21144. else
  21145. chans[1] = 0;
  21146. chans[2] = 0;
  21147. writer->write ((const int**) chans, numSamples);
  21148. }
  21149. else
  21150. {
  21151. HeapBlock <int> tempBuffer (numSamples * 2);
  21152. chans[0] = tempBuffer;
  21153. if (numChannels > 1)
  21154. chans[1] = chans[0] + numSamples;
  21155. else
  21156. chans[1] = 0;
  21157. chans[2] = 0;
  21158. for (int j = 0; j < 2; ++j)
  21159. {
  21160. int* const dest = chans[j];
  21161. if (dest != 0)
  21162. {
  21163. const float* const src = channels [j] + startSample;
  21164. for (int i = 0; i < numSamples; ++i)
  21165. {
  21166. const double samp = src[i];
  21167. if (samp <= -1.0)
  21168. dest[i] = std::numeric_limits<int>::min();
  21169. else if (samp >= 1.0)
  21170. dest[i] = std::numeric_limits<int>::max();
  21171. else
  21172. dest[i] = roundToInt (std::numeric_limits<int>::max() * samp);
  21173. }
  21174. }
  21175. }
  21176. writer->write ((const int**) chans, numSamples);
  21177. }
  21178. }
  21179. }
  21180. END_JUCE_NAMESPACE
  21181. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  21182. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  21183. BEGIN_JUCE_NAMESPACE
  21184. IIRFilter::IIRFilter()
  21185. : active (false)
  21186. {
  21187. reset();
  21188. }
  21189. IIRFilter::IIRFilter (const IIRFilter& other)
  21190. : active (other.active)
  21191. {
  21192. const ScopedLock sl (other.processLock);
  21193. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  21194. reset();
  21195. }
  21196. IIRFilter::~IIRFilter()
  21197. {
  21198. }
  21199. void IIRFilter::reset() throw()
  21200. {
  21201. const ScopedLock sl (processLock);
  21202. x1 = 0;
  21203. x2 = 0;
  21204. y1 = 0;
  21205. y2 = 0;
  21206. }
  21207. float IIRFilter::processSingleSampleRaw (const float in) throw()
  21208. {
  21209. float out = coefficients[0] * in
  21210. + coefficients[1] * x1
  21211. + coefficients[2] * x2
  21212. - coefficients[4] * y1
  21213. - coefficients[5] * y2;
  21214. #if JUCE_INTEL
  21215. if (! (out < -1.0e-8 || out > 1.0e-8))
  21216. out = 0;
  21217. #endif
  21218. x2 = x1;
  21219. x1 = in;
  21220. y2 = y1;
  21221. y1 = out;
  21222. return out;
  21223. }
  21224. void IIRFilter::processSamples (float* const samples,
  21225. const int numSamples) throw()
  21226. {
  21227. const ScopedLock sl (processLock);
  21228. if (active)
  21229. {
  21230. for (int i = 0; i < numSamples; ++i)
  21231. {
  21232. const float in = samples[i];
  21233. float out = coefficients[0] * in
  21234. + coefficients[1] * x1
  21235. + coefficients[2] * x2
  21236. - coefficients[4] * y1
  21237. - coefficients[5] * y2;
  21238. #if JUCE_INTEL
  21239. if (! (out < -1.0e-8 || out > 1.0e-8))
  21240. out = 0;
  21241. #endif
  21242. x2 = x1;
  21243. x1 = in;
  21244. y2 = y1;
  21245. y1 = out;
  21246. samples[i] = out;
  21247. }
  21248. }
  21249. }
  21250. void IIRFilter::makeLowPass (const double sampleRate,
  21251. const double frequency) throw()
  21252. {
  21253. jassert (sampleRate > 0);
  21254. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  21255. const double nSquared = n * n;
  21256. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  21257. setCoefficients (c1,
  21258. c1 * 2.0f,
  21259. c1,
  21260. 1.0,
  21261. c1 * 2.0 * (1.0 - nSquared),
  21262. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  21263. }
  21264. void IIRFilter::makeHighPass (const double sampleRate,
  21265. const double frequency) throw()
  21266. {
  21267. const double n = tan (double_Pi * frequency / sampleRate);
  21268. const double nSquared = n * n;
  21269. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  21270. setCoefficients (c1,
  21271. c1 * -2.0f,
  21272. c1,
  21273. 1.0,
  21274. c1 * 2.0 * (nSquared - 1.0),
  21275. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  21276. }
  21277. void IIRFilter::makeLowShelf (const double sampleRate,
  21278. const double cutOffFrequency,
  21279. const double Q,
  21280. const float gainFactor) throw()
  21281. {
  21282. jassert (sampleRate > 0);
  21283. jassert (Q > 0);
  21284. const double A = jmax (0.0f, gainFactor);
  21285. const double aminus1 = A - 1.0;
  21286. const double aplus1 = A + 1.0;
  21287. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  21288. const double coso = std::cos (omega);
  21289. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  21290. const double aminus1TimesCoso = aminus1 * coso;
  21291. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  21292. A * 2.0 * (aminus1 - aplus1 * coso),
  21293. A * (aplus1 - aminus1TimesCoso - beta),
  21294. aplus1 + aminus1TimesCoso + beta,
  21295. -2.0 * (aminus1 + aplus1 * coso),
  21296. aplus1 + aminus1TimesCoso - beta);
  21297. }
  21298. void IIRFilter::makeHighShelf (const double sampleRate,
  21299. const double cutOffFrequency,
  21300. const double Q,
  21301. const float gainFactor) throw()
  21302. {
  21303. jassert (sampleRate > 0);
  21304. jassert (Q > 0);
  21305. const double A = jmax (0.0f, gainFactor);
  21306. const double aminus1 = A - 1.0;
  21307. const double aplus1 = A + 1.0;
  21308. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  21309. const double coso = std::cos (omega);
  21310. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  21311. const double aminus1TimesCoso = aminus1 * coso;
  21312. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  21313. A * -2.0 * (aminus1 + aplus1 * coso),
  21314. A * (aplus1 + aminus1TimesCoso - beta),
  21315. aplus1 - aminus1TimesCoso + beta,
  21316. 2.0 * (aminus1 - aplus1 * coso),
  21317. aplus1 - aminus1TimesCoso - beta);
  21318. }
  21319. void IIRFilter::makeBandPass (const double sampleRate,
  21320. const double centreFrequency,
  21321. const double Q,
  21322. const float gainFactor) throw()
  21323. {
  21324. jassert (sampleRate > 0);
  21325. jassert (Q > 0);
  21326. const double A = jmax (0.0f, gainFactor);
  21327. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  21328. const double alpha = 0.5 * std::sin (omega) / Q;
  21329. const double c2 = -2.0 * std::cos (omega);
  21330. const double alphaTimesA = alpha * A;
  21331. const double alphaOverA = alpha / A;
  21332. setCoefficients (1.0 + alphaTimesA,
  21333. c2,
  21334. 1.0 - alphaTimesA,
  21335. 1.0 + alphaOverA,
  21336. c2,
  21337. 1.0 - alphaOverA);
  21338. }
  21339. void IIRFilter::makeInactive() throw()
  21340. {
  21341. const ScopedLock sl (processLock);
  21342. active = false;
  21343. }
  21344. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  21345. {
  21346. const ScopedLock sl (processLock);
  21347. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  21348. active = other.active;
  21349. }
  21350. void IIRFilter::setCoefficients (double c1,
  21351. double c2,
  21352. double c3,
  21353. double c4,
  21354. double c5,
  21355. double c6) throw()
  21356. {
  21357. const double a = 1.0 / c4;
  21358. c1 *= a;
  21359. c2 *= a;
  21360. c3 *= a;
  21361. c5 *= a;
  21362. c6 *= a;
  21363. const ScopedLock sl (processLock);
  21364. coefficients[0] = (float) c1;
  21365. coefficients[1] = (float) c2;
  21366. coefficients[2] = (float) c3;
  21367. coefficients[3] = (float) c4;
  21368. coefficients[4] = (float) c5;
  21369. coefficients[5] = (float) c6;
  21370. active = true;
  21371. }
  21372. END_JUCE_NAMESPACE
  21373. /*** End of inlined file: juce_IIRFilter.cpp ***/
  21374. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  21375. BEGIN_JUCE_NAMESPACE
  21376. MidiBuffer::MidiBuffer() throw()
  21377. : bytesUsed (0)
  21378. {
  21379. }
  21380. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  21381. : bytesUsed (0)
  21382. {
  21383. addEvent (message, 0);
  21384. }
  21385. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  21386. : data (other.data),
  21387. bytesUsed (other.bytesUsed)
  21388. {
  21389. }
  21390. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  21391. {
  21392. bytesUsed = other.bytesUsed;
  21393. data = other.data;
  21394. return *this;
  21395. }
  21396. void MidiBuffer::swapWith (MidiBuffer& other)
  21397. {
  21398. data.swapWith (other.data);
  21399. swapVariables <int> (bytesUsed, other.bytesUsed);
  21400. }
  21401. MidiBuffer::~MidiBuffer() throw()
  21402. {
  21403. }
  21404. inline uint8* MidiBuffer::getData() const throw()
  21405. {
  21406. return static_cast <uint8*> (data.getData());
  21407. }
  21408. inline int MidiBuffer::getEventTime (const void* const d) throw()
  21409. {
  21410. return *static_cast <const int*> (d);
  21411. }
  21412. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  21413. {
  21414. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  21415. }
  21416. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  21417. {
  21418. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  21419. }
  21420. void MidiBuffer::clear() throw()
  21421. {
  21422. bytesUsed = 0;
  21423. }
  21424. void MidiBuffer::clear (const int startSample,
  21425. const int numSamples) throw()
  21426. {
  21427. uint8* const start = findEventAfter (getData(), startSample - 1);
  21428. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  21429. if (end > start)
  21430. {
  21431. const int bytesToMove = bytesUsed - (int) (end - getData());
  21432. if (bytesToMove > 0)
  21433. memmove (start, end, bytesToMove);
  21434. bytesUsed -= (int) (end - start);
  21435. }
  21436. }
  21437. void MidiBuffer::addEvent (const MidiMessage& m,
  21438. const int sampleNumber) throw()
  21439. {
  21440. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  21441. }
  21442. static int findActualEventLength (const uint8* const data,
  21443. const int maxBytes) throw()
  21444. {
  21445. unsigned int byte = (unsigned int) *data;
  21446. int size = 0;
  21447. if (byte == 0xf0 || byte == 0xf7)
  21448. {
  21449. const uint8* d = data + 1;
  21450. while (d < data + maxBytes)
  21451. if (*d++ == 0xf7)
  21452. break;
  21453. size = (int) (d - data);
  21454. }
  21455. else if (byte == 0xff)
  21456. {
  21457. int n;
  21458. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  21459. size = jmin (maxBytes, n + 2 + bytesLeft);
  21460. }
  21461. else if (byte >= 0x80)
  21462. {
  21463. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  21464. }
  21465. return size;
  21466. }
  21467. void MidiBuffer::addEvent (const uint8* const newData,
  21468. const int maxBytes,
  21469. const int sampleNumber) throw()
  21470. {
  21471. const int numBytes = findActualEventLength (newData, maxBytes);
  21472. if (numBytes > 0)
  21473. {
  21474. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  21475. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  21476. uint8* d = findEventAfter (getData(), sampleNumber);
  21477. const int bytesToMove = bytesUsed - (int) (d - getData());
  21478. if (bytesToMove > 0)
  21479. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  21480. *reinterpret_cast <int*> (d) = sampleNumber;
  21481. d += sizeof (int);
  21482. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  21483. d += sizeof (uint16);
  21484. memcpy (d, newData, numBytes);
  21485. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  21486. }
  21487. }
  21488. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  21489. const int startSample,
  21490. const int numSamples,
  21491. const int sampleDeltaToAdd) throw()
  21492. {
  21493. Iterator i (otherBuffer);
  21494. i.setNextSamplePosition (startSample);
  21495. const uint8* eventData;
  21496. int eventSize, position;
  21497. while (i.getNextEvent (eventData, eventSize, position)
  21498. && (position < startSample + numSamples || numSamples < 0))
  21499. {
  21500. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  21501. }
  21502. }
  21503. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  21504. {
  21505. data.ensureSize (minimumNumBytes);
  21506. }
  21507. bool MidiBuffer::isEmpty() const throw()
  21508. {
  21509. return bytesUsed == 0;
  21510. }
  21511. int MidiBuffer::getNumEvents() const throw()
  21512. {
  21513. int n = 0;
  21514. const uint8* d = getData();
  21515. const uint8* const end = d + bytesUsed;
  21516. while (d < end)
  21517. {
  21518. d += getEventTotalSize (d);
  21519. ++n;
  21520. }
  21521. return n;
  21522. }
  21523. int MidiBuffer::getFirstEventTime() const throw()
  21524. {
  21525. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  21526. }
  21527. int MidiBuffer::getLastEventTime() const throw()
  21528. {
  21529. if (bytesUsed == 0)
  21530. return 0;
  21531. const uint8* d = getData();
  21532. const uint8* const endData = d + bytesUsed;
  21533. for (;;)
  21534. {
  21535. const uint8* const nextOne = d + getEventTotalSize (d);
  21536. if (nextOne >= endData)
  21537. return getEventTime (d);
  21538. d = nextOne;
  21539. }
  21540. }
  21541. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  21542. {
  21543. const uint8* const endData = getData() + bytesUsed;
  21544. while (d < endData && getEventTime (d) <= samplePosition)
  21545. d += getEventTotalSize (d);
  21546. return d;
  21547. }
  21548. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  21549. : buffer (buffer_),
  21550. data (buffer_.getData())
  21551. {
  21552. }
  21553. MidiBuffer::Iterator::~Iterator() throw()
  21554. {
  21555. }
  21556. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  21557. {
  21558. data = buffer.getData();
  21559. const uint8* dataEnd = data + buffer.bytesUsed;
  21560. while (data < dataEnd && getEventTime (data) < samplePosition)
  21561. data += getEventTotalSize (data);
  21562. }
  21563. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  21564. {
  21565. if (data >= buffer.getData() + buffer.bytesUsed)
  21566. return false;
  21567. samplePosition = getEventTime (data);
  21568. numBytes = getEventDataSize (data);
  21569. data += sizeof (int) + sizeof (uint16);
  21570. midiData = data;
  21571. data += numBytes;
  21572. return true;
  21573. }
  21574. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  21575. {
  21576. if (data >= buffer.getData() + buffer.bytesUsed)
  21577. return false;
  21578. samplePosition = getEventTime (data);
  21579. const int numBytes = getEventDataSize (data);
  21580. data += sizeof (int) + sizeof (uint16);
  21581. result = MidiMessage (data, numBytes, samplePosition);
  21582. data += numBytes;
  21583. return true;
  21584. }
  21585. END_JUCE_NAMESPACE
  21586. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  21587. /*** Start of inlined file: juce_MidiFile.cpp ***/
  21588. BEGIN_JUCE_NAMESPACE
  21589. namespace MidiFileHelpers
  21590. {
  21591. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  21592. {
  21593. unsigned int buffer = v & 0x7F;
  21594. while ((v >>= 7) != 0)
  21595. {
  21596. buffer <<= 8;
  21597. buffer |= ((v & 0x7F) | 0x80);
  21598. }
  21599. for (;;)
  21600. {
  21601. out.writeByte ((char) buffer);
  21602. if (buffer & 0x80)
  21603. buffer >>= 8;
  21604. else
  21605. break;
  21606. }
  21607. }
  21608. static bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  21609. {
  21610. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  21611. data += 4;
  21612. if (ch != ByteOrder::bigEndianInt ("MThd"))
  21613. {
  21614. bool ok = false;
  21615. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  21616. {
  21617. for (int i = 0; i < 8; ++i)
  21618. {
  21619. ch = ByteOrder::bigEndianInt (data);
  21620. data += 4;
  21621. if (ch == ByteOrder::bigEndianInt ("MThd"))
  21622. {
  21623. ok = true;
  21624. break;
  21625. }
  21626. }
  21627. }
  21628. if (! ok)
  21629. return false;
  21630. }
  21631. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  21632. data += 4;
  21633. fileType = (short) ByteOrder::bigEndianShort (data);
  21634. data += 2;
  21635. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  21636. data += 2;
  21637. timeFormat = (short) ByteOrder::bigEndianShort (data);
  21638. data += 2;
  21639. bytesRemaining -= 6;
  21640. data += bytesRemaining;
  21641. return true;
  21642. }
  21643. static double convertTicksToSeconds (const double time,
  21644. const MidiMessageSequence& tempoEvents,
  21645. const int timeFormat)
  21646. {
  21647. if (timeFormat > 0)
  21648. {
  21649. int numer = 4, denom = 4;
  21650. double tempoTime = 0.0, correctedTempoTime = 0.0;
  21651. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  21652. double secsPerTick = 0.5 * tickLen;
  21653. const int numEvents = tempoEvents.getNumEvents();
  21654. for (int i = 0; i < numEvents; ++i)
  21655. {
  21656. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  21657. if (time <= m.getTimeStamp())
  21658. break;
  21659. if (timeFormat > 0)
  21660. {
  21661. correctedTempoTime = correctedTempoTime
  21662. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  21663. }
  21664. else
  21665. {
  21666. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21667. }
  21668. tempoTime = m.getTimeStamp();
  21669. if (m.isTempoMetaEvent())
  21670. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  21671. else if (m.isTimeSignatureMetaEvent())
  21672. m.getTimeSignatureInfo (numer, denom);
  21673. while (i + 1 < numEvents)
  21674. {
  21675. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  21676. if (m2.getTimeStamp() == tempoTime)
  21677. {
  21678. ++i;
  21679. if (m2.isTempoMetaEvent())
  21680. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  21681. else if (m2.isTimeSignatureMetaEvent())
  21682. m2.getTimeSignatureInfo (numer, denom);
  21683. }
  21684. else
  21685. {
  21686. break;
  21687. }
  21688. }
  21689. }
  21690. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  21691. }
  21692. else
  21693. {
  21694. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21695. }
  21696. }
  21697. }
  21698. MidiFile::MidiFile()
  21699. : timeFormat ((short) (unsigned short) 0xe728)
  21700. {
  21701. }
  21702. MidiFile::~MidiFile()
  21703. {
  21704. clear();
  21705. }
  21706. void MidiFile::clear()
  21707. {
  21708. tracks.clear();
  21709. }
  21710. int MidiFile::getNumTracks() const throw()
  21711. {
  21712. return tracks.size();
  21713. }
  21714. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  21715. {
  21716. return tracks [index];
  21717. }
  21718. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  21719. {
  21720. tracks.add (new MidiMessageSequence (trackSequence));
  21721. }
  21722. short MidiFile::getTimeFormat() const throw()
  21723. {
  21724. return timeFormat;
  21725. }
  21726. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  21727. {
  21728. timeFormat = (short) ticks;
  21729. }
  21730. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  21731. const int subframeResolution) throw()
  21732. {
  21733. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  21734. }
  21735. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  21736. {
  21737. for (int i = tracks.size(); --i >= 0;)
  21738. {
  21739. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  21740. for (int j = 0; j < numEvents; ++j)
  21741. {
  21742. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  21743. if (m.isTempoMetaEvent())
  21744. tempoChangeEvents.addEvent (m);
  21745. }
  21746. }
  21747. }
  21748. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  21749. {
  21750. for (int i = tracks.size(); --i >= 0;)
  21751. {
  21752. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  21753. for (int j = 0; j < numEvents; ++j)
  21754. {
  21755. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  21756. if (m.isTimeSignatureMetaEvent())
  21757. timeSigEvents.addEvent (m);
  21758. }
  21759. }
  21760. }
  21761. double MidiFile::getLastTimestamp() const
  21762. {
  21763. double t = 0.0;
  21764. for (int i = tracks.size(); --i >= 0;)
  21765. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  21766. return t;
  21767. }
  21768. bool MidiFile::readFrom (InputStream& sourceStream)
  21769. {
  21770. clear();
  21771. MemoryBlock data;
  21772. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  21773. // (put a sanity-check on the file size, as midi files are generally small)
  21774. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  21775. {
  21776. size_t size = data.getSize();
  21777. const uint8* d = static_cast <const uint8*> (data.getData());
  21778. short fileType, expectedTracks;
  21779. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  21780. {
  21781. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  21782. int track = 0;
  21783. while (size > 0 && track < expectedTracks)
  21784. {
  21785. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  21786. d += 4;
  21787. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  21788. d += 4;
  21789. if (chunkSize <= 0)
  21790. break;
  21791. if (size < 0)
  21792. return false;
  21793. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  21794. {
  21795. readNextTrack (d, chunkSize);
  21796. }
  21797. size -= chunkSize + 8;
  21798. d += chunkSize;
  21799. ++track;
  21800. }
  21801. return true;
  21802. }
  21803. }
  21804. return false;
  21805. }
  21806. // a comparator that puts all the note-offs before note-ons that have the same time
  21807. int MidiFile::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  21808. const MidiMessageSequence::MidiEventHolder* const second)
  21809. {
  21810. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  21811. if (diff == 0)
  21812. {
  21813. if (first->message.isNoteOff() && second->message.isNoteOn())
  21814. return -1;
  21815. else if (first->message.isNoteOn() && second->message.isNoteOff())
  21816. return 1;
  21817. else
  21818. return 0;
  21819. }
  21820. else
  21821. {
  21822. return (diff > 0) ? 1 : -1;
  21823. }
  21824. }
  21825. void MidiFile::readNextTrack (const uint8* data, int size)
  21826. {
  21827. double time = 0;
  21828. char lastStatusByte = 0;
  21829. MidiMessageSequence result;
  21830. while (size > 0)
  21831. {
  21832. int bytesUsed;
  21833. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  21834. data += bytesUsed;
  21835. size -= bytesUsed;
  21836. time += delay;
  21837. int messSize = 0;
  21838. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  21839. if (messSize <= 0)
  21840. break;
  21841. size -= messSize;
  21842. data += messSize;
  21843. result.addEvent (mm);
  21844. const char firstByte = *(mm.getRawData());
  21845. if ((firstByte & 0xf0) != 0xf0)
  21846. lastStatusByte = firstByte;
  21847. }
  21848. // use a sort that puts all the note-offs before note-ons that have the same time
  21849. result.list.sort (*this, true);
  21850. result.updateMatchedPairs();
  21851. addTrack (result);
  21852. }
  21853. void MidiFile::convertTimestampTicksToSeconds()
  21854. {
  21855. MidiMessageSequence tempoEvents;
  21856. findAllTempoEvents (tempoEvents);
  21857. findAllTimeSigEvents (tempoEvents);
  21858. for (int i = 0; i < tracks.size(); ++i)
  21859. {
  21860. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  21861. for (int j = ms.getNumEvents(); --j >= 0;)
  21862. {
  21863. MidiMessage& m = ms.getEventPointer(j)->message;
  21864. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  21865. tempoEvents,
  21866. timeFormat));
  21867. }
  21868. }
  21869. }
  21870. bool MidiFile::writeTo (OutputStream& out)
  21871. {
  21872. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  21873. out.writeIntBigEndian (6);
  21874. out.writeShortBigEndian (1); // type
  21875. out.writeShortBigEndian ((short) tracks.size());
  21876. out.writeShortBigEndian (timeFormat);
  21877. for (int i = 0; i < tracks.size(); ++i)
  21878. writeTrack (out, i);
  21879. out.flush();
  21880. return true;
  21881. }
  21882. void MidiFile::writeTrack (OutputStream& mainOut,
  21883. const int trackNum)
  21884. {
  21885. MemoryOutputStream out;
  21886. const MidiMessageSequence& ms = *tracks[trackNum];
  21887. int lastTick = 0;
  21888. char lastStatusByte = 0;
  21889. for (int i = 0; i < ms.getNumEvents(); ++i)
  21890. {
  21891. const MidiMessage& mm = ms.getEventPointer(i)->message;
  21892. const int tick = roundToInt (mm.getTimeStamp());
  21893. const int delta = jmax (0, tick - lastTick);
  21894. MidiFileHelpers::writeVariableLengthInt (out, delta);
  21895. lastTick = tick;
  21896. const char statusByte = *(mm.getRawData());
  21897. if ((statusByte == lastStatusByte)
  21898. && ((statusByte & 0xf0) != 0xf0)
  21899. && i > 0
  21900. && mm.getRawDataSize() > 1)
  21901. {
  21902. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  21903. }
  21904. else
  21905. {
  21906. out.write (mm.getRawData(), mm.getRawDataSize());
  21907. }
  21908. lastStatusByte = statusByte;
  21909. }
  21910. out.writeByte (0);
  21911. const MidiMessage m (MidiMessage::endOfTrack());
  21912. out.write (m.getRawData(),
  21913. m.getRawDataSize());
  21914. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  21915. mainOut.writeIntBigEndian ((int) out.getDataSize());
  21916. mainOut.write (out.getData(), (int) out.getDataSize());
  21917. }
  21918. END_JUCE_NAMESPACE
  21919. /*** End of inlined file: juce_MidiFile.cpp ***/
  21920. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  21921. BEGIN_JUCE_NAMESPACE
  21922. MidiKeyboardState::MidiKeyboardState()
  21923. {
  21924. zerostruct (noteStates);
  21925. }
  21926. MidiKeyboardState::~MidiKeyboardState()
  21927. {
  21928. }
  21929. void MidiKeyboardState::reset()
  21930. {
  21931. const ScopedLock sl (lock);
  21932. zerostruct (noteStates);
  21933. eventsToAdd.clear();
  21934. }
  21935. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  21936. {
  21937. jassert (midiChannel >= 0 && midiChannel <= 16);
  21938. return ((unsigned int) n) < 128
  21939. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  21940. }
  21941. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  21942. {
  21943. return ((unsigned int) n) < 128
  21944. && (noteStates[n] & midiChannelMask) != 0;
  21945. }
  21946. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  21947. {
  21948. jassert (midiChannel >= 0 && midiChannel <= 16);
  21949. jassert (((unsigned int) midiNoteNumber) < 128);
  21950. const ScopedLock sl (lock);
  21951. if (((unsigned int) midiNoteNumber) < 128)
  21952. {
  21953. const int timeNow = (int) Time::getMillisecondCounter();
  21954. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  21955. eventsToAdd.clear (0, timeNow - 500);
  21956. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  21957. }
  21958. }
  21959. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  21960. {
  21961. if (((unsigned int) midiNoteNumber) < 128)
  21962. {
  21963. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  21964. for (int i = listeners.size(); --i >= 0;)
  21965. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  21966. }
  21967. }
  21968. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  21969. {
  21970. const ScopedLock sl (lock);
  21971. if (isNoteOn (midiChannel, midiNoteNumber))
  21972. {
  21973. const int timeNow = (int) Time::getMillisecondCounter();
  21974. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  21975. eventsToAdd.clear (0, timeNow - 500);
  21976. noteOffInternal (midiChannel, midiNoteNumber);
  21977. }
  21978. }
  21979. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  21980. {
  21981. if (isNoteOn (midiChannel, midiNoteNumber))
  21982. {
  21983. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  21984. for (int i = listeners.size(); --i >= 0;)
  21985. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  21986. }
  21987. }
  21988. void MidiKeyboardState::allNotesOff (const int midiChannel)
  21989. {
  21990. const ScopedLock sl (lock);
  21991. if (midiChannel <= 0)
  21992. {
  21993. for (int i = 1; i <= 16; ++i)
  21994. allNotesOff (i);
  21995. }
  21996. else
  21997. {
  21998. for (int i = 0; i < 128; ++i)
  21999. noteOff (midiChannel, i);
  22000. }
  22001. }
  22002. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  22003. {
  22004. if (message.isNoteOn())
  22005. {
  22006. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  22007. }
  22008. else if (message.isNoteOff())
  22009. {
  22010. noteOffInternal (message.getChannel(), message.getNoteNumber());
  22011. }
  22012. else if (message.isAllNotesOff())
  22013. {
  22014. for (int i = 0; i < 128; ++i)
  22015. noteOffInternal (message.getChannel(), i);
  22016. }
  22017. }
  22018. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  22019. const int startSample,
  22020. const int numSamples,
  22021. const bool injectIndirectEvents)
  22022. {
  22023. MidiBuffer::Iterator i (buffer);
  22024. MidiMessage message (0xf4, 0.0);
  22025. int time;
  22026. const ScopedLock sl (lock);
  22027. while (i.getNextEvent (message, time))
  22028. processNextMidiEvent (message);
  22029. if (injectIndirectEvents)
  22030. {
  22031. MidiBuffer::Iterator i2 (eventsToAdd);
  22032. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  22033. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  22034. while (i2.getNextEvent (message, time))
  22035. {
  22036. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  22037. buffer.addEvent (message, startSample + pos);
  22038. }
  22039. }
  22040. eventsToAdd.clear();
  22041. }
  22042. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener) throw()
  22043. {
  22044. const ScopedLock sl (lock);
  22045. listeners.addIfNotAlreadyThere (listener);
  22046. }
  22047. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener) throw()
  22048. {
  22049. const ScopedLock sl (lock);
  22050. listeners.removeValue (listener);
  22051. }
  22052. END_JUCE_NAMESPACE
  22053. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  22054. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  22055. BEGIN_JUCE_NAMESPACE
  22056. int MidiMessage::readVariableLengthVal (const uint8* data,
  22057. int& numBytesUsed) throw()
  22058. {
  22059. numBytesUsed = 0;
  22060. int v = 0;
  22061. int i;
  22062. do
  22063. {
  22064. i = (int) *data++;
  22065. if (++numBytesUsed > 6)
  22066. break;
  22067. v = (v << 7) + (i & 0x7f);
  22068. } while (i & 0x80);
  22069. return v;
  22070. }
  22071. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  22072. {
  22073. // this method only works for valid starting bytes of a short midi message
  22074. jassert (firstByte >= 0x80
  22075. && firstByte != 0xf0
  22076. && firstByte != 0xf7);
  22077. static const char messageLengths[] =
  22078. {
  22079. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22080. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22081. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22082. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22083. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22084. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22085. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22086. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  22087. };
  22088. return messageLengths [firstByte & 0x7f];
  22089. }
  22090. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  22091. : timeStamp (t),
  22092. size (dataSize)
  22093. {
  22094. jassert (dataSize > 0);
  22095. if (dataSize <= 4)
  22096. data = static_cast<uint8*> (preallocatedData.asBytes);
  22097. else
  22098. data = new uint8 [dataSize];
  22099. memcpy (data, d, dataSize);
  22100. // check that the length matches the data..
  22101. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  22102. }
  22103. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  22104. : timeStamp (t),
  22105. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22106. size (1)
  22107. {
  22108. data[0] = (uint8) byte1;
  22109. // check that the length matches the data..
  22110. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  22111. }
  22112. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  22113. : timeStamp (t),
  22114. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22115. size (2)
  22116. {
  22117. data[0] = (uint8) byte1;
  22118. data[1] = (uint8) byte2;
  22119. // check that the length matches the data..
  22120. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  22121. }
  22122. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  22123. : timeStamp (t),
  22124. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22125. size (3)
  22126. {
  22127. data[0] = (uint8) byte1;
  22128. data[1] = (uint8) byte2;
  22129. data[2] = (uint8) byte3;
  22130. // check that the length matches the data..
  22131. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  22132. }
  22133. MidiMessage::MidiMessage (const MidiMessage& other)
  22134. : timeStamp (other.timeStamp),
  22135. size (other.size)
  22136. {
  22137. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22138. {
  22139. data = new uint8 [size];
  22140. memcpy (data, other.data, size);
  22141. }
  22142. else
  22143. {
  22144. data = static_cast<uint8*> (preallocatedData.asBytes);
  22145. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22146. }
  22147. }
  22148. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  22149. : timeStamp (newTimeStamp),
  22150. size (other.size)
  22151. {
  22152. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22153. {
  22154. data = new uint8 [size];
  22155. memcpy (data, other.data, size);
  22156. }
  22157. else
  22158. {
  22159. data = static_cast<uint8*> (preallocatedData.asBytes);
  22160. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22161. }
  22162. }
  22163. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  22164. : timeStamp (t),
  22165. data (static_cast<uint8*> (preallocatedData.asBytes))
  22166. {
  22167. const uint8* src = static_cast <const uint8*> (src_);
  22168. unsigned int byte = (unsigned int) *src;
  22169. if (byte < 0x80)
  22170. {
  22171. byte = (unsigned int) (uint8) lastStatusByte;
  22172. numBytesUsed = -1;
  22173. }
  22174. else
  22175. {
  22176. numBytesUsed = 0;
  22177. --sz;
  22178. ++src;
  22179. }
  22180. if (byte >= 0x80)
  22181. {
  22182. if (byte == 0xf0)
  22183. {
  22184. const uint8* d = src;
  22185. while (d < src + sz)
  22186. {
  22187. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  22188. {
  22189. if (*d == 0xf7) // include an 0xf7 if we hit one
  22190. ++d;
  22191. break;
  22192. }
  22193. ++d;
  22194. }
  22195. size = 1 + (int) (d - src);
  22196. data = new uint8 [size];
  22197. *data = (uint8) byte;
  22198. memcpy (data + 1, src, size - 1);
  22199. }
  22200. else if (byte == 0xff)
  22201. {
  22202. int n;
  22203. const int bytesLeft = readVariableLengthVal (src + 1, n);
  22204. size = jmin (sz + 1, n + 2 + bytesLeft);
  22205. data = new uint8 [size];
  22206. *data = (uint8) byte;
  22207. memcpy (data + 1, src, size - 1);
  22208. }
  22209. else
  22210. {
  22211. preallocatedData.asInt32 = 0;
  22212. size = getMessageLengthFromFirstByte ((uint8) byte);
  22213. data[0] = (uint8) byte;
  22214. if (size > 1)
  22215. {
  22216. data[1] = src[0];
  22217. if (size > 2)
  22218. data[2] = src[1];
  22219. }
  22220. }
  22221. numBytesUsed += size;
  22222. }
  22223. else
  22224. {
  22225. preallocatedData.asInt32 = 0;
  22226. size = 0;
  22227. }
  22228. }
  22229. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  22230. {
  22231. if (this != &other)
  22232. {
  22233. timeStamp = other.timeStamp;
  22234. size = other.size;
  22235. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  22236. delete[] data;
  22237. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22238. {
  22239. data = new uint8 [size];
  22240. memcpy (data, other.data, size);
  22241. }
  22242. else
  22243. {
  22244. data = static_cast<uint8*> (preallocatedData.asBytes);
  22245. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22246. }
  22247. }
  22248. return *this;
  22249. }
  22250. MidiMessage::~MidiMessage()
  22251. {
  22252. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  22253. delete[] data;
  22254. }
  22255. int MidiMessage::getChannel() const throw()
  22256. {
  22257. if ((data[0] & 0xf0) != 0xf0)
  22258. return (data[0] & 0xf) + 1;
  22259. else
  22260. return 0;
  22261. }
  22262. bool MidiMessage::isForChannel (const int channel) const throw()
  22263. {
  22264. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22265. return ((data[0] & 0xf) == channel - 1)
  22266. && ((data[0] & 0xf0) != 0xf0);
  22267. }
  22268. void MidiMessage::setChannel (const int channel) throw()
  22269. {
  22270. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22271. if ((data[0] & 0xf0) != (uint8) 0xf0)
  22272. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  22273. | (uint8)(channel - 1));
  22274. }
  22275. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  22276. {
  22277. return ((data[0] & 0xf0) == 0x90)
  22278. && (returnTrueForVelocity0 || data[2] != 0);
  22279. }
  22280. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  22281. {
  22282. return ((data[0] & 0xf0) == 0x80)
  22283. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  22284. }
  22285. bool MidiMessage::isNoteOnOrOff() const throw()
  22286. {
  22287. const int d = data[0] & 0xf0;
  22288. return (d == 0x90) || (d == 0x80);
  22289. }
  22290. int MidiMessage::getNoteNumber() const throw()
  22291. {
  22292. return data[1];
  22293. }
  22294. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  22295. {
  22296. if (isNoteOnOrOff())
  22297. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  22298. }
  22299. uint8 MidiMessage::getVelocity() const throw()
  22300. {
  22301. if (isNoteOnOrOff())
  22302. return data[2];
  22303. else
  22304. return 0;
  22305. }
  22306. float MidiMessage::getFloatVelocity() const throw()
  22307. {
  22308. return getVelocity() * (1.0f / 127.0f);
  22309. }
  22310. void MidiMessage::setVelocity (const float newVelocity) throw()
  22311. {
  22312. if (isNoteOnOrOff())
  22313. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (newVelocity * 127.0f));
  22314. }
  22315. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  22316. {
  22317. if (isNoteOnOrOff())
  22318. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (scaleFactor * data[2]));
  22319. }
  22320. bool MidiMessage::isAftertouch() const throw()
  22321. {
  22322. return (data[0] & 0xf0) == 0xa0;
  22323. }
  22324. int MidiMessage::getAfterTouchValue() const throw()
  22325. {
  22326. return data[2];
  22327. }
  22328. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  22329. const int noteNum,
  22330. const int aftertouchValue) throw()
  22331. {
  22332. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22333. jassert (((unsigned int) noteNum) <= 127);
  22334. jassert (((unsigned int) aftertouchValue) <= 127);
  22335. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  22336. noteNum & 0x7f,
  22337. aftertouchValue & 0x7f);
  22338. }
  22339. bool MidiMessage::isChannelPressure() const throw()
  22340. {
  22341. return (data[0] & 0xf0) == 0xd0;
  22342. }
  22343. int MidiMessage::getChannelPressureValue() const throw()
  22344. {
  22345. jassert (isChannelPressure());
  22346. return data[1];
  22347. }
  22348. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  22349. const int pressure) throw()
  22350. {
  22351. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22352. jassert (((unsigned int) pressure) <= 127);
  22353. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  22354. pressure & 0x7f);
  22355. }
  22356. bool MidiMessage::isProgramChange() const throw()
  22357. {
  22358. return (data[0] & 0xf0) == 0xc0;
  22359. }
  22360. int MidiMessage::getProgramChangeNumber() const throw()
  22361. {
  22362. return data[1];
  22363. }
  22364. const MidiMessage MidiMessage::programChange (const int channel,
  22365. const int programNumber) throw()
  22366. {
  22367. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22368. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  22369. programNumber & 0x7f);
  22370. }
  22371. bool MidiMessage::isPitchWheel() const throw()
  22372. {
  22373. return (data[0] & 0xf0) == 0xe0;
  22374. }
  22375. int MidiMessage::getPitchWheelValue() const throw()
  22376. {
  22377. return data[1] | (data[2] << 7);
  22378. }
  22379. const MidiMessage MidiMessage::pitchWheel (const int channel,
  22380. const int position) throw()
  22381. {
  22382. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22383. jassert (((unsigned int) position) <= 0x3fff);
  22384. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  22385. position & 127,
  22386. (position >> 7) & 127);
  22387. }
  22388. bool MidiMessage::isController() const throw()
  22389. {
  22390. return (data[0] & 0xf0) == 0xb0;
  22391. }
  22392. int MidiMessage::getControllerNumber() const throw()
  22393. {
  22394. jassert (isController());
  22395. return data[1];
  22396. }
  22397. int MidiMessage::getControllerValue() const throw()
  22398. {
  22399. jassert (isController());
  22400. return data[2];
  22401. }
  22402. const MidiMessage MidiMessage::controllerEvent (const int channel,
  22403. const int controllerType,
  22404. const int value) throw()
  22405. {
  22406. // the channel must be between 1 and 16 inclusive
  22407. jassert (channel > 0 && channel <= 16);
  22408. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  22409. controllerType & 127,
  22410. value & 127);
  22411. }
  22412. const MidiMessage MidiMessage::noteOn (const int channel,
  22413. const int noteNumber,
  22414. const float velocity) throw()
  22415. {
  22416. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  22417. }
  22418. const MidiMessage MidiMessage::noteOn (const int channel,
  22419. const int noteNumber,
  22420. const uint8 velocity) throw()
  22421. {
  22422. jassert (channel > 0 && channel <= 16);
  22423. jassert (((unsigned int) noteNumber) <= 127);
  22424. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  22425. noteNumber & 127,
  22426. jlimit (0, 127, roundToInt (velocity)));
  22427. }
  22428. const MidiMessage MidiMessage::noteOff (const int channel,
  22429. const int noteNumber) throw()
  22430. {
  22431. jassert (channel > 0 && channel <= 16);
  22432. jassert (((unsigned int) noteNumber) <= 127);
  22433. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  22434. }
  22435. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  22436. {
  22437. jassert (channel > 0 && channel <= 16);
  22438. return controllerEvent (channel, 123, 0);
  22439. }
  22440. bool MidiMessage::isAllNotesOff() const throw()
  22441. {
  22442. return (data[0] & 0xf0) == 0xb0
  22443. && data[1] == 123;
  22444. }
  22445. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  22446. {
  22447. return controllerEvent (channel, 120, 0);
  22448. }
  22449. bool MidiMessage::isAllSoundOff() const throw()
  22450. {
  22451. return (data[0] & 0xf0) == 0xb0
  22452. && data[1] == 120;
  22453. }
  22454. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  22455. {
  22456. return controllerEvent (channel, 121, 0);
  22457. }
  22458. const MidiMessage MidiMessage::masterVolume (const float volume)
  22459. {
  22460. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  22461. uint8 buf[8];
  22462. buf[0] = 0xf0;
  22463. buf[1] = 0x7f;
  22464. buf[2] = 0x7f;
  22465. buf[3] = 0x04;
  22466. buf[4] = 0x01;
  22467. buf[5] = (uint8) (vol & 0x7f);
  22468. buf[6] = (uint8) (vol >> 7);
  22469. buf[7] = 0xf7;
  22470. return MidiMessage (buf, 8);
  22471. }
  22472. bool MidiMessage::isSysEx() const throw()
  22473. {
  22474. return *data == 0xf0;
  22475. }
  22476. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  22477. {
  22478. MemoryBlock mm (dataSize + 2);
  22479. uint8* const m = static_cast <uint8*> (mm.getData());
  22480. m[0] = 0xf0;
  22481. memcpy (m + 1, sysexData, dataSize);
  22482. m[dataSize + 1] = 0xf7;
  22483. return MidiMessage (m, dataSize + 2);
  22484. }
  22485. const uint8* MidiMessage::getSysExData() const throw()
  22486. {
  22487. return (isSysEx()) ? getRawData() + 1 : 0;
  22488. }
  22489. int MidiMessage::getSysExDataSize() const throw()
  22490. {
  22491. return (isSysEx()) ? size - 2 : 0;
  22492. }
  22493. bool MidiMessage::isMetaEvent() const throw()
  22494. {
  22495. return *data == 0xff;
  22496. }
  22497. bool MidiMessage::isActiveSense() const throw()
  22498. {
  22499. return *data == 0xfe;
  22500. }
  22501. int MidiMessage::getMetaEventType() const throw()
  22502. {
  22503. if (*data != 0xff)
  22504. return -1;
  22505. else
  22506. return data[1];
  22507. }
  22508. int MidiMessage::getMetaEventLength() const throw()
  22509. {
  22510. if (*data == 0xff)
  22511. {
  22512. int n;
  22513. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  22514. }
  22515. return 0;
  22516. }
  22517. const uint8* MidiMessage::getMetaEventData() const throw()
  22518. {
  22519. int n;
  22520. const uint8* d = data + 2;
  22521. readVariableLengthVal (d, n);
  22522. return d + n;
  22523. }
  22524. bool MidiMessage::isTrackMetaEvent() const throw()
  22525. {
  22526. return getMetaEventType() == 0;
  22527. }
  22528. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  22529. {
  22530. return getMetaEventType() == 47;
  22531. }
  22532. bool MidiMessage::isTextMetaEvent() const throw()
  22533. {
  22534. const int t = getMetaEventType();
  22535. return t > 0 && t < 16;
  22536. }
  22537. const String MidiMessage::getTextFromTextMetaEvent() const
  22538. {
  22539. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  22540. }
  22541. bool MidiMessage::isTrackNameEvent() const throw()
  22542. {
  22543. return (data[1] == 3)
  22544. && (*data == 0xff);
  22545. }
  22546. bool MidiMessage::isTempoMetaEvent() const throw()
  22547. {
  22548. return (data[1] == 81)
  22549. && (*data == 0xff);
  22550. }
  22551. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  22552. {
  22553. return (data[1] == 0x20)
  22554. && (*data == 0xff)
  22555. && (data[2] == 1);
  22556. }
  22557. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  22558. {
  22559. return data[3] + 1;
  22560. }
  22561. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  22562. {
  22563. if (! isTempoMetaEvent())
  22564. return 0.0;
  22565. const uint8* const d = getMetaEventData();
  22566. return (((unsigned int) d[0] << 16)
  22567. | ((unsigned int) d[1] << 8)
  22568. | d[2])
  22569. / 1000000.0;
  22570. }
  22571. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  22572. {
  22573. if (timeFormat > 0)
  22574. {
  22575. if (! isTempoMetaEvent())
  22576. return 0.5 / timeFormat;
  22577. return getTempoSecondsPerQuarterNote() / timeFormat;
  22578. }
  22579. else
  22580. {
  22581. const int frameCode = (-timeFormat) >> 8;
  22582. double framesPerSecond;
  22583. switch (frameCode)
  22584. {
  22585. case 24: framesPerSecond = 24.0; break;
  22586. case 25: framesPerSecond = 25.0; break;
  22587. case 29: framesPerSecond = 29.97; break;
  22588. case 30: framesPerSecond = 30.0; break;
  22589. default: framesPerSecond = 30.0; break;
  22590. }
  22591. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  22592. }
  22593. }
  22594. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  22595. {
  22596. uint8 d[8];
  22597. d[0] = 0xff;
  22598. d[1] = 81;
  22599. d[2] = 3;
  22600. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  22601. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  22602. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  22603. return MidiMessage (d, 6, 0.0);
  22604. }
  22605. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  22606. {
  22607. return (data[1] == 0x58)
  22608. && (*data == (uint8) 0xff);
  22609. }
  22610. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  22611. {
  22612. if (isTimeSignatureMetaEvent())
  22613. {
  22614. const uint8* const d = getMetaEventData();
  22615. numerator = d[0];
  22616. denominator = 1 << d[1];
  22617. }
  22618. else
  22619. {
  22620. numerator = 4;
  22621. denominator = 4;
  22622. }
  22623. }
  22624. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  22625. {
  22626. uint8 d[8];
  22627. d[0] = 0xff;
  22628. d[1] = 0x58;
  22629. d[2] = 0x04;
  22630. d[3] = (uint8) numerator;
  22631. int n = 1;
  22632. int powerOfTwo = 0;
  22633. while (n < denominator)
  22634. {
  22635. n <<= 1;
  22636. ++powerOfTwo;
  22637. }
  22638. d[4] = (uint8) powerOfTwo;
  22639. d[5] = 0x01;
  22640. d[6] = 96;
  22641. return MidiMessage (d, 7, 0.0);
  22642. }
  22643. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  22644. {
  22645. uint8 d[8];
  22646. d[0] = 0xff;
  22647. d[1] = 0x20;
  22648. d[2] = 0x01;
  22649. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  22650. return MidiMessage (d, 4, 0.0);
  22651. }
  22652. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  22653. {
  22654. return getMetaEventType() == 89;
  22655. }
  22656. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  22657. {
  22658. return (int) *getMetaEventData();
  22659. }
  22660. const MidiMessage MidiMessage::endOfTrack() throw()
  22661. {
  22662. return MidiMessage (0xff, 0x2f, 0, 0.0);
  22663. }
  22664. bool MidiMessage::isSongPositionPointer() const throw()
  22665. {
  22666. return *data == 0xf2;
  22667. }
  22668. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  22669. {
  22670. return data[1] | (data[2] << 7);
  22671. }
  22672. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  22673. {
  22674. return MidiMessage (0xf2,
  22675. positionInMidiBeats & 127,
  22676. (positionInMidiBeats >> 7) & 127);
  22677. }
  22678. bool MidiMessage::isMidiStart() const throw()
  22679. {
  22680. return *data == 0xfa;
  22681. }
  22682. const MidiMessage MidiMessage::midiStart() throw()
  22683. {
  22684. return MidiMessage (0xfa);
  22685. }
  22686. bool MidiMessage::isMidiContinue() const throw()
  22687. {
  22688. return *data == 0xfb;
  22689. }
  22690. const MidiMessage MidiMessage::midiContinue() throw()
  22691. {
  22692. return MidiMessage (0xfb);
  22693. }
  22694. bool MidiMessage::isMidiStop() const throw()
  22695. {
  22696. return *data == 0xfc;
  22697. }
  22698. const MidiMessage MidiMessage::midiStop() throw()
  22699. {
  22700. return MidiMessage (0xfc);
  22701. }
  22702. bool MidiMessage::isMidiClock() const throw()
  22703. {
  22704. return *data == 0xf8;
  22705. }
  22706. const MidiMessage MidiMessage::midiClock() throw()
  22707. {
  22708. return MidiMessage (0xf8);
  22709. }
  22710. bool MidiMessage::isQuarterFrame() const throw()
  22711. {
  22712. return *data == 0xf1;
  22713. }
  22714. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  22715. {
  22716. return ((int) data[1]) >> 4;
  22717. }
  22718. int MidiMessage::getQuarterFrameValue() const throw()
  22719. {
  22720. return ((int) data[1]) & 0x0f;
  22721. }
  22722. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  22723. const int value) throw()
  22724. {
  22725. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  22726. }
  22727. bool MidiMessage::isFullFrame() const throw()
  22728. {
  22729. return data[0] == 0xf0
  22730. && data[1] == 0x7f
  22731. && size >= 10
  22732. && data[3] == 0x01
  22733. && data[4] == 0x01;
  22734. }
  22735. void MidiMessage::getFullFrameParameters (int& hours,
  22736. int& minutes,
  22737. int& seconds,
  22738. int& frames,
  22739. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  22740. {
  22741. jassert (isFullFrame());
  22742. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  22743. hours = data[5] & 0x1f;
  22744. minutes = data[6];
  22745. seconds = data[7];
  22746. frames = data[8];
  22747. }
  22748. const MidiMessage MidiMessage::fullFrame (const int hours,
  22749. const int minutes,
  22750. const int seconds,
  22751. const int frames,
  22752. MidiMessage::SmpteTimecodeType timecodeType)
  22753. {
  22754. uint8 d[10];
  22755. d[0] = 0xf0;
  22756. d[1] = 0x7f;
  22757. d[2] = 0x7f;
  22758. d[3] = 0x01;
  22759. d[4] = 0x01;
  22760. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  22761. d[6] = (uint8) minutes;
  22762. d[7] = (uint8) seconds;
  22763. d[8] = (uint8) frames;
  22764. d[9] = 0xf7;
  22765. return MidiMessage (d, 10, 0.0);
  22766. }
  22767. bool MidiMessage::isMidiMachineControlMessage() const throw()
  22768. {
  22769. return data[0] == 0xf0
  22770. && data[1] == 0x7f
  22771. && data[3] == 0x06
  22772. && size > 5;
  22773. }
  22774. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  22775. {
  22776. jassert (isMidiMachineControlMessage());
  22777. return (MidiMachineControlCommand) data[4];
  22778. }
  22779. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  22780. {
  22781. uint8 d[6];
  22782. d[0] = 0xf0;
  22783. d[1] = 0x7f;
  22784. d[2] = 0x00;
  22785. d[3] = 0x06;
  22786. d[4] = (uint8) command;
  22787. d[5] = 0xf7;
  22788. return MidiMessage (d, 6, 0.0);
  22789. }
  22790. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  22791. int& minutes,
  22792. int& seconds,
  22793. int& frames) const throw()
  22794. {
  22795. if (size >= 12
  22796. && data[0] == 0xf0
  22797. && data[1] == 0x7f
  22798. && data[3] == 0x06
  22799. && data[4] == 0x44
  22800. && data[5] == 0x06
  22801. && data[6] == 0x01)
  22802. {
  22803. hours = data[7] % 24; // (that some machines send out hours > 24)
  22804. minutes = data[8];
  22805. seconds = data[9];
  22806. frames = data[10];
  22807. return true;
  22808. }
  22809. return false;
  22810. }
  22811. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  22812. int minutes,
  22813. int seconds,
  22814. int frames)
  22815. {
  22816. uint8 d[12];
  22817. d[0] = 0xf0;
  22818. d[1] = 0x7f;
  22819. d[2] = 0x00;
  22820. d[3] = 0x06;
  22821. d[4] = 0x44;
  22822. d[5] = 0x06;
  22823. d[6] = 0x01;
  22824. d[7] = (uint8) hours;
  22825. d[8] = (uint8) minutes;
  22826. d[9] = (uint8) seconds;
  22827. d[10] = (uint8) frames;
  22828. d[11] = 0xf7;
  22829. return MidiMessage (d, 12, 0.0);
  22830. }
  22831. const String MidiMessage::getMidiNoteName (int note,
  22832. bool useSharps,
  22833. bool includeOctaveNumber,
  22834. int octaveNumForMiddleC) throw()
  22835. {
  22836. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E",
  22837. "F", "F#", "G", "G#", "A",
  22838. "A#", "B" };
  22839. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E",
  22840. "F", "Gb", "G", "Ab", "A",
  22841. "Bb", "B" };
  22842. if (((unsigned int) note) < 128)
  22843. {
  22844. const String s ((useSharps) ? sharpNoteNames [note % 12]
  22845. : flatNoteNames [note % 12]);
  22846. if (includeOctaveNumber)
  22847. return s + String (note / 12 + (octaveNumForMiddleC - 5));
  22848. else
  22849. return s;
  22850. }
  22851. return String::empty;
  22852. }
  22853. const double MidiMessage::getMidiNoteInHertz (int noteNumber) throw()
  22854. {
  22855. noteNumber -= 12 * 6 + 9; // now 0 = A440
  22856. return 440.0 * pow (2.0, noteNumber / 12.0);
  22857. }
  22858. const String MidiMessage::getGMInstrumentName (int n) throw()
  22859. {
  22860. const char *names[] =
  22861. {
  22862. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  22863. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  22864. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  22865. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  22866. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  22867. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  22868. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  22869. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  22870. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  22871. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  22872. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  22873. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  22874. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  22875. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  22876. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  22877. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  22878. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  22879. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  22880. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  22881. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  22882. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  22883. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  22884. "Applause", "Gunshot"
  22885. };
  22886. return (((unsigned int) n) < 128) ? names[n]
  22887. : (const char*)0;
  22888. }
  22889. const String MidiMessage::getGMInstrumentBankName (int n) throw()
  22890. {
  22891. const char* names[] =
  22892. {
  22893. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  22894. "Bass", "Strings", "Ensemble", "Brass",
  22895. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  22896. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  22897. };
  22898. return (((unsigned int) n) <= 15) ? names[n]
  22899. : (const char*)0;
  22900. }
  22901. const String MidiMessage::getRhythmInstrumentName (int n) throw()
  22902. {
  22903. const char* names[] =
  22904. {
  22905. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  22906. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  22907. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  22908. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  22909. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  22910. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  22911. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  22912. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  22913. "Mute Triangle", "Open Triangle"
  22914. };
  22915. return (n >= 35 && n <= 81) ? names [n - 35]
  22916. : (const char*)0;
  22917. }
  22918. const String MidiMessage::getControllerName (int n) throw()
  22919. {
  22920. const char* names[] =
  22921. {
  22922. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  22923. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  22924. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  22925. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  22926. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  22927. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  22928. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  22929. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  22930. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  22931. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  22932. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  22933. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  22934. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  22935. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  22936. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  22937. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  22938. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  22939. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  22940. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  22941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  22942. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  22943. "Poly Operation"
  22944. };
  22945. return (((unsigned int) n) < 128) ? names[n]
  22946. : (const char*)0;
  22947. }
  22948. END_JUCE_NAMESPACE
  22949. /*** End of inlined file: juce_MidiMessage.cpp ***/
  22950. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  22951. BEGIN_JUCE_NAMESPACE
  22952. MidiMessageCollector::MidiMessageCollector()
  22953. : lastCallbackTime (0),
  22954. sampleRate (44100.0001)
  22955. {
  22956. }
  22957. MidiMessageCollector::~MidiMessageCollector()
  22958. {
  22959. }
  22960. void MidiMessageCollector::reset (const double sampleRate_)
  22961. {
  22962. jassert (sampleRate_ > 0);
  22963. const ScopedLock sl (midiCallbackLock);
  22964. sampleRate = sampleRate_;
  22965. incomingMessages.clear();
  22966. lastCallbackTime = Time::getMillisecondCounterHiRes();
  22967. }
  22968. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  22969. {
  22970. // you need to call reset() to set the correct sample rate before using this object
  22971. jassert (sampleRate != 44100.0001);
  22972. // the messages that come in here need to be time-stamped correctly - see MidiInput
  22973. // for details of what the number should be.
  22974. jassert (message.getTimeStamp() != 0);
  22975. const ScopedLock sl (midiCallbackLock);
  22976. const int sampleNumber
  22977. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  22978. incomingMessages.addEvent (message, sampleNumber);
  22979. // if the messages don't get used for over a second, we'd better
  22980. // get rid of any old ones to avoid the queue getting too big
  22981. if (sampleNumber > sampleRate)
  22982. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  22983. }
  22984. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  22985. const int numSamples)
  22986. {
  22987. // you need to call reset() to set the correct sample rate before using this object
  22988. jassert (sampleRate != 44100.0001);
  22989. const double timeNow = Time::getMillisecondCounterHiRes();
  22990. const double msElapsed = timeNow - lastCallbackTime;
  22991. const ScopedLock sl (midiCallbackLock);
  22992. lastCallbackTime = timeNow;
  22993. if (! incomingMessages.isEmpty())
  22994. {
  22995. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  22996. int startSample = 0;
  22997. int scale = 1 << 16;
  22998. const uint8* midiData;
  22999. int numBytes, samplePosition;
  23000. MidiBuffer::Iterator iter (incomingMessages);
  23001. if (numSourceSamples > numSamples)
  23002. {
  23003. // if our list of events is longer than the buffer we're being
  23004. // asked for, scale them down to squeeze them all in..
  23005. const int maxBlockLengthToUse = numSamples << 5;
  23006. if (numSourceSamples > maxBlockLengthToUse)
  23007. {
  23008. startSample = numSourceSamples - maxBlockLengthToUse;
  23009. numSourceSamples = maxBlockLengthToUse;
  23010. iter.setNextSamplePosition (startSample);
  23011. }
  23012. scale = (numSamples << 10) / numSourceSamples;
  23013. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23014. {
  23015. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  23016. destBuffer.addEvent (midiData, numBytes,
  23017. jlimit (0, numSamples - 1, samplePosition));
  23018. }
  23019. }
  23020. else
  23021. {
  23022. // if our event list is shorter than the number we need, put them
  23023. // towards the end of the buffer
  23024. startSample = numSamples - numSourceSamples;
  23025. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23026. {
  23027. destBuffer.addEvent (midiData, numBytes,
  23028. jlimit (0, numSamples - 1, samplePosition + startSample));
  23029. }
  23030. }
  23031. incomingMessages.clear();
  23032. }
  23033. }
  23034. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  23035. {
  23036. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  23037. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23038. addMessageToQueue (m);
  23039. }
  23040. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  23041. {
  23042. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  23043. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23044. addMessageToQueue (m);
  23045. }
  23046. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  23047. {
  23048. addMessageToQueue (message);
  23049. }
  23050. END_JUCE_NAMESPACE
  23051. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  23052. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  23053. BEGIN_JUCE_NAMESPACE
  23054. MidiMessageSequence::MidiMessageSequence()
  23055. {
  23056. }
  23057. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  23058. {
  23059. list.ensureStorageAllocated (other.list.size());
  23060. for (int i = 0; i < other.list.size(); ++i)
  23061. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  23062. }
  23063. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  23064. {
  23065. MidiMessageSequence otherCopy (other);
  23066. swapWith (otherCopy);
  23067. return *this;
  23068. }
  23069. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  23070. {
  23071. list.swapWithArray (other.list);
  23072. }
  23073. MidiMessageSequence::~MidiMessageSequence()
  23074. {
  23075. }
  23076. void MidiMessageSequence::clear()
  23077. {
  23078. list.clear();
  23079. }
  23080. int MidiMessageSequence::getNumEvents() const
  23081. {
  23082. return list.size();
  23083. }
  23084. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  23085. {
  23086. return list [index];
  23087. }
  23088. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  23089. {
  23090. const MidiEventHolder* const meh = list [index];
  23091. if (meh != 0 && meh->noteOffObject != 0)
  23092. return meh->noteOffObject->message.getTimeStamp();
  23093. else
  23094. return 0.0;
  23095. }
  23096. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  23097. {
  23098. const MidiEventHolder* const meh = list [index];
  23099. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  23100. }
  23101. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  23102. {
  23103. return list.indexOf (event);
  23104. }
  23105. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  23106. {
  23107. const int numEvents = list.size();
  23108. int i;
  23109. for (i = 0; i < numEvents; ++i)
  23110. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  23111. break;
  23112. return i;
  23113. }
  23114. double MidiMessageSequence::getStartTime() const
  23115. {
  23116. if (list.size() > 0)
  23117. return list.getUnchecked(0)->message.getTimeStamp();
  23118. else
  23119. return 0;
  23120. }
  23121. double MidiMessageSequence::getEndTime() const
  23122. {
  23123. if (list.size() > 0)
  23124. return list.getLast()->message.getTimeStamp();
  23125. else
  23126. return 0;
  23127. }
  23128. double MidiMessageSequence::getEventTime (const int index) const
  23129. {
  23130. if (((unsigned int) index) < (unsigned int) list.size())
  23131. return list.getUnchecked (index)->message.getTimeStamp();
  23132. return 0.0;
  23133. }
  23134. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  23135. double timeAdjustment)
  23136. {
  23137. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  23138. timeAdjustment += newMessage.getTimeStamp();
  23139. newOne->message.setTimeStamp (timeAdjustment);
  23140. int i;
  23141. for (i = list.size(); --i >= 0;)
  23142. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  23143. break;
  23144. list.insert (i + 1, newOne);
  23145. }
  23146. void MidiMessageSequence::deleteEvent (const int index,
  23147. const bool deleteMatchingNoteUp)
  23148. {
  23149. if (((unsigned int) index) < (unsigned int) list.size())
  23150. {
  23151. if (deleteMatchingNoteUp)
  23152. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  23153. list.remove (index);
  23154. }
  23155. }
  23156. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  23157. double timeAdjustment,
  23158. double firstAllowableTime,
  23159. double endOfAllowableDestTimes)
  23160. {
  23161. firstAllowableTime -= timeAdjustment;
  23162. endOfAllowableDestTimes -= timeAdjustment;
  23163. for (int i = 0; i < other.list.size(); ++i)
  23164. {
  23165. const MidiMessage& m = other.list.getUnchecked(i)->message;
  23166. const double t = m.getTimeStamp();
  23167. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  23168. {
  23169. MidiEventHolder* const newOne = new MidiEventHolder (m);
  23170. newOne->message.setTimeStamp (timeAdjustment + t);
  23171. list.add (newOne);
  23172. }
  23173. }
  23174. sort();
  23175. }
  23176. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  23177. const MidiMessageSequence::MidiEventHolder* const second) throw()
  23178. {
  23179. const double diff = first->message.getTimeStamp()
  23180. - second->message.getTimeStamp();
  23181. return (diff > 0) - (diff < 0);
  23182. }
  23183. void MidiMessageSequence::sort()
  23184. {
  23185. list.sort (*this, true);
  23186. }
  23187. void MidiMessageSequence::updateMatchedPairs()
  23188. {
  23189. for (int i = 0; i < list.size(); ++i)
  23190. {
  23191. const MidiMessage& m1 = list.getUnchecked(i)->message;
  23192. if (m1.isNoteOn())
  23193. {
  23194. list.getUnchecked(i)->noteOffObject = 0;
  23195. const int note = m1.getNoteNumber();
  23196. const int chan = m1.getChannel();
  23197. const int len = list.size();
  23198. for (int j = i + 1; j < len; ++j)
  23199. {
  23200. const MidiMessage& m = list.getUnchecked(j)->message;
  23201. if (m.getNoteNumber() == note && m.getChannel() == chan)
  23202. {
  23203. if (m.isNoteOff())
  23204. {
  23205. list.getUnchecked(i)->noteOffObject = list[j];
  23206. break;
  23207. }
  23208. else if (m.isNoteOn())
  23209. {
  23210. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  23211. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  23212. list.getUnchecked(i)->noteOffObject = list[j];
  23213. break;
  23214. }
  23215. }
  23216. }
  23217. }
  23218. }
  23219. }
  23220. void MidiMessageSequence::addTimeToMessages (const double delta)
  23221. {
  23222. for (int i = list.size(); --i >= 0;)
  23223. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  23224. + delta);
  23225. }
  23226. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  23227. MidiMessageSequence& destSequence,
  23228. const bool alsoIncludeMetaEvents) const
  23229. {
  23230. for (int i = 0; i < list.size(); ++i)
  23231. {
  23232. const MidiMessage& mm = list.getUnchecked(i)->message;
  23233. if (mm.isForChannel (channelNumberToExtract)
  23234. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  23235. {
  23236. destSequence.addEvent (mm);
  23237. }
  23238. }
  23239. }
  23240. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  23241. {
  23242. for (int i = 0; i < list.size(); ++i)
  23243. {
  23244. const MidiMessage& mm = list.getUnchecked(i)->message;
  23245. if (mm.isSysEx())
  23246. destSequence.addEvent (mm);
  23247. }
  23248. }
  23249. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  23250. {
  23251. for (int i = list.size(); --i >= 0;)
  23252. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  23253. list.remove(i);
  23254. }
  23255. void MidiMessageSequence::deleteSysExMessages()
  23256. {
  23257. for (int i = list.size(); --i >= 0;)
  23258. if (list.getUnchecked(i)->message.isSysEx())
  23259. list.remove(i);
  23260. }
  23261. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  23262. const double time,
  23263. OwnedArray<MidiMessage>& dest)
  23264. {
  23265. bool doneProg = false;
  23266. bool donePitchWheel = false;
  23267. Array <int> doneControllers;
  23268. doneControllers.ensureStorageAllocated (32);
  23269. for (int i = list.size(); --i >= 0;)
  23270. {
  23271. const MidiMessage& mm = list.getUnchecked(i)->message;
  23272. if (mm.isForChannel (channelNumber)
  23273. && mm.getTimeStamp() <= time)
  23274. {
  23275. if (mm.isProgramChange())
  23276. {
  23277. if (! doneProg)
  23278. {
  23279. dest.add (new MidiMessage (mm, 0.0));
  23280. doneProg = true;
  23281. }
  23282. }
  23283. else if (mm.isController())
  23284. {
  23285. if (! doneControllers.contains (mm.getControllerNumber()))
  23286. {
  23287. dest.add (new MidiMessage (mm, 0.0));
  23288. doneControllers.add (mm.getControllerNumber());
  23289. }
  23290. }
  23291. else if (mm.isPitchWheel())
  23292. {
  23293. if (! donePitchWheel)
  23294. {
  23295. dest.add (new MidiMessage (mm, 0.0));
  23296. donePitchWheel = true;
  23297. }
  23298. }
  23299. }
  23300. }
  23301. }
  23302. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  23303. : message (message_),
  23304. noteOffObject (0)
  23305. {
  23306. }
  23307. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  23308. {
  23309. }
  23310. END_JUCE_NAMESPACE
  23311. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  23312. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  23313. BEGIN_JUCE_NAMESPACE
  23314. AudioPluginFormat::AudioPluginFormat() throw()
  23315. {
  23316. }
  23317. AudioPluginFormat::~AudioPluginFormat()
  23318. {
  23319. }
  23320. END_JUCE_NAMESPACE
  23321. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  23322. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  23323. BEGIN_JUCE_NAMESPACE
  23324. AudioPluginFormatManager::AudioPluginFormatManager() throw()
  23325. {
  23326. }
  23327. AudioPluginFormatManager::~AudioPluginFormatManager() throw()
  23328. {
  23329. clearSingletonInstance();
  23330. }
  23331. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  23332. void AudioPluginFormatManager::addDefaultFormats()
  23333. {
  23334. #if JUCE_DEBUG
  23335. // you should only call this method once!
  23336. for (int i = formats.size(); --i >= 0;)
  23337. {
  23338. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  23339. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  23340. #endif
  23341. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  23342. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  23343. #endif
  23344. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  23345. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  23346. #endif
  23347. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  23348. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  23349. #endif
  23350. }
  23351. #endif
  23352. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  23353. formats.add (new AudioUnitPluginFormat());
  23354. #endif
  23355. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  23356. formats.add (new VSTPluginFormat());
  23357. #endif
  23358. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  23359. formats.add (new DirectXPluginFormat());
  23360. #endif
  23361. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  23362. formats.add (new LADSPAPluginFormat());
  23363. #endif
  23364. }
  23365. int AudioPluginFormatManager::getNumFormats() throw()
  23366. {
  23367. return formats.size();
  23368. }
  23369. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index) throw()
  23370. {
  23371. return formats [index];
  23372. }
  23373. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format) throw()
  23374. {
  23375. formats.add (format);
  23376. }
  23377. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  23378. String& errorMessage) const
  23379. {
  23380. AudioPluginInstance* result = 0;
  23381. for (int i = 0; i < formats.size(); ++i)
  23382. {
  23383. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  23384. if (result != 0)
  23385. break;
  23386. }
  23387. if (result == 0)
  23388. {
  23389. if (! doesPluginStillExist (description))
  23390. errorMessage = TRANS ("This plug-in file no longer exists");
  23391. else
  23392. errorMessage = TRANS ("This plug-in failed to load correctly");
  23393. }
  23394. return result;
  23395. }
  23396. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  23397. {
  23398. for (int i = 0; i < formats.size(); ++i)
  23399. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  23400. return formats.getUnchecked(i)->doesPluginStillExist (description);
  23401. return false;
  23402. }
  23403. END_JUCE_NAMESPACE
  23404. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  23405. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  23406. #define JUCE_PLUGIN_HOST 1
  23407. BEGIN_JUCE_NAMESPACE
  23408. AudioPluginInstance::AudioPluginInstance()
  23409. {
  23410. }
  23411. AudioPluginInstance::~AudioPluginInstance()
  23412. {
  23413. }
  23414. END_JUCE_NAMESPACE
  23415. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  23416. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  23417. BEGIN_JUCE_NAMESPACE
  23418. KnownPluginList::KnownPluginList()
  23419. {
  23420. }
  23421. KnownPluginList::~KnownPluginList()
  23422. {
  23423. }
  23424. void KnownPluginList::clear()
  23425. {
  23426. if (types.size() > 0)
  23427. {
  23428. types.clear();
  23429. sendChangeMessage (this);
  23430. }
  23431. }
  23432. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const throw()
  23433. {
  23434. for (int i = 0; i < types.size(); ++i)
  23435. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  23436. return types.getUnchecked(i);
  23437. return 0;
  23438. }
  23439. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const throw()
  23440. {
  23441. for (int i = 0; i < types.size(); ++i)
  23442. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  23443. return types.getUnchecked(i);
  23444. return 0;
  23445. }
  23446. bool KnownPluginList::addType (const PluginDescription& type)
  23447. {
  23448. for (int i = types.size(); --i >= 0;)
  23449. {
  23450. if (types.getUnchecked(i)->isDuplicateOf (type))
  23451. {
  23452. // strange - found a duplicate plugin with different info..
  23453. jassert (types.getUnchecked(i)->name == type.name);
  23454. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  23455. *types.getUnchecked(i) = type;
  23456. return false;
  23457. }
  23458. }
  23459. types.add (new PluginDescription (type));
  23460. sendChangeMessage (this);
  23461. return true;
  23462. }
  23463. void KnownPluginList::removeType (const int index) throw()
  23464. {
  23465. types.remove (index);
  23466. sendChangeMessage (this);
  23467. }
  23468. static Time getFileModTime (const String& fileOrIdentifier) throw()
  23469. {
  23470. if (fileOrIdentifier.startsWithChar ('/')
  23471. || fileOrIdentifier[1] == ':')
  23472. {
  23473. return File (fileOrIdentifier).getLastModificationTime();
  23474. }
  23475. return Time (0);
  23476. }
  23477. static bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  23478. {
  23479. return t1 != t2 || t1 == Time (0);
  23480. }
  23481. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const throw()
  23482. {
  23483. if (getTypeForFile (fileOrIdentifier) == 0)
  23484. return false;
  23485. for (int i = types.size(); --i >= 0;)
  23486. {
  23487. const PluginDescription* const d = types.getUnchecked(i);
  23488. if (d->fileOrIdentifier == fileOrIdentifier
  23489. && timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  23490. {
  23491. return false;
  23492. }
  23493. }
  23494. return true;
  23495. }
  23496. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  23497. const bool dontRescanIfAlreadyInList,
  23498. OwnedArray <PluginDescription>& typesFound,
  23499. AudioPluginFormat& format)
  23500. {
  23501. bool addedOne = false;
  23502. if (dontRescanIfAlreadyInList
  23503. && getTypeForFile (fileOrIdentifier) != 0)
  23504. {
  23505. bool needsRescanning = false;
  23506. for (int i = types.size(); --i >= 0;)
  23507. {
  23508. const PluginDescription* const d = types.getUnchecked(i);
  23509. if (d->fileOrIdentifier == fileOrIdentifier)
  23510. {
  23511. if (timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  23512. needsRescanning = true;
  23513. else
  23514. typesFound.add (new PluginDescription (*d));
  23515. }
  23516. }
  23517. if (! needsRescanning)
  23518. return false;
  23519. }
  23520. OwnedArray <PluginDescription> found;
  23521. format.findAllTypesForFile (found, fileOrIdentifier);
  23522. for (int i = 0; i < found.size(); ++i)
  23523. {
  23524. PluginDescription* const desc = found.getUnchecked(i);
  23525. jassert (desc != 0);
  23526. if (addType (*desc))
  23527. addedOne = true;
  23528. typesFound.add (new PluginDescription (*desc));
  23529. }
  23530. return addedOne;
  23531. }
  23532. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  23533. OwnedArray <PluginDescription>& typesFound)
  23534. {
  23535. for (int i = 0; i < files.size(); ++i)
  23536. {
  23537. bool loaded = false;
  23538. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  23539. {
  23540. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  23541. if (scanAndAddFile (files[i], true, typesFound, *format))
  23542. loaded = true;
  23543. }
  23544. if (! loaded)
  23545. {
  23546. const File f (files[i]);
  23547. if (f.isDirectory())
  23548. {
  23549. StringArray s;
  23550. {
  23551. Array<File> subFiles;
  23552. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  23553. for (int j = 0; j < subFiles.size(); ++j)
  23554. s.add (subFiles.getReference(j).getFullPathName());
  23555. }
  23556. scanAndAddDragAndDroppedFiles (s, typesFound);
  23557. }
  23558. }
  23559. }
  23560. }
  23561. class PluginSorter
  23562. {
  23563. public:
  23564. KnownPluginList::SortMethod method;
  23565. PluginSorter() throw() {}
  23566. int compareElements (const PluginDescription* const first,
  23567. const PluginDescription* const second) const throw()
  23568. {
  23569. int diff = 0;
  23570. if (method == KnownPluginList::sortByCategory)
  23571. diff = first->category.compareLexicographically (second->category);
  23572. else if (method == KnownPluginList::sortByManufacturer)
  23573. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  23574. else if (method == KnownPluginList::sortByFileSystemLocation)
  23575. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  23576. .upToLastOccurrenceOf ("/", false, false)
  23577. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  23578. .upToLastOccurrenceOf ("/", false, false));
  23579. if (diff == 0)
  23580. diff = first->name.compareLexicographically (second->name);
  23581. return diff;
  23582. }
  23583. };
  23584. void KnownPluginList::sort (const SortMethod method)
  23585. {
  23586. if (method != defaultOrder)
  23587. {
  23588. PluginSorter sorter;
  23589. sorter.method = method;
  23590. types.sort (sorter, true);
  23591. sendChangeMessage (this);
  23592. }
  23593. }
  23594. XmlElement* KnownPluginList::createXml() const
  23595. {
  23596. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  23597. for (int i = 0; i < types.size(); ++i)
  23598. e->addChildElement (types.getUnchecked(i)->createXml());
  23599. return e;
  23600. }
  23601. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  23602. {
  23603. clear();
  23604. if (xml.hasTagName ("KNOWNPLUGINS"))
  23605. {
  23606. forEachXmlChildElement (xml, e)
  23607. {
  23608. PluginDescription info;
  23609. if (info.loadFromXml (*e))
  23610. addType (info);
  23611. }
  23612. }
  23613. }
  23614. const int menuIdBase = 0x324503f4;
  23615. // This is used to turn a bunch of paths into a nested menu structure.
  23616. struct PluginFilesystemTree
  23617. {
  23618. private:
  23619. String folder;
  23620. OwnedArray <PluginFilesystemTree> subFolders;
  23621. Array <PluginDescription*> plugins;
  23622. void addPlugin (PluginDescription* const pd, const String& path)
  23623. {
  23624. if (path.isEmpty())
  23625. {
  23626. plugins.add (pd);
  23627. }
  23628. else
  23629. {
  23630. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  23631. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  23632. for (int i = subFolders.size(); --i >= 0;)
  23633. {
  23634. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  23635. {
  23636. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  23637. return;
  23638. }
  23639. }
  23640. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  23641. newFolder->folder = firstSubFolder;
  23642. subFolders.add (newFolder);
  23643. newFolder->addPlugin (pd, remainingPath);
  23644. }
  23645. }
  23646. // removes any deeply nested folders that don't contain any actual plugins
  23647. void optimise()
  23648. {
  23649. for (int i = subFolders.size(); --i >= 0;)
  23650. {
  23651. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  23652. sub->optimise();
  23653. if (sub->plugins.size() == 0)
  23654. {
  23655. for (int j = 0; j < sub->subFolders.size(); ++j)
  23656. subFolders.add (sub->subFolders.getUnchecked(j));
  23657. sub->subFolders.clear (false);
  23658. subFolders.remove (i);
  23659. }
  23660. }
  23661. }
  23662. public:
  23663. void buildTree (const Array <PluginDescription*>& allPlugins)
  23664. {
  23665. for (int i = 0; i < allPlugins.size(); ++i)
  23666. {
  23667. String path (allPlugins.getUnchecked(i)
  23668. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  23669. .upToLastOccurrenceOf ("/", false, false));
  23670. if (path.substring (1, 2) == ":")
  23671. path = path.substring (2);
  23672. addPlugin (allPlugins.getUnchecked(i), path);
  23673. }
  23674. optimise();
  23675. }
  23676. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  23677. {
  23678. int i;
  23679. for (i = 0; i < subFolders.size(); ++i)
  23680. {
  23681. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  23682. PopupMenu subMenu;
  23683. sub->addToMenu (subMenu, allPlugins);
  23684. #if JUCE_MAC
  23685. // avoid the special AU formatting nonsense on Mac..
  23686. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  23687. #else
  23688. m.addSubMenu (sub->folder, subMenu);
  23689. #endif
  23690. }
  23691. for (i = 0; i < plugins.size(); ++i)
  23692. {
  23693. PluginDescription* const plugin = plugins.getUnchecked(i);
  23694. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  23695. plugin->name, true, false);
  23696. }
  23697. }
  23698. };
  23699. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  23700. {
  23701. Array <PluginDescription*> sorted;
  23702. {
  23703. PluginSorter sorter;
  23704. sorter.method = sortMethod;
  23705. for (int i = 0; i < types.size(); ++i)
  23706. sorted.addSorted (sorter, types.getUnchecked(i));
  23707. }
  23708. if (sortMethod == sortByCategory
  23709. || sortMethod == sortByManufacturer)
  23710. {
  23711. String lastSubMenuName;
  23712. PopupMenu sub;
  23713. for (int i = 0; i < sorted.size(); ++i)
  23714. {
  23715. const PluginDescription* const pd = sorted.getUnchecked(i);
  23716. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  23717. : pd->manufacturerName);
  23718. if (! thisSubMenuName.containsNonWhitespaceChars())
  23719. thisSubMenuName = "Other";
  23720. if (thisSubMenuName != lastSubMenuName)
  23721. {
  23722. if (sub.getNumItems() > 0)
  23723. {
  23724. menu.addSubMenu (lastSubMenuName, sub);
  23725. sub.clear();
  23726. }
  23727. lastSubMenuName = thisSubMenuName;
  23728. }
  23729. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23730. }
  23731. if (sub.getNumItems() > 0)
  23732. menu.addSubMenu (lastSubMenuName, sub);
  23733. }
  23734. else if (sortMethod == sortByFileSystemLocation)
  23735. {
  23736. PluginFilesystemTree root;
  23737. root.buildTree (sorted);
  23738. root.addToMenu (menu, types);
  23739. }
  23740. else
  23741. {
  23742. for (int i = 0; i < sorted.size(); ++i)
  23743. {
  23744. const PluginDescription* const pd = sorted.getUnchecked(i);
  23745. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23746. }
  23747. }
  23748. }
  23749. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  23750. {
  23751. const int i = menuResultCode - menuIdBase;
  23752. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  23753. }
  23754. END_JUCE_NAMESPACE
  23755. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  23756. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  23757. BEGIN_JUCE_NAMESPACE
  23758. PluginDescription::PluginDescription() throw()
  23759. : uid (0),
  23760. isInstrument (false),
  23761. numInputChannels (0),
  23762. numOutputChannels (0)
  23763. {
  23764. }
  23765. PluginDescription::~PluginDescription() throw()
  23766. {
  23767. }
  23768. PluginDescription::PluginDescription (const PluginDescription& other) throw()
  23769. : name (other.name),
  23770. pluginFormatName (other.pluginFormatName),
  23771. category (other.category),
  23772. manufacturerName (other.manufacturerName),
  23773. version (other.version),
  23774. fileOrIdentifier (other.fileOrIdentifier),
  23775. lastFileModTime (other.lastFileModTime),
  23776. uid (other.uid),
  23777. isInstrument (other.isInstrument),
  23778. numInputChannels (other.numInputChannels),
  23779. numOutputChannels (other.numOutputChannels)
  23780. {
  23781. }
  23782. PluginDescription& PluginDescription::operator= (const PluginDescription& other) throw()
  23783. {
  23784. name = other.name;
  23785. pluginFormatName = other.pluginFormatName;
  23786. category = other.category;
  23787. manufacturerName = other.manufacturerName;
  23788. version = other.version;
  23789. fileOrIdentifier = other.fileOrIdentifier;
  23790. uid = other.uid;
  23791. isInstrument = other.isInstrument;
  23792. lastFileModTime = other.lastFileModTime;
  23793. numInputChannels = other.numInputChannels;
  23794. numOutputChannels = other.numOutputChannels;
  23795. return *this;
  23796. }
  23797. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  23798. {
  23799. return fileOrIdentifier == other.fileOrIdentifier
  23800. && uid == other.uid;
  23801. }
  23802. const String PluginDescription::createIdentifierString() const throw()
  23803. {
  23804. return pluginFormatName
  23805. + "-" + name
  23806. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  23807. + "-" + String::toHexString (uid);
  23808. }
  23809. XmlElement* PluginDescription::createXml() const
  23810. {
  23811. XmlElement* const e = new XmlElement ("PLUGIN");
  23812. e->setAttribute ("name", name);
  23813. e->setAttribute ("format", pluginFormatName);
  23814. e->setAttribute ("category", category);
  23815. e->setAttribute ("manufacturer", manufacturerName);
  23816. e->setAttribute ("version", version);
  23817. e->setAttribute ("file", fileOrIdentifier);
  23818. e->setAttribute ("uid", String::toHexString (uid));
  23819. e->setAttribute ("isInstrument", isInstrument);
  23820. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  23821. e->setAttribute ("numInputs", numInputChannels);
  23822. e->setAttribute ("numOutputs", numOutputChannels);
  23823. return e;
  23824. }
  23825. bool PluginDescription::loadFromXml (const XmlElement& xml)
  23826. {
  23827. if (xml.hasTagName ("PLUGIN"))
  23828. {
  23829. name = xml.getStringAttribute ("name");
  23830. pluginFormatName = xml.getStringAttribute ("format");
  23831. category = xml.getStringAttribute ("category");
  23832. manufacturerName = xml.getStringAttribute ("manufacturer");
  23833. version = xml.getStringAttribute ("version");
  23834. fileOrIdentifier = xml.getStringAttribute ("file");
  23835. uid = xml.getStringAttribute ("uid").getHexValue32();
  23836. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  23837. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  23838. numInputChannels = xml.getIntAttribute ("numInputs");
  23839. numOutputChannels = xml.getIntAttribute ("numOutputs");
  23840. return true;
  23841. }
  23842. return false;
  23843. }
  23844. END_JUCE_NAMESPACE
  23845. /*** End of inlined file: juce_PluginDescription.cpp ***/
  23846. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  23847. BEGIN_JUCE_NAMESPACE
  23848. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  23849. AudioPluginFormat& formatToLookFor,
  23850. FileSearchPath directoriesToSearch,
  23851. const bool recursive,
  23852. const File& deadMansPedalFile_)
  23853. : list (listToAddTo),
  23854. format (formatToLookFor),
  23855. deadMansPedalFile (deadMansPedalFile_),
  23856. nextIndex (0),
  23857. progress (0)
  23858. {
  23859. directoriesToSearch.removeRedundantPaths();
  23860. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  23861. // If any plugins have crashed recently when being loaded, move them to the
  23862. // end of the list to give the others a chance to load correctly..
  23863. const StringArray crashedPlugins (getDeadMansPedalFile());
  23864. for (int i = 0; i < crashedPlugins.size(); ++i)
  23865. {
  23866. const String f = crashedPlugins[i];
  23867. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  23868. if (f == filesOrIdentifiersToScan[j])
  23869. filesOrIdentifiersToScan.move (j, -1);
  23870. }
  23871. }
  23872. PluginDirectoryScanner::~PluginDirectoryScanner()
  23873. {
  23874. }
  23875. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const throw()
  23876. {
  23877. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  23878. }
  23879. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  23880. {
  23881. String file (filesOrIdentifiersToScan [nextIndex]);
  23882. if (file.isNotEmpty())
  23883. {
  23884. if (! list.isListingUpToDate (file))
  23885. {
  23886. OwnedArray <PluginDescription> typesFound;
  23887. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  23888. StringArray crashedPlugins (getDeadMansPedalFile());
  23889. crashedPlugins.removeString (file);
  23890. crashedPlugins.add (file);
  23891. setDeadMansPedalFile (crashedPlugins);
  23892. list.scanAndAddFile (file,
  23893. dontRescanIfAlreadyInList,
  23894. typesFound,
  23895. format);
  23896. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  23897. crashedPlugins.removeString (file);
  23898. setDeadMansPedalFile (crashedPlugins);
  23899. if (typesFound.size() == 0)
  23900. failedFiles.add (file);
  23901. }
  23902. ++nextIndex;
  23903. progress = nextIndex / (float) filesOrIdentifiersToScan.size();
  23904. }
  23905. return nextIndex < filesOrIdentifiersToScan.size();
  23906. }
  23907. const StringArray PluginDirectoryScanner::getDeadMansPedalFile() throw()
  23908. {
  23909. StringArray lines;
  23910. if (deadMansPedalFile != File::nonexistent)
  23911. {
  23912. lines.addLines (deadMansPedalFile.loadFileAsString());
  23913. lines.removeEmptyStrings();
  23914. }
  23915. return lines;
  23916. }
  23917. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents) throw()
  23918. {
  23919. if (deadMansPedalFile != File::nonexistent)
  23920. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  23921. }
  23922. END_JUCE_NAMESPACE
  23923. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  23924. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  23925. BEGIN_JUCE_NAMESPACE
  23926. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  23927. const File& deadMansPedalFile_,
  23928. PropertiesFile* const propertiesToUse_)
  23929. : list (listToEdit),
  23930. deadMansPedalFile (deadMansPedalFile_),
  23931. propertiesToUse (propertiesToUse_)
  23932. {
  23933. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  23934. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  23935. optionsButton->addButtonListener (this);
  23936. optionsButton->setTriggeredOnMouseDown (true);
  23937. setSize (400, 600);
  23938. list.addChangeListener (this);
  23939. }
  23940. PluginListComponent::~PluginListComponent()
  23941. {
  23942. list.removeChangeListener (this);
  23943. deleteAllChildren();
  23944. }
  23945. void PluginListComponent::resized()
  23946. {
  23947. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  23948. optionsButton->changeWidthToFitText (24);
  23949. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  23950. }
  23951. void PluginListComponent::changeListenerCallback (void*)
  23952. {
  23953. listBox->updateContent();
  23954. listBox->repaint();
  23955. }
  23956. int PluginListComponent::getNumRows()
  23957. {
  23958. return list.getNumTypes();
  23959. }
  23960. void PluginListComponent::paintListBoxItem (int row,
  23961. Graphics& g,
  23962. int width, int height,
  23963. bool rowIsSelected)
  23964. {
  23965. if (rowIsSelected)
  23966. g.fillAll (findColour (TextEditor::highlightColourId));
  23967. const PluginDescription* const pd = list.getType (row);
  23968. if (pd != 0)
  23969. {
  23970. GlyphArrangement ga;
  23971. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  23972. g.setColour (Colours::black);
  23973. ga.draw (g);
  23974. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  23975. String desc;
  23976. desc << pd->pluginFormatName
  23977. << (pd->isInstrument ? " instrument" : " effect")
  23978. << " - "
  23979. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  23980. << " / "
  23981. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  23982. if (pd->manufacturerName.isNotEmpty())
  23983. desc << " - " << pd->manufacturerName;
  23984. if (pd->version.isNotEmpty())
  23985. desc << " - " << pd->version;
  23986. if (pd->category.isNotEmpty())
  23987. desc << " - category: '" << pd->category << '\'';
  23988. g.setColour (Colours::grey);
  23989. ga.clear();
  23990. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  23991. ga.draw (g);
  23992. }
  23993. }
  23994. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  23995. {
  23996. list.removeType (lastRowSelected);
  23997. }
  23998. void PluginListComponent::buttonClicked (Button* b)
  23999. {
  24000. if (optionsButton == b)
  24001. {
  24002. PopupMenu menu;
  24003. menu.addItem (1, TRANS("Clear list"));
  24004. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  24005. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  24006. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  24007. menu.addSeparator();
  24008. menu.addItem (2, TRANS("Sort alphabetically"));
  24009. menu.addItem (3, TRANS("Sort by category"));
  24010. menu.addItem (4, TRANS("Sort by manufacturer"));
  24011. menu.addSeparator();
  24012. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  24013. {
  24014. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  24015. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  24016. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  24017. }
  24018. const int r = menu.showAt (optionsButton);
  24019. if (r == 1)
  24020. {
  24021. list.clear();
  24022. }
  24023. else if (r == 2)
  24024. {
  24025. list.sort (KnownPluginList::sortAlphabetically);
  24026. }
  24027. else if (r == 3)
  24028. {
  24029. list.sort (KnownPluginList::sortByCategory);
  24030. }
  24031. else if (r == 4)
  24032. {
  24033. list.sort (KnownPluginList::sortByManufacturer);
  24034. }
  24035. else if (r == 5)
  24036. {
  24037. const SparseSet <int> selected (listBox->getSelectedRows());
  24038. for (int i = list.getNumTypes(); --i >= 0;)
  24039. if (selected.contains (i))
  24040. list.removeType (i);
  24041. }
  24042. else if (r == 6)
  24043. {
  24044. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  24045. if (desc != 0)
  24046. {
  24047. if (File (desc->fileOrIdentifier).existsAsFile())
  24048. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  24049. }
  24050. }
  24051. else if (r == 7)
  24052. {
  24053. for (int i = list.getNumTypes(); --i >= 0;)
  24054. {
  24055. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  24056. {
  24057. list.removeType (i);
  24058. }
  24059. }
  24060. }
  24061. else if (r != 0)
  24062. {
  24063. typeToScan = r - 10;
  24064. startTimer (1);
  24065. }
  24066. }
  24067. }
  24068. void PluginListComponent::timerCallback()
  24069. {
  24070. stopTimer();
  24071. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  24072. }
  24073. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  24074. {
  24075. return true;
  24076. }
  24077. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  24078. {
  24079. OwnedArray <PluginDescription> typesFound;
  24080. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  24081. }
  24082. void PluginListComponent::scanFor (AudioPluginFormat* format)
  24083. {
  24084. if (format == 0)
  24085. return;
  24086. FileSearchPath path (format->getDefaultLocationsToSearch());
  24087. if (propertiesToUse != 0)
  24088. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24089. {
  24090. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  24091. FileSearchPathListComponent pathList;
  24092. pathList.setSize (500, 300);
  24093. pathList.setPath (path);
  24094. aw.addCustomComponent (&pathList);
  24095. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  24096. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24097. if (aw.runModalLoop() == 0)
  24098. return;
  24099. path = pathList.getPath();
  24100. }
  24101. if (propertiesToUse != 0)
  24102. {
  24103. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24104. propertiesToUse->saveIfNeeded();
  24105. }
  24106. double progress = 0.0;
  24107. AlertWindow aw (TRANS("Scanning for plugins..."),
  24108. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  24109. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24110. aw.addProgressBarComponent (progress);
  24111. aw.enterModalState();
  24112. MessageManager::getInstance()->runDispatchLoopUntil (300);
  24113. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  24114. for (;;)
  24115. {
  24116. aw.setMessage (TRANS("Testing:\n\n")
  24117. + scanner.getNextPluginFileThatWillBeScanned());
  24118. MessageManager::getInstance()->runDispatchLoopUntil (20);
  24119. if (! scanner.scanNextFile (true))
  24120. break;
  24121. if (! aw.isCurrentlyModal())
  24122. break;
  24123. progress = scanner.getProgress();
  24124. }
  24125. if (scanner.getFailedFiles().size() > 0)
  24126. {
  24127. StringArray shortNames;
  24128. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  24129. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  24130. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  24131. TRANS("Scan complete"),
  24132. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  24133. + shortNames.joinIntoString (", "));
  24134. }
  24135. }
  24136. END_JUCE_NAMESPACE
  24137. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  24138. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  24139. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  24140. #include <AudioUnit/AudioUnit.h>
  24141. #include <AudioUnit/AUCocoaUIView.h>
  24142. #include <CoreAudioKit/AUGenericView.h>
  24143. #if JUCE_SUPPORT_CARBON
  24144. #include <AudioToolbox/AudioUnitUtilities.h>
  24145. #include <AudioUnit/AudioUnitCarbonView.h>
  24146. #endif
  24147. BEGIN_JUCE_NAMESPACE
  24148. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  24149. #endif
  24150. #if JUCE_MAC
  24151. // Change this to disable logging of various activities
  24152. #ifndef AU_LOGGING
  24153. #define AU_LOGGING 1
  24154. #endif
  24155. #if AU_LOGGING
  24156. #define log(a) Logger::writeToLog(a);
  24157. #else
  24158. #define log(a)
  24159. #endif
  24160. static int insideCallback = 0;
  24161. static const String osTypeToString (OSType type)
  24162. {
  24163. char s[4];
  24164. s[0] = (char) (((uint32) type) >> 24);
  24165. s[1] = (char) (((uint32) type) >> 16);
  24166. s[2] = (char) (((uint32) type) >> 8);
  24167. s[3] = (char) ((uint32) type);
  24168. return String (s, 4);
  24169. }
  24170. static OSType stringToOSType (const String& s1)
  24171. {
  24172. const String s (s1 + " ");
  24173. return (((OSType) (unsigned char) s[0]) << 24)
  24174. | (((OSType) (unsigned char) s[1]) << 16)
  24175. | (((OSType) (unsigned char) s[2]) << 8)
  24176. | ((OSType) (unsigned char) s[3]);
  24177. }
  24178. static const char* auIdentifierPrefix = "AudioUnit:";
  24179. static const String createAUPluginIdentifier (const ComponentDescription& desc)
  24180. {
  24181. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  24182. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  24183. String s (auIdentifierPrefix);
  24184. if (desc.componentType == kAudioUnitType_MusicDevice)
  24185. s << "Synths/";
  24186. else if (desc.componentType == kAudioUnitType_MusicEffect
  24187. || desc.componentType == kAudioUnitType_Effect)
  24188. s << "Effects/";
  24189. else if (desc.componentType == kAudioUnitType_Generator)
  24190. s << "Generators/";
  24191. else if (desc.componentType == kAudioUnitType_Panner)
  24192. s << "Panners/";
  24193. s << osTypeToString (desc.componentType) << ","
  24194. << osTypeToString (desc.componentSubType) << ","
  24195. << osTypeToString (desc.componentManufacturer);
  24196. return s;
  24197. }
  24198. static void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  24199. {
  24200. Handle componentNameHandle = NewHandle (sizeof (void*));
  24201. Handle componentInfoHandle = NewHandle (sizeof (void*));
  24202. if (componentNameHandle != 0 && componentInfoHandle != 0)
  24203. {
  24204. ComponentDescription desc;
  24205. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  24206. {
  24207. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  24208. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  24209. if (nameString != 0 && nameString[0] != 0)
  24210. {
  24211. const String all ((const char*) nameString + 1, nameString[0]);
  24212. DBG ("name: "+ all);
  24213. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  24214. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  24215. }
  24216. if (infoString != 0 && infoString[0] != 0)
  24217. {
  24218. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  24219. }
  24220. if (name.isEmpty())
  24221. name = "<Unknown>";
  24222. }
  24223. DisposeHandle (componentNameHandle);
  24224. DisposeHandle (componentInfoHandle);
  24225. }
  24226. }
  24227. static bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  24228. String& name, String& version, String& manufacturer)
  24229. {
  24230. zerostruct (desc);
  24231. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  24232. {
  24233. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  24234. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  24235. StringArray tokens;
  24236. tokens.addTokens (s, ",", String::empty);
  24237. tokens.trim();
  24238. tokens.removeEmptyStrings();
  24239. if (tokens.size() == 3)
  24240. {
  24241. desc.componentType = stringToOSType (tokens[0]);
  24242. desc.componentSubType = stringToOSType (tokens[1]);
  24243. desc.componentManufacturer = stringToOSType (tokens[2]);
  24244. ComponentRecord* comp = FindNextComponent (0, &desc);
  24245. if (comp != 0)
  24246. {
  24247. getAUDetails (comp, name, manufacturer);
  24248. return true;
  24249. }
  24250. }
  24251. }
  24252. return false;
  24253. }
  24254. class AudioUnitPluginWindowCarbon;
  24255. class AudioUnitPluginWindowCocoa;
  24256. class AudioUnitPluginInstance : public AudioPluginInstance
  24257. {
  24258. public:
  24259. ~AudioUnitPluginInstance();
  24260. // AudioPluginInstance methods:
  24261. void fillInPluginDescription (PluginDescription& desc) const
  24262. {
  24263. desc.name = pluginName;
  24264. desc.fileOrIdentifier = createAUPluginIdentifier (componentDesc);
  24265. desc.uid = ((int) componentDesc.componentType)
  24266. ^ ((int) componentDesc.componentSubType)
  24267. ^ ((int) componentDesc.componentManufacturer);
  24268. desc.lastFileModTime = 0;
  24269. desc.pluginFormatName = "AudioUnit";
  24270. desc.category = getCategory();
  24271. desc.manufacturerName = manufacturer;
  24272. desc.version = version;
  24273. desc.numInputChannels = getNumInputChannels();
  24274. desc.numOutputChannels = getNumOutputChannels();
  24275. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  24276. }
  24277. const String getName() const { return pluginName; }
  24278. bool acceptsMidi() const { return wantsMidiMessages; }
  24279. bool producesMidi() const { return false; }
  24280. // AudioProcessor methods:
  24281. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  24282. void releaseResources();
  24283. void processBlock (AudioSampleBuffer& buffer,
  24284. MidiBuffer& midiMessages);
  24285. AudioProcessorEditor* createEditor();
  24286. const String getInputChannelName (const int index) const;
  24287. bool isInputChannelStereoPair (int index) const;
  24288. const String getOutputChannelName (const int index) const;
  24289. bool isOutputChannelStereoPair (int index) const;
  24290. int getNumParameters();
  24291. float getParameter (int index);
  24292. void setParameter (int index, float newValue);
  24293. const String getParameterName (int index);
  24294. const String getParameterText (int index);
  24295. bool isParameterAutomatable (int index) const;
  24296. int getNumPrograms();
  24297. int getCurrentProgram();
  24298. void setCurrentProgram (int index);
  24299. const String getProgramName (int index);
  24300. void changeProgramName (int index, const String& newName);
  24301. void getStateInformation (MemoryBlock& destData);
  24302. void getCurrentProgramStateInformation (MemoryBlock& destData);
  24303. void setStateInformation (const void* data, int sizeInBytes);
  24304. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  24305. juce_UseDebuggingNewOperator
  24306. private:
  24307. friend class AudioUnitPluginWindowCarbon;
  24308. friend class AudioUnitPluginWindowCocoa;
  24309. friend class AudioUnitPluginFormat;
  24310. ComponentDescription componentDesc;
  24311. String pluginName, manufacturer, version;
  24312. String fileOrIdentifier;
  24313. CriticalSection lock;
  24314. bool initialised, wantsMidiMessages, wasPlaying;
  24315. HeapBlock <AudioBufferList> outputBufferList;
  24316. AudioTimeStamp timeStamp;
  24317. AudioSampleBuffer* currentBuffer;
  24318. AudioUnit audioUnit;
  24319. Array <int> parameterIds;
  24320. bool getComponentDescFromFile (const String& fileOrIdentifier);
  24321. void initialise();
  24322. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  24323. const AudioTimeStamp* inTimeStamp,
  24324. UInt32 inBusNumber,
  24325. UInt32 inNumberFrames,
  24326. AudioBufferList* ioData) const;
  24327. static OSStatus renderGetInputCallback (void* inRefCon,
  24328. AudioUnitRenderActionFlags* ioActionFlags,
  24329. const AudioTimeStamp* inTimeStamp,
  24330. UInt32 inBusNumber,
  24331. UInt32 inNumberFrames,
  24332. AudioBufferList* ioData)
  24333. {
  24334. return ((AudioUnitPluginInstance*) inRefCon)
  24335. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  24336. }
  24337. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  24338. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  24339. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  24340. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  24341. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  24342. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  24343. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  24344. {
  24345. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  24346. }
  24347. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  24348. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  24349. Float64* outCurrentMeasureDownBeat)
  24350. {
  24351. return ((AudioUnitPluginInstance*) inHostUserData)
  24352. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  24353. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  24354. }
  24355. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  24356. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  24357. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  24358. {
  24359. return ((AudioUnitPluginInstance*) inHostUserData)
  24360. ->getTransportState (outIsPlaying, outTransportStateChanged,
  24361. outCurrentSampleInTimeLine, outIsCycling,
  24362. outCycleStartBeat, outCycleEndBeat);
  24363. }
  24364. void getNumChannels (int& numIns, int& numOuts)
  24365. {
  24366. numIns = 0;
  24367. numOuts = 0;
  24368. AUChannelInfo supportedChannels [128];
  24369. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  24370. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  24371. 0, supportedChannels, &supportedChannelsSize) == noErr
  24372. && supportedChannelsSize > 0)
  24373. {
  24374. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  24375. {
  24376. numIns = jmax (numIns, (int) supportedChannels[i].inChannels);
  24377. numOuts = jmax (numOuts, (int) supportedChannels[i].outChannels);
  24378. }
  24379. }
  24380. else
  24381. {
  24382. // (this really means the plugin will take any number of ins/outs as long
  24383. // as they are the same)
  24384. numIns = numOuts = 2;
  24385. }
  24386. }
  24387. const String getCategory() const;
  24388. AudioUnitPluginInstance (const String& fileOrIdentifier);
  24389. };
  24390. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  24391. : fileOrIdentifier (fileOrIdentifier),
  24392. initialised (false),
  24393. wantsMidiMessages (false),
  24394. audioUnit (0),
  24395. currentBuffer (0)
  24396. {
  24397. try
  24398. {
  24399. ++insideCallback;
  24400. log ("Opening AU: " + fileOrIdentifier);
  24401. if (getComponentDescFromFile (fileOrIdentifier))
  24402. {
  24403. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  24404. if (comp != 0)
  24405. {
  24406. audioUnit = (AudioUnit) OpenComponent (comp);
  24407. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  24408. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  24409. }
  24410. }
  24411. --insideCallback;
  24412. }
  24413. catch (...)
  24414. {
  24415. --insideCallback;
  24416. }
  24417. }
  24418. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  24419. {
  24420. const ScopedLock sl (lock);
  24421. jassert (insideCallback == 0);
  24422. if (audioUnit != 0)
  24423. {
  24424. AudioUnitUninitialize (audioUnit);
  24425. CloseComponent (audioUnit);
  24426. audioUnit = 0;
  24427. }
  24428. }
  24429. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  24430. {
  24431. zerostruct (componentDesc);
  24432. if (getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  24433. return true;
  24434. const File file (fileOrIdentifier);
  24435. if (! file.hasFileExtension (".component"))
  24436. return false;
  24437. const char* const utf8 = fileOrIdentifier.toUTF8();
  24438. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  24439. strlen (utf8), file.isDirectory());
  24440. if (url != 0)
  24441. {
  24442. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  24443. CFRelease (url);
  24444. if (bundleRef != 0)
  24445. {
  24446. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  24447. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  24448. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  24449. if (pluginName.isEmpty())
  24450. pluginName = file.getFileNameWithoutExtension();
  24451. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  24452. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  24453. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  24454. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  24455. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  24456. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  24457. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  24458. UseResFile (resFileId);
  24459. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  24460. {
  24461. Handle h = Get1IndResource ('thng', i);
  24462. if (h != 0)
  24463. {
  24464. HLock (h);
  24465. const uint32* const types = (const uint32*) *h;
  24466. if (types[0] == kAudioUnitType_MusicDevice
  24467. || types[0] == kAudioUnitType_MusicEffect
  24468. || types[0] == kAudioUnitType_Effect
  24469. || types[0] == kAudioUnitType_Generator
  24470. || types[0] == kAudioUnitType_Panner)
  24471. {
  24472. componentDesc.componentType = types[0];
  24473. componentDesc.componentSubType = types[1];
  24474. componentDesc.componentManufacturer = types[2];
  24475. break;
  24476. }
  24477. HUnlock (h);
  24478. ReleaseResource (h);
  24479. }
  24480. }
  24481. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  24482. CFRelease (bundleRef);
  24483. }
  24484. }
  24485. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  24486. }
  24487. void AudioUnitPluginInstance::initialise()
  24488. {
  24489. if (initialised || audioUnit == 0)
  24490. return;
  24491. log ("Initialising AU: " + pluginName);
  24492. parameterIds.clear();
  24493. {
  24494. UInt32 paramListSize = 0;
  24495. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  24496. 0, 0, &paramListSize);
  24497. if (paramListSize > 0)
  24498. {
  24499. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  24500. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  24501. 0, &parameterIds.getReference(0), &paramListSize);
  24502. }
  24503. }
  24504. {
  24505. AURenderCallbackStruct info;
  24506. zerostruct (info);
  24507. info.inputProcRefCon = this;
  24508. info.inputProc = renderGetInputCallback;
  24509. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  24510. 0, &info, sizeof (info));
  24511. }
  24512. {
  24513. HostCallbackInfo info;
  24514. zerostruct (info);
  24515. info.hostUserData = this;
  24516. info.beatAndTempoProc = getBeatAndTempoCallback;
  24517. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  24518. info.transportStateProc = getTransportStateCallback;
  24519. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  24520. 0, &info, sizeof (info));
  24521. }
  24522. int numIns, numOuts;
  24523. getNumChannels (numIns, numOuts);
  24524. setPlayConfigDetails (numIns, numOuts, 0, 0);
  24525. initialised = AudioUnitInitialize (audioUnit) == noErr;
  24526. setLatencySamples (0);
  24527. }
  24528. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  24529. int samplesPerBlockExpected)
  24530. {
  24531. if (audioUnit != 0)
  24532. {
  24533. Float64 sampleRateIn = 0, sampleRateOut = 0;
  24534. UInt32 sampleRateSize = sizeof (sampleRateIn);
  24535. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  24536. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  24537. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  24538. {
  24539. if (initialised)
  24540. {
  24541. AudioUnitUninitialize (audioUnit);
  24542. initialised = false;
  24543. }
  24544. Float64 sr = sampleRate_;
  24545. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  24546. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  24547. }
  24548. }
  24549. initialise();
  24550. if (initialised)
  24551. {
  24552. int numIns, numOuts;
  24553. getNumChannels (numIns, numOuts);
  24554. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  24555. Float64 latencySecs = 0.0;
  24556. UInt32 latencySize = sizeof (latencySecs);
  24557. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  24558. 0, &latencySecs, &latencySize);
  24559. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  24560. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  24561. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  24562. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  24563. AudioStreamBasicDescription stream;
  24564. zerostruct (stream);
  24565. stream.mSampleRate = sampleRate_;
  24566. stream.mFormatID = kAudioFormatLinearPCM;
  24567. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  24568. stream.mFramesPerPacket = 1;
  24569. stream.mBytesPerPacket = 4;
  24570. stream.mBytesPerFrame = 4;
  24571. stream.mBitsPerChannel = 32;
  24572. stream.mChannelsPerFrame = numIns;
  24573. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  24574. 0, &stream, sizeof (stream));
  24575. stream.mChannelsPerFrame = numOuts;
  24576. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  24577. 0, &stream, sizeof (stream));
  24578. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  24579. outputBufferList->mNumberBuffers = numOuts;
  24580. for (int i = numOuts; --i >= 0;)
  24581. outputBufferList->mBuffers[i].mNumberChannels = 1;
  24582. zerostruct (timeStamp);
  24583. timeStamp.mSampleTime = 0;
  24584. timeStamp.mHostTime = AudioGetCurrentHostTime();
  24585. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  24586. currentBuffer = 0;
  24587. wasPlaying = false;
  24588. }
  24589. }
  24590. void AudioUnitPluginInstance::releaseResources()
  24591. {
  24592. if (initialised)
  24593. {
  24594. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  24595. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  24596. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  24597. outputBufferList.free();
  24598. currentBuffer = 0;
  24599. }
  24600. }
  24601. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  24602. const AudioTimeStamp* inTimeStamp,
  24603. UInt32 inBusNumber,
  24604. UInt32 inNumberFrames,
  24605. AudioBufferList* ioData) const
  24606. {
  24607. if (inBusNumber == 0
  24608. && currentBuffer != 0)
  24609. {
  24610. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  24611. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  24612. {
  24613. if (i < currentBuffer->getNumChannels())
  24614. {
  24615. memcpy (ioData->mBuffers[i].mData,
  24616. currentBuffer->getSampleData (i, 0),
  24617. sizeof (float) * inNumberFrames);
  24618. }
  24619. else
  24620. {
  24621. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  24622. }
  24623. }
  24624. }
  24625. return noErr;
  24626. }
  24627. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  24628. MidiBuffer& midiMessages)
  24629. {
  24630. const int numSamples = buffer.getNumSamples();
  24631. if (initialised)
  24632. {
  24633. AudioUnitRenderActionFlags flags = 0;
  24634. timeStamp.mHostTime = AudioGetCurrentHostTime();
  24635. for (int i = getNumOutputChannels(); --i >= 0;)
  24636. {
  24637. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  24638. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  24639. }
  24640. currentBuffer = &buffer;
  24641. if (wantsMidiMessages)
  24642. {
  24643. const uint8* midiEventData;
  24644. int midiEventSize, midiEventPosition;
  24645. MidiBuffer::Iterator i (midiMessages);
  24646. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  24647. {
  24648. if (midiEventSize <= 3)
  24649. MusicDeviceMIDIEvent (audioUnit,
  24650. midiEventData[0], midiEventData[1], midiEventData[2],
  24651. midiEventPosition);
  24652. else
  24653. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  24654. }
  24655. midiMessages.clear();
  24656. }
  24657. AudioUnitRender (audioUnit, &flags, &timeStamp,
  24658. 0, numSamples, outputBufferList);
  24659. timeStamp.mSampleTime += numSamples;
  24660. }
  24661. else
  24662. {
  24663. // Not initialised, so just bypass..
  24664. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  24665. buffer.clear (i, 0, buffer.getNumSamples());
  24666. }
  24667. }
  24668. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  24669. {
  24670. AudioPlayHead* const ph = getPlayHead();
  24671. AudioPlayHead::CurrentPositionInfo result;
  24672. if (ph != 0 && ph->getCurrentPosition (result))
  24673. {
  24674. if (outCurrentBeat != 0)
  24675. *outCurrentBeat = result.ppqPosition;
  24676. if (outCurrentTempo != 0)
  24677. *outCurrentTempo = result.bpm;
  24678. }
  24679. else
  24680. {
  24681. if (outCurrentBeat != 0)
  24682. *outCurrentBeat = 0;
  24683. if (outCurrentTempo != 0)
  24684. *outCurrentTempo = 120.0;
  24685. }
  24686. return noErr;
  24687. }
  24688. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  24689. Float32* outTimeSig_Numerator,
  24690. UInt32* outTimeSig_Denominator,
  24691. Float64* outCurrentMeasureDownBeat) const
  24692. {
  24693. AudioPlayHead* const ph = getPlayHead();
  24694. AudioPlayHead::CurrentPositionInfo result;
  24695. if (ph != 0 && ph->getCurrentPosition (result))
  24696. {
  24697. if (outTimeSig_Numerator != 0)
  24698. *outTimeSig_Numerator = result.timeSigNumerator;
  24699. if (outTimeSig_Denominator != 0)
  24700. *outTimeSig_Denominator = result.timeSigDenominator;
  24701. if (outDeltaSampleOffsetToNextBeat != 0)
  24702. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  24703. if (outCurrentMeasureDownBeat != 0)
  24704. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  24705. }
  24706. else
  24707. {
  24708. if (outDeltaSampleOffsetToNextBeat != 0)
  24709. *outDeltaSampleOffsetToNextBeat = 0;
  24710. if (outTimeSig_Numerator != 0)
  24711. *outTimeSig_Numerator = 4;
  24712. if (outTimeSig_Denominator != 0)
  24713. *outTimeSig_Denominator = 4;
  24714. if (outCurrentMeasureDownBeat != 0)
  24715. *outCurrentMeasureDownBeat = 0;
  24716. }
  24717. return noErr;
  24718. }
  24719. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  24720. Boolean* outTransportStateChanged,
  24721. Float64* outCurrentSampleInTimeLine,
  24722. Boolean* outIsCycling,
  24723. Float64* outCycleStartBeat,
  24724. Float64* outCycleEndBeat)
  24725. {
  24726. AudioPlayHead* const ph = getPlayHead();
  24727. AudioPlayHead::CurrentPositionInfo result;
  24728. if (ph != 0 && ph->getCurrentPosition (result))
  24729. {
  24730. if (outIsPlaying != 0)
  24731. *outIsPlaying = result.isPlaying;
  24732. if (outTransportStateChanged != 0)
  24733. {
  24734. *outTransportStateChanged = result.isPlaying != wasPlaying;
  24735. wasPlaying = result.isPlaying;
  24736. }
  24737. if (outCurrentSampleInTimeLine != 0)
  24738. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  24739. if (outIsCycling != 0)
  24740. *outIsCycling = false;
  24741. if (outCycleStartBeat != 0)
  24742. *outCycleStartBeat = 0;
  24743. if (outCycleEndBeat != 0)
  24744. *outCycleEndBeat = 0;
  24745. }
  24746. else
  24747. {
  24748. if (outIsPlaying != 0)
  24749. *outIsPlaying = false;
  24750. if (outTransportStateChanged != 0)
  24751. *outTransportStateChanged = false;
  24752. if (outCurrentSampleInTimeLine != 0)
  24753. *outCurrentSampleInTimeLine = 0;
  24754. if (outIsCycling != 0)
  24755. *outIsCycling = false;
  24756. if (outCycleStartBeat != 0)
  24757. *outCycleStartBeat = 0;
  24758. if (outCycleEndBeat != 0)
  24759. *outCycleEndBeat = 0;
  24760. }
  24761. return noErr;
  24762. }
  24763. static VoidArray activeWindows;
  24764. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor
  24765. {
  24766. public:
  24767. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  24768. : AudioProcessorEditor (&plugin_),
  24769. plugin (plugin_),
  24770. wrapper (0)
  24771. {
  24772. addAndMakeVisible (wrapper = new NSViewComponent());
  24773. activeWindows.add (this);
  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. activeWindows.removeValue (this);
  24784. if (wasValid)
  24785. plugin.editorBeingDeleted (this);
  24786. delete wrapper;
  24787. }
  24788. bool isValid() const { return wrapper->getView() != 0; }
  24789. void paint (Graphics& g)
  24790. {
  24791. g.fillAll (Colours::white);
  24792. }
  24793. void resized()
  24794. {
  24795. wrapper->setSize (getWidth(), getHeight());
  24796. }
  24797. private:
  24798. AudioUnitPluginInstance& plugin;
  24799. NSViewComponent* wrapper;
  24800. bool createView (const bool createGenericViewIfNeeded)
  24801. {
  24802. NSView* pluginView = 0;
  24803. UInt32 dataSize = 0;
  24804. Boolean isWritable = false;
  24805. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24806. 0, &dataSize, &isWritable) == noErr
  24807. && dataSize != 0
  24808. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24809. 0, &dataSize, &isWritable) == noErr)
  24810. {
  24811. HeapBlock <AudioUnitCocoaViewInfo> info;
  24812. info.calloc (dataSize, 1);
  24813. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24814. 0, info, &dataSize) == noErr)
  24815. {
  24816. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  24817. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  24818. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  24819. Class viewClass = [viewBundle classNamed: viewClassName];
  24820. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  24821. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  24822. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  24823. {
  24824. id factory = [[[viewClass alloc] init] autorelease];
  24825. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  24826. withSize: NSMakeSize (getWidth(), getHeight())];
  24827. }
  24828. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  24829. {
  24830. CFRelease (info->mCocoaAUViewClass[i]);
  24831. CFRelease (info->mCocoaAUViewBundleLocation);
  24832. }
  24833. }
  24834. }
  24835. if (createGenericViewIfNeeded && (pluginView == 0))
  24836. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  24837. wrapper->setView (pluginView);
  24838. if (pluginView != 0)
  24839. setSize ([pluginView frame].size.width,
  24840. [pluginView frame].size.height);
  24841. return pluginView != 0;
  24842. }
  24843. };
  24844. #if JUCE_SUPPORT_CARBON
  24845. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  24846. {
  24847. public:
  24848. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  24849. : AudioProcessorEditor (&plugin_),
  24850. plugin (plugin_),
  24851. viewComponent (0)
  24852. {
  24853. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  24854. activeWindows.add (this);
  24855. setOpaque (true);
  24856. setVisible (true);
  24857. setSize (400, 300);
  24858. ComponentDescription viewList [16];
  24859. UInt32 viewListSize = sizeof (viewList);
  24860. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  24861. 0, &viewList, &viewListSize);
  24862. componentRecord = FindNextComponent (0, &viewList[0]);
  24863. }
  24864. ~AudioUnitPluginWindowCarbon()
  24865. {
  24866. innerWrapper = 0;
  24867. activeWindows.removeValue (this);
  24868. if (isValid())
  24869. plugin.editorBeingDeleted (this);
  24870. }
  24871. bool isValid() const throw() { return componentRecord != 0; }
  24872. void paint (Graphics& g)
  24873. {
  24874. g.fillAll (Colours::black);
  24875. }
  24876. void resized()
  24877. {
  24878. innerWrapper->setSize (getWidth(), getHeight());
  24879. }
  24880. bool keyStateChanged (bool)
  24881. {
  24882. return false;
  24883. }
  24884. bool keyPressed (const KeyPress&)
  24885. {
  24886. return false;
  24887. }
  24888. void broughtToFront()
  24889. {
  24890. activeWindows.removeValue (this);
  24891. activeWindows.add (this);
  24892. }
  24893. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  24894. AudioUnitCarbonView getViewComponent()
  24895. {
  24896. if (viewComponent == 0 && componentRecord != 0)
  24897. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  24898. return viewComponent;
  24899. }
  24900. void closeViewComponent()
  24901. {
  24902. if (viewComponent != 0)
  24903. {
  24904. CloseComponent (viewComponent);
  24905. viewComponent = 0;
  24906. }
  24907. }
  24908. juce_UseDebuggingNewOperator
  24909. private:
  24910. AudioUnitPluginInstance& plugin;
  24911. ComponentRecord* componentRecord;
  24912. AudioUnitCarbonView viewComponent;
  24913. class InnerWrapperComponent : public CarbonViewWrapperComponent
  24914. {
  24915. public:
  24916. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  24917. : owner (owner_)
  24918. {
  24919. }
  24920. ~InnerWrapperComponent()
  24921. {
  24922. deleteWindow();
  24923. }
  24924. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  24925. {
  24926. log ("Opening AU GUI: " + owner->plugin.getName());
  24927. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  24928. if (viewComponent == 0)
  24929. return 0;
  24930. Float32Point pos = { 0, 0 };
  24931. Float32Point size = { 250, 200 };
  24932. HIViewRef pluginView = 0;
  24933. AudioUnitCarbonViewCreate (viewComponent,
  24934. owner->getAudioUnit(),
  24935. windowRef,
  24936. rootView,
  24937. &pos,
  24938. &size,
  24939. (ControlRef*) &pluginView);
  24940. return pluginView;
  24941. }
  24942. void removeView (HIViewRef)
  24943. {
  24944. log ("Closing AU GUI: " + owner->plugin.getName());
  24945. owner->closeViewComponent();
  24946. }
  24947. private:
  24948. AudioUnitPluginWindowCarbon* const owner;
  24949. };
  24950. friend class InnerWrapperComponent;
  24951. ScopedPointer<InnerWrapperComponent> innerWrapper;
  24952. };
  24953. #endif
  24954. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  24955. {
  24956. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  24957. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  24958. w = 0;
  24959. #if JUCE_SUPPORT_CARBON
  24960. if (w == 0)
  24961. {
  24962. w = new AudioUnitPluginWindowCarbon (*this);
  24963. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  24964. w = 0;
  24965. }
  24966. #endif
  24967. if (w == 0)
  24968. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  24969. return w.release();
  24970. }
  24971. const String AudioUnitPluginInstance::getCategory() const
  24972. {
  24973. const char* result = 0;
  24974. switch (componentDesc.componentType)
  24975. {
  24976. case kAudioUnitType_Effect:
  24977. case kAudioUnitType_MusicEffect:
  24978. result = "Effect";
  24979. break;
  24980. case kAudioUnitType_MusicDevice:
  24981. result = "Synth";
  24982. break;
  24983. case kAudioUnitType_Generator:
  24984. result = "Generator";
  24985. break;
  24986. case kAudioUnitType_Panner:
  24987. result = "Panner";
  24988. break;
  24989. default:
  24990. break;
  24991. }
  24992. return result;
  24993. }
  24994. int AudioUnitPluginInstance::getNumParameters()
  24995. {
  24996. return parameterIds.size();
  24997. }
  24998. float AudioUnitPluginInstance::getParameter (int index)
  24999. {
  25000. const ScopedLock sl (lock);
  25001. Float32 value = 0.0f;
  25002. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  25003. {
  25004. AudioUnitGetParameter (audioUnit,
  25005. (UInt32) parameterIds.getUnchecked (index),
  25006. kAudioUnitScope_Global, 0,
  25007. &value);
  25008. }
  25009. return value;
  25010. }
  25011. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  25012. {
  25013. const ScopedLock sl (lock);
  25014. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  25015. {
  25016. AudioUnitSetParameter (audioUnit,
  25017. (UInt32) parameterIds.getUnchecked (index),
  25018. kAudioUnitScope_Global, 0,
  25019. newValue, 0);
  25020. }
  25021. }
  25022. const String AudioUnitPluginInstance::getParameterName (int index)
  25023. {
  25024. AudioUnitParameterInfo info;
  25025. zerostruct (info);
  25026. UInt32 sz = sizeof (info);
  25027. String name;
  25028. if (AudioUnitGetProperty (audioUnit,
  25029. kAudioUnitProperty_ParameterInfo,
  25030. kAudioUnitScope_Global,
  25031. parameterIds [index], &info, &sz) == noErr)
  25032. {
  25033. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  25034. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  25035. else
  25036. name = String (info.name, sizeof (info.name));
  25037. }
  25038. return name;
  25039. }
  25040. const String AudioUnitPluginInstance::getParameterText (int index)
  25041. {
  25042. return String (getParameter (index));
  25043. }
  25044. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  25045. {
  25046. AudioUnitParameterInfo info;
  25047. UInt32 sz = sizeof (info);
  25048. if (AudioUnitGetProperty (audioUnit,
  25049. kAudioUnitProperty_ParameterInfo,
  25050. kAudioUnitScope_Global,
  25051. parameterIds [index], &info, &sz) == noErr)
  25052. {
  25053. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  25054. }
  25055. return true;
  25056. }
  25057. int AudioUnitPluginInstance::getNumPrograms()
  25058. {
  25059. CFArrayRef presets;
  25060. UInt32 sz = sizeof (CFArrayRef);
  25061. int num = 0;
  25062. if (AudioUnitGetProperty (audioUnit,
  25063. kAudioUnitProperty_FactoryPresets,
  25064. kAudioUnitScope_Global,
  25065. 0, &presets, &sz) == noErr)
  25066. {
  25067. num = (int) CFArrayGetCount (presets);
  25068. CFRelease (presets);
  25069. }
  25070. return num;
  25071. }
  25072. int AudioUnitPluginInstance::getCurrentProgram()
  25073. {
  25074. AUPreset current;
  25075. current.presetNumber = 0;
  25076. UInt32 sz = sizeof (AUPreset);
  25077. AudioUnitGetProperty (audioUnit,
  25078. kAudioUnitProperty_FactoryPresets,
  25079. kAudioUnitScope_Global,
  25080. 0, &current, &sz);
  25081. return current.presetNumber;
  25082. }
  25083. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  25084. {
  25085. AUPreset current;
  25086. current.presetNumber = newIndex;
  25087. current.presetName = 0;
  25088. AudioUnitSetProperty (audioUnit,
  25089. kAudioUnitProperty_FactoryPresets,
  25090. kAudioUnitScope_Global,
  25091. 0, &current, sizeof (AUPreset));
  25092. }
  25093. const String AudioUnitPluginInstance::getProgramName (int index)
  25094. {
  25095. String s;
  25096. CFArrayRef presets;
  25097. UInt32 sz = sizeof (CFArrayRef);
  25098. if (AudioUnitGetProperty (audioUnit,
  25099. kAudioUnitProperty_FactoryPresets,
  25100. kAudioUnitScope_Global,
  25101. 0, &presets, &sz) == noErr)
  25102. {
  25103. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  25104. {
  25105. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  25106. if (p != 0 && p->presetNumber == index)
  25107. {
  25108. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  25109. break;
  25110. }
  25111. }
  25112. CFRelease (presets);
  25113. }
  25114. return s;
  25115. }
  25116. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  25117. {
  25118. jassertfalse // xxx not implemented!
  25119. }
  25120. const String AudioUnitPluginInstance::getInputChannelName (const int index) const
  25121. {
  25122. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  25123. return "Input " + String (index + 1);
  25124. return String::empty;
  25125. }
  25126. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  25127. {
  25128. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  25129. return false;
  25130. return true;
  25131. }
  25132. const String AudioUnitPluginInstance::getOutputChannelName (const int index) const
  25133. {
  25134. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  25135. return "Output " + String (index + 1);
  25136. return String::empty;
  25137. }
  25138. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  25139. {
  25140. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  25141. return false;
  25142. return true;
  25143. }
  25144. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  25145. {
  25146. getCurrentProgramStateInformation (destData);
  25147. }
  25148. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  25149. {
  25150. CFPropertyListRef propertyList = 0;
  25151. UInt32 sz = sizeof (CFPropertyListRef);
  25152. if (AudioUnitGetProperty (audioUnit,
  25153. kAudioUnitProperty_ClassInfo,
  25154. kAudioUnitScope_Global,
  25155. 0, &propertyList, &sz) == noErr)
  25156. {
  25157. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  25158. CFWriteStreamOpen (stream);
  25159. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  25160. CFWriteStreamClose (stream);
  25161. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  25162. destData.setSize (bytesWritten);
  25163. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  25164. CFRelease (data);
  25165. CFRelease (stream);
  25166. CFRelease (propertyList);
  25167. }
  25168. }
  25169. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  25170. {
  25171. setCurrentProgramStateInformation (data, sizeInBytes);
  25172. }
  25173. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  25174. {
  25175. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  25176. (const UInt8*) data,
  25177. sizeInBytes,
  25178. kCFAllocatorNull);
  25179. CFReadStreamOpen (stream);
  25180. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  25181. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  25182. stream,
  25183. 0,
  25184. kCFPropertyListImmutable,
  25185. &format,
  25186. 0);
  25187. CFRelease (stream);
  25188. if (propertyList != 0)
  25189. AudioUnitSetProperty (audioUnit,
  25190. kAudioUnitProperty_ClassInfo,
  25191. kAudioUnitScope_Global,
  25192. 0, &propertyList, sizeof (propertyList));
  25193. }
  25194. AudioUnitPluginFormat::AudioUnitPluginFormat()
  25195. {
  25196. }
  25197. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  25198. {
  25199. }
  25200. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  25201. const String& fileOrIdentifier)
  25202. {
  25203. if (! fileMightContainThisPluginType (fileOrIdentifier))
  25204. return;
  25205. PluginDescription desc;
  25206. desc.fileOrIdentifier = fileOrIdentifier;
  25207. desc.uid = 0;
  25208. try
  25209. {
  25210. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  25211. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  25212. if (auInstance != 0)
  25213. {
  25214. auInstance->fillInPluginDescription (desc);
  25215. results.add (new PluginDescription (desc));
  25216. }
  25217. }
  25218. catch (...)
  25219. {
  25220. // crashed while loading...
  25221. }
  25222. }
  25223. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  25224. {
  25225. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  25226. {
  25227. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  25228. if (result->audioUnit != 0)
  25229. {
  25230. result->initialise();
  25231. return result.release();
  25232. }
  25233. }
  25234. return 0;
  25235. }
  25236. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  25237. const bool /*recursive*/)
  25238. {
  25239. StringArray result;
  25240. ComponentRecord* comp = 0;
  25241. ComponentDescription desc;
  25242. zerostruct (desc);
  25243. for (;;)
  25244. {
  25245. zerostruct (desc);
  25246. comp = FindNextComponent (comp, &desc);
  25247. if (comp == 0)
  25248. break;
  25249. GetComponentInfo (comp, &desc, 0, 0, 0);
  25250. if (desc.componentType == kAudioUnitType_MusicDevice
  25251. || desc.componentType == kAudioUnitType_MusicEffect
  25252. || desc.componentType == kAudioUnitType_Effect
  25253. || desc.componentType == kAudioUnitType_Generator
  25254. || desc.componentType == kAudioUnitType_Panner)
  25255. {
  25256. const String s (createAUPluginIdentifier (desc));
  25257. DBG (s);
  25258. result.add (s);
  25259. }
  25260. }
  25261. return result;
  25262. }
  25263. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  25264. {
  25265. ComponentDescription desc;
  25266. String name, version, manufacturer;
  25267. if (getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  25268. return FindNextComponent (0, &desc) != 0;
  25269. const File f (fileOrIdentifier);
  25270. return f.hasFileExtension (".component")
  25271. && f.isDirectory();
  25272. }
  25273. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  25274. {
  25275. ComponentDescription desc;
  25276. String name, version, manufacturer;
  25277. getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  25278. if (name.isEmpty())
  25279. name = fileOrIdentifier;
  25280. return name;
  25281. }
  25282. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  25283. {
  25284. if (desc.fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  25285. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  25286. else
  25287. return File (desc.fileOrIdentifier).exists();
  25288. }
  25289. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  25290. {
  25291. return FileSearchPath ("/(Default AudioUnit locations)");
  25292. }
  25293. #endif
  25294. END_JUCE_NAMESPACE
  25295. #undef log
  25296. #endif
  25297. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  25298. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  25299. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  25300. #define JUCE_MAC_VST_INCLUDED 1
  25301. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  25302. #if JUCE_PLUGINHOST_VST
  25303. #if JUCE_WINDOWS
  25304. #undef _WIN32_WINNT
  25305. #define _WIN32_WINNT 0x500
  25306. #undef STRICT
  25307. #define STRICT
  25308. #include <windows.h>
  25309. #include <float.h>
  25310. #pragma warning (disable : 4312 4355)
  25311. #elif JUCE_LINUX
  25312. #include <float.h>
  25313. #include <sys/time.h>
  25314. #include <X11/Xlib.h>
  25315. #include <X11/Xutil.h>
  25316. #include <X11/Xatom.h>
  25317. #undef Font
  25318. #undef KeyPress
  25319. #undef Drawable
  25320. #undef Time
  25321. #else
  25322. #ifndef JUCE_MAC_VST_INCLUDED
  25323. // On the mac, this file needs to be compiled indirectly, by using
  25324. // juce_VSTPluginFormat.mm instead - that wraps it as an objective-C file for cocoa
  25325. #error
  25326. #endif
  25327. #include <Cocoa/Cocoa.h>
  25328. #include <Carbon/Carbon.h>
  25329. #endif
  25330. #if ! (JUCE_MAC && JUCE_64BIT)
  25331. BEGIN_JUCE_NAMESPACE
  25332. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  25333. #endif
  25334. #undef PRAGMA_ALIGN_SUPPORTED
  25335. #define VST_FORCE_DEPRECATED 0
  25336. #if JUCE_MSVC
  25337. #pragma warning (push)
  25338. #pragma warning (disable: 4996)
  25339. #endif
  25340. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  25341. your include path if you want to add VST support.
  25342. If you're not interested in VSTs, you can disable them by changing the
  25343. JUCE_PLUGINHOST_VST flag in juce_Config.h
  25344. */
  25345. #include "pluginterfaces/vst2.x/aeffectx.h"
  25346. #if JUCE_MSVC
  25347. #pragma warning (pop)
  25348. #endif
  25349. #if JUCE_LINUX
  25350. #define Font JUCE_NAMESPACE::Font
  25351. #define KeyPress JUCE_NAMESPACE::KeyPress
  25352. #define Drawable JUCE_NAMESPACE::Drawable
  25353. #define Time JUCE_NAMESPACE::Time
  25354. #endif
  25355. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  25356. #ifdef __aeffect__
  25357. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25358. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25359. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  25360. events to the list.
  25361. This is used by both the VST hosting code and the plugin wrapper.
  25362. */
  25363. class VSTMidiEventList
  25364. {
  25365. public:
  25366. VSTMidiEventList()
  25367. : numEventsUsed (0), numEventsAllocated (0)
  25368. {
  25369. }
  25370. ~VSTMidiEventList()
  25371. {
  25372. freeEvents();
  25373. }
  25374. void clear()
  25375. {
  25376. numEventsUsed = 0;
  25377. if (events != 0)
  25378. events->numEvents = 0;
  25379. }
  25380. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  25381. {
  25382. ensureSize (numEventsUsed + 1);
  25383. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  25384. events->numEvents = ++numEventsUsed;
  25385. if (numBytes <= 4)
  25386. {
  25387. if (e->type == kVstSysExType)
  25388. {
  25389. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  25390. e->type = kVstMidiType;
  25391. e->byteSize = sizeof (VstMidiEvent);
  25392. e->noteLength = 0;
  25393. e->noteOffset = 0;
  25394. e->detune = 0;
  25395. e->noteOffVelocity = 0;
  25396. }
  25397. e->deltaFrames = frameOffset;
  25398. memcpy (e->midiData, midiData, numBytes);
  25399. }
  25400. else
  25401. {
  25402. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  25403. if (se->type == kVstSysExType)
  25404. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  25405. else
  25406. se->sysexDump = (char*) juce_malloc (numBytes);
  25407. memcpy (se->sysexDump, midiData, numBytes);
  25408. se->type = kVstSysExType;
  25409. se->byteSize = sizeof (VstMidiSysexEvent);
  25410. se->deltaFrames = frameOffset;
  25411. se->flags = 0;
  25412. se->dumpBytes = numBytes;
  25413. se->resvd1 = 0;
  25414. se->resvd2 = 0;
  25415. }
  25416. }
  25417. // Handy method to pull the events out of an event buffer supplied by the host
  25418. // or plugin.
  25419. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  25420. {
  25421. for (int i = 0; i < events->numEvents; ++i)
  25422. {
  25423. const VstEvent* const e = events->events[i];
  25424. if (e != 0)
  25425. {
  25426. if (e->type == kVstMidiType)
  25427. {
  25428. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  25429. 4, e->deltaFrames);
  25430. }
  25431. else if (e->type == kVstSysExType)
  25432. {
  25433. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  25434. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  25435. e->deltaFrames);
  25436. }
  25437. }
  25438. }
  25439. }
  25440. void ensureSize (int numEventsNeeded)
  25441. {
  25442. if (numEventsNeeded > numEventsAllocated)
  25443. {
  25444. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  25445. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  25446. if (events == 0)
  25447. events.calloc (size, 1);
  25448. else
  25449. events.realloc (size, 1);
  25450. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  25451. {
  25452. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  25453. (int) sizeof (VstMidiSysexEvent)));
  25454. e->type = kVstMidiType;
  25455. e->byteSize = sizeof (VstMidiEvent);
  25456. events->events[i] = (VstEvent*) e;
  25457. }
  25458. numEventsAllocated = numEventsNeeded;
  25459. }
  25460. }
  25461. void freeEvents()
  25462. {
  25463. if (events != 0)
  25464. {
  25465. for (int i = numEventsAllocated; --i >= 0;)
  25466. {
  25467. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  25468. if (e->type == kVstSysExType)
  25469. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  25470. juce_free (e);
  25471. }
  25472. events.free();
  25473. numEventsUsed = 0;
  25474. numEventsAllocated = 0;
  25475. }
  25476. }
  25477. HeapBlock <VstEvents> events;
  25478. private:
  25479. int numEventsUsed, numEventsAllocated;
  25480. };
  25481. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25482. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25483. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  25484. #if ! JUCE_WIN32
  25485. static void _fpreset() {}
  25486. static void _clearfp() {}
  25487. #endif
  25488. extern void juce_callAnyTimersSynchronously();
  25489. const int fxbVersionNum = 1;
  25490. struct fxProgram
  25491. {
  25492. long chunkMagic; // 'CcnK'
  25493. long byteSize; // of this chunk, excl. magic + byteSize
  25494. long fxMagic; // 'FxCk'
  25495. long version;
  25496. long fxID; // fx unique id
  25497. long fxVersion;
  25498. long numParams;
  25499. char prgName[28];
  25500. float params[1]; // variable no. of parameters
  25501. };
  25502. struct fxSet
  25503. {
  25504. long chunkMagic; // 'CcnK'
  25505. long byteSize; // of this chunk, excl. magic + byteSize
  25506. long fxMagic; // 'FxBk'
  25507. long version;
  25508. long fxID; // fx unique id
  25509. long fxVersion;
  25510. long numPrograms;
  25511. char future[128];
  25512. fxProgram programs[1]; // variable no. of programs
  25513. };
  25514. struct fxChunkSet
  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 future[128];
  25524. long chunkSize;
  25525. char chunk[8]; // variable
  25526. };
  25527. struct fxProgramSet
  25528. {
  25529. long chunkMagic; // 'CcnK'
  25530. long byteSize; // of this chunk, excl. magic + byteSize
  25531. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  25532. long version;
  25533. long fxID; // fx unique id
  25534. long fxVersion;
  25535. long numPrograms;
  25536. char name[28];
  25537. long chunkSize;
  25538. char chunk[8]; // variable
  25539. };
  25540. static long vst_swap (const long x) throw()
  25541. {
  25542. #ifdef JUCE_LITTLE_ENDIAN
  25543. return (long) ByteOrder::swap ((uint32) x);
  25544. #else
  25545. return x;
  25546. #endif
  25547. }
  25548. static float vst_swapFloat (const float x) throw()
  25549. {
  25550. #ifdef JUCE_LITTLE_ENDIAN
  25551. union { uint32 asInt; float asFloat; } n;
  25552. n.asFloat = x;
  25553. n.asInt = ByteOrder::swap (n.asInt);
  25554. return n.asFloat;
  25555. #else
  25556. return x;
  25557. #endif
  25558. }
  25559. typedef AEffect* (*MainCall) (audioMasterCallback);
  25560. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  25561. static int shellUIDToCreate = 0;
  25562. static int insideVSTCallback = 0;
  25563. class VSTPluginWindow;
  25564. // Change this to disable logging of various VST activities
  25565. #ifndef VST_LOGGING
  25566. #define VST_LOGGING 1
  25567. #endif
  25568. #if VST_LOGGING
  25569. #define log(a) Logger::writeToLog(a);
  25570. #else
  25571. #define log(a)
  25572. #endif
  25573. #if JUCE_MAC && JUCE_PPC
  25574. static void* NewCFMFromMachO (void* const machofp) throw()
  25575. {
  25576. void* result = juce_malloc (8);
  25577. ((void**) result)[0] = machofp;
  25578. ((void**) result)[1] = result;
  25579. return result;
  25580. }
  25581. #endif
  25582. #if JUCE_LINUX
  25583. extern Display* display;
  25584. extern XContext windowHandleXContext;
  25585. typedef void (*EventProcPtr) (XEvent* ev);
  25586. static bool xErrorTriggered;
  25587. static int temporaryErrorHandler (Display*, XErrorEvent*)
  25588. {
  25589. xErrorTriggered = true;
  25590. return 0;
  25591. }
  25592. static int getPropertyFromXWindow (Window handle, Atom atom)
  25593. {
  25594. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  25595. xErrorTriggered = false;
  25596. int userSize;
  25597. unsigned long bytes, userCount;
  25598. unsigned char* data;
  25599. Atom userType;
  25600. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  25601. &userType, &userSize, &userCount, &bytes, &data);
  25602. XSetErrorHandler (oldErrorHandler);
  25603. return (userCount == 1 && ! xErrorTriggered) ? *(int*) data
  25604. : 0;
  25605. }
  25606. static Window getChildWindow (Window windowToCheck)
  25607. {
  25608. Window rootWindow, parentWindow;
  25609. Window* childWindows;
  25610. unsigned int numChildren;
  25611. XQueryTree (display,
  25612. windowToCheck,
  25613. &rootWindow,
  25614. &parentWindow,
  25615. &childWindows,
  25616. &numChildren);
  25617. if (numChildren > 0)
  25618. return childWindows [0];
  25619. return 0;
  25620. }
  25621. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  25622. {
  25623. if (e.mods.isLeftButtonDown())
  25624. {
  25625. ev.xbutton.button = Button1;
  25626. ev.xbutton.state |= Button1Mask;
  25627. }
  25628. else if (e.mods.isRightButtonDown())
  25629. {
  25630. ev.xbutton.button = Button3;
  25631. ev.xbutton.state |= Button3Mask;
  25632. }
  25633. else if (e.mods.isMiddleButtonDown())
  25634. {
  25635. ev.xbutton.button = Button2;
  25636. ev.xbutton.state |= Button2Mask;
  25637. }
  25638. }
  25639. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  25640. {
  25641. if (e.mods.isLeftButtonDown())
  25642. ev.xmotion.state |= Button1Mask;
  25643. else if (e.mods.isRightButtonDown())
  25644. ev.xmotion.state |= Button3Mask;
  25645. else if (e.mods.isMiddleButtonDown())
  25646. ev.xmotion.state |= Button2Mask;
  25647. }
  25648. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  25649. {
  25650. if (e.mods.isLeftButtonDown())
  25651. ev.xcrossing.state |= Button1Mask;
  25652. else if (e.mods.isRightButtonDown())
  25653. ev.xcrossing.state |= Button3Mask;
  25654. else if (e.mods.isMiddleButtonDown())
  25655. ev.xcrossing.state |= Button2Mask;
  25656. }
  25657. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  25658. {
  25659. if (increment < 0)
  25660. {
  25661. ev.xbutton.button = Button5;
  25662. ev.xbutton.state |= Button5Mask;
  25663. }
  25664. else if (increment > 0)
  25665. {
  25666. ev.xbutton.button = Button4;
  25667. ev.xbutton.state |= Button4Mask;
  25668. }
  25669. }
  25670. #endif
  25671. static VoidArray activeModules;
  25672. class ModuleHandle : public ReferenceCountedObject
  25673. {
  25674. public:
  25675. File file;
  25676. MainCall moduleMain;
  25677. String pluginName;
  25678. static ModuleHandle* findOrCreateModule (const File& file)
  25679. {
  25680. for (int i = activeModules.size(); --i >= 0;)
  25681. {
  25682. ModuleHandle* const module = (ModuleHandle*) activeModules.getUnchecked(i);
  25683. if (module->file == file)
  25684. return module;
  25685. }
  25686. _fpreset(); // (doesn't do any harm)
  25687. ++insideVSTCallback;
  25688. shellUIDToCreate = 0;
  25689. log ("Attempting to load VST: " + file.getFullPathName());
  25690. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  25691. if (! m->open())
  25692. m = 0;
  25693. --insideVSTCallback;
  25694. _fpreset(); // (doesn't do any harm)
  25695. return m.release();
  25696. }
  25697. ModuleHandle (const File& file_)
  25698. : file (file_),
  25699. moduleMain (0),
  25700. #if JUCE_WIN32 || JUCE_LINUX
  25701. hModule (0)
  25702. #elif JUCE_MAC
  25703. fragId (0),
  25704. resHandle (0),
  25705. bundleRef (0),
  25706. resFileId (0)
  25707. #endif
  25708. {
  25709. activeModules.add (this);
  25710. #if JUCE_WIN32 || JUCE_LINUX
  25711. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  25712. #elif JUCE_MAC
  25713. FSRef ref;
  25714. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  25715. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  25716. #endif
  25717. }
  25718. ~ModuleHandle()
  25719. {
  25720. activeModules.removeValue (this);
  25721. close();
  25722. }
  25723. juce_UseDebuggingNewOperator
  25724. #if JUCE_WIN32 || JUCE_LINUX
  25725. void* hModule;
  25726. String fullParentDirectoryPathName;
  25727. bool open()
  25728. {
  25729. #if JUCE_WIN32
  25730. static bool timePeriodSet = false;
  25731. if (! timePeriodSet)
  25732. {
  25733. timePeriodSet = true;
  25734. timeBeginPeriod (2);
  25735. }
  25736. #endif
  25737. pluginName = file.getFileNameWithoutExtension();
  25738. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  25739. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  25740. if (moduleMain == 0)
  25741. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  25742. return moduleMain != 0;
  25743. }
  25744. void close()
  25745. {
  25746. _fpreset(); // (doesn't do any harm)
  25747. PlatformUtilities::freeDynamicLibrary (hModule);
  25748. }
  25749. void closeEffect (AEffect* eff)
  25750. {
  25751. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25752. }
  25753. #else
  25754. CFragConnectionID fragId;
  25755. Handle resHandle;
  25756. CFBundleRef bundleRef;
  25757. FSSpec parentDirFSSpec;
  25758. short resFileId;
  25759. bool open()
  25760. {
  25761. bool ok = false;
  25762. const String filename (file.getFullPathName());
  25763. if (file.hasFileExtension (".vst"))
  25764. {
  25765. const char* const utf8 = filename.toUTF8();
  25766. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25767. strlen (utf8), file.isDirectory());
  25768. if (url != 0)
  25769. {
  25770. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25771. CFRelease (url);
  25772. if (bundleRef != 0)
  25773. {
  25774. if (CFBundleLoadExecutable (bundleRef))
  25775. {
  25776. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  25777. if (moduleMain == 0)
  25778. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  25779. if (moduleMain != 0)
  25780. {
  25781. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25782. if (name != 0)
  25783. {
  25784. if (CFGetTypeID (name) == CFStringGetTypeID())
  25785. {
  25786. char buffer[1024];
  25787. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  25788. pluginName = buffer;
  25789. }
  25790. }
  25791. if (pluginName.isEmpty())
  25792. pluginName = file.getFileNameWithoutExtension();
  25793. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25794. ok = true;
  25795. }
  25796. }
  25797. if (! ok)
  25798. {
  25799. CFBundleUnloadExecutable (bundleRef);
  25800. CFRelease (bundleRef);
  25801. bundleRef = 0;
  25802. }
  25803. }
  25804. }
  25805. }
  25806. #if JUCE_PPC
  25807. else
  25808. {
  25809. FSRef fn;
  25810. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  25811. {
  25812. resFileId = FSOpenResFile (&fn, fsRdPerm);
  25813. if (resFileId != -1)
  25814. {
  25815. const int numEffs = Count1Resources ('aEff');
  25816. for (int i = 0; i < numEffs; ++i)
  25817. {
  25818. resHandle = Get1IndResource ('aEff', i + 1);
  25819. if (resHandle != 0)
  25820. {
  25821. OSType type;
  25822. Str255 name;
  25823. SInt16 id;
  25824. GetResInfo (resHandle, &id, &type, name);
  25825. pluginName = String ((const char*) name + 1, name[0]);
  25826. DetachResource (resHandle);
  25827. HLock (resHandle);
  25828. Ptr ptr;
  25829. Str255 errorText;
  25830. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  25831. name, kPrivateCFragCopy,
  25832. &fragId, &ptr, errorText);
  25833. if (err == noErr)
  25834. {
  25835. moduleMain = (MainCall) newMachOFromCFM (ptr);
  25836. ok = true;
  25837. }
  25838. else
  25839. {
  25840. HUnlock (resHandle);
  25841. }
  25842. break;
  25843. }
  25844. }
  25845. if (! ok)
  25846. CloseResFile (resFileId);
  25847. }
  25848. }
  25849. }
  25850. #endif
  25851. return ok;
  25852. }
  25853. void close()
  25854. {
  25855. #if JUCE_PPC
  25856. if (fragId != 0)
  25857. {
  25858. if (moduleMain != 0)
  25859. disposeMachOFromCFM ((void*) moduleMain);
  25860. CloseConnection (&fragId);
  25861. HUnlock (resHandle);
  25862. if (resFileId != 0)
  25863. CloseResFile (resFileId);
  25864. }
  25865. else
  25866. #endif
  25867. if (bundleRef != 0)
  25868. {
  25869. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25870. if (CFGetRetainCount (bundleRef) == 1)
  25871. CFBundleUnloadExecutable (bundleRef);
  25872. if (CFGetRetainCount (bundleRef) > 0)
  25873. CFRelease (bundleRef);
  25874. }
  25875. }
  25876. void closeEffect (AEffect* eff)
  25877. {
  25878. #if JUCE_PPC
  25879. if (fragId != 0)
  25880. {
  25881. VoidArray thingsToDelete;
  25882. thingsToDelete.add ((void*) eff->dispatcher);
  25883. thingsToDelete.add ((void*) eff->process);
  25884. thingsToDelete.add ((void*) eff->setParameter);
  25885. thingsToDelete.add ((void*) eff->getParameter);
  25886. thingsToDelete.add ((void*) eff->processReplacing);
  25887. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25888. for (int i = thingsToDelete.size(); --i >= 0;)
  25889. disposeMachOFromCFM (thingsToDelete[i]);
  25890. }
  25891. else
  25892. #endif
  25893. {
  25894. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25895. }
  25896. }
  25897. #if JUCE_PPC
  25898. static void* newMachOFromCFM (void* cfmfp)
  25899. {
  25900. if (cfmfp == 0)
  25901. return 0;
  25902. UInt32* const mfp = new UInt32[6];
  25903. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  25904. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  25905. mfp[2] = 0x800c0000;
  25906. mfp[3] = 0x804c0004;
  25907. mfp[4] = 0x7c0903a6;
  25908. mfp[5] = 0x4e800420;
  25909. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  25910. return mfp;
  25911. }
  25912. static void disposeMachOFromCFM (void* ptr)
  25913. {
  25914. delete[] static_cast <UInt32*> (ptr);
  25915. }
  25916. void coerceAEffectFunctionCalls (AEffect* eff)
  25917. {
  25918. if (fragId != 0)
  25919. {
  25920. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  25921. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  25922. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  25923. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  25924. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  25925. }
  25926. }
  25927. #endif
  25928. #endif
  25929. };
  25930. /**
  25931. An instance of a plugin, created by a VSTPluginFormat.
  25932. */
  25933. class VSTPluginInstance : public AudioPluginInstance,
  25934. private Timer,
  25935. private AsyncUpdater
  25936. {
  25937. public:
  25938. ~VSTPluginInstance();
  25939. // AudioPluginInstance methods:
  25940. void fillInPluginDescription (PluginDescription& desc) const
  25941. {
  25942. desc.name = name;
  25943. desc.fileOrIdentifier = module->file.getFullPathName();
  25944. desc.uid = getUID();
  25945. desc.lastFileModTime = module->file.getLastModificationTime();
  25946. desc.pluginFormatName = "VST";
  25947. desc.category = getCategory();
  25948. {
  25949. char buffer [kVstMaxVendorStrLen + 8];
  25950. zerostruct (buffer);
  25951. dispatch (effGetVendorString, 0, 0, buffer, 0);
  25952. desc.manufacturerName = buffer;
  25953. }
  25954. desc.version = getVersion();
  25955. desc.numInputChannels = getNumInputChannels();
  25956. desc.numOutputChannels = getNumOutputChannels();
  25957. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  25958. }
  25959. const String getName() const { return name; }
  25960. int getUID() const throw();
  25961. bool acceptsMidi() const { return wantsMidiMessages; }
  25962. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  25963. // AudioProcessor methods:
  25964. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25965. void releaseResources();
  25966. void processBlock (AudioSampleBuffer& buffer,
  25967. MidiBuffer& midiMessages);
  25968. AudioProcessorEditor* createEditor();
  25969. const String getInputChannelName (const int index) const;
  25970. bool isInputChannelStereoPair (int index) const;
  25971. const String getOutputChannelName (const int index) const;
  25972. bool isOutputChannelStereoPair (int index) const;
  25973. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  25974. float getParameter (int index);
  25975. void setParameter (int index, float newValue);
  25976. const String getParameterName (int index);
  25977. const String getParameterText (int index);
  25978. bool isParameterAutomatable (int index) const;
  25979. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  25980. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  25981. void setCurrentProgram (int index);
  25982. const String getProgramName (int index);
  25983. void changeProgramName (int index, const String& newName);
  25984. void getStateInformation (MemoryBlock& destData);
  25985. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25986. void setStateInformation (const void* data, int sizeInBytes);
  25987. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25988. void timerCallback();
  25989. void handleAsyncUpdate();
  25990. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  25991. juce_UseDebuggingNewOperator
  25992. private:
  25993. friend class VSTPluginWindow;
  25994. friend class VSTPluginFormat;
  25995. AEffect* effect;
  25996. String name;
  25997. CriticalSection lock;
  25998. bool wantsMidiMessages, initialised, isPowerOn;
  25999. mutable StringArray programNames;
  26000. AudioSampleBuffer tempBuffer;
  26001. CriticalSection midiInLock;
  26002. MidiBuffer incomingMidi;
  26003. VSTMidiEventList midiEventsToSend;
  26004. VstTimeInfo vstHostTime;
  26005. HeapBlock <float*> channels;
  26006. ReferenceCountedObjectPtr <ModuleHandle> module;
  26007. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  26008. bool restoreProgramSettings (const fxProgram* const prog);
  26009. const String getCurrentProgramName();
  26010. void setParamsInProgramBlock (fxProgram* const prog) throw();
  26011. void updateStoredProgramNames();
  26012. void initialise();
  26013. void handleMidiFromPlugin (const VstEvents* const events);
  26014. void createTempParameterStore (MemoryBlock& dest);
  26015. void restoreFromTempParameterStore (const MemoryBlock& mb);
  26016. const String getParameterLabel (int index) const;
  26017. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  26018. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  26019. void setChunkData (const char* data, int size, bool isPreset);
  26020. bool loadFromFXBFile (const void* data, int numBytes);
  26021. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  26022. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  26023. const String getVersion() const throw();
  26024. const String getCategory() const throw();
  26025. bool hasEditor() const throw() { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  26026. void setPower (const bool on);
  26027. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  26028. };
  26029. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  26030. : effect (0),
  26031. wantsMidiMessages (false),
  26032. initialised (false),
  26033. isPowerOn (false),
  26034. tempBuffer (1, 1),
  26035. module (module_)
  26036. {
  26037. try
  26038. {
  26039. _fpreset();
  26040. ++insideVSTCallback;
  26041. name = module->pluginName;
  26042. log ("Creating VST instance: " + name);
  26043. #if JUCE_MAC
  26044. if (module->resFileId != 0)
  26045. UseResFile (module->resFileId);
  26046. #if JUCE_PPC
  26047. if (module->fragId != 0)
  26048. {
  26049. static void* audioMasterCoerced = 0;
  26050. if (audioMasterCoerced == 0)
  26051. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  26052. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  26053. }
  26054. else
  26055. #endif
  26056. #endif
  26057. {
  26058. effect = module->moduleMain (&audioMaster);
  26059. }
  26060. --insideVSTCallback;
  26061. if (effect != 0 && effect->magic == kEffectMagic)
  26062. {
  26063. #if JUCE_PPC
  26064. module->coerceAEffectFunctionCalls (effect);
  26065. #endif
  26066. jassert (effect->resvd2 == 0);
  26067. jassert (effect->object != 0);
  26068. _fpreset(); // some dodgy plugs fuck around with this
  26069. }
  26070. else
  26071. {
  26072. effect = 0;
  26073. }
  26074. }
  26075. catch (...)
  26076. {
  26077. --insideVSTCallback;
  26078. }
  26079. }
  26080. VSTPluginInstance::~VSTPluginInstance()
  26081. {
  26082. {
  26083. const ScopedLock sl (lock);
  26084. jassert (insideVSTCallback == 0);
  26085. if (effect != 0 && effect->magic == kEffectMagic)
  26086. {
  26087. try
  26088. {
  26089. #if JUCE_MAC
  26090. if (module->resFileId != 0)
  26091. UseResFile (module->resFileId);
  26092. #endif
  26093. // Must delete any editors before deleting the plugin instance!
  26094. jassert (getActiveEditor() == 0);
  26095. _fpreset(); // some dodgy plugs fuck around with this
  26096. module->closeEffect (effect);
  26097. }
  26098. catch (...)
  26099. {}
  26100. }
  26101. module = 0;
  26102. effect = 0;
  26103. }
  26104. }
  26105. void VSTPluginInstance::initialise()
  26106. {
  26107. if (initialised || effect == 0)
  26108. return;
  26109. log ("Initialising VST: " + module->pluginName);
  26110. initialised = true;
  26111. dispatch (effIdentify, 0, 0, 0, 0);
  26112. // this code would ask the plugin for its name, but so few plugins
  26113. // actually bother implementing this correctly, that it's better to
  26114. // just ignore it and use the file name instead.
  26115. /* {
  26116. char buffer [256];
  26117. zerostruct (buffer);
  26118. dispatch (effGetEffectName, 0, 0, buffer, 0);
  26119. name = String (buffer).trim();
  26120. if (name.isEmpty())
  26121. name = module->pluginName;
  26122. }
  26123. */
  26124. if (getSampleRate() > 0)
  26125. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  26126. if (getBlockSize() > 0)
  26127. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  26128. dispatch (effOpen, 0, 0, 0, 0);
  26129. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26130. getSampleRate(), getBlockSize());
  26131. if (getNumPrograms() > 1)
  26132. setCurrentProgram (0);
  26133. else
  26134. dispatch (effSetProgram, 0, 0, 0, 0);
  26135. int i;
  26136. for (i = effect->numInputs; --i >= 0;)
  26137. dispatch (effConnectInput, i, 1, 0, 0);
  26138. for (i = effect->numOutputs; --i >= 0;)
  26139. dispatch (effConnectOutput, i, 1, 0, 0);
  26140. updateStoredProgramNames();
  26141. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  26142. setLatencySamples (effect->initialDelay);
  26143. }
  26144. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  26145. int samplesPerBlockExpected)
  26146. {
  26147. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26148. sampleRate_, samplesPerBlockExpected);
  26149. setLatencySamples (effect->initialDelay);
  26150. channels.calloc (jmax (16, getNumOutputChannels(), getNumInputChannels()) + 2);
  26151. vstHostTime.tempo = 120.0;
  26152. vstHostTime.timeSigNumerator = 4;
  26153. vstHostTime.timeSigDenominator = 4;
  26154. vstHostTime.sampleRate = sampleRate_;
  26155. vstHostTime.samplePos = 0;
  26156. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  26157. initialise();
  26158. if (initialised)
  26159. {
  26160. wantsMidiMessages = wantsMidiMessages
  26161. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  26162. if (wantsMidiMessages)
  26163. midiEventsToSend.ensureSize (256);
  26164. else
  26165. midiEventsToSend.freeEvents();
  26166. incomingMidi.clear();
  26167. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  26168. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  26169. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  26170. if (! isPowerOn)
  26171. setPower (true);
  26172. // dodgy hack to force some plugins to initialise the sample rate..
  26173. if ((! hasEditor()) && getNumParameters() > 0)
  26174. {
  26175. const float old = getParameter (0);
  26176. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  26177. setParameter (0, old);
  26178. }
  26179. dispatch (effStartProcess, 0, 0, 0, 0);
  26180. }
  26181. }
  26182. void VSTPluginInstance::releaseResources()
  26183. {
  26184. if (initialised)
  26185. {
  26186. dispatch (effStopProcess, 0, 0, 0, 0);
  26187. setPower (false);
  26188. }
  26189. tempBuffer.setSize (1, 1);
  26190. incomingMidi.clear();
  26191. midiEventsToSend.freeEvents();
  26192. channels.free();
  26193. }
  26194. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  26195. MidiBuffer& midiMessages)
  26196. {
  26197. const int numSamples = buffer.getNumSamples();
  26198. if (initialised)
  26199. {
  26200. AudioPlayHead* playHead = getPlayHead();
  26201. if (playHead != 0)
  26202. {
  26203. AudioPlayHead::CurrentPositionInfo position;
  26204. playHead->getCurrentPosition (position);
  26205. vstHostTime.tempo = position.bpm;
  26206. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  26207. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  26208. vstHostTime.ppqPos = position.ppqPosition;
  26209. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  26210. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  26211. if (position.isPlaying)
  26212. vstHostTime.flags |= kVstTransportPlaying;
  26213. else
  26214. vstHostTime.flags &= ~kVstTransportPlaying;
  26215. }
  26216. #if JUCE_WIN32
  26217. vstHostTime.nanoSeconds = timeGetTime() * 1000000.0;
  26218. #elif JUCE_LINUX
  26219. timeval micro;
  26220. gettimeofday (&micro, 0);
  26221. vstHostTime.nanoSeconds = micro.tv_usec * 1000.0;
  26222. #elif JUCE_MAC
  26223. UnsignedWide micro;
  26224. Microseconds (&micro);
  26225. vstHostTime.nanoSeconds = micro.lo * 1000.0;
  26226. #endif
  26227. if (wantsMidiMessages)
  26228. {
  26229. midiEventsToSend.clear();
  26230. midiEventsToSend.ensureSize (1);
  26231. MidiBuffer::Iterator iter (midiMessages);
  26232. const uint8* midiData;
  26233. int numBytesOfMidiData, samplePosition;
  26234. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  26235. {
  26236. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  26237. jlimit (0, numSamples - 1, samplePosition));
  26238. }
  26239. try
  26240. {
  26241. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  26242. }
  26243. catch (...)
  26244. {}
  26245. }
  26246. int i;
  26247. const int maxChans = jmax (effect->numInputs, effect->numOutputs);
  26248. for (i = 0; i < maxChans; ++i)
  26249. channels[i] = buffer.getSampleData (i);
  26250. channels [maxChans] = 0;
  26251. _clearfp();
  26252. if ((effect->flags & effFlagsCanReplacing) != 0)
  26253. {
  26254. try
  26255. {
  26256. effect->processReplacing (effect, channels, channels, numSamples);
  26257. }
  26258. catch (...)
  26259. {}
  26260. }
  26261. else
  26262. {
  26263. tempBuffer.setSize (effect->numOutputs, numSamples);
  26264. tempBuffer.clear();
  26265. float* outs [64];
  26266. for (i = effect->numOutputs; --i >= 0;)
  26267. outs[i] = tempBuffer.getSampleData (i);
  26268. outs [effect->numOutputs] = 0;
  26269. try
  26270. {
  26271. effect->process (effect, channels, outs, numSamples);
  26272. }
  26273. catch (...)
  26274. {}
  26275. for (i = effect->numOutputs; --i >= 0;)
  26276. buffer.copyFrom (i, 0, outs[i], numSamples);
  26277. }
  26278. }
  26279. else
  26280. {
  26281. // Not initialised, so just bypass..
  26282. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  26283. buffer.clear (i, 0, buffer.getNumSamples());
  26284. }
  26285. {
  26286. // copy any incoming midi..
  26287. const ScopedLock sl (midiInLock);
  26288. midiMessages.swapWith (incomingMidi);
  26289. incomingMidi.clear();
  26290. }
  26291. }
  26292. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  26293. {
  26294. if (events != 0)
  26295. {
  26296. const ScopedLock sl (midiInLock);
  26297. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  26298. }
  26299. }
  26300. static Array <VSTPluginWindow*> activeVSTWindows;
  26301. class VSTPluginWindow : public AudioProcessorEditor,
  26302. #if ! JUCE_MAC
  26303. public ComponentMovementWatcher,
  26304. #endif
  26305. public Timer
  26306. {
  26307. public:
  26308. VSTPluginWindow (VSTPluginInstance& plugin_)
  26309. : AudioProcessorEditor (&plugin_),
  26310. #if ! JUCE_MAC
  26311. ComponentMovementWatcher (this),
  26312. #endif
  26313. plugin (plugin_),
  26314. isOpen (false),
  26315. wasShowing (false),
  26316. pluginRefusesToResize (false),
  26317. pluginWantsKeys (false),
  26318. alreadyInside (false),
  26319. recursiveResize (false)
  26320. {
  26321. #if JUCE_WIN32
  26322. sizeCheckCount = 0;
  26323. pluginHWND = 0;
  26324. #elif JUCE_LINUX
  26325. pluginWindow = None;
  26326. pluginProc = None;
  26327. #else
  26328. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  26329. #endif
  26330. activeVSTWindows.add (this);
  26331. setSize (1, 1);
  26332. setOpaque (true);
  26333. setVisible (true);
  26334. }
  26335. ~VSTPluginWindow()
  26336. {
  26337. #if JUCE_MAC
  26338. innerWrapper = 0;
  26339. #else
  26340. closePluginWindow();
  26341. #endif
  26342. activeVSTWindows.removeValue (this);
  26343. plugin.editorBeingDeleted (this);
  26344. }
  26345. #if ! JUCE_MAC
  26346. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  26347. {
  26348. if (recursiveResize)
  26349. return;
  26350. Component* const topComp = getTopLevelComponent();
  26351. if (topComp->getPeer() != 0)
  26352. {
  26353. const Point<int> pos (relativePositionToOtherComponent (topComp, Point<int>()));
  26354. recursiveResize = true;
  26355. #if JUCE_WIN32
  26356. if (pluginHWND != 0)
  26357. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  26358. #elif JUCE_LINUX
  26359. if (pluginWindow != 0)
  26360. {
  26361. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  26362. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  26363. XMapRaised (display, pluginWindow);
  26364. }
  26365. #endif
  26366. recursiveResize = false;
  26367. }
  26368. }
  26369. void componentVisibilityChanged (Component&)
  26370. {
  26371. const bool isShowingNow = isShowing();
  26372. if (wasShowing != isShowingNow)
  26373. {
  26374. wasShowing = isShowingNow;
  26375. if (isShowingNow)
  26376. openPluginWindow();
  26377. else
  26378. closePluginWindow();
  26379. }
  26380. componentMovedOrResized (true, true);
  26381. }
  26382. void componentPeerChanged()
  26383. {
  26384. closePluginWindow();
  26385. openPluginWindow();
  26386. }
  26387. #endif
  26388. bool keyStateChanged (bool)
  26389. {
  26390. return pluginWantsKeys;
  26391. }
  26392. bool keyPressed (const KeyPress&)
  26393. {
  26394. return pluginWantsKeys;
  26395. }
  26396. #if JUCE_MAC
  26397. void paint (Graphics& g)
  26398. {
  26399. g.fillAll (Colours::black);
  26400. }
  26401. #else
  26402. void paint (Graphics& g)
  26403. {
  26404. if (isOpen)
  26405. {
  26406. ComponentPeer* const peer = getPeer();
  26407. if (peer != 0)
  26408. {
  26409. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  26410. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  26411. #if JUCE_LINUX
  26412. if (pluginWindow != 0)
  26413. {
  26414. const Rectangle<int> clip (g.getClipBounds());
  26415. XEvent ev;
  26416. zerostruct (ev);
  26417. ev.xexpose.type = Expose;
  26418. ev.xexpose.display = display;
  26419. ev.xexpose.window = pluginWindow;
  26420. ev.xexpose.x = clip.getX();
  26421. ev.xexpose.y = clip.getY();
  26422. ev.xexpose.width = clip.getWidth();
  26423. ev.xexpose.height = clip.getHeight();
  26424. sendEventToChild (&ev);
  26425. }
  26426. #endif
  26427. }
  26428. }
  26429. else
  26430. {
  26431. g.fillAll (Colours::black);
  26432. }
  26433. }
  26434. #endif
  26435. void timerCallback()
  26436. {
  26437. #if JUCE_WIN32
  26438. if (--sizeCheckCount <= 0)
  26439. {
  26440. sizeCheckCount = 10;
  26441. checkPluginWindowSize();
  26442. }
  26443. #endif
  26444. try
  26445. {
  26446. static bool reentrant = false;
  26447. if (! reentrant)
  26448. {
  26449. reentrant = true;
  26450. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  26451. reentrant = false;
  26452. }
  26453. }
  26454. catch (...)
  26455. {}
  26456. }
  26457. void mouseDown (const MouseEvent& e)
  26458. {
  26459. #if JUCE_LINUX
  26460. if (pluginWindow == 0)
  26461. return;
  26462. toFront (true);
  26463. XEvent ev;
  26464. zerostruct (ev);
  26465. ev.xbutton.display = display;
  26466. ev.xbutton.type = ButtonPress;
  26467. ev.xbutton.window = pluginWindow;
  26468. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26469. ev.xbutton.time = CurrentTime;
  26470. ev.xbutton.x = e.x;
  26471. ev.xbutton.y = e.y;
  26472. ev.xbutton.x_root = e.getScreenX();
  26473. ev.xbutton.y_root = e.getScreenY();
  26474. translateJuceToXButtonModifiers (e, ev);
  26475. sendEventToChild (&ev);
  26476. #elif JUCE_WIN32
  26477. (void) e;
  26478. toFront (true);
  26479. #endif
  26480. }
  26481. void broughtToFront()
  26482. {
  26483. activeVSTWindows.removeValue (this);
  26484. activeVSTWindows.add (this);
  26485. #if JUCE_MAC
  26486. dispatch (effEditTop, 0, 0, 0, 0);
  26487. #endif
  26488. }
  26489. juce_UseDebuggingNewOperator
  26490. private:
  26491. VSTPluginInstance& plugin;
  26492. bool isOpen, wasShowing, recursiveResize;
  26493. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  26494. #if JUCE_WIN32
  26495. HWND pluginHWND;
  26496. void* originalWndProc;
  26497. int sizeCheckCount;
  26498. #elif JUCE_LINUX
  26499. Window pluginWindow;
  26500. EventProcPtr pluginProc;
  26501. #endif
  26502. #if JUCE_MAC
  26503. void openPluginWindow (WindowRef parentWindow)
  26504. {
  26505. if (isOpen || parentWindow == 0)
  26506. return;
  26507. isOpen = true;
  26508. ERect* rect = 0;
  26509. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26510. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  26511. // do this before and after like in the steinberg example
  26512. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26513. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  26514. // Install keyboard hooks
  26515. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  26516. // double-check it's not too tiny
  26517. int w = 250, h = 150;
  26518. if (rect != 0)
  26519. {
  26520. w = rect->right - rect->left;
  26521. h = rect->bottom - rect->top;
  26522. if (w == 0 || h == 0)
  26523. {
  26524. w = 250;
  26525. h = 150;
  26526. }
  26527. }
  26528. w = jmax (w, 32);
  26529. h = jmax (h, 32);
  26530. setSize (w, h);
  26531. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  26532. repaint();
  26533. }
  26534. #else
  26535. void openPluginWindow()
  26536. {
  26537. if (isOpen || getWindowHandle() == 0)
  26538. return;
  26539. log ("Opening VST UI: " + plugin.name);
  26540. isOpen = true;
  26541. ERect* rect = 0;
  26542. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26543. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  26544. // do this before and after like in the steinberg example
  26545. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26546. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  26547. // Install keyboard hooks
  26548. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  26549. #if JUCE_WIN32
  26550. originalWndProc = 0;
  26551. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  26552. if (pluginHWND == 0)
  26553. {
  26554. isOpen = false;
  26555. setSize (300, 150);
  26556. return;
  26557. }
  26558. #pragma warning (push)
  26559. #pragma warning (disable: 4244)
  26560. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWL_WNDPROC);
  26561. if (! pluginWantsKeys)
  26562. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  26563. #pragma warning (pop)
  26564. int w, h;
  26565. RECT r;
  26566. GetWindowRect (pluginHWND, &r);
  26567. w = r.right - r.left;
  26568. h = r.bottom - r.top;
  26569. if (rect != 0)
  26570. {
  26571. const int rw = rect->right - rect->left;
  26572. const int rh = rect->bottom - rect->top;
  26573. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  26574. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  26575. {
  26576. // very dodgy logic to decide which size is right.
  26577. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  26578. {
  26579. SetWindowPos (pluginHWND, 0,
  26580. 0, 0, rw, rh,
  26581. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  26582. GetWindowRect (pluginHWND, &r);
  26583. w = r.right - r.left;
  26584. h = r.bottom - r.top;
  26585. pluginRefusesToResize = (w != rw) || (h != rh);
  26586. w = rw;
  26587. h = rh;
  26588. }
  26589. }
  26590. }
  26591. #elif JUCE_LINUX
  26592. pluginWindow = getChildWindow ((Window) getWindowHandle());
  26593. if (pluginWindow != 0)
  26594. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  26595. XInternAtom (display, "_XEventProc", False));
  26596. int w = 250, h = 150;
  26597. if (rect != 0)
  26598. {
  26599. w = rect->right - rect->left;
  26600. h = rect->bottom - rect->top;
  26601. if (w == 0 || h == 0)
  26602. {
  26603. w = 250;
  26604. h = 150;
  26605. }
  26606. }
  26607. if (pluginWindow != 0)
  26608. XMapRaised (display, pluginWindow);
  26609. #endif
  26610. // double-check it's not too tiny
  26611. w = jmax (w, 32);
  26612. h = jmax (h, 32);
  26613. setSize (w, h);
  26614. #if JUCE_WIN32
  26615. checkPluginWindowSize();
  26616. #endif
  26617. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  26618. repaint();
  26619. }
  26620. #endif
  26621. #if ! JUCE_MAC
  26622. void closePluginWindow()
  26623. {
  26624. if (isOpen)
  26625. {
  26626. log ("Closing VST UI: " + plugin.getName());
  26627. isOpen = false;
  26628. dispatch (effEditClose, 0, 0, 0, 0);
  26629. #if JUCE_WIN32
  26630. #pragma warning (push)
  26631. #pragma warning (disable: 4244)
  26632. if (pluginHWND != 0 && IsWindow (pluginHWND))
  26633. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  26634. #pragma warning (pop)
  26635. stopTimer();
  26636. if (pluginHWND != 0 && IsWindow (pluginHWND))
  26637. DestroyWindow (pluginHWND);
  26638. pluginHWND = 0;
  26639. #elif JUCE_LINUX
  26640. stopTimer();
  26641. pluginWindow = 0;
  26642. pluginProc = 0;
  26643. #endif
  26644. }
  26645. }
  26646. #endif
  26647. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  26648. {
  26649. return plugin.dispatch (opcode, index, value, ptr, opt);
  26650. }
  26651. #if JUCE_WIN32
  26652. void checkPluginWindowSize() throw()
  26653. {
  26654. RECT r;
  26655. GetWindowRect (pluginHWND, &r);
  26656. const int w = r.right - r.left;
  26657. const int h = r.bottom - r.top;
  26658. if (isShowing() && w > 0 && h > 0
  26659. && (w != getWidth() || h != getHeight())
  26660. && ! pluginRefusesToResize)
  26661. {
  26662. setSize (w, h);
  26663. sizeCheckCount = 0;
  26664. }
  26665. }
  26666. // hooks to get keyboard events from VST windows..
  26667. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  26668. {
  26669. for (int i = activeVSTWindows.size(); --i >= 0;)
  26670. {
  26671. const VSTPluginWindow* const w = (const VSTPluginWindow*) activeVSTWindows.getUnchecked (i);
  26672. if (w->pluginHWND == hW)
  26673. {
  26674. if (message == WM_CHAR
  26675. || message == WM_KEYDOWN
  26676. || message == WM_SYSKEYDOWN
  26677. || message == WM_KEYUP
  26678. || message == WM_SYSKEYUP
  26679. || message == WM_APPCOMMAND)
  26680. {
  26681. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  26682. message, wParam, lParam);
  26683. }
  26684. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  26685. (HWND) w->pluginHWND,
  26686. message,
  26687. wParam,
  26688. lParam);
  26689. }
  26690. }
  26691. return DefWindowProc (hW, message, wParam, lParam);
  26692. }
  26693. #endif
  26694. #if JUCE_LINUX
  26695. // overload mouse/keyboard events to forward them to the plugin's inner window..
  26696. void sendEventToChild (XEvent* event)
  26697. {
  26698. if (pluginProc != 0)
  26699. {
  26700. // if the plugin publishes an event procedure, pass the event directly..
  26701. pluginProc (event);
  26702. }
  26703. else if (pluginWindow != 0)
  26704. {
  26705. // if the plugin has a window, then send the event to the window so that
  26706. // its message thread will pick it up..
  26707. XSendEvent (display, pluginWindow, False, 0L, event);
  26708. XFlush (display);
  26709. }
  26710. }
  26711. void mouseEnter (const MouseEvent& e)
  26712. {
  26713. if (pluginWindow != 0)
  26714. {
  26715. XEvent ev;
  26716. zerostruct (ev);
  26717. ev.xcrossing.display = display;
  26718. ev.xcrossing.type = EnterNotify;
  26719. ev.xcrossing.window = pluginWindow;
  26720. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26721. ev.xcrossing.time = CurrentTime;
  26722. ev.xcrossing.x = e.x;
  26723. ev.xcrossing.y = e.y;
  26724. ev.xcrossing.x_root = e.getScreenX();
  26725. ev.xcrossing.y_root = e.getScreenY();
  26726. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26727. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26728. translateJuceToXCrossingModifiers (e, ev);
  26729. sendEventToChild (&ev);
  26730. }
  26731. }
  26732. void mouseExit (const MouseEvent& e)
  26733. {
  26734. if (pluginWindow != 0)
  26735. {
  26736. XEvent ev;
  26737. zerostruct (ev);
  26738. ev.xcrossing.display = display;
  26739. ev.xcrossing.type = LeaveNotify;
  26740. ev.xcrossing.window = pluginWindow;
  26741. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26742. ev.xcrossing.time = CurrentTime;
  26743. ev.xcrossing.x = e.x;
  26744. ev.xcrossing.y = e.y;
  26745. ev.xcrossing.x_root = e.getScreenX();
  26746. ev.xcrossing.y_root = e.getScreenY();
  26747. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26748. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26749. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  26750. translateJuceToXCrossingModifiers (e, ev);
  26751. sendEventToChild (&ev);
  26752. }
  26753. }
  26754. void mouseMove (const MouseEvent& e)
  26755. {
  26756. if (pluginWindow != 0)
  26757. {
  26758. XEvent ev;
  26759. zerostruct (ev);
  26760. ev.xmotion.display = display;
  26761. ev.xmotion.type = MotionNotify;
  26762. ev.xmotion.window = pluginWindow;
  26763. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26764. ev.xmotion.time = CurrentTime;
  26765. ev.xmotion.is_hint = NotifyNormal;
  26766. ev.xmotion.x = e.x;
  26767. ev.xmotion.y = e.y;
  26768. ev.xmotion.x_root = e.getScreenX();
  26769. ev.xmotion.y_root = e.getScreenY();
  26770. sendEventToChild (&ev);
  26771. }
  26772. }
  26773. void mouseDrag (const MouseEvent& e)
  26774. {
  26775. if (pluginWindow != 0)
  26776. {
  26777. XEvent ev;
  26778. zerostruct (ev);
  26779. ev.xmotion.display = display;
  26780. ev.xmotion.type = MotionNotify;
  26781. ev.xmotion.window = pluginWindow;
  26782. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26783. ev.xmotion.time = CurrentTime;
  26784. ev.xmotion.x = e.x ;
  26785. ev.xmotion.y = e.y;
  26786. ev.xmotion.x_root = e.getScreenX();
  26787. ev.xmotion.y_root = e.getScreenY();
  26788. ev.xmotion.is_hint = NotifyNormal;
  26789. translateJuceToXMotionModifiers (e, ev);
  26790. sendEventToChild (&ev);
  26791. }
  26792. }
  26793. void mouseUp (const MouseEvent& e)
  26794. {
  26795. if (pluginWindow != 0)
  26796. {
  26797. XEvent ev;
  26798. zerostruct (ev);
  26799. ev.xbutton.display = display;
  26800. ev.xbutton.type = ButtonRelease;
  26801. ev.xbutton.window = pluginWindow;
  26802. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26803. ev.xbutton.time = CurrentTime;
  26804. ev.xbutton.x = e.x;
  26805. ev.xbutton.y = e.y;
  26806. ev.xbutton.x_root = e.getScreenX();
  26807. ev.xbutton.y_root = e.getScreenY();
  26808. translateJuceToXButtonModifiers (e, ev);
  26809. sendEventToChild (&ev);
  26810. }
  26811. }
  26812. void mouseWheelMove (const MouseEvent& e,
  26813. float incrementX,
  26814. float incrementY)
  26815. {
  26816. if (pluginWindow != 0)
  26817. {
  26818. XEvent ev;
  26819. zerostruct (ev);
  26820. ev.xbutton.display = display;
  26821. ev.xbutton.type = ButtonPress;
  26822. ev.xbutton.window = pluginWindow;
  26823. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26824. ev.xbutton.time = CurrentTime;
  26825. ev.xbutton.x = e.x;
  26826. ev.xbutton.y = e.y;
  26827. ev.xbutton.x_root = e.getScreenX();
  26828. ev.xbutton.y_root = e.getScreenY();
  26829. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  26830. sendEventToChild (&ev);
  26831. // TODO - put a usleep here ?
  26832. ev.xbutton.type = ButtonRelease;
  26833. sendEventToChild (&ev);
  26834. }
  26835. }
  26836. #endif
  26837. #if JUCE_MAC
  26838. #if ! JUCE_SUPPORT_CARBON
  26839. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  26840. #endif
  26841. class InnerWrapperComponent : public CarbonViewWrapperComponent
  26842. {
  26843. public:
  26844. InnerWrapperComponent (VSTPluginWindow* const owner_)
  26845. : owner (owner_),
  26846. alreadyInside (false)
  26847. {
  26848. }
  26849. ~InnerWrapperComponent()
  26850. {
  26851. deleteWindow();
  26852. }
  26853. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  26854. {
  26855. owner->openPluginWindow (windowRef);
  26856. return 0;
  26857. }
  26858. void removeView (HIViewRef)
  26859. {
  26860. owner->dispatch (effEditClose, 0, 0, 0, 0);
  26861. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  26862. }
  26863. bool getEmbeddedViewSize (int& w, int& h)
  26864. {
  26865. ERect* rect = 0;
  26866. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  26867. w = rect->right - rect->left;
  26868. h = rect->bottom - rect->top;
  26869. return true;
  26870. }
  26871. void mouseDown (int x, int y)
  26872. {
  26873. if (! alreadyInside)
  26874. {
  26875. alreadyInside = true;
  26876. getTopLevelComponent()->toFront (true);
  26877. owner->dispatch (effEditMouse, x, y, 0, 0);
  26878. alreadyInside = false;
  26879. }
  26880. else
  26881. {
  26882. PostEvent (::mouseDown, 0);
  26883. }
  26884. }
  26885. void paint()
  26886. {
  26887. ComponentPeer* const peer = getPeer();
  26888. if (peer != 0)
  26889. {
  26890. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  26891. ERect r;
  26892. r.left = pos.getX();
  26893. r.right = r.left + getWidth();
  26894. r.top = pos.getY();
  26895. r.bottom = r.top + getHeight();
  26896. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  26897. }
  26898. }
  26899. private:
  26900. VSTPluginWindow* const owner;
  26901. bool alreadyInside;
  26902. };
  26903. friend class InnerWrapperComponent;
  26904. ScopedPointer <InnerWrapperComponent> innerWrapper;
  26905. void resized()
  26906. {
  26907. innerWrapper->setSize (getWidth(), getHeight());
  26908. }
  26909. #endif
  26910. };
  26911. AudioProcessorEditor* VSTPluginInstance::createEditor()
  26912. {
  26913. if (hasEditor())
  26914. return new VSTPluginWindow (*this);
  26915. return 0;
  26916. }
  26917. void VSTPluginInstance::handleAsyncUpdate()
  26918. {
  26919. // indicates that something about the plugin has changed..
  26920. updateHostDisplay();
  26921. }
  26922. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  26923. {
  26924. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  26925. {
  26926. changeProgramName (getCurrentProgram(), prog->prgName);
  26927. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26928. setParameter (i, vst_swapFloat (prog->params[i]));
  26929. return true;
  26930. }
  26931. return false;
  26932. }
  26933. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  26934. const int dataSize)
  26935. {
  26936. if (dataSize < 28)
  26937. return false;
  26938. const fxSet* const set = (const fxSet*) data;
  26939. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  26940. || vst_swap (set->version) > fxbVersionNum)
  26941. return false;
  26942. if (vst_swap (set->fxMagic) == 'FxBk')
  26943. {
  26944. // bank of programs
  26945. if (vst_swap (set->numPrograms) >= 0)
  26946. {
  26947. const int oldProg = getCurrentProgram();
  26948. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  26949. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  26950. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  26951. {
  26952. if (i != oldProg)
  26953. {
  26954. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  26955. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26956. return false;
  26957. if (vst_swap (set->numPrograms) > 0)
  26958. setCurrentProgram (i);
  26959. if (! restoreProgramSettings (prog))
  26960. return false;
  26961. }
  26962. }
  26963. if (vst_swap (set->numPrograms) > 0)
  26964. setCurrentProgram (oldProg);
  26965. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  26966. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26967. return false;
  26968. if (! restoreProgramSettings (prog))
  26969. return false;
  26970. }
  26971. }
  26972. else if (vst_swap (set->fxMagic) == 'FxCk')
  26973. {
  26974. // single program
  26975. const fxProgram* const prog = (const fxProgram*) data;
  26976. if (vst_swap (prog->chunkMagic) != 'CcnK')
  26977. return false;
  26978. changeProgramName (getCurrentProgram(), prog->prgName);
  26979. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26980. setParameter (i, vst_swapFloat (prog->params[i]));
  26981. }
  26982. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  26983. {
  26984. // non-preset chunk
  26985. const fxChunkSet* const cset = (const fxChunkSet*) data;
  26986. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  26987. return false;
  26988. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  26989. }
  26990. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  26991. {
  26992. // preset chunk
  26993. const fxProgramSet* const cset = (const fxProgramSet*) data;
  26994. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  26995. return false;
  26996. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  26997. changeProgramName (getCurrentProgram(), cset->name);
  26998. }
  26999. else
  27000. {
  27001. return false;
  27002. }
  27003. return true;
  27004. }
  27005. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog) throw()
  27006. {
  27007. const int numParams = getNumParameters();
  27008. prog->chunkMagic = vst_swap ('CcnK');
  27009. prog->byteSize = 0;
  27010. prog->fxMagic = vst_swap ('FxCk');
  27011. prog->version = vst_swap (fxbVersionNum);
  27012. prog->fxID = vst_swap (getUID());
  27013. prog->fxVersion = vst_swap (getVersionNumber());
  27014. prog->numParams = vst_swap (numParams);
  27015. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  27016. for (int i = 0; i < numParams; ++i)
  27017. prog->params[i] = vst_swapFloat (getParameter (i));
  27018. }
  27019. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  27020. {
  27021. const int numPrograms = getNumPrograms();
  27022. const int numParams = getNumParameters();
  27023. if (usesChunks())
  27024. {
  27025. if (isFXB)
  27026. {
  27027. MemoryBlock chunk;
  27028. getChunkData (chunk, false, maxSizeMB);
  27029. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  27030. dest.setSize (totalLen, true);
  27031. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  27032. set->chunkMagic = vst_swap ('CcnK');
  27033. set->byteSize = 0;
  27034. set->fxMagic = vst_swap ('FBCh');
  27035. set->version = vst_swap (fxbVersionNum);
  27036. set->fxID = vst_swap (getUID());
  27037. set->fxVersion = vst_swap (getVersionNumber());
  27038. set->numPrograms = vst_swap (numPrograms);
  27039. set->chunkSize = vst_swap ((long) chunk.getSize());
  27040. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27041. }
  27042. else
  27043. {
  27044. MemoryBlock chunk;
  27045. getChunkData (chunk, true, maxSizeMB);
  27046. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  27047. dest.setSize (totalLen, true);
  27048. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  27049. set->chunkMagic = vst_swap ('CcnK');
  27050. set->byteSize = 0;
  27051. set->fxMagic = vst_swap ('FPCh');
  27052. set->version = vst_swap (fxbVersionNum);
  27053. set->fxID = vst_swap (getUID());
  27054. set->fxVersion = vst_swap (getVersionNumber());
  27055. set->numPrograms = vst_swap (numPrograms);
  27056. set->chunkSize = vst_swap ((long) chunk.getSize());
  27057. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  27058. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27059. }
  27060. }
  27061. else
  27062. {
  27063. if (isFXB)
  27064. {
  27065. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27066. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  27067. dest.setSize (len, true);
  27068. fxSet* const set = (fxSet*) dest.getData();
  27069. set->chunkMagic = vst_swap ('CcnK');
  27070. set->byteSize = 0;
  27071. set->fxMagic = vst_swap ('FxBk');
  27072. set->version = vst_swap (fxbVersionNum);
  27073. set->fxID = vst_swap (getUID());
  27074. set->fxVersion = vst_swap (getVersionNumber());
  27075. set->numPrograms = vst_swap (numPrograms);
  27076. const int oldProgram = getCurrentProgram();
  27077. MemoryBlock oldSettings;
  27078. createTempParameterStore (oldSettings);
  27079. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  27080. for (int i = 0; i < numPrograms; ++i)
  27081. {
  27082. if (i != oldProgram)
  27083. {
  27084. setCurrentProgram (i);
  27085. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  27086. }
  27087. }
  27088. setCurrentProgram (oldProgram);
  27089. restoreFromTempParameterStore (oldSettings);
  27090. }
  27091. else
  27092. {
  27093. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27094. dest.setSize (totalLen, true);
  27095. setParamsInProgramBlock ((fxProgram*) dest.getData());
  27096. }
  27097. }
  27098. return true;
  27099. }
  27100. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  27101. {
  27102. if (usesChunks())
  27103. {
  27104. void* data = 0;
  27105. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  27106. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  27107. {
  27108. mb.setSize (bytes);
  27109. mb.copyFrom (data, 0, bytes);
  27110. }
  27111. }
  27112. }
  27113. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  27114. {
  27115. if (size > 0 && usesChunks())
  27116. {
  27117. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  27118. if (! isPreset)
  27119. updateStoredProgramNames();
  27120. }
  27121. }
  27122. void VSTPluginInstance::timerCallback()
  27123. {
  27124. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  27125. stopTimer();
  27126. }
  27127. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  27128. {
  27129. const ScopedLock sl (lock);
  27130. ++insideVSTCallback;
  27131. int result = 0;
  27132. try
  27133. {
  27134. if (effect != 0)
  27135. {
  27136. #if JUCE_MAC
  27137. if (module->resFileId != 0)
  27138. UseResFile (module->resFileId);
  27139. CGrafPtr oldPort;
  27140. if (getActiveEditor() != 0)
  27141. {
  27142. const Point<int> pos (getActiveEditor()->relativePositionToOtherComponent (getActiveEditor()->getTopLevelComponent(), Point<int>()));
  27143. GetPort (&oldPort);
  27144. SetPortWindowPort ((WindowRef) getActiveEditor()->getWindowHandle());
  27145. SetOrigin (-pos.getX(), -pos.getY());
  27146. }
  27147. #endif
  27148. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  27149. #if JUCE_MAC
  27150. if (getActiveEditor() != 0)
  27151. SetPort (oldPort);
  27152. module->resFileId = CurResFile();
  27153. #endif
  27154. --insideVSTCallback;
  27155. return result;
  27156. }
  27157. }
  27158. catch (...)
  27159. {
  27160. }
  27161. --insideVSTCallback;
  27162. return result;
  27163. }
  27164. // handles non plugin-specific callbacks..
  27165. static const int defaultVSTSampleRateValue = 16384;
  27166. static const int defaultVSTBlockSizeValue = 512;
  27167. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27168. {
  27169. (void) index;
  27170. (void) value;
  27171. (void) opt;
  27172. switch (opcode)
  27173. {
  27174. case audioMasterCanDo:
  27175. {
  27176. static const char* canDos[] = { "supplyIdle",
  27177. "sendVstEvents",
  27178. "sendVstMidiEvent",
  27179. "sendVstTimeInfo",
  27180. "receiveVstEvents",
  27181. "receiveVstMidiEvent",
  27182. "supportShell",
  27183. "shellCategory" };
  27184. for (int i = 0; i < numElementsInArray (canDos); ++i)
  27185. if (strcmp (canDos[i], (const char*) ptr) == 0)
  27186. return 1;
  27187. return 0;
  27188. }
  27189. case audioMasterVersion:
  27190. return 0x2400;
  27191. case audioMasterCurrentId:
  27192. return shellUIDToCreate;
  27193. case audioMasterGetNumAutomatableParameters:
  27194. return 0;
  27195. case audioMasterGetAutomationState:
  27196. return 1;
  27197. case audioMasterGetVendorVersion:
  27198. return 0x0101;
  27199. case audioMasterGetVendorString:
  27200. case audioMasterGetProductString:
  27201. {
  27202. String hostName ("Juce VST Host");
  27203. if (JUCEApplication::getInstance() != 0)
  27204. hostName = JUCEApplication::getInstance()->getApplicationName();
  27205. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  27206. }
  27207. break;
  27208. case audioMasterGetSampleRate:
  27209. return (VstIntPtr) defaultVSTSampleRateValue;
  27210. case audioMasterGetBlockSize:
  27211. return (VstIntPtr) defaultVSTBlockSizeValue;
  27212. case audioMasterSetOutputSampleRate:
  27213. return 0;
  27214. default:
  27215. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  27216. break;
  27217. }
  27218. return 0;
  27219. }
  27220. // handles callbacks for a specific plugin
  27221. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27222. {
  27223. switch (opcode)
  27224. {
  27225. case audioMasterAutomate:
  27226. sendParamChangeMessageToListeners (index, opt);
  27227. break;
  27228. case audioMasterProcessEvents:
  27229. handleMidiFromPlugin ((const VstEvents*) ptr);
  27230. break;
  27231. case audioMasterGetTime:
  27232. #if JUCE_MSVC
  27233. #pragma warning (push)
  27234. #pragma warning (disable: 4311)
  27235. #endif
  27236. return (VstIntPtr) &vstHostTime;
  27237. #if JUCE_MSVC
  27238. #pragma warning (pop)
  27239. #endif
  27240. break;
  27241. case audioMasterIdle:
  27242. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  27243. {
  27244. ++insideVSTCallback;
  27245. #if JUCE_MAC
  27246. if (getActiveEditor() != 0)
  27247. dispatch (effEditIdle, 0, 0, 0, 0);
  27248. #endif
  27249. juce_callAnyTimersSynchronously();
  27250. handleUpdateNowIfNeeded();
  27251. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  27252. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  27253. --insideVSTCallback;
  27254. }
  27255. break;
  27256. case audioMasterUpdateDisplay:
  27257. triggerAsyncUpdate();
  27258. break;
  27259. case audioMasterTempoAt:
  27260. // returns (10000 * bpm)
  27261. break;
  27262. case audioMasterNeedIdle:
  27263. startTimer (50);
  27264. break;
  27265. case audioMasterSizeWindow:
  27266. if (getActiveEditor() != 0)
  27267. getActiveEditor()->setSize (index, value);
  27268. return 1;
  27269. case audioMasterGetSampleRate:
  27270. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  27271. case audioMasterGetBlockSize:
  27272. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  27273. case audioMasterWantMidi:
  27274. wantsMidiMessages = true;
  27275. break;
  27276. case audioMasterGetDirectory:
  27277. #if JUCE_MAC
  27278. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  27279. #else
  27280. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8();
  27281. #endif
  27282. case audioMasterGetAutomationState:
  27283. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  27284. break;
  27285. // none of these are handled (yet)..
  27286. case audioMasterBeginEdit:
  27287. case audioMasterEndEdit:
  27288. case audioMasterSetTime:
  27289. case audioMasterPinConnected:
  27290. case audioMasterGetParameterQuantization:
  27291. case audioMasterIOChanged:
  27292. case audioMasterGetInputLatency:
  27293. case audioMasterGetOutputLatency:
  27294. case audioMasterGetPreviousPlug:
  27295. case audioMasterGetNextPlug:
  27296. case audioMasterWillReplaceOrAccumulate:
  27297. case audioMasterGetCurrentProcessLevel:
  27298. case audioMasterOfflineStart:
  27299. case audioMasterOfflineRead:
  27300. case audioMasterOfflineWrite:
  27301. case audioMasterOfflineGetCurrentPass:
  27302. case audioMasterOfflineGetCurrentMetaPass:
  27303. case audioMasterVendorSpecific:
  27304. case audioMasterSetIcon:
  27305. case audioMasterGetLanguage:
  27306. case audioMasterOpenWindow:
  27307. case audioMasterCloseWindow:
  27308. break;
  27309. default:
  27310. return handleGeneralCallback (opcode, index, value, ptr, opt);
  27311. }
  27312. return 0;
  27313. }
  27314. // entry point for all callbacks from the plugin
  27315. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  27316. {
  27317. try
  27318. {
  27319. if (effect != 0 && effect->resvd2 != 0)
  27320. {
  27321. return ((VSTPluginInstance*)(effect->resvd2))
  27322. ->handleCallback (opcode, index, value, ptr, opt);
  27323. }
  27324. return handleGeneralCallback (opcode, index, value, ptr, opt);
  27325. }
  27326. catch (...)
  27327. {
  27328. return 0;
  27329. }
  27330. }
  27331. const String VSTPluginInstance::getVersion() const throw()
  27332. {
  27333. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  27334. String s;
  27335. if (v == 0 || v == -1)
  27336. v = getVersionNumber();
  27337. if (v != 0)
  27338. {
  27339. int versionBits[4];
  27340. int n = 0;
  27341. while (v != 0)
  27342. {
  27343. versionBits [n++] = (v & 0xff);
  27344. v >>= 8;
  27345. }
  27346. s << 'V';
  27347. while (n > 0)
  27348. {
  27349. s << versionBits [--n];
  27350. if (n > 0)
  27351. s << '.';
  27352. }
  27353. }
  27354. return s;
  27355. }
  27356. int VSTPluginInstance::getUID() const throw()
  27357. {
  27358. int uid = effect != 0 ? effect->uniqueID : 0;
  27359. if (uid == 0)
  27360. uid = module->file.hashCode();
  27361. return uid;
  27362. }
  27363. const String VSTPluginInstance::getCategory() const throw()
  27364. {
  27365. const char* result = 0;
  27366. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  27367. {
  27368. case kPlugCategEffect:
  27369. result = "Effect";
  27370. break;
  27371. case kPlugCategSynth:
  27372. result = "Synth";
  27373. break;
  27374. case kPlugCategAnalysis:
  27375. result = "Anaylsis";
  27376. break;
  27377. case kPlugCategMastering:
  27378. result = "Mastering";
  27379. break;
  27380. case kPlugCategSpacializer:
  27381. result = "Spacial";
  27382. break;
  27383. case kPlugCategRoomFx:
  27384. result = "Reverb";
  27385. break;
  27386. case kPlugSurroundFx:
  27387. result = "Surround";
  27388. break;
  27389. case kPlugCategRestoration:
  27390. result = "Restoration";
  27391. break;
  27392. case kPlugCategGenerator:
  27393. result = "Tone generation";
  27394. break;
  27395. default:
  27396. break;
  27397. }
  27398. return result;
  27399. }
  27400. float VSTPluginInstance::getParameter (int index)
  27401. {
  27402. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  27403. {
  27404. try
  27405. {
  27406. const ScopedLock sl (lock);
  27407. return effect->getParameter (effect, index);
  27408. }
  27409. catch (...)
  27410. {
  27411. }
  27412. }
  27413. return 0.0f;
  27414. }
  27415. void VSTPluginInstance::setParameter (int index, float newValue)
  27416. {
  27417. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  27418. {
  27419. try
  27420. {
  27421. const ScopedLock sl (lock);
  27422. if (effect->getParameter (effect, index) != newValue)
  27423. effect->setParameter (effect, index, newValue);
  27424. }
  27425. catch (...)
  27426. {
  27427. }
  27428. }
  27429. }
  27430. const String VSTPluginInstance::getParameterName (int index)
  27431. {
  27432. if (effect != 0)
  27433. {
  27434. jassert (index >= 0 && index < effect->numParams);
  27435. char nm [256];
  27436. zerostruct (nm);
  27437. dispatch (effGetParamName, index, 0, nm, 0);
  27438. return String (nm).trim();
  27439. }
  27440. return String::empty;
  27441. }
  27442. const String VSTPluginInstance::getParameterLabel (int index) const
  27443. {
  27444. if (effect != 0)
  27445. {
  27446. jassert (index >= 0 && index < effect->numParams);
  27447. char nm [256];
  27448. zerostruct (nm);
  27449. dispatch (effGetParamLabel, index, 0, nm, 0);
  27450. return String (nm).trim();
  27451. }
  27452. return String::empty;
  27453. }
  27454. const String VSTPluginInstance::getParameterText (int index)
  27455. {
  27456. if (effect != 0)
  27457. {
  27458. jassert (index >= 0 && index < effect->numParams);
  27459. char nm [256];
  27460. zerostruct (nm);
  27461. dispatch (effGetParamDisplay, index, 0, nm, 0);
  27462. return String (nm).trim();
  27463. }
  27464. return String::empty;
  27465. }
  27466. bool VSTPluginInstance::isParameterAutomatable (int index) const
  27467. {
  27468. if (effect != 0)
  27469. {
  27470. jassert (index >= 0 && index < effect->numParams);
  27471. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  27472. }
  27473. return false;
  27474. }
  27475. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  27476. {
  27477. dest.setSize (64 + 4 * getNumParameters());
  27478. dest.fillWith (0);
  27479. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  27480. float* const p = (float*) (((char*) dest.getData()) + 64);
  27481. for (int i = 0; i < getNumParameters(); ++i)
  27482. p[i] = getParameter(i);
  27483. }
  27484. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  27485. {
  27486. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  27487. float* p = (float*) (((char*) m.getData()) + 64);
  27488. for (int i = 0; i < getNumParameters(); ++i)
  27489. setParameter (i, p[i]);
  27490. }
  27491. void VSTPluginInstance::setCurrentProgram (int newIndex)
  27492. {
  27493. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  27494. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  27495. }
  27496. const String VSTPluginInstance::getProgramName (int index)
  27497. {
  27498. if (index == getCurrentProgram())
  27499. {
  27500. return getCurrentProgramName();
  27501. }
  27502. else if (effect != 0)
  27503. {
  27504. char nm [256];
  27505. zerostruct (nm);
  27506. if (dispatch (effGetProgramNameIndexed,
  27507. jlimit (0, getNumPrograms(), index),
  27508. -1, nm, 0) != 0)
  27509. {
  27510. return String (nm).trim();
  27511. }
  27512. }
  27513. return programNames [index];
  27514. }
  27515. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  27516. {
  27517. if (index == getCurrentProgram())
  27518. {
  27519. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  27520. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  27521. }
  27522. else
  27523. {
  27524. jassertfalse // xxx not implemented!
  27525. }
  27526. }
  27527. void VSTPluginInstance::updateStoredProgramNames()
  27528. {
  27529. if (effect != 0 && getNumPrograms() > 0)
  27530. {
  27531. char nm [256];
  27532. zerostruct (nm);
  27533. // only do this if the plugin can't use indexed names..
  27534. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  27535. {
  27536. const int oldProgram = getCurrentProgram();
  27537. MemoryBlock oldSettings;
  27538. createTempParameterStore (oldSettings);
  27539. for (int i = 0; i < getNumPrograms(); ++i)
  27540. {
  27541. setCurrentProgram (i);
  27542. getCurrentProgramName(); // (this updates the list)
  27543. }
  27544. setCurrentProgram (oldProgram);
  27545. restoreFromTempParameterStore (oldSettings);
  27546. }
  27547. }
  27548. }
  27549. const String VSTPluginInstance::getCurrentProgramName()
  27550. {
  27551. if (effect != 0)
  27552. {
  27553. char nm [256];
  27554. zerostruct (nm);
  27555. dispatch (effGetProgramName, 0, 0, nm, 0);
  27556. const int index = getCurrentProgram();
  27557. if (programNames[index].isEmpty())
  27558. {
  27559. while (programNames.size() < index)
  27560. programNames.add (String::empty);
  27561. programNames.set (index, String (nm).trim());
  27562. }
  27563. return String (nm).trim();
  27564. }
  27565. return String::empty;
  27566. }
  27567. const String VSTPluginInstance::getInputChannelName (const int index) const
  27568. {
  27569. if (index >= 0 && index < getNumInputChannels())
  27570. {
  27571. VstPinProperties pinProps;
  27572. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  27573. return String (pinProps.label, sizeof (pinProps.label));
  27574. }
  27575. return String::empty;
  27576. }
  27577. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  27578. {
  27579. if (index < 0 || index >= getNumInputChannels())
  27580. return false;
  27581. VstPinProperties pinProps;
  27582. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  27583. return (pinProps.flags & kVstPinIsStereo) != 0;
  27584. return true;
  27585. }
  27586. const String VSTPluginInstance::getOutputChannelName (const int index) const
  27587. {
  27588. if (index >= 0 && index < getNumOutputChannels())
  27589. {
  27590. VstPinProperties pinProps;
  27591. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  27592. return String (pinProps.label, sizeof (pinProps.label));
  27593. }
  27594. return String::empty;
  27595. }
  27596. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  27597. {
  27598. if (index < 0 || index >= getNumOutputChannels())
  27599. return false;
  27600. VstPinProperties pinProps;
  27601. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  27602. return (pinProps.flags & kVstPinIsStereo) != 0;
  27603. return true;
  27604. }
  27605. void VSTPluginInstance::setPower (const bool on)
  27606. {
  27607. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  27608. isPowerOn = on;
  27609. }
  27610. const int defaultMaxSizeMB = 64;
  27611. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  27612. {
  27613. saveToFXBFile (destData, true, defaultMaxSizeMB);
  27614. }
  27615. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  27616. {
  27617. saveToFXBFile (destData, false, defaultMaxSizeMB);
  27618. }
  27619. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  27620. {
  27621. loadFromFXBFile (data, sizeInBytes);
  27622. }
  27623. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  27624. {
  27625. loadFromFXBFile (data, sizeInBytes);
  27626. }
  27627. VSTPluginFormat::VSTPluginFormat()
  27628. {
  27629. }
  27630. VSTPluginFormat::~VSTPluginFormat()
  27631. {
  27632. }
  27633. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  27634. const String& fileOrIdentifier)
  27635. {
  27636. if (! fileMightContainThisPluginType (fileOrIdentifier))
  27637. return;
  27638. PluginDescription desc;
  27639. desc.fileOrIdentifier = fileOrIdentifier;
  27640. desc.uid = 0;
  27641. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  27642. if (instance == 0)
  27643. return;
  27644. try
  27645. {
  27646. #if JUCE_MAC
  27647. if (instance->module->resFileId != 0)
  27648. UseResFile (instance->module->resFileId);
  27649. #endif
  27650. instance->fillInPluginDescription (desc);
  27651. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  27652. if (category != kPlugCategShell)
  27653. {
  27654. // Normal plugin...
  27655. results.add (new PluginDescription (desc));
  27656. ++insideVSTCallback;
  27657. instance->dispatch (effOpen, 0, 0, 0, 0);
  27658. --insideVSTCallback;
  27659. }
  27660. else
  27661. {
  27662. // It's a shell plugin, so iterate all the subtypes...
  27663. char shellEffectName [64];
  27664. for (;;)
  27665. {
  27666. zerostruct (shellEffectName);
  27667. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  27668. if (uid == 0)
  27669. {
  27670. break;
  27671. }
  27672. else
  27673. {
  27674. desc.uid = uid;
  27675. desc.name = shellEffectName;
  27676. bool alreadyThere = false;
  27677. for (int i = results.size(); --i >= 0;)
  27678. {
  27679. PluginDescription* const d = results.getUnchecked(i);
  27680. if (d->isDuplicateOf (desc))
  27681. {
  27682. alreadyThere = true;
  27683. break;
  27684. }
  27685. }
  27686. if (! alreadyThere)
  27687. results.add (new PluginDescription (desc));
  27688. }
  27689. }
  27690. }
  27691. }
  27692. catch (...)
  27693. {
  27694. // crashed while loading...
  27695. }
  27696. }
  27697. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  27698. {
  27699. ScopedPointer <VSTPluginInstance> result;
  27700. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  27701. {
  27702. File file (desc.fileOrIdentifier);
  27703. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  27704. file.getParentDirectory().setAsCurrentWorkingDirectory();
  27705. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  27706. if (module != 0)
  27707. {
  27708. shellUIDToCreate = desc.uid;
  27709. result = new VSTPluginInstance (module);
  27710. if (result->effect != 0)
  27711. {
  27712. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  27713. result->initialise();
  27714. }
  27715. else
  27716. {
  27717. result = 0;
  27718. }
  27719. }
  27720. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  27721. }
  27722. return result.release();
  27723. }
  27724. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  27725. {
  27726. const File f (fileOrIdentifier);
  27727. #if JUCE_MAC
  27728. if (f.isDirectory() && f.hasFileExtension (".vst"))
  27729. return true;
  27730. #if JUCE_PPC
  27731. FSRef fileRef;
  27732. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  27733. {
  27734. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  27735. if (resFileId != -1)
  27736. {
  27737. const int numEffects = Count1Resources ('aEff');
  27738. CloseResFile (resFileId);
  27739. if (numEffects > 0)
  27740. return true;
  27741. }
  27742. }
  27743. #endif
  27744. return false;
  27745. #elif JUCE_WIN32
  27746. return f.existsAsFile()
  27747. && f.hasFileExtension (".dll");
  27748. #elif JUCE_LINUX
  27749. return f.existsAsFile()
  27750. && f.hasFileExtension (".so");
  27751. #endif
  27752. }
  27753. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  27754. {
  27755. return fileOrIdentifier;
  27756. }
  27757. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  27758. {
  27759. return File (desc.fileOrIdentifier).exists();
  27760. }
  27761. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  27762. {
  27763. StringArray results;
  27764. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  27765. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  27766. return results;
  27767. }
  27768. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  27769. {
  27770. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  27771. // .component or .vst directories.
  27772. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  27773. while (iter.next())
  27774. {
  27775. const File f (iter.getFile());
  27776. bool isPlugin = false;
  27777. if (fileMightContainThisPluginType (f.getFullPathName()))
  27778. {
  27779. isPlugin = true;
  27780. results.add (f.getFullPathName());
  27781. }
  27782. if (recursive && (! isPlugin) && f.isDirectory())
  27783. recursiveFileSearch (results, f, true);
  27784. }
  27785. }
  27786. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  27787. {
  27788. #if JUCE_MAC
  27789. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  27790. #elif JUCE_WIN32
  27791. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  27792. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  27793. #elif JUCE_LINUX
  27794. return FileSearchPath ("/usr/lib/vst");
  27795. #endif
  27796. }
  27797. END_JUCE_NAMESPACE
  27798. #endif
  27799. #undef log
  27800. #endif
  27801. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  27802. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  27803. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  27804. BEGIN_JUCE_NAMESPACE
  27805. AudioProcessor::AudioProcessor()
  27806. : playHead (0),
  27807. activeEditor (0),
  27808. sampleRate (0),
  27809. blockSize (0),
  27810. numInputChannels (0),
  27811. numOutputChannels (0),
  27812. latencySamples (0),
  27813. suspended (false),
  27814. nonRealtime (false)
  27815. {
  27816. }
  27817. AudioProcessor::~AudioProcessor()
  27818. {
  27819. // ooh, nasty - the editor should have been deleted before the filter
  27820. // that it refers to is deleted..
  27821. jassert (activeEditor == 0);
  27822. #if JUCE_DEBUG
  27823. // This will fail if you've called beginParameterChangeGesture() for one
  27824. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  27825. jassert (changingParams.countNumberOfSetBits() == 0);
  27826. #endif
  27827. }
  27828. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  27829. {
  27830. playHead = newPlayHead;
  27831. }
  27832. void AudioProcessor::addListener (AudioProcessorListener* const newListener) throw()
  27833. {
  27834. const ScopedLock sl (listenerLock);
  27835. listeners.addIfNotAlreadyThere (newListener);
  27836. }
  27837. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove) throw()
  27838. {
  27839. const ScopedLock sl (listenerLock);
  27840. listeners.removeValue (listenerToRemove);
  27841. }
  27842. void AudioProcessor::setPlayConfigDetails (const int numIns,
  27843. const int numOuts,
  27844. const double sampleRate_,
  27845. const int blockSize_) throw()
  27846. {
  27847. numInputChannels = numIns;
  27848. numOutputChannels = numOuts;
  27849. sampleRate = sampleRate_;
  27850. blockSize = blockSize_;
  27851. }
  27852. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  27853. {
  27854. nonRealtime = nonRealtime_;
  27855. }
  27856. void AudioProcessor::setLatencySamples (const int newLatency)
  27857. {
  27858. if (latencySamples != newLatency)
  27859. {
  27860. latencySamples = newLatency;
  27861. updateHostDisplay();
  27862. }
  27863. }
  27864. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  27865. const float newValue)
  27866. {
  27867. setParameter (parameterIndex, newValue);
  27868. sendParamChangeMessageToListeners (parameterIndex, newValue);
  27869. }
  27870. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  27871. {
  27872. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27873. for (int i = listeners.size(); --i >= 0;)
  27874. {
  27875. AudioProcessorListener* l;
  27876. {
  27877. const ScopedLock sl (listenerLock);
  27878. l = (AudioProcessorListener*) listeners [i];
  27879. }
  27880. if (l != 0)
  27881. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  27882. }
  27883. }
  27884. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  27885. {
  27886. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27887. #if JUCE_DEBUG
  27888. // This means you've called beginParameterChangeGesture twice in succession without a matching
  27889. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  27890. jassert (! changingParams [parameterIndex]);
  27891. changingParams.setBit (parameterIndex);
  27892. #endif
  27893. for (int i = listeners.size(); --i >= 0;)
  27894. {
  27895. AudioProcessorListener* l;
  27896. {
  27897. const ScopedLock sl (listenerLock);
  27898. l = (AudioProcessorListener*) listeners [i];
  27899. }
  27900. if (l != 0)
  27901. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  27902. }
  27903. }
  27904. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  27905. {
  27906. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27907. #if JUCE_DEBUG
  27908. // This means you've called endParameterChangeGesture without having previously called
  27909. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  27910. // calls matched correctly.
  27911. jassert (changingParams [parameterIndex]);
  27912. changingParams.clearBit (parameterIndex);
  27913. #endif
  27914. for (int i = listeners.size(); --i >= 0;)
  27915. {
  27916. AudioProcessorListener* l;
  27917. {
  27918. const ScopedLock sl (listenerLock);
  27919. l = (AudioProcessorListener*) listeners [i];
  27920. }
  27921. if (l != 0)
  27922. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  27923. }
  27924. }
  27925. void AudioProcessor::updateHostDisplay()
  27926. {
  27927. for (int i = listeners.size(); --i >= 0;)
  27928. {
  27929. AudioProcessorListener* l;
  27930. {
  27931. const ScopedLock sl (listenerLock);
  27932. l = (AudioProcessorListener*) listeners [i];
  27933. }
  27934. if (l != 0)
  27935. l->audioProcessorChanged (this);
  27936. }
  27937. }
  27938. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  27939. {
  27940. return true;
  27941. }
  27942. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  27943. {
  27944. return false;
  27945. }
  27946. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  27947. {
  27948. const ScopedLock sl (callbackLock);
  27949. suspended = shouldBeSuspended;
  27950. }
  27951. void AudioProcessor::reset()
  27952. {
  27953. }
  27954. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  27955. {
  27956. const ScopedLock sl (callbackLock);
  27957. jassert (activeEditor == editor);
  27958. if (activeEditor == editor)
  27959. activeEditor = 0;
  27960. }
  27961. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  27962. {
  27963. if (activeEditor != 0)
  27964. return activeEditor;
  27965. AudioProcessorEditor* const ed = createEditor();
  27966. if (ed != 0)
  27967. {
  27968. // you must give your editor comp a size before returning it..
  27969. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  27970. const ScopedLock sl (callbackLock);
  27971. activeEditor = ed;
  27972. }
  27973. return ed;
  27974. }
  27975. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  27976. {
  27977. getStateInformation (destData);
  27978. }
  27979. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  27980. {
  27981. setStateInformation (data, sizeInBytes);
  27982. }
  27983. // magic number to identify memory blocks that we've stored as XML
  27984. const uint32 magicXmlNumber = 0x21324356;
  27985. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  27986. JUCE_NAMESPACE::MemoryBlock& destData)
  27987. {
  27988. const String xmlString (xml.createDocument (String::empty, true, false));
  27989. const int stringLength = xmlString.getNumBytesAsUTF8();
  27990. destData.setSize (stringLength + 10);
  27991. char* const d = (char*) destData.getData();
  27992. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  27993. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  27994. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  27995. }
  27996. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  27997. const int sizeInBytes)
  27998. {
  27999. if (sizeInBytes > 8
  28000. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  28001. {
  28002. const int stringLength = (int) ByteOrder::littleEndianInt (((const char*) data) + 4);
  28003. if (stringLength > 0)
  28004. {
  28005. XmlDocument doc (String::fromUTF8 (((const char*) data) + 8,
  28006. jmin ((sizeInBytes - 8), stringLength)));
  28007. return doc.getDocumentElement();
  28008. }
  28009. }
  28010. return 0;
  28011. }
  28012. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int)
  28013. {
  28014. }
  28015. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int)
  28016. {
  28017. }
  28018. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  28019. {
  28020. return timeInSeconds == other.timeInSeconds
  28021. && ppqPosition == other.ppqPosition
  28022. && editOriginTime == other.editOriginTime
  28023. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  28024. && frameRate == other.frameRate
  28025. && isPlaying == other.isPlaying
  28026. && isRecording == other.isRecording
  28027. && bpm == other.bpm
  28028. && timeSigNumerator == other.timeSigNumerator
  28029. && timeSigDenominator == other.timeSigDenominator;
  28030. }
  28031. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  28032. {
  28033. return ! operator== (other);
  28034. }
  28035. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  28036. {
  28037. zerostruct (*this);
  28038. timeSigNumerator = 4;
  28039. timeSigDenominator = 4;
  28040. bpm = 120;
  28041. }
  28042. END_JUCE_NAMESPACE
  28043. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  28044. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  28045. BEGIN_JUCE_NAMESPACE
  28046. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  28047. : owner (owner_)
  28048. {
  28049. // the filter must be valid..
  28050. jassert (owner != 0);
  28051. }
  28052. AudioProcessorEditor::~AudioProcessorEditor()
  28053. {
  28054. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  28055. // filter for some reason..
  28056. jassert (owner->getActiveEditor() != this);
  28057. }
  28058. END_JUCE_NAMESPACE
  28059. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  28060. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  28061. BEGIN_JUCE_NAMESPACE
  28062. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  28063. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  28064. : id (id_),
  28065. processor (processor_),
  28066. isPrepared (false)
  28067. {
  28068. jassert (processor_ != 0);
  28069. }
  28070. AudioProcessorGraph::Node::~Node()
  28071. {
  28072. delete processor;
  28073. }
  28074. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  28075. AudioProcessorGraph* const graph)
  28076. {
  28077. if (! isPrepared)
  28078. {
  28079. isPrepared = true;
  28080. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28081. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (processor);
  28082. if (ioProc != 0)
  28083. ioProc->setParentGraph (graph);
  28084. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  28085. processor->getNumOutputChannels(),
  28086. sampleRate, blockSize);
  28087. processor->prepareToPlay (sampleRate, blockSize);
  28088. }
  28089. }
  28090. void AudioProcessorGraph::Node::unprepare()
  28091. {
  28092. if (isPrepared)
  28093. {
  28094. isPrepared = false;
  28095. processor->releaseResources();
  28096. }
  28097. }
  28098. AudioProcessorGraph::AudioProcessorGraph()
  28099. : lastNodeId (0),
  28100. renderingBuffers (1, 1),
  28101. currentAudioOutputBuffer (1, 1)
  28102. {
  28103. }
  28104. AudioProcessorGraph::~AudioProcessorGraph()
  28105. {
  28106. clearRenderingSequence();
  28107. clear();
  28108. }
  28109. const String AudioProcessorGraph::getName() const
  28110. {
  28111. return "Audio Graph";
  28112. }
  28113. void AudioProcessorGraph::clear()
  28114. {
  28115. nodes.clear();
  28116. connections.clear();
  28117. triggerAsyncUpdate();
  28118. }
  28119. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  28120. {
  28121. for (int i = nodes.size(); --i >= 0;)
  28122. if (nodes.getUnchecked(i)->id == nodeId)
  28123. return nodes.getUnchecked(i);
  28124. return 0;
  28125. }
  28126. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  28127. uint32 nodeId)
  28128. {
  28129. if (newProcessor == 0)
  28130. {
  28131. jassertfalse
  28132. return 0;
  28133. }
  28134. if (nodeId == 0)
  28135. {
  28136. nodeId = ++lastNodeId;
  28137. }
  28138. else
  28139. {
  28140. // you can't add a node with an id that already exists in the graph..
  28141. jassert (getNodeForId (nodeId) == 0);
  28142. removeNode (nodeId);
  28143. }
  28144. lastNodeId = nodeId;
  28145. Node* const n = new Node (nodeId, newProcessor);
  28146. nodes.add (n);
  28147. triggerAsyncUpdate();
  28148. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28149. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (n->processor);
  28150. if (ioProc != 0)
  28151. ioProc->setParentGraph (this);
  28152. return n;
  28153. }
  28154. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  28155. {
  28156. disconnectNode (nodeId);
  28157. for (int i = nodes.size(); --i >= 0;)
  28158. {
  28159. if (nodes.getUnchecked(i)->id == nodeId)
  28160. {
  28161. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28162. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (nodes.getUnchecked(i)->processor);
  28163. if (ioProc != 0)
  28164. ioProc->setParentGraph (0);
  28165. nodes.remove (i);
  28166. triggerAsyncUpdate();
  28167. return true;
  28168. }
  28169. }
  28170. return false;
  28171. }
  28172. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  28173. const int sourceChannelIndex,
  28174. const uint32 destNodeId,
  28175. const int destChannelIndex) const
  28176. {
  28177. for (int i = connections.size(); --i >= 0;)
  28178. {
  28179. const Connection* const c = connections.getUnchecked(i);
  28180. if (c->sourceNodeId == sourceNodeId
  28181. && c->destNodeId == destNodeId
  28182. && c->sourceChannelIndex == sourceChannelIndex
  28183. && c->destChannelIndex == destChannelIndex)
  28184. {
  28185. return c;
  28186. }
  28187. }
  28188. return 0;
  28189. }
  28190. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  28191. const uint32 possibleDestNodeId) const
  28192. {
  28193. for (int i = connections.size(); --i >= 0;)
  28194. {
  28195. const Connection* const c = connections.getUnchecked(i);
  28196. if (c->sourceNodeId == possibleSourceNodeId
  28197. && c->destNodeId == possibleDestNodeId)
  28198. {
  28199. return true;
  28200. }
  28201. }
  28202. return false;
  28203. }
  28204. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  28205. const int sourceChannelIndex,
  28206. const uint32 destNodeId,
  28207. const int destChannelIndex) const
  28208. {
  28209. if (sourceChannelIndex < 0
  28210. || destChannelIndex < 0
  28211. || sourceNodeId == destNodeId
  28212. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  28213. return false;
  28214. const Node* const source = getNodeForId (sourceNodeId);
  28215. if (source == 0
  28216. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  28217. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  28218. return false;
  28219. const Node* const dest = getNodeForId (destNodeId);
  28220. if (dest == 0
  28221. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  28222. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  28223. return false;
  28224. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  28225. destNodeId, destChannelIndex) == 0;
  28226. }
  28227. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  28228. const int sourceChannelIndex,
  28229. const uint32 destNodeId,
  28230. const int destChannelIndex)
  28231. {
  28232. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  28233. return false;
  28234. Connection* const c = new Connection();
  28235. c->sourceNodeId = sourceNodeId;
  28236. c->sourceChannelIndex = sourceChannelIndex;
  28237. c->destNodeId = destNodeId;
  28238. c->destChannelIndex = destChannelIndex;
  28239. connections.add (c);
  28240. triggerAsyncUpdate();
  28241. return true;
  28242. }
  28243. void AudioProcessorGraph::removeConnection (const int index)
  28244. {
  28245. connections.remove (index);
  28246. triggerAsyncUpdate();
  28247. }
  28248. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  28249. const uint32 destNodeId, const int destChannelIndex)
  28250. {
  28251. bool doneAnything = false;
  28252. for (int i = connections.size(); --i >= 0;)
  28253. {
  28254. const Connection* const c = connections.getUnchecked(i);
  28255. if (c->sourceNodeId == sourceNodeId
  28256. && c->destNodeId == destNodeId
  28257. && c->sourceChannelIndex == sourceChannelIndex
  28258. && c->destChannelIndex == destChannelIndex)
  28259. {
  28260. removeConnection (i);
  28261. doneAnything = true;
  28262. triggerAsyncUpdate();
  28263. }
  28264. }
  28265. return doneAnything;
  28266. }
  28267. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  28268. {
  28269. bool doneAnything = false;
  28270. for (int i = connections.size(); --i >= 0;)
  28271. {
  28272. const Connection* const c = connections.getUnchecked(i);
  28273. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  28274. {
  28275. removeConnection (i);
  28276. doneAnything = true;
  28277. triggerAsyncUpdate();
  28278. }
  28279. }
  28280. return doneAnything;
  28281. }
  28282. bool AudioProcessorGraph::removeIllegalConnections()
  28283. {
  28284. bool doneAnything = false;
  28285. for (int i = connections.size(); --i >= 0;)
  28286. {
  28287. const Connection* const c = connections.getUnchecked(i);
  28288. const Node* const source = getNodeForId (c->sourceNodeId);
  28289. const Node* const dest = getNodeForId (c->destNodeId);
  28290. if (source == 0 || dest == 0
  28291. || (c->sourceChannelIndex != midiChannelIndex
  28292. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  28293. || (c->sourceChannelIndex == midiChannelIndex
  28294. && ! source->processor->producesMidi())
  28295. || (c->destChannelIndex != midiChannelIndex
  28296. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  28297. || (c->destChannelIndex == midiChannelIndex
  28298. && ! dest->processor->acceptsMidi()))
  28299. {
  28300. removeConnection (i);
  28301. doneAnything = true;
  28302. triggerAsyncUpdate();
  28303. }
  28304. }
  28305. return doneAnything;
  28306. }
  28307. namespace GraphRenderingOps
  28308. {
  28309. class AudioGraphRenderingOp
  28310. {
  28311. public:
  28312. AudioGraphRenderingOp() {}
  28313. virtual ~AudioGraphRenderingOp() {}
  28314. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  28315. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  28316. const int numSamples) = 0;
  28317. juce_UseDebuggingNewOperator
  28318. };
  28319. class ClearChannelOp : public AudioGraphRenderingOp
  28320. {
  28321. public:
  28322. ClearChannelOp (const int channelNum_)
  28323. : channelNum (channelNum_)
  28324. {}
  28325. ~ClearChannelOp() {}
  28326. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28327. {
  28328. sharedBufferChans.clear (channelNum, 0, numSamples);
  28329. }
  28330. private:
  28331. const int channelNum;
  28332. ClearChannelOp (const ClearChannelOp&);
  28333. ClearChannelOp& operator= (const ClearChannelOp&);
  28334. };
  28335. class CopyChannelOp : public AudioGraphRenderingOp
  28336. {
  28337. public:
  28338. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  28339. : srcChannelNum (srcChannelNum_),
  28340. dstChannelNum (dstChannelNum_)
  28341. {}
  28342. ~CopyChannelOp() {}
  28343. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28344. {
  28345. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  28346. }
  28347. private:
  28348. const int srcChannelNum, dstChannelNum;
  28349. CopyChannelOp (const CopyChannelOp&);
  28350. CopyChannelOp& operator= (const CopyChannelOp&);
  28351. };
  28352. class AddChannelOp : public AudioGraphRenderingOp
  28353. {
  28354. public:
  28355. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  28356. : srcChannelNum (srcChannelNum_),
  28357. dstChannelNum (dstChannelNum_)
  28358. {}
  28359. ~AddChannelOp() {}
  28360. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28361. {
  28362. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  28363. }
  28364. private:
  28365. const int srcChannelNum, dstChannelNum;
  28366. AddChannelOp (const AddChannelOp&);
  28367. AddChannelOp& operator= (const AddChannelOp&);
  28368. };
  28369. class ClearMidiBufferOp : public AudioGraphRenderingOp
  28370. {
  28371. public:
  28372. ClearMidiBufferOp (const int bufferNum_)
  28373. : bufferNum (bufferNum_)
  28374. {}
  28375. ~ClearMidiBufferOp() {}
  28376. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  28377. {
  28378. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  28379. }
  28380. private:
  28381. const int bufferNum;
  28382. ClearMidiBufferOp (const ClearMidiBufferOp&);
  28383. ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  28384. };
  28385. class CopyMidiBufferOp : public AudioGraphRenderingOp
  28386. {
  28387. public:
  28388. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  28389. : srcBufferNum (srcBufferNum_),
  28390. dstBufferNum (dstBufferNum_)
  28391. {}
  28392. ~CopyMidiBufferOp() {}
  28393. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  28394. {
  28395. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  28396. }
  28397. private:
  28398. const int srcBufferNum, dstBufferNum;
  28399. CopyMidiBufferOp (const CopyMidiBufferOp&);
  28400. CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  28401. };
  28402. class AddMidiBufferOp : public AudioGraphRenderingOp
  28403. {
  28404. public:
  28405. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  28406. : srcBufferNum (srcBufferNum_),
  28407. dstBufferNum (dstBufferNum_)
  28408. {}
  28409. ~AddMidiBufferOp() {}
  28410. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  28411. {
  28412. sharedMidiBuffers.getUnchecked (dstBufferNum)
  28413. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  28414. }
  28415. private:
  28416. const int srcBufferNum, dstBufferNum;
  28417. AddMidiBufferOp (const AddMidiBufferOp&);
  28418. AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  28419. };
  28420. class ProcessBufferOp : public AudioGraphRenderingOp
  28421. {
  28422. public:
  28423. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  28424. const Array <int>& audioChannelsToUse_,
  28425. const int totalChans_,
  28426. const int midiBufferToUse_)
  28427. : node (node_),
  28428. processor (node_->processor),
  28429. audioChannelsToUse (audioChannelsToUse_),
  28430. totalChans (jmax (1, totalChans_)),
  28431. midiBufferToUse (midiBufferToUse_)
  28432. {
  28433. channels.calloc (totalChans);
  28434. while (audioChannelsToUse.size() < totalChans)
  28435. audioChannelsToUse.add (0);
  28436. }
  28437. ~ProcessBufferOp()
  28438. {
  28439. }
  28440. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  28441. {
  28442. for (int i = totalChans; --i >= 0;)
  28443. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  28444. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  28445. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  28446. }
  28447. const AudioProcessorGraph::Node::Ptr node;
  28448. AudioProcessor* const processor;
  28449. private:
  28450. Array <int> audioChannelsToUse;
  28451. HeapBlock <float*> channels;
  28452. int totalChans;
  28453. int midiBufferToUse;
  28454. ProcessBufferOp (const ProcessBufferOp&);
  28455. ProcessBufferOp& operator= (const ProcessBufferOp&);
  28456. };
  28457. /** Used to calculate the correct sequence of rendering ops needed, based on
  28458. the best re-use of shared buffers at each stage.
  28459. */
  28460. class RenderingOpSequenceCalculator
  28461. {
  28462. public:
  28463. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  28464. const VoidArray& orderedNodes_,
  28465. VoidArray& renderingOps)
  28466. : graph (graph_),
  28467. orderedNodes (orderedNodes_)
  28468. {
  28469. nodeIds.add (-2); // first buffer is read-only zeros
  28470. channels.add (0);
  28471. midiNodeIds.add (-2);
  28472. for (int i = 0; i < orderedNodes.size(); ++i)
  28473. {
  28474. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  28475. renderingOps, i);
  28476. markAnyUnusedBuffersAsFree (i);
  28477. }
  28478. }
  28479. int getNumBuffersNeeded() const { return nodeIds.size(); }
  28480. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  28481. juce_UseDebuggingNewOperator
  28482. private:
  28483. AudioProcessorGraph& graph;
  28484. const VoidArray& orderedNodes;
  28485. Array <int> nodeIds, channels, midiNodeIds;
  28486. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  28487. VoidArray& renderingOps,
  28488. const int ourRenderingIndex)
  28489. {
  28490. const int numIns = node->processor->getNumInputChannels();
  28491. const int numOuts = node->processor->getNumOutputChannels();
  28492. const int totalChans = jmax (numIns, numOuts);
  28493. Array <int> audioChannelsToUse;
  28494. int midiBufferToUse = -1;
  28495. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  28496. {
  28497. // get a list of all the inputs to this node
  28498. Array <int> sourceNodes, sourceOutputChans;
  28499. for (int i = graph.getNumConnections(); --i >= 0;)
  28500. {
  28501. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  28502. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  28503. {
  28504. sourceNodes.add (c->sourceNodeId);
  28505. sourceOutputChans.add (c->sourceChannelIndex);
  28506. }
  28507. }
  28508. int bufIndex = -1;
  28509. if (sourceNodes.size() == 0)
  28510. {
  28511. // unconnected input channel
  28512. if (inputChan >= numOuts)
  28513. {
  28514. bufIndex = getReadOnlyEmptyBuffer();
  28515. jassert (bufIndex >= 0);
  28516. }
  28517. else
  28518. {
  28519. bufIndex = getFreeBuffer (false);
  28520. renderingOps.add (new ClearChannelOp (bufIndex));
  28521. }
  28522. }
  28523. else if (sourceNodes.size() == 1)
  28524. {
  28525. // channel with a straightforward single input..
  28526. const int srcNode = sourceNodes.getUnchecked(0);
  28527. const int srcChan = sourceOutputChans.getUnchecked(0);
  28528. bufIndex = getBufferContaining (srcNode, srcChan);
  28529. if (bufIndex < 0)
  28530. {
  28531. // if not found, this is probably a feedback loop
  28532. bufIndex = getReadOnlyEmptyBuffer();
  28533. jassert (bufIndex >= 0);
  28534. }
  28535. if (inputChan < numOuts
  28536. && isBufferNeededLater (ourRenderingIndex,
  28537. inputChan,
  28538. srcNode, srcChan))
  28539. {
  28540. // can't mess up this channel because it's needed later by another node, so we
  28541. // need to use a copy of it..
  28542. const int newFreeBuffer = getFreeBuffer (false);
  28543. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  28544. bufIndex = newFreeBuffer;
  28545. }
  28546. }
  28547. else
  28548. {
  28549. // channel with a mix of several inputs..
  28550. // try to find a re-usable channel from our inputs..
  28551. int reusableInputIndex = -1;
  28552. for (int i = 0; i < sourceNodes.size(); ++i)
  28553. {
  28554. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  28555. sourceOutputChans.getUnchecked(i));
  28556. if (sourceBufIndex >= 0
  28557. && ! isBufferNeededLater (ourRenderingIndex,
  28558. inputChan,
  28559. sourceNodes.getUnchecked(i),
  28560. sourceOutputChans.getUnchecked(i)))
  28561. {
  28562. // we've found one of our input chans that can be re-used..
  28563. reusableInputIndex = i;
  28564. bufIndex = sourceBufIndex;
  28565. break;
  28566. }
  28567. }
  28568. if (reusableInputIndex < 0)
  28569. {
  28570. // can't re-use any of our input chans, so get a new one and copy everything into it..
  28571. bufIndex = getFreeBuffer (false);
  28572. jassert (bufIndex != 0);
  28573. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  28574. sourceOutputChans.getUnchecked (0));
  28575. if (srcIndex < 0)
  28576. {
  28577. // if not found, this is probably a feedback loop
  28578. renderingOps.add (new ClearChannelOp (bufIndex));
  28579. }
  28580. else
  28581. {
  28582. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  28583. }
  28584. reusableInputIndex = 0;
  28585. }
  28586. for (int j = 0; j < sourceNodes.size(); ++j)
  28587. {
  28588. if (j != reusableInputIndex)
  28589. {
  28590. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  28591. sourceOutputChans.getUnchecked(j));
  28592. if (srcIndex >= 0)
  28593. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  28594. }
  28595. }
  28596. }
  28597. jassert (bufIndex >= 0);
  28598. audioChannelsToUse.add (bufIndex);
  28599. if (inputChan < numOuts)
  28600. markBufferAsContaining (bufIndex, node->id, inputChan);
  28601. }
  28602. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  28603. {
  28604. const int bufIndex = getFreeBuffer (false);
  28605. jassert (bufIndex != 0);
  28606. audioChannelsToUse.add (bufIndex);
  28607. markBufferAsContaining (bufIndex, node->id, outputChan);
  28608. }
  28609. // Now the same thing for midi..
  28610. Array <int> midiSourceNodes;
  28611. for (int i = graph.getNumConnections(); --i >= 0;)
  28612. {
  28613. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  28614. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  28615. midiSourceNodes.add (c->sourceNodeId);
  28616. }
  28617. if (midiSourceNodes.size() == 0)
  28618. {
  28619. // No midi inputs..
  28620. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  28621. if (node->processor->acceptsMidi() || node->processor->producesMidi())
  28622. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  28623. }
  28624. else if (midiSourceNodes.size() == 1)
  28625. {
  28626. // One midi input..
  28627. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  28628. AudioProcessorGraph::midiChannelIndex);
  28629. if (midiBufferToUse >= 0)
  28630. {
  28631. if (isBufferNeededLater (ourRenderingIndex,
  28632. AudioProcessorGraph::midiChannelIndex,
  28633. midiSourceNodes.getUnchecked(0),
  28634. AudioProcessorGraph::midiChannelIndex))
  28635. {
  28636. // can't mess up this channel because it's needed later by another node, so we
  28637. // need to use a copy of it..
  28638. const int newFreeBuffer = getFreeBuffer (true);
  28639. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  28640. midiBufferToUse = newFreeBuffer;
  28641. }
  28642. }
  28643. else
  28644. {
  28645. // probably a feedback loop, so just use an empty one..
  28646. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  28647. }
  28648. }
  28649. else
  28650. {
  28651. // More than one midi input being mixed..
  28652. int reusableInputIndex = -1;
  28653. for (int i = 0; i < midiSourceNodes.size(); ++i)
  28654. {
  28655. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  28656. AudioProcessorGraph::midiChannelIndex);
  28657. if (sourceBufIndex >= 0
  28658. && ! isBufferNeededLater (ourRenderingIndex,
  28659. AudioProcessorGraph::midiChannelIndex,
  28660. midiSourceNodes.getUnchecked(i),
  28661. AudioProcessorGraph::midiChannelIndex))
  28662. {
  28663. // we've found one of our input buffers that can be re-used..
  28664. reusableInputIndex = i;
  28665. midiBufferToUse = sourceBufIndex;
  28666. break;
  28667. }
  28668. }
  28669. if (reusableInputIndex < 0)
  28670. {
  28671. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  28672. midiBufferToUse = getFreeBuffer (true);
  28673. jassert (midiBufferToUse >= 0);
  28674. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  28675. AudioProcessorGraph::midiChannelIndex);
  28676. if (srcIndex >= 0)
  28677. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  28678. else
  28679. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  28680. reusableInputIndex = 0;
  28681. }
  28682. for (int j = 0; j < midiSourceNodes.size(); ++j)
  28683. {
  28684. if (j != reusableInputIndex)
  28685. {
  28686. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  28687. AudioProcessorGraph::midiChannelIndex);
  28688. if (srcIndex >= 0)
  28689. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  28690. }
  28691. }
  28692. }
  28693. if (node->processor->producesMidi())
  28694. markBufferAsContaining (midiBufferToUse, node->id,
  28695. AudioProcessorGraph::midiChannelIndex);
  28696. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  28697. totalChans, midiBufferToUse));
  28698. }
  28699. int getFreeBuffer (const bool forMidi)
  28700. {
  28701. if (forMidi)
  28702. {
  28703. for (int i = 1; i < midiNodeIds.size(); ++i)
  28704. if (midiNodeIds.getUnchecked(i) < 0)
  28705. return i;
  28706. midiNodeIds.add (-1);
  28707. return midiNodeIds.size() - 1;
  28708. }
  28709. else
  28710. {
  28711. for (int i = 1; i < nodeIds.size(); ++i)
  28712. if (nodeIds.getUnchecked(i) < 0)
  28713. return i;
  28714. nodeIds.add (-1);
  28715. channels.add (0);
  28716. return nodeIds.size() - 1;
  28717. }
  28718. }
  28719. int getReadOnlyEmptyBuffer() const
  28720. {
  28721. return 0;
  28722. }
  28723. int getBufferContaining (const int nodeId, const int outputChannel) const
  28724. {
  28725. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  28726. {
  28727. for (int i = midiNodeIds.size(); --i >= 0;)
  28728. if (midiNodeIds.getUnchecked(i) == nodeId)
  28729. return i;
  28730. }
  28731. else
  28732. {
  28733. for (int i = nodeIds.size(); --i >= 0;)
  28734. if (nodeIds.getUnchecked(i) == nodeId
  28735. && channels.getUnchecked(i) == outputChannel)
  28736. return i;
  28737. }
  28738. return -1;
  28739. }
  28740. void markAnyUnusedBuffersAsFree (const int stepIndex)
  28741. {
  28742. int i;
  28743. for (i = 0; i < nodeIds.size(); ++i)
  28744. {
  28745. if (nodeIds.getUnchecked(i) >= 0
  28746. && ! isBufferNeededLater (stepIndex, -1,
  28747. nodeIds.getUnchecked(i),
  28748. channels.getUnchecked(i)))
  28749. {
  28750. nodeIds.set (i, -1);
  28751. }
  28752. }
  28753. for (i = 0; i < midiNodeIds.size(); ++i)
  28754. {
  28755. if (midiNodeIds.getUnchecked(i) >= 0
  28756. && ! isBufferNeededLater (stepIndex, -1,
  28757. midiNodeIds.getUnchecked(i),
  28758. AudioProcessorGraph::midiChannelIndex))
  28759. {
  28760. midiNodeIds.set (i, -1);
  28761. }
  28762. }
  28763. }
  28764. bool isBufferNeededLater (int stepIndexToSearchFrom,
  28765. int inputChannelOfIndexToIgnore,
  28766. const int nodeId,
  28767. const int outputChanIndex) const
  28768. {
  28769. while (stepIndexToSearchFrom < orderedNodes.size())
  28770. {
  28771. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  28772. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  28773. {
  28774. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  28775. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  28776. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  28777. return true;
  28778. }
  28779. else
  28780. {
  28781. for (int i = 0; i < node->processor->getNumInputChannels(); ++i)
  28782. if (i != inputChannelOfIndexToIgnore
  28783. && graph.getConnectionBetween (nodeId, outputChanIndex,
  28784. node->id, i) != 0)
  28785. return true;
  28786. }
  28787. inputChannelOfIndexToIgnore = -1;
  28788. ++stepIndexToSearchFrom;
  28789. }
  28790. return false;
  28791. }
  28792. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  28793. {
  28794. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  28795. {
  28796. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  28797. midiNodeIds.set (bufferNum, nodeId);
  28798. }
  28799. else
  28800. {
  28801. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  28802. nodeIds.set (bufferNum, nodeId);
  28803. channels.set (bufferNum, outputIndex);
  28804. }
  28805. }
  28806. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  28807. RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  28808. };
  28809. }
  28810. void AudioProcessorGraph::clearRenderingSequence()
  28811. {
  28812. const ScopedLock sl (renderLock);
  28813. for (int i = renderingOps.size(); --i >= 0;)
  28814. {
  28815. GraphRenderingOps::AudioGraphRenderingOp* const r
  28816. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28817. renderingOps.remove (i);
  28818. delete r;
  28819. }
  28820. }
  28821. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  28822. const uint32 possibleDestinationId,
  28823. const int recursionCheck) const
  28824. {
  28825. if (recursionCheck > 0)
  28826. {
  28827. for (int i = connections.size(); --i >= 0;)
  28828. {
  28829. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  28830. if (c->destNodeId == possibleDestinationId
  28831. && (c->sourceNodeId == possibleInputId
  28832. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  28833. return true;
  28834. }
  28835. }
  28836. return false;
  28837. }
  28838. void AudioProcessorGraph::buildRenderingSequence()
  28839. {
  28840. VoidArray newRenderingOps;
  28841. int numRenderingBuffersNeeded = 2;
  28842. int numMidiBuffersNeeded = 1;
  28843. {
  28844. MessageManagerLock mml;
  28845. VoidArray orderedNodes;
  28846. int i;
  28847. for (i = 0; i < nodes.size(); ++i)
  28848. {
  28849. Node* const node = nodes.getUnchecked(i);
  28850. node->prepare (getSampleRate(), getBlockSize(), this);
  28851. int j = 0;
  28852. for (; j < orderedNodes.size(); ++j)
  28853. if (isAnInputTo (node->id,
  28854. ((Node*) orderedNodes.getUnchecked (j))->id,
  28855. nodes.size() + 1))
  28856. break;
  28857. orderedNodes.insert (j, node);
  28858. }
  28859. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  28860. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  28861. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  28862. }
  28863. VoidArray oldRenderingOps (renderingOps);
  28864. {
  28865. // swap over to the new rendering sequence..
  28866. const ScopedLock sl (renderLock);
  28867. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  28868. renderingBuffers.clear();
  28869. for (int i = midiBuffers.size(); --i >= 0;)
  28870. midiBuffers.getUnchecked(i)->clear();
  28871. while (midiBuffers.size() < numMidiBuffersNeeded)
  28872. midiBuffers.add (new MidiBuffer());
  28873. renderingOps = newRenderingOps;
  28874. }
  28875. for (int i = oldRenderingOps.size(); --i >= 0;)
  28876. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  28877. }
  28878. void AudioProcessorGraph::handleAsyncUpdate()
  28879. {
  28880. buildRenderingSequence();
  28881. }
  28882. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  28883. {
  28884. currentAudioInputBuffer = 0;
  28885. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  28886. currentMidiInputBuffer = 0;
  28887. currentMidiOutputBuffer.clear();
  28888. clearRenderingSequence();
  28889. buildRenderingSequence();
  28890. }
  28891. void AudioProcessorGraph::releaseResources()
  28892. {
  28893. for (int i = 0; i < nodes.size(); ++i)
  28894. nodes.getUnchecked(i)->unprepare();
  28895. renderingBuffers.setSize (1, 1);
  28896. midiBuffers.clear();
  28897. currentAudioInputBuffer = 0;
  28898. currentAudioOutputBuffer.setSize (1, 1);
  28899. currentMidiInputBuffer = 0;
  28900. currentMidiOutputBuffer.clear();
  28901. }
  28902. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  28903. {
  28904. const int numSamples = buffer.getNumSamples();
  28905. const ScopedLock sl (renderLock);
  28906. currentAudioInputBuffer = &buffer;
  28907. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  28908. currentAudioOutputBuffer.clear();
  28909. currentMidiInputBuffer = &midiMessages;
  28910. currentMidiOutputBuffer.clear();
  28911. int i;
  28912. for (i = 0; i < renderingOps.size(); ++i)
  28913. {
  28914. GraphRenderingOps::AudioGraphRenderingOp* const op
  28915. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28916. op->perform (renderingBuffers, midiBuffers, numSamples);
  28917. }
  28918. for (i = 0; i < buffer.getNumChannels(); ++i)
  28919. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  28920. midiMessages.clear();
  28921. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  28922. }
  28923. const String AudioProcessorGraph::getInputChannelName (const int channelIndex) const
  28924. {
  28925. return "Input " + String (channelIndex + 1);
  28926. }
  28927. const String AudioProcessorGraph::getOutputChannelName (const int channelIndex) const
  28928. {
  28929. return "Output " + String (channelIndex + 1);
  28930. }
  28931. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const
  28932. {
  28933. return true;
  28934. }
  28935. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const
  28936. {
  28937. return true;
  28938. }
  28939. bool AudioProcessorGraph::acceptsMidi() const
  28940. {
  28941. return true;
  28942. }
  28943. bool AudioProcessorGraph::producesMidi() const
  28944. {
  28945. return true;
  28946. }
  28947. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/)
  28948. {
  28949. }
  28950. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/)
  28951. {
  28952. }
  28953. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  28954. : type (type_),
  28955. graph (0)
  28956. {
  28957. }
  28958. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  28959. {
  28960. }
  28961. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  28962. {
  28963. switch (type)
  28964. {
  28965. case audioOutputNode:
  28966. return "Audio Output";
  28967. case audioInputNode:
  28968. return "Audio Input";
  28969. case midiOutputNode:
  28970. return "Midi Output";
  28971. case midiInputNode:
  28972. return "Midi Input";
  28973. default:
  28974. break;
  28975. }
  28976. return String::empty;
  28977. }
  28978. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  28979. {
  28980. d.name = getName();
  28981. d.uid = d.name.hashCode();
  28982. d.category = "I/O devices";
  28983. d.pluginFormatName = "Internal";
  28984. d.manufacturerName = "Raw Material Software";
  28985. d.version = "1.0";
  28986. d.isInstrument = false;
  28987. d.numInputChannels = getNumInputChannels();
  28988. if (type == audioOutputNode && graph != 0)
  28989. d.numInputChannels = graph->getNumInputChannels();
  28990. d.numOutputChannels = getNumOutputChannels();
  28991. if (type == audioInputNode && graph != 0)
  28992. d.numOutputChannels = graph->getNumOutputChannels();
  28993. }
  28994. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  28995. {
  28996. jassert (graph != 0);
  28997. }
  28998. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  28999. {
  29000. }
  29001. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  29002. MidiBuffer& midiMessages)
  29003. {
  29004. jassert (graph != 0);
  29005. switch (type)
  29006. {
  29007. case audioOutputNode:
  29008. {
  29009. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  29010. buffer.getNumChannels()); --i >= 0;)
  29011. {
  29012. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  29013. }
  29014. break;
  29015. }
  29016. case audioInputNode:
  29017. {
  29018. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  29019. buffer.getNumChannels()); --i >= 0;)
  29020. {
  29021. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  29022. }
  29023. break;
  29024. }
  29025. case midiOutputNode:
  29026. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  29027. break;
  29028. case midiInputNode:
  29029. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  29030. break;
  29031. default:
  29032. break;
  29033. }
  29034. }
  29035. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  29036. {
  29037. return type == midiOutputNode;
  29038. }
  29039. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  29040. {
  29041. return type == midiInputNode;
  29042. }
  29043. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (const int channelIndex) const
  29044. {
  29045. switch (type)
  29046. {
  29047. case audioOutputNode:
  29048. return "Output " + String (channelIndex + 1);
  29049. case midiOutputNode:
  29050. return "Midi Output";
  29051. default:
  29052. break;
  29053. }
  29054. return String::empty;
  29055. }
  29056. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (const int channelIndex) const
  29057. {
  29058. switch (type)
  29059. {
  29060. case audioInputNode:
  29061. return "Input " + String (channelIndex + 1);
  29062. case midiInputNode:
  29063. return "Midi Input";
  29064. default:
  29065. break;
  29066. }
  29067. return String::empty;
  29068. }
  29069. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  29070. {
  29071. return type == audioInputNode || type == audioOutputNode;
  29072. }
  29073. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  29074. {
  29075. return isInputChannelStereoPair (index);
  29076. }
  29077. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  29078. {
  29079. return type == audioInputNode || type == midiInputNode;
  29080. }
  29081. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  29082. {
  29083. return type == audioOutputNode || type == midiOutputNode;
  29084. }
  29085. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor()
  29086. {
  29087. return 0;
  29088. }
  29089. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  29090. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  29091. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  29092. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  29093. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  29094. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  29095. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  29096. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  29097. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  29098. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  29099. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  29100. {
  29101. }
  29102. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  29103. {
  29104. }
  29105. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  29106. {
  29107. graph = newGraph;
  29108. if (graph != 0)
  29109. {
  29110. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  29111. type == audioInputNode ? graph->getNumInputChannels() : 0,
  29112. getSampleRate(),
  29113. getBlockSize());
  29114. updateHostDisplay();
  29115. }
  29116. }
  29117. END_JUCE_NAMESPACE
  29118. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  29119. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29120. BEGIN_JUCE_NAMESPACE
  29121. AudioProcessorPlayer::AudioProcessorPlayer()
  29122. : processor (0),
  29123. sampleRate (0),
  29124. blockSize (0),
  29125. isPrepared (false),
  29126. numInputChans (0),
  29127. numOutputChans (0),
  29128. tempBuffer (1, 1)
  29129. {
  29130. }
  29131. AudioProcessorPlayer::~AudioProcessorPlayer()
  29132. {
  29133. setProcessor (0);
  29134. }
  29135. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  29136. {
  29137. if (processor != processorToPlay)
  29138. {
  29139. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  29140. {
  29141. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  29142. sampleRate, blockSize);
  29143. processorToPlay->prepareToPlay (sampleRate, blockSize);
  29144. }
  29145. AudioProcessor* oldOne;
  29146. {
  29147. const ScopedLock sl (lock);
  29148. oldOne = isPrepared ? processor : 0;
  29149. processor = processorToPlay;
  29150. isPrepared = true;
  29151. }
  29152. if (oldOne != 0)
  29153. oldOne->releaseResources();
  29154. }
  29155. }
  29156. void AudioProcessorPlayer::audioDeviceIOCallback (const float** inputChannelData,
  29157. int numInputChannels,
  29158. float** outputChannelData,
  29159. int numOutputChannels,
  29160. int numSamples)
  29161. {
  29162. // these should have been prepared by audioDeviceAboutToStart()...
  29163. jassert (sampleRate > 0 && blockSize > 0);
  29164. incomingMidi.clear();
  29165. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  29166. int i, totalNumChans = 0;
  29167. if (numInputChannels > numOutputChannels)
  29168. {
  29169. // if there aren't enough output channels for the number of
  29170. // inputs, we need to create some temporary extra ones (can't
  29171. // use the input data in case it gets written to)
  29172. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  29173. false, false, true);
  29174. for (i = 0; i < numOutputChannels; ++i)
  29175. {
  29176. channels[totalNumChans] = outputChannelData[i];
  29177. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29178. ++totalNumChans;
  29179. }
  29180. for (i = numOutputChannels; i < numInputChannels; ++i)
  29181. {
  29182. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  29183. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29184. ++totalNumChans;
  29185. }
  29186. }
  29187. else
  29188. {
  29189. for (i = 0; i < numInputChannels; ++i)
  29190. {
  29191. channels[totalNumChans] = outputChannelData[i];
  29192. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29193. ++totalNumChans;
  29194. }
  29195. for (i = numInputChannels; i < numOutputChannels; ++i)
  29196. {
  29197. channels[totalNumChans] = outputChannelData[i];
  29198. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  29199. ++totalNumChans;
  29200. }
  29201. }
  29202. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  29203. const ScopedLock sl (lock);
  29204. if (processor != 0)
  29205. processor->processBlock (buffer, incomingMidi);
  29206. }
  29207. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  29208. {
  29209. const ScopedLock sl (lock);
  29210. sampleRate = device->getCurrentSampleRate();
  29211. blockSize = device->getCurrentBufferSizeSamples();
  29212. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  29213. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  29214. messageCollector.reset (sampleRate);
  29215. zeromem (channels, sizeof (channels));
  29216. if (processor != 0)
  29217. {
  29218. if (isPrepared)
  29219. processor->releaseResources();
  29220. AudioProcessor* const oldProcessor = processor;
  29221. setProcessor (0);
  29222. setProcessor (oldProcessor);
  29223. }
  29224. }
  29225. void AudioProcessorPlayer::audioDeviceStopped()
  29226. {
  29227. const ScopedLock sl (lock);
  29228. if (processor != 0 && isPrepared)
  29229. processor->releaseResources();
  29230. sampleRate = 0.0;
  29231. blockSize = 0;
  29232. isPrepared = false;
  29233. tempBuffer.setSize (1, 1);
  29234. }
  29235. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  29236. {
  29237. messageCollector.addMessageToQueue (message);
  29238. }
  29239. END_JUCE_NAMESPACE
  29240. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29241. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29242. BEGIN_JUCE_NAMESPACE
  29243. class ProcessorParameterPropertyComp : public PropertyComponent,
  29244. public AudioProcessorListener,
  29245. public AsyncUpdater
  29246. {
  29247. public:
  29248. ProcessorParameterPropertyComp (const String& name,
  29249. AudioProcessor* const owner_,
  29250. const int index_)
  29251. : PropertyComponent (name),
  29252. owner (owner_),
  29253. index (index_)
  29254. {
  29255. addAndMakeVisible (slider = new ParamSlider (owner_, index_));
  29256. owner_->addListener (this);
  29257. }
  29258. ~ProcessorParameterPropertyComp()
  29259. {
  29260. owner->removeListener (this);
  29261. deleteAllChildren();
  29262. }
  29263. void refresh()
  29264. {
  29265. slider->setValue (owner->getParameter (index), false);
  29266. }
  29267. void audioProcessorChanged (AudioProcessor*) {}
  29268. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  29269. {
  29270. if (parameterIndex == index)
  29271. triggerAsyncUpdate();
  29272. }
  29273. void handleAsyncUpdate()
  29274. {
  29275. refresh();
  29276. }
  29277. juce_UseDebuggingNewOperator
  29278. private:
  29279. AudioProcessor* const owner;
  29280. const int index;
  29281. Slider* slider;
  29282. class ParamSlider : public Slider
  29283. {
  29284. public:
  29285. ParamSlider (AudioProcessor* const owner_, const int index_)
  29286. : Slider (String::empty),
  29287. owner (owner_),
  29288. index (index_)
  29289. {
  29290. setRange (0.0, 1.0, 0.0);
  29291. setSliderStyle (Slider::LinearBar);
  29292. setTextBoxIsEditable (false);
  29293. setScrollWheelEnabled (false);
  29294. }
  29295. ~ParamSlider()
  29296. {
  29297. }
  29298. void valueChanged()
  29299. {
  29300. const float newVal = (float) getValue();
  29301. if (owner->getParameter (index) != newVal)
  29302. owner->setParameter (index, newVal);
  29303. }
  29304. const String getTextFromValue (double /*value*/)
  29305. {
  29306. return owner->getParameterText (index);
  29307. }
  29308. juce_UseDebuggingNewOperator
  29309. private:
  29310. AudioProcessor* const owner;
  29311. const int index;
  29312. ParamSlider (const ParamSlider&);
  29313. ParamSlider& operator= (const ParamSlider&);
  29314. };
  29315. ProcessorParameterPropertyComp (const ProcessorParameterPropertyComp&);
  29316. ProcessorParameterPropertyComp& operator= (const ProcessorParameterPropertyComp&);
  29317. };
  29318. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  29319. : AudioProcessorEditor (owner_)
  29320. {
  29321. setOpaque (true);
  29322. addAndMakeVisible (panel = new PropertyPanel());
  29323. Array <PropertyComponent*> params;
  29324. const int numParams = owner_->getNumParameters();
  29325. int totalHeight = 0;
  29326. for (int i = 0; i < numParams; ++i)
  29327. {
  29328. String name (owner_->getParameterName (i));
  29329. if (name.trim().isEmpty())
  29330. name = "Unnamed";
  29331. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, owner_, i);
  29332. params.add (pc);
  29333. totalHeight += pc->getPreferredHeight();
  29334. }
  29335. panel->addProperties (params);
  29336. setSize (400, jlimit (25, 400, totalHeight));
  29337. }
  29338. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  29339. {
  29340. deleteAllChildren();
  29341. }
  29342. void GenericAudioProcessorEditor::paint (Graphics& g)
  29343. {
  29344. g.fillAll (Colours::white);
  29345. }
  29346. void GenericAudioProcessorEditor::resized()
  29347. {
  29348. panel->setSize (getWidth(), getHeight());
  29349. }
  29350. END_JUCE_NAMESPACE
  29351. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29352. /*** Start of inlined file: juce_Sampler.cpp ***/
  29353. BEGIN_JUCE_NAMESPACE
  29354. SamplerSound::SamplerSound (const String& name_,
  29355. AudioFormatReader& source,
  29356. const BigInteger& midiNotes_,
  29357. const int midiNoteForNormalPitch,
  29358. const double attackTimeSecs,
  29359. const double releaseTimeSecs,
  29360. const double maxSampleLengthSeconds)
  29361. : name (name_),
  29362. midiNotes (midiNotes_),
  29363. midiRootNote (midiNoteForNormalPitch)
  29364. {
  29365. sourceSampleRate = source.sampleRate;
  29366. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  29367. {
  29368. length = 0;
  29369. attackSamples = 0;
  29370. releaseSamples = 0;
  29371. }
  29372. else
  29373. {
  29374. length = jmin ((int) source.lengthInSamples,
  29375. (int) (maxSampleLengthSeconds * sourceSampleRate));
  29376. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  29377. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  29378. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  29379. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  29380. }
  29381. }
  29382. SamplerSound::~SamplerSound()
  29383. {
  29384. }
  29385. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  29386. {
  29387. return midiNotes [midiNoteNumber];
  29388. }
  29389. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  29390. {
  29391. return true;
  29392. }
  29393. SamplerVoice::SamplerVoice()
  29394. : pitchRatio (0.0),
  29395. sourceSamplePosition (0.0),
  29396. lgain (0.0f),
  29397. rgain (0.0f),
  29398. isInAttack (false),
  29399. isInRelease (false)
  29400. {
  29401. }
  29402. SamplerVoice::~SamplerVoice()
  29403. {
  29404. }
  29405. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  29406. {
  29407. return dynamic_cast <const SamplerSound*> (sound) != 0;
  29408. }
  29409. void SamplerVoice::startNote (const int midiNoteNumber,
  29410. const float velocity,
  29411. SynthesiserSound* s,
  29412. const int /*currentPitchWheelPosition*/)
  29413. {
  29414. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  29415. jassert (sound != 0); // this object can only play SamplerSounds!
  29416. if (sound != 0)
  29417. {
  29418. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  29419. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  29420. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  29421. sourceSamplePosition = 0.0;
  29422. lgain = velocity;
  29423. rgain = velocity;
  29424. isInAttack = (sound->attackSamples > 0);
  29425. isInRelease = false;
  29426. if (isInAttack)
  29427. {
  29428. attackReleaseLevel = 0.0f;
  29429. attackDelta = (float) (pitchRatio / sound->attackSamples);
  29430. }
  29431. else
  29432. {
  29433. attackReleaseLevel = 1.0f;
  29434. attackDelta = 0.0f;
  29435. }
  29436. if (sound->releaseSamples > 0)
  29437. {
  29438. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  29439. }
  29440. else
  29441. {
  29442. releaseDelta = 0.0f;
  29443. }
  29444. }
  29445. }
  29446. void SamplerVoice::stopNote (const bool allowTailOff)
  29447. {
  29448. if (allowTailOff)
  29449. {
  29450. isInAttack = false;
  29451. isInRelease = true;
  29452. }
  29453. else
  29454. {
  29455. clearCurrentNote();
  29456. }
  29457. }
  29458. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  29459. {
  29460. }
  29461. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  29462. const int /*newValue*/)
  29463. {
  29464. }
  29465. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  29466. {
  29467. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  29468. if (playingSound != 0)
  29469. {
  29470. const float* const inL = playingSound->data->getSampleData (0, 0);
  29471. const float* const inR = playingSound->data->getNumChannels() > 1
  29472. ? playingSound->data->getSampleData (1, 0) : 0;
  29473. float* outL = outputBuffer.getSampleData (0, startSample);
  29474. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  29475. while (--numSamples >= 0)
  29476. {
  29477. const int pos = (int) sourceSamplePosition;
  29478. const float alpha = (float) (sourceSamplePosition - pos);
  29479. const float invAlpha = 1.0f - alpha;
  29480. // just using a very simple linear interpolation here..
  29481. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  29482. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  29483. : l;
  29484. l *= lgain;
  29485. r *= rgain;
  29486. if (isInAttack)
  29487. {
  29488. l *= attackReleaseLevel;
  29489. r *= attackReleaseLevel;
  29490. attackReleaseLevel += attackDelta;
  29491. if (attackReleaseLevel >= 1.0f)
  29492. {
  29493. attackReleaseLevel = 1.0f;
  29494. isInAttack = false;
  29495. }
  29496. }
  29497. else if (isInRelease)
  29498. {
  29499. l *= attackReleaseLevel;
  29500. r *= attackReleaseLevel;
  29501. attackReleaseLevel += releaseDelta;
  29502. if (attackReleaseLevel <= 0.0f)
  29503. {
  29504. stopNote (false);
  29505. break;
  29506. }
  29507. }
  29508. if (outR != 0)
  29509. {
  29510. *outL++ += l;
  29511. *outR++ += r;
  29512. }
  29513. else
  29514. {
  29515. *outL++ += (l + r) * 0.5f;
  29516. }
  29517. sourceSamplePosition += pitchRatio;
  29518. if (sourceSamplePosition > playingSound->length)
  29519. {
  29520. stopNote (false);
  29521. break;
  29522. }
  29523. }
  29524. }
  29525. }
  29526. END_JUCE_NAMESPACE
  29527. /*** End of inlined file: juce_Sampler.cpp ***/
  29528. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  29529. BEGIN_JUCE_NAMESPACE
  29530. SynthesiserSound::SynthesiserSound()
  29531. {
  29532. }
  29533. SynthesiserSound::~SynthesiserSound()
  29534. {
  29535. }
  29536. SynthesiserVoice::SynthesiserVoice()
  29537. : currentSampleRate (44100.0),
  29538. currentlyPlayingNote (-1),
  29539. noteOnTime (0),
  29540. currentlyPlayingSound (0)
  29541. {
  29542. }
  29543. SynthesiserVoice::~SynthesiserVoice()
  29544. {
  29545. }
  29546. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  29547. {
  29548. return currentlyPlayingSound != 0
  29549. && currentlyPlayingSound->appliesToChannel (midiChannel);
  29550. }
  29551. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  29552. {
  29553. currentSampleRate = newRate;
  29554. }
  29555. void SynthesiserVoice::clearCurrentNote()
  29556. {
  29557. currentlyPlayingNote = -1;
  29558. currentlyPlayingSound = 0;
  29559. }
  29560. Synthesiser::Synthesiser()
  29561. : sampleRate (0),
  29562. lastNoteOnCounter (0),
  29563. shouldStealNotes (true)
  29564. {
  29565. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  29566. lastPitchWheelValues[i] = 0x2000;
  29567. }
  29568. Synthesiser::~Synthesiser()
  29569. {
  29570. }
  29571. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  29572. {
  29573. const ScopedLock sl (lock);
  29574. return voices [index];
  29575. }
  29576. void Synthesiser::clearVoices()
  29577. {
  29578. const ScopedLock sl (lock);
  29579. voices.clear();
  29580. }
  29581. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  29582. {
  29583. const ScopedLock sl (lock);
  29584. voices.add (newVoice);
  29585. }
  29586. void Synthesiser::removeVoice (const int index)
  29587. {
  29588. const ScopedLock sl (lock);
  29589. voices.remove (index);
  29590. }
  29591. void Synthesiser::clearSounds()
  29592. {
  29593. const ScopedLock sl (lock);
  29594. sounds.clear();
  29595. }
  29596. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  29597. {
  29598. const ScopedLock sl (lock);
  29599. sounds.add (newSound);
  29600. }
  29601. void Synthesiser::removeSound (const int index)
  29602. {
  29603. const ScopedLock sl (lock);
  29604. sounds.remove (index);
  29605. }
  29606. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  29607. {
  29608. shouldStealNotes = shouldStealNotes_;
  29609. }
  29610. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  29611. {
  29612. if (sampleRate != newRate)
  29613. {
  29614. const ScopedLock sl (lock);
  29615. allNotesOff (0, false);
  29616. sampleRate = newRate;
  29617. for (int i = voices.size(); --i >= 0;)
  29618. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  29619. }
  29620. }
  29621. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  29622. const MidiBuffer& midiData,
  29623. int startSample,
  29624. int numSamples)
  29625. {
  29626. // must set the sample rate before using this!
  29627. jassert (sampleRate != 0);
  29628. const ScopedLock sl (lock);
  29629. MidiBuffer::Iterator midiIterator (midiData);
  29630. midiIterator.setNextSamplePosition (startSample);
  29631. MidiMessage m (0xf4, 0.0);
  29632. while (numSamples > 0)
  29633. {
  29634. int midiEventPos;
  29635. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  29636. && midiEventPos < startSample + numSamples;
  29637. const int numThisTime = useEvent ? midiEventPos - startSample
  29638. : numSamples;
  29639. if (numThisTime > 0)
  29640. {
  29641. for (int i = voices.size(); --i >= 0;)
  29642. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  29643. }
  29644. if (useEvent)
  29645. {
  29646. if (m.isNoteOn())
  29647. {
  29648. const int channel = m.getChannel();
  29649. noteOn (channel,
  29650. m.getNoteNumber(),
  29651. m.getFloatVelocity());
  29652. }
  29653. else if (m.isNoteOff())
  29654. {
  29655. noteOff (m.getChannel(),
  29656. m.getNoteNumber(),
  29657. true);
  29658. }
  29659. else if (m.isAllNotesOff() || m.isAllSoundOff())
  29660. {
  29661. allNotesOff (m.getChannel(), true);
  29662. }
  29663. else if (m.isPitchWheel())
  29664. {
  29665. const int channel = m.getChannel();
  29666. const int wheelPos = m.getPitchWheelValue();
  29667. lastPitchWheelValues [channel - 1] = wheelPos;
  29668. handlePitchWheel (channel, wheelPos);
  29669. }
  29670. else if (m.isController())
  29671. {
  29672. handleController (m.getChannel(),
  29673. m.getControllerNumber(),
  29674. m.getControllerValue());
  29675. }
  29676. }
  29677. startSample += numThisTime;
  29678. numSamples -= numThisTime;
  29679. }
  29680. }
  29681. void Synthesiser::noteOn (const int midiChannel,
  29682. const int midiNoteNumber,
  29683. const float velocity)
  29684. {
  29685. const ScopedLock sl (lock);
  29686. for (int i = sounds.size(); --i >= 0;)
  29687. {
  29688. SynthesiserSound* const sound = sounds.getUnchecked(i);
  29689. if (sound->appliesToNote (midiNoteNumber)
  29690. && sound->appliesToChannel (midiChannel))
  29691. {
  29692. startVoice (findFreeVoice (sound, shouldStealNotes),
  29693. sound, midiChannel, midiNoteNumber, velocity);
  29694. }
  29695. }
  29696. }
  29697. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  29698. SynthesiserSound* const sound,
  29699. const int midiChannel,
  29700. const int midiNoteNumber,
  29701. const float velocity)
  29702. {
  29703. if (voice != 0 && sound != 0)
  29704. {
  29705. if (voice->currentlyPlayingSound != 0)
  29706. voice->stopNote (false);
  29707. voice->startNote (midiNoteNumber,
  29708. velocity,
  29709. sound,
  29710. lastPitchWheelValues [midiChannel - 1]);
  29711. voice->currentlyPlayingNote = midiNoteNumber;
  29712. voice->noteOnTime = ++lastNoteOnCounter;
  29713. voice->currentlyPlayingSound = sound;
  29714. }
  29715. }
  29716. void Synthesiser::noteOff (const int midiChannel,
  29717. const int midiNoteNumber,
  29718. const bool allowTailOff)
  29719. {
  29720. const ScopedLock sl (lock);
  29721. for (int i = voices.size(); --i >= 0;)
  29722. {
  29723. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29724. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  29725. {
  29726. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  29727. if (sound != 0
  29728. && sound->appliesToNote (midiNoteNumber)
  29729. && sound->appliesToChannel (midiChannel))
  29730. {
  29731. voice->stopNote (allowTailOff);
  29732. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  29733. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  29734. }
  29735. }
  29736. }
  29737. }
  29738. void Synthesiser::allNotesOff (const int midiChannel,
  29739. const bool allowTailOff)
  29740. {
  29741. const ScopedLock sl (lock);
  29742. for (int i = voices.size(); --i >= 0;)
  29743. {
  29744. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29745. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29746. voice->stopNote (allowTailOff);
  29747. }
  29748. }
  29749. void Synthesiser::handlePitchWheel (const int midiChannel,
  29750. const int wheelValue)
  29751. {
  29752. const ScopedLock sl (lock);
  29753. for (int i = voices.size(); --i >= 0;)
  29754. {
  29755. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29756. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29757. {
  29758. voice->pitchWheelMoved (wheelValue);
  29759. }
  29760. }
  29761. }
  29762. void Synthesiser::handleController (const int midiChannel,
  29763. const int controllerNumber,
  29764. const int controllerValue)
  29765. {
  29766. const ScopedLock sl (lock);
  29767. for (int i = voices.size(); --i >= 0;)
  29768. {
  29769. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29770. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29771. voice->controllerMoved (controllerNumber, controllerValue);
  29772. }
  29773. }
  29774. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  29775. const bool stealIfNoneAvailable) const
  29776. {
  29777. const ScopedLock sl (lock);
  29778. for (int i = voices.size(); --i >= 0;)
  29779. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  29780. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  29781. return voices.getUnchecked (i);
  29782. if (stealIfNoneAvailable)
  29783. {
  29784. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  29785. SynthesiserVoice* oldest = 0;
  29786. for (int i = voices.size(); --i >= 0;)
  29787. {
  29788. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29789. if (voice->canPlaySound (soundToPlay)
  29790. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  29791. oldest = voice;
  29792. }
  29793. jassert (oldest != 0);
  29794. return oldest;
  29795. }
  29796. return 0;
  29797. }
  29798. END_JUCE_NAMESPACE
  29799. /*** End of inlined file: juce_Synthesiser.cpp ***/
  29800. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  29801. BEGIN_JUCE_NAMESPACE
  29802. ActionBroadcaster::ActionBroadcaster() throw()
  29803. {
  29804. // are you trying to create this object before or after juce has been intialised??
  29805. jassert (MessageManager::instance != 0);
  29806. }
  29807. ActionBroadcaster::~ActionBroadcaster()
  29808. {
  29809. // all event-based objects must be deleted BEFORE juce is shut down!
  29810. jassert (MessageManager::instance != 0);
  29811. }
  29812. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  29813. {
  29814. actionListenerList.addActionListener (listener);
  29815. }
  29816. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  29817. {
  29818. jassert (actionListenerList.isValidMessageListener());
  29819. if (actionListenerList.isValidMessageListener())
  29820. actionListenerList.removeActionListener (listener);
  29821. }
  29822. void ActionBroadcaster::removeAllActionListeners()
  29823. {
  29824. actionListenerList.removeAllActionListeners();
  29825. }
  29826. void ActionBroadcaster::sendActionMessage (const String& message) const
  29827. {
  29828. actionListenerList.sendActionMessage (message);
  29829. }
  29830. END_JUCE_NAMESPACE
  29831. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  29832. /*** Start of inlined file: juce_ActionListenerList.cpp ***/
  29833. BEGIN_JUCE_NAMESPACE
  29834. // special message of our own with a string in it
  29835. class ActionMessage : public Message
  29836. {
  29837. public:
  29838. const String message;
  29839. ActionMessage (const String& messageText,
  29840. void* const listener_) throw()
  29841. : message (messageText)
  29842. {
  29843. pointerParameter = listener_;
  29844. }
  29845. ~ActionMessage() throw()
  29846. {
  29847. }
  29848. private:
  29849. ActionMessage (const ActionMessage&);
  29850. ActionMessage& operator= (const ActionMessage&);
  29851. };
  29852. ActionListenerList::ActionListenerList() throw()
  29853. {
  29854. }
  29855. ActionListenerList::~ActionListenerList() throw()
  29856. {
  29857. }
  29858. void ActionListenerList::addActionListener (ActionListener* const listener) throw()
  29859. {
  29860. const ScopedLock sl (actionListenerLock_);
  29861. jassert (listener != 0);
  29862. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  29863. if (listener != 0)
  29864. actionListeners_.add (listener);
  29865. }
  29866. void ActionListenerList::removeActionListener (ActionListener* const listener) throw()
  29867. {
  29868. const ScopedLock sl (actionListenerLock_);
  29869. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  29870. actionListeners_.removeValue (listener);
  29871. }
  29872. void ActionListenerList::removeAllActionListeners() throw()
  29873. {
  29874. const ScopedLock sl (actionListenerLock_);
  29875. actionListeners_.clear();
  29876. }
  29877. void ActionListenerList::sendActionMessage (const String& message) const
  29878. {
  29879. const ScopedLock sl (actionListenerLock_);
  29880. for (int i = actionListeners_.size(); --i >= 0;)
  29881. postMessage (new ActionMessage (message, static_cast <ActionListener*> (actionListeners_.getUnchecked(i))));
  29882. }
  29883. void ActionListenerList::handleMessage (const Message& message)
  29884. {
  29885. const ActionMessage& am = (const ActionMessage&) message;
  29886. if (actionListeners_.contains (am.pointerParameter))
  29887. static_cast <ActionListener*> (am.pointerParameter)->actionListenerCallback (am.message);
  29888. }
  29889. END_JUCE_NAMESPACE
  29890. /*** End of inlined file: juce_ActionListenerList.cpp ***/
  29891. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  29892. BEGIN_JUCE_NAMESPACE
  29893. AsyncUpdater::AsyncUpdater() throw()
  29894. : asyncMessagePending (false)
  29895. {
  29896. internalAsyncHandler.owner = this;
  29897. }
  29898. AsyncUpdater::~AsyncUpdater()
  29899. {
  29900. }
  29901. void AsyncUpdater::triggerAsyncUpdate() throw()
  29902. {
  29903. if (! asyncMessagePending)
  29904. {
  29905. asyncMessagePending = true;
  29906. internalAsyncHandler.postMessage (new Message());
  29907. }
  29908. }
  29909. void AsyncUpdater::cancelPendingUpdate() throw()
  29910. {
  29911. asyncMessagePending = false;
  29912. }
  29913. void AsyncUpdater::handleUpdateNowIfNeeded()
  29914. {
  29915. if (asyncMessagePending)
  29916. {
  29917. asyncMessagePending = false;
  29918. handleAsyncUpdate();
  29919. }
  29920. }
  29921. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  29922. {
  29923. owner->handleUpdateNowIfNeeded();
  29924. }
  29925. END_JUCE_NAMESPACE
  29926. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  29927. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  29928. BEGIN_JUCE_NAMESPACE
  29929. ChangeBroadcaster::ChangeBroadcaster() throw()
  29930. {
  29931. // are you trying to create this object before or after juce has been intialised??
  29932. jassert (MessageManager::instance != 0);
  29933. }
  29934. ChangeBroadcaster::~ChangeBroadcaster()
  29935. {
  29936. // all event-based objects must be deleted BEFORE juce is shut down!
  29937. jassert (MessageManager::instance != 0);
  29938. }
  29939. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener) throw()
  29940. {
  29941. changeListenerList.addChangeListener (listener);
  29942. }
  29943. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener) throw()
  29944. {
  29945. jassert (changeListenerList.isValidMessageListener());
  29946. if (changeListenerList.isValidMessageListener())
  29947. changeListenerList.removeChangeListener (listener);
  29948. }
  29949. void ChangeBroadcaster::removeAllChangeListeners() throw()
  29950. {
  29951. changeListenerList.removeAllChangeListeners();
  29952. }
  29953. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged) throw()
  29954. {
  29955. changeListenerList.sendChangeMessage (objectThatHasChanged);
  29956. }
  29957. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  29958. {
  29959. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  29960. }
  29961. void ChangeBroadcaster::dispatchPendingMessages()
  29962. {
  29963. changeListenerList.dispatchPendingMessages();
  29964. }
  29965. END_JUCE_NAMESPACE
  29966. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  29967. /*** Start of inlined file: juce_ChangeListenerList.cpp ***/
  29968. BEGIN_JUCE_NAMESPACE
  29969. ChangeListenerList::ChangeListenerList() throw()
  29970. : lastChangedObject (0),
  29971. messagePending (false)
  29972. {
  29973. }
  29974. ChangeListenerList::~ChangeListenerList() throw()
  29975. {
  29976. }
  29977. void ChangeListenerList::addChangeListener (ChangeListener* const listener) throw()
  29978. {
  29979. const ScopedLock sl (lock);
  29980. jassert (listener != 0);
  29981. if (listener != 0)
  29982. listeners.add (listener);
  29983. }
  29984. void ChangeListenerList::removeChangeListener (ChangeListener* const listener) throw()
  29985. {
  29986. const ScopedLock sl (lock);
  29987. listeners.removeValue (listener);
  29988. }
  29989. void ChangeListenerList::removeAllChangeListeners() throw()
  29990. {
  29991. const ScopedLock sl (lock);
  29992. listeners.clear();
  29993. }
  29994. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged) throw()
  29995. {
  29996. const ScopedLock sl (lock);
  29997. if ((! messagePending) && (listeners.size() > 0))
  29998. {
  29999. lastChangedObject = objectThatHasChanged;
  30000. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  30001. messagePending = true;
  30002. }
  30003. }
  30004. void ChangeListenerList::handleMessage (const Message& message)
  30005. {
  30006. sendSynchronousChangeMessage (message.pointerParameter);
  30007. }
  30008. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  30009. {
  30010. const ScopedLock sl (lock);
  30011. messagePending = false;
  30012. for (int i = listeners.size(); --i >= 0;)
  30013. {
  30014. ChangeListener* const l = static_cast <ChangeListener*> (listeners.getUnchecked (i));
  30015. {
  30016. const ScopedUnlock tempUnlocker (lock);
  30017. l->changeListenerCallback (objectThatHasChanged);
  30018. }
  30019. i = jmin (i, listeners.size());
  30020. }
  30021. }
  30022. void ChangeListenerList::dispatchPendingMessages()
  30023. {
  30024. if (messagePending)
  30025. sendSynchronousChangeMessage (lastChangedObject);
  30026. }
  30027. END_JUCE_NAMESPACE
  30028. /*** End of inlined file: juce_ChangeListenerList.cpp ***/
  30029. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  30030. BEGIN_JUCE_NAMESPACE
  30031. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30032. const uint32 magicMessageHeaderNumber)
  30033. : Thread ("Juce IPC connection"),
  30034. callbackConnectionState (false),
  30035. useMessageThread (callbacksOnMessageThread),
  30036. magicMessageHeader (magicMessageHeaderNumber),
  30037. pipeReceiveMessageTimeout (-1)
  30038. {
  30039. }
  30040. InterprocessConnection::~InterprocessConnection()
  30041. {
  30042. callbackConnectionState = false;
  30043. disconnect();
  30044. }
  30045. bool InterprocessConnection::connectToSocket (const String& hostName,
  30046. const int portNumber,
  30047. const int timeOutMillisecs)
  30048. {
  30049. disconnect();
  30050. const ScopedLock sl (pipeAndSocketLock);
  30051. socket = new StreamingSocket();
  30052. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  30053. {
  30054. connectionMadeInt();
  30055. startThread();
  30056. return true;
  30057. }
  30058. else
  30059. {
  30060. socket = 0;
  30061. return false;
  30062. }
  30063. }
  30064. bool InterprocessConnection::connectToPipe (const String& pipeName,
  30065. const int pipeReceiveMessageTimeoutMs)
  30066. {
  30067. disconnect();
  30068. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30069. if (newPipe->openExisting (pipeName))
  30070. {
  30071. const ScopedLock sl (pipeAndSocketLock);
  30072. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30073. initialiseWithPipe (newPipe.release());
  30074. return true;
  30075. }
  30076. return false;
  30077. }
  30078. bool InterprocessConnection::createPipe (const String& pipeName,
  30079. const int pipeReceiveMessageTimeoutMs)
  30080. {
  30081. disconnect();
  30082. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30083. if (newPipe->createNewPipe (pipeName))
  30084. {
  30085. const ScopedLock sl (pipeAndSocketLock);
  30086. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30087. initialiseWithPipe (newPipe.release());
  30088. return true;
  30089. }
  30090. return false;
  30091. }
  30092. void InterprocessConnection::disconnect()
  30093. {
  30094. if (socket != 0)
  30095. socket->close();
  30096. if (pipe != 0)
  30097. {
  30098. pipe->cancelPendingReads();
  30099. pipe->close();
  30100. }
  30101. stopThread (4000);
  30102. {
  30103. const ScopedLock sl (pipeAndSocketLock);
  30104. socket = 0;
  30105. pipe = 0;
  30106. }
  30107. connectionLostInt();
  30108. }
  30109. bool InterprocessConnection::isConnected() const
  30110. {
  30111. const ScopedLock sl (pipeAndSocketLock);
  30112. return ((socket != 0 && socket->isConnected())
  30113. || (pipe != 0 && pipe->isOpen()))
  30114. && isThreadRunning();
  30115. }
  30116. const String InterprocessConnection::getConnectedHostName() const
  30117. {
  30118. if (pipe != 0)
  30119. {
  30120. return "localhost";
  30121. }
  30122. else if (socket != 0)
  30123. {
  30124. if (! socket->isLocal())
  30125. return socket->getHostName();
  30126. return "localhost";
  30127. }
  30128. return String::empty;
  30129. }
  30130. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  30131. {
  30132. uint32 messageHeader[2];
  30133. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  30134. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  30135. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  30136. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  30137. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  30138. size_t bytesWritten = 0;
  30139. const ScopedLock sl (pipeAndSocketLock);
  30140. if (socket != 0)
  30141. {
  30142. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  30143. }
  30144. else if (pipe != 0)
  30145. {
  30146. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  30147. }
  30148. if (bytesWritten < 0)
  30149. {
  30150. // error..
  30151. return false;
  30152. }
  30153. return (bytesWritten == messageData.getSize());
  30154. }
  30155. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  30156. {
  30157. jassert (socket == 0);
  30158. socket = socket_;
  30159. connectionMadeInt();
  30160. startThread();
  30161. }
  30162. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  30163. {
  30164. jassert (pipe == 0);
  30165. pipe = pipe_;
  30166. connectionMadeInt();
  30167. startThread();
  30168. }
  30169. const int messageMagicNumber = 0xb734128b;
  30170. void InterprocessConnection::handleMessage (const Message& message)
  30171. {
  30172. if (message.intParameter1 == messageMagicNumber)
  30173. {
  30174. switch (message.intParameter2)
  30175. {
  30176. case 0:
  30177. {
  30178. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  30179. messageReceived (*data);
  30180. break;
  30181. }
  30182. case 1:
  30183. connectionMade();
  30184. break;
  30185. case 2:
  30186. connectionLost();
  30187. break;
  30188. }
  30189. }
  30190. }
  30191. void InterprocessConnection::connectionMadeInt()
  30192. {
  30193. if (! callbackConnectionState)
  30194. {
  30195. callbackConnectionState = true;
  30196. if (useMessageThread)
  30197. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  30198. else
  30199. connectionMade();
  30200. }
  30201. }
  30202. void InterprocessConnection::connectionLostInt()
  30203. {
  30204. if (callbackConnectionState)
  30205. {
  30206. callbackConnectionState = false;
  30207. if (useMessageThread)
  30208. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  30209. else
  30210. connectionLost();
  30211. }
  30212. }
  30213. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  30214. {
  30215. jassert (callbackConnectionState);
  30216. if (useMessageThread)
  30217. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  30218. else
  30219. messageReceived (data);
  30220. }
  30221. bool InterprocessConnection::readNextMessageInt()
  30222. {
  30223. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  30224. uint32 messageHeader[2];
  30225. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  30226. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  30227. if (bytes == sizeof (messageHeader)
  30228. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  30229. {
  30230. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  30231. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  30232. {
  30233. MemoryBlock messageData (bytesInMessage, true);
  30234. int bytesRead = 0;
  30235. while (bytesInMessage > 0)
  30236. {
  30237. if (threadShouldExit())
  30238. return false;
  30239. const int numThisTime = jmin (bytesInMessage, 65536);
  30240. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  30241. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  30242. if (bytesIn <= 0)
  30243. break;
  30244. bytesRead += bytesIn;
  30245. bytesInMessage -= bytesIn;
  30246. }
  30247. if (bytesRead >= 0)
  30248. deliverDataInt (messageData);
  30249. }
  30250. }
  30251. else if (bytes < 0)
  30252. {
  30253. {
  30254. const ScopedLock sl (pipeAndSocketLock);
  30255. socket = 0;
  30256. }
  30257. connectionLostInt();
  30258. return false;
  30259. }
  30260. return true;
  30261. }
  30262. void InterprocessConnection::run()
  30263. {
  30264. while (! threadShouldExit())
  30265. {
  30266. if (socket != 0)
  30267. {
  30268. const int ready = socket->waitUntilReady (true, 0);
  30269. if (ready < 0)
  30270. {
  30271. {
  30272. const ScopedLock sl (pipeAndSocketLock);
  30273. socket = 0;
  30274. }
  30275. connectionLostInt();
  30276. break;
  30277. }
  30278. else if (ready > 0)
  30279. {
  30280. if (! readNextMessageInt())
  30281. break;
  30282. }
  30283. else
  30284. {
  30285. Thread::sleep (2);
  30286. }
  30287. }
  30288. else if (pipe != 0)
  30289. {
  30290. if (! pipe->isOpen())
  30291. {
  30292. {
  30293. const ScopedLock sl (pipeAndSocketLock);
  30294. pipe = 0;
  30295. }
  30296. connectionLostInt();
  30297. break;
  30298. }
  30299. else
  30300. {
  30301. if (! readNextMessageInt())
  30302. break;
  30303. }
  30304. }
  30305. else
  30306. {
  30307. break;
  30308. }
  30309. }
  30310. }
  30311. END_JUCE_NAMESPACE
  30312. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  30313. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30314. BEGIN_JUCE_NAMESPACE
  30315. InterprocessConnectionServer::InterprocessConnectionServer()
  30316. : Thread ("Juce IPC server")
  30317. {
  30318. }
  30319. InterprocessConnectionServer::~InterprocessConnectionServer()
  30320. {
  30321. stop();
  30322. }
  30323. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  30324. {
  30325. stop();
  30326. socket = new StreamingSocket();
  30327. if (socket->createListener (portNumber))
  30328. {
  30329. startThread();
  30330. return true;
  30331. }
  30332. socket = 0;
  30333. return false;
  30334. }
  30335. void InterprocessConnectionServer::stop()
  30336. {
  30337. signalThreadShouldExit();
  30338. if (socket != 0)
  30339. socket->close();
  30340. stopThread (4000);
  30341. socket = 0;
  30342. }
  30343. void InterprocessConnectionServer::run()
  30344. {
  30345. while ((! threadShouldExit()) && socket != 0)
  30346. {
  30347. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  30348. if (clientSocket != 0)
  30349. {
  30350. InterprocessConnection* newConnection = createConnectionObject();
  30351. if (newConnection != 0)
  30352. newConnection->initialiseWithSocket (clientSocket.release());
  30353. }
  30354. }
  30355. }
  30356. END_JUCE_NAMESPACE
  30357. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30358. /*** Start of inlined file: juce_Message.cpp ***/
  30359. BEGIN_JUCE_NAMESPACE
  30360. Message::Message() throw()
  30361. : intParameter1 (0),
  30362. intParameter2 (0),
  30363. intParameter3 (0),
  30364. pointerParameter (0)
  30365. {
  30366. }
  30367. Message::Message (const int intParameter1_,
  30368. const int intParameter2_,
  30369. const int intParameter3_,
  30370. void* const pointerParameter_) throw()
  30371. : intParameter1 (intParameter1_),
  30372. intParameter2 (intParameter2_),
  30373. intParameter3 (intParameter3_),
  30374. pointerParameter (pointerParameter_)
  30375. {
  30376. }
  30377. Message::~Message() throw()
  30378. {
  30379. }
  30380. END_JUCE_NAMESPACE
  30381. /*** End of inlined file: juce_Message.cpp ***/
  30382. /*** Start of inlined file: juce_MessageListener.cpp ***/
  30383. BEGIN_JUCE_NAMESPACE
  30384. MessageListener::MessageListener() throw()
  30385. {
  30386. // are you trying to create a messagelistener before or after juce has been intialised??
  30387. jassert (MessageManager::instance != 0);
  30388. if (MessageManager::instance != 0)
  30389. MessageManager::instance->messageListeners.add (this);
  30390. }
  30391. MessageListener::~MessageListener()
  30392. {
  30393. if (MessageManager::instance != 0)
  30394. MessageManager::instance->messageListeners.removeValue (this);
  30395. }
  30396. void MessageListener::postMessage (Message* const message) const throw()
  30397. {
  30398. message->messageRecipient = const_cast <MessageListener*> (this);
  30399. if (MessageManager::instance == 0)
  30400. MessageManager::getInstance();
  30401. MessageManager::instance->postMessageToQueue (message);
  30402. }
  30403. bool MessageListener::isValidMessageListener() const throw()
  30404. {
  30405. return (MessageManager::instance != 0)
  30406. && MessageManager::instance->messageListeners.contains (this);
  30407. }
  30408. END_JUCE_NAMESPACE
  30409. /*** End of inlined file: juce_MessageListener.cpp ***/
  30410. /*** Start of inlined file: juce_MessageManager.cpp ***/
  30411. BEGIN_JUCE_NAMESPACE
  30412. // platform-specific functions..
  30413. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  30414. bool juce_postMessageToSystemQueue (void* message);
  30415. MessageManager* MessageManager::instance = 0;
  30416. static const int quitMessageId = 0xfffff321;
  30417. MessageManager::MessageManager() throw()
  30418. : quitMessagePosted (false),
  30419. quitMessageReceived (false),
  30420. threadWithLock (0)
  30421. {
  30422. messageThreadId = Thread::getCurrentThreadId();
  30423. }
  30424. MessageManager::~MessageManager() throw()
  30425. {
  30426. broadcastListeners = 0;
  30427. doPlatformSpecificShutdown();
  30428. jassert (instance == this);
  30429. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  30430. }
  30431. MessageManager* MessageManager::getInstance() throw()
  30432. {
  30433. if (instance == 0)
  30434. {
  30435. instance = new MessageManager();
  30436. doPlatformSpecificInitialisation();
  30437. }
  30438. return instance;
  30439. }
  30440. void MessageManager::postMessageToQueue (Message* const message)
  30441. {
  30442. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  30443. delete message;
  30444. }
  30445. CallbackMessage::CallbackMessage() throw() {}
  30446. CallbackMessage::~CallbackMessage() throw() {}
  30447. void CallbackMessage::post()
  30448. {
  30449. if (MessageManager::instance != 0)
  30450. MessageManager::instance->postCallbackMessage (this);
  30451. }
  30452. void MessageManager::postCallbackMessage (Message* const message)
  30453. {
  30454. message->messageRecipient = 0;
  30455. postMessageToQueue (message);
  30456. }
  30457. // not for public use..
  30458. void MessageManager::deliverMessage (void* const message)
  30459. {
  30460. const ScopedPointer <Message> m (static_cast <Message*> (message));
  30461. MessageListener* const recipient = m->messageRecipient;
  30462. JUCE_TRY
  30463. {
  30464. if (messageListeners.contains (recipient))
  30465. {
  30466. recipient->handleMessage (*m);
  30467. }
  30468. else if (recipient == 0)
  30469. {
  30470. if (m->intParameter1 == quitMessageId)
  30471. {
  30472. quitMessageReceived = true;
  30473. }
  30474. else
  30475. {
  30476. CallbackMessage* const cm = dynamic_cast <CallbackMessage*> (static_cast <Message*> (m));
  30477. if (cm != 0)
  30478. cm->messageCallback();
  30479. }
  30480. }
  30481. }
  30482. JUCE_CATCH_EXCEPTION
  30483. }
  30484. #if ! (JUCE_MAC || JUCE_IPHONE)
  30485. void MessageManager::runDispatchLoop()
  30486. {
  30487. jassert (isThisTheMessageThread()); // must only be called by the message thread
  30488. runDispatchLoopUntil (-1);
  30489. }
  30490. void MessageManager::stopDispatchLoop()
  30491. {
  30492. Message* const m = new Message (quitMessageId, 0, 0, 0);
  30493. m->messageRecipient = 0;
  30494. postMessageToQueue (m);
  30495. quitMessagePosted = true;
  30496. }
  30497. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  30498. {
  30499. jassert (isThisTheMessageThread()); // must only be called by the message thread
  30500. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  30501. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  30502. && ! quitMessageReceived)
  30503. {
  30504. JUCE_TRY
  30505. {
  30506. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  30507. {
  30508. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  30509. if (msToWait > 0)
  30510. Thread::sleep (jmin (5, msToWait));
  30511. }
  30512. }
  30513. JUCE_CATCH_EXCEPTION
  30514. }
  30515. return ! quitMessageReceived;
  30516. }
  30517. #endif
  30518. void MessageManager::deliverBroadcastMessage (const String& value)
  30519. {
  30520. if (broadcastListeners != 0)
  30521. broadcastListeners->sendActionMessage (value);
  30522. }
  30523. void MessageManager::registerBroadcastListener (ActionListener* const listener) throw()
  30524. {
  30525. if (broadcastListeners == 0)
  30526. broadcastListeners = new ActionListenerList();
  30527. broadcastListeners->addActionListener (listener);
  30528. }
  30529. void MessageManager::deregisterBroadcastListener (ActionListener* const listener) throw()
  30530. {
  30531. if (broadcastListeners != 0)
  30532. broadcastListeners->removeActionListener (listener);
  30533. }
  30534. bool MessageManager::isThisTheMessageThread() const throw()
  30535. {
  30536. return Thread::getCurrentThreadId() == messageThreadId;
  30537. }
  30538. void MessageManager::setCurrentThreadAsMessageThread()
  30539. {
  30540. if (messageThreadId != Thread::getCurrentThreadId())
  30541. {
  30542. messageThreadId = Thread::getCurrentThreadId();
  30543. // This is needed on windows to make sure the message window is created by this thread
  30544. doPlatformSpecificShutdown();
  30545. doPlatformSpecificInitialisation();
  30546. }
  30547. }
  30548. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  30549. {
  30550. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  30551. return thisThread == messageThreadId || thisThread == threadWithLock;
  30552. }
  30553. /* The only safe way to lock the message thread while another thread does
  30554. some work is by posting a special message, whose purpose is to tie up the event
  30555. loop until the other thread has finished its business.
  30556. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  30557. get locked before making an event callback, because if the same OS lock gets indirectly
  30558. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  30559. in Cocoa).
  30560. */
  30561. class MessageManagerLock::SharedEvents : public ReferenceCountedObject
  30562. {
  30563. public:
  30564. SharedEvents() {}
  30565. ~SharedEvents() {}
  30566. /* This class just holds a couple of events to communicate between the BlockingMessage
  30567. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  30568. this shared data must be kept in a separate, ref-counted container. */
  30569. WaitableEvent lockedEvent, releaseEvent;
  30570. private:
  30571. SharedEvents (const SharedEvents&);
  30572. SharedEvents& operator= (const SharedEvents&);
  30573. };
  30574. class MessageManagerLock::BlockingMessage : public CallbackMessage
  30575. {
  30576. public:
  30577. BlockingMessage (MessageManagerLock::SharedEvents* const events_) : events (events_) {}
  30578. ~BlockingMessage() throw() {}
  30579. void messageCallback()
  30580. {
  30581. events->lockedEvent.signal();
  30582. events->releaseEvent.wait();
  30583. }
  30584. juce_UseDebuggingNewOperator
  30585. private:
  30586. ReferenceCountedObjectPtr <MessageManagerLock::SharedEvents> events;
  30587. BlockingMessage (const BlockingMessage&);
  30588. BlockingMessage& operator= (const BlockingMessage&);
  30589. };
  30590. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck) throw()
  30591. : sharedEvents (0),
  30592. locked (false)
  30593. {
  30594. init (threadToCheck, 0);
  30595. }
  30596. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal) throw()
  30597. : sharedEvents (0),
  30598. locked (false)
  30599. {
  30600. init (0, jobToCheckForExitSignal);
  30601. }
  30602. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job) throw()
  30603. {
  30604. if (MessageManager::instance != 0)
  30605. {
  30606. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  30607. {
  30608. locked = true; // either we're on the message thread, or this is a re-entrant call.
  30609. }
  30610. else
  30611. {
  30612. if (threadToCheck == 0 && job == 0)
  30613. {
  30614. MessageManager::instance->lockingLock.enter();
  30615. }
  30616. else
  30617. {
  30618. while (! MessageManager::instance->lockingLock.tryEnter())
  30619. {
  30620. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  30621. || (job != 0 && job->shouldExit()))
  30622. return;
  30623. Thread::sleep (1);
  30624. }
  30625. }
  30626. sharedEvents = new SharedEvents();
  30627. sharedEvents->incReferenceCount();
  30628. (new BlockingMessage (sharedEvents))->post();
  30629. while (! sharedEvents->lockedEvent.wait (50))
  30630. {
  30631. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  30632. || (job != 0 && job->shouldExit()))
  30633. {
  30634. sharedEvents->releaseEvent.signal();
  30635. sharedEvents->decReferenceCount();
  30636. sharedEvents = 0;
  30637. MessageManager::instance->lockingLock.exit();
  30638. return;
  30639. }
  30640. }
  30641. jassert (MessageManager::instance->threadWithLock == 0);
  30642. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  30643. locked = true;
  30644. }
  30645. }
  30646. }
  30647. MessageManagerLock::~MessageManagerLock() throw()
  30648. {
  30649. if (sharedEvents != 0)
  30650. {
  30651. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  30652. sharedEvents->releaseEvent.signal();
  30653. sharedEvents->decReferenceCount();
  30654. if (MessageManager::instance != 0)
  30655. {
  30656. MessageManager::instance->threadWithLock = 0;
  30657. MessageManager::instance->lockingLock.exit();
  30658. }
  30659. }
  30660. }
  30661. END_JUCE_NAMESPACE
  30662. /*** End of inlined file: juce_MessageManager.cpp ***/
  30663. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  30664. BEGIN_JUCE_NAMESPACE
  30665. class MultiTimer::MultiTimerCallback : public Timer
  30666. {
  30667. public:
  30668. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  30669. : timerId (timerId_),
  30670. owner (owner_)
  30671. {
  30672. }
  30673. ~MultiTimerCallback()
  30674. {
  30675. }
  30676. void timerCallback()
  30677. {
  30678. owner.timerCallback (timerId);
  30679. }
  30680. const int timerId;
  30681. private:
  30682. MultiTimer& owner;
  30683. };
  30684. MultiTimer::MultiTimer() throw()
  30685. {
  30686. }
  30687. MultiTimer::MultiTimer (const MultiTimer&) throw()
  30688. {
  30689. }
  30690. MultiTimer::~MultiTimer()
  30691. {
  30692. const ScopedLock sl (timerListLock);
  30693. timers.clear();
  30694. }
  30695. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  30696. {
  30697. const ScopedLock sl (timerListLock);
  30698. for (int i = timers.size(); --i >= 0;)
  30699. {
  30700. MultiTimerCallback* const t = timers.getUnchecked(i);
  30701. if (t->timerId == timerId)
  30702. {
  30703. t->startTimer (intervalInMilliseconds);
  30704. return;
  30705. }
  30706. }
  30707. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  30708. timers.add (newTimer);
  30709. newTimer->startTimer (intervalInMilliseconds);
  30710. }
  30711. void MultiTimer::stopTimer (const int timerId) throw()
  30712. {
  30713. const ScopedLock sl (timerListLock);
  30714. for (int i = timers.size(); --i >= 0;)
  30715. {
  30716. MultiTimerCallback* const t = timers.getUnchecked(i);
  30717. if (t->timerId == timerId)
  30718. t->stopTimer();
  30719. }
  30720. }
  30721. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  30722. {
  30723. const ScopedLock sl (timerListLock);
  30724. for (int i = timers.size(); --i >= 0;)
  30725. {
  30726. const MultiTimerCallback* const t = timers.getUnchecked(i);
  30727. if (t->timerId == timerId)
  30728. return t->isTimerRunning();
  30729. }
  30730. return false;
  30731. }
  30732. int MultiTimer::getTimerInterval (const int timerId) const throw()
  30733. {
  30734. const ScopedLock sl (timerListLock);
  30735. for (int i = timers.size(); --i >= 0;)
  30736. {
  30737. const MultiTimerCallback* const t = timers.getUnchecked(i);
  30738. if (t->timerId == timerId)
  30739. return t->getTimerInterval();
  30740. }
  30741. return 0;
  30742. }
  30743. END_JUCE_NAMESPACE
  30744. /*** End of inlined file: juce_MultiTimer.cpp ***/
  30745. /*** Start of inlined file: juce_Timer.cpp ***/
  30746. BEGIN_JUCE_NAMESPACE
  30747. class InternalTimerThread : private Thread,
  30748. private MessageListener,
  30749. private DeletedAtShutdown,
  30750. private AsyncUpdater
  30751. {
  30752. public:
  30753. InternalTimerThread()
  30754. : Thread ("Juce Timer"),
  30755. firstTimer (0),
  30756. callbackNeeded (0)
  30757. {
  30758. triggerAsyncUpdate();
  30759. }
  30760. ~InternalTimerThread() throw()
  30761. {
  30762. stopThread (4000);
  30763. jassert (instance == this || instance == 0);
  30764. if (instance == this)
  30765. instance = 0;
  30766. }
  30767. void run()
  30768. {
  30769. uint32 lastTime = Time::getMillisecondCounter();
  30770. while (! threadShouldExit())
  30771. {
  30772. const uint32 now = Time::getMillisecondCounter();
  30773. if (now <= lastTime)
  30774. {
  30775. wait (2);
  30776. continue;
  30777. }
  30778. const int elapsed = now - lastTime;
  30779. lastTime = now;
  30780. int timeUntilFirstTimer = 1000;
  30781. {
  30782. const ScopedLock sl (lock);
  30783. decrementAllCounters (elapsed);
  30784. if (firstTimer != 0)
  30785. timeUntilFirstTimer = firstTimer->countdownMs;
  30786. }
  30787. if (timeUntilFirstTimer <= 0)
  30788. {
  30789. /* If we managed to set the atomic boolean to true then send a message, this is needed
  30790. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  30791. but if it fails it means the message-thread changed the value from under us so at least
  30792. some processing is happenening and we can just loop around and try again
  30793. */
  30794. if (callbackNeeded.compareAndSetBool (1, 0))
  30795. {
  30796. postMessage (new Message());
  30797. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  30798. when the app has a modal loop), so this is how long to wait before assuming the
  30799. message has been lost and trying again.
  30800. */
  30801. const uint32 messageDeliveryTimeout = now + 2000;
  30802. while (callbackNeeded.get() != 0)
  30803. {
  30804. wait (4);
  30805. if (threadShouldExit())
  30806. return;
  30807. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  30808. break;
  30809. }
  30810. }
  30811. }
  30812. else
  30813. {
  30814. // don't wait for too long because running this loop also helps keep the
  30815. // Time::getApproximateMillisecondTimer value stay up-to-date
  30816. wait (jlimit (1, 50, timeUntilFirstTimer));
  30817. }
  30818. }
  30819. }
  30820. void callTimers()
  30821. {
  30822. const ScopedLock sl (lock);
  30823. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  30824. {
  30825. Timer* const t = firstTimer;
  30826. t->countdownMs = t->periodMs;
  30827. removeTimer (t);
  30828. addTimer (t);
  30829. const ScopedUnlock ul (lock);
  30830. JUCE_TRY
  30831. {
  30832. t->timerCallback();
  30833. }
  30834. JUCE_CATCH_EXCEPTION
  30835. }
  30836. /* This is needed as a memory barrier to make sure all processing of current timers is done
  30837. before the boolean is set. This set should never fail since if it was false in the first place,
  30838. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  30839. get a message then the value is true and the other thread can only set it to true again and
  30840. we will get another callback to set it to false.
  30841. */
  30842. callbackNeeded.set (0);
  30843. }
  30844. void handleMessage (const Message&)
  30845. {
  30846. callTimers();
  30847. }
  30848. void callTimersSynchronously()
  30849. {
  30850. if (! isThreadRunning())
  30851. {
  30852. // (This is relied on by some plugins in cases where the MM has
  30853. // had to restart and the async callback never started)
  30854. cancelPendingUpdate();
  30855. triggerAsyncUpdate();
  30856. }
  30857. callTimers();
  30858. }
  30859. static void callAnyTimersSynchronously()
  30860. {
  30861. if (InternalTimerThread::instance != 0)
  30862. InternalTimerThread::instance->callTimersSynchronously();
  30863. }
  30864. static inline void add (Timer* const tim) throw()
  30865. {
  30866. if (instance == 0)
  30867. instance = new InternalTimerThread();
  30868. const ScopedLock sl (instance->lock);
  30869. instance->addTimer (tim);
  30870. }
  30871. static inline void remove (Timer* const tim) throw()
  30872. {
  30873. if (instance != 0)
  30874. {
  30875. const ScopedLock sl (instance->lock);
  30876. instance->removeTimer (tim);
  30877. }
  30878. }
  30879. static inline void resetCounter (Timer* const tim,
  30880. const int newCounter) throw()
  30881. {
  30882. if (instance != 0)
  30883. {
  30884. tim->countdownMs = newCounter;
  30885. tim->periodMs = newCounter;
  30886. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  30887. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  30888. {
  30889. const ScopedLock sl (instance->lock);
  30890. instance->removeTimer (tim);
  30891. instance->addTimer (tim);
  30892. }
  30893. }
  30894. }
  30895. private:
  30896. friend class Timer;
  30897. static InternalTimerThread* instance;
  30898. static CriticalSection lock;
  30899. Timer* volatile firstTimer;
  30900. Atomic <int> callbackNeeded;
  30901. void addTimer (Timer* const t) throw()
  30902. {
  30903. #if JUCE_DEBUG
  30904. Timer* tt = firstTimer;
  30905. while (tt != 0)
  30906. {
  30907. // trying to add a timer that's already here - shouldn't get to this point,
  30908. // so if you get this assertion, let me know!
  30909. jassert (tt != t);
  30910. tt = tt->next;
  30911. }
  30912. jassert (t->previous == 0 && t->next == 0);
  30913. #endif
  30914. Timer* i = firstTimer;
  30915. if (i == 0 || i->countdownMs > t->countdownMs)
  30916. {
  30917. t->next = firstTimer;
  30918. firstTimer = t;
  30919. }
  30920. else
  30921. {
  30922. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  30923. i = i->next;
  30924. jassert (i != 0);
  30925. t->next = i->next;
  30926. t->previous = i;
  30927. i->next = t;
  30928. }
  30929. if (t->next != 0)
  30930. t->next->previous = t;
  30931. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  30932. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  30933. notify();
  30934. }
  30935. void removeTimer (Timer* const t) throw()
  30936. {
  30937. #if JUCE_DEBUG
  30938. Timer* tt = firstTimer;
  30939. bool found = false;
  30940. while (tt != 0)
  30941. {
  30942. if (tt == t)
  30943. {
  30944. found = true;
  30945. break;
  30946. }
  30947. tt = tt->next;
  30948. }
  30949. // trying to remove a timer that's not here - shouldn't get to this point,
  30950. // so if you get this assertion, let me know!
  30951. jassert (found);
  30952. #endif
  30953. if (t->previous != 0)
  30954. {
  30955. jassert (firstTimer != t);
  30956. t->previous->next = t->next;
  30957. }
  30958. else
  30959. {
  30960. jassert (firstTimer == t);
  30961. firstTimer = t->next;
  30962. }
  30963. if (t->next != 0)
  30964. t->next->previous = t->previous;
  30965. t->next = 0;
  30966. t->previous = 0;
  30967. }
  30968. void decrementAllCounters (const int numMillisecs) const
  30969. {
  30970. Timer* t = firstTimer;
  30971. while (t != 0)
  30972. {
  30973. t->countdownMs -= numMillisecs;
  30974. t = t->next;
  30975. }
  30976. }
  30977. void handleAsyncUpdate()
  30978. {
  30979. startThread (7);
  30980. }
  30981. InternalTimerThread (const InternalTimerThread&);
  30982. InternalTimerThread& operator= (const InternalTimerThread&);
  30983. };
  30984. InternalTimerThread* InternalTimerThread::instance = 0;
  30985. CriticalSection InternalTimerThread::lock;
  30986. void juce_callAnyTimersSynchronously()
  30987. {
  30988. InternalTimerThread::callAnyTimersSynchronously();
  30989. }
  30990. #if JUCE_DEBUG
  30991. static SortedSet <Timer*> activeTimers;
  30992. #endif
  30993. Timer::Timer() throw()
  30994. : countdownMs (0),
  30995. periodMs (0),
  30996. previous (0),
  30997. next (0)
  30998. {
  30999. #if JUCE_DEBUG
  31000. activeTimers.add (this);
  31001. #endif
  31002. }
  31003. Timer::Timer (const Timer&) throw()
  31004. : countdownMs (0),
  31005. periodMs (0),
  31006. previous (0),
  31007. next (0)
  31008. {
  31009. #if JUCE_DEBUG
  31010. activeTimers.add (this);
  31011. #endif
  31012. }
  31013. Timer::~Timer()
  31014. {
  31015. stopTimer();
  31016. #if JUCE_DEBUG
  31017. activeTimers.removeValue (this);
  31018. #endif
  31019. }
  31020. void Timer::startTimer (const int interval) throw()
  31021. {
  31022. const ScopedLock sl (InternalTimerThread::lock);
  31023. #if JUCE_DEBUG
  31024. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31025. jassert (activeTimers.contains (this));
  31026. #endif
  31027. if (periodMs == 0)
  31028. {
  31029. countdownMs = interval;
  31030. periodMs = jmax (1, interval);
  31031. InternalTimerThread::add (this);
  31032. }
  31033. else
  31034. {
  31035. InternalTimerThread::resetCounter (this, interval);
  31036. }
  31037. }
  31038. void Timer::stopTimer() throw()
  31039. {
  31040. const ScopedLock sl (InternalTimerThread::lock);
  31041. #if JUCE_DEBUG
  31042. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31043. jassert (activeTimers.contains (this));
  31044. #endif
  31045. if (periodMs > 0)
  31046. {
  31047. InternalTimerThread::remove (this);
  31048. periodMs = 0;
  31049. }
  31050. }
  31051. END_JUCE_NAMESPACE
  31052. /*** End of inlined file: juce_Timer.cpp ***/
  31053. #endif
  31054. #if JUCE_BUILD_GUI
  31055. /*** Start of inlined file: juce_Component.cpp ***/
  31056. BEGIN_JUCE_NAMESPACE
  31057. Component* Component::currentlyFocusedComponent = 0;
  31058. static Array <Component*> modalComponentStack, modalComponentReturnValueKeys;
  31059. static Array <int> modalReturnValues;
  31060. enum ComponentMessageNumbers
  31061. {
  31062. customCommandMessage = 0x7fff0001,
  31063. exitModalStateMessage = 0x7fff0002
  31064. };
  31065. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  31066. static uint32 nextComponentUID = 0;
  31067. Component::Component()
  31068. : parentComponent_ (0),
  31069. componentUID (++nextComponentUID),
  31070. numDeepMouseListeners (0),
  31071. lookAndFeel_ (0),
  31072. effect_ (0),
  31073. bufferedImage_ (0),
  31074. mouseListeners_ (0),
  31075. keyListeners_ (0),
  31076. componentFlags_ (0)
  31077. {
  31078. }
  31079. Component::Component (const String& name)
  31080. : componentName_ (name),
  31081. parentComponent_ (0),
  31082. componentUID (++nextComponentUID),
  31083. numDeepMouseListeners (0),
  31084. lookAndFeel_ (0),
  31085. effect_ (0),
  31086. bufferedImage_ (0),
  31087. mouseListeners_ (0),
  31088. keyListeners_ (0),
  31089. componentFlags_ (0)
  31090. {
  31091. }
  31092. Component::~Component()
  31093. {
  31094. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  31095. if (parentComponent_ != 0)
  31096. {
  31097. parentComponent_->removeChildComponent (this);
  31098. }
  31099. else if ((currentlyFocusedComponent == this)
  31100. || isParentOf (currentlyFocusedComponent))
  31101. {
  31102. giveAwayFocus();
  31103. }
  31104. if (flags.hasHeavyweightPeerFlag)
  31105. removeFromDesktop();
  31106. modalComponentStack.removeValue (this);
  31107. for (int i = childComponentList_.size(); --i >= 0;)
  31108. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  31109. delete bufferedImage_;
  31110. delete mouseListeners_;
  31111. delete keyListeners_;
  31112. }
  31113. void Component::setName (const String& name)
  31114. {
  31115. // if component methods are being called from threads other than the message
  31116. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31117. checkMessageManagerIsLocked
  31118. if (componentName_ != name)
  31119. {
  31120. componentName_ = name;
  31121. if (flags.hasHeavyweightPeerFlag)
  31122. {
  31123. ComponentPeer* const peer = getPeer();
  31124. jassert (peer != 0);
  31125. if (peer != 0)
  31126. peer->setTitle (name);
  31127. }
  31128. BailOutChecker checker (this);
  31129. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  31130. }
  31131. }
  31132. void Component::setVisible (bool shouldBeVisible)
  31133. {
  31134. if (flags.visibleFlag != shouldBeVisible)
  31135. {
  31136. // if component methods are being called from threads other than the message
  31137. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31138. checkMessageManagerIsLocked
  31139. SafePointer<Component> safePointer (this);
  31140. flags.visibleFlag = shouldBeVisible;
  31141. internalRepaint (0, 0, getWidth(), getHeight());
  31142. sendFakeMouseMove();
  31143. if (! shouldBeVisible)
  31144. {
  31145. if (currentlyFocusedComponent == this
  31146. || isParentOf (currentlyFocusedComponent))
  31147. {
  31148. if (parentComponent_ != 0)
  31149. parentComponent_->grabKeyboardFocus();
  31150. else
  31151. giveAwayFocus();
  31152. }
  31153. }
  31154. if (safePointer != 0)
  31155. {
  31156. sendVisibilityChangeMessage();
  31157. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  31158. {
  31159. ComponentPeer* const peer = getPeer();
  31160. jassert (peer != 0);
  31161. if (peer != 0)
  31162. {
  31163. peer->setVisible (shouldBeVisible);
  31164. internalHierarchyChanged();
  31165. }
  31166. }
  31167. }
  31168. }
  31169. }
  31170. void Component::visibilityChanged()
  31171. {
  31172. }
  31173. void Component::sendVisibilityChangeMessage()
  31174. {
  31175. BailOutChecker checker (this);
  31176. visibilityChanged();
  31177. if (! checker.shouldBailOut())
  31178. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  31179. }
  31180. bool Component::isShowing() const
  31181. {
  31182. if (flags.visibleFlag)
  31183. {
  31184. if (parentComponent_ != 0)
  31185. {
  31186. return parentComponent_->isShowing();
  31187. }
  31188. else
  31189. {
  31190. const ComponentPeer* const peer = getPeer();
  31191. return peer != 0 && ! peer->isMinimised();
  31192. }
  31193. }
  31194. return false;
  31195. }
  31196. class FadeOutProxyComponent : public Component,
  31197. public Timer
  31198. {
  31199. public:
  31200. FadeOutProxyComponent (Component* comp,
  31201. const int fadeLengthMs,
  31202. const int deltaXToMove,
  31203. const int deltaYToMove,
  31204. const float scaleFactorAtEnd)
  31205. : lastTime (0),
  31206. alpha (1.0f),
  31207. scale (1.0f)
  31208. {
  31209. image = comp->createComponentSnapshot (comp->getLocalBounds());
  31210. setBounds (comp->getBounds());
  31211. comp->getParentComponent()->addAndMakeVisible (this);
  31212. toBehind (comp);
  31213. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  31214. centreX = comp->getX() + comp->getWidth() * 0.5f;
  31215. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  31216. centreY = comp->getY() + comp->getHeight() * 0.5f;
  31217. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  31218. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  31219. setInterceptsMouseClicks (false, false);
  31220. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  31221. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  31222. }
  31223. ~FadeOutProxyComponent()
  31224. {
  31225. delete image;
  31226. }
  31227. void paint (Graphics& g)
  31228. {
  31229. g.setOpacity (alpha);
  31230. g.drawImage (image,
  31231. 0, 0, getWidth(), getHeight(),
  31232. 0, 0, image->getWidth(), image->getHeight());
  31233. }
  31234. void timerCallback()
  31235. {
  31236. const uint32 now = Time::getMillisecondCounter();
  31237. if (lastTime == 0)
  31238. lastTime = now;
  31239. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  31240. lastTime = now;
  31241. alpha += alphaChangePerMs * msPassed;
  31242. if (alpha > 0)
  31243. {
  31244. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  31245. {
  31246. centreX += xChangePerMs * msPassed;
  31247. centreY += yChangePerMs * msPassed;
  31248. scale += scaleChangePerMs * msPassed;
  31249. const int w = roundToInt (image->getWidth() * scale);
  31250. const int h = roundToInt (image->getHeight() * scale);
  31251. setBounds (roundToInt (centreX) - w / 2,
  31252. roundToInt (centreY) - h / 2,
  31253. w, h);
  31254. }
  31255. repaint();
  31256. }
  31257. else
  31258. {
  31259. delete this;
  31260. }
  31261. }
  31262. juce_UseDebuggingNewOperator
  31263. private:
  31264. Image* image;
  31265. uint32 lastTime;
  31266. float alpha, alphaChangePerMs;
  31267. float centreX, xChangePerMs;
  31268. float centreY, yChangePerMs;
  31269. float scale, scaleChangePerMs;
  31270. FadeOutProxyComponent (const FadeOutProxyComponent&);
  31271. FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  31272. };
  31273. void Component::fadeOutComponent (const int millisecondsToFade,
  31274. const int deltaXToMove,
  31275. const int deltaYToMove,
  31276. const float scaleFactorAtEnd)
  31277. {
  31278. //xxx won't work for comps without parents
  31279. if (isShowing() && millisecondsToFade > 0)
  31280. new FadeOutProxyComponent (this, millisecondsToFade,
  31281. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  31282. setVisible (false);
  31283. }
  31284. bool Component::isValidComponent() const
  31285. {
  31286. return (this != 0) && isValidMessageListener();
  31287. }
  31288. void* Component::getWindowHandle() const
  31289. {
  31290. const ComponentPeer* const peer = getPeer();
  31291. if (peer != 0)
  31292. return peer->getNativeHandle();
  31293. return 0;
  31294. }
  31295. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  31296. {
  31297. // if component methods are being called from threads other than the message
  31298. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31299. checkMessageManagerIsLocked
  31300. if (isOpaque())
  31301. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  31302. else
  31303. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  31304. int currentStyleFlags = 0;
  31305. // don't use getPeer(), so that we only get the peer that's specifically
  31306. // for this comp, and not for one of its parents.
  31307. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  31308. if (peer != 0)
  31309. currentStyleFlags = peer->getStyleFlags();
  31310. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  31311. {
  31312. SafePointer<Component> safePointer (this);
  31313. #if JUCE_LINUX
  31314. // it's wise to give the component a non-zero size before
  31315. // putting it on the desktop, as X windows get confused by this, and
  31316. // a (1, 1) minimum size is enforced here.
  31317. setSize (jmax (1, getWidth()),
  31318. jmax (1, getHeight()));
  31319. #endif
  31320. const Point<int> topLeft (relativePositionToGlobal (Point<int> (0, 0)));
  31321. bool wasFullscreen = false;
  31322. bool wasMinimised = false;
  31323. ComponentBoundsConstrainer* currentConstainer = 0;
  31324. Rectangle<int> oldNonFullScreenBounds;
  31325. if (peer != 0)
  31326. {
  31327. wasFullscreen = peer->isFullScreen();
  31328. wasMinimised = peer->isMinimised();
  31329. currentConstainer = peer->getConstrainer();
  31330. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  31331. removeFromDesktop();
  31332. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  31333. }
  31334. if (parentComponent_ != 0)
  31335. parentComponent_->removeChildComponent (this);
  31336. if (safePointer != 0)
  31337. {
  31338. flags.hasHeavyweightPeerFlag = true;
  31339. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  31340. Desktop::getInstance().addDesktopComponent (this);
  31341. bounds_.setPosition (topLeft);
  31342. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  31343. peer->setVisible (isVisible());
  31344. if (wasFullscreen)
  31345. {
  31346. peer->setFullScreen (true);
  31347. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  31348. }
  31349. if (wasMinimised)
  31350. peer->setMinimised (true);
  31351. if (isAlwaysOnTop())
  31352. peer->setAlwaysOnTop (true);
  31353. peer->setConstrainer (currentConstainer);
  31354. repaint();
  31355. }
  31356. internalHierarchyChanged();
  31357. }
  31358. }
  31359. void Component::removeFromDesktop()
  31360. {
  31361. // if component methods are being called from threads other than the message
  31362. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31363. checkMessageManagerIsLocked
  31364. if (flags.hasHeavyweightPeerFlag)
  31365. {
  31366. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  31367. flags.hasHeavyweightPeerFlag = false;
  31368. jassert (peer != 0);
  31369. delete peer;
  31370. Desktop::getInstance().removeDesktopComponent (this);
  31371. }
  31372. }
  31373. bool Component::isOnDesktop() const throw()
  31374. {
  31375. return flags.hasHeavyweightPeerFlag;
  31376. }
  31377. void Component::userTriedToCloseWindow()
  31378. {
  31379. /* This means that the user's trying to get rid of your window with the 'close window' system
  31380. menu option (on windows) or possibly the task manager - you should really handle this
  31381. and delete or hide your component in an appropriate way.
  31382. If you want to ignore the event and don't want to trigger this assertion, just override
  31383. this method and do nothing.
  31384. */
  31385. jassertfalse
  31386. }
  31387. void Component::minimisationStateChanged (bool)
  31388. {
  31389. }
  31390. void Component::setOpaque (const bool shouldBeOpaque)
  31391. {
  31392. if (shouldBeOpaque != flags.opaqueFlag)
  31393. {
  31394. flags.opaqueFlag = shouldBeOpaque;
  31395. if (flags.hasHeavyweightPeerFlag)
  31396. {
  31397. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  31398. if (peer != 0)
  31399. {
  31400. // to make it recreate the heavyweight window
  31401. addToDesktop (peer->getStyleFlags());
  31402. }
  31403. }
  31404. repaint();
  31405. }
  31406. }
  31407. bool Component::isOpaque() const throw()
  31408. {
  31409. return flags.opaqueFlag;
  31410. }
  31411. void Component::setBufferedToImage (const bool shouldBeBuffered)
  31412. {
  31413. if (shouldBeBuffered != flags.bufferToImageFlag)
  31414. {
  31415. deleteAndZero (bufferedImage_);
  31416. flags.bufferToImageFlag = shouldBeBuffered;
  31417. }
  31418. }
  31419. void Component::toFront (const bool setAsForeground)
  31420. {
  31421. // if component methods are being called from threads other than the message
  31422. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31423. checkMessageManagerIsLocked
  31424. if (flags.hasHeavyweightPeerFlag)
  31425. {
  31426. ComponentPeer* const peer = getPeer();
  31427. if (peer != 0)
  31428. {
  31429. peer->toFront (setAsForeground);
  31430. if (setAsForeground && ! hasKeyboardFocus (true))
  31431. grabKeyboardFocus();
  31432. }
  31433. }
  31434. else if (parentComponent_ != 0)
  31435. {
  31436. Array<Component*>& childList = parentComponent_->childComponentList_;
  31437. if (childList.getLast() != this)
  31438. {
  31439. const int index = childList.indexOf (this);
  31440. if (index >= 0)
  31441. {
  31442. int insertIndex = -1;
  31443. if (! flags.alwaysOnTopFlag)
  31444. {
  31445. insertIndex = childList.size() - 1;
  31446. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  31447. --insertIndex;
  31448. }
  31449. if (index != insertIndex)
  31450. {
  31451. childList.move (index, insertIndex);
  31452. sendFakeMouseMove();
  31453. repaintParent();
  31454. }
  31455. }
  31456. }
  31457. if (setAsForeground)
  31458. {
  31459. internalBroughtToFront();
  31460. grabKeyboardFocus();
  31461. }
  31462. }
  31463. }
  31464. void Component::toBehind (Component* const other)
  31465. {
  31466. if (other != 0 && other != this)
  31467. {
  31468. // the two components must belong to the same parent..
  31469. jassert (parentComponent_ == other->parentComponent_);
  31470. if (parentComponent_ != 0)
  31471. {
  31472. Array<Component*>& childList = parentComponent_->childComponentList_;
  31473. const int index = childList.indexOf (this);
  31474. if (index >= 0 && childList [index + 1] != other)
  31475. {
  31476. int otherIndex = childList.indexOf (other);
  31477. if (otherIndex >= 0)
  31478. {
  31479. if (index < otherIndex)
  31480. --otherIndex;
  31481. childList.move (index, otherIndex);
  31482. sendFakeMouseMove();
  31483. repaintParent();
  31484. }
  31485. }
  31486. }
  31487. else if (isOnDesktop())
  31488. {
  31489. jassert (other->isOnDesktop());
  31490. if (other->isOnDesktop())
  31491. {
  31492. ComponentPeer* const us = getPeer();
  31493. ComponentPeer* const them = other->getPeer();
  31494. jassert (us != 0 && them != 0);
  31495. if (us != 0 && them != 0)
  31496. us->toBehind (them);
  31497. }
  31498. }
  31499. }
  31500. }
  31501. void Component::toBack()
  31502. {
  31503. Array<Component*>& childList = parentComponent_->childComponentList_;
  31504. if (isOnDesktop())
  31505. {
  31506. jassertfalse //xxx need to add this to native window
  31507. }
  31508. else if (parentComponent_ != 0 && childList.getFirst() != this)
  31509. {
  31510. const int index = childList.indexOf (this);
  31511. if (index > 0)
  31512. {
  31513. int insertIndex = 0;
  31514. if (flags.alwaysOnTopFlag)
  31515. {
  31516. while (insertIndex < childList.size()
  31517. && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  31518. {
  31519. ++insertIndex;
  31520. }
  31521. }
  31522. if (index != insertIndex)
  31523. {
  31524. childList.move (index, insertIndex);
  31525. sendFakeMouseMove();
  31526. repaintParent();
  31527. }
  31528. }
  31529. }
  31530. }
  31531. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  31532. {
  31533. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  31534. {
  31535. flags.alwaysOnTopFlag = shouldStayOnTop;
  31536. if (isOnDesktop())
  31537. {
  31538. ComponentPeer* const peer = getPeer();
  31539. jassert (peer != 0);
  31540. if (peer != 0)
  31541. {
  31542. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  31543. {
  31544. // some kinds of peer can't change their always-on-top status, so
  31545. // for these, we'll need to create a new window
  31546. const int oldFlags = peer->getStyleFlags();
  31547. removeFromDesktop();
  31548. addToDesktop (oldFlags);
  31549. }
  31550. }
  31551. }
  31552. if (shouldStayOnTop)
  31553. toFront (false);
  31554. internalHierarchyChanged();
  31555. }
  31556. }
  31557. bool Component::isAlwaysOnTop() const throw()
  31558. {
  31559. return flags.alwaysOnTopFlag;
  31560. }
  31561. int Component::proportionOfWidth (const float proportion) const throw()
  31562. {
  31563. return roundToInt (proportion * bounds_.getWidth());
  31564. }
  31565. int Component::proportionOfHeight (const float proportion) const throw()
  31566. {
  31567. return roundToInt (proportion * bounds_.getHeight());
  31568. }
  31569. int Component::getParentWidth() const throw()
  31570. {
  31571. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  31572. : getParentMonitorArea().getWidth();
  31573. }
  31574. int Component::getParentHeight() const throw()
  31575. {
  31576. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  31577. : getParentMonitorArea().getHeight();
  31578. }
  31579. int Component::getScreenX() const
  31580. {
  31581. return getScreenPosition().getX();
  31582. }
  31583. int Component::getScreenY() const
  31584. {
  31585. return getScreenPosition().getY();
  31586. }
  31587. const Point<int> Component::getScreenPosition() const
  31588. {
  31589. return (parentComponent_ != 0) ? parentComponent_->getScreenPosition() + getPosition()
  31590. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenPosition()
  31591. : getPosition());
  31592. }
  31593. const Rectangle<int> Component::getScreenBounds() const
  31594. {
  31595. return bounds_.withPosition (getScreenPosition());
  31596. }
  31597. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  31598. {
  31599. const Component* c = this;
  31600. Point<int> p (relativePosition);
  31601. do
  31602. {
  31603. if (c->flags.hasHeavyweightPeerFlag)
  31604. return c->getPeer()->relativePositionToGlobal (p);
  31605. p += c->getPosition();
  31606. c = c->parentComponent_;
  31607. }
  31608. while (c != 0);
  31609. return p;
  31610. }
  31611. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  31612. {
  31613. if (flags.hasHeavyweightPeerFlag)
  31614. {
  31615. return getPeer()->globalPositionToRelative (screenPosition);
  31616. }
  31617. else
  31618. {
  31619. if (parentComponent_ != 0)
  31620. return parentComponent_->globalPositionToRelative (screenPosition) - getPosition();
  31621. return screenPosition - getPosition();
  31622. }
  31623. }
  31624. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  31625. {
  31626. Point<int> p (positionRelativeToThis);
  31627. if (targetComponent != 0)
  31628. {
  31629. const Component* c = this;
  31630. do
  31631. {
  31632. if (c == targetComponent)
  31633. return p;
  31634. if (c->flags.hasHeavyweightPeerFlag)
  31635. {
  31636. p = c->getPeer()->relativePositionToGlobal (p);
  31637. break;
  31638. }
  31639. p += c->getPosition();
  31640. c = c->parentComponent_;
  31641. }
  31642. while (c != 0);
  31643. p = targetComponent->globalPositionToRelative (p);
  31644. }
  31645. return p;
  31646. }
  31647. void Component::setBounds (int x, int y, int w, int h)
  31648. {
  31649. // if component methods are being called from threads other than the message
  31650. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31651. checkMessageManagerIsLocked
  31652. if (w < 0) w = 0;
  31653. if (h < 0) h = 0;
  31654. const bool wasResized = (getWidth() != w || getHeight() != h);
  31655. const bool wasMoved = (getX() != x || getY() != y);
  31656. #if JUCE_DEBUG
  31657. // It's a very bad idea to try to resize a window during its paint() method!
  31658. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  31659. #endif
  31660. if (wasMoved || wasResized)
  31661. {
  31662. if (flags.visibleFlag)
  31663. {
  31664. // send a fake mouse move to trigger enter/exit messages if needed..
  31665. sendFakeMouseMove();
  31666. if (! flags.hasHeavyweightPeerFlag)
  31667. repaintParent();
  31668. }
  31669. bounds_.setBounds (x, y, w, h);
  31670. if (wasResized)
  31671. repaint();
  31672. else if (! flags.hasHeavyweightPeerFlag)
  31673. repaintParent();
  31674. if (flags.hasHeavyweightPeerFlag)
  31675. {
  31676. ComponentPeer* const peer = getPeer();
  31677. if (peer != 0)
  31678. {
  31679. if (wasMoved && wasResized)
  31680. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  31681. else if (wasMoved)
  31682. peer->setPosition (getX(), getY());
  31683. else if (wasResized)
  31684. peer->setSize (getWidth(), getHeight());
  31685. }
  31686. }
  31687. sendMovedResizedMessages (wasMoved, wasResized);
  31688. }
  31689. }
  31690. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  31691. {
  31692. JUCE_TRY
  31693. {
  31694. if (wasMoved)
  31695. moved();
  31696. if (wasResized)
  31697. {
  31698. resized();
  31699. for (int i = childComponentList_.size(); --i >= 0;)
  31700. {
  31701. childComponentList_.getUnchecked(i)->parentSizeChanged();
  31702. i = jmin (i, childComponentList_.size());
  31703. }
  31704. }
  31705. BailOutChecker checker (this);
  31706. if (parentComponent_ != 0)
  31707. parentComponent_->childBoundsChanged (this);
  31708. if (! checker.shouldBailOut())
  31709. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  31710. *this, wasMoved, wasResized);
  31711. }
  31712. JUCE_CATCH_EXCEPTION
  31713. }
  31714. void Component::setSize (const int w, const int h)
  31715. {
  31716. setBounds (getX(), getY(), w, h);
  31717. }
  31718. void Component::setTopLeftPosition (const int x, const int y)
  31719. {
  31720. setBounds (x, y, getWidth(), getHeight());
  31721. }
  31722. void Component::setTopRightPosition (const int x, const int y)
  31723. {
  31724. setTopLeftPosition (x - getWidth(), y);
  31725. }
  31726. void Component::setBounds (const Rectangle<int>& r)
  31727. {
  31728. setBounds (r.getX(),
  31729. r.getY(),
  31730. r.getWidth(),
  31731. r.getHeight());
  31732. }
  31733. void Component::setBoundsRelative (const float x, const float y,
  31734. const float w, const float h)
  31735. {
  31736. const int pw = getParentWidth();
  31737. const int ph = getParentHeight();
  31738. setBounds (roundToInt (x * pw),
  31739. roundToInt (y * ph),
  31740. roundToInt (w * pw),
  31741. roundToInt (h * ph));
  31742. }
  31743. void Component::setCentrePosition (const int x, const int y)
  31744. {
  31745. setTopLeftPosition (x - getWidth() / 2,
  31746. y - getHeight() / 2);
  31747. }
  31748. void Component::setCentreRelative (const float x, const float y)
  31749. {
  31750. setCentrePosition (roundToInt (getParentWidth() * x),
  31751. roundToInt (getParentHeight() * y));
  31752. }
  31753. void Component::centreWithSize (const int width, const int height)
  31754. {
  31755. setBounds ((getParentWidth() - width) / 2,
  31756. (getParentHeight() - height) / 2,
  31757. width,
  31758. height);
  31759. }
  31760. void Component::setBoundsInset (const BorderSize& borders)
  31761. {
  31762. setBounds (borders.getLeft(),
  31763. borders.getTop(),
  31764. getParentWidth() - (borders.getLeftAndRight()),
  31765. getParentHeight() - (borders.getTopAndBottom()));
  31766. }
  31767. void Component::setBoundsToFit (int x, int y, int width, int height,
  31768. const Justification& justification,
  31769. const bool onlyReduceInSize)
  31770. {
  31771. // it's no good calling this method unless both the component and
  31772. // target rectangle have a finite size.
  31773. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  31774. if (getWidth() > 0 && getHeight() > 0
  31775. && width > 0 && height > 0)
  31776. {
  31777. int newW, newH;
  31778. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  31779. {
  31780. newW = getWidth();
  31781. newH = getHeight();
  31782. }
  31783. else
  31784. {
  31785. const double imageRatio = getHeight() / (double) getWidth();
  31786. const double targetRatio = height / (double) width;
  31787. if (imageRatio <= targetRatio)
  31788. {
  31789. newW = width;
  31790. newH = jmin (height, roundToInt (newW * imageRatio));
  31791. }
  31792. else
  31793. {
  31794. newH = height;
  31795. newW = jmin (width, roundToInt (newH / imageRatio));
  31796. }
  31797. }
  31798. if (newW > 0 && newH > 0)
  31799. {
  31800. int newX, newY;
  31801. justification.applyToRectangle (newX, newY, newW, newH,
  31802. x, y, width, height);
  31803. setBounds (newX, newY, newW, newH);
  31804. }
  31805. }
  31806. }
  31807. bool Component::hitTest (int x, int y)
  31808. {
  31809. if (! flags.ignoresMouseClicksFlag)
  31810. return true;
  31811. if (flags.allowChildMouseClicksFlag)
  31812. {
  31813. for (int i = getNumChildComponents(); --i >= 0;)
  31814. {
  31815. Component* const c = getChildComponent (i);
  31816. if (c->isVisible()
  31817. && c->bounds_.contains (x, y)
  31818. && c->hitTest (x - c->getX(),
  31819. y - c->getY()))
  31820. {
  31821. return true;
  31822. }
  31823. }
  31824. }
  31825. return false;
  31826. }
  31827. void Component::setInterceptsMouseClicks (const bool allowClicks,
  31828. const bool allowClicksOnChildComponents) throw()
  31829. {
  31830. flags.ignoresMouseClicksFlag = ! allowClicks;
  31831. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  31832. }
  31833. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  31834. bool& allowsClicksOnChildComponents) const throw()
  31835. {
  31836. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  31837. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  31838. }
  31839. bool Component::contains (const int x, const int y)
  31840. {
  31841. if (((unsigned int) x) < (unsigned int) getWidth()
  31842. && ((unsigned int) y) < (unsigned int) getHeight()
  31843. && hitTest (x, y))
  31844. {
  31845. if (parentComponent_ != 0)
  31846. {
  31847. return parentComponent_->contains (x + getX(),
  31848. y + getY());
  31849. }
  31850. else if (flags.hasHeavyweightPeerFlag)
  31851. {
  31852. const ComponentPeer* const peer = getPeer();
  31853. if (peer != 0)
  31854. return peer->contains (Point<int> (x, y), true);
  31855. }
  31856. }
  31857. return false;
  31858. }
  31859. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  31860. {
  31861. if (! contains (x, y))
  31862. return false;
  31863. Component* p = this;
  31864. while (p->parentComponent_ != 0)
  31865. {
  31866. x += p->getX();
  31867. y += p->getY();
  31868. p = p->parentComponent_;
  31869. }
  31870. const Component* const c = p->getComponentAt (x, y);
  31871. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  31872. }
  31873. Component* Component::getComponentAt (const Point<int>& position)
  31874. {
  31875. return getComponentAt (position.getX(), position.getY());
  31876. }
  31877. Component* Component::getComponentAt (const int x, const int y)
  31878. {
  31879. if (flags.visibleFlag
  31880. && ((unsigned int) x) < (unsigned int) getWidth()
  31881. && ((unsigned int) y) < (unsigned int) getHeight()
  31882. && hitTest (x, y))
  31883. {
  31884. for (int i = childComponentList_.size(); --i >= 0;)
  31885. {
  31886. Component* const child = childComponentList_.getUnchecked(i);
  31887. Component* const c = child->getComponentAt (x - child->getX(),
  31888. y - child->getY());
  31889. if (c != 0)
  31890. return c;
  31891. }
  31892. return this;
  31893. }
  31894. return 0;
  31895. }
  31896. void Component::addChildComponent (Component* const child, int zOrder)
  31897. {
  31898. // if component methods are being called from threads other than the message
  31899. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31900. checkMessageManagerIsLocked
  31901. if (child != 0 && child->parentComponent_ != this)
  31902. {
  31903. if (child->parentComponent_ != 0)
  31904. child->parentComponent_->removeChildComponent (child);
  31905. else
  31906. child->removeFromDesktop();
  31907. child->parentComponent_ = this;
  31908. if (child->isVisible())
  31909. child->repaintParent();
  31910. if (! child->isAlwaysOnTop())
  31911. {
  31912. if (zOrder < 0 || zOrder > childComponentList_.size())
  31913. zOrder = childComponentList_.size();
  31914. while (zOrder > 0)
  31915. {
  31916. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  31917. break;
  31918. --zOrder;
  31919. }
  31920. }
  31921. childComponentList_.insert (zOrder, child);
  31922. child->internalHierarchyChanged();
  31923. internalChildrenChanged();
  31924. }
  31925. }
  31926. void Component::addAndMakeVisible (Component* const child, int zOrder)
  31927. {
  31928. if (child != 0)
  31929. {
  31930. child->setVisible (true);
  31931. addChildComponent (child, zOrder);
  31932. }
  31933. }
  31934. void Component::removeChildComponent (Component* const child)
  31935. {
  31936. removeChildComponent (childComponentList_.indexOf (child));
  31937. }
  31938. Component* Component::removeChildComponent (const int index)
  31939. {
  31940. // if component methods are being called from threads other than the message
  31941. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31942. checkMessageManagerIsLocked
  31943. Component* const child = childComponentList_ [index];
  31944. if (child != 0)
  31945. {
  31946. sendFakeMouseMove();
  31947. child->repaintParent();
  31948. childComponentList_.remove (index);
  31949. child->parentComponent_ = 0;
  31950. JUCE_TRY
  31951. {
  31952. if ((currentlyFocusedComponent == child)
  31953. || child->isParentOf (currentlyFocusedComponent))
  31954. {
  31955. // get rid first to force the grabKeyboardFocus to change to us.
  31956. giveAwayFocus();
  31957. grabKeyboardFocus();
  31958. }
  31959. }
  31960. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  31961. catch (const std::exception& e)
  31962. {
  31963. currentlyFocusedComponent = 0;
  31964. Desktop::getInstance().triggerFocusCallback();
  31965. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  31966. }
  31967. catch (...)
  31968. {
  31969. currentlyFocusedComponent = 0;
  31970. Desktop::getInstance().triggerFocusCallback();
  31971. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  31972. }
  31973. #endif
  31974. child->internalHierarchyChanged();
  31975. internalChildrenChanged();
  31976. }
  31977. return child;
  31978. }
  31979. void Component::removeAllChildren()
  31980. {
  31981. while (childComponentList_.size() > 0)
  31982. removeChildComponent (childComponentList_.size() - 1);
  31983. }
  31984. void Component::deleteAllChildren()
  31985. {
  31986. while (childComponentList_.size() > 0)
  31987. delete (removeChildComponent (childComponentList_.size() - 1));
  31988. }
  31989. int Component::getNumChildComponents() const throw()
  31990. {
  31991. return childComponentList_.size();
  31992. }
  31993. Component* Component::getChildComponent (const int index) const throw()
  31994. {
  31995. return childComponentList_ [index];
  31996. }
  31997. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  31998. {
  31999. return childComponentList_.indexOf (const_cast <Component*> (child));
  32000. }
  32001. Component* Component::getTopLevelComponent() const throw()
  32002. {
  32003. const Component* comp = this;
  32004. while (comp->parentComponent_ != 0)
  32005. comp = comp->parentComponent_;
  32006. return const_cast <Component*> (comp);
  32007. }
  32008. bool Component::isParentOf (const Component* possibleChild) const throw()
  32009. {
  32010. if (! possibleChild->isValidComponent())
  32011. {
  32012. jassert (possibleChild == 0);
  32013. return false;
  32014. }
  32015. while (possibleChild != 0)
  32016. {
  32017. possibleChild = possibleChild->parentComponent_;
  32018. if (possibleChild == this)
  32019. return true;
  32020. }
  32021. return false;
  32022. }
  32023. void Component::parentHierarchyChanged()
  32024. {
  32025. }
  32026. void Component::childrenChanged()
  32027. {
  32028. }
  32029. void Component::internalChildrenChanged()
  32030. {
  32031. if (componentListeners.isEmpty())
  32032. {
  32033. childrenChanged();
  32034. }
  32035. else
  32036. {
  32037. BailOutChecker checker (this);
  32038. childrenChanged();
  32039. if (! checker.shouldBailOut())
  32040. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  32041. }
  32042. }
  32043. void Component::internalHierarchyChanged()
  32044. {
  32045. BailOutChecker checker (this);
  32046. parentHierarchyChanged();
  32047. if (checker.shouldBailOut())
  32048. return;
  32049. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  32050. if (checker.shouldBailOut())
  32051. return;
  32052. for (int i = childComponentList_.size(); --i >= 0;)
  32053. {
  32054. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  32055. if (checker.shouldBailOut())
  32056. {
  32057. // you really shouldn't delete the parent component during a callback telling you
  32058. // that it's changed..
  32059. jassertfalse;
  32060. return;
  32061. }
  32062. i = jmin (i, childComponentList_.size());
  32063. }
  32064. }
  32065. void* Component::runModalLoopCallback (void* userData)
  32066. {
  32067. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  32068. }
  32069. int Component::runModalLoop()
  32070. {
  32071. if (! MessageManager::getInstance()->isThisTheMessageThread())
  32072. {
  32073. // use a callback so this can be called from non-gui threads
  32074. return (int) (pointer_sized_int)
  32075. MessageManager::getInstance()
  32076. ->callFunctionOnMessageThread (&runModalLoopCallback, this);
  32077. }
  32078. SafePointer<Component> prevFocused (getCurrentlyFocusedComponent());
  32079. if (! isCurrentlyModal())
  32080. enterModalState();
  32081. JUCE_TRY
  32082. {
  32083. while (flags.currentlyModalFlag && flags.visibleFlag)
  32084. {
  32085. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  32086. break;
  32087. // check whether this component was deleted during the last message
  32088. if (! isValidMessageListener())
  32089. break;
  32090. }
  32091. }
  32092. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  32093. catch (const std::exception& e)
  32094. {
  32095. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  32096. return 0;
  32097. }
  32098. catch (...)
  32099. {
  32100. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  32101. return 0;
  32102. }
  32103. #endif
  32104. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  32105. int returnValue = 0;
  32106. if (modalIndex >= 0)
  32107. {
  32108. modalComponentReturnValueKeys.remove (modalIndex);
  32109. returnValue = modalReturnValues.remove (modalIndex);
  32110. }
  32111. modalComponentStack.removeValue (this);
  32112. if (prevFocused != 0)
  32113. prevFocused->grabKeyboardFocus();
  32114. return returnValue;
  32115. }
  32116. void Component::enterModalState (const bool takeKeyboardFocus_)
  32117. {
  32118. // if component methods are being called from threads other than the message
  32119. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32120. checkMessageManagerIsLocked
  32121. // Check for an attempt to make a component modal when it already is!
  32122. // This can cause nasty problems..
  32123. jassert (! flags.currentlyModalFlag);
  32124. if (! isCurrentlyModal())
  32125. {
  32126. modalComponentStack.add (this);
  32127. modalComponentReturnValueKeys.add (this);
  32128. modalReturnValues.add (0);
  32129. flags.currentlyModalFlag = true;
  32130. setVisible (true);
  32131. if (takeKeyboardFocus_)
  32132. grabKeyboardFocus();
  32133. }
  32134. }
  32135. void Component::exitModalState (const int returnValue)
  32136. {
  32137. if (isCurrentlyModal())
  32138. {
  32139. if (MessageManager::getInstance()->isThisTheMessageThread())
  32140. {
  32141. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  32142. if (modalIndex >= 0)
  32143. {
  32144. modalReturnValues.set (modalIndex, returnValue);
  32145. }
  32146. else
  32147. {
  32148. modalComponentReturnValueKeys.add (this);
  32149. modalReturnValues.add (returnValue);
  32150. }
  32151. modalComponentStack.removeValue (this);
  32152. flags.currentlyModalFlag = false;
  32153. bringModalComponentToFront();
  32154. }
  32155. else
  32156. {
  32157. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  32158. }
  32159. }
  32160. }
  32161. bool Component::isCurrentlyModal() const throw()
  32162. {
  32163. return flags.currentlyModalFlag
  32164. && getCurrentlyModalComponent() == this;
  32165. }
  32166. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  32167. {
  32168. Component* const mc = getCurrentlyModalComponent();
  32169. return mc != 0
  32170. && mc != this
  32171. && (! mc->isParentOf (this))
  32172. && ! mc->canModalEventBeSentToComponent (this);
  32173. }
  32174. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  32175. {
  32176. return modalComponentStack.size();
  32177. }
  32178. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  32179. {
  32180. Component* const c = static_cast <Component*> (modalComponentStack [modalComponentStack.size() - index - 1]);
  32181. return c->isValidComponent() ? c : 0;
  32182. }
  32183. void Component::bringModalComponentToFront()
  32184. {
  32185. ComponentPeer* lastOne = 0;
  32186. for (int i = 0; i < getNumCurrentlyModalComponents(); ++i)
  32187. {
  32188. Component* const c = getCurrentlyModalComponent (i);
  32189. if (c == 0)
  32190. break;
  32191. ComponentPeer* peer = c->getPeer();
  32192. if (peer != 0 && peer != lastOne)
  32193. {
  32194. if (lastOne == 0)
  32195. {
  32196. peer->toFront (true);
  32197. peer->grabFocus();
  32198. }
  32199. else
  32200. peer->toBehind (lastOne);
  32201. lastOne = peer;
  32202. }
  32203. }
  32204. }
  32205. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  32206. {
  32207. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  32208. }
  32209. bool Component::isBroughtToFrontOnMouseClick() const throw()
  32210. {
  32211. return flags.bringToFrontOnClickFlag;
  32212. }
  32213. void Component::setMouseCursor (const MouseCursor& cursor)
  32214. {
  32215. if (cursor_ != cursor)
  32216. {
  32217. cursor_ = cursor;
  32218. if (flags.visibleFlag)
  32219. updateMouseCursor();
  32220. }
  32221. }
  32222. const MouseCursor Component::getMouseCursor()
  32223. {
  32224. return cursor_;
  32225. }
  32226. void Component::updateMouseCursor() const
  32227. {
  32228. sendFakeMouseMove();
  32229. }
  32230. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  32231. {
  32232. flags.repaintOnMouseActivityFlag = shouldRepaint;
  32233. }
  32234. void Component::repaintParent()
  32235. {
  32236. if (flags.visibleFlag)
  32237. internalRepaint (0, 0, getWidth(), getHeight());
  32238. }
  32239. void Component::repaint()
  32240. {
  32241. repaint (0, 0, getWidth(), getHeight());
  32242. }
  32243. void Component::repaint (const int x, const int y,
  32244. const int w, const int h)
  32245. {
  32246. deleteAndZero (bufferedImage_);
  32247. if (flags.visibleFlag)
  32248. internalRepaint (x, y, w, h);
  32249. }
  32250. void Component::internalRepaint (int x, int y, int w, int h)
  32251. {
  32252. // if component methods are being called from threads other than the message
  32253. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32254. checkMessageManagerIsLocked
  32255. if (x < 0)
  32256. {
  32257. w += x;
  32258. x = 0;
  32259. }
  32260. if (x + w > getWidth())
  32261. w = getWidth() - x;
  32262. if (w > 0)
  32263. {
  32264. if (y < 0)
  32265. {
  32266. h += y;
  32267. y = 0;
  32268. }
  32269. if (y + h > getHeight())
  32270. h = getHeight() - y;
  32271. if (h > 0)
  32272. {
  32273. if (parentComponent_ != 0)
  32274. {
  32275. x += getX();
  32276. y += getY();
  32277. if (parentComponent_->flags.visibleFlag)
  32278. parentComponent_->internalRepaint (x, y, w, h);
  32279. }
  32280. else if (flags.hasHeavyweightPeerFlag)
  32281. {
  32282. ComponentPeer* const peer = getPeer();
  32283. if (peer != 0)
  32284. peer->repaint (x, y, w, h);
  32285. }
  32286. }
  32287. }
  32288. }
  32289. void Component::renderComponent (Graphics& g)
  32290. {
  32291. const Rectangle<int> clipBounds (g.getClipBounds());
  32292. g.saveState();
  32293. clipObscuredRegions (g, clipBounds, 0, 0);
  32294. if (! g.isClipEmpty())
  32295. {
  32296. if (flags.bufferToImageFlag)
  32297. {
  32298. if (bufferedImage_ == 0)
  32299. {
  32300. bufferedImage_ = Image::createNativeImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32301. getWidth(), getHeight(), ! flags.opaqueFlag);
  32302. Graphics imG (*bufferedImage_);
  32303. paint (imG);
  32304. }
  32305. g.setColour (Colours::black);
  32306. g.drawImageAt (bufferedImage_, 0, 0);
  32307. }
  32308. else
  32309. {
  32310. paint (g);
  32311. }
  32312. }
  32313. g.restoreState();
  32314. for (int i = 0; i < childComponentList_.size(); ++i)
  32315. {
  32316. Component* const child = childComponentList_.getUnchecked (i);
  32317. if (child->isVisible() && clipBounds.intersects (child->getBounds()))
  32318. {
  32319. g.saveState();
  32320. if (g.reduceClipRegion (child->getX(), child->getY(),
  32321. child->getWidth(), child->getHeight()))
  32322. {
  32323. for (int j = i + 1; j < childComponentList_.size(); ++j)
  32324. {
  32325. const Component* const sibling = childComponentList_.getUnchecked (j);
  32326. if (sibling->flags.opaqueFlag && sibling->isVisible())
  32327. g.excludeClipRegion (sibling->getBounds());
  32328. }
  32329. if (! g.isClipEmpty())
  32330. {
  32331. g.setOrigin (child->getX(), child->getY());
  32332. child->paintEntireComponent (g);
  32333. }
  32334. }
  32335. g.restoreState();
  32336. }
  32337. }
  32338. g.saveState();
  32339. paintOverChildren (g);
  32340. g.restoreState();
  32341. }
  32342. void Component::paintEntireComponent (Graphics& g)
  32343. {
  32344. jassert (! g.isClipEmpty());
  32345. #if JUCE_DEBUG
  32346. flags.isInsidePaintCall = true;
  32347. #endif
  32348. if (effect_ != 0)
  32349. {
  32350. ScopedPointer<Image> effectImage (Image::createNativeImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32351. getWidth(), getHeight(),
  32352. ! flags.opaqueFlag));
  32353. {
  32354. Graphics g2 (*effectImage);
  32355. renderComponent (g2);
  32356. }
  32357. effect_->applyEffect (*effectImage, g);
  32358. }
  32359. else
  32360. {
  32361. renderComponent (g);
  32362. }
  32363. #if JUCE_DEBUG
  32364. flags.isInsidePaintCall = false;
  32365. #endif
  32366. }
  32367. Image* Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  32368. const bool clipImageToComponentBounds)
  32369. {
  32370. Rectangle<int> r (areaToGrab);
  32371. if (clipImageToComponentBounds)
  32372. r = r.getIntersection (getLocalBounds());
  32373. ScopedPointer<Image> componentImage (Image::createNativeImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32374. jmax (1, r.getWidth()),
  32375. jmax (1, r.getHeight()),
  32376. true));
  32377. Graphics imageContext (*componentImage);
  32378. imageContext.setOrigin (-r.getX(), -r.getY());
  32379. paintEntireComponent (imageContext);
  32380. return componentImage.release();
  32381. }
  32382. void Component::setComponentEffect (ImageEffectFilter* const effect)
  32383. {
  32384. if (effect_ != effect)
  32385. {
  32386. effect_ = effect;
  32387. repaint();
  32388. }
  32389. }
  32390. LookAndFeel& Component::getLookAndFeel() const throw()
  32391. {
  32392. const Component* c = this;
  32393. do
  32394. {
  32395. if (c->lookAndFeel_ != 0)
  32396. return *(c->lookAndFeel_);
  32397. c = c->parentComponent_;
  32398. }
  32399. while (c != 0);
  32400. return LookAndFeel::getDefaultLookAndFeel();
  32401. }
  32402. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  32403. {
  32404. if (lookAndFeel_ != newLookAndFeel)
  32405. {
  32406. lookAndFeel_ = newLookAndFeel;
  32407. sendLookAndFeelChange();
  32408. }
  32409. }
  32410. void Component::lookAndFeelChanged()
  32411. {
  32412. }
  32413. void Component::sendLookAndFeelChange()
  32414. {
  32415. repaint();
  32416. lookAndFeelChanged();
  32417. // (it's not a great idea to do anything that would delete this component
  32418. // during the lookAndFeelChanged() callback)
  32419. jassert (isValidComponent());
  32420. SafePointer<Component> safePointer (this);
  32421. for (int i = childComponentList_.size(); --i >= 0;)
  32422. {
  32423. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  32424. if (safePointer == 0)
  32425. return;
  32426. i = jmin (i, childComponentList_.size());
  32427. }
  32428. }
  32429. static const var::identifier getColourPropertyId (const int colourId)
  32430. {
  32431. String s;
  32432. s.preallocateStorage (18);
  32433. s << "jcclr_" << String::toHexString (colourId);
  32434. return s;
  32435. }
  32436. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  32437. {
  32438. var* v = properties.getItem (getColourPropertyId (colourId));
  32439. if (v != 0)
  32440. return Colour ((int) *v);
  32441. if (inheritFromParent && parentComponent_ != 0)
  32442. return parentComponent_->findColour (colourId, true);
  32443. return getLookAndFeel().findColour (colourId);
  32444. }
  32445. bool Component::isColourSpecified (const int colourId) const
  32446. {
  32447. return properties.contains (getColourPropertyId (colourId));
  32448. }
  32449. void Component::removeColour (const int colourId)
  32450. {
  32451. if (properties.remove (getColourPropertyId (colourId)))
  32452. colourChanged();
  32453. }
  32454. void Component::setColour (const int colourId, const Colour& colour)
  32455. {
  32456. if (properties.set (getColourPropertyId (colourId), (int) colour.getARGB()))
  32457. colourChanged();
  32458. }
  32459. void Component::copyAllExplicitColoursTo (Component& target) const
  32460. {
  32461. bool changed = false;
  32462. for (int i = properties.size(); --i >= 0;)
  32463. {
  32464. const var::identifier name (properties.getName(i));
  32465. if (name.name.startsWith ("jcclr_"))
  32466. if (target.properties.set (name, properties [name]))
  32467. changed = true;
  32468. }
  32469. if (changed)
  32470. target.colourChanged();
  32471. }
  32472. void Component::colourChanged()
  32473. {
  32474. }
  32475. const Rectangle<int> Component::getLocalBounds() const throw()
  32476. {
  32477. return Rectangle<int> (0, 0, getWidth(), getHeight());
  32478. }
  32479. const Rectangle<int> Component::getUnclippedArea() const
  32480. {
  32481. int x = 0, y = 0, w = getWidth(), h = getHeight();
  32482. Component* p = parentComponent_;
  32483. int px = getX();
  32484. int py = getY();
  32485. while (p != 0)
  32486. {
  32487. if (! Rectangle<int>::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  32488. return Rectangle<int>();
  32489. px += p->getX();
  32490. py += p->getY();
  32491. p = p->parentComponent_;
  32492. }
  32493. return Rectangle<int> (x, y, w, h);
  32494. }
  32495. void Component::clipObscuredRegions (Graphics& g, const Rectangle<int>& clipRect,
  32496. const int deltaX, const int deltaY) const
  32497. {
  32498. for (int i = childComponentList_.size(); --i >= 0;)
  32499. {
  32500. const Component* const c = childComponentList_.getUnchecked(i);
  32501. if (c->isVisible())
  32502. {
  32503. const Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  32504. if (! newClip.isEmpty())
  32505. {
  32506. if (c->isOpaque())
  32507. {
  32508. g.excludeClipRegion (newClip.translated (deltaX, deltaY));
  32509. }
  32510. else
  32511. {
  32512. c->clipObscuredRegions (g, newClip.translated (-c->getX(), -c->getY()),
  32513. c->getX() + deltaX,
  32514. c->getY() + deltaY);
  32515. }
  32516. }
  32517. }
  32518. }
  32519. }
  32520. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  32521. {
  32522. result.clear();
  32523. const Rectangle<int> unclipped (getUnclippedArea());
  32524. if (! unclipped.isEmpty())
  32525. {
  32526. result.add (unclipped);
  32527. if (includeSiblings)
  32528. {
  32529. const Component* const c = getTopLevelComponent();
  32530. c->subtractObscuredRegions (result, c->relativePositionToOtherComponent (this, Point<int>()),
  32531. c->getLocalBounds(), this);
  32532. }
  32533. subtractObscuredRegions (result, Point<int>(), unclipped, 0);
  32534. result.consolidate();
  32535. }
  32536. }
  32537. void Component::subtractObscuredRegions (RectangleList& result,
  32538. const Point<int>& delta,
  32539. const Rectangle<int>& clipRect,
  32540. const Component* const compToAvoid) const
  32541. {
  32542. for (int i = childComponentList_.size(); --i >= 0;)
  32543. {
  32544. const Component* const c = childComponentList_.getUnchecked(i);
  32545. if (c != compToAvoid && c->isVisible())
  32546. {
  32547. if (c->isOpaque())
  32548. {
  32549. Rectangle<int> childBounds (c->bounds_.getIntersection (clipRect));
  32550. childBounds.translate (delta.getX(), delta.getY());
  32551. result.subtract (childBounds);
  32552. }
  32553. else
  32554. {
  32555. Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  32556. newClip.translate (-c->getX(), -c->getY());
  32557. c->subtractObscuredRegions (result, c->getPosition() + delta,
  32558. newClip, compToAvoid);
  32559. }
  32560. }
  32561. }
  32562. }
  32563. void Component::mouseEnter (const MouseEvent&)
  32564. {
  32565. // base class does nothing
  32566. }
  32567. void Component::mouseExit (const MouseEvent&)
  32568. {
  32569. // base class does nothing
  32570. }
  32571. void Component::mouseDown (const MouseEvent&)
  32572. {
  32573. // base class does nothing
  32574. }
  32575. void Component::mouseUp (const MouseEvent&)
  32576. {
  32577. // base class does nothing
  32578. }
  32579. void Component::mouseDrag (const MouseEvent&)
  32580. {
  32581. // base class does nothing
  32582. }
  32583. void Component::mouseMove (const MouseEvent&)
  32584. {
  32585. // base class does nothing
  32586. }
  32587. void Component::mouseDoubleClick (const MouseEvent&)
  32588. {
  32589. // base class does nothing
  32590. }
  32591. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  32592. {
  32593. // the base class just passes this event up to its parent..
  32594. if (parentComponent_ != 0)
  32595. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  32596. wheelIncrementX, wheelIncrementY);
  32597. }
  32598. void Component::resized()
  32599. {
  32600. // base class does nothing
  32601. }
  32602. void Component::moved()
  32603. {
  32604. // base class does nothing
  32605. }
  32606. void Component::childBoundsChanged (Component*)
  32607. {
  32608. // base class does nothing
  32609. }
  32610. void Component::parentSizeChanged()
  32611. {
  32612. // base class does nothing
  32613. }
  32614. void Component::addComponentListener (ComponentListener* const newListener)
  32615. {
  32616. jassert (isValidComponent());
  32617. componentListeners.add (newListener);
  32618. }
  32619. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  32620. {
  32621. jassert (isValidComponent());
  32622. componentListeners.remove (listenerToRemove);
  32623. }
  32624. void Component::inputAttemptWhenModal()
  32625. {
  32626. bringModalComponentToFront();
  32627. getLookAndFeel().playAlertSound();
  32628. }
  32629. bool Component::canModalEventBeSentToComponent (const Component*)
  32630. {
  32631. return false;
  32632. }
  32633. void Component::internalModalInputAttempt()
  32634. {
  32635. Component* const current = getCurrentlyModalComponent();
  32636. if (current != 0)
  32637. current->inputAttemptWhenModal();
  32638. }
  32639. void Component::paint (Graphics&)
  32640. {
  32641. // all painting is done in the subclasses
  32642. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  32643. }
  32644. void Component::paintOverChildren (Graphics&)
  32645. {
  32646. // all painting is done in the subclasses
  32647. }
  32648. void Component::handleMessage (const Message& message)
  32649. {
  32650. if (message.intParameter1 == exitModalStateMessage)
  32651. {
  32652. exitModalState (message.intParameter2);
  32653. }
  32654. else if (message.intParameter1 == customCommandMessage)
  32655. {
  32656. handleCommandMessage (message.intParameter2);
  32657. }
  32658. }
  32659. void Component::postCommandMessage (const int commandId)
  32660. {
  32661. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  32662. }
  32663. void Component::handleCommandMessage (int)
  32664. {
  32665. // used by subclasses
  32666. }
  32667. void Component::addMouseListener (MouseListener* const newListener,
  32668. const bool wantsEventsForAllNestedChildComponents)
  32669. {
  32670. // if component methods are being called from threads other than the message
  32671. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32672. checkMessageManagerIsLocked
  32673. if (mouseListeners_ == 0)
  32674. mouseListeners_ = new Array<MouseListener*>();
  32675. if (! mouseListeners_->contains (newListener))
  32676. {
  32677. if (wantsEventsForAllNestedChildComponents)
  32678. {
  32679. mouseListeners_->insert (0, newListener);
  32680. ++numDeepMouseListeners;
  32681. }
  32682. else
  32683. {
  32684. mouseListeners_->add (newListener);
  32685. }
  32686. }
  32687. }
  32688. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  32689. {
  32690. // if component methods are being called from threads other than the message
  32691. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32692. checkMessageManagerIsLocked
  32693. if (mouseListeners_ != 0)
  32694. {
  32695. const int index = mouseListeners_->indexOf (listenerToRemove);
  32696. if (index >= 0)
  32697. {
  32698. if (index < numDeepMouseListeners)
  32699. --numDeepMouseListeners;
  32700. mouseListeners_->remove (index);
  32701. }
  32702. }
  32703. }
  32704. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32705. {
  32706. if (isCurrentlyBlockedByAnotherModalComponent())
  32707. {
  32708. // if something else is modal, always just show a normal mouse cursor
  32709. source.showMouseCursor (MouseCursor::NormalCursor);
  32710. return;
  32711. }
  32712. if (! flags.mouseInsideFlag)
  32713. {
  32714. flags.mouseInsideFlag = true;
  32715. flags.mouseOverFlag = true;
  32716. flags.draggingFlag = false;
  32717. BailOutChecker checker (this);
  32718. if (flags.repaintOnMouseActivityFlag)
  32719. repaint();
  32720. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32721. this, time, relativePos,
  32722. time, 0, false);
  32723. mouseEnter (me);
  32724. if (checker.shouldBailOut())
  32725. return;
  32726. Desktop::getInstance().resetTimer();
  32727. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  32728. if (checker.shouldBailOut())
  32729. return;
  32730. if (mouseListeners_ != 0)
  32731. {
  32732. for (int i = mouseListeners_->size(); --i >= 0;)
  32733. {
  32734. mouseListeners_->getUnchecked(i)->mouseEnter (me);
  32735. if (checker.shouldBailOut())
  32736. return;
  32737. i = jmin (i, mouseListeners_->size());
  32738. }
  32739. }
  32740. Component* p = parentComponent_;
  32741. while (p != 0)
  32742. {
  32743. if (p->numDeepMouseListeners > 0)
  32744. {
  32745. BailOutChecker checker2 (this, p);
  32746. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32747. {
  32748. p->mouseListeners_->getUnchecked(i)->mouseEnter (me);
  32749. if (checker2.shouldBailOut())
  32750. return;
  32751. i = jmin (i, p->numDeepMouseListeners);
  32752. }
  32753. }
  32754. p = p->parentComponent_;
  32755. }
  32756. }
  32757. }
  32758. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32759. {
  32760. BailOutChecker checker (this);
  32761. if (flags.draggingFlag)
  32762. {
  32763. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  32764. if (checker.shouldBailOut())
  32765. return;
  32766. }
  32767. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  32768. {
  32769. flags.mouseInsideFlag = false;
  32770. flags.mouseOverFlag = false;
  32771. flags.draggingFlag = false;
  32772. if (flags.repaintOnMouseActivityFlag)
  32773. repaint();
  32774. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32775. this, time, relativePos,
  32776. time, 0, false);
  32777. mouseExit (me);
  32778. if (checker.shouldBailOut())
  32779. return;
  32780. Desktop::getInstance().resetTimer();
  32781. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  32782. if (checker.shouldBailOut())
  32783. return;
  32784. if (mouseListeners_ != 0)
  32785. {
  32786. for (int i = mouseListeners_->size(); --i >= 0;)
  32787. {
  32788. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  32789. if (checker.shouldBailOut())
  32790. return;
  32791. i = jmin (i, mouseListeners_->size());
  32792. }
  32793. }
  32794. Component* p = parentComponent_;
  32795. while (p != 0)
  32796. {
  32797. if (p->numDeepMouseListeners > 0)
  32798. {
  32799. BailOutChecker checker2 (this, p);
  32800. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32801. {
  32802. p->mouseListeners_->getUnchecked (i)->mouseExit (me);
  32803. if (checker2.shouldBailOut())
  32804. return;
  32805. i = jmin (i, p->numDeepMouseListeners);
  32806. }
  32807. }
  32808. p = p->parentComponent_;
  32809. }
  32810. }
  32811. }
  32812. class InternalDragRepeater : public Timer
  32813. {
  32814. public:
  32815. InternalDragRepeater()
  32816. {}
  32817. ~InternalDragRepeater()
  32818. {
  32819. clearSingletonInstance();
  32820. }
  32821. juce_DeclareSingleton_SingleThreaded_Minimal (InternalDragRepeater)
  32822. void timerCallback()
  32823. {
  32824. Desktop& desktop = Desktop::getInstance();
  32825. int numMiceDown = 0;
  32826. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  32827. {
  32828. MouseInputSource* const source = desktop.getMouseSource(i);
  32829. if (source->isDragging())
  32830. {
  32831. source->triggerFakeMove();
  32832. ++numMiceDown;
  32833. }
  32834. }
  32835. if (numMiceDown == 0)
  32836. deleteInstance();
  32837. }
  32838. juce_UseDebuggingNewOperator
  32839. private:
  32840. InternalDragRepeater (const InternalDragRepeater&);
  32841. InternalDragRepeater& operator= (const InternalDragRepeater&);
  32842. };
  32843. juce_ImplementSingleton_SingleThreaded (InternalDragRepeater)
  32844. void Component::beginDragAutoRepeat (const int interval)
  32845. {
  32846. if (interval > 0)
  32847. {
  32848. if (InternalDragRepeater::getInstance()->getTimerInterval() != interval)
  32849. InternalDragRepeater::getInstance()->startTimer (interval);
  32850. }
  32851. else
  32852. {
  32853. InternalDragRepeater::deleteInstance();
  32854. }
  32855. }
  32856. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32857. {
  32858. Desktop& desktop = Desktop::getInstance();
  32859. BailOutChecker checker (this);
  32860. if (isCurrentlyBlockedByAnotherModalComponent())
  32861. {
  32862. internalModalInputAttempt();
  32863. if (checker.shouldBailOut())
  32864. return;
  32865. // If processing the input attempt has exited the modal loop, we'll allow the event
  32866. // to be delivered..
  32867. if (isCurrentlyBlockedByAnotherModalComponent())
  32868. {
  32869. // allow blocked mouse-events to go to global listeners..
  32870. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32871. this, time, relativePos, time,
  32872. source.getNumberOfMultipleClicks(), false);
  32873. desktop.resetTimer();
  32874. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  32875. return;
  32876. }
  32877. }
  32878. {
  32879. Component* c = this;
  32880. while (c != 0)
  32881. {
  32882. if (c->isBroughtToFrontOnMouseClick())
  32883. {
  32884. c->toFront (true);
  32885. if (checker.shouldBailOut())
  32886. return;
  32887. }
  32888. c = c->parentComponent_;
  32889. }
  32890. }
  32891. if (! flags.dontFocusOnMouseClickFlag)
  32892. {
  32893. grabFocusInternal (focusChangedByMouseClick);
  32894. if (checker.shouldBailOut())
  32895. return;
  32896. }
  32897. flags.draggingFlag = true;
  32898. flags.mouseOverFlag = true;
  32899. if (flags.repaintOnMouseActivityFlag)
  32900. repaint();
  32901. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32902. this, time, relativePos, time,
  32903. source.getNumberOfMultipleClicks(), false);
  32904. mouseDown (me);
  32905. if (checker.shouldBailOut())
  32906. return;
  32907. desktop.resetTimer();
  32908. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  32909. if (checker.shouldBailOut())
  32910. return;
  32911. if (mouseListeners_ != 0)
  32912. {
  32913. for (int i = mouseListeners_->size(); --i >= 0;)
  32914. {
  32915. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  32916. if (checker.shouldBailOut())
  32917. return;
  32918. i = jmin (i, mouseListeners_->size());
  32919. }
  32920. }
  32921. Component* p = parentComponent_;
  32922. while (p != 0)
  32923. {
  32924. if (p->numDeepMouseListeners > 0)
  32925. {
  32926. BailOutChecker checker2 (this, p);
  32927. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32928. {
  32929. p->mouseListeners_->getUnchecked (i)->mouseDown (me);
  32930. if (checker2.shouldBailOut())
  32931. return;
  32932. i = jmin (i, p->numDeepMouseListeners);
  32933. }
  32934. }
  32935. p = p->parentComponent_;
  32936. }
  32937. }
  32938. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  32939. {
  32940. if (flags.draggingFlag)
  32941. {
  32942. Desktop& desktop = Desktop::getInstance();
  32943. flags.draggingFlag = false;
  32944. BailOutChecker checker (this);
  32945. if (flags.repaintOnMouseActivityFlag)
  32946. repaint();
  32947. const MouseEvent me (source, relativePos,
  32948. oldModifiers, this, time,
  32949. globalPositionToRelative (source.getLastMouseDownPosition()),
  32950. source.getLastMouseDownTime(),
  32951. source.getNumberOfMultipleClicks(),
  32952. source.hasMouseMovedSignificantlySincePressed());
  32953. mouseUp (me);
  32954. if (checker.shouldBailOut())
  32955. return;
  32956. desktop.resetTimer();
  32957. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  32958. if (checker.shouldBailOut())
  32959. return;
  32960. if (mouseListeners_ != 0)
  32961. {
  32962. for (int i = mouseListeners_->size(); --i >= 0;)
  32963. {
  32964. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  32965. if (checker.shouldBailOut())
  32966. return;
  32967. i = jmin (i, mouseListeners_->size());
  32968. }
  32969. }
  32970. {
  32971. Component* p = parentComponent_;
  32972. while (p != 0)
  32973. {
  32974. if (p->numDeepMouseListeners > 0)
  32975. {
  32976. BailOutChecker checker2 (this, p);
  32977. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32978. {
  32979. p->mouseListeners_->getUnchecked (i)->mouseUp (me);
  32980. if (checker2.shouldBailOut())
  32981. return;
  32982. i = jmin (i, p->numDeepMouseListeners);
  32983. }
  32984. }
  32985. p = p->parentComponent_;
  32986. }
  32987. }
  32988. // check for double-click
  32989. if (me.getNumberOfClicks() >= 2)
  32990. {
  32991. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  32992. mouseDoubleClick (me);
  32993. if (checker.shouldBailOut())
  32994. return;
  32995. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  32996. if (checker.shouldBailOut())
  32997. return;
  32998. for (int i = numListeners; --i >= 0;)
  32999. {
  33000. if (checker.shouldBailOut())
  33001. return;
  33002. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  33003. if (ml != 0)
  33004. ml->mouseDoubleClick (me);
  33005. }
  33006. if (checker.shouldBailOut())
  33007. return;
  33008. Component* p = parentComponent_;
  33009. while (p != 0)
  33010. {
  33011. if (p->numDeepMouseListeners > 0)
  33012. {
  33013. BailOutChecker checker2 (this, p);
  33014. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33015. {
  33016. p->mouseListeners_->getUnchecked (i)->mouseDoubleClick (me);
  33017. if (checker2.shouldBailOut())
  33018. return;
  33019. i = jmin (i, p->numDeepMouseListeners);
  33020. }
  33021. }
  33022. p = p->parentComponent_;
  33023. }
  33024. }
  33025. }
  33026. }
  33027. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33028. {
  33029. if (flags.draggingFlag)
  33030. {
  33031. Desktop& desktop = Desktop::getInstance();
  33032. flags.mouseOverFlag = reallyContains (relativePos.getX(), relativePos.getY(), false);
  33033. BailOutChecker checker (this);
  33034. const MouseEvent me (source, relativePos,
  33035. source.getCurrentModifiers(), this, time,
  33036. globalPositionToRelative (source.getLastMouseDownPosition()),
  33037. source.getLastMouseDownTime(),
  33038. source.getNumberOfMultipleClicks(),
  33039. source.hasMouseMovedSignificantlySincePressed());
  33040. mouseDrag (me);
  33041. if (checker.shouldBailOut())
  33042. return;
  33043. desktop.resetTimer();
  33044. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33045. if (checker.shouldBailOut())
  33046. return;
  33047. if (mouseListeners_ != 0)
  33048. {
  33049. for (int i = mouseListeners_->size(); --i >= 0;)
  33050. {
  33051. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  33052. if (checker.shouldBailOut())
  33053. return;
  33054. i = jmin (i, mouseListeners_->size());
  33055. }
  33056. }
  33057. Component* p = parentComponent_;
  33058. while (p != 0)
  33059. {
  33060. if (p->numDeepMouseListeners > 0)
  33061. {
  33062. BailOutChecker checker2 (this, p);
  33063. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33064. {
  33065. p->mouseListeners_->getUnchecked (i)->mouseDrag (me);
  33066. if (checker2.shouldBailOut())
  33067. return;
  33068. i = jmin (i, p->numDeepMouseListeners);
  33069. }
  33070. }
  33071. p = p->parentComponent_;
  33072. }
  33073. }
  33074. }
  33075. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33076. {
  33077. Desktop& desktop = Desktop::getInstance();
  33078. BailOutChecker checker (this);
  33079. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33080. this, time, relativePos,
  33081. time, 0, false);
  33082. if (isCurrentlyBlockedByAnotherModalComponent())
  33083. {
  33084. // allow blocked mouse-events to go to global listeners..
  33085. desktop.sendMouseMove();
  33086. }
  33087. else
  33088. {
  33089. flags.mouseOverFlag = true;
  33090. mouseMove (me);
  33091. if (checker.shouldBailOut())
  33092. return;
  33093. desktop.resetTimer();
  33094. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33095. if (checker.shouldBailOut())
  33096. return;
  33097. if (mouseListeners_ != 0)
  33098. {
  33099. for (int i = mouseListeners_->size(); --i >= 0;)
  33100. {
  33101. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  33102. if (checker.shouldBailOut())
  33103. return;
  33104. i = jmin (i, mouseListeners_->size());
  33105. }
  33106. }
  33107. Component* p = parentComponent_;
  33108. while (p != 0)
  33109. {
  33110. if (p->numDeepMouseListeners > 0)
  33111. {
  33112. BailOutChecker checker2 (this, p);
  33113. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33114. {
  33115. p->mouseListeners_->getUnchecked (i)->mouseMove (me);
  33116. if (checker2.shouldBailOut())
  33117. return;
  33118. i = jmin (i, p->numDeepMouseListeners);
  33119. }
  33120. }
  33121. p = p->parentComponent_;
  33122. }
  33123. }
  33124. }
  33125. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33126. const Time& time, const float amountX, const float amountY)
  33127. {
  33128. Desktop& desktop = Desktop::getInstance();
  33129. BailOutChecker checker (this);
  33130. const float wheelIncrementX = amountX * (1.0f / 256.0f);
  33131. const float wheelIncrementY = amountY * (1.0f / 256.0f);
  33132. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33133. this, time, relativePos, time, 0, false);
  33134. if (isCurrentlyBlockedByAnotherModalComponent())
  33135. {
  33136. // allow blocked mouse-events to go to global listeners..
  33137. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33138. }
  33139. else
  33140. {
  33141. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33142. if (checker.shouldBailOut())
  33143. return;
  33144. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33145. if (checker.shouldBailOut())
  33146. return;
  33147. if (mouseListeners_ != 0)
  33148. {
  33149. for (int i = mouseListeners_->size(); --i >= 0;)
  33150. {
  33151. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33152. if (checker.shouldBailOut())
  33153. return;
  33154. i = jmin (i, mouseListeners_->size());
  33155. }
  33156. }
  33157. Component* p = parentComponent_;
  33158. while (p != 0)
  33159. {
  33160. if (p->numDeepMouseListeners > 0)
  33161. {
  33162. BailOutChecker checker2 (this, p);
  33163. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33164. {
  33165. p->mouseListeners_->getUnchecked (i)->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33166. if (checker2.shouldBailOut())
  33167. return;
  33168. i = jmin (i, p->numDeepMouseListeners);
  33169. }
  33170. }
  33171. p = p->parentComponent_;
  33172. }
  33173. }
  33174. }
  33175. void Component::sendFakeMouseMove() const
  33176. {
  33177. Desktop::getInstance().getMainMouseSource().triggerFakeMove();
  33178. }
  33179. void Component::broughtToFront()
  33180. {
  33181. }
  33182. void Component::internalBroughtToFront()
  33183. {
  33184. if (! isValidComponent())
  33185. return;
  33186. if (flags.hasHeavyweightPeerFlag)
  33187. Desktop::getInstance().componentBroughtToFront (this);
  33188. BailOutChecker checker (this);
  33189. broughtToFront();
  33190. if (checker.shouldBailOut())
  33191. return;
  33192. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  33193. if (checker.shouldBailOut())
  33194. return;
  33195. // When brought to the front and there's a modal component blocking this one,
  33196. // we need to bring the modal one to the front instead..
  33197. Component* const cm = getCurrentlyModalComponent();
  33198. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  33199. bringModalComponentToFront();
  33200. }
  33201. void Component::focusGained (FocusChangeType)
  33202. {
  33203. // base class does nothing
  33204. }
  33205. void Component::internalFocusGain (const FocusChangeType cause)
  33206. {
  33207. SafePointer<Component> safePointer (this);
  33208. focusGained (cause);
  33209. if (safePointer != 0)
  33210. internalChildFocusChange (cause);
  33211. }
  33212. void Component::focusLost (FocusChangeType)
  33213. {
  33214. // base class does nothing
  33215. }
  33216. void Component::internalFocusLoss (const FocusChangeType cause)
  33217. {
  33218. SafePointer<Component> safePointer (this);
  33219. focusLost (focusChangedDirectly);
  33220. if (safePointer != 0)
  33221. internalChildFocusChange (cause);
  33222. }
  33223. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  33224. {
  33225. // base class does nothing
  33226. }
  33227. void Component::internalChildFocusChange (FocusChangeType cause)
  33228. {
  33229. const bool childIsNowFocused = hasKeyboardFocus (true);
  33230. if (flags.childCompFocusedFlag != childIsNowFocused)
  33231. {
  33232. flags.childCompFocusedFlag = childIsNowFocused;
  33233. SafePointer<Component> safePointer (this);
  33234. focusOfChildComponentChanged (cause);
  33235. if (safePointer == 0)
  33236. return;
  33237. }
  33238. if (parentComponent_ != 0)
  33239. parentComponent_->internalChildFocusChange (cause);
  33240. }
  33241. bool Component::isEnabled() const throw()
  33242. {
  33243. return (! flags.isDisabledFlag)
  33244. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  33245. }
  33246. void Component::setEnabled (const bool shouldBeEnabled)
  33247. {
  33248. if (flags.isDisabledFlag == shouldBeEnabled)
  33249. {
  33250. flags.isDisabledFlag = ! shouldBeEnabled;
  33251. // if any parent components are disabled, setting our flag won't make a difference,
  33252. // so no need to send a change message
  33253. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  33254. sendEnablementChangeMessage();
  33255. }
  33256. }
  33257. void Component::sendEnablementChangeMessage()
  33258. {
  33259. SafePointer<Component> safePointer (this);
  33260. enablementChanged();
  33261. if (safePointer == 0)
  33262. return;
  33263. for (int i = getNumChildComponents(); --i >= 0;)
  33264. {
  33265. Component* const c = getChildComponent (i);
  33266. if (c != 0)
  33267. {
  33268. c->sendEnablementChangeMessage();
  33269. if (safePointer == 0)
  33270. return;
  33271. }
  33272. }
  33273. }
  33274. void Component::enablementChanged()
  33275. {
  33276. }
  33277. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  33278. {
  33279. flags.wantsFocusFlag = wantsFocus;
  33280. }
  33281. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  33282. {
  33283. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  33284. }
  33285. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  33286. {
  33287. return ! flags.dontFocusOnMouseClickFlag;
  33288. }
  33289. bool Component::getWantsKeyboardFocus() const throw()
  33290. {
  33291. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  33292. }
  33293. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  33294. {
  33295. flags.isFocusContainerFlag = shouldBeFocusContainer;
  33296. }
  33297. bool Component::isFocusContainer() const throw()
  33298. {
  33299. return flags.isFocusContainerFlag;
  33300. }
  33301. int Component::getExplicitFocusOrder() const
  33302. {
  33303. return properties ["_jexfo"];
  33304. }
  33305. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  33306. {
  33307. properties.set ("_jexfo", newFocusOrderIndex);
  33308. }
  33309. KeyboardFocusTraverser* Component::createFocusTraverser()
  33310. {
  33311. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  33312. return new KeyboardFocusTraverser();
  33313. return parentComponent_->createFocusTraverser();
  33314. }
  33315. void Component::takeKeyboardFocus (const FocusChangeType cause)
  33316. {
  33317. // give the focus to this component
  33318. if (currentlyFocusedComponent != this)
  33319. {
  33320. JUCE_TRY
  33321. {
  33322. // get the focus onto our desktop window
  33323. ComponentPeer* const peer = getPeer();
  33324. if (peer != 0)
  33325. {
  33326. SafePointer<Component> safePointer (this);
  33327. peer->grabFocus();
  33328. if (peer->isFocused() && currentlyFocusedComponent != this)
  33329. {
  33330. Component* const componentLosingFocus = currentlyFocusedComponent;
  33331. currentlyFocusedComponent = this;
  33332. Desktop::getInstance().triggerFocusCallback();
  33333. // call this after setting currentlyFocusedComponent so that the one that's
  33334. // losing it has a chance to see where focus is going
  33335. if (componentLosingFocus->isValidComponent())
  33336. componentLosingFocus->internalFocusLoss (cause);
  33337. if (currentlyFocusedComponent == this)
  33338. {
  33339. focusGained (cause);
  33340. if (safePointer != 0)
  33341. internalChildFocusChange (cause);
  33342. }
  33343. }
  33344. }
  33345. }
  33346. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  33347. catch (const std::exception& e)
  33348. {
  33349. currentlyFocusedComponent = 0;
  33350. Desktop::getInstance().triggerFocusCallback();
  33351. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  33352. }
  33353. catch (...)
  33354. {
  33355. currentlyFocusedComponent = 0;
  33356. Desktop::getInstance().triggerFocusCallback();
  33357. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  33358. }
  33359. #endif
  33360. }
  33361. }
  33362. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  33363. {
  33364. if (isShowing())
  33365. {
  33366. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  33367. {
  33368. takeKeyboardFocus (cause);
  33369. }
  33370. else
  33371. {
  33372. if (isParentOf (currentlyFocusedComponent)
  33373. && currentlyFocusedComponent->isShowing())
  33374. {
  33375. // do nothing if the focused component is actually a child of ours..
  33376. }
  33377. else
  33378. {
  33379. // find the default child component..
  33380. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33381. if (traverser != 0)
  33382. {
  33383. Component* const defaultComp = traverser->getDefaultComponent (this);
  33384. traverser = 0;
  33385. if (defaultComp != 0)
  33386. {
  33387. defaultComp->grabFocusInternal (cause, false);
  33388. return;
  33389. }
  33390. }
  33391. if (canTryParent && parentComponent_ != 0)
  33392. {
  33393. // if no children want it and we're allowed to try our parent comp,
  33394. // then pass up to parent, which will try our siblings.
  33395. parentComponent_->grabFocusInternal (cause, true);
  33396. }
  33397. }
  33398. }
  33399. }
  33400. }
  33401. void Component::grabKeyboardFocus()
  33402. {
  33403. // if component methods are being called from threads other than the message
  33404. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33405. checkMessageManagerIsLocked
  33406. grabFocusInternal (focusChangedDirectly);
  33407. }
  33408. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  33409. {
  33410. // if component methods are being called from threads other than the message
  33411. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33412. checkMessageManagerIsLocked
  33413. if (parentComponent_ != 0)
  33414. {
  33415. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33416. if (traverser != 0)
  33417. {
  33418. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  33419. : traverser->getPreviousComponent (this);
  33420. traverser = 0;
  33421. if (nextComp != 0)
  33422. {
  33423. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33424. {
  33425. SafePointer<Component> nextCompPointer (nextComp);
  33426. internalModalInputAttempt();
  33427. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33428. return;
  33429. }
  33430. nextComp->grabFocusInternal (focusChangedByTabKey);
  33431. return;
  33432. }
  33433. }
  33434. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  33435. }
  33436. }
  33437. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  33438. {
  33439. return (currentlyFocusedComponent == this)
  33440. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  33441. }
  33442. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  33443. {
  33444. return currentlyFocusedComponent;
  33445. }
  33446. void Component::giveAwayFocus()
  33447. {
  33448. // use a copy so we can clear the value before the call
  33449. Component* const componentLosingFocus = currentlyFocusedComponent;
  33450. currentlyFocusedComponent = 0;
  33451. Desktop::getInstance().triggerFocusCallback();
  33452. if (componentLosingFocus->isValidComponent())
  33453. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  33454. }
  33455. bool Component::isMouseOver() const throw()
  33456. {
  33457. return flags.mouseOverFlag;
  33458. }
  33459. bool Component::isMouseButtonDown() const throw()
  33460. {
  33461. return flags.draggingFlag;
  33462. }
  33463. bool Component::isMouseOverOrDragging() const throw()
  33464. {
  33465. return flags.mouseOverFlag || flags.draggingFlag;
  33466. }
  33467. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  33468. {
  33469. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  33470. }
  33471. const Point<int> Component::getMouseXYRelative() const
  33472. {
  33473. return globalPositionToRelative (Desktop::getMousePosition());
  33474. }
  33475. const Rectangle<int> Component::getParentMonitorArea() const
  33476. {
  33477. return Desktop::getInstance()
  33478. .getMonitorAreaContaining (relativePositionToGlobal (Point<int> (getWidth() / 2,
  33479. getHeight() / 2)));
  33480. }
  33481. void Component::addKeyListener (KeyListener* const newListener)
  33482. {
  33483. if (keyListeners_ == 0)
  33484. keyListeners_ = new VoidArray();
  33485. keyListeners_->addIfNotAlreadyThere (newListener);
  33486. }
  33487. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  33488. {
  33489. if (keyListeners_ != 0)
  33490. keyListeners_->removeValue (listenerToRemove);
  33491. }
  33492. bool Component::keyPressed (const KeyPress&)
  33493. {
  33494. return false;
  33495. }
  33496. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  33497. {
  33498. return false;
  33499. }
  33500. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  33501. {
  33502. if (parentComponent_ != 0)
  33503. parentComponent_->modifierKeysChanged (modifiers);
  33504. }
  33505. void Component::internalModifierKeysChanged()
  33506. {
  33507. sendFakeMouseMove();
  33508. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  33509. }
  33510. ComponentPeer* Component::getPeer() const
  33511. {
  33512. if (flags.hasHeavyweightPeerFlag)
  33513. return ComponentPeer::getPeerFor (this);
  33514. else if (parentComponent_ != 0)
  33515. return parentComponent_->getPeer();
  33516. else
  33517. return 0;
  33518. }
  33519. Component::BailOutChecker::BailOutChecker (Component* const component1, Component* const component2_)
  33520. : safePointer1 (component1), safePointer2 (component2_), component2 (component2_)
  33521. {
  33522. jassert (component1 != 0);
  33523. }
  33524. bool Component::BailOutChecker::shouldBailOut() const throw()
  33525. {
  33526. return safePointer1 == 0 || safePointer2.getComponent() != component2;
  33527. }
  33528. END_JUCE_NAMESPACE
  33529. /*** End of inlined file: juce_Component.cpp ***/
  33530. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  33531. BEGIN_JUCE_NAMESPACE
  33532. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  33533. void ComponentListener::componentBroughtToFront (Component&) {}
  33534. void ComponentListener::componentVisibilityChanged (Component&) {}
  33535. void ComponentListener::componentChildrenChanged (Component&) {}
  33536. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  33537. void ComponentListener::componentNameChanged (Component&) {}
  33538. void ComponentListener::componentBeingDeleted (Component&) {}
  33539. END_JUCE_NAMESPACE
  33540. /*** End of inlined file: juce_ComponentListener.cpp ***/
  33541. /*** Start of inlined file: juce_Desktop.cpp ***/
  33542. BEGIN_JUCE_NAMESPACE
  33543. Desktop::Desktop()
  33544. : mouseClickCounter (0),
  33545. kioskModeComponent (0)
  33546. {
  33547. createMouseInputSources();
  33548. refreshMonitorSizes();
  33549. }
  33550. Desktop::~Desktop()
  33551. {
  33552. jassert (instance == this);
  33553. instance = 0;
  33554. // doh! If you don't delete all your windows before exiting, you're going to
  33555. // be leaking memory!
  33556. jassert (desktopComponents.size() == 0);
  33557. }
  33558. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  33559. {
  33560. if (instance == 0)
  33561. instance = new Desktop();
  33562. return *instance;
  33563. }
  33564. Desktop* Desktop::instance = 0;
  33565. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  33566. const bool clipToWorkArea);
  33567. void Desktop::refreshMonitorSizes()
  33568. {
  33569. const Array <Rectangle<int> > oldClipped (monitorCoordsClipped);
  33570. const Array <Rectangle<int> > oldUnclipped (monitorCoordsUnclipped);
  33571. monitorCoordsClipped.clear();
  33572. monitorCoordsUnclipped.clear();
  33573. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  33574. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  33575. jassert (monitorCoordsClipped.size() > 0
  33576. && monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  33577. if (oldClipped != monitorCoordsClipped
  33578. || oldUnclipped != monitorCoordsUnclipped)
  33579. {
  33580. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  33581. {
  33582. ComponentPeer* const p = ComponentPeer::getPeer (i);
  33583. if (p != 0)
  33584. p->handleScreenSizeChange();
  33585. }
  33586. }
  33587. }
  33588. int Desktop::getNumDisplayMonitors() const throw()
  33589. {
  33590. return monitorCoordsClipped.size();
  33591. }
  33592. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  33593. {
  33594. return clippedToWorkArea ? monitorCoordsClipped [index]
  33595. : monitorCoordsUnclipped [index];
  33596. }
  33597. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  33598. {
  33599. RectangleList rl;
  33600. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  33601. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33602. return rl;
  33603. }
  33604. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  33605. {
  33606. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  33607. }
  33608. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  33609. {
  33610. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  33611. double bestDistance = 1.0e10;
  33612. for (int i = getNumDisplayMonitors(); --i >= 0;)
  33613. {
  33614. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33615. if (rect.contains (position))
  33616. return rect;
  33617. const double distance = rect.getCentre().getDistanceFrom (position);
  33618. if (distance < bestDistance)
  33619. {
  33620. bestDistance = distance;
  33621. best = rect;
  33622. }
  33623. }
  33624. return best;
  33625. }
  33626. int Desktop::getNumComponents() const throw()
  33627. {
  33628. return desktopComponents.size();
  33629. }
  33630. Component* Desktop::getComponent (const int index) const throw()
  33631. {
  33632. return desktopComponents [index];
  33633. }
  33634. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  33635. {
  33636. for (int i = desktopComponents.size(); --i >= 0;)
  33637. {
  33638. Component* const c = desktopComponents.getUnchecked(i);
  33639. const Point<int> relative (c->globalPositionToRelative (screenPosition));
  33640. if (c->contains (relative.getX(), relative.getY()))
  33641. return c->getComponentAt (relative.getX(), relative.getY());
  33642. }
  33643. return 0;
  33644. }
  33645. void Desktop::addDesktopComponent (Component* const c)
  33646. {
  33647. jassert (c != 0);
  33648. jassert (! desktopComponents.contains (c));
  33649. desktopComponents.addIfNotAlreadyThere (c);
  33650. }
  33651. void Desktop::removeDesktopComponent (Component* const c)
  33652. {
  33653. desktopComponents.removeValue (c);
  33654. }
  33655. void Desktop::componentBroughtToFront (Component* const c)
  33656. {
  33657. const int index = desktopComponents.indexOf (c);
  33658. jassert (index >= 0);
  33659. if (index >= 0)
  33660. {
  33661. int newIndex = -1;
  33662. if (! c->isAlwaysOnTop())
  33663. {
  33664. newIndex = desktopComponents.size();
  33665. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  33666. --newIndex;
  33667. --newIndex;
  33668. }
  33669. desktopComponents.move (index, newIndex);
  33670. }
  33671. }
  33672. const Point<int> Desktop::getLastMouseDownPosition() throw()
  33673. {
  33674. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  33675. }
  33676. int Desktop::getMouseButtonClickCounter() throw()
  33677. {
  33678. return getInstance().mouseClickCounter;
  33679. }
  33680. void Desktop::incrementMouseClickCounter() throw()
  33681. {
  33682. ++mouseClickCounter;
  33683. }
  33684. int Desktop::getNumDraggingMouseSources() const throw()
  33685. {
  33686. int num = 0;
  33687. for (int i = mouseSources.size(); --i >= 0;)
  33688. if (mouseSources.getUnchecked(i)->isDragging())
  33689. ++num;
  33690. return num;
  33691. }
  33692. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  33693. {
  33694. int num = 0;
  33695. for (int i = mouseSources.size(); --i >= 0;)
  33696. {
  33697. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  33698. if (mi->isDragging())
  33699. {
  33700. if (index == num)
  33701. return mi;
  33702. ++num;
  33703. }
  33704. }
  33705. return 0;
  33706. }
  33707. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  33708. {
  33709. focusListeners.add (listener);
  33710. }
  33711. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  33712. {
  33713. focusListeners.remove (listener);
  33714. }
  33715. void Desktop::triggerFocusCallback()
  33716. {
  33717. triggerAsyncUpdate();
  33718. }
  33719. void Desktop::handleAsyncUpdate()
  33720. {
  33721. Component* currentFocus = Component::getCurrentlyFocusedComponent();
  33722. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  33723. }
  33724. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  33725. {
  33726. mouseListeners.add (listener);
  33727. resetTimer();
  33728. }
  33729. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  33730. {
  33731. mouseListeners.remove (listener);
  33732. resetTimer();
  33733. }
  33734. void Desktop::timerCallback()
  33735. {
  33736. if (lastFakeMouseMove != getMousePosition())
  33737. sendMouseMove();
  33738. }
  33739. void Desktop::sendMouseMove()
  33740. {
  33741. if (! mouseListeners.isEmpty())
  33742. {
  33743. startTimer (20);
  33744. lastFakeMouseMove = getMousePosition();
  33745. Component* const target = findComponentAt (lastFakeMouseMove);
  33746. if (target != 0)
  33747. {
  33748. Component::BailOutChecker checker (target);
  33749. const Point<int> pos (target->globalPositionToRelative (lastFakeMouseMove));
  33750. const Time now (Time::getCurrentTime());
  33751. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  33752. target, now, pos, now, 0, false);
  33753. if (me.mods.isAnyMouseButtonDown())
  33754. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33755. else
  33756. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33757. }
  33758. }
  33759. }
  33760. void Desktop::resetTimer()
  33761. {
  33762. if (mouseListeners.size() == 0)
  33763. stopTimer();
  33764. else
  33765. startTimer (100);
  33766. lastFakeMouseMove = getMousePosition();
  33767. }
  33768. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  33769. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  33770. {
  33771. if (kioskModeComponent != componentToUse)
  33772. {
  33773. // agh! Don't delete a component without first stopping it being the kiosk comp
  33774. jassert (kioskModeComponent == 0 || kioskModeComponent->isValidComponent());
  33775. // agh! Don't remove a component from the desktop if it's the kiosk comp!
  33776. jassert (kioskModeComponent == 0 || kioskModeComponent->isOnDesktop());
  33777. if (kioskModeComponent->isValidComponent())
  33778. {
  33779. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  33780. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  33781. }
  33782. kioskModeComponent = componentToUse;
  33783. if (kioskModeComponent != 0)
  33784. {
  33785. jassert (kioskModeComponent->isValidComponent());
  33786. // Only components that are already on the desktop can be put into kiosk mode!
  33787. jassert (kioskModeComponent->isOnDesktop());
  33788. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  33789. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  33790. }
  33791. }
  33792. }
  33793. END_JUCE_NAMESPACE
  33794. /*** End of inlined file: juce_Desktop.cpp ***/
  33795. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  33796. BEGIN_JUCE_NAMESPACE
  33797. ArrowButton::ArrowButton (const String& name,
  33798. float arrowDirectionInRadians,
  33799. const Colour& arrowColour)
  33800. : Button (name),
  33801. colour (arrowColour)
  33802. {
  33803. path.lineTo (0.0f, 1.0f);
  33804. path.lineTo (1.0f, 0.5f);
  33805. path.closeSubPath();
  33806. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  33807. 0.5f, 0.5f));
  33808. setComponentEffect (&shadow);
  33809. buttonStateChanged();
  33810. }
  33811. ArrowButton::~ArrowButton()
  33812. {
  33813. }
  33814. void ArrowButton::paintButton (Graphics& g,
  33815. bool /*isMouseOverButton*/,
  33816. bool /*isButtonDown*/)
  33817. {
  33818. g.setColour (colour);
  33819. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  33820. (float) offset,
  33821. (float) (getWidth() - 3),
  33822. (float) (getHeight() - 3),
  33823. false));
  33824. }
  33825. void ArrowButton::buttonStateChanged()
  33826. {
  33827. offset = (isDown()) ? 1 : 0;
  33828. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  33829. 0.3f, -1, 0);
  33830. }
  33831. END_JUCE_NAMESPACE
  33832. /*** End of inlined file: juce_ArrowButton.cpp ***/
  33833. /*** Start of inlined file: juce_Button.cpp ***/
  33834. BEGIN_JUCE_NAMESPACE
  33835. class Button::RepeatTimer : public Timer
  33836. {
  33837. public:
  33838. RepeatTimer (Button& owner_) : owner (owner_) {}
  33839. void timerCallback() { owner.repeatTimerCallback(); }
  33840. juce_UseDebuggingNewOperator
  33841. private:
  33842. Button& owner;
  33843. RepeatTimer (const RepeatTimer&);
  33844. RepeatTimer& operator= (const RepeatTimer&);
  33845. };
  33846. Button::Button (const String& name)
  33847. : Component (name),
  33848. text (name),
  33849. buttonPressTime (0),
  33850. lastTimeCallbackTime (0),
  33851. commandManagerToUse (0),
  33852. autoRepeatDelay (-1),
  33853. autoRepeatSpeed (0),
  33854. autoRepeatMinimumDelay (-1),
  33855. radioGroupId (0),
  33856. commandID (0),
  33857. connectedEdgeFlags (0),
  33858. buttonState (buttonNormal),
  33859. lastToggleState (false),
  33860. clickTogglesState (false),
  33861. needsToRelease (false),
  33862. needsRepainting (false),
  33863. isKeyDown (false),
  33864. triggerOnMouseDown (false),
  33865. generateTooltip (false)
  33866. {
  33867. setWantsKeyboardFocus (true);
  33868. isOn.addListener (this);
  33869. }
  33870. Button::~Button()
  33871. {
  33872. isOn.removeListener (this);
  33873. if (commandManagerToUse != 0)
  33874. commandManagerToUse->removeListener (this);
  33875. repeatTimer = 0;
  33876. clearShortcuts();
  33877. }
  33878. void Button::setButtonText (const String& newText)
  33879. {
  33880. if (text != newText)
  33881. {
  33882. text = newText;
  33883. repaint();
  33884. }
  33885. }
  33886. void Button::setTooltip (const String& newTooltip)
  33887. {
  33888. SettableTooltipClient::setTooltip (newTooltip);
  33889. generateTooltip = false;
  33890. }
  33891. const String Button::getTooltip()
  33892. {
  33893. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  33894. {
  33895. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  33896. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  33897. for (int i = 0; i < keyPresses.size(); ++i)
  33898. {
  33899. const String key (keyPresses.getReference(i).getTextDescription());
  33900. tt << " [";
  33901. if (key.length() == 1)
  33902. tt << TRANS("shortcut") << ": '" << key << "']";
  33903. else
  33904. tt << key << ']';
  33905. }
  33906. return tt;
  33907. }
  33908. return SettableTooltipClient::getTooltip();
  33909. }
  33910. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  33911. {
  33912. if (connectedEdgeFlags != connectedEdgeFlags_)
  33913. {
  33914. connectedEdgeFlags = connectedEdgeFlags_;
  33915. repaint();
  33916. }
  33917. }
  33918. void Button::setToggleState (const bool shouldBeOn,
  33919. const bool sendChangeNotification)
  33920. {
  33921. if (shouldBeOn != lastToggleState)
  33922. {
  33923. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  33924. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  33925. lastToggleState = shouldBeOn;
  33926. repaint();
  33927. if (sendChangeNotification)
  33928. {
  33929. Component::SafePointer<Component> deletionWatcher (this);
  33930. sendClickMessage (ModifierKeys());
  33931. if (deletionWatcher == 0)
  33932. return;
  33933. }
  33934. if (lastToggleState)
  33935. turnOffOtherButtonsInGroup (sendChangeNotification);
  33936. }
  33937. }
  33938. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  33939. {
  33940. clickTogglesState = shouldToggle;
  33941. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  33942. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  33943. // it is that this button represents, and the button will update its state to reflect this
  33944. // in the applicationCommandListChanged() method.
  33945. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  33946. }
  33947. bool Button::getClickingTogglesState() const throw()
  33948. {
  33949. return clickTogglesState;
  33950. }
  33951. void Button::valueChanged (Value& value)
  33952. {
  33953. if (value.refersToSameSourceAs (isOn))
  33954. setToggleState (isOn.getValue(), true);
  33955. }
  33956. void Button::setRadioGroupId (const int newGroupId)
  33957. {
  33958. if (radioGroupId != newGroupId)
  33959. {
  33960. radioGroupId = newGroupId;
  33961. if (lastToggleState)
  33962. turnOffOtherButtonsInGroup (true);
  33963. }
  33964. }
  33965. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  33966. {
  33967. Component* const p = getParentComponent();
  33968. if (p != 0 && radioGroupId != 0)
  33969. {
  33970. Component::SafePointer<Component> deletionWatcher (this);
  33971. for (int i = p->getNumChildComponents(); --i >= 0;)
  33972. {
  33973. Component* const c = p->getChildComponent (i);
  33974. if (c != this)
  33975. {
  33976. Button* const b = dynamic_cast <Button*> (c);
  33977. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  33978. {
  33979. b->setToggleState (false, sendChangeNotification);
  33980. if (deletionWatcher == 0)
  33981. return;
  33982. }
  33983. }
  33984. }
  33985. }
  33986. }
  33987. void Button::enablementChanged()
  33988. {
  33989. updateState (0);
  33990. repaint();
  33991. }
  33992. Button::ButtonState Button::updateState (const MouseEvent* const e)
  33993. {
  33994. ButtonState state = buttonNormal;
  33995. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  33996. {
  33997. Point<int> mousePos;
  33998. if (e == 0)
  33999. mousePos = getMouseXYRelative();
  34000. else
  34001. mousePos = e->getEventRelativeTo (this).getPosition();
  34002. const bool over = reallyContains (mousePos.getX(), mousePos.getY(), true);
  34003. const bool down = isMouseButtonDown();
  34004. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  34005. state = buttonDown;
  34006. else if (over)
  34007. state = buttonOver;
  34008. }
  34009. setState (state);
  34010. return state;
  34011. }
  34012. void Button::setState (const ButtonState newState)
  34013. {
  34014. if (buttonState != newState)
  34015. {
  34016. buttonState = newState;
  34017. repaint();
  34018. if (buttonState == buttonDown)
  34019. {
  34020. buttonPressTime = Time::getApproximateMillisecondCounter();
  34021. lastTimeCallbackTime = buttonPressTime;
  34022. }
  34023. sendStateMessage();
  34024. }
  34025. }
  34026. bool Button::isDown() const throw()
  34027. {
  34028. return buttonState == buttonDown;
  34029. }
  34030. bool Button::isOver() const throw()
  34031. {
  34032. return buttonState != buttonNormal;
  34033. }
  34034. void Button::buttonStateChanged()
  34035. {
  34036. }
  34037. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  34038. {
  34039. const uint32 now = Time::getApproximateMillisecondCounter();
  34040. return now > buttonPressTime ? now - buttonPressTime : 0;
  34041. }
  34042. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  34043. {
  34044. triggerOnMouseDown = isTriggeredOnMouseDown;
  34045. }
  34046. void Button::clicked()
  34047. {
  34048. }
  34049. void Button::clicked (const ModifierKeys& /*modifiers*/)
  34050. {
  34051. clicked();
  34052. }
  34053. static const int clickMessageId = 0x2f3f4f99;
  34054. void Button::triggerClick()
  34055. {
  34056. postCommandMessage (clickMessageId);
  34057. }
  34058. void Button::internalClickCallback (const ModifierKeys& modifiers)
  34059. {
  34060. if (clickTogglesState)
  34061. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  34062. sendClickMessage (modifiers);
  34063. }
  34064. void Button::flashButtonState()
  34065. {
  34066. if (isEnabled())
  34067. {
  34068. needsToRelease = true;
  34069. setState (buttonDown);
  34070. getRepeatTimer().startTimer (100);
  34071. }
  34072. }
  34073. void Button::handleCommandMessage (int commandId)
  34074. {
  34075. if (commandId == clickMessageId)
  34076. {
  34077. if (isEnabled())
  34078. {
  34079. flashButtonState();
  34080. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34081. }
  34082. }
  34083. else
  34084. {
  34085. Component::handleCommandMessage (commandId);
  34086. }
  34087. }
  34088. void Button::addButtonListener (ButtonListener* const newListener)
  34089. {
  34090. buttonListeners.add (newListener);
  34091. }
  34092. void Button::removeButtonListener (ButtonListener* const listener)
  34093. {
  34094. buttonListeners.remove (listener);
  34095. }
  34096. void Button::sendClickMessage (const ModifierKeys& modifiers)
  34097. {
  34098. Component::BailOutChecker checker (this);
  34099. if (commandManagerToUse != 0 && commandID != 0)
  34100. {
  34101. ApplicationCommandTarget::InvocationInfo info (commandID);
  34102. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  34103. info.originatingComponent = this;
  34104. commandManagerToUse->invoke (info, true);
  34105. }
  34106. clicked (modifiers);
  34107. if (! checker.shouldBailOut())
  34108. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this);
  34109. }
  34110. void Button::sendStateMessage()
  34111. {
  34112. Component::BailOutChecker checker (this);
  34113. buttonStateChanged();
  34114. if (! checker.shouldBailOut())
  34115. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  34116. }
  34117. void Button::paint (Graphics& g)
  34118. {
  34119. if (needsToRelease && isEnabled())
  34120. {
  34121. needsToRelease = false;
  34122. needsRepainting = true;
  34123. }
  34124. paintButton (g, isOver(), isDown());
  34125. }
  34126. void Button::mouseEnter (const MouseEvent& e)
  34127. {
  34128. updateState (&e);
  34129. }
  34130. void Button::mouseExit (const MouseEvent& e)
  34131. {
  34132. updateState (&e);
  34133. }
  34134. void Button::mouseDown (const MouseEvent& e)
  34135. {
  34136. updateState (&e);
  34137. if (isDown())
  34138. {
  34139. if (autoRepeatDelay >= 0)
  34140. getRepeatTimer().startTimer (autoRepeatDelay);
  34141. if (triggerOnMouseDown)
  34142. internalClickCallback (e.mods);
  34143. }
  34144. }
  34145. void Button::mouseUp (const MouseEvent& e)
  34146. {
  34147. const bool wasDown = isDown();
  34148. updateState (&e);
  34149. if (wasDown && isOver() && ! triggerOnMouseDown)
  34150. internalClickCallback (e.mods);
  34151. }
  34152. void Button::mouseDrag (const MouseEvent& e)
  34153. {
  34154. const ButtonState oldState = buttonState;
  34155. updateState (&e);
  34156. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  34157. getRepeatTimer().startTimer (autoRepeatSpeed);
  34158. }
  34159. void Button::focusGained (FocusChangeType)
  34160. {
  34161. updateState (0);
  34162. repaint();
  34163. }
  34164. void Button::focusLost (FocusChangeType)
  34165. {
  34166. updateState (0);
  34167. repaint();
  34168. }
  34169. void Button::setVisible (bool shouldBeVisible)
  34170. {
  34171. if (shouldBeVisible != isVisible())
  34172. {
  34173. Component::setVisible (shouldBeVisible);
  34174. if (! shouldBeVisible)
  34175. needsToRelease = false;
  34176. updateState (0);
  34177. }
  34178. else
  34179. {
  34180. Component::setVisible (shouldBeVisible);
  34181. }
  34182. }
  34183. void Button::parentHierarchyChanged()
  34184. {
  34185. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  34186. if (newKeySource != keySource.getComponent())
  34187. {
  34188. if (keySource != 0)
  34189. keySource->removeKeyListener (this);
  34190. keySource = newKeySource;
  34191. if (keySource != 0)
  34192. keySource->addKeyListener (this);
  34193. }
  34194. }
  34195. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  34196. const int commandID_,
  34197. const bool generateTooltip_)
  34198. {
  34199. commandID = commandID_;
  34200. generateTooltip = generateTooltip_;
  34201. if (commandManagerToUse != commandManagerToUse_)
  34202. {
  34203. if (commandManagerToUse != 0)
  34204. commandManagerToUse->removeListener (this);
  34205. commandManagerToUse = commandManagerToUse_;
  34206. if (commandManagerToUse != 0)
  34207. commandManagerToUse->addListener (this);
  34208. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34209. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34210. // it is that this button represents, and the button will update its state to reflect this
  34211. // in the applicationCommandListChanged() method.
  34212. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34213. }
  34214. if (commandManagerToUse != 0)
  34215. applicationCommandListChanged();
  34216. else
  34217. setEnabled (true);
  34218. }
  34219. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  34220. {
  34221. if (info.commandID == commandID
  34222. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  34223. {
  34224. flashButtonState();
  34225. }
  34226. }
  34227. void Button::applicationCommandListChanged()
  34228. {
  34229. if (commandManagerToUse != 0)
  34230. {
  34231. ApplicationCommandInfo info (0);
  34232. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  34233. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  34234. if (target != 0)
  34235. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  34236. }
  34237. }
  34238. void Button::addShortcut (const KeyPress& key)
  34239. {
  34240. if (key.isValid())
  34241. {
  34242. jassert (! isRegisteredForShortcut (key)); // already registered!
  34243. shortcuts.add (key);
  34244. parentHierarchyChanged();
  34245. }
  34246. }
  34247. void Button::clearShortcuts()
  34248. {
  34249. shortcuts.clear();
  34250. parentHierarchyChanged();
  34251. }
  34252. bool Button::isShortcutPressed() const
  34253. {
  34254. if (! isCurrentlyBlockedByAnotherModalComponent())
  34255. {
  34256. for (int i = shortcuts.size(); --i >= 0;)
  34257. if (shortcuts.getReference(i).isCurrentlyDown())
  34258. return true;
  34259. }
  34260. return false;
  34261. }
  34262. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  34263. {
  34264. for (int i = shortcuts.size(); --i >= 0;)
  34265. if (key == shortcuts.getReference(i))
  34266. return true;
  34267. return false;
  34268. }
  34269. bool Button::keyStateChanged (const bool, Component*)
  34270. {
  34271. if (! isEnabled())
  34272. return false;
  34273. const bool wasDown = isKeyDown;
  34274. isKeyDown = isShortcutPressed();
  34275. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  34276. getRepeatTimer().startTimer (autoRepeatDelay);
  34277. updateState (0);
  34278. if (isEnabled() && wasDown && ! isKeyDown)
  34279. {
  34280. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34281. // (return immediately - this button may now have been deleted)
  34282. return true;
  34283. }
  34284. return wasDown || isKeyDown;
  34285. }
  34286. bool Button::keyPressed (const KeyPress&, Component*)
  34287. {
  34288. // returning true will avoid forwarding events for keys that we're using as shortcuts
  34289. return isShortcutPressed();
  34290. }
  34291. bool Button::keyPressed (const KeyPress& key)
  34292. {
  34293. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  34294. {
  34295. triggerClick();
  34296. return true;
  34297. }
  34298. return false;
  34299. }
  34300. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  34301. const int repeatMillisecs,
  34302. const int minimumDelayInMillisecs) throw()
  34303. {
  34304. autoRepeatDelay = initialDelayMillisecs;
  34305. autoRepeatSpeed = repeatMillisecs;
  34306. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  34307. }
  34308. void Button::repeatTimerCallback()
  34309. {
  34310. if (needsRepainting)
  34311. {
  34312. getRepeatTimer().stopTimer();
  34313. updateState (0);
  34314. needsRepainting = false;
  34315. }
  34316. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  34317. {
  34318. int repeatSpeed = autoRepeatSpeed;
  34319. if (autoRepeatMinimumDelay >= 0)
  34320. {
  34321. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  34322. timeHeldDown *= timeHeldDown;
  34323. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  34324. }
  34325. repeatSpeed = jmax (1, repeatSpeed);
  34326. getRepeatTimer().startTimer (repeatSpeed);
  34327. const uint32 now = Time::getApproximateMillisecondCounter();
  34328. const int numTimesToCallback = (now > lastTimeCallbackTime) ? jmax (1, (int) (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  34329. lastTimeCallbackTime = now;
  34330. Component::SafePointer<Component> deletionWatcher (this);
  34331. for (int i = numTimesToCallback; --i >= 0;)
  34332. {
  34333. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34334. if (deletionWatcher == 0 || ! isDown())
  34335. return;
  34336. }
  34337. }
  34338. else if (! needsToRelease)
  34339. {
  34340. getRepeatTimer().stopTimer();
  34341. }
  34342. }
  34343. Button::RepeatTimer& Button::getRepeatTimer()
  34344. {
  34345. if (repeatTimer == 0)
  34346. repeatTimer = new RepeatTimer (*this);
  34347. return *repeatTimer;
  34348. }
  34349. END_JUCE_NAMESPACE
  34350. /*** End of inlined file: juce_Button.cpp ***/
  34351. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  34352. BEGIN_JUCE_NAMESPACE
  34353. DrawableButton::DrawableButton (const String& name,
  34354. const DrawableButton::ButtonStyle buttonStyle)
  34355. : Button (name),
  34356. style (buttonStyle),
  34357. edgeIndent (3)
  34358. {
  34359. if (buttonStyle == ImageOnButtonBackground)
  34360. {
  34361. backgroundOff = Colour (0xffbbbbff);
  34362. backgroundOn = Colour (0xff3333ff);
  34363. }
  34364. else
  34365. {
  34366. backgroundOff = Colours::transparentBlack;
  34367. backgroundOn = Colour (0xaabbbbff);
  34368. }
  34369. }
  34370. DrawableButton::~DrawableButton()
  34371. {
  34372. deleteImages();
  34373. }
  34374. void DrawableButton::deleteImages()
  34375. {
  34376. }
  34377. void DrawableButton::setImages (const Drawable* normal,
  34378. const Drawable* over,
  34379. const Drawable* down,
  34380. const Drawable* disabled,
  34381. const Drawable* normalOn,
  34382. const Drawable* overOn,
  34383. const Drawable* downOn,
  34384. const Drawable* disabledOn)
  34385. {
  34386. deleteImages();
  34387. jassert (normal != 0); // you really need to give it at least a normal image..
  34388. if (normal != 0)
  34389. normalImage = normal->createCopy();
  34390. if (over != 0)
  34391. overImage = over->createCopy();
  34392. if (down != 0)
  34393. downImage = down->createCopy();
  34394. if (disabled != 0)
  34395. disabledImage = disabled->createCopy();
  34396. if (normalOn != 0)
  34397. normalImageOn = normalOn->createCopy();
  34398. if (overOn != 0)
  34399. overImageOn = overOn->createCopy();
  34400. if (downOn != 0)
  34401. downImageOn = downOn->createCopy();
  34402. if (disabledOn != 0)
  34403. disabledImageOn = disabledOn->createCopy();
  34404. repaint();
  34405. }
  34406. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  34407. {
  34408. if (style != newStyle)
  34409. {
  34410. style = newStyle;
  34411. repaint();
  34412. }
  34413. }
  34414. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  34415. const Colour& toggledOnColour)
  34416. {
  34417. if (backgroundOff != toggledOffColour
  34418. || backgroundOn != toggledOnColour)
  34419. {
  34420. backgroundOff = toggledOffColour;
  34421. backgroundOn = toggledOnColour;
  34422. repaint();
  34423. }
  34424. }
  34425. const Colour& DrawableButton::getBackgroundColour() const throw()
  34426. {
  34427. return getToggleState() ? backgroundOn
  34428. : backgroundOff;
  34429. }
  34430. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  34431. {
  34432. edgeIndent = numPixelsIndent;
  34433. repaint();
  34434. }
  34435. void DrawableButton::paintButton (Graphics& g,
  34436. bool isMouseOverButton,
  34437. bool isButtonDown)
  34438. {
  34439. Rectangle<int> imageSpace;
  34440. if (style == ImageOnButtonBackground)
  34441. {
  34442. const int insetX = getWidth() / 4;
  34443. const int insetY = getHeight() / 4;
  34444. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  34445. getLookAndFeel().drawButtonBackground (g, *this,
  34446. getBackgroundColour(),
  34447. isMouseOverButton,
  34448. isButtonDown);
  34449. }
  34450. else
  34451. {
  34452. g.fillAll (getBackgroundColour());
  34453. const int textH = (style == ImageAboveTextLabel)
  34454. ? jmin (16, proportionOfHeight (0.25f))
  34455. : 0;
  34456. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  34457. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  34458. imageSpace.setBounds (indentX, indentY,
  34459. getWidth() - indentX * 2,
  34460. getHeight() - indentY * 2 - textH);
  34461. if (textH > 0)
  34462. {
  34463. g.setFont ((float) textH);
  34464. g.setColour (Colours::black.withAlpha (isEnabled() ? 1.0f : 0.4f));
  34465. g.drawFittedText (getButtonText(),
  34466. 2, getHeight() - textH - 1,
  34467. getWidth() - 4, textH,
  34468. Justification::centred, 1);
  34469. }
  34470. }
  34471. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  34472. g.setOpacity (1.0f);
  34473. const Drawable* imageToDraw = 0;
  34474. if (isEnabled())
  34475. {
  34476. imageToDraw = getCurrentImage();
  34477. }
  34478. else
  34479. {
  34480. imageToDraw = getToggleState() ? disabledImageOn
  34481. : disabledImage;
  34482. if (imageToDraw == 0)
  34483. {
  34484. g.setOpacity (0.4f);
  34485. imageToDraw = getNormalImage();
  34486. }
  34487. }
  34488. if (imageToDraw != 0)
  34489. {
  34490. if (style == ImageRaw)
  34491. {
  34492. imageToDraw->draw (g, 1.0f);
  34493. }
  34494. else
  34495. {
  34496. imageToDraw->drawWithin (g,
  34497. imageSpace.getX(),
  34498. imageSpace.getY(),
  34499. imageSpace.getWidth(),
  34500. imageSpace.getHeight(),
  34501. RectanglePlacement::centred,
  34502. 1.0f);
  34503. }
  34504. }
  34505. }
  34506. const Drawable* DrawableButton::getCurrentImage() const throw()
  34507. {
  34508. if (isDown())
  34509. return getDownImage();
  34510. if (isOver())
  34511. return getOverImage();
  34512. return getNormalImage();
  34513. }
  34514. const Drawable* DrawableButton::getNormalImage() const throw()
  34515. {
  34516. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  34517. : normalImage;
  34518. }
  34519. const Drawable* DrawableButton::getOverImage() const throw()
  34520. {
  34521. const Drawable* d = normalImage;
  34522. if (getToggleState())
  34523. {
  34524. if (overImageOn != 0)
  34525. d = overImageOn;
  34526. else if (normalImageOn != 0)
  34527. d = normalImageOn;
  34528. else if (overImage != 0)
  34529. d = overImage;
  34530. }
  34531. else
  34532. {
  34533. if (overImage != 0)
  34534. d = overImage;
  34535. }
  34536. return d;
  34537. }
  34538. const Drawable* DrawableButton::getDownImage() const throw()
  34539. {
  34540. const Drawable* d = normalImage;
  34541. if (getToggleState())
  34542. {
  34543. if (downImageOn != 0)
  34544. d = downImageOn;
  34545. else if (overImageOn != 0)
  34546. d = overImageOn;
  34547. else if (normalImageOn != 0)
  34548. d = normalImageOn;
  34549. else if (downImage != 0)
  34550. d = downImage;
  34551. else
  34552. d = getOverImage();
  34553. }
  34554. else
  34555. {
  34556. if (downImage != 0)
  34557. d = downImage;
  34558. else
  34559. d = getOverImage();
  34560. }
  34561. return d;
  34562. }
  34563. END_JUCE_NAMESPACE
  34564. /*** End of inlined file: juce_DrawableButton.cpp ***/
  34565. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  34566. BEGIN_JUCE_NAMESPACE
  34567. HyperlinkButton::HyperlinkButton (const String& linkText,
  34568. const URL& linkURL)
  34569. : Button (linkText),
  34570. url (linkURL),
  34571. font (14.0f, Font::underlined),
  34572. resizeFont (true),
  34573. justification (Justification::centred)
  34574. {
  34575. setMouseCursor (MouseCursor::PointingHandCursor);
  34576. setTooltip (linkURL.toString (false));
  34577. }
  34578. HyperlinkButton::~HyperlinkButton()
  34579. {
  34580. }
  34581. void HyperlinkButton::setFont (const Font& newFont,
  34582. const bool resizeToMatchComponentHeight,
  34583. const Justification& justificationType)
  34584. {
  34585. font = newFont;
  34586. resizeFont = resizeToMatchComponentHeight;
  34587. justification = justificationType;
  34588. repaint();
  34589. }
  34590. void HyperlinkButton::setURL (const URL& newURL) throw()
  34591. {
  34592. url = newURL;
  34593. setTooltip (newURL.toString (false));
  34594. }
  34595. const Font HyperlinkButton::getFontToUse() const
  34596. {
  34597. Font f (font);
  34598. if (resizeFont)
  34599. f.setHeight (getHeight() * 0.7f);
  34600. return f;
  34601. }
  34602. void HyperlinkButton::changeWidthToFitText()
  34603. {
  34604. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  34605. }
  34606. void HyperlinkButton::colourChanged()
  34607. {
  34608. repaint();
  34609. }
  34610. void HyperlinkButton::clicked()
  34611. {
  34612. if (url.isWellFormed())
  34613. url.launchInDefaultBrowser();
  34614. }
  34615. void HyperlinkButton::paintButton (Graphics& g,
  34616. bool isMouseOverButton,
  34617. bool isButtonDown)
  34618. {
  34619. const Colour textColour (findColour (textColourId));
  34620. if (isEnabled())
  34621. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  34622. : textColour);
  34623. else
  34624. g.setColour (textColour.withMultipliedAlpha (0.4f));
  34625. g.setFont (getFontToUse());
  34626. g.drawText (getButtonText(),
  34627. 2, 0, getWidth() - 2, getHeight(),
  34628. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  34629. true);
  34630. }
  34631. END_JUCE_NAMESPACE
  34632. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  34633. /*** Start of inlined file: juce_ImageButton.cpp ***/
  34634. BEGIN_JUCE_NAMESPACE
  34635. ImageButton::ImageButton (const String& text_)
  34636. : Button (text_),
  34637. scaleImageToFit (true),
  34638. preserveProportions (true),
  34639. alphaThreshold (0),
  34640. imageX (0),
  34641. imageY (0),
  34642. imageW (0),
  34643. imageH (0),
  34644. normalImage (0),
  34645. overImage (0),
  34646. downImage (0)
  34647. {
  34648. }
  34649. ImageButton::~ImageButton()
  34650. {
  34651. deleteImages();
  34652. }
  34653. void ImageButton::deleteImages()
  34654. {
  34655. ImageCache::releaseOrDelete (normalImage);
  34656. ImageCache::releaseOrDelete (overImage);
  34657. ImageCache::releaseOrDelete (downImage);
  34658. }
  34659. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  34660. const bool rescaleImagesWhenButtonSizeChanges,
  34661. const bool preserveImageProportions,
  34662. Image* const normalImage_,
  34663. const float imageOpacityWhenNormal,
  34664. const Colour& overlayColourWhenNormal,
  34665. Image* const overImage_,
  34666. const float imageOpacityWhenOver,
  34667. const Colour& overlayColourWhenOver,
  34668. Image* const downImage_,
  34669. const float imageOpacityWhenDown,
  34670. const Colour& overlayColourWhenDown,
  34671. const float hitTestAlphaThreshold)
  34672. {
  34673. deleteImages();
  34674. normalImage = normalImage_;
  34675. overImage = overImage_;
  34676. downImage = downImage_;
  34677. if (resizeButtonNowToFitThisImage && normalImage != 0)
  34678. {
  34679. imageW = normalImage->getWidth();
  34680. imageH = normalImage->getHeight();
  34681. setSize (imageW, imageH);
  34682. }
  34683. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  34684. preserveProportions = preserveImageProportions;
  34685. normalOpacity = imageOpacityWhenNormal;
  34686. normalOverlay = overlayColourWhenNormal;
  34687. overOpacity = imageOpacityWhenOver;
  34688. overOverlay = overlayColourWhenOver;
  34689. downOpacity = imageOpacityWhenDown;
  34690. downOverlay = overlayColourWhenDown;
  34691. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  34692. repaint();
  34693. }
  34694. Image* ImageButton::getCurrentImage() const
  34695. {
  34696. if (isDown() || getToggleState())
  34697. return getDownImage();
  34698. if (isOver())
  34699. return getOverImage();
  34700. return getNormalImage();
  34701. }
  34702. Image* ImageButton::getNormalImage() const throw()
  34703. {
  34704. return normalImage;
  34705. }
  34706. Image* ImageButton::getOverImage() const throw()
  34707. {
  34708. return (overImage != 0) ? overImage
  34709. : normalImage;
  34710. }
  34711. Image* ImageButton::getDownImage() const throw()
  34712. {
  34713. return (downImage != 0) ? downImage
  34714. : getOverImage();
  34715. }
  34716. void ImageButton::paintButton (Graphics& g,
  34717. bool isMouseOverButton,
  34718. bool isButtonDown)
  34719. {
  34720. if (! isEnabled())
  34721. {
  34722. isMouseOverButton = false;
  34723. isButtonDown = false;
  34724. }
  34725. Image* const im = getCurrentImage();
  34726. if (im != 0)
  34727. {
  34728. const int iw = im->getWidth();
  34729. const int ih = im->getHeight();
  34730. imageW = getWidth();
  34731. imageH = getHeight();
  34732. imageX = (imageW - iw) >> 1;
  34733. imageY = (imageH - ih) >> 1;
  34734. if (scaleImageToFit)
  34735. {
  34736. if (preserveProportions)
  34737. {
  34738. int newW, newH;
  34739. const float imRatio = ih / (float)iw;
  34740. const float destRatio = imageH / (float)imageW;
  34741. if (imRatio > destRatio)
  34742. {
  34743. newW = roundToInt (imageH / imRatio);
  34744. newH = imageH;
  34745. }
  34746. else
  34747. {
  34748. newW = imageW;
  34749. newH = roundToInt (imageW * imRatio);
  34750. }
  34751. imageX = (imageW - newW) / 2;
  34752. imageY = (imageH - newH) / 2;
  34753. imageW = newW;
  34754. imageH = newH;
  34755. }
  34756. else
  34757. {
  34758. imageX = 0;
  34759. imageY = 0;
  34760. }
  34761. }
  34762. if (! scaleImageToFit)
  34763. {
  34764. imageW = iw;
  34765. imageH = ih;
  34766. }
  34767. getLookAndFeel().drawImageButton (g, im, imageX, imageY, imageW, imageH,
  34768. isButtonDown ? downOverlay
  34769. : (isMouseOverButton ? overOverlay
  34770. : normalOverlay),
  34771. isButtonDown ? downOpacity
  34772. : (isMouseOverButton ? overOpacity
  34773. : normalOpacity),
  34774. *this);
  34775. }
  34776. }
  34777. bool ImageButton::hitTest (int x, int y)
  34778. {
  34779. if (alphaThreshold == 0)
  34780. return true;
  34781. Image* const im = getCurrentImage();
  34782. return im == 0
  34783. || (imageW > 0 && imageH > 0
  34784. && alphaThreshold < im->getPixelAt (((x - imageX) * im->getWidth()) / imageW,
  34785. ((y - imageY) * im->getHeight()) / imageH).getAlpha());
  34786. }
  34787. END_JUCE_NAMESPACE
  34788. /*** End of inlined file: juce_ImageButton.cpp ***/
  34789. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  34790. BEGIN_JUCE_NAMESPACE
  34791. ShapeButton::ShapeButton (const String& text_,
  34792. const Colour& normalColour_,
  34793. const Colour& overColour_,
  34794. const Colour& downColour_)
  34795. : Button (text_),
  34796. normalColour (normalColour_),
  34797. overColour (overColour_),
  34798. downColour (downColour_),
  34799. maintainShapeProportions (false),
  34800. outlineWidth (0.0f)
  34801. {
  34802. }
  34803. ShapeButton::~ShapeButton()
  34804. {
  34805. }
  34806. void ShapeButton::setColours (const Colour& newNormalColour,
  34807. const Colour& newOverColour,
  34808. const Colour& newDownColour)
  34809. {
  34810. normalColour = newNormalColour;
  34811. overColour = newOverColour;
  34812. downColour = newDownColour;
  34813. }
  34814. void ShapeButton::setOutline (const Colour& newOutlineColour,
  34815. const float newOutlineWidth)
  34816. {
  34817. outlineColour = newOutlineColour;
  34818. outlineWidth = newOutlineWidth;
  34819. }
  34820. void ShapeButton::setShape (const Path& newShape,
  34821. const bool resizeNowToFitThisShape,
  34822. const bool maintainShapeProportions_,
  34823. const bool hasShadow)
  34824. {
  34825. shape = newShape;
  34826. maintainShapeProportions = maintainShapeProportions_;
  34827. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  34828. setComponentEffect ((hasShadow) ? &shadow : 0);
  34829. if (resizeNowToFitThisShape)
  34830. {
  34831. Rectangle<float> bounds (shape.getBounds());
  34832. if (hasShadow)
  34833. bounds.expand (4.0f, 4.0f);
  34834. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  34835. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  34836. 1 + (int) (bounds.getHeight() + outlineWidth));
  34837. }
  34838. }
  34839. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  34840. {
  34841. if (! isEnabled())
  34842. {
  34843. isMouseOverButton = false;
  34844. isButtonDown = false;
  34845. }
  34846. g.setColour ((isButtonDown) ? downColour
  34847. : (isMouseOverButton) ? overColour
  34848. : normalColour);
  34849. int w = getWidth();
  34850. int h = getHeight();
  34851. if (getComponentEffect() != 0)
  34852. {
  34853. w -= 4;
  34854. h -= 4;
  34855. }
  34856. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  34857. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  34858. w - offset - outlineWidth,
  34859. h - offset - outlineWidth,
  34860. maintainShapeProportions));
  34861. g.fillPath (shape, trans);
  34862. if (outlineWidth > 0.0f)
  34863. {
  34864. g.setColour (outlineColour);
  34865. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  34866. }
  34867. }
  34868. END_JUCE_NAMESPACE
  34869. /*** End of inlined file: juce_ShapeButton.cpp ***/
  34870. /*** Start of inlined file: juce_TextButton.cpp ***/
  34871. BEGIN_JUCE_NAMESPACE
  34872. TextButton::TextButton (const String& name,
  34873. const String& toolTip)
  34874. : Button (name)
  34875. {
  34876. setTooltip (toolTip);
  34877. }
  34878. TextButton::~TextButton()
  34879. {
  34880. }
  34881. void TextButton::paintButton (Graphics& g,
  34882. bool isMouseOverButton,
  34883. bool isButtonDown)
  34884. {
  34885. getLookAndFeel().drawButtonBackground (g, *this,
  34886. findColour (getToggleState() ? buttonOnColourId
  34887. : buttonColourId),
  34888. isMouseOverButton,
  34889. isButtonDown);
  34890. getLookAndFeel().drawButtonText (g, *this,
  34891. isMouseOverButton,
  34892. isButtonDown);
  34893. }
  34894. void TextButton::colourChanged()
  34895. {
  34896. repaint();
  34897. }
  34898. const Font TextButton::getFont()
  34899. {
  34900. return Font (jmin (15.0f, getHeight() * 0.6f));
  34901. }
  34902. void TextButton::changeWidthToFitText (const int newHeight)
  34903. {
  34904. if (newHeight >= 0)
  34905. setSize (jmax (1, getWidth()), newHeight);
  34906. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  34907. getHeight());
  34908. }
  34909. END_JUCE_NAMESPACE
  34910. /*** End of inlined file: juce_TextButton.cpp ***/
  34911. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  34912. BEGIN_JUCE_NAMESPACE
  34913. ToggleButton::ToggleButton (const String& buttonText)
  34914. : Button (buttonText)
  34915. {
  34916. setClickingTogglesState (true);
  34917. }
  34918. ToggleButton::~ToggleButton()
  34919. {
  34920. }
  34921. void ToggleButton::paintButton (Graphics& g,
  34922. bool isMouseOverButton,
  34923. bool isButtonDown)
  34924. {
  34925. getLookAndFeel().drawToggleButton (g, *this,
  34926. isMouseOverButton,
  34927. isButtonDown);
  34928. }
  34929. void ToggleButton::changeWidthToFitText()
  34930. {
  34931. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  34932. }
  34933. void ToggleButton::colourChanged()
  34934. {
  34935. repaint();
  34936. }
  34937. END_JUCE_NAMESPACE
  34938. /*** End of inlined file: juce_ToggleButton.cpp ***/
  34939. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  34940. BEGIN_JUCE_NAMESPACE
  34941. ToolbarButton::ToolbarButton (const int itemId_,
  34942. const String& buttonText,
  34943. Drawable* const normalImage_,
  34944. Drawable* const toggledOnImage_)
  34945. : ToolbarItemComponent (itemId_, buttonText, true),
  34946. normalImage (normalImage_),
  34947. toggledOnImage (toggledOnImage_)
  34948. {
  34949. jassert (normalImage_ != 0);
  34950. }
  34951. ToolbarButton::~ToolbarButton()
  34952. {
  34953. }
  34954. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  34955. bool /*isToolbarVertical*/,
  34956. int& preferredSize,
  34957. int& minSize, int& maxSize)
  34958. {
  34959. preferredSize = minSize = maxSize = toolbarDepth;
  34960. return true;
  34961. }
  34962. void ToolbarButton::paintButtonArea (Graphics& g,
  34963. int width, int height,
  34964. bool /*isMouseOver*/,
  34965. bool /*isMouseDown*/)
  34966. {
  34967. Drawable* d = normalImage;
  34968. if (getToggleState() && toggledOnImage != 0)
  34969. d = toggledOnImage;
  34970. if (! isEnabled())
  34971. {
  34972. Image im (Image::ARGB, width, height, true);
  34973. Graphics g2 (im);
  34974. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  34975. im.desaturate();
  34976. g.drawImageAt (&im, 0, 0);
  34977. }
  34978. else
  34979. {
  34980. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  34981. }
  34982. }
  34983. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  34984. {
  34985. }
  34986. END_JUCE_NAMESPACE
  34987. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  34988. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  34989. BEGIN_JUCE_NAMESPACE
  34990. class CodeDocumentLine
  34991. {
  34992. public:
  34993. CodeDocumentLine (const juce_wchar* const line_,
  34994. const int lineLength_,
  34995. const int numNewLineChars,
  34996. const int lineStartInFile_)
  34997. : line (line_, lineLength_),
  34998. lineStartInFile (lineStartInFile_),
  34999. lineLength (lineLength_),
  35000. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  35001. {
  35002. }
  35003. ~CodeDocumentLine()
  35004. {
  35005. }
  35006. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  35007. {
  35008. const juce_wchar* const t = text;
  35009. int pos = 0;
  35010. while (t [pos] != 0)
  35011. {
  35012. const int startOfLine = pos;
  35013. int numNewLineChars = 0;
  35014. while (t[pos] != 0)
  35015. {
  35016. if (t[pos] == '\r')
  35017. {
  35018. ++numNewLineChars;
  35019. ++pos;
  35020. if (t[pos] == '\n')
  35021. {
  35022. ++numNewLineChars;
  35023. ++pos;
  35024. }
  35025. break;
  35026. }
  35027. if (t[pos] == '\n')
  35028. {
  35029. ++numNewLineChars;
  35030. ++pos;
  35031. break;
  35032. }
  35033. ++pos;
  35034. }
  35035. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  35036. numNewLineChars, startOfLine));
  35037. }
  35038. jassert (pos == text.length());
  35039. }
  35040. bool endsWithLineBreak() const throw()
  35041. {
  35042. return lineLengthWithoutNewLines != lineLength;
  35043. }
  35044. void updateLength() throw()
  35045. {
  35046. lineLengthWithoutNewLines = lineLength = line.length();
  35047. while (lineLengthWithoutNewLines > 0
  35048. && (line [lineLengthWithoutNewLines - 1] == '\n'
  35049. || line [lineLengthWithoutNewLines - 1] == '\r'))
  35050. {
  35051. --lineLengthWithoutNewLines;
  35052. }
  35053. }
  35054. String line;
  35055. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  35056. };
  35057. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  35058. : document (document_),
  35059. currentLine (document_->lines[0]),
  35060. line (0),
  35061. position (0)
  35062. {
  35063. }
  35064. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  35065. : document (other.document),
  35066. currentLine (other.currentLine),
  35067. line (other.line),
  35068. position (other.position)
  35069. {
  35070. }
  35071. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  35072. {
  35073. document = other.document;
  35074. currentLine = other.currentLine;
  35075. line = other.line;
  35076. position = other.position;
  35077. return *this;
  35078. }
  35079. CodeDocument::Iterator::~Iterator() throw()
  35080. {
  35081. }
  35082. juce_wchar CodeDocument::Iterator::nextChar()
  35083. {
  35084. if (currentLine == 0)
  35085. return 0;
  35086. jassert (currentLine == document->lines.getUnchecked (line));
  35087. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  35088. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35089. {
  35090. ++line;
  35091. currentLine = document->lines [line];
  35092. }
  35093. return result;
  35094. }
  35095. void CodeDocument::Iterator::skip()
  35096. {
  35097. if (currentLine != 0)
  35098. {
  35099. jassert (currentLine == document->lines.getUnchecked (line));
  35100. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35101. {
  35102. ++line;
  35103. currentLine = document->lines [line];
  35104. }
  35105. }
  35106. }
  35107. void CodeDocument::Iterator::skipToEndOfLine()
  35108. {
  35109. if (currentLine != 0)
  35110. {
  35111. jassert (currentLine == document->lines.getUnchecked (line));
  35112. ++line;
  35113. currentLine = document->lines [line];
  35114. if (currentLine != 0)
  35115. position = currentLine->lineStartInFile;
  35116. else
  35117. position = document->getNumCharacters();
  35118. }
  35119. }
  35120. juce_wchar CodeDocument::Iterator::peekNextChar() const
  35121. {
  35122. if (currentLine == 0)
  35123. return 0;
  35124. jassert (currentLine == document->lines.getUnchecked (line));
  35125. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  35126. }
  35127. void CodeDocument::Iterator::skipWhitespace()
  35128. {
  35129. while (CharacterFunctions::isWhitespace (peekNextChar()))
  35130. skip();
  35131. }
  35132. bool CodeDocument::Iterator::isEOF() const throw()
  35133. {
  35134. return currentLine == 0;
  35135. }
  35136. CodeDocument::Position::Position() throw()
  35137. : owner (0), characterPos (0), line (0),
  35138. indexInLine (0), positionMaintained (false)
  35139. {
  35140. }
  35141. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35142. const int line_, const int indexInLine_) throw()
  35143. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35144. characterPos (0), line (line_),
  35145. indexInLine (indexInLine_), positionMaintained (false)
  35146. {
  35147. setLineAndIndex (line_, indexInLine_);
  35148. }
  35149. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35150. const int characterPos_) throw()
  35151. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35152. positionMaintained (false)
  35153. {
  35154. setPosition (characterPos_);
  35155. }
  35156. CodeDocument::Position::Position (const Position& other) throw()
  35157. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  35158. indexInLine (other.indexInLine), positionMaintained (false)
  35159. {
  35160. jassert (*this == other);
  35161. }
  35162. CodeDocument::Position::~Position() throw()
  35163. {
  35164. setPositionMaintained (false);
  35165. }
  35166. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other) throw()
  35167. {
  35168. if (this != &other)
  35169. {
  35170. const bool wasPositionMaintained = positionMaintained;
  35171. if (owner != other.owner)
  35172. setPositionMaintained (false);
  35173. owner = other.owner;
  35174. line = other.line;
  35175. indexInLine = other.indexInLine;
  35176. characterPos = other.characterPos;
  35177. setPositionMaintained (wasPositionMaintained);
  35178. jassert (*this == other);
  35179. }
  35180. return *this;
  35181. }
  35182. bool CodeDocument::Position::operator== (const Position& other) const throw()
  35183. {
  35184. jassert ((characterPos == other.characterPos)
  35185. == (line == other.line && indexInLine == other.indexInLine));
  35186. return characterPos == other.characterPos
  35187. && line == other.line
  35188. && indexInLine == other.indexInLine
  35189. && owner == other.owner;
  35190. }
  35191. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  35192. {
  35193. return ! operator== (other);
  35194. }
  35195. void CodeDocument::Position::setLineAndIndex (const int newLine, const int newIndexInLine) throw()
  35196. {
  35197. jassert (owner != 0);
  35198. if (owner->lines.size() == 0)
  35199. {
  35200. line = 0;
  35201. indexInLine = 0;
  35202. characterPos = 0;
  35203. }
  35204. else
  35205. {
  35206. if (newLine >= owner->lines.size())
  35207. {
  35208. line = owner->lines.size() - 1;
  35209. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35210. jassert (l != 0);
  35211. indexInLine = l->lineLengthWithoutNewLines;
  35212. characterPos = l->lineStartInFile + indexInLine;
  35213. }
  35214. else
  35215. {
  35216. line = jmax (0, newLine);
  35217. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35218. jassert (l != 0);
  35219. if (l->lineLengthWithoutNewLines > 0)
  35220. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  35221. else
  35222. indexInLine = 0;
  35223. characterPos = l->lineStartInFile + indexInLine;
  35224. }
  35225. }
  35226. }
  35227. void CodeDocument::Position::setPosition (const int newPosition) throw()
  35228. {
  35229. jassert (owner != 0);
  35230. line = 0;
  35231. indexInLine = 0;
  35232. characterPos = 0;
  35233. if (newPosition > 0)
  35234. {
  35235. int lineStart = 0;
  35236. int lineEnd = owner->lines.size();
  35237. for (;;)
  35238. {
  35239. if (lineEnd - lineStart < 4)
  35240. {
  35241. for (int i = lineStart; i < lineEnd; ++i)
  35242. {
  35243. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  35244. int index = newPosition - l->lineStartInFile;
  35245. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  35246. {
  35247. line = i;
  35248. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  35249. characterPos = l->lineStartInFile + indexInLine;
  35250. }
  35251. }
  35252. break;
  35253. }
  35254. else
  35255. {
  35256. const int midIndex = (lineStart + lineEnd + 1) / 2;
  35257. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  35258. if (newPosition >= mid->lineStartInFile)
  35259. lineStart = midIndex;
  35260. else
  35261. lineEnd = midIndex;
  35262. }
  35263. }
  35264. }
  35265. }
  35266. void CodeDocument::Position::moveBy (int characterDelta) throw()
  35267. {
  35268. jassert (owner != 0);
  35269. if (characterDelta == 1)
  35270. {
  35271. setPosition (getPosition());
  35272. // If moving right, make sure we don't get stuck between the \r and \n characters..
  35273. if (line < owner->lines.size())
  35274. {
  35275. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35276. if (indexInLine + characterDelta < l->lineLength
  35277. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  35278. ++characterDelta;
  35279. }
  35280. }
  35281. setPosition (characterPos + characterDelta);
  35282. }
  35283. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const throw()
  35284. {
  35285. CodeDocument::Position p (*this);
  35286. p.moveBy (characterDelta);
  35287. return p;
  35288. }
  35289. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const throw()
  35290. {
  35291. CodeDocument::Position p (*this);
  35292. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  35293. return p;
  35294. }
  35295. const juce_wchar CodeDocument::Position::getCharacter() const throw()
  35296. {
  35297. const CodeDocumentLine* const l = owner->lines [line];
  35298. return l == 0 ? 0 : l->line [getIndexInLine()];
  35299. }
  35300. const String CodeDocument::Position::getLineText() const throw()
  35301. {
  35302. const CodeDocumentLine* const l = owner->lines [line];
  35303. return l == 0 ? String::empty : l->line;
  35304. }
  35305. void CodeDocument::Position::setPositionMaintained (const bool isMaintained) throw()
  35306. {
  35307. if (isMaintained != positionMaintained)
  35308. {
  35309. positionMaintained = isMaintained;
  35310. if (owner != 0)
  35311. {
  35312. if (isMaintained)
  35313. {
  35314. jassert (! owner->positionsToMaintain.contains (this));
  35315. owner->positionsToMaintain.add (this);
  35316. }
  35317. else
  35318. {
  35319. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  35320. jassert (owner->positionsToMaintain.contains (this));
  35321. owner->positionsToMaintain.removeValue (this);
  35322. }
  35323. }
  35324. }
  35325. }
  35326. CodeDocument::CodeDocument()
  35327. : undoManager (std::numeric_limits<int>::max(), 10000),
  35328. currentActionIndex (0),
  35329. indexOfSavedState (-1),
  35330. maximumLineLength (-1),
  35331. newLineChars ("\r\n")
  35332. {
  35333. }
  35334. CodeDocument::~CodeDocument()
  35335. {
  35336. }
  35337. const String CodeDocument::getAllContent() const throw()
  35338. {
  35339. return getTextBetween (Position (this, 0),
  35340. Position (this, lines.size(), 0));
  35341. }
  35342. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const throw()
  35343. {
  35344. if (end.getPosition() <= start.getPosition())
  35345. return String::empty;
  35346. const int startLine = start.getLineNumber();
  35347. const int endLine = end.getLineNumber();
  35348. if (startLine == endLine)
  35349. {
  35350. CodeDocumentLine* const line = lines [startLine];
  35351. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  35352. }
  35353. String result;
  35354. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  35355. String::Concatenator concatenator (result);
  35356. const int maxLine = jmin (lines.size() - 1, endLine);
  35357. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  35358. {
  35359. const CodeDocumentLine* line = lines.getUnchecked(i);
  35360. int len = line->lineLength;
  35361. if (i == startLine)
  35362. {
  35363. const int index = start.getIndexInLine();
  35364. concatenator.append (line->line.substring (index, len));
  35365. }
  35366. else if (i == endLine)
  35367. {
  35368. len = end.getIndexInLine();
  35369. concatenator.append (line->line.substring (0, len));
  35370. }
  35371. else
  35372. {
  35373. concatenator.append (line->line);
  35374. }
  35375. }
  35376. return result;
  35377. }
  35378. int CodeDocument::getNumCharacters() const throw()
  35379. {
  35380. const CodeDocumentLine* const lastLine = lines.getLast();
  35381. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  35382. }
  35383. const String CodeDocument::getLine (const int lineIndex) const throw()
  35384. {
  35385. const CodeDocumentLine* const line = lines [lineIndex];
  35386. return (line == 0) ? String::empty : line->line;
  35387. }
  35388. int CodeDocument::getMaximumLineLength() throw()
  35389. {
  35390. if (maximumLineLength < 0)
  35391. {
  35392. maximumLineLength = 0;
  35393. for (int i = lines.size(); --i >= 0;)
  35394. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  35395. }
  35396. return maximumLineLength;
  35397. }
  35398. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  35399. {
  35400. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  35401. }
  35402. void CodeDocument::insertText (const Position& position, const String& text)
  35403. {
  35404. insert (text, position.getPosition(), true);
  35405. }
  35406. void CodeDocument::replaceAllContent (const String& newContent)
  35407. {
  35408. remove (0, getNumCharacters(), true);
  35409. insert (newContent, 0, true);
  35410. }
  35411. bool CodeDocument::loadFromStream (InputStream& stream)
  35412. {
  35413. replaceAllContent (stream.readEntireStreamAsString());
  35414. setSavePoint();
  35415. clearUndoHistory();
  35416. return true;
  35417. }
  35418. bool CodeDocument::writeToStream (OutputStream& stream)
  35419. {
  35420. for (int i = 0; i < lines.size(); ++i)
  35421. {
  35422. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  35423. const char* utf8 = temp.toUTF8();
  35424. if (! stream.write (utf8, (int) strlen (utf8)))
  35425. return false;
  35426. }
  35427. return true;
  35428. }
  35429. void CodeDocument::setNewLineCharacters (const String& newLine) throw()
  35430. {
  35431. jassert (newLine == "\r\n" || newLine == "\n" || newLine == "\r");
  35432. newLineChars = newLine;
  35433. }
  35434. void CodeDocument::newTransaction()
  35435. {
  35436. undoManager.beginNewTransaction (String::empty);
  35437. }
  35438. void CodeDocument::undo()
  35439. {
  35440. newTransaction();
  35441. undoManager.undo();
  35442. }
  35443. void CodeDocument::redo()
  35444. {
  35445. undoManager.redo();
  35446. }
  35447. void CodeDocument::clearUndoHistory()
  35448. {
  35449. undoManager.clearUndoHistory();
  35450. }
  35451. void CodeDocument::setSavePoint() throw()
  35452. {
  35453. indexOfSavedState = currentActionIndex;
  35454. }
  35455. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  35456. {
  35457. return currentActionIndex != indexOfSavedState;
  35458. }
  35459. static int getCodeCharacterCategory (const juce_wchar character) throw()
  35460. {
  35461. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  35462. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  35463. }
  35464. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  35465. {
  35466. Position p (position);
  35467. const int maxDistance = 256;
  35468. int i = 0;
  35469. while (i < maxDistance
  35470. && CharacterFunctions::isWhitespace (p.getCharacter())
  35471. && (i == 0 || (p.getCharacter() != '\n'
  35472. && p.getCharacter() != '\r')))
  35473. {
  35474. ++i;
  35475. p.moveBy (1);
  35476. }
  35477. if (i == 0)
  35478. {
  35479. const int type = getCodeCharacterCategory (p.getCharacter());
  35480. while (i < maxDistance && type == getCodeCharacterCategory (p.getCharacter()))
  35481. {
  35482. ++i;
  35483. p.moveBy (1);
  35484. }
  35485. while (i < maxDistance
  35486. && CharacterFunctions::isWhitespace (p.getCharacter())
  35487. && (i == 0 || (p.getCharacter() != '\n'
  35488. && p.getCharacter() != '\r')))
  35489. {
  35490. ++i;
  35491. p.moveBy (1);
  35492. }
  35493. }
  35494. return p;
  35495. }
  35496. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  35497. {
  35498. Position p (position);
  35499. const int maxDistance = 256;
  35500. int i = 0;
  35501. bool stoppedAtLineStart = false;
  35502. while (i < maxDistance)
  35503. {
  35504. const juce_wchar c = p.movedBy (-1).getCharacter();
  35505. if (c == '\r' || c == '\n')
  35506. {
  35507. stoppedAtLineStart = true;
  35508. if (i > 0)
  35509. break;
  35510. }
  35511. if (! CharacterFunctions::isWhitespace (c))
  35512. break;
  35513. p.moveBy (-1);
  35514. ++i;
  35515. }
  35516. if (i < maxDistance && ! stoppedAtLineStart)
  35517. {
  35518. const int type = getCodeCharacterCategory (p.movedBy (-1).getCharacter());
  35519. while (i < maxDistance && type == getCodeCharacterCategory (p.movedBy (-1).getCharacter()))
  35520. {
  35521. p.moveBy (-1);
  35522. ++i;
  35523. }
  35524. }
  35525. return p;
  35526. }
  35527. void CodeDocument::checkLastLineStatus()
  35528. {
  35529. while (lines.size() > 0
  35530. && lines.getLast()->lineLength == 0
  35531. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  35532. {
  35533. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  35534. lines.removeLast();
  35535. }
  35536. const CodeDocumentLine* const lastLine = lines.getLast();
  35537. if (lastLine != 0 && lastLine->endsWithLineBreak())
  35538. {
  35539. // check that there's an empty line at the end if the preceding one ends in a newline..
  35540. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  35541. }
  35542. }
  35543. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  35544. {
  35545. listeners.add (listener);
  35546. }
  35547. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  35548. {
  35549. listeners.remove (listener);
  35550. }
  35551. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  35552. {
  35553. Position startPos (this, startLine, 0);
  35554. Position endPos (this, endLine, 0);
  35555. listeners.call (&Listener::codeDocumentChanged, startPos, endPos);
  35556. }
  35557. class CodeDocumentInsertAction : public UndoableAction
  35558. {
  35559. CodeDocument& owner;
  35560. const String text;
  35561. int insertPos;
  35562. CodeDocumentInsertAction (const CodeDocumentInsertAction&);
  35563. CodeDocumentInsertAction& operator= (const CodeDocumentInsertAction&);
  35564. public:
  35565. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  35566. : owner (owner_),
  35567. text (text_),
  35568. insertPos (insertPos_)
  35569. {
  35570. }
  35571. ~CodeDocumentInsertAction() {}
  35572. bool perform()
  35573. {
  35574. owner.currentActionIndex++;
  35575. owner.insert (text, insertPos, false);
  35576. return true;
  35577. }
  35578. bool undo()
  35579. {
  35580. owner.currentActionIndex--;
  35581. owner.remove (insertPos, insertPos + text.length(), false);
  35582. return true;
  35583. }
  35584. int getSizeInUnits() { return text.length() + 32; }
  35585. };
  35586. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  35587. {
  35588. if (text.isEmpty())
  35589. return;
  35590. if (undoable)
  35591. {
  35592. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  35593. }
  35594. else
  35595. {
  35596. Position pos (this, insertPos);
  35597. const int firstAffectedLine = pos.getLineNumber();
  35598. int lastAffectedLine = firstAffectedLine + 1;
  35599. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  35600. String textInsideOriginalLine (text);
  35601. if (firstLine != 0)
  35602. {
  35603. const int index = pos.getIndexInLine();
  35604. textInsideOriginalLine = firstLine->line.substring (0, index)
  35605. + textInsideOriginalLine
  35606. + firstLine->line.substring (index);
  35607. }
  35608. maximumLineLength = -1;
  35609. Array <CodeDocumentLine*> newLines;
  35610. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  35611. jassert (newLines.size() > 0);
  35612. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  35613. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  35614. lines.set (firstAffectedLine, newFirstLine);
  35615. if (newLines.size() > 1)
  35616. {
  35617. for (int i = 1; i < newLines.size(); ++i)
  35618. {
  35619. CodeDocumentLine* const l = newLines.getUnchecked (i);
  35620. lines.insert (firstAffectedLine + i, l);
  35621. }
  35622. lastAffectedLine = lines.size();
  35623. }
  35624. int i, lineStart = newFirstLine->lineStartInFile;
  35625. for (i = firstAffectedLine; i < lines.size(); ++i)
  35626. {
  35627. CodeDocumentLine* const l = lines.getUnchecked (i);
  35628. l->lineStartInFile = lineStart;
  35629. lineStart += l->lineLength;
  35630. }
  35631. checkLastLineStatus();
  35632. const int newTextLength = text.length();
  35633. for (i = 0; i < positionsToMaintain.size(); ++i)
  35634. {
  35635. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  35636. if (p->getPosition() >= insertPos)
  35637. p->setPosition (p->getPosition() + newTextLength);
  35638. }
  35639. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  35640. }
  35641. }
  35642. class CodeDocumentDeleteAction : public UndoableAction
  35643. {
  35644. CodeDocument& owner;
  35645. int startPos, endPos;
  35646. String removedText;
  35647. CodeDocumentDeleteAction (const CodeDocumentDeleteAction&);
  35648. CodeDocumentDeleteAction& operator= (const CodeDocumentDeleteAction&);
  35649. public:
  35650. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  35651. : owner (owner_),
  35652. startPos (startPos_),
  35653. endPos (endPos_)
  35654. {
  35655. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  35656. CodeDocument::Position (&owner, endPos));
  35657. }
  35658. ~CodeDocumentDeleteAction() {}
  35659. bool perform()
  35660. {
  35661. owner.currentActionIndex++;
  35662. owner.remove (startPos, endPos, false);
  35663. return true;
  35664. }
  35665. bool undo()
  35666. {
  35667. owner.currentActionIndex--;
  35668. owner.insert (removedText, startPos, false);
  35669. return true;
  35670. }
  35671. int getSizeInUnits() { return removedText.length() + 32; }
  35672. };
  35673. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  35674. {
  35675. if (endPos <= startPos)
  35676. return;
  35677. if (undoable)
  35678. {
  35679. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  35680. }
  35681. else
  35682. {
  35683. Position startPosition (this, startPos);
  35684. Position endPosition (this, endPos);
  35685. maximumLineLength = -1;
  35686. const int firstAffectedLine = startPosition.getLineNumber();
  35687. const int endLine = endPosition.getLineNumber();
  35688. int lastAffectedLine = firstAffectedLine + 1;
  35689. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  35690. if (firstAffectedLine == endLine)
  35691. {
  35692. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  35693. + firstLine->line.substring (endPosition.getIndexInLine());
  35694. firstLine->updateLength();
  35695. }
  35696. else
  35697. {
  35698. lastAffectedLine = lines.size();
  35699. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  35700. jassert (lastLine != 0);
  35701. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  35702. + lastLine->line.substring (endPosition.getIndexInLine());
  35703. firstLine->updateLength();
  35704. int numLinesToRemove = endLine - firstAffectedLine;
  35705. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  35706. }
  35707. int i;
  35708. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  35709. {
  35710. CodeDocumentLine* const l = lines.getUnchecked (i);
  35711. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  35712. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  35713. }
  35714. checkLastLineStatus();
  35715. const int totalChars = getNumCharacters();
  35716. for (i = 0; i < positionsToMaintain.size(); ++i)
  35717. {
  35718. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  35719. if (p->getPosition() > startPosition.getPosition())
  35720. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  35721. if (p->getPosition() > totalChars)
  35722. p->setPosition (totalChars);
  35723. }
  35724. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  35725. }
  35726. }
  35727. END_JUCE_NAMESPACE
  35728. /*** End of inlined file: juce_CodeDocument.cpp ***/
  35729. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  35730. BEGIN_JUCE_NAMESPACE
  35731. class CodeEditorComponent::CaretComponent : public Component,
  35732. public Timer
  35733. {
  35734. public:
  35735. CaretComponent (CodeEditorComponent& owner_)
  35736. : owner (owner_)
  35737. {
  35738. setAlwaysOnTop (true);
  35739. setInterceptsMouseClicks (false, false);
  35740. }
  35741. ~CaretComponent()
  35742. {
  35743. }
  35744. void paint (Graphics& g)
  35745. {
  35746. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  35747. }
  35748. void timerCallback()
  35749. {
  35750. setVisible (shouldBeShown() && ! isVisible());
  35751. }
  35752. void updatePosition()
  35753. {
  35754. startTimer (400);
  35755. setVisible (shouldBeShown());
  35756. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  35757. }
  35758. private:
  35759. CodeEditorComponent& owner;
  35760. CaretComponent (const CaretComponent&);
  35761. CaretComponent& operator= (const CaretComponent&);
  35762. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  35763. };
  35764. class CodeEditorComponent::CodeEditorLine
  35765. {
  35766. public:
  35767. CodeEditorLine() throw()
  35768. : highlightColumnStart (0), highlightColumnEnd (0)
  35769. {
  35770. }
  35771. ~CodeEditorLine() throw()
  35772. {
  35773. }
  35774. bool update (CodeDocument& document, int lineNum,
  35775. CodeDocument::Iterator& source,
  35776. CodeTokeniser* analyser, const int spacesPerTab,
  35777. const CodeDocument::Position& selectionStart,
  35778. const CodeDocument::Position& selectionEnd)
  35779. {
  35780. Array <SyntaxToken> newTokens;
  35781. newTokens.ensureStorageAllocated (8);
  35782. if (analyser == 0)
  35783. {
  35784. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  35785. }
  35786. else if (lineNum < document.getNumLines())
  35787. {
  35788. const CodeDocument::Position pos (&document, lineNum, 0);
  35789. createTokens (pos.getPosition(), pos.getLineText(),
  35790. source, analyser, newTokens);
  35791. }
  35792. replaceTabsWithSpaces (newTokens, spacesPerTab);
  35793. int newHighlightStart = 0;
  35794. int newHighlightEnd = 0;
  35795. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  35796. {
  35797. const String line (document.getLine (lineNum));
  35798. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  35799. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  35800. line, spacesPerTab);
  35801. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  35802. line, spacesPerTab);
  35803. }
  35804. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  35805. {
  35806. highlightColumnStart = newHighlightStart;
  35807. highlightColumnEnd = newHighlightEnd;
  35808. }
  35809. else
  35810. {
  35811. if (tokens.size() == newTokens.size())
  35812. {
  35813. bool allTheSame = true;
  35814. for (int i = newTokens.size(); --i >= 0;)
  35815. {
  35816. if (tokens.getReference(i) != newTokens.getReference(i))
  35817. {
  35818. allTheSame = false;
  35819. break;
  35820. }
  35821. }
  35822. if (allTheSame)
  35823. return false;
  35824. }
  35825. }
  35826. tokens.swapWithArray (newTokens);
  35827. return true;
  35828. }
  35829. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  35830. float x, const int y, const int baselineOffset, const int lineHeight,
  35831. const Colour& highlightColour) const throw()
  35832. {
  35833. if (highlightColumnStart < highlightColumnEnd)
  35834. {
  35835. g.setColour (highlightColour);
  35836. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  35837. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  35838. }
  35839. int lastType = std::numeric_limits<int>::min();
  35840. for (int i = 0; i < tokens.size(); ++i)
  35841. {
  35842. SyntaxToken& token = tokens.getReference(i);
  35843. if (lastType != token.tokenType)
  35844. {
  35845. lastType = token.tokenType;
  35846. g.setColour (owner.getColourForTokenType (lastType));
  35847. }
  35848. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  35849. if (i < tokens.size() - 1)
  35850. {
  35851. if (token.width < 0)
  35852. token.width = font.getStringWidthFloat (token.text);
  35853. x += token.width;
  35854. }
  35855. }
  35856. }
  35857. private:
  35858. struct SyntaxToken
  35859. {
  35860. String text;
  35861. int tokenType;
  35862. float width;
  35863. SyntaxToken (const String& text_, const int type) throw()
  35864. : text (text_), tokenType (type), width (-1.0f)
  35865. {
  35866. }
  35867. bool operator!= (const SyntaxToken& other) const throw()
  35868. {
  35869. return text != other.text || tokenType != other.tokenType;
  35870. }
  35871. };
  35872. Array <SyntaxToken> tokens;
  35873. int highlightColumnStart, highlightColumnEnd;
  35874. static void createTokens (int startPosition, const String& lineText,
  35875. CodeDocument::Iterator& source,
  35876. CodeTokeniser* analyser,
  35877. Array <SyntaxToken>& newTokens)
  35878. {
  35879. CodeDocument::Iterator lastIterator (source);
  35880. const int lineLength = lineText.length();
  35881. for (;;)
  35882. {
  35883. int tokenType = analyser->readNextToken (source);
  35884. int tokenStart = lastIterator.getPosition();
  35885. int tokenEnd = source.getPosition();
  35886. if (tokenEnd <= tokenStart)
  35887. break;
  35888. tokenEnd -= startPosition;
  35889. if (tokenEnd > 0)
  35890. {
  35891. tokenStart -= startPosition;
  35892. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  35893. tokenType));
  35894. if (tokenEnd >= lineLength)
  35895. break;
  35896. }
  35897. lastIterator = source;
  35898. }
  35899. source = lastIterator;
  35900. }
  35901. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab) throw()
  35902. {
  35903. int x = 0;
  35904. for (int i = 0; i < tokens.size(); ++i)
  35905. {
  35906. SyntaxToken& t = tokens.getReference(i);
  35907. for (;;)
  35908. {
  35909. int tabPos = t.text.indexOfChar ('\t');
  35910. if (tabPos < 0)
  35911. break;
  35912. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  35913. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  35914. }
  35915. x += t.text.length();
  35916. }
  35917. }
  35918. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  35919. {
  35920. jassert (index <= line.length());
  35921. int col = 0;
  35922. for (int i = 0; i < index; ++i)
  35923. {
  35924. if (line[i] != '\t')
  35925. ++col;
  35926. else
  35927. col += spacesPerTab - (col % spacesPerTab);
  35928. }
  35929. return col;
  35930. }
  35931. };
  35932. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  35933. CodeTokeniser* const codeTokeniser_)
  35934. : document (document_),
  35935. firstLineOnScreen (0),
  35936. gutter (5),
  35937. spacesPerTab (4),
  35938. lineHeight (0),
  35939. linesOnScreen (0),
  35940. columnsOnScreen (0),
  35941. scrollbarThickness (16),
  35942. columnToTryToMaintain (-1),
  35943. useSpacesForTabs (false),
  35944. xOffset (0),
  35945. codeTokeniser (codeTokeniser_)
  35946. {
  35947. caretPos = CodeDocument::Position (&document_, 0, 0);
  35948. caretPos.setPositionMaintained (true);
  35949. selectionStart = CodeDocument::Position (&document_, 0, 0);
  35950. selectionStart.setPositionMaintained (true);
  35951. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  35952. selectionEnd.setPositionMaintained (true);
  35953. setOpaque (true);
  35954. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  35955. setWantsKeyboardFocus (true);
  35956. addAndMakeVisible (verticalScrollBar = new ScrollBar (true));
  35957. verticalScrollBar->setSingleStepSize (1.0);
  35958. addAndMakeVisible (horizontalScrollBar = new ScrollBar (false));
  35959. horizontalScrollBar->setSingleStepSize (1.0);
  35960. addAndMakeVisible (caret = new CaretComponent (*this));
  35961. Font f (12.0f);
  35962. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  35963. setFont (f);
  35964. resetToDefaultColours();
  35965. verticalScrollBar->addListener (this);
  35966. horizontalScrollBar->addListener (this);
  35967. document.addListener (this);
  35968. }
  35969. CodeEditorComponent::~CodeEditorComponent()
  35970. {
  35971. document.removeListener (this);
  35972. deleteAllChildren();
  35973. }
  35974. void CodeEditorComponent::loadContent (const String& newContent)
  35975. {
  35976. clearCachedIterators (0);
  35977. document.replaceAllContent (newContent);
  35978. document.clearUndoHistory();
  35979. document.setSavePoint();
  35980. caretPos.setPosition (0);
  35981. selectionStart.setPosition (0);
  35982. selectionEnd.setPosition (0);
  35983. scrollToLine (0);
  35984. }
  35985. bool CodeEditorComponent::isTextInputActive() const
  35986. {
  35987. return true;
  35988. }
  35989. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  35990. const CodeDocument::Position& affectedTextEnd)
  35991. {
  35992. clearCachedIterators (affectedTextStart.getLineNumber());
  35993. triggerAsyncUpdate();
  35994. caret->updatePosition();
  35995. columnToTryToMaintain = -1;
  35996. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  35997. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  35998. deselectAll();
  35999. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  36000. || caretPos.getPosition() < affectedTextStart.getPosition())
  36001. moveCaretTo (affectedTextStart, false);
  36002. updateScrollBars();
  36003. }
  36004. void CodeEditorComponent::resized()
  36005. {
  36006. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  36007. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  36008. lines.clear();
  36009. rebuildLineTokens();
  36010. caret->updatePosition();
  36011. verticalScrollBar->setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  36012. horizontalScrollBar->setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  36013. updateScrollBars();
  36014. }
  36015. void CodeEditorComponent::paint (Graphics& g)
  36016. {
  36017. handleUpdateNowIfNeeded();
  36018. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  36019. g.reduceClipRegion (gutter, 0, verticalScrollBar->getX() - gutter, horizontalScrollBar->getY());
  36020. g.setFont (font);
  36021. const int baselineOffset = (int) font.getAscent();
  36022. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  36023. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  36024. const Rectangle<int> clip (g.getClipBounds());
  36025. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  36026. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  36027. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  36028. {
  36029. lines.getUnchecked(j)->draw (*this, g, font,
  36030. (float) (gutter - xOffset * charWidth),
  36031. lineHeight * j, baselineOffset, lineHeight,
  36032. highlightColour);
  36033. }
  36034. }
  36035. void CodeEditorComponent::setScrollbarThickness (const int thickness) throw()
  36036. {
  36037. if (scrollbarThickness != thickness)
  36038. {
  36039. scrollbarThickness = thickness;
  36040. resized();
  36041. }
  36042. }
  36043. void CodeEditorComponent::handleAsyncUpdate()
  36044. {
  36045. rebuildLineTokens();
  36046. }
  36047. void CodeEditorComponent::rebuildLineTokens()
  36048. {
  36049. cancelPendingUpdate();
  36050. const int numNeeded = linesOnScreen + 1;
  36051. int minLineToRepaint = numNeeded;
  36052. int maxLineToRepaint = 0;
  36053. if (numNeeded != lines.size())
  36054. {
  36055. lines.clear();
  36056. for (int i = numNeeded; --i >= 0;)
  36057. lines.add (new CodeEditorLine());
  36058. minLineToRepaint = 0;
  36059. maxLineToRepaint = numNeeded;
  36060. }
  36061. jassert (numNeeded == lines.size());
  36062. CodeDocument::Iterator source (&document);
  36063. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  36064. for (int i = 0; i < numNeeded; ++i)
  36065. {
  36066. CodeEditorLine* const line = lines.getUnchecked(i);
  36067. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  36068. selectionStart, selectionEnd))
  36069. {
  36070. minLineToRepaint = jmin (minLineToRepaint, i);
  36071. maxLineToRepaint = jmax (maxLineToRepaint, i);
  36072. }
  36073. }
  36074. if (minLineToRepaint <= maxLineToRepaint)
  36075. {
  36076. repaint (gutter, lineHeight * minLineToRepaint - 1,
  36077. verticalScrollBar->getX() - gutter,
  36078. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  36079. }
  36080. }
  36081. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  36082. {
  36083. caretPos = newPos;
  36084. columnToTryToMaintain = -1;
  36085. if (highlighting)
  36086. {
  36087. if (dragType == notDragging)
  36088. {
  36089. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  36090. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  36091. dragType = draggingSelectionStart;
  36092. else
  36093. dragType = draggingSelectionEnd;
  36094. }
  36095. if (dragType == draggingSelectionStart)
  36096. {
  36097. selectionStart = caretPos;
  36098. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36099. {
  36100. const CodeDocument::Position temp (selectionStart);
  36101. selectionStart = selectionEnd;
  36102. selectionEnd = temp;
  36103. dragType = draggingSelectionEnd;
  36104. }
  36105. }
  36106. else
  36107. {
  36108. selectionEnd = caretPos;
  36109. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36110. {
  36111. const CodeDocument::Position temp (selectionStart);
  36112. selectionStart = selectionEnd;
  36113. selectionEnd = temp;
  36114. dragType = draggingSelectionStart;
  36115. }
  36116. }
  36117. triggerAsyncUpdate();
  36118. }
  36119. else
  36120. {
  36121. deselectAll();
  36122. }
  36123. caret->updatePosition();
  36124. scrollToKeepCaretOnScreen();
  36125. updateScrollBars();
  36126. }
  36127. void CodeEditorComponent::deselectAll()
  36128. {
  36129. if (selectionStart != selectionEnd)
  36130. triggerAsyncUpdate();
  36131. selectionStart = caretPos;
  36132. selectionEnd = caretPos;
  36133. }
  36134. void CodeEditorComponent::updateScrollBars()
  36135. {
  36136. verticalScrollBar->setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  36137. verticalScrollBar->setCurrentRange (firstLineOnScreen, linesOnScreen);
  36138. horizontalScrollBar->setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  36139. horizontalScrollBar->setCurrentRange (xOffset, columnsOnScreen);
  36140. }
  36141. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  36142. {
  36143. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  36144. newFirstLineOnScreen);
  36145. if (newFirstLineOnScreen != firstLineOnScreen)
  36146. {
  36147. firstLineOnScreen = newFirstLineOnScreen;
  36148. caret->updatePosition();
  36149. updateCachedIterators (firstLineOnScreen);
  36150. triggerAsyncUpdate();
  36151. }
  36152. }
  36153. void CodeEditorComponent::scrollToColumnInternal (double column)
  36154. {
  36155. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  36156. if (xOffset != newOffset)
  36157. {
  36158. xOffset = newOffset;
  36159. caret->updatePosition();
  36160. repaint();
  36161. }
  36162. }
  36163. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  36164. {
  36165. scrollToLineInternal (newFirstLineOnScreen);
  36166. updateScrollBars();
  36167. }
  36168. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  36169. {
  36170. scrollToColumnInternal (newFirstColumnOnScreen);
  36171. updateScrollBars();
  36172. }
  36173. void CodeEditorComponent::scrollBy (int deltaLines)
  36174. {
  36175. scrollToLine (firstLineOnScreen + deltaLines);
  36176. }
  36177. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  36178. {
  36179. if (caretPos.getLineNumber() < firstLineOnScreen)
  36180. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  36181. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  36182. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  36183. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36184. if (column >= xOffset + columnsOnScreen - 1)
  36185. scrollToColumn (column + 1 - columnsOnScreen);
  36186. else if (column < xOffset)
  36187. scrollToColumn (column);
  36188. }
  36189. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const throw()
  36190. {
  36191. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  36192. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  36193. roundToInt (charWidth),
  36194. lineHeight);
  36195. }
  36196. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  36197. {
  36198. const int line = y / lineHeight + firstLineOnScreen;
  36199. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  36200. const int index = columnToIndex (line, column);
  36201. return CodeDocument::Position (&document, line, index);
  36202. }
  36203. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  36204. {
  36205. document.deleteSection (selectionStart, selectionEnd);
  36206. if (newText.isNotEmpty())
  36207. document.insertText (caretPos, newText);
  36208. scrollToKeepCaretOnScreen();
  36209. }
  36210. void CodeEditorComponent::insertTabAtCaret()
  36211. {
  36212. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  36213. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  36214. {
  36215. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  36216. }
  36217. if (useSpacesForTabs)
  36218. {
  36219. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36220. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  36221. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  36222. }
  36223. else
  36224. {
  36225. insertTextAtCaret ("\t");
  36226. }
  36227. }
  36228. void CodeEditorComponent::cut()
  36229. {
  36230. insertTextAtCaret (String::empty);
  36231. }
  36232. void CodeEditorComponent::copy()
  36233. {
  36234. newTransaction();
  36235. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  36236. if (selection.isNotEmpty())
  36237. SystemClipboard::copyTextToClipboard (selection);
  36238. }
  36239. void CodeEditorComponent::copyThenCut()
  36240. {
  36241. copy();
  36242. cut();
  36243. newTransaction();
  36244. }
  36245. void CodeEditorComponent::paste()
  36246. {
  36247. newTransaction();
  36248. const String clip (SystemClipboard::getTextFromClipboard());
  36249. if (clip.isNotEmpty())
  36250. insertTextAtCaret (clip);
  36251. newTransaction();
  36252. }
  36253. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  36254. {
  36255. newTransaction();
  36256. if (moveInWholeWordSteps)
  36257. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  36258. else
  36259. moveCaretTo (caretPos.movedBy (-1), selecting);
  36260. }
  36261. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  36262. {
  36263. newTransaction();
  36264. if (moveInWholeWordSteps)
  36265. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  36266. else
  36267. moveCaretTo (caretPos.movedBy (1), selecting);
  36268. }
  36269. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  36270. {
  36271. CodeDocument::Position pos (caretPos);
  36272. const int newLineNum = pos.getLineNumber() + delta;
  36273. if (columnToTryToMaintain < 0)
  36274. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  36275. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  36276. const int colToMaintain = columnToTryToMaintain;
  36277. moveCaretTo (pos, selecting);
  36278. columnToTryToMaintain = colToMaintain;
  36279. }
  36280. void CodeEditorComponent::cursorDown (const bool selecting)
  36281. {
  36282. newTransaction();
  36283. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  36284. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  36285. else
  36286. moveLineDelta (1, selecting);
  36287. }
  36288. void CodeEditorComponent::cursorUp (const bool selecting)
  36289. {
  36290. newTransaction();
  36291. if (caretPos.getLineNumber() == 0)
  36292. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  36293. else
  36294. moveLineDelta (-1, selecting);
  36295. }
  36296. void CodeEditorComponent::pageDown (const bool selecting)
  36297. {
  36298. newTransaction();
  36299. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  36300. moveLineDelta (linesOnScreen, selecting);
  36301. }
  36302. void CodeEditorComponent::pageUp (const bool selecting)
  36303. {
  36304. newTransaction();
  36305. scrollBy (-linesOnScreen);
  36306. moveLineDelta (-linesOnScreen, selecting);
  36307. }
  36308. void CodeEditorComponent::scrollUp()
  36309. {
  36310. newTransaction();
  36311. scrollBy (1);
  36312. if (caretPos.getLineNumber() < firstLineOnScreen)
  36313. moveLineDelta (1, false);
  36314. }
  36315. void CodeEditorComponent::scrollDown()
  36316. {
  36317. newTransaction();
  36318. scrollBy (-1);
  36319. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  36320. moveLineDelta (-1, false);
  36321. }
  36322. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  36323. {
  36324. newTransaction();
  36325. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  36326. }
  36327. static int findFirstNonWhitespaceChar (const String& line) throw()
  36328. {
  36329. const int len = line.length();
  36330. for (int i = 0; i < len; ++i)
  36331. if (! CharacterFunctions::isWhitespace (line [i]))
  36332. return i;
  36333. return 0;
  36334. }
  36335. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  36336. {
  36337. newTransaction();
  36338. int index = findFirstNonWhitespaceChar (caretPos.getLineText());
  36339. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  36340. index = 0;
  36341. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  36342. }
  36343. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  36344. {
  36345. newTransaction();
  36346. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  36347. }
  36348. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  36349. {
  36350. newTransaction();
  36351. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  36352. }
  36353. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  36354. {
  36355. if (moveInWholeWordSteps)
  36356. {
  36357. cut(); // in case something is already highlighted
  36358. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  36359. }
  36360. else
  36361. {
  36362. if (selectionStart == selectionEnd)
  36363. selectionStart.moveBy (-1);
  36364. }
  36365. cut();
  36366. }
  36367. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  36368. {
  36369. if (moveInWholeWordSteps)
  36370. {
  36371. cut(); // in case something is already highlighted
  36372. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  36373. }
  36374. else
  36375. {
  36376. if (selectionStart == selectionEnd)
  36377. selectionEnd.moveBy (1);
  36378. else
  36379. newTransaction();
  36380. }
  36381. cut();
  36382. }
  36383. void CodeEditorComponent::selectAll()
  36384. {
  36385. newTransaction();
  36386. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  36387. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  36388. }
  36389. void CodeEditorComponent::undo()
  36390. {
  36391. document.undo();
  36392. scrollToKeepCaretOnScreen();
  36393. }
  36394. void CodeEditorComponent::redo()
  36395. {
  36396. document.redo();
  36397. scrollToKeepCaretOnScreen();
  36398. }
  36399. void CodeEditorComponent::newTransaction()
  36400. {
  36401. document.newTransaction();
  36402. startTimer (600);
  36403. }
  36404. void CodeEditorComponent::timerCallback()
  36405. {
  36406. newTransaction();
  36407. }
  36408. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  36409. {
  36410. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  36411. }
  36412. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  36413. {
  36414. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  36415. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  36416. }
  36417. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  36418. {
  36419. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  36420. CodeDocument::Position (&document, range.getEnd()));
  36421. }
  36422. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  36423. {
  36424. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  36425. const bool shiftDown = key.getModifiers().isShiftDown();
  36426. if (key.isKeyCode (KeyPress::leftKey))
  36427. {
  36428. cursorLeft (moveInWholeWordSteps, shiftDown);
  36429. }
  36430. else if (key.isKeyCode (KeyPress::rightKey))
  36431. {
  36432. cursorRight (moveInWholeWordSteps, shiftDown);
  36433. }
  36434. else if (key.isKeyCode (KeyPress::upKey))
  36435. {
  36436. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  36437. scrollDown();
  36438. #if JUCE_MAC
  36439. else if (key.getModifiers().isCommandDown())
  36440. goToStartOfDocument (shiftDown);
  36441. #endif
  36442. else
  36443. cursorUp (shiftDown);
  36444. }
  36445. else if (key.isKeyCode (KeyPress::downKey))
  36446. {
  36447. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  36448. scrollUp();
  36449. #if JUCE_MAC
  36450. else if (key.getModifiers().isCommandDown())
  36451. goToEndOfDocument (shiftDown);
  36452. #endif
  36453. else
  36454. cursorDown (shiftDown);
  36455. }
  36456. else if (key.isKeyCode (KeyPress::pageDownKey))
  36457. {
  36458. pageDown (shiftDown);
  36459. }
  36460. else if (key.isKeyCode (KeyPress::pageUpKey))
  36461. {
  36462. pageUp (shiftDown);
  36463. }
  36464. else if (key.isKeyCode (KeyPress::homeKey))
  36465. {
  36466. if (moveInWholeWordSteps)
  36467. goToStartOfDocument (shiftDown);
  36468. else
  36469. goToStartOfLine (shiftDown);
  36470. }
  36471. else if (key.isKeyCode (KeyPress::endKey))
  36472. {
  36473. if (moveInWholeWordSteps)
  36474. goToEndOfDocument (shiftDown);
  36475. else
  36476. goToEndOfLine (shiftDown);
  36477. }
  36478. else if (key.isKeyCode (KeyPress::backspaceKey))
  36479. {
  36480. backspace (moveInWholeWordSteps);
  36481. }
  36482. else if (key.isKeyCode (KeyPress::deleteKey))
  36483. {
  36484. deleteForward (moveInWholeWordSteps);
  36485. }
  36486. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  36487. {
  36488. copy();
  36489. }
  36490. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  36491. {
  36492. copyThenCut();
  36493. }
  36494. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  36495. {
  36496. paste();
  36497. }
  36498. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  36499. {
  36500. undo();
  36501. }
  36502. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  36503. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  36504. {
  36505. redo();
  36506. }
  36507. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  36508. {
  36509. selectAll();
  36510. }
  36511. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  36512. {
  36513. insertTabAtCaret();
  36514. }
  36515. else if (key == KeyPress::returnKey)
  36516. {
  36517. newTransaction();
  36518. insertTextAtCaret (document.getNewLineCharacters());
  36519. }
  36520. else if (key.isKeyCode (KeyPress::escapeKey))
  36521. {
  36522. newTransaction();
  36523. }
  36524. else if (key.getTextCharacter() >= ' ')
  36525. {
  36526. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  36527. }
  36528. else
  36529. {
  36530. return false;
  36531. }
  36532. return true;
  36533. }
  36534. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  36535. {
  36536. newTransaction();
  36537. dragType = notDragging;
  36538. if (! e.mods.isPopupMenu())
  36539. {
  36540. beginDragAutoRepeat (100);
  36541. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  36542. }
  36543. else
  36544. {
  36545. /*PopupMenu m;
  36546. addPopupMenuItems (m, &e);
  36547. const int result = m.show();
  36548. if (result != 0)
  36549. performPopupMenuAction (result);
  36550. */
  36551. }
  36552. }
  36553. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  36554. {
  36555. if (! e.mods.isPopupMenu())
  36556. moveCaretTo (getPositionAt (e.x, e.y), true);
  36557. }
  36558. void CodeEditorComponent::mouseUp (const MouseEvent&)
  36559. {
  36560. newTransaction();
  36561. beginDragAutoRepeat (0);
  36562. dragType = notDragging;
  36563. }
  36564. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  36565. {
  36566. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  36567. CodeDocument::Position tokenEnd (tokenStart);
  36568. if (e.getNumberOfClicks() > 2)
  36569. {
  36570. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  36571. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  36572. }
  36573. else
  36574. {
  36575. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  36576. tokenEnd.moveBy (1);
  36577. tokenStart = tokenEnd;
  36578. while (tokenStart.getIndexInLine() > 0
  36579. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  36580. tokenStart.moveBy (-1);
  36581. }
  36582. moveCaretTo (tokenEnd, false);
  36583. moveCaretTo (tokenStart, true);
  36584. }
  36585. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  36586. {
  36587. if ((verticalScrollBar->isVisible() && wheelIncrementY != 0)
  36588. || (horizontalScrollBar->isVisible() && wheelIncrementX != 0))
  36589. {
  36590. verticalScrollBar->mouseWheelMove (e, 0, wheelIncrementY);
  36591. horizontalScrollBar->mouseWheelMove (e, wheelIncrementX, 0);
  36592. }
  36593. else
  36594. {
  36595. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  36596. }
  36597. }
  36598. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  36599. {
  36600. if (scrollBarThatHasMoved == verticalScrollBar)
  36601. scrollToLineInternal ((int) newRangeStart);
  36602. else
  36603. scrollToColumnInternal (newRangeStart);
  36604. }
  36605. void CodeEditorComponent::focusGained (FocusChangeType)
  36606. {
  36607. caret->updatePosition();
  36608. }
  36609. void CodeEditorComponent::focusLost (FocusChangeType)
  36610. {
  36611. caret->updatePosition();
  36612. }
  36613. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces) throw()
  36614. {
  36615. useSpacesForTabs = insertSpaces;
  36616. if (spacesPerTab != numSpaces)
  36617. {
  36618. spacesPerTab = numSpaces;
  36619. triggerAsyncUpdate();
  36620. }
  36621. }
  36622. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  36623. {
  36624. const String line (document.getLine (lineNum));
  36625. jassert (index <= line.length());
  36626. int col = 0;
  36627. for (int i = 0; i < index; ++i)
  36628. {
  36629. if (line[i] != '\t')
  36630. ++col;
  36631. else
  36632. col += getTabSize() - (col % getTabSize());
  36633. }
  36634. return col;
  36635. }
  36636. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  36637. {
  36638. const String line (document.getLine (lineNum));
  36639. const int lineLength = line.length();
  36640. int i, col = 0;
  36641. for (i = 0; i < lineLength; ++i)
  36642. {
  36643. if (line[i] != '\t')
  36644. ++col;
  36645. else
  36646. col += getTabSize() - (col % getTabSize());
  36647. if (col > column)
  36648. break;
  36649. }
  36650. return i;
  36651. }
  36652. void CodeEditorComponent::setFont (const Font& newFont)
  36653. {
  36654. font = newFont;
  36655. charWidth = font.getStringWidthFloat ("0");
  36656. lineHeight = roundToInt (font.getHeight());
  36657. resized();
  36658. }
  36659. void CodeEditorComponent::resetToDefaultColours()
  36660. {
  36661. coloursForTokenCategories.clear();
  36662. if (codeTokeniser != 0)
  36663. {
  36664. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  36665. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  36666. }
  36667. }
  36668. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  36669. {
  36670. jassert (tokenType < 256);
  36671. while (coloursForTokenCategories.size() < tokenType)
  36672. coloursForTokenCategories.add (Colours::black);
  36673. coloursForTokenCategories.set (tokenType, colour);
  36674. repaint();
  36675. }
  36676. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const throw()
  36677. {
  36678. if (((unsigned int) tokenType) >= (unsigned int) coloursForTokenCategories.size())
  36679. return findColour (CodeEditorComponent::defaultTextColourId);
  36680. return coloursForTokenCategories.getReference (tokenType);
  36681. }
  36682. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid) throw()
  36683. {
  36684. int i;
  36685. for (i = cachedIterators.size(); --i >= 0;)
  36686. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  36687. break;
  36688. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  36689. }
  36690. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  36691. {
  36692. const int maxNumCachedPositions = 5000;
  36693. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  36694. if (cachedIterators.size() == 0)
  36695. cachedIterators.add (new CodeDocument::Iterator (&document));
  36696. if (codeTokeniser == 0)
  36697. return;
  36698. for (;;)
  36699. {
  36700. CodeDocument::Iterator* last = cachedIterators.getLast();
  36701. if (last->getLine() >= maxLineNum)
  36702. break;
  36703. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  36704. cachedIterators.add (t);
  36705. const int targetLine = last->getLine() + linesBetweenCachedSources;
  36706. for (;;)
  36707. {
  36708. codeTokeniser->readNextToken (*t);
  36709. if (t->getLine() >= targetLine)
  36710. break;
  36711. if (t->isEOF())
  36712. return;
  36713. }
  36714. }
  36715. }
  36716. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  36717. {
  36718. if (codeTokeniser == 0)
  36719. return;
  36720. for (int i = cachedIterators.size(); --i >= 0;)
  36721. {
  36722. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  36723. if (t->getPosition() <= position)
  36724. {
  36725. source = *t;
  36726. break;
  36727. }
  36728. }
  36729. while (source.getPosition() < position)
  36730. {
  36731. const CodeDocument::Iterator original (source);
  36732. codeTokeniser->readNextToken (source);
  36733. if (source.getPosition() > position || source.isEOF())
  36734. {
  36735. source = original;
  36736. break;
  36737. }
  36738. }
  36739. }
  36740. END_JUCE_NAMESPACE
  36741. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  36742. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  36743. BEGIN_JUCE_NAMESPACE
  36744. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  36745. {
  36746. }
  36747. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  36748. {
  36749. }
  36750. namespace CppTokeniser
  36751. {
  36752. static bool isIdentifierStart (const juce_wchar c) throw()
  36753. {
  36754. return CharacterFunctions::isLetter (c)
  36755. || c == '_' || c == '@';
  36756. }
  36757. static bool isIdentifierBody (const juce_wchar c) throw()
  36758. {
  36759. return CharacterFunctions::isLetterOrDigit (c)
  36760. || c == '_' || c == '@';
  36761. }
  36762. static bool isReservedKeyword (const juce_wchar* const token, const int tokenLength) throw()
  36763. {
  36764. static const juce_wchar* const keywords2Char[] =
  36765. { T("if"), T("do"), T("or"), T("id"), 0 };
  36766. static const juce_wchar* const keywords3Char[] =
  36767. { T("for"), T("int"), T("new"), T("try"), T("xor"), T("and"), T("asm"), T("not"), 0 };
  36768. static const juce_wchar* const keywords4Char[] =
  36769. { T("bool"), T("void"), T("this"), T("true"), T("long"), T("else"), T("char"),
  36770. T("enum"), T("case"), T("goto"), T("auto"), 0 };
  36771. static const juce_wchar* const keywords5Char[] =
  36772. { T("while"), T("bitor"), T("break"), T("catch"), T("class"), T("compl"), T("const"), T("false"),
  36773. T("float"), T("short"), T("throw"), T("union"), T("using"), T("or_eq"), 0 };
  36774. static const juce_wchar* const keywords6Char[] =
  36775. { T("return"), T("struct"), T("and_eq"), T("bitand"), T("delete"), T("double"), T("extern"),
  36776. T("friend"), T("inline"), T("not_eq"), T("public"), T("sizeof"), T("static"), T("signed"),
  36777. T("switch"), T("typeid"), T("wchar_t"), T("xor_eq"), 0};
  36778. static const juce_wchar* const keywordsOther[] =
  36779. { T("const_cast"), T("continue"), T("default"), T("explicit"), T("mutable"), T("namespace"),
  36780. T("operator"), T("private"), T("protected"), T("register"), T("reinterpret_cast"), T("static_cast"),
  36781. T("template"), T("typedef"), T("typename"), T("unsigned"), T("virtual"), T("volatile"),
  36782. T("@implementation"), T("@interface"), T("@end"), T("@synthesize"), T("@dynamic"), T("@public"),
  36783. T("@private"), T("@property"), T("@protected"), T("@class"), 0 };
  36784. const juce_wchar* const* k;
  36785. switch (tokenLength)
  36786. {
  36787. case 2: k = keywords2Char; break;
  36788. case 3: k = keywords3Char; break;
  36789. case 4: k = keywords4Char; break;
  36790. case 5: k = keywords5Char; break;
  36791. case 6: k = keywords6Char; break;
  36792. default:
  36793. if (tokenLength < 2 || tokenLength > 16)
  36794. return false;
  36795. k = keywordsOther;
  36796. break;
  36797. }
  36798. int i = 0;
  36799. while (k[i] != 0)
  36800. {
  36801. if (k[i][0] == token[0] && CharacterFunctions::compare (k[i], token) == 0)
  36802. return true;
  36803. ++i;
  36804. }
  36805. return false;
  36806. }
  36807. static int parseIdentifier (CodeDocument::Iterator& source) throw()
  36808. {
  36809. int tokenLength = 0;
  36810. juce_wchar possibleIdentifier [19];
  36811. while (isIdentifierBody (source.peekNextChar()))
  36812. {
  36813. const juce_wchar c = source.nextChar();
  36814. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  36815. possibleIdentifier [tokenLength] = c;
  36816. ++tokenLength;
  36817. }
  36818. if (tokenLength > 1 && tokenLength <= 16)
  36819. {
  36820. possibleIdentifier [tokenLength] = 0;
  36821. if (isReservedKeyword (possibleIdentifier, tokenLength))
  36822. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  36823. }
  36824. return CPlusPlusCodeTokeniser::tokenType_identifier;
  36825. }
  36826. static bool skipNumberSuffix (CodeDocument::Iterator& source)
  36827. {
  36828. const juce_wchar c = source.peekNextChar();
  36829. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  36830. source.skip();
  36831. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  36832. return false;
  36833. return true;
  36834. }
  36835. static bool isHexDigit (const juce_wchar c) throw()
  36836. {
  36837. return (c >= '0' && c <= '9')
  36838. || (c >= 'a' && c <= 'f')
  36839. || (c >= 'A' && c <= 'F');
  36840. }
  36841. static bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  36842. {
  36843. if (source.nextChar() != '0')
  36844. return false;
  36845. juce_wchar c = source.nextChar();
  36846. if (c != 'x' && c != 'X')
  36847. return false;
  36848. int numDigits = 0;
  36849. while (isHexDigit (source.peekNextChar()))
  36850. {
  36851. ++numDigits;
  36852. source.skip();
  36853. }
  36854. if (numDigits == 0)
  36855. return false;
  36856. return skipNumberSuffix (source);
  36857. }
  36858. static bool isOctalDigit (const juce_wchar c) throw()
  36859. {
  36860. return c >= '0' && c <= '7';
  36861. }
  36862. static bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  36863. {
  36864. if (source.nextChar() != '0')
  36865. return false;
  36866. if (! isOctalDigit (source.nextChar()))
  36867. return false;
  36868. while (isOctalDigit (source.peekNextChar()))
  36869. source.skip();
  36870. return skipNumberSuffix (source);
  36871. }
  36872. static bool isDecimalDigit (const juce_wchar c) throw()
  36873. {
  36874. return c >= '0' && c <= '9';
  36875. }
  36876. static bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  36877. {
  36878. int numChars = 0;
  36879. while (isDecimalDigit (source.peekNextChar()))
  36880. {
  36881. ++numChars;
  36882. source.skip();
  36883. }
  36884. if (numChars == 0)
  36885. return false;
  36886. return skipNumberSuffix (source);
  36887. }
  36888. static bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  36889. {
  36890. int numDigits = 0;
  36891. while (isDecimalDigit (source.peekNextChar()))
  36892. {
  36893. source.skip();
  36894. ++numDigits;
  36895. }
  36896. const bool hasPoint = (source.peekNextChar() == '.');
  36897. if (hasPoint)
  36898. {
  36899. source.skip();
  36900. while (isDecimalDigit (source.peekNextChar()))
  36901. {
  36902. source.skip();
  36903. ++numDigits;
  36904. }
  36905. }
  36906. if (numDigits == 0)
  36907. return false;
  36908. juce_wchar c = source.peekNextChar();
  36909. const bool hasExponent = (c == 'e' || c == 'E');
  36910. if (hasExponent)
  36911. {
  36912. source.skip();
  36913. c = source.peekNextChar();
  36914. if (c == '+' || c == '-')
  36915. source.skip();
  36916. int numExpDigits = 0;
  36917. while (isDecimalDigit (source.peekNextChar()))
  36918. {
  36919. source.skip();
  36920. ++numExpDigits;
  36921. }
  36922. if (numExpDigits == 0)
  36923. return false;
  36924. }
  36925. c = source.peekNextChar();
  36926. if (c == 'f' || c == 'F')
  36927. source.skip();
  36928. else if (! (hasExponent || hasPoint))
  36929. return false;
  36930. return true;
  36931. }
  36932. static int parseNumber (CodeDocument::Iterator& source)
  36933. {
  36934. const CodeDocument::Iterator original (source);
  36935. if (parseFloatLiteral (source))
  36936. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  36937. source = original;
  36938. if (parseHexLiteral (source))
  36939. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  36940. source = original;
  36941. if (parseOctalLiteral (source))
  36942. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  36943. source = original;
  36944. if (parseDecimalLiteral (source))
  36945. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  36946. source = original;
  36947. source.skip();
  36948. return CPlusPlusCodeTokeniser::tokenType_error;
  36949. }
  36950. static void skipQuotedString (CodeDocument::Iterator& source) throw()
  36951. {
  36952. const juce_wchar quote = source.nextChar();
  36953. for (;;)
  36954. {
  36955. const juce_wchar c = source.nextChar();
  36956. if (c == quote || c == 0)
  36957. break;
  36958. if (c == '\\')
  36959. source.skip();
  36960. }
  36961. }
  36962. static void skipComment (CodeDocument::Iterator& source) throw()
  36963. {
  36964. bool lastWasStar = false;
  36965. for (;;)
  36966. {
  36967. const juce_wchar c = source.nextChar();
  36968. if (c == 0 || (c == '/' && lastWasStar))
  36969. break;
  36970. lastWasStar = (c == '*');
  36971. }
  36972. }
  36973. }
  36974. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  36975. {
  36976. int result = tokenType_error;
  36977. source.skipWhitespace();
  36978. juce_wchar firstChar = source.peekNextChar();
  36979. switch (firstChar)
  36980. {
  36981. case 0:
  36982. source.skip();
  36983. break;
  36984. case '0':
  36985. case '1':
  36986. case '2':
  36987. case '3':
  36988. case '4':
  36989. case '5':
  36990. case '6':
  36991. case '7':
  36992. case '8':
  36993. case '9':
  36994. result = CppTokeniser::parseNumber (source);
  36995. break;
  36996. case '.':
  36997. result = CppTokeniser::parseNumber (source);
  36998. if (result == tokenType_error)
  36999. result = tokenType_punctuation;
  37000. break;
  37001. case ',':
  37002. case ';':
  37003. case ':':
  37004. source.skip();
  37005. result = tokenType_punctuation;
  37006. break;
  37007. case '(':
  37008. case ')':
  37009. case '{':
  37010. case '}':
  37011. case '[':
  37012. case ']':
  37013. source.skip();
  37014. result = tokenType_bracket;
  37015. break;
  37016. case '"':
  37017. case '\'':
  37018. CppTokeniser::skipQuotedString (source);
  37019. result = tokenType_stringLiteral;
  37020. break;
  37021. case '+':
  37022. result = tokenType_operator;
  37023. source.skip();
  37024. if (source.peekNextChar() == '+')
  37025. source.skip();
  37026. else if (source.peekNextChar() == '=')
  37027. source.skip();
  37028. break;
  37029. case '-':
  37030. source.skip();
  37031. result = CppTokeniser::parseNumber (source);
  37032. if (result == tokenType_error)
  37033. {
  37034. result = tokenType_operator;
  37035. if (source.peekNextChar() == '-')
  37036. source.skip();
  37037. else if (source.peekNextChar() == '=')
  37038. source.skip();
  37039. }
  37040. break;
  37041. case '*':
  37042. case '%':
  37043. case '=':
  37044. case '!':
  37045. result = tokenType_operator;
  37046. source.skip();
  37047. if (source.peekNextChar() == '=')
  37048. source.skip();
  37049. break;
  37050. case '/':
  37051. result = tokenType_operator;
  37052. source.skip();
  37053. if (source.peekNextChar() == '=')
  37054. {
  37055. source.skip();
  37056. }
  37057. else if (source.peekNextChar() == '/')
  37058. {
  37059. result = tokenType_comment;
  37060. source.skipToEndOfLine();
  37061. }
  37062. else if (source.peekNextChar() == '*')
  37063. {
  37064. source.skip();
  37065. result = tokenType_comment;
  37066. CppTokeniser::skipComment (source);
  37067. }
  37068. break;
  37069. case '?':
  37070. case '~':
  37071. source.skip();
  37072. result = tokenType_operator;
  37073. break;
  37074. case '<':
  37075. source.skip();
  37076. result = tokenType_operator;
  37077. if (source.peekNextChar() == '=')
  37078. {
  37079. source.skip();
  37080. }
  37081. else if (source.peekNextChar() == '<')
  37082. {
  37083. source.skip();
  37084. if (source.peekNextChar() == '=')
  37085. source.skip();
  37086. }
  37087. break;
  37088. case '>':
  37089. source.skip();
  37090. result = tokenType_operator;
  37091. if (source.peekNextChar() == '=')
  37092. {
  37093. source.skip();
  37094. }
  37095. else if (source.peekNextChar() == '<')
  37096. {
  37097. source.skip();
  37098. if (source.peekNextChar() == '=')
  37099. source.skip();
  37100. }
  37101. break;
  37102. case '|':
  37103. source.skip();
  37104. result = tokenType_operator;
  37105. if (source.peekNextChar() == '=')
  37106. {
  37107. source.skip();
  37108. }
  37109. else if (source.peekNextChar() == '|')
  37110. {
  37111. source.skip();
  37112. if (source.peekNextChar() == '=')
  37113. source.skip();
  37114. }
  37115. break;
  37116. case '&':
  37117. source.skip();
  37118. result = tokenType_operator;
  37119. if (source.peekNextChar() == '=')
  37120. {
  37121. source.skip();
  37122. }
  37123. else if (source.peekNextChar() == '&')
  37124. {
  37125. source.skip();
  37126. if (source.peekNextChar() == '=')
  37127. source.skip();
  37128. }
  37129. break;
  37130. case '^':
  37131. source.skip();
  37132. result = tokenType_operator;
  37133. if (source.peekNextChar() == '=')
  37134. {
  37135. source.skip();
  37136. }
  37137. else if (source.peekNextChar() == '^')
  37138. {
  37139. source.skip();
  37140. if (source.peekNextChar() == '=')
  37141. source.skip();
  37142. }
  37143. break;
  37144. case '#':
  37145. result = tokenType_preprocessor;
  37146. source.skipToEndOfLine();
  37147. break;
  37148. default:
  37149. if (CppTokeniser::isIdentifierStart (firstChar))
  37150. result = CppTokeniser::parseIdentifier (source);
  37151. else
  37152. source.skip();
  37153. break;
  37154. }
  37155. return result;
  37156. }
  37157. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  37158. {
  37159. const char* const types[] =
  37160. {
  37161. "Error",
  37162. "Comment",
  37163. "C++ keyword",
  37164. "Identifier",
  37165. "Integer literal",
  37166. "Float literal",
  37167. "String literal",
  37168. "Operator",
  37169. "Bracket",
  37170. "Punctuation",
  37171. "Preprocessor line",
  37172. 0
  37173. };
  37174. return StringArray (types);
  37175. }
  37176. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  37177. {
  37178. const uint32 colours[] =
  37179. {
  37180. 0xffcc0000, // error
  37181. 0xff00aa00, // comment
  37182. 0xff0000cc, // keyword
  37183. 0xff000000, // identifier
  37184. 0xff880000, // int literal
  37185. 0xff885500, // float literal
  37186. 0xff990099, // string literal
  37187. 0xff225500, // operator
  37188. 0xff000055, // bracket
  37189. 0xff004400, // punctuation
  37190. 0xff660000 // preprocessor
  37191. };
  37192. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  37193. return Colour (colours [tokenType]);
  37194. return Colours::black;
  37195. }
  37196. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  37197. {
  37198. return CppTokeniser::isReservedKeyword (token, token.length());
  37199. }
  37200. END_JUCE_NAMESPACE
  37201. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37202. /*** Start of inlined file: juce_ComboBox.cpp ***/
  37203. BEGIN_JUCE_NAMESPACE
  37204. ComboBox::ComboBox (const String& name)
  37205. : Component (name),
  37206. lastCurrentId (0),
  37207. isButtonDown (false),
  37208. separatorPending (false),
  37209. menuActive (false),
  37210. label (0)
  37211. {
  37212. noChoicesMessage = TRANS("(no choices)");
  37213. setRepaintsOnMouseActivity (true);
  37214. lookAndFeelChanged();
  37215. currentId.addListener (this);
  37216. }
  37217. ComboBox::~ComboBox()
  37218. {
  37219. currentId.removeListener (this);
  37220. if (menuActive)
  37221. PopupMenu::dismissAllActiveMenus();
  37222. label = 0;
  37223. deleteAllChildren();
  37224. }
  37225. void ComboBox::setEditableText (const bool isEditable)
  37226. {
  37227. label->setEditable (isEditable, isEditable, false);
  37228. setWantsKeyboardFocus (! isEditable);
  37229. resized();
  37230. }
  37231. bool ComboBox::isTextEditable() const throw()
  37232. {
  37233. return label->isEditable();
  37234. }
  37235. void ComboBox::setJustificationType (const Justification& justification) throw()
  37236. {
  37237. label->setJustificationType (justification);
  37238. }
  37239. const Justification ComboBox::getJustificationType() const throw()
  37240. {
  37241. return label->getJustificationType();
  37242. }
  37243. void ComboBox::setTooltip (const String& newTooltip)
  37244. {
  37245. SettableTooltipClient::setTooltip (newTooltip);
  37246. label->setTooltip (newTooltip);
  37247. }
  37248. void ComboBox::addItem (const String& newItemText,
  37249. const int newItemId) throw()
  37250. {
  37251. // you can't add empty strings to the list..
  37252. jassert (newItemText.isNotEmpty());
  37253. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  37254. jassert (newItemId != 0);
  37255. // you shouldn't use duplicate item IDs!
  37256. jassert (getItemForId (newItemId) == 0);
  37257. if (newItemText.isNotEmpty() && newItemId != 0)
  37258. {
  37259. if (separatorPending)
  37260. {
  37261. separatorPending = false;
  37262. ItemInfo* const item = new ItemInfo();
  37263. item->itemId = 0;
  37264. item->isEnabled = false;
  37265. item->isHeading = false;
  37266. items.add (item);
  37267. }
  37268. ItemInfo* const item = new ItemInfo();
  37269. item->name = newItemText;
  37270. item->itemId = newItemId;
  37271. item->isEnabled = true;
  37272. item->isHeading = false;
  37273. items.add (item);
  37274. }
  37275. }
  37276. void ComboBox::addSeparator() throw()
  37277. {
  37278. separatorPending = (items.size() > 0);
  37279. }
  37280. void ComboBox::addSectionHeading (const String& headingName) throw()
  37281. {
  37282. // you can't add empty strings to the list..
  37283. jassert (headingName.isNotEmpty());
  37284. if (headingName.isNotEmpty())
  37285. {
  37286. if (separatorPending)
  37287. {
  37288. separatorPending = false;
  37289. ItemInfo* const item = new ItemInfo();
  37290. item->itemId = 0;
  37291. item->isEnabled = false;
  37292. item->isHeading = false;
  37293. items.add (item);
  37294. }
  37295. ItemInfo* const item = new ItemInfo();
  37296. item->name = headingName;
  37297. item->itemId = 0;
  37298. item->isEnabled = true;
  37299. item->isHeading = true;
  37300. items.add (item);
  37301. }
  37302. }
  37303. void ComboBox::setItemEnabled (const int itemId,
  37304. const bool shouldBeEnabled) throw()
  37305. {
  37306. ItemInfo* const item = getItemForId (itemId);
  37307. if (item != 0)
  37308. item->isEnabled = shouldBeEnabled;
  37309. }
  37310. void ComboBox::changeItemText (const int itemId,
  37311. const String& newText) throw()
  37312. {
  37313. ItemInfo* const item = getItemForId (itemId);
  37314. jassert (item != 0);
  37315. if (item != 0)
  37316. item->name = newText;
  37317. }
  37318. void ComboBox::clear (const bool dontSendChangeMessage)
  37319. {
  37320. items.clear();
  37321. separatorPending = false;
  37322. if (! label->isEditable())
  37323. setSelectedItemIndex (-1, dontSendChangeMessage);
  37324. }
  37325. bool ComboBox::ItemInfo::isSeparator() const throw()
  37326. {
  37327. return name.isEmpty();
  37328. }
  37329. bool ComboBox::ItemInfo::isRealItem() const throw()
  37330. {
  37331. return ! (isHeading || name.isEmpty());
  37332. }
  37333. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  37334. {
  37335. if (itemId != 0)
  37336. {
  37337. for (int i = items.size(); --i >= 0;)
  37338. if (items.getUnchecked(i)->itemId == itemId)
  37339. return items.getUnchecked(i);
  37340. }
  37341. return 0;
  37342. }
  37343. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  37344. {
  37345. int n = 0;
  37346. for (int i = 0; i < items.size(); ++i)
  37347. {
  37348. ItemInfo* const item = items.getUnchecked(i);
  37349. if (item->isRealItem())
  37350. if (n++ == index)
  37351. return item;
  37352. }
  37353. return 0;
  37354. }
  37355. int ComboBox::getNumItems() const throw()
  37356. {
  37357. int n = 0;
  37358. for (int i = items.size(); --i >= 0;)
  37359. if (items.getUnchecked(i)->isRealItem())
  37360. ++n;
  37361. return n;
  37362. }
  37363. const String ComboBox::getItemText (const int index) const throw()
  37364. {
  37365. const ItemInfo* const item = getItemForIndex (index);
  37366. if (item != 0)
  37367. return item->name;
  37368. return String::empty;
  37369. }
  37370. int ComboBox::getItemId (const int index) const throw()
  37371. {
  37372. const ItemInfo* const item = getItemForIndex (index);
  37373. return (item != 0) ? item->itemId : 0;
  37374. }
  37375. int ComboBox::indexOfItemId (const int itemId) const throw()
  37376. {
  37377. int n = 0;
  37378. for (int i = 0; i < items.size(); ++i)
  37379. {
  37380. const ItemInfo* const item = items.getUnchecked(i);
  37381. if (item->isRealItem())
  37382. {
  37383. if (item->itemId == itemId)
  37384. return n;
  37385. ++n;
  37386. }
  37387. }
  37388. return -1;
  37389. }
  37390. int ComboBox::getSelectedItemIndex() const throw()
  37391. {
  37392. int index = indexOfItemId (currentId.getValue());
  37393. if (getText() != getItemText (index))
  37394. index = -1;
  37395. return index;
  37396. }
  37397. void ComboBox::setSelectedItemIndex (const int index,
  37398. const bool dontSendChangeMessage) throw()
  37399. {
  37400. setSelectedId (getItemId (index), dontSendChangeMessage);
  37401. }
  37402. int ComboBox::getSelectedId() const throw()
  37403. {
  37404. const ItemInfo* const item = getItemForId (currentId.getValue());
  37405. return (item != 0 && getText() == item->name)
  37406. ? item->itemId
  37407. : 0;
  37408. }
  37409. void ComboBox::setSelectedId (const int newItemId,
  37410. const bool dontSendChangeMessage) throw()
  37411. {
  37412. const ItemInfo* const item = getItemForId (newItemId);
  37413. const String newItemText (item != 0 ? item->name : String::empty);
  37414. if (lastCurrentId != newItemId || label->getText() != newItemText)
  37415. {
  37416. if (! dontSendChangeMessage)
  37417. triggerAsyncUpdate();
  37418. label->setText (newItemText, false);
  37419. lastCurrentId = newItemId;
  37420. currentId = newItemId;
  37421. repaint(); // for the benefit of the 'none selected' text
  37422. }
  37423. }
  37424. void ComboBox::valueChanged (Value&)
  37425. {
  37426. if (lastCurrentId != (int) currentId.getValue())
  37427. setSelectedId (currentId.getValue(), false);
  37428. }
  37429. const String ComboBox::getText() const throw()
  37430. {
  37431. return label->getText();
  37432. }
  37433. void ComboBox::setText (const String& newText,
  37434. const bool dontSendChangeMessage) throw()
  37435. {
  37436. for (int i = items.size(); --i >= 0;)
  37437. {
  37438. const ItemInfo* const item = items.getUnchecked(i);
  37439. if (item->isRealItem()
  37440. && item->name == newText)
  37441. {
  37442. setSelectedId (item->itemId, dontSendChangeMessage);
  37443. return;
  37444. }
  37445. }
  37446. lastCurrentId = 0;
  37447. currentId = 0;
  37448. if (label->getText() != newText)
  37449. {
  37450. label->setText (newText, false);
  37451. if (! dontSendChangeMessage)
  37452. triggerAsyncUpdate();
  37453. }
  37454. repaint();
  37455. }
  37456. void ComboBox::showEditor()
  37457. {
  37458. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  37459. label->showEditor();
  37460. }
  37461. void ComboBox::setTextWhenNothingSelected (const String& newMessage) throw()
  37462. {
  37463. textWhenNothingSelected = newMessage;
  37464. repaint();
  37465. }
  37466. const String ComboBox::getTextWhenNothingSelected() const throw()
  37467. {
  37468. return textWhenNothingSelected;
  37469. }
  37470. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage) throw()
  37471. {
  37472. noChoicesMessage = newMessage;
  37473. }
  37474. const String ComboBox::getTextWhenNoChoicesAvailable() const throw()
  37475. {
  37476. return noChoicesMessage;
  37477. }
  37478. void ComboBox::paint (Graphics& g)
  37479. {
  37480. getLookAndFeel().drawComboBox (g,
  37481. getWidth(),
  37482. getHeight(),
  37483. isButtonDown,
  37484. label->getRight(),
  37485. 0,
  37486. getWidth() - label->getRight(),
  37487. getHeight(),
  37488. *this);
  37489. if (textWhenNothingSelected.isNotEmpty()
  37490. && label->getText().isEmpty()
  37491. && ! label->isBeingEdited())
  37492. {
  37493. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  37494. g.setFont (label->getFont());
  37495. g.drawFittedText (textWhenNothingSelected,
  37496. label->getX() + 2, label->getY() + 1,
  37497. label->getWidth() - 4, label->getHeight() - 2,
  37498. label->getJustificationType(),
  37499. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  37500. }
  37501. }
  37502. void ComboBox::resized()
  37503. {
  37504. if (getHeight() > 0 && getWidth() > 0)
  37505. getLookAndFeel().positionComboBoxText (*this, *label);
  37506. }
  37507. void ComboBox::enablementChanged()
  37508. {
  37509. repaint();
  37510. }
  37511. void ComboBox::lookAndFeelChanged()
  37512. {
  37513. repaint();
  37514. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  37515. if (label != 0)
  37516. {
  37517. newLabel->setEditable (label->isEditable());
  37518. newLabel->setJustificationType (label->getJustificationType());
  37519. newLabel->setTooltip (label->getTooltip());
  37520. newLabel->setText (label->getText(), false);
  37521. }
  37522. label = newLabel;
  37523. addAndMakeVisible (newLabel);
  37524. newLabel->addListener (this);
  37525. newLabel->addMouseListener (this, false);
  37526. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  37527. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  37528. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  37529. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  37530. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  37531. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  37532. resized();
  37533. }
  37534. void ComboBox::colourChanged()
  37535. {
  37536. lookAndFeelChanged();
  37537. }
  37538. bool ComboBox::keyPressed (const KeyPress& key)
  37539. {
  37540. bool used = false;
  37541. if (key.isKeyCode (KeyPress::upKey)
  37542. || key.isKeyCode (KeyPress::leftKey))
  37543. {
  37544. setSelectedItemIndex (jmax (0, getSelectedItemIndex() - 1));
  37545. used = true;
  37546. }
  37547. else if (key.isKeyCode (KeyPress::downKey)
  37548. || key.isKeyCode (KeyPress::rightKey))
  37549. {
  37550. setSelectedItemIndex (jmin (getSelectedItemIndex() + 1, getNumItems() - 1));
  37551. used = true;
  37552. }
  37553. else if (key.isKeyCode (KeyPress::returnKey))
  37554. {
  37555. showPopup();
  37556. used = true;
  37557. }
  37558. return used;
  37559. }
  37560. bool ComboBox::keyStateChanged (const bool isKeyDown)
  37561. {
  37562. // only forward key events that aren't used by this component
  37563. return isKeyDown
  37564. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  37565. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  37566. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  37567. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  37568. }
  37569. void ComboBox::focusGained (FocusChangeType)
  37570. {
  37571. repaint();
  37572. }
  37573. void ComboBox::focusLost (FocusChangeType)
  37574. {
  37575. repaint();
  37576. }
  37577. void ComboBox::labelTextChanged (Label*)
  37578. {
  37579. triggerAsyncUpdate();
  37580. }
  37581. void ComboBox::showPopup()
  37582. {
  37583. if (! menuActive)
  37584. {
  37585. const int selectedId = getSelectedId();
  37586. Component::SafePointer<Component> deletionWatcher (this);
  37587. PopupMenu menu;
  37588. menu.setLookAndFeel (&getLookAndFeel());
  37589. for (int i = 0; i < items.size(); ++i)
  37590. {
  37591. const ItemInfo* const item = items.getUnchecked(i);
  37592. if (item->isSeparator())
  37593. menu.addSeparator();
  37594. else if (item->isHeading)
  37595. menu.addSectionHeader (item->name);
  37596. else
  37597. menu.addItem (item->itemId, item->name,
  37598. item->isEnabled, item->itemId == selectedId);
  37599. }
  37600. if (items.size() == 0)
  37601. menu.addItem (1, noChoicesMessage, false);
  37602. const int itemHeight = jlimit (12, 24, getHeight());
  37603. menuActive = true;
  37604. const int resultId = menu.showAt (this, selectedId,
  37605. getWidth(), 1, itemHeight);
  37606. if (deletionWatcher == 0)
  37607. return;
  37608. menuActive = false;
  37609. if (resultId != 0)
  37610. setSelectedId (resultId);
  37611. }
  37612. }
  37613. void ComboBox::mouseDown (const MouseEvent& e)
  37614. {
  37615. beginDragAutoRepeat (300);
  37616. isButtonDown = isEnabled();
  37617. if (isButtonDown
  37618. && (e.eventComponent == this || ! label->isEditable()))
  37619. {
  37620. showPopup();
  37621. }
  37622. }
  37623. void ComboBox::mouseDrag (const MouseEvent& e)
  37624. {
  37625. beginDragAutoRepeat (50);
  37626. if (isButtonDown && ! e.mouseWasClicked())
  37627. showPopup();
  37628. }
  37629. void ComboBox::mouseUp (const MouseEvent& e2)
  37630. {
  37631. if (isButtonDown)
  37632. {
  37633. isButtonDown = false;
  37634. repaint();
  37635. const MouseEvent e (e2.getEventRelativeTo (this));
  37636. if (reallyContains (e.x, e.y, true)
  37637. && (e2.eventComponent == this || ! label->isEditable()))
  37638. {
  37639. showPopup();
  37640. }
  37641. }
  37642. }
  37643. void ComboBox::addListener (ComboBoxListener* const listener) throw()
  37644. {
  37645. listeners.add (listener);
  37646. }
  37647. void ComboBox::removeListener (ComboBoxListener* const listener) throw()
  37648. {
  37649. listeners.remove (listener);
  37650. }
  37651. void ComboBox::handleAsyncUpdate()
  37652. {
  37653. Component::BailOutChecker checker (this);
  37654. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this);
  37655. }
  37656. END_JUCE_NAMESPACE
  37657. /*** End of inlined file: juce_ComboBox.cpp ***/
  37658. /*** Start of inlined file: juce_Label.cpp ***/
  37659. BEGIN_JUCE_NAMESPACE
  37660. Label::Label (const String& componentName,
  37661. const String& labelText)
  37662. : Component (componentName),
  37663. textValue (labelText),
  37664. lastTextValue (labelText),
  37665. font (15.0f),
  37666. justification (Justification::centredLeft),
  37667. ownerComponent (0),
  37668. horizontalBorderSize (5),
  37669. verticalBorderSize (1),
  37670. minimumHorizontalScale (0.7f),
  37671. editSingleClick (false),
  37672. editDoubleClick (false),
  37673. lossOfFocusDiscardsChanges (false)
  37674. {
  37675. setColour (TextEditor::textColourId, Colours::black);
  37676. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  37677. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  37678. textValue.addListener (this);
  37679. }
  37680. Label::~Label()
  37681. {
  37682. textValue.removeListener (this);
  37683. if (ownerComponent != 0)
  37684. ownerComponent->removeComponentListener (this);
  37685. editor = 0;
  37686. }
  37687. void Label::setText (const String& newText,
  37688. const bool broadcastChangeMessage)
  37689. {
  37690. hideEditor (true);
  37691. if (lastTextValue != newText)
  37692. {
  37693. lastTextValue = newText;
  37694. textValue = newText;
  37695. repaint();
  37696. textWasChanged();
  37697. if (ownerComponent != 0)
  37698. componentMovedOrResized (*ownerComponent, true, true);
  37699. if (broadcastChangeMessage)
  37700. callChangeListeners();
  37701. }
  37702. }
  37703. const String Label::getText (const bool returnActiveEditorContents) const throw()
  37704. {
  37705. return (returnActiveEditorContents && isBeingEdited())
  37706. ? editor->getText()
  37707. : textValue.toString();
  37708. }
  37709. void Label::valueChanged (Value&)
  37710. {
  37711. if (lastTextValue != textValue.toString())
  37712. setText (textValue.toString(), true);
  37713. }
  37714. void Label::setFont (const Font& newFont) throw()
  37715. {
  37716. font = newFont;
  37717. repaint();
  37718. }
  37719. const Font& Label::getFont() const throw()
  37720. {
  37721. return font;
  37722. }
  37723. void Label::setEditable (const bool editOnSingleClick,
  37724. const bool editOnDoubleClick,
  37725. const bool lossOfFocusDiscardsChanges_) throw()
  37726. {
  37727. editSingleClick = editOnSingleClick;
  37728. editDoubleClick = editOnDoubleClick;
  37729. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  37730. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  37731. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  37732. }
  37733. void Label::setJustificationType (const Justification& justification_) throw()
  37734. {
  37735. justification = justification_;
  37736. repaint();
  37737. }
  37738. void Label::setBorderSize (int h, int v)
  37739. {
  37740. horizontalBorderSize = h;
  37741. verticalBorderSize = v;
  37742. repaint();
  37743. }
  37744. Component* Label::getAttachedComponent() const
  37745. {
  37746. return static_cast<Component*> (ownerComponent);
  37747. }
  37748. void Label::attachToComponent (Component* owner,
  37749. const bool onLeft)
  37750. {
  37751. if (ownerComponent != 0)
  37752. ownerComponent->removeComponentListener (this);
  37753. ownerComponent = owner;
  37754. leftOfOwnerComp = onLeft;
  37755. if (ownerComponent != 0)
  37756. {
  37757. setVisible (owner->isVisible());
  37758. ownerComponent->addComponentListener (this);
  37759. componentParentHierarchyChanged (*ownerComponent);
  37760. componentMovedOrResized (*ownerComponent, true, true);
  37761. }
  37762. }
  37763. void Label::componentMovedOrResized (Component& component,
  37764. bool /*wasMoved*/,
  37765. bool /*wasResized*/)
  37766. {
  37767. if (leftOfOwnerComp)
  37768. {
  37769. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  37770. component.getHeight());
  37771. setTopRightPosition (component.getX(), component.getY());
  37772. }
  37773. else
  37774. {
  37775. setSize (component.getWidth(),
  37776. 8 + roundToInt (getFont().getHeight()));
  37777. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  37778. }
  37779. }
  37780. void Label::componentParentHierarchyChanged (Component& component)
  37781. {
  37782. if (component.getParentComponent() != 0)
  37783. component.getParentComponent()->addChildComponent (this);
  37784. }
  37785. void Label::componentVisibilityChanged (Component& component)
  37786. {
  37787. setVisible (component.isVisible());
  37788. }
  37789. void Label::textWasEdited()
  37790. {
  37791. }
  37792. void Label::textWasChanged()
  37793. {
  37794. }
  37795. void Label::showEditor()
  37796. {
  37797. if (editor == 0)
  37798. {
  37799. addAndMakeVisible (editor = createEditorComponent());
  37800. editor->setText (getText(), false);
  37801. editor->addListener (this);
  37802. editor->grabKeyboardFocus();
  37803. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  37804. editor->addListener (this);
  37805. resized();
  37806. repaint();
  37807. editorShown (editor);
  37808. enterModalState (false);
  37809. editor->grabKeyboardFocus();
  37810. }
  37811. }
  37812. void Label::editorShown (TextEditor* /*editorComponent*/)
  37813. {
  37814. }
  37815. void Label::editorAboutToBeHidden (TextEditor* /*editorComponent*/)
  37816. {
  37817. }
  37818. bool Label::updateFromTextEditorContents()
  37819. {
  37820. jassert (editor != 0);
  37821. const String newText (editor->getText());
  37822. if (textValue.toString() != newText)
  37823. {
  37824. lastTextValue = newText;
  37825. textValue = newText;
  37826. repaint();
  37827. textWasChanged();
  37828. if (ownerComponent != 0)
  37829. componentMovedOrResized (*ownerComponent, true, true);
  37830. return true;
  37831. }
  37832. return false;
  37833. }
  37834. void Label::hideEditor (const bool discardCurrentEditorContents)
  37835. {
  37836. if (editor != 0)
  37837. {
  37838. Component::SafePointer<Component> deletionChecker (this);
  37839. editorAboutToBeHidden (editor);
  37840. const bool changed = (! discardCurrentEditorContents)
  37841. && updateFromTextEditorContents();
  37842. editor = 0;
  37843. repaint();
  37844. if (changed)
  37845. textWasEdited();
  37846. if (deletionChecker != 0)
  37847. exitModalState (0);
  37848. if (changed && deletionChecker != 0)
  37849. callChangeListeners();
  37850. }
  37851. }
  37852. void Label::inputAttemptWhenModal()
  37853. {
  37854. if (editor != 0)
  37855. {
  37856. if (lossOfFocusDiscardsChanges)
  37857. textEditorEscapeKeyPressed (*editor);
  37858. else
  37859. textEditorReturnKeyPressed (*editor);
  37860. }
  37861. }
  37862. bool Label::isBeingEdited() const throw()
  37863. {
  37864. return editor != 0;
  37865. }
  37866. TextEditor* Label::createEditorComponent()
  37867. {
  37868. TextEditor* const ed = new TextEditor (getName());
  37869. ed->setFont (font);
  37870. // copy these colours from our own settings..
  37871. const int cols[] = { TextEditor::backgroundColourId,
  37872. TextEditor::textColourId,
  37873. TextEditor::highlightColourId,
  37874. TextEditor::highlightedTextColourId,
  37875. TextEditor::caretColourId,
  37876. TextEditor::outlineColourId,
  37877. TextEditor::focusedOutlineColourId,
  37878. TextEditor::shadowColourId };
  37879. for (int i = 0; i < numElementsInArray (cols); ++i)
  37880. ed->setColour (cols[i], findColour (cols[i]));
  37881. return ed;
  37882. }
  37883. void Label::paint (Graphics& g)
  37884. {
  37885. getLookAndFeel().drawLabel (g, *this);
  37886. }
  37887. void Label::mouseUp (const MouseEvent& e)
  37888. {
  37889. if (editSingleClick
  37890. && e.mouseWasClicked()
  37891. && contains (e.x, e.y)
  37892. && ! e.mods.isPopupMenu())
  37893. {
  37894. showEditor();
  37895. }
  37896. }
  37897. void Label::mouseDoubleClick (const MouseEvent& e)
  37898. {
  37899. if (editDoubleClick && ! e.mods.isPopupMenu())
  37900. showEditor();
  37901. }
  37902. void Label::resized()
  37903. {
  37904. if (editor != 0)
  37905. editor->setBoundsInset (BorderSize (0));
  37906. }
  37907. void Label::focusGained (FocusChangeType cause)
  37908. {
  37909. if (editSingleClick && cause == focusChangedByTabKey)
  37910. showEditor();
  37911. }
  37912. void Label::enablementChanged()
  37913. {
  37914. repaint();
  37915. }
  37916. void Label::colourChanged()
  37917. {
  37918. repaint();
  37919. }
  37920. void Label::setMinimumHorizontalScale (const float newScale)
  37921. {
  37922. if (minimumHorizontalScale != newScale)
  37923. {
  37924. minimumHorizontalScale = newScale;
  37925. repaint();
  37926. }
  37927. }
  37928. // We'll use a custom focus traverser here to make sure focus goes from the
  37929. // text editor to another component rather than back to the label itself.
  37930. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  37931. {
  37932. public:
  37933. LabelKeyboardFocusTraverser() {}
  37934. Component* getNextComponent (Component* current)
  37935. {
  37936. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  37937. ? current->getParentComponent() : current);
  37938. }
  37939. Component* getPreviousComponent (Component* current)
  37940. {
  37941. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  37942. ? current->getParentComponent() : current);
  37943. }
  37944. };
  37945. KeyboardFocusTraverser* Label::createFocusTraverser()
  37946. {
  37947. return new LabelKeyboardFocusTraverser();
  37948. }
  37949. void Label::addListener (LabelListener* const listener) throw()
  37950. {
  37951. listeners.add (listener);
  37952. }
  37953. void Label::removeListener (LabelListener* const listener) throw()
  37954. {
  37955. listeners.remove (listener);
  37956. }
  37957. void Label::callChangeListeners()
  37958. {
  37959. Component::BailOutChecker checker (this);
  37960. listeners.callChecked (checker, &LabelListener::labelTextChanged, this);
  37961. }
  37962. void Label::textEditorTextChanged (TextEditor& ed)
  37963. {
  37964. if (editor != 0)
  37965. {
  37966. jassert (&ed == editor);
  37967. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  37968. {
  37969. if (lossOfFocusDiscardsChanges)
  37970. textEditorEscapeKeyPressed (ed);
  37971. else
  37972. textEditorReturnKeyPressed (ed);
  37973. }
  37974. }
  37975. }
  37976. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  37977. {
  37978. if (editor != 0)
  37979. {
  37980. jassert (&ed == editor);
  37981. (void) ed;
  37982. const bool changed = updateFromTextEditorContents();
  37983. hideEditor (true);
  37984. if (changed)
  37985. {
  37986. Component::SafePointer<Component> deletionChecker (this);
  37987. textWasEdited();
  37988. if (deletionChecker != 0)
  37989. callChangeListeners();
  37990. }
  37991. }
  37992. }
  37993. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  37994. {
  37995. if (editor != 0)
  37996. {
  37997. jassert (&ed == editor);
  37998. (void) ed;
  37999. editor->setText (textValue.toString(), false);
  38000. hideEditor (true);
  38001. }
  38002. }
  38003. void Label::textEditorFocusLost (TextEditor& ed)
  38004. {
  38005. textEditorTextChanged (ed);
  38006. }
  38007. END_JUCE_NAMESPACE
  38008. /*** End of inlined file: juce_Label.cpp ***/
  38009. /*** Start of inlined file: juce_ListBox.cpp ***/
  38010. BEGIN_JUCE_NAMESPACE
  38011. class ListBoxRowComponent : public Component,
  38012. public TooltipClient
  38013. {
  38014. public:
  38015. ListBoxRowComponent (ListBox& owner_)
  38016. : owner (owner_),
  38017. row (-1),
  38018. selected (false),
  38019. isDragging (false)
  38020. {
  38021. }
  38022. ~ListBoxRowComponent()
  38023. {
  38024. deleteAllChildren();
  38025. }
  38026. void paint (Graphics& g)
  38027. {
  38028. if (owner.getModel() != 0)
  38029. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  38030. }
  38031. void update (const int row_, const bool selected_)
  38032. {
  38033. if (row != row_ || selected != selected_)
  38034. {
  38035. repaint();
  38036. row = row_;
  38037. selected = selected_;
  38038. }
  38039. if (owner.getModel() != 0)
  38040. {
  38041. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  38042. if (customComp != 0)
  38043. {
  38044. addAndMakeVisible (customComp);
  38045. customComp->setBounds (0, 0, getWidth(), getHeight());
  38046. for (int i = getNumChildComponents(); --i >= 0;)
  38047. if (getChildComponent (i) != customComp)
  38048. delete getChildComponent (i);
  38049. }
  38050. else
  38051. {
  38052. deleteAllChildren();
  38053. }
  38054. }
  38055. }
  38056. void mouseDown (const MouseEvent& e)
  38057. {
  38058. isDragging = false;
  38059. selectRowOnMouseUp = false;
  38060. if (isEnabled())
  38061. {
  38062. if (! selected)
  38063. {
  38064. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38065. if (owner.getModel() != 0)
  38066. owner.getModel()->listBoxItemClicked (row, e);
  38067. }
  38068. else
  38069. {
  38070. selectRowOnMouseUp = true;
  38071. }
  38072. }
  38073. }
  38074. void mouseUp (const MouseEvent& e)
  38075. {
  38076. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  38077. {
  38078. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38079. if (owner.getModel() != 0)
  38080. owner.getModel()->listBoxItemClicked (row, e);
  38081. }
  38082. }
  38083. void mouseDoubleClick (const MouseEvent& e)
  38084. {
  38085. if (owner.getModel() != 0 && isEnabled())
  38086. owner.getModel()->listBoxItemDoubleClicked (row, e);
  38087. }
  38088. void mouseDrag (const MouseEvent& e)
  38089. {
  38090. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  38091. {
  38092. const SparseSet<int> selectedRows (owner.getSelectedRows());
  38093. if (selectedRows.size() > 0)
  38094. {
  38095. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  38096. if (dragDescription.isNotEmpty())
  38097. {
  38098. isDragging = true;
  38099. owner.startDragAndDrop (e, dragDescription);
  38100. }
  38101. }
  38102. }
  38103. }
  38104. void resized()
  38105. {
  38106. if (getNumChildComponents() > 0)
  38107. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  38108. }
  38109. const String getTooltip()
  38110. {
  38111. if (owner.getModel() != 0)
  38112. return owner.getModel()->getTooltipForRow (row);
  38113. return String::empty;
  38114. }
  38115. juce_UseDebuggingNewOperator
  38116. bool neededFlag;
  38117. private:
  38118. ListBox& owner;
  38119. int row;
  38120. bool selected, isDragging, selectRowOnMouseUp;
  38121. ListBoxRowComponent (const ListBoxRowComponent&);
  38122. ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  38123. };
  38124. class ListViewport : public Viewport
  38125. {
  38126. public:
  38127. int firstIndex, firstWholeIndex, lastWholeIndex;
  38128. bool hasUpdated;
  38129. ListViewport (ListBox& owner_)
  38130. : owner (owner_)
  38131. {
  38132. setWantsKeyboardFocus (false);
  38133. setViewedComponent (new Component());
  38134. getViewedComponent()->addMouseListener (this, false);
  38135. getViewedComponent()->setWantsKeyboardFocus (false);
  38136. }
  38137. ~ListViewport()
  38138. {
  38139. getViewedComponent()->removeMouseListener (this);
  38140. getViewedComponent()->deleteAllChildren();
  38141. }
  38142. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  38143. {
  38144. return static_cast <ListBoxRowComponent*>
  38145. (getViewedComponent()->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents())));
  38146. }
  38147. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  38148. {
  38149. const int index = getIndexOfChildComponent (rowComponent);
  38150. const int num = getViewedComponent()->getNumChildComponents();
  38151. for (int i = num; --i >= 0;)
  38152. if (((firstIndex + i) % jmax (1, num)) == index)
  38153. return firstIndex + i;
  38154. return -1;
  38155. }
  38156. Component* getComponentForRowIfOnscreen (const int row) const throw()
  38157. {
  38158. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  38159. ? getComponentForRow (row) : 0;
  38160. }
  38161. void visibleAreaChanged (int, int, int, int)
  38162. {
  38163. updateVisibleArea (true);
  38164. if (owner.getModel() != 0)
  38165. owner.getModel()->listWasScrolled();
  38166. }
  38167. void updateVisibleArea (const bool makeSureItUpdatesContent)
  38168. {
  38169. hasUpdated = false;
  38170. const int newX = getViewedComponent()->getX();
  38171. int newY = getViewedComponent()->getY();
  38172. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  38173. const int newH = owner.totalItems * owner.getRowHeight();
  38174. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  38175. newY = getMaximumVisibleHeight() - newH;
  38176. getViewedComponent()->setBounds (newX, newY, newW, newH);
  38177. if (makeSureItUpdatesContent && ! hasUpdated)
  38178. updateContents();
  38179. }
  38180. void updateContents()
  38181. {
  38182. hasUpdated = true;
  38183. const int rowHeight = owner.getRowHeight();
  38184. if (rowHeight > 0)
  38185. {
  38186. const int y = getViewPositionY();
  38187. const int w = getViewedComponent()->getWidth();
  38188. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  38189. while (numNeeded > getViewedComponent()->getNumChildComponents())
  38190. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  38191. jassert (numNeeded >= 0);
  38192. while (numNeeded < getViewedComponent()->getNumChildComponents())
  38193. {
  38194. Component* const rowToRemove
  38195. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  38196. delete rowToRemove;
  38197. }
  38198. firstIndex = y / rowHeight;
  38199. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  38200. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  38201. for (int i = 0; i < numNeeded; ++i)
  38202. {
  38203. const int row = i + firstIndex;
  38204. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  38205. if (rowComp != 0)
  38206. {
  38207. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  38208. rowComp->update (row, owner.isRowSelected (row));
  38209. }
  38210. }
  38211. }
  38212. if (owner.headerComponent != 0)
  38213. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  38214. owner.outlineThickness,
  38215. jmax (owner.getWidth() - owner.outlineThickness * 2,
  38216. getViewedComponent()->getWidth()),
  38217. owner.headerComponent->getHeight());
  38218. }
  38219. void paint (Graphics& g)
  38220. {
  38221. if (isOpaque())
  38222. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  38223. }
  38224. bool keyPressed (const KeyPress& key)
  38225. {
  38226. if (key.isKeyCode (KeyPress::upKey)
  38227. || key.isKeyCode (KeyPress::downKey)
  38228. || key.isKeyCode (KeyPress::pageUpKey)
  38229. || key.isKeyCode (KeyPress::pageDownKey)
  38230. || key.isKeyCode (KeyPress::homeKey)
  38231. || key.isKeyCode (KeyPress::endKey))
  38232. {
  38233. // we want to avoid these keypresses going to the viewport, and instead allow
  38234. // them to pass up to our listbox..
  38235. return false;
  38236. }
  38237. return Viewport::keyPressed (key);
  38238. }
  38239. juce_UseDebuggingNewOperator
  38240. private:
  38241. ListBox& owner;
  38242. ListViewport (const ListViewport&);
  38243. ListViewport& operator= (const ListViewport&);
  38244. };
  38245. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  38246. : Component (name),
  38247. model (model_),
  38248. headerComponent (0),
  38249. totalItems (0),
  38250. rowHeight (22),
  38251. minimumRowWidth (0),
  38252. outlineThickness (0),
  38253. lastRowSelected (-1),
  38254. mouseMoveSelects (false),
  38255. multipleSelection (false),
  38256. hasDoneInitialUpdate (false)
  38257. {
  38258. addAndMakeVisible (viewport = new ListViewport (*this));
  38259. setWantsKeyboardFocus (true);
  38260. colourChanged();
  38261. }
  38262. ListBox::~ListBox()
  38263. {
  38264. deleteAllChildren();
  38265. }
  38266. void ListBox::setModel (ListBoxModel* const newModel)
  38267. {
  38268. if (model != newModel)
  38269. {
  38270. model = newModel;
  38271. updateContent();
  38272. }
  38273. }
  38274. void ListBox::setMultipleSelectionEnabled (bool b)
  38275. {
  38276. multipleSelection = b;
  38277. }
  38278. void ListBox::setMouseMoveSelectsRows (bool b)
  38279. {
  38280. mouseMoveSelects = b;
  38281. if (b)
  38282. addMouseListener (this, true);
  38283. }
  38284. void ListBox::paint (Graphics& g)
  38285. {
  38286. if (! hasDoneInitialUpdate)
  38287. updateContent();
  38288. g.fillAll (findColour (backgroundColourId));
  38289. }
  38290. void ListBox::paintOverChildren (Graphics& g)
  38291. {
  38292. if (outlineThickness > 0)
  38293. {
  38294. g.setColour (findColour (outlineColourId));
  38295. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  38296. }
  38297. }
  38298. void ListBox::resized()
  38299. {
  38300. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  38301. outlineThickness,
  38302. outlineThickness,
  38303. outlineThickness));
  38304. viewport->setSingleStepSizes (20, getRowHeight());
  38305. viewport->updateVisibleArea (false);
  38306. }
  38307. void ListBox::visibilityChanged()
  38308. {
  38309. viewport->updateVisibleArea (true);
  38310. }
  38311. Viewport* ListBox::getViewport() const throw()
  38312. {
  38313. return viewport;
  38314. }
  38315. void ListBox::updateContent()
  38316. {
  38317. hasDoneInitialUpdate = true;
  38318. totalItems = (model != 0) ? model->getNumRows() : 0;
  38319. bool selectionChanged = false;
  38320. if (selected [selected.size() - 1] >= totalItems)
  38321. {
  38322. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  38323. lastRowSelected = getSelectedRow (0);
  38324. selectionChanged = true;
  38325. }
  38326. viewport->updateVisibleArea (isVisible());
  38327. viewport->resized();
  38328. if (selectionChanged && model != 0)
  38329. model->selectedRowsChanged (lastRowSelected);
  38330. }
  38331. void ListBox::selectRow (const int row,
  38332. bool dontScroll,
  38333. bool deselectOthersFirst)
  38334. {
  38335. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  38336. }
  38337. void ListBox::selectRowInternal (const int row,
  38338. bool dontScroll,
  38339. bool deselectOthersFirst,
  38340. bool isMouseClick)
  38341. {
  38342. if (! multipleSelection)
  38343. deselectOthersFirst = true;
  38344. if ((! isRowSelected (row))
  38345. || (deselectOthersFirst && getNumSelectedRows() > 1))
  38346. {
  38347. if (((unsigned int) row) < (unsigned int) totalItems)
  38348. {
  38349. if (deselectOthersFirst)
  38350. selected.clear();
  38351. selected.addRange (Range<int> (row, row + 1));
  38352. if (getHeight() == 0 || getWidth() == 0)
  38353. dontScroll = true;
  38354. viewport->hasUpdated = false;
  38355. if (row < viewport->firstWholeIndex && ! dontScroll)
  38356. {
  38357. viewport->setViewPosition (viewport->getViewPositionX(),
  38358. row * getRowHeight());
  38359. }
  38360. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  38361. {
  38362. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  38363. if (row >= lastRowSelected + rowsOnScreen
  38364. && rowsOnScreen < totalItems - 1
  38365. && ! isMouseClick)
  38366. {
  38367. viewport->setViewPosition (viewport->getViewPositionX(),
  38368. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  38369. * getRowHeight());
  38370. }
  38371. else
  38372. {
  38373. viewport->setViewPosition (viewport->getViewPositionX(),
  38374. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  38375. }
  38376. }
  38377. if (! viewport->hasUpdated)
  38378. viewport->updateContents();
  38379. lastRowSelected = row;
  38380. model->selectedRowsChanged (row);
  38381. }
  38382. else
  38383. {
  38384. if (deselectOthersFirst)
  38385. deselectAllRows();
  38386. }
  38387. }
  38388. }
  38389. void ListBox::deselectRow (const int row)
  38390. {
  38391. if (selected.contains (row))
  38392. {
  38393. selected.removeRange (Range <int> (row, row + 1));
  38394. if (row == lastRowSelected)
  38395. lastRowSelected = getSelectedRow (0);
  38396. viewport->updateContents();
  38397. model->selectedRowsChanged (lastRowSelected);
  38398. }
  38399. }
  38400. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  38401. const bool sendNotificationEventToModel)
  38402. {
  38403. selected = setOfRowsToBeSelected;
  38404. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  38405. if (! isRowSelected (lastRowSelected))
  38406. lastRowSelected = getSelectedRow (0);
  38407. viewport->updateContents();
  38408. if ((model != 0) && sendNotificationEventToModel)
  38409. model->selectedRowsChanged (lastRowSelected);
  38410. }
  38411. const SparseSet<int> ListBox::getSelectedRows() const
  38412. {
  38413. return selected;
  38414. }
  38415. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  38416. {
  38417. if (multipleSelection && (firstRow != lastRow))
  38418. {
  38419. const int numRows = totalItems - 1;
  38420. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  38421. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  38422. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  38423. jmax (firstRow, lastRow) + 1));
  38424. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  38425. }
  38426. selectRowInternal (lastRow, false, false, true);
  38427. }
  38428. void ListBox::flipRowSelection (const int row)
  38429. {
  38430. if (isRowSelected (row))
  38431. deselectRow (row);
  38432. else
  38433. selectRowInternal (row, false, false, true);
  38434. }
  38435. void ListBox::deselectAllRows()
  38436. {
  38437. if (! selected.isEmpty())
  38438. {
  38439. selected.clear();
  38440. lastRowSelected = -1;
  38441. viewport->updateContents();
  38442. if (model != 0)
  38443. model->selectedRowsChanged (lastRowSelected);
  38444. }
  38445. }
  38446. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  38447. const ModifierKeys& mods)
  38448. {
  38449. if (multipleSelection && mods.isCommandDown())
  38450. {
  38451. flipRowSelection (row);
  38452. }
  38453. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  38454. {
  38455. selectRangeOfRows (lastRowSelected, row);
  38456. }
  38457. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  38458. {
  38459. selectRowInternal (row, false, true, true);
  38460. }
  38461. }
  38462. int ListBox::getNumSelectedRows() const
  38463. {
  38464. return selected.size();
  38465. }
  38466. int ListBox::getSelectedRow (const int index) const
  38467. {
  38468. return (((unsigned int) index) < (unsigned int) selected.size())
  38469. ? selected [index] : -1;
  38470. }
  38471. bool ListBox::isRowSelected (const int row) const
  38472. {
  38473. return selected.contains (row);
  38474. }
  38475. int ListBox::getLastRowSelected() const
  38476. {
  38477. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  38478. }
  38479. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  38480. {
  38481. if (((unsigned int) x) < (unsigned int) getWidth())
  38482. {
  38483. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  38484. if (((unsigned int) row) < (unsigned int) totalItems)
  38485. return row;
  38486. }
  38487. return -1;
  38488. }
  38489. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  38490. {
  38491. if (((unsigned int) x) < (unsigned int) getWidth())
  38492. {
  38493. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  38494. return jlimit (0, totalItems, row);
  38495. }
  38496. return -1;
  38497. }
  38498. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  38499. {
  38500. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  38501. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  38502. }
  38503. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  38504. {
  38505. return viewport->getRowNumberOfComponent (rowComponent);
  38506. }
  38507. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  38508. const bool relativeToComponentTopLeft) const throw()
  38509. {
  38510. int y = viewport->getY() + rowHeight * rowNumber;
  38511. if (relativeToComponentTopLeft)
  38512. y -= viewport->getViewPositionY();
  38513. return Rectangle<int> (viewport->getX(), y,
  38514. viewport->getViewedComponent()->getWidth(), rowHeight);
  38515. }
  38516. void ListBox::setVerticalPosition (const double proportion)
  38517. {
  38518. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  38519. viewport->setViewPosition (viewport->getViewPositionX(),
  38520. jmax (0, roundToInt (proportion * offscreen)));
  38521. }
  38522. double ListBox::getVerticalPosition() const
  38523. {
  38524. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  38525. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  38526. : 0;
  38527. }
  38528. int ListBox::getVisibleRowWidth() const throw()
  38529. {
  38530. return viewport->getViewWidth();
  38531. }
  38532. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  38533. {
  38534. if (row < viewport->firstWholeIndex)
  38535. {
  38536. viewport->setViewPosition (viewport->getViewPositionX(),
  38537. row * getRowHeight());
  38538. }
  38539. else if (row >= viewport->lastWholeIndex)
  38540. {
  38541. viewport->setViewPosition (viewport->getViewPositionX(),
  38542. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  38543. }
  38544. }
  38545. bool ListBox::keyPressed (const KeyPress& key)
  38546. {
  38547. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  38548. const bool multiple = multipleSelection
  38549. && (lastRowSelected >= 0)
  38550. && (key.getModifiers().isShiftDown()
  38551. || key.getModifiers().isCtrlDown()
  38552. || key.getModifiers().isCommandDown());
  38553. if (key.isKeyCode (KeyPress::upKey))
  38554. {
  38555. if (multiple)
  38556. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  38557. else
  38558. selectRow (jmax (0, lastRowSelected - 1));
  38559. }
  38560. else if (key.isKeyCode (KeyPress::returnKey)
  38561. && isRowSelected (lastRowSelected))
  38562. {
  38563. if (model != 0)
  38564. model->returnKeyPressed (lastRowSelected);
  38565. }
  38566. else if (key.isKeyCode (KeyPress::pageUpKey))
  38567. {
  38568. if (multiple)
  38569. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  38570. else
  38571. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  38572. }
  38573. else if (key.isKeyCode (KeyPress::pageDownKey))
  38574. {
  38575. if (multiple)
  38576. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  38577. else
  38578. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  38579. }
  38580. else if (key.isKeyCode (KeyPress::homeKey))
  38581. {
  38582. if (multiple && key.getModifiers().isShiftDown())
  38583. selectRangeOfRows (lastRowSelected, 0);
  38584. else
  38585. selectRow (0);
  38586. }
  38587. else if (key.isKeyCode (KeyPress::endKey))
  38588. {
  38589. if (multiple && key.getModifiers().isShiftDown())
  38590. selectRangeOfRows (lastRowSelected, totalItems - 1);
  38591. else
  38592. selectRow (totalItems - 1);
  38593. }
  38594. else if (key.isKeyCode (KeyPress::downKey))
  38595. {
  38596. if (multiple)
  38597. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  38598. else
  38599. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  38600. }
  38601. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  38602. && isRowSelected (lastRowSelected))
  38603. {
  38604. if (model != 0)
  38605. model->deleteKeyPressed (lastRowSelected);
  38606. }
  38607. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  38608. {
  38609. selectRangeOfRows (0, std::numeric_limits<int>::max());
  38610. }
  38611. else
  38612. {
  38613. return false;
  38614. }
  38615. return true;
  38616. }
  38617. bool ListBox::keyStateChanged (const bool isKeyDown)
  38618. {
  38619. return isKeyDown
  38620. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38621. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  38622. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38623. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  38624. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  38625. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  38626. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  38627. }
  38628. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  38629. {
  38630. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  38631. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  38632. }
  38633. void ListBox::mouseMove (const MouseEvent& e)
  38634. {
  38635. if (mouseMoveSelects)
  38636. {
  38637. const MouseEvent e2 (e.getEventRelativeTo (this));
  38638. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  38639. }
  38640. }
  38641. void ListBox::mouseExit (const MouseEvent& e)
  38642. {
  38643. mouseMove (e);
  38644. }
  38645. void ListBox::mouseUp (const MouseEvent& e)
  38646. {
  38647. if (e.mouseWasClicked() && model != 0)
  38648. model->backgroundClicked();
  38649. }
  38650. void ListBox::setRowHeight (const int newHeight)
  38651. {
  38652. rowHeight = jmax (1, newHeight);
  38653. viewport->setSingleStepSizes (20, rowHeight);
  38654. updateContent();
  38655. }
  38656. int ListBox::getNumRowsOnScreen() const throw()
  38657. {
  38658. return viewport->getMaximumVisibleHeight() / rowHeight;
  38659. }
  38660. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  38661. {
  38662. minimumRowWidth = newMinimumWidth;
  38663. updateContent();
  38664. }
  38665. int ListBox::getVisibleContentWidth() const throw()
  38666. {
  38667. return viewport->getMaximumVisibleWidth();
  38668. }
  38669. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  38670. {
  38671. return viewport->getVerticalScrollBar();
  38672. }
  38673. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  38674. {
  38675. return viewport->getHorizontalScrollBar();
  38676. }
  38677. void ListBox::colourChanged()
  38678. {
  38679. setOpaque (findColour (backgroundColourId).isOpaque());
  38680. viewport->setOpaque (isOpaque());
  38681. repaint();
  38682. }
  38683. void ListBox::setOutlineThickness (const int outlineThickness_)
  38684. {
  38685. outlineThickness = outlineThickness_;
  38686. resized();
  38687. }
  38688. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  38689. {
  38690. if (headerComponent != newHeaderComponent)
  38691. {
  38692. delete headerComponent;
  38693. headerComponent = newHeaderComponent;
  38694. addAndMakeVisible (newHeaderComponent);
  38695. ListBox::resized();
  38696. }
  38697. }
  38698. void ListBox::repaintRow (const int rowNumber) throw()
  38699. {
  38700. const Rectangle<int> r (getRowPosition (rowNumber, true));
  38701. repaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  38702. }
  38703. Image* ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  38704. {
  38705. Rectangle<int> imageArea;
  38706. const int firstRow = getRowContainingPosition (0, 0);
  38707. int i;
  38708. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  38709. {
  38710. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  38711. if (rowComp != 0 && isRowSelected (firstRow + i))
  38712. {
  38713. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  38714. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  38715. if (imageArea.isEmpty())
  38716. imageArea = rowRect;
  38717. else
  38718. imageArea = imageArea.getUnion (rowRect);
  38719. }
  38720. }
  38721. imageArea = imageArea.getIntersection (getLocalBounds());
  38722. imageX = imageArea.getX();
  38723. imageY = imageArea.getY();
  38724. Image* snapshot = Image::createNativeImage (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true);
  38725. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  38726. {
  38727. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  38728. if (rowComp != 0 && isRowSelected (firstRow + i))
  38729. {
  38730. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  38731. Graphics g (*snapshot);
  38732. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  38733. if (g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight()))
  38734. rowComp->paintEntireComponent (g);
  38735. }
  38736. }
  38737. return snapshot;
  38738. }
  38739. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  38740. {
  38741. DragAndDropContainer* const dragContainer
  38742. = DragAndDropContainer::findParentDragContainerFor (this);
  38743. if (dragContainer != 0)
  38744. {
  38745. int x, y;
  38746. Image* dragImage = createSnapshotOfSelectedRows (x, y);
  38747. dragImage->multiplyAllAlphas (0.6f);
  38748. MouseEvent e2 (e.getEventRelativeTo (this));
  38749. const Point<int> p (x - e2.x, y - e2.y);
  38750. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  38751. }
  38752. else
  38753. {
  38754. // to be able to do a drag-and-drop operation, the listbox needs to
  38755. // be inside a component which is also a DragAndDropContainer.
  38756. jassertfalse
  38757. }
  38758. }
  38759. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  38760. {
  38761. (void) existingComponentToUpdate;
  38762. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  38763. return 0;
  38764. }
  38765. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  38766. {
  38767. }
  38768. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  38769. {
  38770. }
  38771. void ListBoxModel::backgroundClicked()
  38772. {
  38773. }
  38774. void ListBoxModel::selectedRowsChanged (int)
  38775. {
  38776. }
  38777. void ListBoxModel::deleteKeyPressed (int)
  38778. {
  38779. }
  38780. void ListBoxModel::returnKeyPressed (int)
  38781. {
  38782. }
  38783. void ListBoxModel::listWasScrolled()
  38784. {
  38785. }
  38786. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  38787. {
  38788. return String::empty;
  38789. }
  38790. const String ListBoxModel::getTooltipForRow (int)
  38791. {
  38792. return String::empty;
  38793. }
  38794. END_JUCE_NAMESPACE
  38795. /*** End of inlined file: juce_ListBox.cpp ***/
  38796. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  38797. BEGIN_JUCE_NAMESPACE
  38798. ProgressBar::ProgressBar (double& progress_)
  38799. : progress (progress_),
  38800. displayPercentage (true),
  38801. lastCallbackTime (0)
  38802. {
  38803. currentValue = jlimit (0.0, 1.0, progress);
  38804. }
  38805. ProgressBar::~ProgressBar()
  38806. {
  38807. }
  38808. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  38809. {
  38810. displayPercentage = shouldDisplayPercentage;
  38811. repaint();
  38812. }
  38813. void ProgressBar::setTextToDisplay (const String& text)
  38814. {
  38815. displayPercentage = false;
  38816. displayedMessage = text;
  38817. }
  38818. void ProgressBar::lookAndFeelChanged()
  38819. {
  38820. setOpaque (findColour (backgroundColourId).isOpaque());
  38821. }
  38822. void ProgressBar::colourChanged()
  38823. {
  38824. lookAndFeelChanged();
  38825. }
  38826. void ProgressBar::paint (Graphics& g)
  38827. {
  38828. String text;
  38829. if (displayPercentage)
  38830. {
  38831. if (currentValue >= 0 && currentValue <= 1.0)
  38832. text << roundToInt (currentValue * 100.0) << '%';
  38833. }
  38834. else
  38835. {
  38836. text = displayedMessage;
  38837. }
  38838. getLookAndFeel().drawProgressBar (g, *this,
  38839. getWidth(), getHeight(),
  38840. currentValue, text);
  38841. }
  38842. void ProgressBar::visibilityChanged()
  38843. {
  38844. if (isVisible())
  38845. startTimer (30);
  38846. else
  38847. stopTimer();
  38848. }
  38849. void ProgressBar::timerCallback()
  38850. {
  38851. double newProgress = progress;
  38852. const uint32 now = Time::getMillisecondCounter();
  38853. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  38854. lastCallbackTime = now;
  38855. if (currentValue != newProgress
  38856. || newProgress < 0 || newProgress >= 1.0
  38857. || currentMessage != displayedMessage)
  38858. {
  38859. if (currentValue < newProgress
  38860. && newProgress >= 0 && newProgress < 1.0
  38861. && currentValue >= 0 && currentValue < 1.0)
  38862. {
  38863. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  38864. newProgress);
  38865. }
  38866. currentValue = newProgress;
  38867. currentMessage = displayedMessage;
  38868. repaint();
  38869. }
  38870. }
  38871. END_JUCE_NAMESPACE
  38872. /*** End of inlined file: juce_ProgressBar.cpp ***/
  38873. /*** Start of inlined file: juce_Slider.cpp ***/
  38874. BEGIN_JUCE_NAMESPACE
  38875. class SliderPopupDisplayComponent : public BubbleComponent
  38876. {
  38877. public:
  38878. SliderPopupDisplayComponent (Slider* const owner_)
  38879. : owner (owner_),
  38880. font (15.0f, Font::bold)
  38881. {
  38882. setAlwaysOnTop (true);
  38883. }
  38884. ~SliderPopupDisplayComponent()
  38885. {
  38886. }
  38887. void paintContent (Graphics& g, int w, int h)
  38888. {
  38889. g.setFont (font);
  38890. g.setColour (Colours::black);
  38891. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  38892. }
  38893. void getContentSize (int& w, int& h)
  38894. {
  38895. w = font.getStringWidth (text) + 18;
  38896. h = (int) (font.getHeight() * 1.6f);
  38897. }
  38898. void updatePosition (const String& newText)
  38899. {
  38900. if (text != newText)
  38901. {
  38902. text = newText;
  38903. repaint();
  38904. }
  38905. BubbleComponent::setPosition (owner);
  38906. }
  38907. juce_UseDebuggingNewOperator
  38908. private:
  38909. Slider* owner;
  38910. Font font;
  38911. String text;
  38912. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  38913. SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  38914. };
  38915. Slider::Slider (const String& name)
  38916. : Component (name),
  38917. lastCurrentValue (0),
  38918. lastValueMin (0),
  38919. lastValueMax (0),
  38920. minimum (0),
  38921. maximum (10),
  38922. interval (0),
  38923. skewFactor (1.0),
  38924. velocityModeSensitivity (1.0),
  38925. velocityModeOffset (0.0),
  38926. velocityModeThreshold (1),
  38927. rotaryStart (float_Pi * 1.2f),
  38928. rotaryEnd (float_Pi * 2.8f),
  38929. numDecimalPlaces (7),
  38930. sliderRegionStart (0),
  38931. sliderRegionSize (1),
  38932. sliderBeingDragged (-1),
  38933. pixelsForFullDragExtent (250),
  38934. style (LinearHorizontal),
  38935. textBoxPos (TextBoxLeft),
  38936. textBoxWidth (80),
  38937. textBoxHeight (20),
  38938. incDecButtonMode (incDecButtonsNotDraggable),
  38939. editableText (true),
  38940. doubleClickToValue (false),
  38941. isVelocityBased (false),
  38942. userKeyOverridesVelocity (true),
  38943. rotaryStop (true),
  38944. incDecButtonsSideBySide (false),
  38945. sendChangeOnlyOnRelease (false),
  38946. popupDisplayEnabled (false),
  38947. menuEnabled (false),
  38948. menuShown (false),
  38949. scrollWheelEnabled (true),
  38950. snapsToMousePos (true),
  38951. valueBox (0),
  38952. incButton (0),
  38953. decButton (0),
  38954. popupDisplay (0),
  38955. parentForPopupDisplay (0)
  38956. {
  38957. setWantsKeyboardFocus (false);
  38958. setRepaintsOnMouseActivity (true);
  38959. lookAndFeelChanged();
  38960. updateText();
  38961. currentValue.addListener (this);
  38962. valueMin.addListener (this);
  38963. valueMax.addListener (this);
  38964. }
  38965. Slider::~Slider()
  38966. {
  38967. currentValue.removeListener (this);
  38968. valueMin.removeListener (this);
  38969. valueMax.removeListener (this);
  38970. popupDisplay = 0;
  38971. deleteAllChildren();
  38972. }
  38973. void Slider::handleAsyncUpdate()
  38974. {
  38975. cancelPendingUpdate();
  38976. Component::BailOutChecker checker (this);
  38977. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this);
  38978. }
  38979. void Slider::sendDragStart()
  38980. {
  38981. startedDragging();
  38982. Component::BailOutChecker checker (this);
  38983. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  38984. }
  38985. void Slider::sendDragEnd()
  38986. {
  38987. stoppedDragging();
  38988. sliderBeingDragged = -1;
  38989. Component::BailOutChecker checker (this);
  38990. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  38991. }
  38992. void Slider::addListener (SliderListener* const listener)
  38993. {
  38994. listeners.add (listener);
  38995. }
  38996. void Slider::removeListener (SliderListener* const listener)
  38997. {
  38998. listeners.remove (listener);
  38999. }
  39000. void Slider::setSliderStyle (const SliderStyle newStyle)
  39001. {
  39002. if (style != newStyle)
  39003. {
  39004. style = newStyle;
  39005. repaint();
  39006. lookAndFeelChanged();
  39007. }
  39008. }
  39009. void Slider::setRotaryParameters (const float startAngleRadians,
  39010. const float endAngleRadians,
  39011. const bool stopAtEnd)
  39012. {
  39013. // make sure the values are sensible..
  39014. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  39015. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  39016. jassert (rotaryStart < rotaryEnd);
  39017. rotaryStart = startAngleRadians;
  39018. rotaryEnd = endAngleRadians;
  39019. rotaryStop = stopAtEnd;
  39020. }
  39021. void Slider::setVelocityBasedMode (const bool velBased)
  39022. {
  39023. isVelocityBased = velBased;
  39024. }
  39025. void Slider::setVelocityModeParameters (const double sensitivity,
  39026. const int threshold,
  39027. const double offset,
  39028. const bool userCanPressKeyToSwapMode)
  39029. {
  39030. jassert (threshold >= 0);
  39031. jassert (sensitivity > 0);
  39032. jassert (offset >= 0);
  39033. velocityModeSensitivity = sensitivity;
  39034. velocityModeOffset = offset;
  39035. velocityModeThreshold = threshold;
  39036. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  39037. }
  39038. void Slider::setSkewFactor (const double factor)
  39039. {
  39040. skewFactor = factor;
  39041. }
  39042. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  39043. {
  39044. if (maximum > minimum)
  39045. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  39046. / (maximum - minimum));
  39047. }
  39048. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  39049. {
  39050. jassert (distanceForFullScaleDrag > 0);
  39051. pixelsForFullDragExtent = distanceForFullScaleDrag;
  39052. }
  39053. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  39054. {
  39055. if (incDecButtonMode != mode)
  39056. {
  39057. incDecButtonMode = mode;
  39058. lookAndFeelChanged();
  39059. }
  39060. }
  39061. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  39062. const bool isReadOnly,
  39063. const int textEntryBoxWidth,
  39064. const int textEntryBoxHeight)
  39065. {
  39066. textBoxPos = newPosition;
  39067. editableText = ! isReadOnly;
  39068. textBoxWidth = textEntryBoxWidth;
  39069. textBoxHeight = textEntryBoxHeight;
  39070. repaint();
  39071. lookAndFeelChanged();
  39072. }
  39073. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  39074. {
  39075. editableText = shouldBeEditable;
  39076. if (valueBox != 0)
  39077. valueBox->setEditable (shouldBeEditable && isEnabled());
  39078. }
  39079. void Slider::showTextBox()
  39080. {
  39081. jassert (editableText); // this should probably be avoided in read-only sliders.
  39082. if (valueBox != 0)
  39083. valueBox->showEditor();
  39084. }
  39085. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  39086. {
  39087. if (valueBox != 0)
  39088. {
  39089. valueBox->hideEditor (discardCurrentEditorContents);
  39090. if (discardCurrentEditorContents)
  39091. updateText();
  39092. }
  39093. }
  39094. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  39095. {
  39096. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  39097. }
  39098. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  39099. {
  39100. snapsToMousePos = shouldSnapToMouse;
  39101. }
  39102. void Slider::setPopupDisplayEnabled (const bool enabled,
  39103. Component* const parentComponentToUse)
  39104. {
  39105. popupDisplayEnabled = enabled;
  39106. parentForPopupDisplay = parentComponentToUse;
  39107. }
  39108. void Slider::colourChanged()
  39109. {
  39110. lookAndFeelChanged();
  39111. }
  39112. void Slider::lookAndFeelChanged()
  39113. {
  39114. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  39115. : getTextFromValue (currentValue.getValue()));
  39116. deleteAllChildren();
  39117. valueBox = 0;
  39118. LookAndFeel& lf = getLookAndFeel();
  39119. if (textBoxPos != NoTextBox)
  39120. {
  39121. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  39122. valueBox->setWantsKeyboardFocus (false);
  39123. valueBox->setText (previousTextBoxContent, false);
  39124. valueBox->setEditable (editableText && isEnabled());
  39125. valueBox->addListener (this);
  39126. if (style == LinearBar)
  39127. valueBox->addMouseListener (this, false);
  39128. valueBox->setTooltip (getTooltip());
  39129. }
  39130. if (style == IncDecButtons)
  39131. {
  39132. addAndMakeVisible (incButton = lf.createSliderButton (true));
  39133. incButton->addButtonListener (this);
  39134. addAndMakeVisible (decButton = lf.createSliderButton (false));
  39135. decButton->addButtonListener (this);
  39136. if (incDecButtonMode != incDecButtonsNotDraggable)
  39137. {
  39138. incButton->addMouseListener (this, false);
  39139. decButton->addMouseListener (this, false);
  39140. }
  39141. else
  39142. {
  39143. incButton->setRepeatSpeed (300, 100, 20);
  39144. incButton->addMouseListener (decButton, false);
  39145. decButton->setRepeatSpeed (300, 100, 20);
  39146. decButton->addMouseListener (incButton, false);
  39147. }
  39148. incButton->setTooltip (getTooltip());
  39149. decButton->setTooltip (getTooltip());
  39150. }
  39151. setComponentEffect (lf.getSliderEffect());
  39152. resized();
  39153. repaint();
  39154. }
  39155. void Slider::setRange (const double newMin,
  39156. const double newMax,
  39157. const double newInt)
  39158. {
  39159. if (minimum != newMin
  39160. || maximum != newMax
  39161. || interval != newInt)
  39162. {
  39163. minimum = newMin;
  39164. maximum = newMax;
  39165. interval = newInt;
  39166. // figure out the number of DPs needed to display all values at this
  39167. // interval setting.
  39168. numDecimalPlaces = 7;
  39169. if (newInt != 0)
  39170. {
  39171. int v = abs ((int) (newInt * 10000000));
  39172. while ((v % 10) == 0)
  39173. {
  39174. --numDecimalPlaces;
  39175. v /= 10;
  39176. }
  39177. }
  39178. // keep the current values inside the new range..
  39179. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39180. {
  39181. setValue (getValue(), false, false);
  39182. }
  39183. else
  39184. {
  39185. setMinValue (getMinValue(), false, false);
  39186. setMaxValue (getMaxValue(), false, false);
  39187. }
  39188. updateText();
  39189. }
  39190. }
  39191. void Slider::triggerChangeMessage (const bool synchronous)
  39192. {
  39193. if (synchronous)
  39194. handleAsyncUpdate();
  39195. else
  39196. triggerAsyncUpdate();
  39197. valueChanged();
  39198. }
  39199. void Slider::valueChanged (Value& value)
  39200. {
  39201. if (value.refersToSameSourceAs (currentValue))
  39202. {
  39203. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39204. setValue (currentValue.getValue(), false, false);
  39205. }
  39206. else if (value.refersToSameSourceAs (valueMin))
  39207. setMinValue (valueMin.getValue(), false, false, true);
  39208. else if (value.refersToSameSourceAs (valueMax))
  39209. setMaxValue (valueMax.getValue(), false, false, true);
  39210. }
  39211. double Slider::getValue() const
  39212. {
  39213. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  39214. // methods to get the two values.
  39215. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39216. return currentValue.getValue();
  39217. }
  39218. void Slider::setValue (double newValue,
  39219. const bool sendUpdateMessage,
  39220. const bool sendMessageSynchronously)
  39221. {
  39222. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  39223. // methods to set the two values.
  39224. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39225. newValue = constrainedValue (newValue);
  39226. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  39227. {
  39228. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  39229. newValue = jlimit ((double) valueMin.getValue(),
  39230. (double) valueMax.getValue(),
  39231. newValue);
  39232. }
  39233. if (newValue != lastCurrentValue)
  39234. {
  39235. if (valueBox != 0)
  39236. valueBox->hideEditor (true);
  39237. lastCurrentValue = newValue;
  39238. currentValue = newValue;
  39239. updateText();
  39240. repaint();
  39241. if (popupDisplay != 0)
  39242. {
  39243. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39244. ->updatePosition (getTextFromValue (newValue));
  39245. popupDisplay->repaint();
  39246. }
  39247. if (sendUpdateMessage)
  39248. triggerChangeMessage (sendMessageSynchronously);
  39249. }
  39250. }
  39251. double Slider::getMinValue() const
  39252. {
  39253. // The minimum value only applies to sliders that are in two- or three-value mode.
  39254. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39255. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39256. return valueMin.getValue();
  39257. }
  39258. double Slider::getMaxValue() const
  39259. {
  39260. // The maximum value only applies to sliders that are in two- or three-value mode.
  39261. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39262. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39263. return valueMax.getValue();
  39264. }
  39265. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39266. {
  39267. // The minimum value only applies to sliders that are in two- or three-value mode.
  39268. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39269. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39270. newValue = constrainedValue (newValue);
  39271. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39272. {
  39273. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  39274. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39275. newValue = jmin ((double) valueMax.getValue(), newValue);
  39276. }
  39277. else
  39278. {
  39279. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  39280. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39281. newValue = jmin (lastCurrentValue, newValue);
  39282. }
  39283. if (lastValueMin != newValue)
  39284. {
  39285. lastValueMin = newValue;
  39286. valueMin = newValue;
  39287. repaint();
  39288. if (popupDisplay != 0)
  39289. {
  39290. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39291. ->updatePosition (getTextFromValue (newValue));
  39292. popupDisplay->repaint();
  39293. }
  39294. if (sendUpdateMessage)
  39295. triggerChangeMessage (sendMessageSynchronously);
  39296. }
  39297. }
  39298. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39299. {
  39300. // The maximum value only applies to sliders that are in two- or three-value mode.
  39301. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39302. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39303. newValue = constrainedValue (newValue);
  39304. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39305. {
  39306. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  39307. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39308. newValue = jmax ((double) valueMin.getValue(), newValue);
  39309. }
  39310. else
  39311. {
  39312. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  39313. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39314. newValue = jmax (lastCurrentValue, newValue);
  39315. }
  39316. if (lastValueMax != newValue)
  39317. {
  39318. lastValueMax = newValue;
  39319. valueMax = newValue;
  39320. repaint();
  39321. if (popupDisplay != 0)
  39322. {
  39323. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39324. ->updatePosition (getTextFromValue (valueMax.getValue()));
  39325. popupDisplay->repaint();
  39326. }
  39327. if (sendUpdateMessage)
  39328. triggerChangeMessage (sendMessageSynchronously);
  39329. }
  39330. }
  39331. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  39332. const double valueToSetOnDoubleClick)
  39333. {
  39334. doubleClickToValue = isDoubleClickEnabled;
  39335. doubleClickReturnValue = valueToSetOnDoubleClick;
  39336. }
  39337. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  39338. {
  39339. isEnabled_ = doubleClickToValue;
  39340. return doubleClickReturnValue;
  39341. }
  39342. void Slider::updateText()
  39343. {
  39344. if (valueBox != 0)
  39345. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  39346. }
  39347. void Slider::setTextValueSuffix (const String& suffix)
  39348. {
  39349. if (textSuffix != suffix)
  39350. {
  39351. textSuffix = suffix;
  39352. updateText();
  39353. }
  39354. }
  39355. const String Slider::getTextValueSuffix() const
  39356. {
  39357. return textSuffix;
  39358. }
  39359. const String Slider::getTextFromValue (double v)
  39360. {
  39361. if (getNumDecimalPlacesToDisplay() > 0)
  39362. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  39363. else
  39364. return String (roundToInt (v)) + getTextValueSuffix();
  39365. }
  39366. double Slider::getValueFromText (const String& text)
  39367. {
  39368. String t (text.trimStart());
  39369. if (t.endsWith (textSuffix))
  39370. t = t.substring (0, t.length() - textSuffix.length());
  39371. while (t.startsWithChar ('+'))
  39372. t = t.substring (1).trimStart();
  39373. return t.initialSectionContainingOnly ("0123456789.,-")
  39374. .getDoubleValue();
  39375. }
  39376. double Slider::proportionOfLengthToValue (double proportion)
  39377. {
  39378. if (skewFactor != 1.0 && proportion > 0.0)
  39379. proportion = exp (log (proportion) / skewFactor);
  39380. return minimum + (maximum - minimum) * proportion;
  39381. }
  39382. double Slider::valueToProportionOfLength (double value)
  39383. {
  39384. const double n = (value - minimum) / (maximum - minimum);
  39385. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  39386. }
  39387. double Slider::snapValue (double attemptedValue, const bool)
  39388. {
  39389. return attemptedValue;
  39390. }
  39391. void Slider::startedDragging()
  39392. {
  39393. }
  39394. void Slider::stoppedDragging()
  39395. {
  39396. }
  39397. void Slider::valueChanged()
  39398. {
  39399. }
  39400. void Slider::enablementChanged()
  39401. {
  39402. repaint();
  39403. }
  39404. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  39405. {
  39406. menuEnabled = menuEnabled_;
  39407. }
  39408. void Slider::setScrollWheelEnabled (const bool enabled)
  39409. {
  39410. scrollWheelEnabled = enabled;
  39411. }
  39412. void Slider::labelTextChanged (Label* label)
  39413. {
  39414. const double newValue = snapValue (getValueFromText (label->getText()), false);
  39415. if (newValue != (double) currentValue.getValue())
  39416. {
  39417. sendDragStart();
  39418. setValue (newValue, true, true);
  39419. sendDragEnd();
  39420. }
  39421. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  39422. }
  39423. void Slider::buttonClicked (Button* button)
  39424. {
  39425. if (style == IncDecButtons)
  39426. {
  39427. sendDragStart();
  39428. if (button == incButton)
  39429. setValue (snapValue (getValue() + interval, false), true, true);
  39430. else if (button == decButton)
  39431. setValue (snapValue (getValue() - interval, false), true, true);
  39432. sendDragEnd();
  39433. }
  39434. }
  39435. double Slider::constrainedValue (double value) const
  39436. {
  39437. if (interval > 0)
  39438. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  39439. if (value <= minimum || maximum <= minimum)
  39440. value = minimum;
  39441. else if (value >= maximum)
  39442. value = maximum;
  39443. return value;
  39444. }
  39445. float Slider::getLinearSliderPos (const double value)
  39446. {
  39447. double sliderPosProportional;
  39448. if (maximum > minimum)
  39449. {
  39450. if (value < minimum)
  39451. {
  39452. sliderPosProportional = 0.0;
  39453. }
  39454. else if (value > maximum)
  39455. {
  39456. sliderPosProportional = 1.0;
  39457. }
  39458. else
  39459. {
  39460. sliderPosProportional = valueToProportionOfLength (value);
  39461. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  39462. }
  39463. }
  39464. else
  39465. {
  39466. sliderPosProportional = 0.5;
  39467. }
  39468. if (isVertical() || style == IncDecButtons)
  39469. sliderPosProportional = 1.0 - sliderPosProportional;
  39470. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  39471. }
  39472. bool Slider::isHorizontal() const
  39473. {
  39474. return style == LinearHorizontal
  39475. || style == LinearBar
  39476. || style == TwoValueHorizontal
  39477. || style == ThreeValueHorizontal;
  39478. }
  39479. bool Slider::isVertical() const
  39480. {
  39481. return style == LinearVertical
  39482. || style == TwoValueVertical
  39483. || style == ThreeValueVertical;
  39484. }
  39485. bool Slider::incDecDragDirectionIsHorizontal() const
  39486. {
  39487. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  39488. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  39489. }
  39490. float Slider::getPositionOfValue (const double value)
  39491. {
  39492. if (isHorizontal() || isVertical())
  39493. {
  39494. return getLinearSliderPos (value);
  39495. }
  39496. else
  39497. {
  39498. jassertfalse // not a valid call on a slider that doesn't work linearly!
  39499. return 0.0f;
  39500. }
  39501. }
  39502. void Slider::paint (Graphics& g)
  39503. {
  39504. if (style != IncDecButtons)
  39505. {
  39506. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39507. {
  39508. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  39509. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  39510. getLookAndFeel().drawRotarySlider (g,
  39511. sliderRect.getX(),
  39512. sliderRect.getY(),
  39513. sliderRect.getWidth(),
  39514. sliderRect.getHeight(),
  39515. sliderPos,
  39516. rotaryStart, rotaryEnd,
  39517. *this);
  39518. }
  39519. else
  39520. {
  39521. getLookAndFeel().drawLinearSlider (g,
  39522. sliderRect.getX(),
  39523. sliderRect.getY(),
  39524. sliderRect.getWidth(),
  39525. sliderRect.getHeight(),
  39526. getLinearSliderPos (lastCurrentValue),
  39527. getLinearSliderPos (lastValueMin),
  39528. getLinearSliderPos (lastValueMax),
  39529. style,
  39530. *this);
  39531. }
  39532. if (style == LinearBar && valueBox == 0)
  39533. {
  39534. g.setColour (findColour (Slider::textBoxOutlineColourId));
  39535. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  39536. }
  39537. }
  39538. }
  39539. void Slider::resized()
  39540. {
  39541. int minXSpace = 0;
  39542. int minYSpace = 0;
  39543. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  39544. minXSpace = 30;
  39545. else
  39546. minYSpace = 15;
  39547. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  39548. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  39549. if (style == LinearBar)
  39550. {
  39551. if (valueBox != 0)
  39552. valueBox->setBounds (0, 0, getWidth(), getHeight());
  39553. }
  39554. else
  39555. {
  39556. if (textBoxPos == NoTextBox)
  39557. {
  39558. sliderRect.setBounds (0, 0, getWidth(), getHeight());
  39559. }
  39560. else if (textBoxPos == TextBoxLeft)
  39561. {
  39562. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  39563. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  39564. }
  39565. else if (textBoxPos == TextBoxRight)
  39566. {
  39567. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  39568. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  39569. }
  39570. else if (textBoxPos == TextBoxAbove)
  39571. {
  39572. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  39573. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  39574. }
  39575. else if (textBoxPos == TextBoxBelow)
  39576. {
  39577. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  39578. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  39579. }
  39580. }
  39581. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  39582. if (style == LinearBar)
  39583. {
  39584. const int barIndent = 1;
  39585. sliderRegionStart = barIndent;
  39586. sliderRegionSize = getWidth() - barIndent * 2;
  39587. sliderRect.setBounds (sliderRegionStart, barIndent,
  39588. sliderRegionSize, getHeight() - barIndent * 2);
  39589. }
  39590. else if (isHorizontal())
  39591. {
  39592. sliderRegionStart = sliderRect.getX() + indent;
  39593. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  39594. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  39595. sliderRegionSize, sliderRect.getHeight());
  39596. }
  39597. else if (isVertical())
  39598. {
  39599. sliderRegionStart = sliderRect.getY() + indent;
  39600. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  39601. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  39602. sliderRect.getWidth(), sliderRegionSize);
  39603. }
  39604. else
  39605. {
  39606. sliderRegionStart = 0;
  39607. sliderRegionSize = 100;
  39608. }
  39609. if (style == IncDecButtons)
  39610. {
  39611. Rectangle<int> buttonRect (sliderRect);
  39612. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  39613. buttonRect.expand (-2, 0);
  39614. else
  39615. buttonRect.expand (0, -2);
  39616. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  39617. if (incDecButtonsSideBySide)
  39618. {
  39619. decButton->setBounds (buttonRect.getX(),
  39620. buttonRect.getY(),
  39621. buttonRect.getWidth() / 2,
  39622. buttonRect.getHeight());
  39623. decButton->setConnectedEdges (Button::ConnectedOnRight);
  39624. incButton->setBounds (buttonRect.getCentreX(),
  39625. buttonRect.getY(),
  39626. buttonRect.getWidth() / 2,
  39627. buttonRect.getHeight());
  39628. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  39629. }
  39630. else
  39631. {
  39632. incButton->setBounds (buttonRect.getX(),
  39633. buttonRect.getY(),
  39634. buttonRect.getWidth(),
  39635. buttonRect.getHeight() / 2);
  39636. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  39637. decButton->setBounds (buttonRect.getX(),
  39638. buttonRect.getCentreY(),
  39639. buttonRect.getWidth(),
  39640. buttonRect.getHeight() / 2);
  39641. decButton->setConnectedEdges (Button::ConnectedOnTop);
  39642. }
  39643. }
  39644. }
  39645. void Slider::focusOfChildComponentChanged (FocusChangeType)
  39646. {
  39647. repaint();
  39648. }
  39649. void Slider::mouseDown (const MouseEvent& e)
  39650. {
  39651. mouseWasHidden = false;
  39652. incDecDragged = false;
  39653. mouseXWhenLastDragged = e.x;
  39654. mouseYWhenLastDragged = e.y;
  39655. mouseDragStartX = e.getMouseDownX();
  39656. mouseDragStartY = e.getMouseDownY();
  39657. if (isEnabled())
  39658. {
  39659. if (e.mods.isPopupMenu() && menuEnabled)
  39660. {
  39661. menuShown = true;
  39662. PopupMenu m;
  39663. m.setLookAndFeel (&getLookAndFeel());
  39664. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  39665. m.addSeparator();
  39666. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39667. {
  39668. PopupMenu rotaryMenu;
  39669. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  39670. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  39671. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  39672. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  39673. }
  39674. const int r = m.show();
  39675. if (r == 1)
  39676. {
  39677. setVelocityBasedMode (! isVelocityBased);
  39678. }
  39679. else if (r == 2)
  39680. {
  39681. setSliderStyle (Rotary);
  39682. }
  39683. else if (r == 3)
  39684. {
  39685. setSliderStyle (RotaryHorizontalDrag);
  39686. }
  39687. else if (r == 4)
  39688. {
  39689. setSliderStyle (RotaryVerticalDrag);
  39690. }
  39691. }
  39692. else if (maximum > minimum)
  39693. {
  39694. menuShown = false;
  39695. if (valueBox != 0)
  39696. valueBox->hideEditor (true);
  39697. sliderBeingDragged = 0;
  39698. if (style == TwoValueHorizontal
  39699. || style == TwoValueVertical
  39700. || style == ThreeValueHorizontal
  39701. || style == ThreeValueVertical)
  39702. {
  39703. const float mousePos = (float) (isVertical() ? e.y : e.x);
  39704. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  39705. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  39706. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  39707. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39708. {
  39709. if (maxPosDistance <= minPosDistance)
  39710. sliderBeingDragged = 2;
  39711. else
  39712. sliderBeingDragged = 1;
  39713. }
  39714. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  39715. {
  39716. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  39717. sliderBeingDragged = 1;
  39718. else if (normalPosDistance >= maxPosDistance)
  39719. sliderBeingDragged = 2;
  39720. }
  39721. }
  39722. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  39723. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  39724. * valueToProportionOfLength (currentValue.getValue());
  39725. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  39726. : ((sliderBeingDragged == 1) ? valueMin
  39727. : currentValue)).getValue();
  39728. valueOnMouseDown = valueWhenLastDragged;
  39729. if (popupDisplayEnabled)
  39730. {
  39731. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  39732. popupDisplay = popup;
  39733. if (parentForPopupDisplay != 0)
  39734. {
  39735. parentForPopupDisplay->addChildComponent (popup);
  39736. }
  39737. else
  39738. {
  39739. popup->addToDesktop (0);
  39740. }
  39741. popup->setVisible (true);
  39742. }
  39743. sendDragStart();
  39744. mouseDrag (e);
  39745. }
  39746. }
  39747. }
  39748. void Slider::mouseUp (const MouseEvent&)
  39749. {
  39750. if (isEnabled()
  39751. && (! menuShown)
  39752. && (maximum > minimum)
  39753. && (style != IncDecButtons || incDecDragged))
  39754. {
  39755. restoreMouseIfHidden();
  39756. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  39757. triggerChangeMessage (false);
  39758. sendDragEnd();
  39759. popupDisplay = 0;
  39760. if (style == IncDecButtons)
  39761. {
  39762. incButton->setState (Button::buttonNormal);
  39763. decButton->setState (Button::buttonNormal);
  39764. }
  39765. }
  39766. }
  39767. void Slider::restoreMouseIfHidden()
  39768. {
  39769. if (mouseWasHidden)
  39770. {
  39771. mouseWasHidden = false;
  39772. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  39773. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  39774. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  39775. : ((sliderBeingDragged == 1) ? getMinValue()
  39776. : (double) currentValue.getValue());
  39777. Point<int> mousePos;
  39778. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39779. {
  39780. mousePos = Desktop::getLastMouseDownPosition();
  39781. if (style == RotaryHorizontalDrag)
  39782. {
  39783. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  39784. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  39785. }
  39786. else
  39787. {
  39788. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  39789. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  39790. }
  39791. }
  39792. else
  39793. {
  39794. const int pixelPos = (int) getLinearSliderPos (pos);
  39795. mousePos = relativePositionToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  39796. isVertical() ? pixelPos : (getHeight() / 2)));
  39797. }
  39798. Desktop::setMousePosition (mousePos);
  39799. }
  39800. }
  39801. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  39802. {
  39803. if (isEnabled()
  39804. && style != IncDecButtons
  39805. && style != Rotary
  39806. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  39807. {
  39808. restoreMouseIfHidden();
  39809. }
  39810. }
  39811. static double smallestAngleBetween (double a1, double a2)
  39812. {
  39813. return jmin (std::abs (a1 - a2),
  39814. std::abs (a1 + double_Pi * 2.0 - a2),
  39815. std::abs (a2 + double_Pi * 2.0 - a1));
  39816. }
  39817. void Slider::mouseDrag (const MouseEvent& e)
  39818. {
  39819. if (isEnabled()
  39820. && (! menuShown)
  39821. && (maximum > minimum))
  39822. {
  39823. if (style == Rotary)
  39824. {
  39825. int dx = e.x - sliderRect.getCentreX();
  39826. int dy = e.y - sliderRect.getCentreY();
  39827. if (dx * dx + dy * dy > 25)
  39828. {
  39829. double angle = std::atan2 ((double) dx, (double) -dy);
  39830. while (angle < 0.0)
  39831. angle += double_Pi * 2.0;
  39832. if (rotaryStop && ! e.mouseWasClicked())
  39833. {
  39834. if (std::abs (angle - lastAngle) > double_Pi)
  39835. {
  39836. if (angle >= lastAngle)
  39837. angle -= double_Pi * 2.0;
  39838. else
  39839. angle += double_Pi * 2.0;
  39840. }
  39841. if (angle >= lastAngle)
  39842. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  39843. else
  39844. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  39845. }
  39846. else
  39847. {
  39848. while (angle < rotaryStart)
  39849. angle += double_Pi * 2.0;
  39850. if (angle > rotaryEnd)
  39851. {
  39852. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  39853. angle = rotaryStart;
  39854. else
  39855. angle = rotaryEnd;
  39856. }
  39857. }
  39858. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  39859. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  39860. lastAngle = angle;
  39861. }
  39862. }
  39863. else
  39864. {
  39865. if (style == LinearBar && e.mouseWasClicked()
  39866. && valueBox != 0 && valueBox->isEditable())
  39867. return;
  39868. if (style == IncDecButtons && ! incDecDragged)
  39869. {
  39870. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  39871. return;
  39872. incDecDragged = true;
  39873. mouseDragStartX = e.x;
  39874. mouseDragStartY = e.y;
  39875. }
  39876. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  39877. : false))
  39878. || ((maximum - minimum) / sliderRegionSize < interval))
  39879. {
  39880. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  39881. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  39882. if (style == RotaryHorizontalDrag
  39883. || style == RotaryVerticalDrag
  39884. || style == IncDecButtons
  39885. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  39886. && ! snapsToMousePos))
  39887. {
  39888. const int mouseDiff = (style == RotaryHorizontalDrag
  39889. || style == LinearHorizontal
  39890. || style == LinearBar
  39891. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  39892. ? e.x - mouseDragStartX
  39893. : mouseDragStartY - e.y;
  39894. double newPos = valueToProportionOfLength (valueOnMouseDown)
  39895. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  39896. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  39897. if (style == IncDecButtons)
  39898. {
  39899. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  39900. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  39901. }
  39902. }
  39903. else
  39904. {
  39905. if (isVertical())
  39906. scaledMousePos = 1.0 - scaledMousePos;
  39907. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  39908. }
  39909. }
  39910. else
  39911. {
  39912. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  39913. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  39914. ? e.x - mouseXWhenLastDragged
  39915. : e.y - mouseYWhenLastDragged;
  39916. const double maxSpeed = jmax (200, sliderRegionSize);
  39917. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  39918. if (speed != 0)
  39919. {
  39920. speed = 0.2 * velocityModeSensitivity
  39921. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  39922. + jmax (0.0, (double) (speed - velocityModeThreshold))
  39923. / maxSpeed))));
  39924. if (mouseDiff < 0)
  39925. speed = -speed;
  39926. if (isVertical() || style == RotaryVerticalDrag
  39927. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  39928. speed = -speed;
  39929. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  39930. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  39931. e.source.enableUnboundedMouseMovement (true, false);
  39932. mouseWasHidden = true;
  39933. }
  39934. }
  39935. }
  39936. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  39937. if (sliderBeingDragged == 0)
  39938. {
  39939. setValue (snapValue (valueWhenLastDragged, true),
  39940. ! sendChangeOnlyOnRelease, true);
  39941. }
  39942. else if (sliderBeingDragged == 1)
  39943. {
  39944. setMinValue (snapValue (valueWhenLastDragged, true),
  39945. ! sendChangeOnlyOnRelease, false, true);
  39946. if (e.mods.isShiftDown())
  39947. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  39948. else
  39949. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  39950. }
  39951. else
  39952. {
  39953. jassert (sliderBeingDragged == 2);
  39954. setMaxValue (snapValue (valueWhenLastDragged, true),
  39955. ! sendChangeOnlyOnRelease, false, true);
  39956. if (e.mods.isShiftDown())
  39957. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  39958. else
  39959. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  39960. }
  39961. mouseXWhenLastDragged = e.x;
  39962. mouseYWhenLastDragged = e.y;
  39963. }
  39964. }
  39965. void Slider::mouseDoubleClick (const MouseEvent&)
  39966. {
  39967. if (doubleClickToValue
  39968. && isEnabled()
  39969. && style != IncDecButtons
  39970. && minimum <= doubleClickReturnValue
  39971. && maximum >= doubleClickReturnValue)
  39972. {
  39973. sendDragStart();
  39974. setValue (doubleClickReturnValue, true, true);
  39975. sendDragEnd();
  39976. }
  39977. }
  39978. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39979. {
  39980. if (scrollWheelEnabled && isEnabled()
  39981. && style != TwoValueHorizontal
  39982. && style != TwoValueVertical)
  39983. {
  39984. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  39985. {
  39986. if (valueBox != 0)
  39987. valueBox->hideEditor (false);
  39988. const double value = (double) currentValue.getValue();
  39989. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  39990. const double currentPos = valueToProportionOfLength (value);
  39991. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  39992. double delta = (newValue != value)
  39993. ? jmax (std::abs (newValue - value), interval) : 0;
  39994. if (value > newValue)
  39995. delta = -delta;
  39996. sendDragStart();
  39997. setValue (snapValue (value + delta, false), true, true);
  39998. sendDragEnd();
  39999. }
  40000. }
  40001. else
  40002. {
  40003. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40004. }
  40005. }
  40006. void SliderListener::sliderDragStarted (Slider*)
  40007. {
  40008. }
  40009. void SliderListener::sliderDragEnded (Slider*)
  40010. {
  40011. }
  40012. END_JUCE_NAMESPACE
  40013. /*** End of inlined file: juce_Slider.cpp ***/
  40014. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  40015. BEGIN_JUCE_NAMESPACE
  40016. class DragOverlayComp : public Component
  40017. {
  40018. public:
  40019. DragOverlayComp (Image* const image_)
  40020. : image (image_)
  40021. {
  40022. image->multiplyAllAlphas (0.8f);
  40023. setAlwaysOnTop (true);
  40024. }
  40025. ~DragOverlayComp()
  40026. {
  40027. }
  40028. void paint (Graphics& g)
  40029. {
  40030. g.drawImageAt (image, 0, 0);
  40031. }
  40032. private:
  40033. ScopedPointer <Image> image;
  40034. DragOverlayComp (const DragOverlayComp&);
  40035. DragOverlayComp& operator= (const DragOverlayComp&);
  40036. };
  40037. TableHeaderComponent::TableHeaderComponent()
  40038. : columnsChanged (false),
  40039. columnsResized (false),
  40040. sortChanged (false),
  40041. menuActive (true),
  40042. stretchToFit (false),
  40043. columnIdBeingResized (0),
  40044. columnIdBeingDragged (0),
  40045. columnIdUnderMouse (0),
  40046. lastDeliberateWidth (0)
  40047. {
  40048. }
  40049. TableHeaderComponent::~TableHeaderComponent()
  40050. {
  40051. dragOverlayComp = 0;
  40052. }
  40053. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  40054. {
  40055. menuActive = hasMenu;
  40056. }
  40057. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  40058. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  40059. {
  40060. if (onlyCountVisibleColumns)
  40061. {
  40062. int num = 0;
  40063. for (int i = columns.size(); --i >= 0;)
  40064. if (columns.getUnchecked(i)->isVisible())
  40065. ++num;
  40066. return num;
  40067. }
  40068. else
  40069. {
  40070. return columns.size();
  40071. }
  40072. }
  40073. const String TableHeaderComponent::getColumnName (const int columnId) const
  40074. {
  40075. const ColumnInfo* const ci = getInfoForId (columnId);
  40076. return ci != 0 ? ci->name : String::empty;
  40077. }
  40078. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  40079. {
  40080. ColumnInfo* const ci = getInfoForId (columnId);
  40081. if (ci != 0 && ci->name != newName)
  40082. {
  40083. ci->name = newName;
  40084. sendColumnsChanged();
  40085. }
  40086. }
  40087. void TableHeaderComponent::addColumn (const String& columnName,
  40088. const int columnId,
  40089. const int width,
  40090. const int minimumWidth,
  40091. const int maximumWidth,
  40092. const int propertyFlags,
  40093. const int insertIndex)
  40094. {
  40095. // can't have a duplicate or null ID!
  40096. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  40097. jassert (width > 0);
  40098. ColumnInfo* const ci = new ColumnInfo();
  40099. ci->name = columnName;
  40100. ci->id = columnId;
  40101. ci->width = width;
  40102. ci->lastDeliberateWidth = width;
  40103. ci->minimumWidth = minimumWidth;
  40104. ci->maximumWidth = maximumWidth;
  40105. if (ci->maximumWidth < 0)
  40106. ci->maximumWidth = std::numeric_limits<int>::max();
  40107. jassert (ci->maximumWidth >= ci->minimumWidth);
  40108. ci->propertyFlags = propertyFlags;
  40109. columns.insert (insertIndex, ci);
  40110. sendColumnsChanged();
  40111. }
  40112. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  40113. {
  40114. const int index = getIndexOfColumnId (columnIdToRemove, false);
  40115. if (index >= 0)
  40116. {
  40117. columns.remove (index);
  40118. sortChanged = true;
  40119. sendColumnsChanged();
  40120. }
  40121. }
  40122. void TableHeaderComponent::removeAllColumns()
  40123. {
  40124. if (columns.size() > 0)
  40125. {
  40126. columns.clear();
  40127. sendColumnsChanged();
  40128. }
  40129. }
  40130. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  40131. {
  40132. const int currentIndex = getIndexOfColumnId (columnId, false);
  40133. newIndex = visibleIndexToTotalIndex (newIndex);
  40134. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  40135. {
  40136. columns.move (currentIndex, newIndex);
  40137. sendColumnsChanged();
  40138. }
  40139. }
  40140. int TableHeaderComponent::getColumnWidth (const int columnId) const
  40141. {
  40142. const ColumnInfo* const ci = getInfoForId (columnId);
  40143. return ci != 0 ? ci->width : 0;
  40144. }
  40145. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  40146. {
  40147. ColumnInfo* const ci = getInfoForId (columnId);
  40148. if (ci != 0 && ci->width != newWidth)
  40149. {
  40150. const int numColumns = getNumColumns (true);
  40151. ci->lastDeliberateWidth = ci->width
  40152. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  40153. if (stretchToFit)
  40154. {
  40155. const int index = getIndexOfColumnId (columnId, true) + 1;
  40156. if (((unsigned int) index) < (unsigned int) numColumns)
  40157. {
  40158. const int x = getColumnPosition (index).getX();
  40159. if (lastDeliberateWidth == 0)
  40160. lastDeliberateWidth = getTotalWidth();
  40161. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  40162. }
  40163. }
  40164. repaint();
  40165. columnsResized = true;
  40166. triggerAsyncUpdate();
  40167. }
  40168. }
  40169. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  40170. {
  40171. int n = 0;
  40172. for (int i = 0; i < columns.size(); ++i)
  40173. {
  40174. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  40175. {
  40176. if (columns.getUnchecked(i)->id == columnId)
  40177. return n;
  40178. ++n;
  40179. }
  40180. }
  40181. return -1;
  40182. }
  40183. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  40184. {
  40185. if (onlyCountVisibleColumns)
  40186. index = visibleIndexToTotalIndex (index);
  40187. const ColumnInfo* const ci = columns [index];
  40188. return (ci != 0) ? ci->id : 0;
  40189. }
  40190. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  40191. {
  40192. int x = 0, width = 0, n = 0;
  40193. for (int i = 0; i < columns.size(); ++i)
  40194. {
  40195. x += width;
  40196. if (columns.getUnchecked(i)->isVisible())
  40197. {
  40198. width = columns.getUnchecked(i)->width;
  40199. if (n++ == index)
  40200. break;
  40201. }
  40202. else
  40203. {
  40204. width = 0;
  40205. }
  40206. }
  40207. return Rectangle<int> (x, 0, width, getHeight());
  40208. }
  40209. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  40210. {
  40211. if (xToFind >= 0)
  40212. {
  40213. int x = 0;
  40214. for (int i = 0; i < columns.size(); ++i)
  40215. {
  40216. const ColumnInfo* const ci = columns.getUnchecked(i);
  40217. if (ci->isVisible())
  40218. {
  40219. x += ci->width;
  40220. if (xToFind < x)
  40221. return ci->id;
  40222. }
  40223. }
  40224. }
  40225. return 0;
  40226. }
  40227. int TableHeaderComponent::getTotalWidth() const
  40228. {
  40229. int w = 0;
  40230. for (int i = columns.size(); --i >= 0;)
  40231. if (columns.getUnchecked(i)->isVisible())
  40232. w += columns.getUnchecked(i)->width;
  40233. return w;
  40234. }
  40235. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  40236. {
  40237. stretchToFit = shouldStretchToFit;
  40238. lastDeliberateWidth = getTotalWidth();
  40239. resized();
  40240. }
  40241. bool TableHeaderComponent::isStretchToFitActive() const
  40242. {
  40243. return stretchToFit;
  40244. }
  40245. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  40246. {
  40247. if (stretchToFit && getWidth() > 0
  40248. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  40249. {
  40250. lastDeliberateWidth = targetTotalWidth;
  40251. resizeColumnsToFit (0, targetTotalWidth);
  40252. }
  40253. }
  40254. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  40255. {
  40256. targetTotalWidth = jmax (targetTotalWidth, 0);
  40257. StretchableObjectResizer sor;
  40258. int i;
  40259. for (i = firstColumnIndex; i < columns.size(); ++i)
  40260. {
  40261. ColumnInfo* const ci = columns.getUnchecked(i);
  40262. if (ci->isVisible())
  40263. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  40264. }
  40265. sor.resizeToFit (targetTotalWidth);
  40266. int visIndex = 0;
  40267. for (i = firstColumnIndex; i < columns.size(); ++i)
  40268. {
  40269. ColumnInfo* const ci = columns.getUnchecked(i);
  40270. if (ci->isVisible())
  40271. {
  40272. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  40273. (int) std::floor (sor.getItemSize (visIndex++)));
  40274. if (newWidth != ci->width)
  40275. {
  40276. ci->width = newWidth;
  40277. repaint();
  40278. columnsResized = true;
  40279. triggerAsyncUpdate();
  40280. }
  40281. }
  40282. }
  40283. }
  40284. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  40285. {
  40286. ColumnInfo* const ci = getInfoForId (columnId);
  40287. if (ci != 0 && shouldBeVisible != ci->isVisible())
  40288. {
  40289. if (shouldBeVisible)
  40290. ci->propertyFlags |= visible;
  40291. else
  40292. ci->propertyFlags &= ~visible;
  40293. sendColumnsChanged();
  40294. resized();
  40295. }
  40296. }
  40297. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  40298. {
  40299. const ColumnInfo* const ci = getInfoForId (columnId);
  40300. return ci != 0 && ci->isVisible();
  40301. }
  40302. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  40303. {
  40304. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  40305. {
  40306. for (int i = columns.size(); --i >= 0;)
  40307. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  40308. ColumnInfo* const ci = getInfoForId (columnId);
  40309. if (ci != 0)
  40310. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  40311. reSortTable();
  40312. }
  40313. }
  40314. int TableHeaderComponent::getSortColumnId() const
  40315. {
  40316. for (int i = columns.size(); --i >= 0;)
  40317. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40318. return columns.getUnchecked(i)->id;
  40319. return 0;
  40320. }
  40321. bool TableHeaderComponent::isSortedForwards() const
  40322. {
  40323. for (int i = columns.size(); --i >= 0;)
  40324. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40325. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  40326. return true;
  40327. }
  40328. void TableHeaderComponent::reSortTable()
  40329. {
  40330. sortChanged = true;
  40331. repaint();
  40332. triggerAsyncUpdate();
  40333. }
  40334. const String TableHeaderComponent::toString() const
  40335. {
  40336. String s;
  40337. XmlElement doc ("TABLELAYOUT");
  40338. doc.setAttribute ("sortedCol", getSortColumnId());
  40339. doc.setAttribute ("sortForwards", isSortedForwards());
  40340. for (int i = 0; i < columns.size(); ++i)
  40341. {
  40342. const ColumnInfo* const ci = columns.getUnchecked (i);
  40343. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  40344. e->setAttribute ("id", ci->id);
  40345. e->setAttribute ("visible", ci->isVisible());
  40346. e->setAttribute ("width", ci->width);
  40347. }
  40348. return doc.createDocument (String::empty, true, false);
  40349. }
  40350. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  40351. {
  40352. XmlDocument doc (storedVersion);
  40353. ScopedPointer <XmlElement> storedXml (doc.getDocumentElement());
  40354. int index = 0;
  40355. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  40356. {
  40357. forEachXmlChildElement (*storedXml, col)
  40358. {
  40359. const int tabId = col->getIntAttribute ("id");
  40360. ColumnInfo* const ci = getInfoForId (tabId);
  40361. if (ci != 0)
  40362. {
  40363. columns.move (columns.indexOf (ci), index);
  40364. ci->width = col->getIntAttribute ("width");
  40365. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  40366. }
  40367. ++index;
  40368. }
  40369. columnsResized = true;
  40370. sendColumnsChanged();
  40371. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  40372. storedXml->getBoolAttribute ("sortForwards", true));
  40373. }
  40374. }
  40375. void TableHeaderComponent::addListener (TableHeaderListener* const newListener)
  40376. {
  40377. listeners.addIfNotAlreadyThere (newListener);
  40378. }
  40379. void TableHeaderComponent::removeListener (TableHeaderListener* const listenerToRemove)
  40380. {
  40381. listeners.removeValue (listenerToRemove);
  40382. }
  40383. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  40384. {
  40385. const ColumnInfo* const ci = getInfoForId (columnId);
  40386. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  40387. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  40388. }
  40389. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  40390. {
  40391. for (int i = 0; i < columns.size(); ++i)
  40392. {
  40393. const ColumnInfo* const ci = columns.getUnchecked(i);
  40394. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  40395. menu.addItem (ci->id, ci->name,
  40396. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  40397. isColumnVisible (ci->id));
  40398. }
  40399. }
  40400. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  40401. {
  40402. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  40403. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  40404. }
  40405. void TableHeaderComponent::paint (Graphics& g)
  40406. {
  40407. LookAndFeel& lf = getLookAndFeel();
  40408. lf.drawTableHeaderBackground (g, *this);
  40409. const Rectangle<int> clip (g.getClipBounds());
  40410. int x = 0;
  40411. for (int i = 0; i < columns.size(); ++i)
  40412. {
  40413. const ColumnInfo* const ci = columns.getUnchecked(i);
  40414. if (ci->isVisible())
  40415. {
  40416. if (x + ci->width > clip.getX()
  40417. && (ci->id != columnIdBeingDragged
  40418. || dragOverlayComp == 0
  40419. || ! dragOverlayComp->isVisible()))
  40420. {
  40421. g.saveState();
  40422. g.setOrigin (x, 0);
  40423. g.reduceClipRegion (0, 0, ci->width, getHeight());
  40424. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  40425. ci->id == columnIdUnderMouse,
  40426. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  40427. ci->propertyFlags);
  40428. g.restoreState();
  40429. }
  40430. x += ci->width;
  40431. if (x >= clip.getRight())
  40432. break;
  40433. }
  40434. }
  40435. }
  40436. void TableHeaderComponent::resized()
  40437. {
  40438. }
  40439. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  40440. {
  40441. updateColumnUnderMouse (e.x, e.y);
  40442. }
  40443. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  40444. {
  40445. updateColumnUnderMouse (e.x, e.y);
  40446. }
  40447. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  40448. {
  40449. updateColumnUnderMouse (e.x, e.y);
  40450. }
  40451. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  40452. {
  40453. repaint();
  40454. columnIdBeingResized = 0;
  40455. columnIdBeingDragged = 0;
  40456. if (columnIdUnderMouse != 0)
  40457. {
  40458. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  40459. if (e.mods.isPopupMenu())
  40460. columnClicked (columnIdUnderMouse, e.mods);
  40461. }
  40462. if (menuActive && e.mods.isPopupMenu())
  40463. showColumnChooserMenu (columnIdUnderMouse);
  40464. }
  40465. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  40466. {
  40467. if (columnIdBeingResized == 0
  40468. && columnIdBeingDragged == 0
  40469. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  40470. {
  40471. dragOverlayComp = 0;
  40472. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  40473. if (columnIdBeingResized != 0)
  40474. {
  40475. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  40476. initialColumnWidth = ci->width;
  40477. }
  40478. else
  40479. {
  40480. beginDrag (e);
  40481. }
  40482. }
  40483. if (columnIdBeingResized != 0)
  40484. {
  40485. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  40486. if (ci != 0)
  40487. {
  40488. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  40489. initialColumnWidth + e.getDistanceFromDragStartX());
  40490. if (stretchToFit)
  40491. {
  40492. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  40493. int minWidthOnRight = 0;
  40494. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  40495. if (columns.getUnchecked (i)->isVisible())
  40496. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  40497. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  40498. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  40499. }
  40500. setColumnWidth (columnIdBeingResized, w);
  40501. }
  40502. }
  40503. else if (columnIdBeingDragged != 0)
  40504. {
  40505. if (e.y >= -50 && e.y < getHeight() + 50)
  40506. {
  40507. if (dragOverlayComp != 0)
  40508. {
  40509. dragOverlayComp->setVisible (true);
  40510. dragOverlayComp->setBounds (jlimit (0,
  40511. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  40512. e.x - draggingColumnOffset),
  40513. 0,
  40514. dragOverlayComp->getWidth(),
  40515. getHeight());
  40516. for (int i = columns.size(); --i >= 0;)
  40517. {
  40518. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  40519. int newIndex = currentIndex;
  40520. if (newIndex > 0)
  40521. {
  40522. // if the previous column isn't draggable, we can't move our column
  40523. // past it, because that'd change the undraggable column's position..
  40524. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  40525. if ((previous->propertyFlags & draggable) != 0)
  40526. {
  40527. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  40528. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  40529. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  40530. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  40531. {
  40532. --newIndex;
  40533. }
  40534. }
  40535. }
  40536. if (newIndex < columns.size() - 1)
  40537. {
  40538. // if the next column isn't draggable, we can't move our column
  40539. // past it, because that'd change the undraggable column's position..
  40540. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  40541. if ((nextCol->propertyFlags & draggable) != 0)
  40542. {
  40543. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  40544. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  40545. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  40546. > abs (dragOverlayComp->getRight() - rightOfNext))
  40547. {
  40548. ++newIndex;
  40549. }
  40550. }
  40551. }
  40552. if (newIndex != currentIndex)
  40553. moveColumn (columnIdBeingDragged, newIndex);
  40554. else
  40555. break;
  40556. }
  40557. }
  40558. }
  40559. else
  40560. {
  40561. endDrag (draggingColumnOriginalIndex);
  40562. }
  40563. }
  40564. }
  40565. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  40566. {
  40567. if (columnIdBeingDragged == 0)
  40568. {
  40569. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  40570. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  40571. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  40572. {
  40573. columnIdBeingDragged = 0;
  40574. }
  40575. else
  40576. {
  40577. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  40578. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  40579. const int temp = columnIdBeingDragged;
  40580. columnIdBeingDragged = 0;
  40581. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  40582. columnIdBeingDragged = temp;
  40583. dragOverlayComp->setBounds (columnRect);
  40584. for (int i = listeners.size(); --i >= 0;)
  40585. {
  40586. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  40587. i = jmin (i, listeners.size() - 1);
  40588. }
  40589. }
  40590. }
  40591. }
  40592. void TableHeaderComponent::endDrag (const int finalIndex)
  40593. {
  40594. if (columnIdBeingDragged != 0)
  40595. {
  40596. moveColumn (columnIdBeingDragged, finalIndex);
  40597. columnIdBeingDragged = 0;
  40598. repaint();
  40599. for (int i = listeners.size(); --i >= 0;)
  40600. {
  40601. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  40602. i = jmin (i, listeners.size() - 1);
  40603. }
  40604. }
  40605. }
  40606. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  40607. {
  40608. mouseDrag (e);
  40609. for (int i = columns.size(); --i >= 0;)
  40610. if (columns.getUnchecked (i)->isVisible())
  40611. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  40612. columnIdBeingResized = 0;
  40613. repaint();
  40614. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  40615. updateColumnUnderMouse (e.x, e.y);
  40616. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  40617. columnClicked (columnIdUnderMouse, e.mods);
  40618. dragOverlayComp = 0;
  40619. }
  40620. const MouseCursor TableHeaderComponent::getMouseCursor()
  40621. {
  40622. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  40623. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  40624. return Component::getMouseCursor();
  40625. }
  40626. bool TableHeaderComponent::ColumnInfo::isVisible() const
  40627. {
  40628. return (propertyFlags & TableHeaderComponent::visible) != 0;
  40629. }
  40630. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  40631. {
  40632. for (int i = columns.size(); --i >= 0;)
  40633. if (columns.getUnchecked(i)->id == id)
  40634. return columns.getUnchecked(i);
  40635. return 0;
  40636. }
  40637. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  40638. {
  40639. int n = 0;
  40640. for (int i = 0; i < columns.size(); ++i)
  40641. {
  40642. if (columns.getUnchecked(i)->isVisible())
  40643. {
  40644. if (n == visibleIndex)
  40645. return i;
  40646. ++n;
  40647. }
  40648. }
  40649. return -1;
  40650. }
  40651. void TableHeaderComponent::sendColumnsChanged()
  40652. {
  40653. if (stretchToFit && lastDeliberateWidth > 0)
  40654. resizeAllColumnsToFit (lastDeliberateWidth);
  40655. repaint();
  40656. columnsChanged = true;
  40657. triggerAsyncUpdate();
  40658. }
  40659. void TableHeaderComponent::handleAsyncUpdate()
  40660. {
  40661. const bool changed = columnsChanged || sortChanged;
  40662. const bool sized = columnsResized || changed;
  40663. const bool sorted = sortChanged;
  40664. columnsChanged = false;
  40665. columnsResized = false;
  40666. sortChanged = false;
  40667. if (sorted)
  40668. {
  40669. for (int i = listeners.size(); --i >= 0;)
  40670. {
  40671. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  40672. i = jmin (i, listeners.size() - 1);
  40673. }
  40674. }
  40675. if (changed)
  40676. {
  40677. for (int i = listeners.size(); --i >= 0;)
  40678. {
  40679. listeners.getUnchecked(i)->tableColumnsChanged (this);
  40680. i = jmin (i, listeners.size() - 1);
  40681. }
  40682. }
  40683. if (sized)
  40684. {
  40685. for (int i = listeners.size(); --i >= 0;)
  40686. {
  40687. listeners.getUnchecked(i)->tableColumnsResized (this);
  40688. i = jmin (i, listeners.size() - 1);
  40689. }
  40690. }
  40691. }
  40692. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  40693. {
  40694. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  40695. {
  40696. const int draggableDistance = 3;
  40697. int x = 0;
  40698. for (int i = 0; i < columns.size(); ++i)
  40699. {
  40700. const ColumnInfo* const ci = columns.getUnchecked(i);
  40701. if (ci->isVisible())
  40702. {
  40703. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  40704. && (ci->propertyFlags & resizable) != 0)
  40705. return ci->id;
  40706. x += ci->width;
  40707. }
  40708. }
  40709. }
  40710. return 0;
  40711. }
  40712. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  40713. {
  40714. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  40715. ? getColumnIdAtX (x) : 0;
  40716. if (newCol != columnIdUnderMouse)
  40717. {
  40718. columnIdUnderMouse = newCol;
  40719. repaint();
  40720. }
  40721. }
  40722. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  40723. {
  40724. PopupMenu m;
  40725. addMenuItems (m, columnIdClicked);
  40726. if (m.getNumItems() > 0)
  40727. {
  40728. m.setLookAndFeel (&getLookAndFeel());
  40729. const int result = m.show();
  40730. if (result != 0)
  40731. reactToMenuItem (result, columnIdClicked);
  40732. }
  40733. }
  40734. void TableHeaderListener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  40735. {
  40736. }
  40737. END_JUCE_NAMESPACE
  40738. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  40739. /*** Start of inlined file: juce_TableListBox.cpp ***/
  40740. BEGIN_JUCE_NAMESPACE
  40741. static const char* const tableColumnPropertyTag = "_tableColumnID";
  40742. class TableListRowComp : public Component,
  40743. public TooltipClient
  40744. {
  40745. public:
  40746. TableListRowComp (TableListBox& owner_)
  40747. : owner (owner_),
  40748. row (-1),
  40749. isSelected (false)
  40750. {
  40751. }
  40752. ~TableListRowComp()
  40753. {
  40754. deleteAllChildren();
  40755. }
  40756. void paint (Graphics& g)
  40757. {
  40758. TableListBoxModel* const model = owner.getModel();
  40759. if (model != 0)
  40760. {
  40761. const TableHeaderComponent* const header = owner.getHeader();
  40762. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  40763. const int numColumns = header->getNumColumns (true);
  40764. for (int i = 0; i < numColumns; ++i)
  40765. {
  40766. if (! columnsWithComponents [i])
  40767. {
  40768. const int columnId = header->getColumnIdOfIndex (i, true);
  40769. Rectangle<int> columnRect (header->getColumnPosition (i));
  40770. columnRect.setSize (columnRect.getWidth(), getHeight());
  40771. g.saveState();
  40772. g.reduceClipRegion (columnRect);
  40773. g.setOrigin (columnRect.getX(), 0);
  40774. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  40775. g.restoreState();
  40776. }
  40777. }
  40778. }
  40779. }
  40780. void update (const int newRow, const bool isNowSelected)
  40781. {
  40782. if (newRow != row || isNowSelected != isSelected)
  40783. {
  40784. row = newRow;
  40785. isSelected = isNowSelected;
  40786. repaint();
  40787. }
  40788. if (row < owner.getNumRows())
  40789. {
  40790. jassert (row >= 0);
  40791. const var::identifier tagPropertyName ("_tableLastUseNum");
  40792. const int newTag = Random::getSystemRandom().nextInt();
  40793. const TableHeaderComponent* const header = owner.getHeader();
  40794. const int numColumns = header->getNumColumns (true);
  40795. int i;
  40796. columnsWithComponents.clear();
  40797. if (owner.getModel() != 0)
  40798. {
  40799. for (i = 0; i < numColumns; ++i)
  40800. {
  40801. const int columnId = header->getColumnIdOfIndex (i, true);
  40802. Component* const newComp
  40803. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  40804. findChildComponentForColumn (columnId));
  40805. if (newComp != 0)
  40806. {
  40807. addAndMakeVisible (newComp);
  40808. newComp->getProperties().set (tagPropertyName, newTag);
  40809. newComp->getProperties().set (tableColumnPropertyTag, columnId);
  40810. const Rectangle<int> columnRect (header->getColumnPosition (i));
  40811. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  40812. columnsWithComponents.setBit (i);
  40813. }
  40814. }
  40815. }
  40816. for (i = getNumChildComponents(); --i >= 0;)
  40817. {
  40818. Component* const c = getChildComponent (i);
  40819. if ((int) c->getProperties() [tagPropertyName] != newTag)
  40820. delete c;
  40821. }
  40822. }
  40823. else
  40824. {
  40825. columnsWithComponents.clear();
  40826. deleteAllChildren();
  40827. }
  40828. }
  40829. void resized()
  40830. {
  40831. for (int i = getNumChildComponents(); --i >= 0;)
  40832. {
  40833. Component* const c = getChildComponent (i);
  40834. const int columnId = c->getProperties() [tableColumnPropertyTag];
  40835. if (columnId != 0)
  40836. {
  40837. const Rectangle<int> columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  40838. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  40839. }
  40840. }
  40841. }
  40842. void mouseDown (const MouseEvent& e)
  40843. {
  40844. isDragging = false;
  40845. selectRowOnMouseUp = false;
  40846. if (isEnabled())
  40847. {
  40848. if (! isSelected)
  40849. {
  40850. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  40851. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  40852. if (columnId != 0 && owner.getModel() != 0)
  40853. owner.getModel()->cellClicked (row, columnId, e);
  40854. }
  40855. else
  40856. {
  40857. selectRowOnMouseUp = true;
  40858. }
  40859. }
  40860. }
  40861. void mouseDrag (const MouseEvent& e)
  40862. {
  40863. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  40864. {
  40865. const SparseSet<int> selectedRows (owner.getSelectedRows());
  40866. if (selectedRows.size() > 0)
  40867. {
  40868. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  40869. if (dragDescription.isNotEmpty())
  40870. {
  40871. isDragging = true;
  40872. owner.startDragAndDrop (e, dragDescription);
  40873. }
  40874. }
  40875. }
  40876. }
  40877. void mouseUp (const MouseEvent& e)
  40878. {
  40879. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  40880. {
  40881. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  40882. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  40883. if (columnId != 0 && owner.getModel() != 0)
  40884. owner.getModel()->cellClicked (row, columnId, e);
  40885. }
  40886. }
  40887. void mouseDoubleClick (const MouseEvent& e)
  40888. {
  40889. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  40890. if (columnId != 0 && owner.getModel() != 0)
  40891. owner.getModel()->cellDoubleClicked (row, columnId, e);
  40892. }
  40893. const String getTooltip()
  40894. {
  40895. const int columnId = owner.getHeader()->getColumnIdAtX (getMouseXYRelative().getX());
  40896. if (columnId != 0 && owner.getModel() != 0)
  40897. return owner.getModel()->getCellTooltip (row, columnId);
  40898. return String::empty;
  40899. }
  40900. juce_UseDebuggingNewOperator
  40901. private:
  40902. TableListBox& owner;
  40903. int row;
  40904. bool isSelected, isDragging, selectRowOnMouseUp;
  40905. BigInteger columnsWithComponents;
  40906. Component* findChildComponentForColumn (const int columnId) const
  40907. {
  40908. for (int i = getNumChildComponents(); --i >= 0;)
  40909. {
  40910. Component* const c = getChildComponent (i);
  40911. if ((int) c->getProperties() [tableColumnPropertyTag] == columnId)
  40912. return c;
  40913. }
  40914. return 0;
  40915. }
  40916. TableListRowComp (const TableListRowComp&);
  40917. TableListRowComp& operator= (const TableListRowComp&);
  40918. };
  40919. class TableListBoxHeader : public TableHeaderComponent
  40920. {
  40921. public:
  40922. TableListBoxHeader (TableListBox& owner_)
  40923. : owner (owner_)
  40924. {
  40925. }
  40926. ~TableListBoxHeader()
  40927. {
  40928. }
  40929. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  40930. {
  40931. if (owner.isAutoSizeMenuOptionShown())
  40932. {
  40933. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  40934. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  40935. menu.addSeparator();
  40936. }
  40937. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  40938. }
  40939. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  40940. {
  40941. if (menuReturnId == 0xf836743)
  40942. {
  40943. owner.autoSizeColumn (columnIdClicked);
  40944. }
  40945. else if (menuReturnId == 0xf836744)
  40946. {
  40947. owner.autoSizeAllColumns();
  40948. }
  40949. else
  40950. {
  40951. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  40952. }
  40953. }
  40954. juce_UseDebuggingNewOperator
  40955. private:
  40956. TableListBox& owner;
  40957. TableListBoxHeader (const TableListBoxHeader&);
  40958. TableListBoxHeader& operator= (const TableListBoxHeader&);
  40959. };
  40960. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  40961. : ListBox (name, 0),
  40962. model (model_),
  40963. autoSizeOptionsShown (true)
  40964. {
  40965. ListBox::model = this;
  40966. header = new TableListBoxHeader (*this);
  40967. header->setSize (100, 28);
  40968. header->addListener (this);
  40969. setHeaderComponent (header);
  40970. }
  40971. TableListBox::~TableListBox()
  40972. {
  40973. deleteAllChildren();
  40974. }
  40975. void TableListBox::setModel (TableListBoxModel* const newModel)
  40976. {
  40977. if (model != newModel)
  40978. {
  40979. model = newModel;
  40980. updateContent();
  40981. }
  40982. }
  40983. int TableListBox::getHeaderHeight() const
  40984. {
  40985. return header->getHeight();
  40986. }
  40987. void TableListBox::setHeaderHeight (const int newHeight)
  40988. {
  40989. header->setSize (header->getWidth(), newHeight);
  40990. resized();
  40991. }
  40992. void TableListBox::autoSizeColumn (const int columnId)
  40993. {
  40994. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  40995. if (width > 0)
  40996. header->setColumnWidth (columnId, width);
  40997. }
  40998. void TableListBox::autoSizeAllColumns()
  40999. {
  41000. for (int i = 0; i < header->getNumColumns (true); ++i)
  41001. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  41002. }
  41003. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  41004. {
  41005. autoSizeOptionsShown = shouldBeShown;
  41006. }
  41007. bool TableListBox::isAutoSizeMenuOptionShown() const
  41008. {
  41009. return autoSizeOptionsShown;
  41010. }
  41011. const Rectangle<int> TableListBox::getCellPosition (const int columnId,
  41012. const int rowNumber,
  41013. const bool relativeToComponentTopLeft) const
  41014. {
  41015. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41016. if (relativeToComponentTopLeft)
  41017. headerCell.translate (header->getX(), 0);
  41018. const Rectangle<int> row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  41019. return Rectangle<int> (headerCell.getX(), row.getY(),
  41020. headerCell.getWidth(), row.getHeight());
  41021. }
  41022. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  41023. {
  41024. ScrollBar* const scrollbar = getHorizontalScrollBar();
  41025. if (scrollbar != 0)
  41026. {
  41027. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41028. double x = scrollbar->getCurrentRangeStart();
  41029. const double w = scrollbar->getCurrentRangeSize();
  41030. if (pos.getX() < x)
  41031. x = pos.getX();
  41032. else if (pos.getRight() > x + w)
  41033. x += jmax (0.0, pos.getRight() - (x + w));
  41034. scrollbar->setCurrentRangeStart (x);
  41035. }
  41036. }
  41037. int TableListBox::getNumRows()
  41038. {
  41039. return model != 0 ? model->getNumRows() : 0;
  41040. }
  41041. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  41042. {
  41043. }
  41044. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  41045. {
  41046. if (existingComponentToUpdate == 0)
  41047. existingComponentToUpdate = new TableListRowComp (*this);
  41048. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  41049. return existingComponentToUpdate;
  41050. }
  41051. void TableListBox::selectedRowsChanged (int row)
  41052. {
  41053. if (model != 0)
  41054. model->selectedRowsChanged (row);
  41055. }
  41056. void TableListBox::deleteKeyPressed (int row)
  41057. {
  41058. if (model != 0)
  41059. model->deleteKeyPressed (row);
  41060. }
  41061. void TableListBox::returnKeyPressed (int row)
  41062. {
  41063. if (model != 0)
  41064. model->returnKeyPressed (row);
  41065. }
  41066. void TableListBox::backgroundClicked()
  41067. {
  41068. if (model != 0)
  41069. model->backgroundClicked();
  41070. }
  41071. void TableListBox::listWasScrolled()
  41072. {
  41073. if (model != 0)
  41074. model->listWasScrolled();
  41075. }
  41076. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  41077. {
  41078. setMinimumContentWidth (header->getTotalWidth());
  41079. repaint();
  41080. updateColumnComponents();
  41081. }
  41082. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  41083. {
  41084. setMinimumContentWidth (header->getTotalWidth());
  41085. repaint();
  41086. updateColumnComponents();
  41087. }
  41088. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  41089. {
  41090. if (model != 0)
  41091. model->sortOrderChanged (header->getSortColumnId(),
  41092. header->isSortedForwards());
  41093. }
  41094. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  41095. {
  41096. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  41097. repaint();
  41098. }
  41099. void TableListBox::resized()
  41100. {
  41101. ListBox::resized();
  41102. header->resizeAllColumnsToFit (getVisibleContentWidth());
  41103. setMinimumContentWidth (header->getTotalWidth());
  41104. }
  41105. void TableListBox::updateColumnComponents() const
  41106. {
  41107. const int firstRow = getRowContainingPosition (0, 0);
  41108. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  41109. {
  41110. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  41111. if (rowComp != 0)
  41112. rowComp->resized();
  41113. }
  41114. }
  41115. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  41116. {
  41117. }
  41118. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  41119. {
  41120. }
  41121. void TableListBoxModel::backgroundClicked()
  41122. {
  41123. }
  41124. void TableListBoxModel::sortOrderChanged (int, const bool)
  41125. {
  41126. }
  41127. int TableListBoxModel::getColumnAutoSizeWidth (int)
  41128. {
  41129. return 0;
  41130. }
  41131. void TableListBoxModel::selectedRowsChanged (int)
  41132. {
  41133. }
  41134. void TableListBoxModel::deleteKeyPressed (int)
  41135. {
  41136. }
  41137. void TableListBoxModel::returnKeyPressed (int)
  41138. {
  41139. }
  41140. void TableListBoxModel::listWasScrolled()
  41141. {
  41142. }
  41143. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/)
  41144. {
  41145. return String::empty;
  41146. }
  41147. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  41148. {
  41149. return String::empty;
  41150. }
  41151. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  41152. {
  41153. (void) existingComponentToUpdate;
  41154. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  41155. return 0;
  41156. }
  41157. END_JUCE_NAMESPACE
  41158. /*** End of inlined file: juce_TableListBox.cpp ***/
  41159. /*** Start of inlined file: juce_TextEditor.cpp ***/
  41160. BEGIN_JUCE_NAMESPACE
  41161. // a word or space that can't be broken down any further
  41162. struct TextAtom
  41163. {
  41164. String atomText;
  41165. float width;
  41166. uint16 numChars;
  41167. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  41168. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  41169. const String getText (const juce_wchar passwordCharacter) const
  41170. {
  41171. if (passwordCharacter == 0)
  41172. return atomText;
  41173. else
  41174. return String::repeatedString (String::charToString (passwordCharacter),
  41175. atomText.length());
  41176. }
  41177. const String getTrimmedText (const juce_wchar passwordCharacter) const
  41178. {
  41179. if (passwordCharacter == 0)
  41180. return atomText.substring (0, numChars);
  41181. else if (isNewLine())
  41182. return String::empty;
  41183. else
  41184. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  41185. }
  41186. };
  41187. // a run of text with a single font and colour
  41188. class TextEditor::UniformTextSection
  41189. {
  41190. public:
  41191. UniformTextSection (const String& text,
  41192. const Font& font_,
  41193. const Colour& colour_,
  41194. const juce_wchar passwordCharacter)
  41195. : font (font_),
  41196. colour (colour_)
  41197. {
  41198. initialiseAtoms (text, passwordCharacter);
  41199. }
  41200. UniformTextSection (const UniformTextSection& other)
  41201. : font (other.font),
  41202. colour (other.colour)
  41203. {
  41204. atoms.ensureStorageAllocated (other.atoms.size());
  41205. for (int i = 0; i < other.atoms.size(); ++i)
  41206. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  41207. }
  41208. ~UniformTextSection()
  41209. {
  41210. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  41211. }
  41212. void clear()
  41213. {
  41214. for (int i = atoms.size(); --i >= 0;)
  41215. delete getAtom(i);
  41216. atoms.clear();
  41217. }
  41218. int getNumAtoms() const
  41219. {
  41220. return atoms.size();
  41221. }
  41222. TextAtom* getAtom (const int index) const throw()
  41223. {
  41224. return atoms.getUnchecked (index);
  41225. }
  41226. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  41227. {
  41228. if (other.atoms.size() > 0)
  41229. {
  41230. TextAtom* const lastAtom = atoms.getLast();
  41231. int i = 0;
  41232. if (lastAtom != 0)
  41233. {
  41234. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  41235. {
  41236. TextAtom* const first = other.getAtom(0);
  41237. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  41238. {
  41239. lastAtom->atomText += first->atomText;
  41240. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  41241. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  41242. delete first;
  41243. ++i;
  41244. }
  41245. }
  41246. }
  41247. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  41248. while (i < other.atoms.size())
  41249. {
  41250. atoms.add (other.getAtom(i));
  41251. ++i;
  41252. }
  41253. }
  41254. }
  41255. UniformTextSection* split (const int indexToBreakAt,
  41256. const juce_wchar passwordCharacter)
  41257. {
  41258. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  41259. font, colour,
  41260. passwordCharacter);
  41261. int index = 0;
  41262. for (int i = 0; i < atoms.size(); ++i)
  41263. {
  41264. TextAtom* const atom = getAtom(i);
  41265. const int nextIndex = index + atom->numChars;
  41266. if (index == indexToBreakAt)
  41267. {
  41268. int j;
  41269. for (j = i; j < atoms.size(); ++j)
  41270. section2->atoms.add (getAtom (j));
  41271. for (j = atoms.size(); --j >= i;)
  41272. atoms.remove (j);
  41273. break;
  41274. }
  41275. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  41276. {
  41277. TextAtom* const secondAtom = new TextAtom();
  41278. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  41279. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  41280. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  41281. section2->atoms.add (secondAtom);
  41282. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  41283. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  41284. atom->numChars = (uint16) (indexToBreakAt - index);
  41285. int j;
  41286. for (j = i + 1; j < atoms.size(); ++j)
  41287. section2->atoms.add (getAtom (j));
  41288. for (j = atoms.size(); --j > i;)
  41289. atoms.remove (j);
  41290. break;
  41291. }
  41292. index = nextIndex;
  41293. }
  41294. return section2;
  41295. }
  41296. void appendAllText (String::Concatenator& concatenator) const
  41297. {
  41298. for (int i = 0; i < atoms.size(); ++i)
  41299. concatenator.append (getAtom(i)->atomText);
  41300. }
  41301. void appendSubstring (String::Concatenator& concatenator,
  41302. const Range<int>& range) const
  41303. {
  41304. int index = 0;
  41305. for (int i = 0; i < atoms.size(); ++i)
  41306. {
  41307. const TextAtom* const atom = getAtom (i);
  41308. const int nextIndex = index + atom->numChars;
  41309. if (range.getStart() < nextIndex)
  41310. {
  41311. if (range.getEnd() <= index)
  41312. break;
  41313. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  41314. if (! r.isEmpty())
  41315. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  41316. }
  41317. index = nextIndex;
  41318. }
  41319. }
  41320. int getTotalLength() const
  41321. {
  41322. int total = 0;
  41323. for (int i = atoms.size(); --i >= 0;)
  41324. total += getAtom(i)->numChars;
  41325. return total;
  41326. }
  41327. void setFont (const Font& newFont,
  41328. const juce_wchar passwordCharacter)
  41329. {
  41330. if (font != newFont)
  41331. {
  41332. font = newFont;
  41333. for (int i = atoms.size(); --i >= 0;)
  41334. {
  41335. TextAtom* const atom = atoms.getUnchecked(i);
  41336. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  41337. }
  41338. }
  41339. }
  41340. juce_UseDebuggingNewOperator
  41341. Font font;
  41342. Colour colour;
  41343. private:
  41344. Array <TextAtom*> atoms;
  41345. void initialiseAtoms (const String& textToParse,
  41346. const juce_wchar passwordCharacter)
  41347. {
  41348. int i = 0;
  41349. const int len = textToParse.length();
  41350. const juce_wchar* const text = textToParse;
  41351. while (i < len)
  41352. {
  41353. int start = i;
  41354. // create a whitespace atom unless it starts with non-ws
  41355. if (CharacterFunctions::isWhitespace (text[i])
  41356. && text[i] != '\r'
  41357. && text[i] != '\n')
  41358. {
  41359. while (i < len
  41360. && CharacterFunctions::isWhitespace (text[i])
  41361. && text[i] != '\r'
  41362. && text[i] != '\n')
  41363. {
  41364. ++i;
  41365. }
  41366. }
  41367. else
  41368. {
  41369. if (text[i] == '\r')
  41370. {
  41371. ++i;
  41372. if ((i < len) && (text[i] == '\n'))
  41373. {
  41374. ++start;
  41375. ++i;
  41376. }
  41377. }
  41378. else if (text[i] == '\n')
  41379. {
  41380. ++i;
  41381. }
  41382. else
  41383. {
  41384. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  41385. ++i;
  41386. }
  41387. }
  41388. TextAtom* const atom = new TextAtom();
  41389. atom->atomText = String (text + start, i - start);
  41390. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  41391. atom->numChars = (uint16) (i - start);
  41392. atoms.add (atom);
  41393. }
  41394. }
  41395. UniformTextSection& operator= (const UniformTextSection& other);
  41396. };
  41397. class TextEditor::Iterator
  41398. {
  41399. public:
  41400. Iterator (const Array <UniformTextSection*>& sections_,
  41401. const float wordWrapWidth_,
  41402. const juce_wchar passwordCharacter_)
  41403. : indexInText (0),
  41404. lineY (0),
  41405. lineHeight (0),
  41406. maxDescent (0),
  41407. atomX (0),
  41408. atomRight (0),
  41409. atom (0),
  41410. currentSection (0),
  41411. sections (sections_),
  41412. sectionIndex (0),
  41413. atomIndex (0),
  41414. wordWrapWidth (wordWrapWidth_),
  41415. passwordCharacter (passwordCharacter_)
  41416. {
  41417. jassert (wordWrapWidth_ > 0);
  41418. if (sections.size() > 0)
  41419. {
  41420. currentSection = sections.getUnchecked (sectionIndex);
  41421. if (currentSection != 0)
  41422. beginNewLine();
  41423. }
  41424. }
  41425. Iterator (const Iterator& other)
  41426. : indexInText (other.indexInText),
  41427. lineY (other.lineY),
  41428. lineHeight (other.lineHeight),
  41429. maxDescent (other.maxDescent),
  41430. atomX (other.atomX),
  41431. atomRight (other.atomRight),
  41432. atom (other.atom),
  41433. currentSection (other.currentSection),
  41434. sections (other.sections),
  41435. sectionIndex (other.sectionIndex),
  41436. atomIndex (other.atomIndex),
  41437. wordWrapWidth (other.wordWrapWidth),
  41438. passwordCharacter (other.passwordCharacter),
  41439. tempAtom (other.tempAtom)
  41440. {
  41441. }
  41442. ~Iterator()
  41443. {
  41444. }
  41445. bool next()
  41446. {
  41447. if (atom == &tempAtom)
  41448. {
  41449. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  41450. if (numRemaining > 0)
  41451. {
  41452. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  41453. atomX = 0;
  41454. if (tempAtom.numChars > 0)
  41455. lineY += lineHeight;
  41456. indexInText += tempAtom.numChars;
  41457. GlyphArrangement g;
  41458. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  41459. int split;
  41460. for (split = 0; split < g.getNumGlyphs(); ++split)
  41461. if (shouldWrap (g.getGlyph (split).getRight()))
  41462. break;
  41463. if (split > 0 && split <= numRemaining)
  41464. {
  41465. tempAtom.numChars = (uint16) split;
  41466. tempAtom.width = g.getGlyph (split - 1).getRight();
  41467. atomRight = atomX + tempAtom.width;
  41468. return true;
  41469. }
  41470. }
  41471. }
  41472. bool forceNewLine = false;
  41473. if (sectionIndex >= sections.size())
  41474. {
  41475. moveToEndOfLastAtom();
  41476. return false;
  41477. }
  41478. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  41479. {
  41480. if (atomIndex >= currentSection->getNumAtoms())
  41481. {
  41482. if (++sectionIndex >= sections.size())
  41483. {
  41484. moveToEndOfLastAtom();
  41485. return false;
  41486. }
  41487. atomIndex = 0;
  41488. currentSection = sections.getUnchecked (sectionIndex);
  41489. }
  41490. else
  41491. {
  41492. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  41493. if (! lastAtom->isWhitespace())
  41494. {
  41495. // handle the case where the last atom in a section is actually part of the same
  41496. // word as the first atom of the next section...
  41497. float right = atomRight + lastAtom->width;
  41498. float lineHeight2 = lineHeight;
  41499. float maxDescent2 = maxDescent;
  41500. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  41501. {
  41502. const UniformTextSection* const s = sections.getUnchecked (section);
  41503. if (s->getNumAtoms() == 0)
  41504. break;
  41505. const TextAtom* const nextAtom = s->getAtom (0);
  41506. if (nextAtom->isWhitespace())
  41507. break;
  41508. right += nextAtom->width;
  41509. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  41510. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  41511. if (shouldWrap (right))
  41512. {
  41513. lineHeight = lineHeight2;
  41514. maxDescent = maxDescent2;
  41515. forceNewLine = true;
  41516. break;
  41517. }
  41518. if (s->getNumAtoms() > 1)
  41519. break;
  41520. }
  41521. }
  41522. }
  41523. }
  41524. if (atom != 0)
  41525. {
  41526. atomX = atomRight;
  41527. indexInText += atom->numChars;
  41528. if (atom->isNewLine())
  41529. beginNewLine();
  41530. }
  41531. atom = currentSection->getAtom (atomIndex);
  41532. atomRight = atomX + atom->width;
  41533. ++atomIndex;
  41534. if (shouldWrap (atomRight) || forceNewLine)
  41535. {
  41536. if (atom->isWhitespace())
  41537. {
  41538. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  41539. atomRight = jmin (atomRight, wordWrapWidth);
  41540. }
  41541. else
  41542. {
  41543. atomRight = atom->width;
  41544. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  41545. {
  41546. tempAtom = *atom;
  41547. tempAtom.width = 0;
  41548. tempAtom.numChars = 0;
  41549. atom = &tempAtom;
  41550. if (atomX > 0)
  41551. beginNewLine();
  41552. return next();
  41553. }
  41554. beginNewLine();
  41555. return true;
  41556. }
  41557. }
  41558. return true;
  41559. }
  41560. void beginNewLine()
  41561. {
  41562. atomX = 0;
  41563. lineY += lineHeight;
  41564. int tempSectionIndex = sectionIndex;
  41565. int tempAtomIndex = atomIndex;
  41566. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  41567. lineHeight = section->font.getHeight();
  41568. maxDescent = section->font.getDescent();
  41569. float x = (atom != 0) ? atom->width : 0;
  41570. while (! shouldWrap (x))
  41571. {
  41572. if (tempSectionIndex >= sections.size())
  41573. break;
  41574. bool checkSize = false;
  41575. if (tempAtomIndex >= section->getNumAtoms())
  41576. {
  41577. if (++tempSectionIndex >= sections.size())
  41578. break;
  41579. tempAtomIndex = 0;
  41580. section = sections.getUnchecked (tempSectionIndex);
  41581. checkSize = true;
  41582. }
  41583. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  41584. if (nextAtom == 0)
  41585. break;
  41586. x += nextAtom->width;
  41587. if (shouldWrap (x) || nextAtom->isNewLine())
  41588. break;
  41589. if (checkSize)
  41590. {
  41591. lineHeight = jmax (lineHeight, section->font.getHeight());
  41592. maxDescent = jmax (maxDescent, section->font.getDescent());
  41593. }
  41594. ++tempAtomIndex;
  41595. }
  41596. }
  41597. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  41598. {
  41599. if (passwordCharacter != 0 || ! atom->isWhitespace())
  41600. {
  41601. if (lastSection != currentSection)
  41602. {
  41603. lastSection = currentSection;
  41604. g.setColour (currentSection->colour);
  41605. g.setFont (currentSection->font);
  41606. }
  41607. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  41608. GlyphArrangement ga;
  41609. ga.addLineOfText (currentSection->font,
  41610. atom->getTrimmedText (passwordCharacter),
  41611. atomX,
  41612. (float) roundToInt (lineY + lineHeight - maxDescent));
  41613. ga.draw (g);
  41614. }
  41615. }
  41616. void drawSelection (Graphics& g,
  41617. const Range<int>& selection) const
  41618. {
  41619. const int startX = roundToInt (indexToX (selection.getStart()));
  41620. const int endX = roundToInt (indexToX (selection.getEnd()));
  41621. const int y = roundToInt (lineY);
  41622. const int nextY = roundToInt (lineY + lineHeight);
  41623. g.fillRect (startX, y, endX - startX, nextY - y);
  41624. }
  41625. void drawSelectedText (Graphics& g,
  41626. const Range<int>& selection,
  41627. const Colour& selectedTextColour) const
  41628. {
  41629. if (passwordCharacter != 0 || ! atom->isWhitespace())
  41630. {
  41631. GlyphArrangement ga;
  41632. ga.addLineOfText (currentSection->font,
  41633. atom->getTrimmedText (passwordCharacter),
  41634. atomX,
  41635. (float) roundToInt (lineY + lineHeight - maxDescent));
  41636. if (selection.getEnd() < indexInText + atom->numChars)
  41637. {
  41638. GlyphArrangement ga2 (ga);
  41639. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  41640. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  41641. g.setColour (currentSection->colour);
  41642. ga2.draw (g);
  41643. }
  41644. if (selection.getStart() > indexInText)
  41645. {
  41646. GlyphArrangement ga2 (ga);
  41647. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  41648. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  41649. g.setColour (currentSection->colour);
  41650. ga2.draw (g);
  41651. }
  41652. g.setColour (selectedTextColour);
  41653. ga.draw (g);
  41654. }
  41655. }
  41656. float indexToX (const int indexToFind) const
  41657. {
  41658. if (indexToFind <= indexInText)
  41659. return atomX;
  41660. if (indexToFind >= indexInText + atom->numChars)
  41661. return atomRight;
  41662. GlyphArrangement g;
  41663. g.addLineOfText (currentSection->font,
  41664. atom->getText (passwordCharacter),
  41665. atomX, 0.0f);
  41666. if (indexToFind - indexInText >= g.getNumGlyphs())
  41667. return atomRight;
  41668. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  41669. }
  41670. int xToIndex (const float xToFind) const
  41671. {
  41672. if (xToFind <= atomX || atom->isNewLine())
  41673. return indexInText;
  41674. if (xToFind >= atomRight)
  41675. return indexInText + atom->numChars;
  41676. GlyphArrangement g;
  41677. g.addLineOfText (currentSection->font,
  41678. atom->getText (passwordCharacter),
  41679. atomX, 0.0f);
  41680. int j;
  41681. for (j = 0; j < g.getNumGlyphs(); ++j)
  41682. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  41683. break;
  41684. return indexInText + j;
  41685. }
  41686. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  41687. {
  41688. while (next())
  41689. {
  41690. if (indexInText + atom->numChars > index)
  41691. {
  41692. cx = indexToX (index);
  41693. cy = lineY;
  41694. lineHeight_ = lineHeight;
  41695. return true;
  41696. }
  41697. }
  41698. cx = atomX;
  41699. cy = lineY;
  41700. lineHeight_ = lineHeight;
  41701. return false;
  41702. }
  41703. juce_UseDebuggingNewOperator
  41704. int indexInText;
  41705. float lineY, lineHeight, maxDescent;
  41706. float atomX, atomRight;
  41707. const TextAtom* atom;
  41708. const UniformTextSection* currentSection;
  41709. private:
  41710. const Array <UniformTextSection*>& sections;
  41711. int sectionIndex, atomIndex;
  41712. const float wordWrapWidth;
  41713. const juce_wchar passwordCharacter;
  41714. TextAtom tempAtom;
  41715. Iterator& operator= (const Iterator&);
  41716. void moveToEndOfLastAtom()
  41717. {
  41718. if (atom != 0)
  41719. {
  41720. atomX = atomRight;
  41721. if (atom->isNewLine())
  41722. {
  41723. atomX = 0.0f;
  41724. lineY += lineHeight;
  41725. }
  41726. }
  41727. }
  41728. bool shouldWrap (const float x) const
  41729. {
  41730. return (x - 0.0001f) >= wordWrapWidth;
  41731. }
  41732. };
  41733. class TextEditor::InsertAction : public UndoableAction
  41734. {
  41735. TextEditor& owner;
  41736. const String text;
  41737. const int insertIndex, oldCaretPos, newCaretPos;
  41738. const Font font;
  41739. const Colour colour;
  41740. InsertAction (const InsertAction&);
  41741. InsertAction& operator= (const InsertAction&);
  41742. public:
  41743. InsertAction (TextEditor& owner_,
  41744. const String& text_,
  41745. const int insertIndex_,
  41746. const Font& font_,
  41747. const Colour& colour_,
  41748. const int oldCaretPos_,
  41749. const int newCaretPos_)
  41750. : owner (owner_),
  41751. text (text_),
  41752. insertIndex (insertIndex_),
  41753. oldCaretPos (oldCaretPos_),
  41754. newCaretPos (newCaretPos_),
  41755. font (font_),
  41756. colour (colour_)
  41757. {
  41758. }
  41759. ~InsertAction()
  41760. {
  41761. }
  41762. bool perform()
  41763. {
  41764. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  41765. return true;
  41766. }
  41767. bool undo()
  41768. {
  41769. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  41770. return true;
  41771. }
  41772. int getSizeInUnits()
  41773. {
  41774. return text.length() + 16;
  41775. }
  41776. };
  41777. class TextEditor::RemoveAction : public UndoableAction
  41778. {
  41779. TextEditor& owner;
  41780. const Range<int> range;
  41781. const int oldCaretPos, newCaretPos;
  41782. Array <UniformTextSection*> removedSections;
  41783. RemoveAction (const RemoveAction&);
  41784. RemoveAction& operator= (const RemoveAction&);
  41785. public:
  41786. RemoveAction (TextEditor& owner_,
  41787. const Range<int> range_,
  41788. const int oldCaretPos_,
  41789. const int newCaretPos_,
  41790. const Array <UniformTextSection*>& removedSections_)
  41791. : owner (owner_),
  41792. range (range_),
  41793. oldCaretPos (oldCaretPos_),
  41794. newCaretPos (newCaretPos_),
  41795. removedSections (removedSections_)
  41796. {
  41797. }
  41798. ~RemoveAction()
  41799. {
  41800. for (int i = removedSections.size(); --i >= 0;)
  41801. {
  41802. UniformTextSection* const section = removedSections.getUnchecked (i);
  41803. section->clear();
  41804. delete section;
  41805. }
  41806. }
  41807. bool perform()
  41808. {
  41809. owner.remove (range, 0, newCaretPos);
  41810. return true;
  41811. }
  41812. bool undo()
  41813. {
  41814. owner.reinsert (range.getStart(), removedSections);
  41815. owner.moveCursorTo (oldCaretPos, false);
  41816. return true;
  41817. }
  41818. int getSizeInUnits()
  41819. {
  41820. int n = 0;
  41821. for (int i = removedSections.size(); --i >= 0;)
  41822. n += removedSections.getUnchecked (i)->getTotalLength();
  41823. return n + 16;
  41824. }
  41825. };
  41826. class TextEditor::TextHolderComponent : public Component,
  41827. public Timer,
  41828. public Value::Listener
  41829. {
  41830. public:
  41831. TextHolderComponent (TextEditor& owner_)
  41832. : owner (owner_)
  41833. {
  41834. setWantsKeyboardFocus (false);
  41835. setInterceptsMouseClicks (false, true);
  41836. owner.getTextValue().addListener (this);
  41837. }
  41838. ~TextHolderComponent()
  41839. {
  41840. owner.getTextValue().removeListener (this);
  41841. }
  41842. void paint (Graphics& g)
  41843. {
  41844. owner.drawContent (g);
  41845. }
  41846. void timerCallback()
  41847. {
  41848. owner.timerCallbackInt();
  41849. }
  41850. const MouseCursor getMouseCursor()
  41851. {
  41852. return owner.getMouseCursor();
  41853. }
  41854. void valueChanged (Value&)
  41855. {
  41856. owner.textWasChangedByValue();
  41857. }
  41858. private:
  41859. TextEditor& owner;
  41860. TextHolderComponent (const TextHolderComponent&);
  41861. TextHolderComponent& operator= (const TextHolderComponent&);
  41862. };
  41863. class TextEditorViewport : public Viewport
  41864. {
  41865. public:
  41866. TextEditorViewport (TextEditor* const owner_)
  41867. : owner (owner_),
  41868. lastWordWrapWidth (0)
  41869. {
  41870. }
  41871. ~TextEditorViewport()
  41872. {
  41873. }
  41874. void visibleAreaChanged (int, int, int, int)
  41875. {
  41876. const float wordWrapWidth = owner->getWordWrapWidth();
  41877. if (wordWrapWidth != lastWordWrapWidth)
  41878. {
  41879. lastWordWrapWidth = wordWrapWidth;
  41880. owner->updateTextHolderSize();
  41881. }
  41882. }
  41883. private:
  41884. TextEditor* const owner;
  41885. float lastWordWrapWidth;
  41886. TextEditorViewport (const TextEditorViewport&);
  41887. TextEditorViewport& operator= (const TextEditorViewport&);
  41888. };
  41889. namespace TextEditorDefs
  41890. {
  41891. const int flashSpeedIntervalMs = 380;
  41892. const int textChangeMessageId = 0x10003001;
  41893. const int returnKeyMessageId = 0x10003002;
  41894. const int escapeKeyMessageId = 0x10003003;
  41895. const int focusLossMessageId = 0x10003004;
  41896. const int maxActionsPerTransaction = 100;
  41897. }
  41898. TextEditor::TextEditor (const String& name,
  41899. const juce_wchar passwordCharacter_)
  41900. : Component (name),
  41901. borderSize (1, 1, 1, 3),
  41902. readOnly (false),
  41903. multiline (false),
  41904. wordWrap (false),
  41905. returnKeyStartsNewLine (false),
  41906. caretVisible (true),
  41907. popupMenuEnabled (true),
  41908. selectAllTextWhenFocused (false),
  41909. scrollbarVisible (true),
  41910. wasFocused (false),
  41911. caretFlashState (true),
  41912. keepCursorOnScreen (true),
  41913. tabKeyUsed (false),
  41914. menuActive (false),
  41915. valueTextNeedsUpdating (false),
  41916. cursorX (0),
  41917. cursorY (0),
  41918. cursorHeight (0),
  41919. maxTextLength (0),
  41920. leftIndent (4),
  41921. topIndent (4),
  41922. lastTransactionTime (0),
  41923. currentFont (14.0f),
  41924. totalNumChars (0),
  41925. caretPosition (0),
  41926. passwordCharacter (passwordCharacter_),
  41927. dragType (notDragging)
  41928. {
  41929. setOpaque (true);
  41930. addAndMakeVisible (viewport = new TextEditorViewport (this));
  41931. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  41932. viewport->setWantsKeyboardFocus (false);
  41933. viewport->setScrollBarsShown (false, false);
  41934. setMouseCursor (MouseCursor::IBeamCursor);
  41935. setWantsKeyboardFocus (true);
  41936. }
  41937. TextEditor::~TextEditor()
  41938. {
  41939. textValue.referTo (Value());
  41940. clearInternal (0);
  41941. viewport = 0;
  41942. textHolder = 0;
  41943. }
  41944. void TextEditor::newTransaction()
  41945. {
  41946. lastTransactionTime = Time::getApproximateMillisecondCounter();
  41947. undoManager.beginNewTransaction();
  41948. }
  41949. void TextEditor::doUndoRedo (const bool isRedo)
  41950. {
  41951. if (! isReadOnly())
  41952. {
  41953. if (isRedo ? undoManager.redo()
  41954. : undoManager.undo())
  41955. {
  41956. scrollToMakeSureCursorIsVisible();
  41957. repaint();
  41958. textChanged();
  41959. }
  41960. }
  41961. }
  41962. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  41963. const bool shouldWordWrap)
  41964. {
  41965. multiline = shouldBeMultiLine;
  41966. wordWrap = shouldWordWrap && shouldBeMultiLine;
  41967. setScrollbarsShown (scrollbarVisible);
  41968. viewport->setViewPosition (0, 0);
  41969. resized();
  41970. scrollToMakeSureCursorIsVisible();
  41971. }
  41972. bool TextEditor::isMultiLine() const
  41973. {
  41974. return multiline;
  41975. }
  41976. void TextEditor::setScrollbarsShown (bool enabled)
  41977. {
  41978. scrollbarVisible = enabled;
  41979. enabled = enabled && isMultiLine();
  41980. viewport->setScrollBarsShown (enabled, enabled);
  41981. }
  41982. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  41983. {
  41984. readOnly = shouldBeReadOnly;
  41985. enablementChanged();
  41986. }
  41987. bool TextEditor::isReadOnly() const
  41988. {
  41989. return readOnly || ! isEnabled();
  41990. }
  41991. bool TextEditor::isTextInputActive() const
  41992. {
  41993. return ! isReadOnly();
  41994. }
  41995. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  41996. {
  41997. returnKeyStartsNewLine = shouldStartNewLine;
  41998. }
  41999. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  42000. {
  42001. tabKeyUsed = shouldTabKeyBeUsed;
  42002. }
  42003. void TextEditor::setPopupMenuEnabled (const bool b)
  42004. {
  42005. popupMenuEnabled = b;
  42006. }
  42007. void TextEditor::setSelectAllWhenFocused (const bool b)
  42008. {
  42009. selectAllTextWhenFocused = b;
  42010. }
  42011. const Font TextEditor::getFont() const
  42012. {
  42013. return currentFont;
  42014. }
  42015. void TextEditor::setFont (const Font& newFont)
  42016. {
  42017. currentFont = newFont;
  42018. scrollToMakeSureCursorIsVisible();
  42019. }
  42020. void TextEditor::applyFontToAllText (const Font& newFont)
  42021. {
  42022. currentFont = newFont;
  42023. const Colour overallColour (findColour (textColourId));
  42024. for (int i = sections.size(); --i >= 0;)
  42025. {
  42026. UniformTextSection* const uts = sections.getUnchecked (i);
  42027. uts->setFont (newFont, passwordCharacter);
  42028. uts->colour = overallColour;
  42029. }
  42030. coalesceSimilarSections();
  42031. updateTextHolderSize();
  42032. scrollToMakeSureCursorIsVisible();
  42033. repaint();
  42034. }
  42035. void TextEditor::colourChanged()
  42036. {
  42037. setOpaque (findColour (backgroundColourId).isOpaque());
  42038. repaint();
  42039. }
  42040. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  42041. {
  42042. caretVisible = shouldCaretBeVisible;
  42043. if (shouldCaretBeVisible)
  42044. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42045. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  42046. : MouseCursor::NormalCursor);
  42047. }
  42048. void TextEditor::setInputRestrictions (const int maxLen,
  42049. const String& chars)
  42050. {
  42051. maxTextLength = jmax (0, maxLen);
  42052. allowedCharacters = chars;
  42053. }
  42054. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  42055. {
  42056. textToShowWhenEmpty = text;
  42057. colourForTextWhenEmpty = colourToUse;
  42058. }
  42059. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  42060. {
  42061. if (passwordCharacter != newPasswordCharacter)
  42062. {
  42063. passwordCharacter = newPasswordCharacter;
  42064. resized();
  42065. repaint();
  42066. }
  42067. }
  42068. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  42069. {
  42070. viewport->setScrollBarThickness (newThicknessPixels);
  42071. }
  42072. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  42073. {
  42074. viewport->setScrollBarButtonVisibility (buttonsVisible);
  42075. }
  42076. void TextEditor::clear()
  42077. {
  42078. clearInternal (0);
  42079. updateTextHolderSize();
  42080. undoManager.clearUndoHistory();
  42081. }
  42082. void TextEditor::setText (const String& newText,
  42083. const bool sendTextChangeMessage)
  42084. {
  42085. const int newLength = newText.length();
  42086. if (newLength != getTotalNumChars() || getText() != newText)
  42087. {
  42088. const int oldCursorPos = caretPosition;
  42089. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  42090. clearInternal (0);
  42091. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  42092. // if you're adding text with line-feeds to a single-line text editor, it
  42093. // ain't gonna look right!
  42094. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  42095. if (cursorWasAtEnd && ! isMultiLine())
  42096. moveCursorTo (getTotalNumChars(), false);
  42097. else
  42098. moveCursorTo (oldCursorPos, false);
  42099. if (sendTextChangeMessage)
  42100. textChanged();
  42101. repaint();
  42102. }
  42103. updateTextHolderSize();
  42104. scrollToMakeSureCursorIsVisible();
  42105. undoManager.clearUndoHistory();
  42106. }
  42107. Value& TextEditor::getTextValue()
  42108. {
  42109. if (valueTextNeedsUpdating)
  42110. {
  42111. valueTextNeedsUpdating = false;
  42112. textValue = getText();
  42113. }
  42114. return textValue;
  42115. }
  42116. void TextEditor::textWasChangedByValue()
  42117. {
  42118. if (textValue.getValueSource().getReferenceCount() > 1)
  42119. setText (textValue.getValue());
  42120. }
  42121. void TextEditor::textChanged()
  42122. {
  42123. updateTextHolderSize();
  42124. postCommandMessage (TextEditorDefs::textChangeMessageId);
  42125. if (textValue.getValueSource().getReferenceCount() > 1)
  42126. {
  42127. valueTextNeedsUpdating = false;
  42128. textValue = getText();
  42129. }
  42130. }
  42131. void TextEditor::returnPressed()
  42132. {
  42133. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  42134. }
  42135. void TextEditor::escapePressed()
  42136. {
  42137. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  42138. }
  42139. void TextEditor::addListener (TextEditorListener* const newListener)
  42140. {
  42141. listeners.add (newListener);
  42142. }
  42143. void TextEditor::removeListener (TextEditorListener* const listenerToRemove)
  42144. {
  42145. listeners.remove (listenerToRemove);
  42146. }
  42147. void TextEditor::timerCallbackInt()
  42148. {
  42149. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  42150. if (caretFlashState != newState)
  42151. {
  42152. caretFlashState = newState;
  42153. if (caretFlashState)
  42154. wasFocused = true;
  42155. if (caretVisible
  42156. && hasKeyboardFocus (false)
  42157. && ! isReadOnly())
  42158. {
  42159. repaintCaret();
  42160. }
  42161. }
  42162. const unsigned int now = Time::getApproximateMillisecondCounter();
  42163. if (now > lastTransactionTime + 200)
  42164. newTransaction();
  42165. }
  42166. void TextEditor::repaintCaret()
  42167. {
  42168. if (! findColour (caretColourId).isTransparent())
  42169. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  42170. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  42171. 4,
  42172. roundToInt (cursorHeight) + 2);
  42173. }
  42174. void TextEditor::repaintText (const Range<int>& range)
  42175. {
  42176. if (! range.isEmpty())
  42177. {
  42178. float x = 0, y = 0, lh = currentFont.getHeight();
  42179. const float wordWrapWidth = getWordWrapWidth();
  42180. if (wordWrapWidth > 0)
  42181. {
  42182. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42183. i.getCharPosition (range.getStart(), x, y, lh);
  42184. const int y1 = (int) y;
  42185. int y2;
  42186. if (range.getEnd() >= getTotalNumChars())
  42187. {
  42188. y2 = textHolder->getHeight();
  42189. }
  42190. else
  42191. {
  42192. i.getCharPosition (range.getEnd(), x, y, lh);
  42193. y2 = (int) (y + lh * 2.0f);
  42194. }
  42195. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  42196. }
  42197. }
  42198. }
  42199. void TextEditor::moveCaret (int newCaretPos)
  42200. {
  42201. if (newCaretPos < 0)
  42202. newCaretPos = 0;
  42203. else if (newCaretPos > getTotalNumChars())
  42204. newCaretPos = getTotalNumChars();
  42205. if (newCaretPos != getCaretPosition())
  42206. {
  42207. repaintCaret();
  42208. caretFlashState = true;
  42209. caretPosition = newCaretPos;
  42210. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42211. scrollToMakeSureCursorIsVisible();
  42212. repaintCaret();
  42213. }
  42214. }
  42215. void TextEditor::setCaretPosition (const int newIndex)
  42216. {
  42217. moveCursorTo (newIndex, false);
  42218. }
  42219. int TextEditor::getCaretPosition() const
  42220. {
  42221. return caretPosition;
  42222. }
  42223. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  42224. const int desiredCaretY)
  42225. {
  42226. updateCaretPosition();
  42227. int vx = roundToInt (cursorX) - desiredCaretX;
  42228. int vy = roundToInt (cursorY) - desiredCaretY;
  42229. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  42230. {
  42231. vx += desiredCaretX - proportionOfWidth (0.2f);
  42232. }
  42233. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42234. {
  42235. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42236. }
  42237. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  42238. if (! isMultiLine())
  42239. {
  42240. vy = viewport->getViewPositionY();
  42241. }
  42242. else
  42243. {
  42244. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  42245. const int curH = roundToInt (cursorHeight);
  42246. if (desiredCaretY < 0)
  42247. {
  42248. vy = jmax (0, desiredCaretY + vy);
  42249. }
  42250. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42251. {
  42252. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42253. }
  42254. }
  42255. viewport->setViewPosition (vx, vy);
  42256. }
  42257. const Rectangle<int> TextEditor::getCaretRectangle()
  42258. {
  42259. updateCaretPosition();
  42260. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  42261. roundToInt (cursorY) - viewport->getY(),
  42262. 1, roundToInt (cursorHeight));
  42263. }
  42264. float TextEditor::getWordWrapWidth() const
  42265. {
  42266. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  42267. : 1.0e10f;
  42268. }
  42269. void TextEditor::updateTextHolderSize()
  42270. {
  42271. const float wordWrapWidth = getWordWrapWidth();
  42272. if (wordWrapWidth > 0)
  42273. {
  42274. float maxWidth = 0.0f;
  42275. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42276. while (i.next())
  42277. maxWidth = jmax (maxWidth, i.atomRight);
  42278. const int w = leftIndent + roundToInt (maxWidth);
  42279. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  42280. currentFont.getHeight()));
  42281. textHolder->setSize (w + 1, h + 1);
  42282. }
  42283. }
  42284. int TextEditor::getTextWidth() const
  42285. {
  42286. return textHolder->getWidth();
  42287. }
  42288. int TextEditor::getTextHeight() const
  42289. {
  42290. return textHolder->getHeight();
  42291. }
  42292. void TextEditor::setIndents (const int newLeftIndent,
  42293. const int newTopIndent)
  42294. {
  42295. leftIndent = newLeftIndent;
  42296. topIndent = newTopIndent;
  42297. }
  42298. void TextEditor::setBorder (const BorderSize& border)
  42299. {
  42300. borderSize = border;
  42301. resized();
  42302. }
  42303. const BorderSize TextEditor::getBorder() const
  42304. {
  42305. return borderSize;
  42306. }
  42307. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  42308. {
  42309. keepCursorOnScreen = shouldScrollToShowCursor;
  42310. }
  42311. void TextEditor::updateCaretPosition()
  42312. {
  42313. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  42314. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  42315. }
  42316. void TextEditor::scrollToMakeSureCursorIsVisible()
  42317. {
  42318. updateCaretPosition();
  42319. if (keepCursorOnScreen)
  42320. {
  42321. int x = viewport->getViewPositionX();
  42322. int y = viewport->getViewPositionY();
  42323. const int relativeCursorX = roundToInt (cursorX) - x;
  42324. const int relativeCursorY = roundToInt (cursorY) - y;
  42325. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  42326. {
  42327. x += relativeCursorX - proportionOfWidth (0.2f);
  42328. }
  42329. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42330. {
  42331. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42332. }
  42333. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  42334. if (! isMultiLine())
  42335. {
  42336. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  42337. }
  42338. else
  42339. {
  42340. const int curH = roundToInt (cursorHeight);
  42341. if (relativeCursorY < 0)
  42342. {
  42343. y = jmax (0, relativeCursorY + y);
  42344. }
  42345. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42346. {
  42347. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42348. }
  42349. }
  42350. viewport->setViewPosition (x, y);
  42351. }
  42352. }
  42353. void TextEditor::moveCursorTo (const int newPosition,
  42354. const bool isSelecting)
  42355. {
  42356. if (isSelecting)
  42357. {
  42358. moveCaret (newPosition);
  42359. const Range<int> oldSelection (selection);
  42360. if (dragType == notDragging)
  42361. {
  42362. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  42363. dragType = draggingSelectionStart;
  42364. else
  42365. dragType = draggingSelectionEnd;
  42366. }
  42367. if (dragType == draggingSelectionStart)
  42368. {
  42369. if (getCaretPosition() >= selection.getEnd())
  42370. dragType = draggingSelectionEnd;
  42371. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  42372. }
  42373. else
  42374. {
  42375. if (getCaretPosition() < selection.getStart())
  42376. dragType = draggingSelectionStart;
  42377. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  42378. }
  42379. repaintText (selection.getUnionWith (oldSelection));
  42380. }
  42381. else
  42382. {
  42383. dragType = notDragging;
  42384. repaintText (selection);
  42385. moveCaret (newPosition);
  42386. selection = Range<int>::emptyRange (getCaretPosition());
  42387. }
  42388. }
  42389. int TextEditor::getTextIndexAt (const int x,
  42390. const int y)
  42391. {
  42392. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  42393. (float) (y + viewport->getViewPositionY() - topIndent));
  42394. }
  42395. void TextEditor::insertTextAtCaret (const String& newText_)
  42396. {
  42397. String newText (newText_);
  42398. if (allowedCharacters.isNotEmpty())
  42399. newText = newText.retainCharacters (allowedCharacters);
  42400. if ((! returnKeyStartsNewLine) && newText == "\n")
  42401. {
  42402. returnPressed();
  42403. return;
  42404. }
  42405. if (! isMultiLine())
  42406. newText = newText.replaceCharacters ("\r\n", " ");
  42407. else
  42408. newText = newText.replace ("\r\n", "\n");
  42409. const int newCaretPos = selection.getStart() + newText.length();
  42410. const int insertIndex = selection.getStart();
  42411. remove (selection, getUndoManager(),
  42412. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  42413. if (maxTextLength > 0)
  42414. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  42415. if (newText.isNotEmpty())
  42416. insert (newText,
  42417. insertIndex,
  42418. currentFont,
  42419. findColour (textColourId),
  42420. getUndoManager(),
  42421. newCaretPos);
  42422. textChanged();
  42423. }
  42424. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  42425. {
  42426. moveCursorTo (newSelection.getStart(), false);
  42427. moveCursorTo (newSelection.getEnd(), true);
  42428. }
  42429. void TextEditor::copy()
  42430. {
  42431. if (passwordCharacter == 0)
  42432. {
  42433. const String selectedText (getHighlightedText());
  42434. if (selectedText.isNotEmpty())
  42435. SystemClipboard::copyTextToClipboard (selectedText);
  42436. }
  42437. }
  42438. void TextEditor::paste()
  42439. {
  42440. if (! isReadOnly())
  42441. {
  42442. const String clip (SystemClipboard::getTextFromClipboard());
  42443. if (clip.isNotEmpty())
  42444. insertTextAtCaret (clip);
  42445. }
  42446. }
  42447. void TextEditor::cut()
  42448. {
  42449. if (! isReadOnly())
  42450. {
  42451. moveCaret (selection.getEnd());
  42452. insertTextAtCaret (String::empty);
  42453. }
  42454. }
  42455. void TextEditor::drawContent (Graphics& g)
  42456. {
  42457. const float wordWrapWidth = getWordWrapWidth();
  42458. if (wordWrapWidth > 0)
  42459. {
  42460. g.setOrigin (leftIndent, topIndent);
  42461. const Rectangle<int> clip (g.getClipBounds());
  42462. Colour selectedTextColour;
  42463. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42464. while (i.lineY + 200.0 < clip.getY() && i.next())
  42465. {}
  42466. if (! selection.isEmpty())
  42467. {
  42468. g.setColour (findColour (highlightColourId)
  42469. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  42470. selectedTextColour = findColour (highlightedTextColourId);
  42471. Iterator i2 (i);
  42472. while (i2.next() && i2.lineY < clip.getBottom())
  42473. {
  42474. if (i2.lineY + i2.lineHeight >= clip.getY()
  42475. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  42476. {
  42477. i2.drawSelection (g, selection);
  42478. }
  42479. }
  42480. }
  42481. const UniformTextSection* lastSection = 0;
  42482. while (i.next() && i.lineY < clip.getBottom())
  42483. {
  42484. if (i.lineY + i.lineHeight >= clip.getY())
  42485. {
  42486. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  42487. {
  42488. i.drawSelectedText (g, selection, selectedTextColour);
  42489. lastSection = 0;
  42490. }
  42491. else
  42492. {
  42493. i.draw (g, lastSection);
  42494. }
  42495. }
  42496. }
  42497. }
  42498. }
  42499. void TextEditor::paint (Graphics& g)
  42500. {
  42501. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  42502. }
  42503. void TextEditor::paintOverChildren (Graphics& g)
  42504. {
  42505. if (caretFlashState
  42506. && hasKeyboardFocus (false)
  42507. && caretVisible
  42508. && ! isReadOnly())
  42509. {
  42510. g.setColour (findColour (caretColourId));
  42511. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  42512. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  42513. 2.0f, cursorHeight);
  42514. }
  42515. if (textToShowWhenEmpty.isNotEmpty()
  42516. && (! hasKeyboardFocus (false))
  42517. && getTotalNumChars() == 0)
  42518. {
  42519. g.setColour (colourForTextWhenEmpty);
  42520. g.setFont (getFont());
  42521. if (isMultiLine())
  42522. {
  42523. g.drawText (textToShowWhenEmpty,
  42524. 0, 0, getWidth(), getHeight(),
  42525. Justification::centred, true);
  42526. }
  42527. else
  42528. {
  42529. g.drawText (textToShowWhenEmpty,
  42530. leftIndent, topIndent,
  42531. viewport->getWidth() - leftIndent,
  42532. viewport->getHeight() - topIndent,
  42533. Justification::centredLeft, true);
  42534. }
  42535. }
  42536. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  42537. }
  42538. void TextEditor::mouseDown (const MouseEvent& e)
  42539. {
  42540. beginDragAutoRepeat (100);
  42541. newTransaction();
  42542. if (wasFocused || ! selectAllTextWhenFocused)
  42543. {
  42544. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  42545. {
  42546. moveCursorTo (getTextIndexAt (e.x, e.y),
  42547. e.mods.isShiftDown());
  42548. }
  42549. else
  42550. {
  42551. PopupMenu m;
  42552. m.setLookAndFeel (&getLookAndFeel());
  42553. addPopupMenuItems (m, &e);
  42554. menuActive = true;
  42555. const int result = m.show();
  42556. menuActive = false;
  42557. if (result != 0)
  42558. performPopupMenuAction (result);
  42559. }
  42560. }
  42561. }
  42562. void TextEditor::mouseDrag (const MouseEvent& e)
  42563. {
  42564. if (wasFocused || ! selectAllTextWhenFocused)
  42565. {
  42566. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  42567. {
  42568. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  42569. }
  42570. }
  42571. }
  42572. void TextEditor::mouseUp (const MouseEvent& e)
  42573. {
  42574. newTransaction();
  42575. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42576. if (wasFocused || ! selectAllTextWhenFocused)
  42577. {
  42578. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  42579. {
  42580. moveCaret (getTextIndexAt (e.x, e.y));
  42581. }
  42582. }
  42583. wasFocused = true;
  42584. }
  42585. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  42586. {
  42587. int tokenEnd = getTextIndexAt (e.x, e.y);
  42588. int tokenStart = tokenEnd;
  42589. if (e.getNumberOfClicks() > 3)
  42590. {
  42591. tokenStart = 0;
  42592. tokenEnd = getTotalNumChars();
  42593. }
  42594. else
  42595. {
  42596. const String t (getText());
  42597. const int totalLength = getTotalNumChars();
  42598. while (tokenEnd < totalLength)
  42599. {
  42600. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]))
  42601. ++tokenEnd;
  42602. else
  42603. break;
  42604. }
  42605. tokenStart = tokenEnd;
  42606. while (tokenStart > 0)
  42607. {
  42608. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]))
  42609. --tokenStart;
  42610. else
  42611. break;
  42612. }
  42613. if (e.getNumberOfClicks() > 2)
  42614. {
  42615. while (tokenEnd < totalLength)
  42616. {
  42617. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  42618. ++tokenEnd;
  42619. else
  42620. break;
  42621. }
  42622. while (tokenStart > 0)
  42623. {
  42624. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  42625. --tokenStart;
  42626. else
  42627. break;
  42628. }
  42629. }
  42630. }
  42631. moveCursorTo (tokenEnd, false);
  42632. moveCursorTo (tokenStart, true);
  42633. }
  42634. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  42635. {
  42636. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  42637. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  42638. }
  42639. bool TextEditor::keyPressed (const KeyPress& key)
  42640. {
  42641. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  42642. return false;
  42643. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  42644. if (key.isKeyCode (KeyPress::leftKey)
  42645. || key.isKeyCode (KeyPress::upKey))
  42646. {
  42647. newTransaction();
  42648. int newPos;
  42649. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  42650. newPos = indexAtPosition (cursorX, cursorY - 1);
  42651. else if (moveInWholeWordSteps)
  42652. newPos = findWordBreakBefore (getCaretPosition());
  42653. else
  42654. newPos = getCaretPosition() - 1;
  42655. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  42656. }
  42657. else if (key.isKeyCode (KeyPress::rightKey)
  42658. || key.isKeyCode (KeyPress::downKey))
  42659. {
  42660. newTransaction();
  42661. int newPos;
  42662. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  42663. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  42664. else if (moveInWholeWordSteps)
  42665. newPos = findWordBreakAfter (getCaretPosition());
  42666. else
  42667. newPos = getCaretPosition() + 1;
  42668. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  42669. }
  42670. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  42671. {
  42672. newTransaction();
  42673. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  42674. key.getModifiers().isShiftDown());
  42675. }
  42676. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  42677. {
  42678. newTransaction();
  42679. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  42680. key.getModifiers().isShiftDown());
  42681. }
  42682. else if (key.isKeyCode (KeyPress::homeKey))
  42683. {
  42684. newTransaction();
  42685. if (isMultiLine() && ! moveInWholeWordSteps)
  42686. moveCursorTo (indexAtPosition (0.0f, cursorY),
  42687. key.getModifiers().isShiftDown());
  42688. else
  42689. moveCursorTo (0, key.getModifiers().isShiftDown());
  42690. }
  42691. else if (key.isKeyCode (KeyPress::endKey))
  42692. {
  42693. newTransaction();
  42694. if (isMultiLine() && ! moveInWholeWordSteps)
  42695. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  42696. key.getModifiers().isShiftDown());
  42697. else
  42698. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  42699. }
  42700. else if (key.isKeyCode (KeyPress::backspaceKey))
  42701. {
  42702. if (moveInWholeWordSteps)
  42703. {
  42704. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  42705. }
  42706. else
  42707. {
  42708. if (selection.isEmpty() && selection.getStart() > 0)
  42709. selection.setStart (selection.getEnd() - 1);
  42710. }
  42711. cut();
  42712. }
  42713. else if (key.isKeyCode (KeyPress::deleteKey))
  42714. {
  42715. if (key.getModifiers().isShiftDown())
  42716. copy();
  42717. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  42718. selection.setEnd (selection.getStart() + 1);
  42719. cut();
  42720. }
  42721. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  42722. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  42723. {
  42724. newTransaction();
  42725. copy();
  42726. }
  42727. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  42728. {
  42729. newTransaction();
  42730. copy();
  42731. cut();
  42732. }
  42733. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  42734. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  42735. {
  42736. newTransaction();
  42737. paste();
  42738. }
  42739. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  42740. {
  42741. newTransaction();
  42742. doUndoRedo (false);
  42743. }
  42744. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  42745. {
  42746. newTransaction();
  42747. doUndoRedo (true);
  42748. }
  42749. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  42750. {
  42751. newTransaction();
  42752. moveCursorTo (getTotalNumChars(), false);
  42753. moveCursorTo (0, true);
  42754. }
  42755. else if (key == KeyPress::returnKey)
  42756. {
  42757. newTransaction();
  42758. insertTextAtCaret ("\n");
  42759. }
  42760. else if (key.isKeyCode (KeyPress::escapeKey))
  42761. {
  42762. newTransaction();
  42763. moveCursorTo (getCaretPosition(), false);
  42764. escapePressed();
  42765. }
  42766. else if (key.getTextCharacter() >= ' '
  42767. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  42768. {
  42769. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  42770. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42771. }
  42772. else
  42773. {
  42774. return false;
  42775. }
  42776. return true;
  42777. }
  42778. bool TextEditor::keyStateChanged (const bool isKeyDown)
  42779. {
  42780. if (! isKeyDown)
  42781. return false;
  42782. #if JUCE_WIN32
  42783. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  42784. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  42785. #endif
  42786. // (overridden to avoid forwarding key events to the parent)
  42787. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  42788. }
  42789. const int baseMenuItemID = 0x7fff0000;
  42790. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  42791. {
  42792. const bool writable = ! isReadOnly();
  42793. if (passwordCharacter == 0)
  42794. {
  42795. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  42796. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  42797. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  42798. }
  42799. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  42800. m.addSeparator();
  42801. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  42802. m.addSeparator();
  42803. if (getUndoManager() != 0)
  42804. {
  42805. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  42806. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  42807. }
  42808. }
  42809. void TextEditor::performPopupMenuAction (const int menuItemID)
  42810. {
  42811. switch (menuItemID)
  42812. {
  42813. case baseMenuItemID + 1:
  42814. copy();
  42815. cut();
  42816. break;
  42817. case baseMenuItemID + 2:
  42818. copy();
  42819. break;
  42820. case baseMenuItemID + 3:
  42821. paste();
  42822. break;
  42823. case baseMenuItemID + 4:
  42824. cut();
  42825. break;
  42826. case baseMenuItemID + 5:
  42827. moveCursorTo (getTotalNumChars(), false);
  42828. moveCursorTo (0, true);
  42829. break;
  42830. case baseMenuItemID + 6:
  42831. doUndoRedo (false);
  42832. break;
  42833. case baseMenuItemID + 7:
  42834. doUndoRedo (true);
  42835. break;
  42836. default:
  42837. break;
  42838. }
  42839. }
  42840. void TextEditor::focusGained (FocusChangeType)
  42841. {
  42842. newTransaction();
  42843. caretFlashState = true;
  42844. if (selectAllTextWhenFocused)
  42845. {
  42846. moveCursorTo (0, false);
  42847. moveCursorTo (getTotalNumChars(), true);
  42848. }
  42849. repaint();
  42850. if (caretVisible)
  42851. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42852. ComponentPeer* const peer = getPeer();
  42853. if (peer != 0 && ! isReadOnly())
  42854. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  42855. }
  42856. void TextEditor::focusLost (FocusChangeType)
  42857. {
  42858. newTransaction();
  42859. wasFocused = false;
  42860. textHolder->stopTimer();
  42861. caretFlashState = false;
  42862. postCommandMessage (TextEditorDefs::focusLossMessageId);
  42863. repaint();
  42864. }
  42865. void TextEditor::resized()
  42866. {
  42867. viewport->setBoundsInset (borderSize);
  42868. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  42869. updateTextHolderSize();
  42870. if (! isMultiLine())
  42871. {
  42872. scrollToMakeSureCursorIsVisible();
  42873. }
  42874. else
  42875. {
  42876. updateCaretPosition();
  42877. }
  42878. }
  42879. void TextEditor::handleCommandMessage (const int commandId)
  42880. {
  42881. Component::BailOutChecker checker (this);
  42882. switch (commandId)
  42883. {
  42884. case TextEditorDefs::textChangeMessageId:
  42885. listeners.callChecked (checker, &TextEditorListener::textEditorTextChanged, (TextEditor&) *this);
  42886. break;
  42887. case TextEditorDefs::returnKeyMessageId:
  42888. listeners.callChecked (checker, &TextEditorListener::textEditorReturnKeyPressed, (TextEditor&) *this);
  42889. break;
  42890. case TextEditorDefs::escapeKeyMessageId:
  42891. listeners.callChecked (checker, &TextEditorListener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  42892. break;
  42893. case TextEditorDefs::focusLossMessageId:
  42894. listeners.callChecked (checker, &TextEditorListener::textEditorFocusLost, (TextEditor&) *this);
  42895. break;
  42896. default:
  42897. jassertfalse
  42898. break;
  42899. }
  42900. }
  42901. void TextEditor::enablementChanged()
  42902. {
  42903. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  42904. : MouseCursor::IBeamCursor);
  42905. repaint();
  42906. }
  42907. UndoManager* TextEditor::getUndoManager() throw()
  42908. {
  42909. return isReadOnly() ? &undoManager : 0;
  42910. }
  42911. void TextEditor::clearInternal (UndoManager* const um)
  42912. {
  42913. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  42914. }
  42915. void TextEditor::insert (const String& text,
  42916. const int insertIndex,
  42917. const Font& font,
  42918. const Colour& colour,
  42919. UndoManager* const um,
  42920. const int caretPositionToMoveTo)
  42921. {
  42922. if (text.isNotEmpty())
  42923. {
  42924. if (um != 0)
  42925. {
  42926. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  42927. newTransaction();
  42928. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  42929. caretPosition, caretPositionToMoveTo));
  42930. }
  42931. else
  42932. {
  42933. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  42934. // a line gets moved due to word wrap
  42935. int index = 0;
  42936. int nextIndex = 0;
  42937. for (int i = 0; i < sections.size(); ++i)
  42938. {
  42939. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  42940. if (insertIndex == index)
  42941. {
  42942. sections.insert (i, new UniformTextSection (text,
  42943. font, colour,
  42944. passwordCharacter));
  42945. break;
  42946. }
  42947. else if (insertIndex > index && insertIndex < nextIndex)
  42948. {
  42949. splitSection (i, insertIndex - index);
  42950. sections.insert (i + 1, new UniformTextSection (text,
  42951. font, colour,
  42952. passwordCharacter));
  42953. break;
  42954. }
  42955. index = nextIndex;
  42956. }
  42957. if (nextIndex == insertIndex)
  42958. sections.add (new UniformTextSection (text,
  42959. font, colour,
  42960. passwordCharacter));
  42961. coalesceSimilarSections();
  42962. totalNumChars = -1;
  42963. valueTextNeedsUpdating = true;
  42964. moveCursorTo (caretPositionToMoveTo, false);
  42965. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  42966. }
  42967. }
  42968. }
  42969. void TextEditor::reinsert (const int insertIndex,
  42970. const Array <UniformTextSection*>& sectionsToInsert)
  42971. {
  42972. int index = 0;
  42973. int nextIndex = 0;
  42974. for (int i = 0; i < sections.size(); ++i)
  42975. {
  42976. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  42977. if (insertIndex == index)
  42978. {
  42979. for (int j = sectionsToInsert.size(); --j >= 0;)
  42980. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  42981. break;
  42982. }
  42983. else if (insertIndex > index && insertIndex < nextIndex)
  42984. {
  42985. splitSection (i, insertIndex - index);
  42986. for (int j = sectionsToInsert.size(); --j >= 0;)
  42987. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  42988. break;
  42989. }
  42990. index = nextIndex;
  42991. }
  42992. if (nextIndex == insertIndex)
  42993. {
  42994. for (int j = 0; j < sectionsToInsert.size(); ++j)
  42995. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  42996. }
  42997. coalesceSimilarSections();
  42998. totalNumChars = -1;
  42999. valueTextNeedsUpdating = true;
  43000. }
  43001. void TextEditor::remove (const Range<int>& range,
  43002. UndoManager* const um,
  43003. const int caretPositionToMoveTo)
  43004. {
  43005. if (! range.isEmpty())
  43006. {
  43007. int index = 0;
  43008. for (int i = 0; i < sections.size(); ++i)
  43009. {
  43010. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  43011. if (range.getStart() > index && range.getStart() < nextIndex)
  43012. {
  43013. splitSection (i, range.getStart() - index);
  43014. --i;
  43015. }
  43016. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  43017. {
  43018. splitSection (i, range.getEnd() - index);
  43019. --i;
  43020. }
  43021. else
  43022. {
  43023. index = nextIndex;
  43024. if (index > range.getEnd())
  43025. break;
  43026. }
  43027. }
  43028. index = 0;
  43029. if (um != 0)
  43030. {
  43031. Array <UniformTextSection*> removedSections;
  43032. for (int i = 0; i < sections.size(); ++i)
  43033. {
  43034. if (range.getEnd() <= range.getStart())
  43035. break;
  43036. UniformTextSection* const section = sections.getUnchecked (i);
  43037. const int nextIndex = index + section->getTotalLength();
  43038. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  43039. removedSections.add (new UniformTextSection (*section));
  43040. index = nextIndex;
  43041. }
  43042. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43043. newTransaction();
  43044. um->perform (new RemoveAction (*this, range, caretPosition,
  43045. caretPositionToMoveTo, removedSections));
  43046. }
  43047. else
  43048. {
  43049. Range<int> remainingRange (range);
  43050. for (int i = 0; i < sections.size(); ++i)
  43051. {
  43052. UniformTextSection* const section = sections.getUnchecked (i);
  43053. const int nextIndex = index + section->getTotalLength();
  43054. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  43055. {
  43056. sections.remove(i);
  43057. section->clear();
  43058. delete section;
  43059. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  43060. if (remainingRange.isEmpty())
  43061. break;
  43062. --i;
  43063. }
  43064. else
  43065. {
  43066. index = nextIndex;
  43067. }
  43068. }
  43069. coalesceSimilarSections();
  43070. totalNumChars = -1;
  43071. valueTextNeedsUpdating = true;
  43072. moveCursorTo (caretPositionToMoveTo, false);
  43073. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  43074. }
  43075. }
  43076. }
  43077. const String TextEditor::getText() const
  43078. {
  43079. String t;
  43080. t.preallocateStorage (getTotalNumChars());
  43081. String::Concatenator concatenator (t);
  43082. for (int i = 0; i < sections.size(); ++i)
  43083. sections.getUnchecked (i)->appendAllText (concatenator);
  43084. return t;
  43085. }
  43086. const String TextEditor::getTextInRange (const Range<int>& range) const
  43087. {
  43088. String t;
  43089. if (! range.isEmpty())
  43090. {
  43091. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  43092. String::Concatenator concatenator (t);
  43093. int index = 0;
  43094. for (int i = 0; i < sections.size(); ++i)
  43095. {
  43096. const UniformTextSection* const s = sections.getUnchecked (i);
  43097. const int nextIndex = index + s->getTotalLength();
  43098. if (range.getStart() < nextIndex)
  43099. {
  43100. if (range.getEnd() <= index)
  43101. break;
  43102. s->appendSubstring (concatenator, range - index);
  43103. }
  43104. index = nextIndex;
  43105. }
  43106. }
  43107. return t;
  43108. }
  43109. const String TextEditor::getHighlightedText() const
  43110. {
  43111. return getTextInRange (selection);
  43112. }
  43113. int TextEditor::getTotalNumChars() const
  43114. {
  43115. if (totalNumChars < 0)
  43116. {
  43117. totalNumChars = 0;
  43118. for (int i = sections.size(); --i >= 0;)
  43119. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  43120. }
  43121. return totalNumChars;
  43122. }
  43123. bool TextEditor::isEmpty() const
  43124. {
  43125. return getTotalNumChars() == 0;
  43126. }
  43127. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  43128. {
  43129. const float wordWrapWidth = getWordWrapWidth();
  43130. if (wordWrapWidth > 0 && sections.size() > 0)
  43131. {
  43132. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43133. i.getCharPosition (index, cx, cy, lineHeight);
  43134. }
  43135. else
  43136. {
  43137. cx = cy = 0;
  43138. lineHeight = currentFont.getHeight();
  43139. }
  43140. }
  43141. int TextEditor::indexAtPosition (const float x, const float y)
  43142. {
  43143. const float wordWrapWidth = getWordWrapWidth();
  43144. if (wordWrapWidth > 0)
  43145. {
  43146. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43147. while (i.next())
  43148. {
  43149. if (i.lineY + i.lineHeight > y)
  43150. {
  43151. if (i.lineY > y)
  43152. return jmax (0, i.indexInText - 1);
  43153. if (i.atomX >= x)
  43154. return i.indexInText;
  43155. if (x < i.atomRight)
  43156. return i.xToIndex (x);
  43157. }
  43158. }
  43159. }
  43160. return getTotalNumChars();
  43161. }
  43162. static int getCharacterCategory (const juce_wchar character)
  43163. {
  43164. return CharacterFunctions::isLetterOrDigit (character)
  43165. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  43166. }
  43167. int TextEditor::findWordBreakAfter (const int position) const
  43168. {
  43169. const String t (getTextInRange (Range<int> (position, position + 512)));
  43170. const int totalLength = t.length();
  43171. int i = 0;
  43172. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43173. ++i;
  43174. const int type = getCharacterCategory (t[i]);
  43175. while (i < totalLength && type == getCharacterCategory (t[i]))
  43176. ++i;
  43177. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43178. ++i;
  43179. return position + i;
  43180. }
  43181. int TextEditor::findWordBreakBefore (const int position) const
  43182. {
  43183. if (position <= 0)
  43184. return 0;
  43185. const int startOfBuffer = jmax (0, position - 512);
  43186. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  43187. int i = position - startOfBuffer;
  43188. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  43189. --i;
  43190. if (i > 0)
  43191. {
  43192. const int type = getCharacterCategory (t [i - 1]);
  43193. while (i > 0 && type == getCharacterCategory (t [i - 1]))
  43194. --i;
  43195. }
  43196. jassert (startOfBuffer + i >= 0);
  43197. return startOfBuffer + i;
  43198. }
  43199. void TextEditor::splitSection (const int sectionIndex,
  43200. const int charToSplitAt)
  43201. {
  43202. jassert (sections[sectionIndex] != 0);
  43203. sections.insert (sectionIndex + 1,
  43204. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  43205. }
  43206. void TextEditor::coalesceSimilarSections()
  43207. {
  43208. for (int i = 0; i < sections.size() - 1; ++i)
  43209. {
  43210. UniformTextSection* const s1 = sections.getUnchecked (i);
  43211. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  43212. if (s1->font == s2->font
  43213. && s1->colour == s2->colour)
  43214. {
  43215. s1->append (*s2, passwordCharacter);
  43216. sections.remove (i + 1);
  43217. delete s2;
  43218. --i;
  43219. }
  43220. }
  43221. }
  43222. END_JUCE_NAMESPACE
  43223. /*** End of inlined file: juce_TextEditor.cpp ***/
  43224. /*** Start of inlined file: juce_Toolbar.cpp ***/
  43225. BEGIN_JUCE_NAMESPACE
  43226. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  43227. class ToolbarSpacerComp : public ToolbarItemComponent
  43228. {
  43229. public:
  43230. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  43231. : ToolbarItemComponent (itemId_, String::empty, false),
  43232. fixedSize (fixedSize_),
  43233. drawBar (drawBar_)
  43234. {
  43235. }
  43236. ~ToolbarSpacerComp()
  43237. {
  43238. }
  43239. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  43240. int& preferredSize, int& minSize, int& maxSize)
  43241. {
  43242. if (fixedSize <= 0)
  43243. {
  43244. preferredSize = toolbarThickness * 2;
  43245. minSize = 4;
  43246. maxSize = 32768;
  43247. }
  43248. else
  43249. {
  43250. maxSize = roundToInt (toolbarThickness * fixedSize);
  43251. minSize = drawBar ? maxSize : jmin (4, maxSize);
  43252. preferredSize = maxSize;
  43253. if (getEditingMode() == editableOnPalette)
  43254. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  43255. }
  43256. return true;
  43257. }
  43258. void paintButtonArea (Graphics&, int, int, bool, bool)
  43259. {
  43260. }
  43261. void contentAreaChanged (const Rectangle<int>&)
  43262. {
  43263. }
  43264. int getResizeOrder() const throw()
  43265. {
  43266. return fixedSize <= 0 ? 0 : 1;
  43267. }
  43268. void paint (Graphics& g)
  43269. {
  43270. const int w = getWidth();
  43271. const int h = getHeight();
  43272. if (drawBar)
  43273. {
  43274. g.setColour (findColour (Toolbar::separatorColourId, true));
  43275. const float thickness = 0.2f;
  43276. if (isToolbarVertical())
  43277. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  43278. else
  43279. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  43280. }
  43281. if (getEditingMode() != normalMode && ! drawBar)
  43282. {
  43283. g.setColour (findColour (Toolbar::separatorColourId, true));
  43284. const int indentX = jmin (2, (w - 3) / 2);
  43285. const int indentY = jmin (2, (h - 3) / 2);
  43286. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  43287. if (fixedSize <= 0)
  43288. {
  43289. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  43290. if (isToolbarVertical())
  43291. {
  43292. x1 = w * 0.5f;
  43293. y1 = h * 0.4f;
  43294. x2 = x1;
  43295. y2 = indentX * 2.0f;
  43296. x3 = x1;
  43297. y3 = h * 0.6f;
  43298. x4 = x1;
  43299. y4 = h - y2;
  43300. hw = w * 0.15f;
  43301. hl = w * 0.2f;
  43302. }
  43303. else
  43304. {
  43305. x1 = w * 0.4f;
  43306. y1 = h * 0.5f;
  43307. x2 = indentX * 2.0f;
  43308. y2 = y1;
  43309. x3 = w * 0.6f;
  43310. y3 = y1;
  43311. x4 = w - x2;
  43312. y4 = y1;
  43313. hw = h * 0.15f;
  43314. hl = h * 0.2f;
  43315. }
  43316. Path p;
  43317. p.addArrow (x1, y1, x2, y2, 1.5f, hw, hl);
  43318. p.addArrow (x3, y3, x4, y4, 1.5f, hw, hl);
  43319. g.fillPath (p);
  43320. }
  43321. }
  43322. }
  43323. juce_UseDebuggingNewOperator
  43324. private:
  43325. const float fixedSize;
  43326. const bool drawBar;
  43327. ToolbarSpacerComp (const ToolbarSpacerComp&);
  43328. ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  43329. };
  43330. class MissingItemsComponent : public PopupMenuCustomComponent
  43331. {
  43332. public:
  43333. MissingItemsComponent (Toolbar& owner_, const int height_)
  43334. : PopupMenuCustomComponent (true),
  43335. owner (owner_),
  43336. height (height_)
  43337. {
  43338. for (int i = owner_.items.size(); --i >= 0;)
  43339. {
  43340. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  43341. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  43342. {
  43343. oldIndexes.insert (0, i);
  43344. addAndMakeVisible (tc, 0);
  43345. }
  43346. }
  43347. layout (400);
  43348. }
  43349. ~MissingItemsComponent()
  43350. {
  43351. // deleting the toolbar while its menu it open??
  43352. jassert (owner.isValidComponent());
  43353. for (int i = 0; i < getNumChildComponents(); ++i)
  43354. {
  43355. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  43356. if (tc != 0)
  43357. {
  43358. tc->setVisible (false);
  43359. const int index = oldIndexes.remove (i);
  43360. owner.addChildComponent (tc, index);
  43361. --i;
  43362. }
  43363. }
  43364. owner.resized();
  43365. }
  43366. void layout (const int preferredWidth)
  43367. {
  43368. const int indent = 8;
  43369. int x = indent;
  43370. int y = indent;
  43371. int maxX = 0;
  43372. for (int i = 0; i < getNumChildComponents(); ++i)
  43373. {
  43374. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  43375. if (tc != 0)
  43376. {
  43377. int preferredSize = 1, minSize = 1, maxSize = 1;
  43378. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  43379. {
  43380. if (x + preferredSize > preferredWidth && x > indent)
  43381. {
  43382. x = indent;
  43383. y += height;
  43384. }
  43385. tc->setBounds (x, y, preferredSize, height);
  43386. x += preferredSize;
  43387. maxX = jmax (maxX, x);
  43388. }
  43389. }
  43390. }
  43391. setSize (maxX + 8, y + height + 8);
  43392. }
  43393. void getIdealSize (int& idealWidth, int& idealHeight)
  43394. {
  43395. idealWidth = getWidth();
  43396. idealHeight = getHeight();
  43397. }
  43398. juce_UseDebuggingNewOperator
  43399. private:
  43400. Toolbar& owner;
  43401. const int height;
  43402. Array <int> oldIndexes;
  43403. MissingItemsComponent (const MissingItemsComponent&);
  43404. MissingItemsComponent& operator= (const MissingItemsComponent&);
  43405. };
  43406. Toolbar::Toolbar()
  43407. : vertical (false),
  43408. isEditingActive (false),
  43409. toolbarStyle (Toolbar::iconsOnly)
  43410. {
  43411. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  43412. missingItemsButton->setAlwaysOnTop (true);
  43413. missingItemsButton->addButtonListener (this);
  43414. }
  43415. Toolbar::~Toolbar()
  43416. {
  43417. animator.cancelAllAnimations (true);
  43418. deleteAllChildren();
  43419. }
  43420. void Toolbar::setVertical (const bool shouldBeVertical)
  43421. {
  43422. if (vertical != shouldBeVertical)
  43423. {
  43424. vertical = shouldBeVertical;
  43425. resized();
  43426. }
  43427. }
  43428. void Toolbar::clear()
  43429. {
  43430. for (int i = items.size(); --i >= 0;)
  43431. {
  43432. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43433. items.remove (i);
  43434. delete tc;
  43435. }
  43436. resized();
  43437. }
  43438. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  43439. {
  43440. if (itemId == ToolbarItemFactory::separatorBarId)
  43441. return new ToolbarSpacerComp (itemId, 0.1f, true);
  43442. else if (itemId == ToolbarItemFactory::spacerId)
  43443. return new ToolbarSpacerComp (itemId, 0.5f, false);
  43444. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  43445. return new ToolbarSpacerComp (itemId, 0, false);
  43446. return factory.createItem (itemId);
  43447. }
  43448. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  43449. const int itemId,
  43450. const int insertIndex)
  43451. {
  43452. // An ID can't be zero - this might indicate a mistake somewhere?
  43453. jassert (itemId != 0);
  43454. ToolbarItemComponent* const tc = createItem (factory, itemId);
  43455. if (tc != 0)
  43456. {
  43457. #if JUCE_DEBUG
  43458. Array <int> allowedIds;
  43459. factory.getAllToolbarItemIds (allowedIds);
  43460. // If your factory can create an item for a given ID, it must also return
  43461. // that ID from its getAllToolbarItemIds() method!
  43462. jassert (allowedIds.contains (itemId));
  43463. #endif
  43464. items.insert (insertIndex, tc);
  43465. addAndMakeVisible (tc, insertIndex);
  43466. }
  43467. }
  43468. void Toolbar::addItem (ToolbarItemFactory& factory,
  43469. const int itemId,
  43470. const int insertIndex)
  43471. {
  43472. addItemInternal (factory, itemId, insertIndex);
  43473. resized();
  43474. }
  43475. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  43476. {
  43477. Array <int> ids;
  43478. factoryToUse.getDefaultItemSet (ids);
  43479. clear();
  43480. for (int i = 0; i < ids.size(); ++i)
  43481. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  43482. resized();
  43483. }
  43484. void Toolbar::removeToolbarItem (const int itemIndex)
  43485. {
  43486. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  43487. if (tc != 0)
  43488. {
  43489. items.removeValue (tc);
  43490. delete tc;
  43491. resized();
  43492. }
  43493. }
  43494. int Toolbar::getNumItems() const throw()
  43495. {
  43496. return items.size();
  43497. }
  43498. int Toolbar::getItemId (const int itemIndex) const throw()
  43499. {
  43500. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  43501. return tc != 0 ? tc->getItemId() : 0;
  43502. }
  43503. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  43504. {
  43505. return items [itemIndex];
  43506. }
  43507. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  43508. {
  43509. for (;;)
  43510. {
  43511. index += delta;
  43512. ToolbarItemComponent* const tc = getItemComponent (index);
  43513. if (tc == 0)
  43514. break;
  43515. if (tc->isActive)
  43516. return tc;
  43517. }
  43518. return 0;
  43519. }
  43520. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  43521. {
  43522. if (toolbarStyle != newStyle)
  43523. {
  43524. toolbarStyle = newStyle;
  43525. updateAllItemPositions (false);
  43526. }
  43527. }
  43528. const String Toolbar::toString() const
  43529. {
  43530. String s ("TB:");
  43531. for (int i = 0; i < getNumItems(); ++i)
  43532. s << getItemId(i) << ' ';
  43533. return s.trimEnd();
  43534. }
  43535. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  43536. const String& savedVersion)
  43537. {
  43538. if (! savedVersion.startsWith ("TB:"))
  43539. return false;
  43540. StringArray tokens;
  43541. tokens.addTokens (savedVersion.substring (3), false);
  43542. clear();
  43543. for (int i = 0; i < tokens.size(); ++i)
  43544. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  43545. resized();
  43546. return true;
  43547. }
  43548. void Toolbar::paint (Graphics& g)
  43549. {
  43550. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  43551. }
  43552. int Toolbar::getThickness() const throw()
  43553. {
  43554. return vertical ? getWidth() : getHeight();
  43555. }
  43556. int Toolbar::getLength() const throw()
  43557. {
  43558. return vertical ? getHeight() : getWidth();
  43559. }
  43560. void Toolbar::setEditingActive (const bool active)
  43561. {
  43562. if (isEditingActive != active)
  43563. {
  43564. isEditingActive = active;
  43565. updateAllItemPositions (false);
  43566. }
  43567. }
  43568. void Toolbar::resized()
  43569. {
  43570. updateAllItemPositions (false);
  43571. }
  43572. void Toolbar::updateAllItemPositions (const bool animate)
  43573. {
  43574. if (getWidth() > 0 && getHeight() > 0)
  43575. {
  43576. StretchableObjectResizer resizer;
  43577. int i;
  43578. for (i = 0; i < items.size(); ++i)
  43579. {
  43580. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43581. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  43582. : ToolbarItemComponent::normalMode);
  43583. tc->setStyle (toolbarStyle);
  43584. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  43585. int preferredSize = 1, minSize = 1, maxSize = 1;
  43586. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  43587. preferredSize, minSize, maxSize))
  43588. {
  43589. tc->isActive = true;
  43590. resizer.addItem (preferredSize, minSize, maxSize,
  43591. spacer != 0 ? spacer->getResizeOrder() : 2);
  43592. }
  43593. else
  43594. {
  43595. tc->isActive = false;
  43596. tc->setVisible (false);
  43597. }
  43598. }
  43599. resizer.resizeToFit (getLength());
  43600. int totalLength = 0;
  43601. for (i = 0; i < resizer.getNumItems(); ++i)
  43602. totalLength += (int) resizer.getItemSize (i);
  43603. const bool itemsOffTheEnd = totalLength > getLength();
  43604. const int extrasButtonSize = getThickness() / 2;
  43605. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  43606. missingItemsButton->setVisible (itemsOffTheEnd);
  43607. missingItemsButton->setEnabled (! isEditingActive);
  43608. if (vertical)
  43609. missingItemsButton->setCentrePosition (getWidth() / 2,
  43610. getHeight() - 4 - extrasButtonSize / 2);
  43611. else
  43612. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  43613. getHeight() / 2);
  43614. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  43615. : missingItemsButton->getX()) - 4
  43616. : getLength();
  43617. int pos = 0, activeIndex = 0;
  43618. for (i = 0; i < items.size(); ++i)
  43619. {
  43620. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43621. if (tc->isActive)
  43622. {
  43623. const int size = (int) resizer.getItemSize (activeIndex++);
  43624. Rectangle<int> newBounds;
  43625. if (vertical)
  43626. newBounds.setBounds (0, pos, getWidth(), size);
  43627. else
  43628. newBounds.setBounds (pos, 0, size, getHeight());
  43629. if (animate)
  43630. {
  43631. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  43632. }
  43633. else
  43634. {
  43635. animator.cancelAnimation (tc, false);
  43636. tc->setBounds (newBounds);
  43637. }
  43638. pos += size;
  43639. tc->setVisible (pos <= maxLength
  43640. && ((! tc->isBeingDragged)
  43641. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  43642. }
  43643. }
  43644. }
  43645. }
  43646. void Toolbar::buttonClicked (Button*)
  43647. {
  43648. jassert (missingItemsButton->isShowing());
  43649. if (missingItemsButton->isShowing())
  43650. {
  43651. PopupMenu m;
  43652. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  43653. m.showAt (missingItemsButton);
  43654. }
  43655. }
  43656. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  43657. Component* /*sourceComponent*/)
  43658. {
  43659. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  43660. }
  43661. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  43662. {
  43663. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  43664. if (tc != 0)
  43665. {
  43666. if (getNumItems() == 0)
  43667. {
  43668. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  43669. {
  43670. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  43671. if (palette != 0)
  43672. palette->replaceComponent (tc);
  43673. }
  43674. else
  43675. {
  43676. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  43677. }
  43678. items.add (tc);
  43679. addChildComponent (tc);
  43680. updateAllItemPositions (false);
  43681. }
  43682. else
  43683. {
  43684. for (int i = getNumItems(); --i >= 0;)
  43685. {
  43686. int currentIndex = getIndexOfChildComponent (tc);
  43687. if (currentIndex < 0)
  43688. {
  43689. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  43690. {
  43691. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  43692. if (palette != 0)
  43693. palette->replaceComponent (tc);
  43694. }
  43695. else
  43696. {
  43697. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  43698. }
  43699. items.add (tc);
  43700. addChildComponent (tc);
  43701. currentIndex = getIndexOfChildComponent (tc);
  43702. updateAllItemPositions (true);
  43703. }
  43704. int newIndex = currentIndex;
  43705. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  43706. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  43707. const Rectangle<int> current (animator.getComponentDestination (getChildComponent (newIndex)));
  43708. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  43709. if (prev != 0)
  43710. {
  43711. const Rectangle<int> previousPos (animator.getComponentDestination (prev));
  43712. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  43713. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  43714. {
  43715. newIndex = getIndexOfChildComponent (prev);
  43716. }
  43717. }
  43718. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  43719. if (next != 0)
  43720. {
  43721. const Rectangle<int> nextPos (animator.getComponentDestination (next));
  43722. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  43723. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  43724. {
  43725. newIndex = getIndexOfChildComponent (next) + 1;
  43726. }
  43727. }
  43728. if (newIndex != currentIndex)
  43729. {
  43730. items.removeValue (tc);
  43731. removeChildComponent (tc);
  43732. addChildComponent (tc, newIndex);
  43733. items.insert (newIndex, tc);
  43734. updateAllItemPositions (true);
  43735. }
  43736. else
  43737. {
  43738. break;
  43739. }
  43740. }
  43741. }
  43742. }
  43743. }
  43744. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  43745. {
  43746. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  43747. if (tc != 0)
  43748. {
  43749. if (isParentOf (tc))
  43750. {
  43751. items.removeValue (tc);
  43752. removeChildComponent (tc);
  43753. updateAllItemPositions (true);
  43754. }
  43755. }
  43756. }
  43757. void Toolbar::itemDropped (const String&, Component*, int, int)
  43758. {
  43759. }
  43760. void Toolbar::mouseDown (const MouseEvent& e)
  43761. {
  43762. if (e.mods.isPopupMenu())
  43763. {
  43764. }
  43765. }
  43766. class ToolbarCustomisationDialog : public DialogWindow
  43767. {
  43768. public:
  43769. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  43770. Toolbar* const toolbar_,
  43771. const int optionFlags)
  43772. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  43773. toolbar (toolbar_)
  43774. {
  43775. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  43776. setResizable (true, true);
  43777. setResizeLimits (400, 300, 1500, 1000);
  43778. positionNearBar();
  43779. }
  43780. ~ToolbarCustomisationDialog()
  43781. {
  43782. setContentComponent (0, true);
  43783. }
  43784. void closeButtonPressed()
  43785. {
  43786. setVisible (false);
  43787. }
  43788. bool canModalEventBeSentToComponent (const Component* comp)
  43789. {
  43790. return toolbar->isParentOf (comp);
  43791. }
  43792. void positionNearBar()
  43793. {
  43794. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  43795. const int tbx = toolbar->getScreenX();
  43796. const int tby = toolbar->getScreenY();
  43797. const int gap = 8;
  43798. int x, y;
  43799. if (toolbar->isVertical())
  43800. {
  43801. y = tby;
  43802. if (tbx > screenSize.getCentreX())
  43803. x = tbx - getWidth() - gap;
  43804. else
  43805. x = tbx + toolbar->getWidth() + gap;
  43806. }
  43807. else
  43808. {
  43809. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  43810. if (tby > screenSize.getCentreY())
  43811. y = tby - getHeight() - gap;
  43812. else
  43813. y = tby + toolbar->getHeight() + gap;
  43814. }
  43815. setTopLeftPosition (x, y);
  43816. }
  43817. private:
  43818. Toolbar* const toolbar;
  43819. class CustomiserPanel : public Component,
  43820. private ComboBoxListener,
  43821. private ButtonListener
  43822. {
  43823. public:
  43824. CustomiserPanel (ToolbarItemFactory& factory_,
  43825. Toolbar* const toolbar_,
  43826. const int optionFlags)
  43827. : factory (factory_),
  43828. toolbar (toolbar_),
  43829. styleBox (0),
  43830. defaultButton (0)
  43831. {
  43832. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  43833. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  43834. | Toolbar::allowIconsWithTextChoice
  43835. | Toolbar::allowTextOnlyChoice)) != 0)
  43836. {
  43837. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  43838. styleBox->setEditableText (false);
  43839. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  43840. styleBox->addItem (TRANS("Show icons only"), 1);
  43841. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  43842. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  43843. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  43844. styleBox->addItem (TRANS("Show descriptions only"), 3);
  43845. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  43846. styleBox->setSelectedId (1);
  43847. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  43848. styleBox->setSelectedId (2);
  43849. else if (toolbar_->getStyle() == Toolbar::textOnly)
  43850. styleBox->setSelectedId (3);
  43851. styleBox->addListener (this);
  43852. }
  43853. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  43854. {
  43855. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  43856. defaultButton->addButtonListener (this);
  43857. }
  43858. addAndMakeVisible (instructions = new Label (String::empty,
  43859. 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.")));
  43860. instructions->setFont (Font (13.0f));
  43861. setSize (500, 300);
  43862. }
  43863. ~CustomiserPanel()
  43864. {
  43865. deleteAllChildren();
  43866. }
  43867. void comboBoxChanged (ComboBox*)
  43868. {
  43869. if (styleBox->getSelectedId() == 1)
  43870. toolbar->setStyle (Toolbar::iconsOnly);
  43871. else if (styleBox->getSelectedId() == 2)
  43872. toolbar->setStyle (Toolbar::iconsWithText);
  43873. else if (styleBox->getSelectedId() == 3)
  43874. toolbar->setStyle (Toolbar::textOnly);
  43875. palette->resized(); // to make it update the styles
  43876. }
  43877. void buttonClicked (Button*)
  43878. {
  43879. toolbar->addDefaultItems (factory);
  43880. }
  43881. void paint (Graphics& g)
  43882. {
  43883. Colour background;
  43884. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  43885. if (dw != 0)
  43886. background = dw->getBackgroundColour();
  43887. g.setColour (background.contrasting().withAlpha (0.3f));
  43888. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  43889. }
  43890. void resized()
  43891. {
  43892. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  43893. if (styleBox != 0)
  43894. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  43895. if (defaultButton != 0)
  43896. {
  43897. defaultButton->changeWidthToFitText (22);
  43898. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  43899. }
  43900. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  43901. }
  43902. private:
  43903. ToolbarItemFactory& factory;
  43904. Toolbar* const toolbar;
  43905. Label* instructions;
  43906. ToolbarItemPalette* palette;
  43907. ComboBox* styleBox;
  43908. TextButton* defaultButton;
  43909. };
  43910. };
  43911. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  43912. {
  43913. setEditingActive (true);
  43914. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  43915. dw.runModalLoop();
  43916. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  43917. setEditingActive (false);
  43918. }
  43919. END_JUCE_NAMESPACE
  43920. /*** End of inlined file: juce_Toolbar.cpp ***/
  43921. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  43922. BEGIN_JUCE_NAMESPACE
  43923. ToolbarItemFactory::ToolbarItemFactory()
  43924. {
  43925. }
  43926. ToolbarItemFactory::~ToolbarItemFactory()
  43927. {
  43928. }
  43929. class ItemDragAndDropOverlayComponent : public Component
  43930. {
  43931. public:
  43932. ItemDragAndDropOverlayComponent()
  43933. : isDragging (false)
  43934. {
  43935. setAlwaysOnTop (true);
  43936. setRepaintsOnMouseActivity (true);
  43937. setMouseCursor (MouseCursor::DraggingHandCursor);
  43938. }
  43939. ~ItemDragAndDropOverlayComponent()
  43940. {
  43941. }
  43942. void paint (Graphics& g)
  43943. {
  43944. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  43945. if (isMouseOverOrDragging()
  43946. && tc != 0
  43947. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  43948. {
  43949. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  43950. g.drawRect (0, 0, getWidth(), getHeight(),
  43951. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  43952. }
  43953. }
  43954. void mouseDown (const MouseEvent& e)
  43955. {
  43956. isDragging = false;
  43957. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  43958. if (tc != 0)
  43959. {
  43960. tc->dragOffsetX = e.x;
  43961. tc->dragOffsetY = e.y;
  43962. }
  43963. }
  43964. void mouseDrag (const MouseEvent& e)
  43965. {
  43966. if (! (isDragging || e.mouseWasClicked()))
  43967. {
  43968. isDragging = true;
  43969. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  43970. if (dnd != 0)
  43971. {
  43972. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), 0, true);
  43973. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  43974. if (tc != 0)
  43975. {
  43976. tc->isBeingDragged = true;
  43977. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  43978. tc->setVisible (false);
  43979. }
  43980. }
  43981. }
  43982. }
  43983. void mouseUp (const MouseEvent&)
  43984. {
  43985. isDragging = false;
  43986. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  43987. if (tc != 0)
  43988. {
  43989. tc->isBeingDragged = false;
  43990. Toolbar* const tb = tc->getToolbar();
  43991. if (tb != 0)
  43992. tb->updateAllItemPositions (true);
  43993. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  43994. delete tc;
  43995. }
  43996. }
  43997. void parentSizeChanged()
  43998. {
  43999. setBounds (0, 0, getParentWidth(), getParentHeight());
  44000. }
  44001. juce_UseDebuggingNewOperator
  44002. private:
  44003. bool isDragging;
  44004. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  44005. ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  44006. };
  44007. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  44008. const String& labelText,
  44009. const bool isBeingUsedAsAButton_)
  44010. : Button (labelText),
  44011. itemId (itemId_),
  44012. mode (normalMode),
  44013. toolbarStyle (Toolbar::iconsOnly),
  44014. dragOffsetX (0),
  44015. dragOffsetY (0),
  44016. isActive (true),
  44017. isBeingDragged (false),
  44018. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  44019. {
  44020. // Your item ID can't be 0!
  44021. jassert (itemId_ != 0);
  44022. }
  44023. ToolbarItemComponent::~ToolbarItemComponent()
  44024. {
  44025. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  44026. overlayComp = 0;
  44027. }
  44028. Toolbar* ToolbarItemComponent::getToolbar() const
  44029. {
  44030. return dynamic_cast <Toolbar*> (getParentComponent());
  44031. }
  44032. bool ToolbarItemComponent::isToolbarVertical() const
  44033. {
  44034. const Toolbar* const t = getToolbar();
  44035. return t != 0 && t->isVertical();
  44036. }
  44037. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  44038. {
  44039. if (toolbarStyle != newStyle)
  44040. {
  44041. toolbarStyle = newStyle;
  44042. repaint();
  44043. resized();
  44044. }
  44045. }
  44046. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  44047. {
  44048. if (isBeingUsedAsAButton)
  44049. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  44050. over, down, *this);
  44051. if (toolbarStyle != Toolbar::iconsOnly)
  44052. {
  44053. const int indent = contentArea.getX();
  44054. int y = indent;
  44055. int h = getHeight() - indent * 2;
  44056. if (toolbarStyle == Toolbar::iconsWithText)
  44057. {
  44058. y = contentArea.getBottom() + indent / 2;
  44059. h -= contentArea.getHeight();
  44060. }
  44061. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  44062. getButtonText(), *this);
  44063. }
  44064. if (! contentArea.isEmpty())
  44065. {
  44066. g.saveState();
  44067. g.setOrigin (contentArea.getX(), contentArea.getY());
  44068. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  44069. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  44070. g.restoreState();
  44071. }
  44072. }
  44073. void ToolbarItemComponent::resized()
  44074. {
  44075. if (toolbarStyle != Toolbar::textOnly)
  44076. {
  44077. const int indent = jmin (proportionOfWidth (0.08f),
  44078. proportionOfHeight (0.08f));
  44079. contentArea = Rectangle<int> (indent, indent,
  44080. getWidth() - indent * 2,
  44081. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  44082. : (getHeight() - indent * 2));
  44083. }
  44084. else
  44085. {
  44086. contentArea = Rectangle<int>();
  44087. }
  44088. contentAreaChanged (contentArea);
  44089. }
  44090. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  44091. {
  44092. if (mode != newMode)
  44093. {
  44094. mode = newMode;
  44095. repaint();
  44096. if (mode == normalMode)
  44097. {
  44098. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  44099. overlayComp = 0;
  44100. }
  44101. else if (overlayComp == 0)
  44102. {
  44103. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  44104. overlayComp->parentSizeChanged();
  44105. }
  44106. resized();
  44107. }
  44108. }
  44109. END_JUCE_NAMESPACE
  44110. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  44111. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  44112. BEGIN_JUCE_NAMESPACE
  44113. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  44114. Toolbar* const toolbar_)
  44115. : factory (factory_),
  44116. toolbar (toolbar_)
  44117. {
  44118. Component* const itemHolder = new Component();
  44119. Array <int> allIds;
  44120. factory_.getAllToolbarItemIds (allIds);
  44121. for (int i = 0; i < allIds.size(); ++i)
  44122. {
  44123. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  44124. jassert (tc != 0);
  44125. if (tc != 0)
  44126. {
  44127. itemHolder->addAndMakeVisible (tc);
  44128. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  44129. }
  44130. }
  44131. viewport = new Viewport();
  44132. viewport->setViewedComponent (itemHolder);
  44133. addAndMakeVisible (viewport);
  44134. }
  44135. ToolbarItemPalette::~ToolbarItemPalette()
  44136. {
  44137. viewport->getViewedComponent()->deleteAllChildren();
  44138. deleteAllChildren();
  44139. }
  44140. void ToolbarItemPalette::resized()
  44141. {
  44142. viewport->setBoundsInset (BorderSize (1));
  44143. Component* const itemHolder = viewport->getViewedComponent();
  44144. const int indent = 8;
  44145. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  44146. const int height = toolbar->getThickness();
  44147. int x = indent;
  44148. int y = indent;
  44149. int maxX = 0;
  44150. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  44151. {
  44152. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  44153. if (tc != 0)
  44154. {
  44155. tc->setStyle (toolbar->getStyle());
  44156. int preferredSize = 1, minSize = 1, maxSize = 1;
  44157. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44158. {
  44159. if (x + preferredSize > preferredWidth && x > indent)
  44160. {
  44161. x = indent;
  44162. y += height;
  44163. }
  44164. tc->setBounds (x, y, preferredSize, height);
  44165. x += preferredSize + 8;
  44166. maxX = jmax (maxX, x);
  44167. }
  44168. }
  44169. }
  44170. itemHolder->setSize (maxX, y + height + 8);
  44171. }
  44172. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  44173. {
  44174. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  44175. jassert (tc != 0);
  44176. if (tc != 0)
  44177. {
  44178. tc->setBounds (comp->getBounds());
  44179. tc->setStyle (toolbar->getStyle());
  44180. tc->setEditingMode (comp->getEditingMode());
  44181. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  44182. }
  44183. }
  44184. END_JUCE_NAMESPACE
  44185. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  44186. /*** Start of inlined file: juce_TreeView.cpp ***/
  44187. BEGIN_JUCE_NAMESPACE
  44188. class TreeViewContentComponent : public Component,
  44189. public TooltipClient
  44190. {
  44191. public:
  44192. TreeViewContentComponent (TreeView& owner_)
  44193. : owner (owner_),
  44194. buttonUnderMouse (0),
  44195. isDragging (false)
  44196. {
  44197. }
  44198. ~TreeViewContentComponent()
  44199. {
  44200. deleteAllChildren();
  44201. }
  44202. void mouseDown (const MouseEvent& e)
  44203. {
  44204. updateButtonUnderMouse (e);
  44205. isDragging = false;
  44206. needSelectionOnMouseUp = false;
  44207. Rectangle<int> pos;
  44208. TreeViewItem* const item = findItemAt (e.y, pos);
  44209. if (item == 0)
  44210. return;
  44211. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  44212. // as selection clicks)
  44213. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  44214. {
  44215. if (e.x >= pos.getX() - owner.getIndentSize())
  44216. item->setOpen (! item->isOpen());
  44217. // (clicks to the left of an open/close button are ignored)
  44218. }
  44219. else
  44220. {
  44221. // mouse-down inside the body of the item..
  44222. if (! owner.isMultiSelectEnabled())
  44223. item->setSelected (true, true);
  44224. else if (item->isSelected())
  44225. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  44226. else
  44227. selectBasedOnModifiers (item, e.mods);
  44228. if (e.x >= pos.getX())
  44229. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44230. }
  44231. }
  44232. void mouseUp (const MouseEvent& e)
  44233. {
  44234. updateButtonUnderMouse (e);
  44235. if (needSelectionOnMouseUp && e.mouseWasClicked())
  44236. {
  44237. Rectangle<int> pos;
  44238. TreeViewItem* const item = findItemAt (e.y, pos);
  44239. if (item != 0)
  44240. selectBasedOnModifiers (item, e.mods);
  44241. }
  44242. }
  44243. void mouseDoubleClick (const MouseEvent& e)
  44244. {
  44245. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  44246. {
  44247. Rectangle<int> pos;
  44248. TreeViewItem* const item = findItemAt (e.y, pos);
  44249. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  44250. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44251. }
  44252. }
  44253. void mouseDrag (const MouseEvent& e)
  44254. {
  44255. if (isEnabled()
  44256. && ! (isDragging || e.mouseWasClicked()
  44257. || e.getDistanceFromDragStart() < 5
  44258. || e.mods.isPopupMenu()))
  44259. {
  44260. isDragging = true;
  44261. Rectangle<int> pos;
  44262. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  44263. if (item != 0 && e.getMouseDownX() >= pos.getX())
  44264. {
  44265. const String dragDescription (item->getDragSourceDescription());
  44266. if (dragDescription.isNotEmpty())
  44267. {
  44268. DragAndDropContainer* const dragContainer
  44269. = DragAndDropContainer::findParentDragContainerFor (this);
  44270. if (dragContainer != 0)
  44271. {
  44272. pos.setSize (pos.getWidth(), item->itemHeight);
  44273. Image* dragImage = Component::createComponentSnapshot (pos, true);
  44274. dragImage->multiplyAllAlphas (0.6f);
  44275. Point<int> imageOffset (pos.getX() - e.x, pos.getY() - e.y);
  44276. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  44277. }
  44278. else
  44279. {
  44280. // to be able to do a drag-and-drop operation, the treeview needs to
  44281. // be inside a component which is also a DragAndDropContainer.
  44282. jassertfalse
  44283. }
  44284. }
  44285. }
  44286. }
  44287. }
  44288. void mouseMove (const MouseEvent& e)
  44289. {
  44290. updateButtonUnderMouse (e);
  44291. }
  44292. void mouseExit (const MouseEvent& e)
  44293. {
  44294. updateButtonUnderMouse (e);
  44295. }
  44296. void paint (Graphics& g)
  44297. {
  44298. if (owner.rootItem != 0)
  44299. {
  44300. owner.handleAsyncUpdate();
  44301. if (! owner.rootItemVisible)
  44302. g.setOrigin (0, -owner.rootItem->itemHeight);
  44303. owner.rootItem->paintRecursively (g, getWidth());
  44304. }
  44305. }
  44306. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  44307. {
  44308. if (owner.rootItem != 0)
  44309. {
  44310. owner.handleAsyncUpdate();
  44311. if (! owner.rootItemVisible)
  44312. y += owner.rootItem->itemHeight;
  44313. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  44314. if (ti != 0)
  44315. itemPosition = ti->getItemPosition (false);
  44316. return ti;
  44317. }
  44318. return 0;
  44319. }
  44320. void updateComponents()
  44321. {
  44322. const int visibleTop = -getY();
  44323. const int visibleBottom = visibleTop + getParentHeight();
  44324. BigInteger itemsToKeep;
  44325. {
  44326. TreeViewItem* item = owner.rootItem;
  44327. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  44328. while (item != 0 && y < visibleBottom)
  44329. {
  44330. y += item->itemHeight;
  44331. if (y >= visibleTop)
  44332. {
  44333. const int index = rowComponentIds.indexOf (item->uid);
  44334. if (index < 0)
  44335. {
  44336. Component* const comp = item->createItemComponent();
  44337. if (comp != 0)
  44338. {
  44339. addAndMakeVisible (comp);
  44340. itemsToKeep.setBit (rowComponentItems.size());
  44341. rowComponentItems.add (item);
  44342. rowComponentIds.add (item->uid);
  44343. rowComponents.add (comp);
  44344. }
  44345. }
  44346. else
  44347. {
  44348. itemsToKeep.setBit (index);
  44349. }
  44350. }
  44351. item = item->getNextVisibleItem (true);
  44352. }
  44353. }
  44354. for (int i = rowComponentItems.size(); --i >= 0;)
  44355. {
  44356. Component* const comp = rowComponents.getUnchecked(i);
  44357. bool keep = false;
  44358. if (isParentOf (comp))
  44359. {
  44360. if (itemsToKeep[i])
  44361. {
  44362. const TreeViewItem* const item = rowComponentItems.getUnchecked(i);
  44363. Rectangle<int> pos (item->getItemPosition (false));
  44364. pos.setSize (pos.getWidth(), item->itemHeight);
  44365. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  44366. {
  44367. keep = true;
  44368. comp->setBounds (pos);
  44369. }
  44370. }
  44371. if ((! keep) && isMouseDraggingInChildCompOf (comp))
  44372. {
  44373. keep = true;
  44374. comp->setSize (0, 0);
  44375. }
  44376. }
  44377. if (! keep)
  44378. {
  44379. delete comp;
  44380. rowComponents.remove (i);
  44381. rowComponentIds.remove (i);
  44382. rowComponentItems.remove (i);
  44383. }
  44384. }
  44385. }
  44386. void updateButtonUnderMouse (const MouseEvent& e)
  44387. {
  44388. TreeViewItem* newItem = 0;
  44389. if (owner.openCloseButtonsVisible)
  44390. {
  44391. Rectangle<int> pos;
  44392. TreeViewItem* item = findItemAt (e.y, pos);
  44393. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  44394. {
  44395. newItem = item;
  44396. if (! newItem->mightContainSubItems())
  44397. newItem = 0;
  44398. }
  44399. }
  44400. if (buttonUnderMouse != newItem)
  44401. {
  44402. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  44403. {
  44404. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44405. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44406. }
  44407. buttonUnderMouse = newItem;
  44408. if (buttonUnderMouse != 0)
  44409. {
  44410. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44411. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44412. }
  44413. }
  44414. }
  44415. bool isMouseOverButton (TreeViewItem* const item) const throw()
  44416. {
  44417. return item == buttonUnderMouse;
  44418. }
  44419. void resized()
  44420. {
  44421. owner.itemsChanged();
  44422. }
  44423. const String getTooltip()
  44424. {
  44425. Rectangle<int> pos;
  44426. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  44427. if (item != 0)
  44428. return item->getTooltip();
  44429. return owner.getTooltip();
  44430. }
  44431. juce_UseDebuggingNewOperator
  44432. private:
  44433. TreeView& owner;
  44434. Array <TreeViewItem*> rowComponentItems;
  44435. Array <int> rowComponentIds;
  44436. Array <Component*> rowComponents;
  44437. TreeViewItem* buttonUnderMouse;
  44438. bool isDragging, needSelectionOnMouseUp;
  44439. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  44440. {
  44441. TreeViewItem* firstSelected = 0;
  44442. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  44443. {
  44444. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  44445. jassert (lastSelected != 0);
  44446. int rowStart = firstSelected->getRowNumberInTree();
  44447. int rowEnd = lastSelected->getRowNumberInTree();
  44448. if (rowStart > rowEnd)
  44449. swapVariables (rowStart, rowEnd);
  44450. int ourRow = item->getRowNumberInTree();
  44451. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  44452. if (ourRow > otherEnd)
  44453. swapVariables (ourRow, otherEnd);
  44454. for (int i = ourRow; i <= otherEnd; ++i)
  44455. owner.getItemOnRow (i)->setSelected (true, false);
  44456. }
  44457. else
  44458. {
  44459. const bool cmd = modifiers.isCommandDown();
  44460. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  44461. }
  44462. }
  44463. bool containsItem (TreeViewItem* const item) const
  44464. {
  44465. for (int i = rowComponentItems.size(); --i >= 0;)
  44466. if (rowComponentItems.getUnchecked(i) == item)
  44467. return true;
  44468. return false;
  44469. }
  44470. static bool isMouseDraggingInChildCompOf (Component* const comp)
  44471. {
  44472. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  44473. {
  44474. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  44475. if (source->isDragging())
  44476. {
  44477. Component* const underMouse = source->getComponentUnderMouse();
  44478. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  44479. return true;
  44480. }
  44481. }
  44482. return false;
  44483. }
  44484. TreeViewContentComponent (const TreeViewContentComponent&);
  44485. TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  44486. };
  44487. class TreeView::TreeViewport : public Viewport
  44488. {
  44489. public:
  44490. TreeViewport() throw() : lastX (-1) {}
  44491. ~TreeViewport() throw() {}
  44492. void updateComponents (const bool triggerResize = false)
  44493. {
  44494. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  44495. if (tvc != 0)
  44496. {
  44497. if (triggerResize)
  44498. tvc->resized();
  44499. else
  44500. tvc->updateComponents();
  44501. }
  44502. repaint();
  44503. }
  44504. void visibleAreaChanged (int x, int, int, int)
  44505. {
  44506. const bool hasScrolledSideways = (x != lastX);
  44507. lastX = x;
  44508. updateComponents (hasScrolledSideways);
  44509. }
  44510. juce_UseDebuggingNewOperator
  44511. private:
  44512. int lastX;
  44513. TreeViewport (const TreeViewport&);
  44514. TreeViewport& operator= (const TreeViewport&);
  44515. };
  44516. TreeView::TreeView (const String& componentName)
  44517. : Component (componentName),
  44518. rootItem (0),
  44519. dragInsertPointHighlight (0),
  44520. dragTargetGroupHighlight (0),
  44521. indentSize (24),
  44522. defaultOpenness (false),
  44523. needsRecalculating (true),
  44524. rootItemVisible (true),
  44525. multiSelectEnabled (false),
  44526. openCloseButtonsVisible (true)
  44527. {
  44528. addAndMakeVisible (viewport = new TreeViewport());
  44529. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  44530. viewport->setWantsKeyboardFocus (false);
  44531. setWantsKeyboardFocus (true);
  44532. }
  44533. TreeView::~TreeView()
  44534. {
  44535. if (rootItem != 0)
  44536. rootItem->setOwnerView (0);
  44537. deleteAllChildren();
  44538. }
  44539. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  44540. {
  44541. if (rootItem != newRootItem)
  44542. {
  44543. if (newRootItem != 0)
  44544. {
  44545. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  44546. if (newRootItem->ownerView != 0)
  44547. newRootItem->ownerView->setRootItem (0);
  44548. }
  44549. if (rootItem != 0)
  44550. rootItem->setOwnerView (0);
  44551. rootItem = newRootItem;
  44552. if (newRootItem != 0)
  44553. newRootItem->setOwnerView (this);
  44554. needsRecalculating = true;
  44555. handleAsyncUpdate();
  44556. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  44557. {
  44558. rootItem->setOpen (false); // force a re-open
  44559. rootItem->setOpen (true);
  44560. }
  44561. }
  44562. }
  44563. void TreeView::deleteRootItem()
  44564. {
  44565. const ScopedPointer <TreeViewItem> deleter (rootItem);
  44566. setRootItem (0);
  44567. }
  44568. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  44569. {
  44570. rootItemVisible = shouldBeVisible;
  44571. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  44572. {
  44573. rootItem->setOpen (false); // force a re-open
  44574. rootItem->setOpen (true);
  44575. }
  44576. itemsChanged();
  44577. }
  44578. void TreeView::colourChanged()
  44579. {
  44580. setOpaque (findColour (backgroundColourId).isOpaque());
  44581. repaint();
  44582. }
  44583. void TreeView::setIndentSize (const int newIndentSize)
  44584. {
  44585. if (indentSize != newIndentSize)
  44586. {
  44587. indentSize = newIndentSize;
  44588. resized();
  44589. }
  44590. }
  44591. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  44592. {
  44593. if (defaultOpenness != isOpenByDefault)
  44594. {
  44595. defaultOpenness = isOpenByDefault;
  44596. itemsChanged();
  44597. }
  44598. }
  44599. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  44600. {
  44601. multiSelectEnabled = canMultiSelect;
  44602. }
  44603. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  44604. {
  44605. if (openCloseButtonsVisible != shouldBeVisible)
  44606. {
  44607. openCloseButtonsVisible = shouldBeVisible;
  44608. itemsChanged();
  44609. }
  44610. }
  44611. Viewport* TreeView::getViewport() const throw()
  44612. {
  44613. return viewport;
  44614. }
  44615. void TreeView::clearSelectedItems()
  44616. {
  44617. if (rootItem != 0)
  44618. rootItem->deselectAllRecursively();
  44619. }
  44620. int TreeView::getNumSelectedItems() const throw()
  44621. {
  44622. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  44623. }
  44624. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  44625. {
  44626. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  44627. }
  44628. int TreeView::getNumRowsInTree() const
  44629. {
  44630. if (rootItem != 0)
  44631. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  44632. return 0;
  44633. }
  44634. TreeViewItem* TreeView::getItemOnRow (int index) const
  44635. {
  44636. if (! rootItemVisible)
  44637. ++index;
  44638. if (rootItem != 0 && index >= 0)
  44639. return rootItem->getItemOnRow (index);
  44640. return 0;
  44641. }
  44642. TreeViewItem* TreeView::getItemAt (int y) const throw()
  44643. {
  44644. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  44645. Rectangle<int> pos;
  44646. return tc->findItemAt (relativePositionToOtherComponent (tc, Point<int> (0, y)).getY(), pos);
  44647. }
  44648. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  44649. {
  44650. if (rootItem == 0)
  44651. return 0;
  44652. return rootItem->findItemFromIdentifierString (identifierString);
  44653. }
  44654. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  44655. {
  44656. XmlElement* e = 0;
  44657. if (rootItem != 0)
  44658. {
  44659. e = rootItem->getOpennessState();
  44660. if (e != 0 && alsoIncludeScrollPosition)
  44661. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  44662. }
  44663. return e;
  44664. }
  44665. void TreeView::restoreOpennessState (const XmlElement& newState)
  44666. {
  44667. if (rootItem != 0)
  44668. {
  44669. rootItem->restoreOpennessState (newState);
  44670. if (newState.hasAttribute ("scrollPos"))
  44671. viewport->setViewPosition (viewport->getViewPositionX(),
  44672. newState.getIntAttribute ("scrollPos"));
  44673. }
  44674. }
  44675. void TreeView::paint (Graphics& g)
  44676. {
  44677. g.fillAll (findColour (backgroundColourId));
  44678. }
  44679. void TreeView::resized()
  44680. {
  44681. viewport->setBounds (0, 0, getWidth(), getHeight());
  44682. itemsChanged();
  44683. handleAsyncUpdate();
  44684. }
  44685. void TreeView::enablementChanged()
  44686. {
  44687. repaint();
  44688. }
  44689. void TreeView::moveSelectedRow (int delta)
  44690. {
  44691. if (delta == 0)
  44692. return;
  44693. int rowSelected = 0;
  44694. TreeViewItem* const firstSelected = getSelectedItem (0);
  44695. if (firstSelected != 0)
  44696. rowSelected = firstSelected->getRowNumberInTree();
  44697. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  44698. for (;;)
  44699. {
  44700. TreeViewItem* item = getItemOnRow (rowSelected);
  44701. if (item != 0)
  44702. {
  44703. if (! item->canBeSelected())
  44704. {
  44705. // if the row we want to highlight doesn't allow it, try skipping
  44706. // to the next item..
  44707. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  44708. rowSelected + (delta < 0 ? -1 : 1));
  44709. if (rowSelected != nextRowToTry)
  44710. {
  44711. rowSelected = nextRowToTry;
  44712. continue;
  44713. }
  44714. else
  44715. {
  44716. break;
  44717. }
  44718. }
  44719. item->setSelected (true, true);
  44720. scrollToKeepItemVisible (item);
  44721. }
  44722. break;
  44723. }
  44724. }
  44725. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  44726. {
  44727. if (item != 0 && item->ownerView == this)
  44728. {
  44729. handleAsyncUpdate();
  44730. item = item->getDeepestOpenParentItem();
  44731. int y = item->y;
  44732. int viewTop = viewport->getViewPositionY();
  44733. if (y < viewTop)
  44734. {
  44735. viewport->setViewPosition (viewport->getViewPositionX(), y);
  44736. }
  44737. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  44738. {
  44739. viewport->setViewPosition (viewport->getViewPositionX(),
  44740. (y + item->itemHeight) - viewport->getViewHeight());
  44741. }
  44742. }
  44743. }
  44744. bool TreeView::keyPressed (const KeyPress& key)
  44745. {
  44746. if (key.isKeyCode (KeyPress::upKey))
  44747. {
  44748. moveSelectedRow (-1);
  44749. }
  44750. else if (key.isKeyCode (KeyPress::downKey))
  44751. {
  44752. moveSelectedRow (1);
  44753. }
  44754. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  44755. {
  44756. if (rootItem != 0)
  44757. {
  44758. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  44759. if (key.isKeyCode (KeyPress::pageUpKey))
  44760. rowsOnScreen = -rowsOnScreen;
  44761. moveSelectedRow (rowsOnScreen);
  44762. }
  44763. }
  44764. else if (key.isKeyCode (KeyPress::homeKey))
  44765. {
  44766. moveSelectedRow (-0x3fffffff);
  44767. }
  44768. else if (key.isKeyCode (KeyPress::endKey))
  44769. {
  44770. moveSelectedRow (0x3fffffff);
  44771. }
  44772. else if (key.isKeyCode (KeyPress::returnKey))
  44773. {
  44774. TreeViewItem* const firstSelected = getSelectedItem (0);
  44775. if (firstSelected != 0)
  44776. firstSelected->setOpen (! firstSelected->isOpen());
  44777. }
  44778. else if (key.isKeyCode (KeyPress::leftKey))
  44779. {
  44780. TreeViewItem* const firstSelected = getSelectedItem (0);
  44781. if (firstSelected != 0)
  44782. {
  44783. if (firstSelected->isOpen())
  44784. {
  44785. firstSelected->setOpen (false);
  44786. }
  44787. else
  44788. {
  44789. TreeViewItem* parent = firstSelected->parentItem;
  44790. if ((! rootItemVisible) && parent == rootItem)
  44791. parent = 0;
  44792. if (parent != 0)
  44793. {
  44794. parent->setSelected (true, true);
  44795. scrollToKeepItemVisible (parent);
  44796. }
  44797. }
  44798. }
  44799. }
  44800. else if (key.isKeyCode (KeyPress::rightKey))
  44801. {
  44802. TreeViewItem* const firstSelected = getSelectedItem (0);
  44803. if (firstSelected != 0)
  44804. {
  44805. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  44806. moveSelectedRow (1);
  44807. else
  44808. firstSelected->setOpen (true);
  44809. }
  44810. }
  44811. else
  44812. {
  44813. return false;
  44814. }
  44815. return true;
  44816. }
  44817. void TreeView::itemsChanged() throw()
  44818. {
  44819. needsRecalculating = true;
  44820. repaint();
  44821. triggerAsyncUpdate();
  44822. }
  44823. void TreeView::handleAsyncUpdate()
  44824. {
  44825. if (needsRecalculating)
  44826. {
  44827. needsRecalculating = false;
  44828. const ScopedLock sl (nodeAlterationLock);
  44829. if (rootItem != 0)
  44830. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  44831. viewport->updateComponents();
  44832. if (rootItem != 0)
  44833. {
  44834. viewport->getViewedComponent()
  44835. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  44836. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  44837. }
  44838. else
  44839. {
  44840. viewport->getViewedComponent()->setSize (0, 0);
  44841. }
  44842. }
  44843. }
  44844. class TreeView::InsertPointHighlight : public Component
  44845. {
  44846. public:
  44847. InsertPointHighlight()
  44848. : lastItem (0)
  44849. {
  44850. setSize (100, 12);
  44851. setAlwaysOnTop (true);
  44852. setInterceptsMouseClicks (false, false);
  44853. }
  44854. ~InsertPointHighlight() {}
  44855. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  44856. {
  44857. lastItem = item;
  44858. lastIndex = insertIndex;
  44859. const int offset = getHeight() / 2;
  44860. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  44861. }
  44862. void paint (Graphics& g)
  44863. {
  44864. Path p;
  44865. const float h = (float) getHeight();
  44866. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  44867. p.startNewSubPath (h - 2.0f, h / 2.0f);
  44868. p.lineTo ((float) getWidth(), h / 2.0f);
  44869. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  44870. g.strokePath (p, PathStrokeType (2.0f));
  44871. }
  44872. TreeViewItem* lastItem;
  44873. int lastIndex;
  44874. private:
  44875. InsertPointHighlight (const InsertPointHighlight&);
  44876. InsertPointHighlight& operator= (const InsertPointHighlight&);
  44877. };
  44878. class TreeView::TargetGroupHighlight : public Component
  44879. {
  44880. public:
  44881. TargetGroupHighlight()
  44882. {
  44883. setAlwaysOnTop (true);
  44884. setInterceptsMouseClicks (false, false);
  44885. }
  44886. ~TargetGroupHighlight() {}
  44887. void setTargetPosition (TreeViewItem* const item) throw()
  44888. {
  44889. Rectangle<int> r (item->getItemPosition (true));
  44890. r.setHeight (item->getItemHeight());
  44891. setBounds (r);
  44892. }
  44893. void paint (Graphics& g)
  44894. {
  44895. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  44896. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  44897. }
  44898. private:
  44899. TargetGroupHighlight (const TargetGroupHighlight&);
  44900. TargetGroupHighlight& operator= (const TargetGroupHighlight&);
  44901. };
  44902. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  44903. {
  44904. beginDragAutoRepeat (1000 / 30);
  44905. if (dragInsertPointHighlight == 0)
  44906. {
  44907. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  44908. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  44909. }
  44910. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  44911. dragTargetGroupHighlight->setTargetPosition (item);
  44912. }
  44913. void TreeView::hideDragHighlight() throw()
  44914. {
  44915. deleteAndZero (dragInsertPointHighlight);
  44916. deleteAndZero (dragTargetGroupHighlight);
  44917. }
  44918. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  44919. const StringArray& files, const String& sourceDescription,
  44920. Component* sourceComponent) const throw()
  44921. {
  44922. insertIndex = 0;
  44923. TreeViewItem* item = getItemAt (y);
  44924. if (item == 0)
  44925. return 0;
  44926. Rectangle<int> itemPos (item->getItemPosition (true));
  44927. insertIndex = item->getIndexInParent();
  44928. const int oldY = y;
  44929. y = itemPos.getY();
  44930. if (item->getNumSubItems() == 0 || ! item->isOpen())
  44931. {
  44932. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  44933. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  44934. {
  44935. // Check if we're trying to drag into an empty group item..
  44936. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  44937. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  44938. {
  44939. insertIndex = 0;
  44940. x = itemPos.getX() + getIndentSize();
  44941. y = itemPos.getBottom();
  44942. return item;
  44943. }
  44944. }
  44945. }
  44946. if (oldY > itemPos.getCentreY())
  44947. {
  44948. y += item->getItemHeight();
  44949. while (item->isLastOfSiblings() && item->parentItem != 0
  44950. && item->parentItem->parentItem != 0)
  44951. {
  44952. if (x > itemPos.getX())
  44953. break;
  44954. item = item->parentItem;
  44955. itemPos = item->getItemPosition (true);
  44956. insertIndex = item->getIndexInParent();
  44957. }
  44958. ++insertIndex;
  44959. }
  44960. x = itemPos.getX();
  44961. return item->parentItem;
  44962. }
  44963. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  44964. {
  44965. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  44966. int insertIndex;
  44967. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  44968. if (item != 0)
  44969. {
  44970. if (scrolled || dragInsertPointHighlight == 0
  44971. || dragInsertPointHighlight->lastItem != item
  44972. || dragInsertPointHighlight->lastIndex != insertIndex)
  44973. {
  44974. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  44975. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  44976. showDragHighlight (item, insertIndex, x, y);
  44977. else
  44978. hideDragHighlight();
  44979. }
  44980. }
  44981. else
  44982. {
  44983. hideDragHighlight();
  44984. }
  44985. }
  44986. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  44987. {
  44988. hideDragHighlight();
  44989. int insertIndex;
  44990. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  44991. if (item != 0)
  44992. {
  44993. if (files.size() > 0)
  44994. {
  44995. if (item->isInterestedInFileDrag (files))
  44996. item->filesDropped (files, insertIndex);
  44997. }
  44998. else
  44999. {
  45000. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45001. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  45002. }
  45003. }
  45004. }
  45005. bool TreeView::isInterestedInFileDrag (const StringArray&)
  45006. {
  45007. return true;
  45008. }
  45009. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  45010. {
  45011. fileDragMove (files, x, y);
  45012. }
  45013. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  45014. {
  45015. handleDrag (files, String::empty, 0, x, y);
  45016. }
  45017. void TreeView::fileDragExit (const StringArray&)
  45018. {
  45019. hideDragHighlight();
  45020. }
  45021. void TreeView::filesDropped (const StringArray& files, int x, int y)
  45022. {
  45023. handleDrop (files, String::empty, 0, x, y);
  45024. }
  45025. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45026. {
  45027. return true;
  45028. }
  45029. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45030. {
  45031. itemDragMove (sourceDescription, sourceComponent, x, y);
  45032. }
  45033. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45034. {
  45035. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  45036. }
  45037. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45038. {
  45039. hideDragHighlight();
  45040. }
  45041. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45042. {
  45043. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  45044. }
  45045. enum TreeViewOpenness
  45046. {
  45047. opennessDefault = 0,
  45048. opennessClosed = 1,
  45049. opennessOpen = 2
  45050. };
  45051. TreeViewItem::TreeViewItem()
  45052. : ownerView (0),
  45053. parentItem (0),
  45054. y (0),
  45055. itemHeight (0),
  45056. totalHeight (0),
  45057. selected (false),
  45058. redrawNeeded (true),
  45059. drawLinesInside (true),
  45060. drawsInLeftMargin (false),
  45061. openness (opennessDefault)
  45062. {
  45063. static int nextUID = 0;
  45064. uid = nextUID++;
  45065. }
  45066. TreeViewItem::~TreeViewItem()
  45067. {
  45068. }
  45069. const String TreeViewItem::getUniqueName() const
  45070. {
  45071. return String::empty;
  45072. }
  45073. void TreeViewItem::itemOpennessChanged (bool)
  45074. {
  45075. }
  45076. int TreeViewItem::getNumSubItems() const throw()
  45077. {
  45078. return subItems.size();
  45079. }
  45080. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  45081. {
  45082. return subItems [index];
  45083. }
  45084. void TreeViewItem::clearSubItems()
  45085. {
  45086. if (subItems.size() > 0)
  45087. {
  45088. if (ownerView != 0)
  45089. {
  45090. const ScopedLock sl (ownerView->nodeAlterationLock);
  45091. subItems.clear();
  45092. treeHasChanged();
  45093. }
  45094. else
  45095. {
  45096. subItems.clear();
  45097. }
  45098. }
  45099. }
  45100. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  45101. {
  45102. if (newItem != 0)
  45103. {
  45104. newItem->parentItem = this;
  45105. newItem->setOwnerView (ownerView);
  45106. newItem->y = 0;
  45107. newItem->itemHeight = newItem->getItemHeight();
  45108. newItem->totalHeight = 0;
  45109. newItem->itemWidth = newItem->getItemWidth();
  45110. newItem->totalWidth = 0;
  45111. if (ownerView != 0)
  45112. {
  45113. const ScopedLock sl (ownerView->nodeAlterationLock);
  45114. subItems.insert (insertPosition, newItem);
  45115. treeHasChanged();
  45116. if (newItem->isOpen())
  45117. newItem->itemOpennessChanged (true);
  45118. }
  45119. else
  45120. {
  45121. subItems.insert (insertPosition, newItem);
  45122. if (newItem->isOpen())
  45123. newItem->itemOpennessChanged (true);
  45124. }
  45125. }
  45126. }
  45127. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  45128. {
  45129. if (ownerView != 0)
  45130. {
  45131. const ScopedLock sl (ownerView->nodeAlterationLock);
  45132. if (((unsigned int) index) < (unsigned int) subItems.size())
  45133. {
  45134. subItems.remove (index, deleteItem);
  45135. treeHasChanged();
  45136. }
  45137. }
  45138. else
  45139. {
  45140. subItems.remove (index, deleteItem);
  45141. }
  45142. }
  45143. bool TreeViewItem::isOpen() const throw()
  45144. {
  45145. if (openness == opennessDefault)
  45146. return ownerView != 0 && ownerView->defaultOpenness;
  45147. else
  45148. return openness == opennessOpen;
  45149. }
  45150. void TreeViewItem::setOpen (const bool shouldBeOpen)
  45151. {
  45152. if (isOpen() != shouldBeOpen)
  45153. {
  45154. openness = shouldBeOpen ? opennessOpen
  45155. : opennessClosed;
  45156. treeHasChanged();
  45157. itemOpennessChanged (isOpen());
  45158. }
  45159. }
  45160. bool TreeViewItem::isSelected() const throw()
  45161. {
  45162. return selected;
  45163. }
  45164. void TreeViewItem::deselectAllRecursively()
  45165. {
  45166. setSelected (false, false);
  45167. for (int i = 0; i < subItems.size(); ++i)
  45168. subItems.getUnchecked(i)->deselectAllRecursively();
  45169. }
  45170. void TreeViewItem::setSelected (const bool shouldBeSelected,
  45171. const bool deselectOtherItemsFirst)
  45172. {
  45173. if (shouldBeSelected && ! canBeSelected())
  45174. return;
  45175. if (deselectOtherItemsFirst)
  45176. getTopLevelItem()->deselectAllRecursively();
  45177. if (shouldBeSelected != selected)
  45178. {
  45179. selected = shouldBeSelected;
  45180. if (ownerView != 0)
  45181. ownerView->repaint();
  45182. itemSelectionChanged (shouldBeSelected);
  45183. }
  45184. }
  45185. void TreeViewItem::paintItem (Graphics&, int, int)
  45186. {
  45187. }
  45188. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  45189. {
  45190. ownerView->getLookAndFeel()
  45191. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  45192. }
  45193. void TreeViewItem::itemClicked (const MouseEvent&)
  45194. {
  45195. }
  45196. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  45197. {
  45198. if (mightContainSubItems())
  45199. setOpen (! isOpen());
  45200. }
  45201. void TreeViewItem::itemSelectionChanged (bool)
  45202. {
  45203. }
  45204. const String TreeViewItem::getTooltip()
  45205. {
  45206. return String::empty;
  45207. }
  45208. const String TreeViewItem::getDragSourceDescription()
  45209. {
  45210. return String::empty;
  45211. }
  45212. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  45213. {
  45214. return false;
  45215. }
  45216. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  45217. {
  45218. }
  45219. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45220. {
  45221. return false;
  45222. }
  45223. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  45224. {
  45225. }
  45226. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  45227. {
  45228. const int indentX = getIndentX();
  45229. int width = itemWidth;
  45230. if (ownerView != 0 && width < 0)
  45231. width = ownerView->viewport->getViewWidth() - indentX;
  45232. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  45233. if (relativeToTreeViewTopLeft)
  45234. r -= ownerView->viewport->getViewPosition();
  45235. return r;
  45236. }
  45237. void TreeViewItem::treeHasChanged() const throw()
  45238. {
  45239. if (ownerView != 0)
  45240. ownerView->itemsChanged();
  45241. }
  45242. void TreeViewItem::repaintItem() const
  45243. {
  45244. if (ownerView != 0 && areAllParentsOpen())
  45245. {
  45246. const Rectangle<int> r (getItemPosition (true));
  45247. ownerView->viewport->repaint (0, r.getY(), r.getRight(), r.getHeight());
  45248. }
  45249. }
  45250. bool TreeViewItem::areAllParentsOpen() const throw()
  45251. {
  45252. return parentItem == 0
  45253. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  45254. }
  45255. void TreeViewItem::updatePositions (int newY)
  45256. {
  45257. y = newY;
  45258. itemHeight = getItemHeight();
  45259. totalHeight = itemHeight;
  45260. itemWidth = getItemWidth();
  45261. totalWidth = jmax (itemWidth, 0) + getIndentX();
  45262. if (isOpen())
  45263. {
  45264. newY += totalHeight;
  45265. for (int i = 0; i < subItems.size(); ++i)
  45266. {
  45267. TreeViewItem* const ti = subItems.getUnchecked(i);
  45268. ti->updatePositions (newY);
  45269. newY += ti->totalHeight;
  45270. totalHeight += ti->totalHeight;
  45271. totalWidth = jmax (totalWidth, ti->totalWidth);
  45272. }
  45273. }
  45274. }
  45275. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  45276. {
  45277. TreeViewItem* result = this;
  45278. TreeViewItem* item = this;
  45279. while (item->parentItem != 0)
  45280. {
  45281. item = item->parentItem;
  45282. if (! item->isOpen())
  45283. result = item;
  45284. }
  45285. return result;
  45286. }
  45287. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  45288. {
  45289. ownerView = newOwner;
  45290. for (int i = subItems.size(); --i >= 0;)
  45291. subItems.getUnchecked(i)->setOwnerView (newOwner);
  45292. }
  45293. int TreeViewItem::getIndentX() const throw()
  45294. {
  45295. const int indentWidth = ownerView->getIndentSize();
  45296. int x = ownerView->rootItemVisible ? indentWidth : 0;
  45297. if (! ownerView->openCloseButtonsVisible)
  45298. x -= indentWidth;
  45299. TreeViewItem* p = parentItem;
  45300. while (p != 0)
  45301. {
  45302. x += indentWidth;
  45303. p = p->parentItem;
  45304. }
  45305. return x;
  45306. }
  45307. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  45308. {
  45309. drawsInLeftMargin = canDrawInLeftMargin;
  45310. }
  45311. void TreeViewItem::paintRecursively (Graphics& g, int width)
  45312. {
  45313. jassert (ownerView != 0);
  45314. if (ownerView == 0)
  45315. return;
  45316. const int indent = getIndentX();
  45317. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  45318. g.setColour (ownerView->findColour (TreeView::linesColourId));
  45319. const float halfH = itemHeight * 0.5f;
  45320. int depth = 0;
  45321. TreeViewItem* p = parentItem;
  45322. while (p != 0)
  45323. {
  45324. ++depth;
  45325. p = p->parentItem;
  45326. }
  45327. if (! ownerView->rootItemVisible)
  45328. --depth;
  45329. const int indentWidth = ownerView->getIndentSize();
  45330. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  45331. {
  45332. float x = (depth + 0.5f) * indentWidth;
  45333. if (depth >= 0)
  45334. {
  45335. if (parentItem != 0 && parentItem->drawLinesInside)
  45336. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  45337. if ((parentItem != 0 && parentItem->drawLinesInside)
  45338. || (parentItem == 0 && drawLinesInside))
  45339. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  45340. }
  45341. p = parentItem;
  45342. int d = depth;
  45343. while (p != 0 && --d >= 0)
  45344. {
  45345. x -= (float) indentWidth;
  45346. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  45347. && ! p->isLastOfSiblings())
  45348. {
  45349. g.drawLine (x, 0, x, (float) itemHeight);
  45350. }
  45351. p = p->parentItem;
  45352. }
  45353. if (mightContainSubItems())
  45354. {
  45355. g.saveState();
  45356. g.setOrigin (depth * indentWidth, 0);
  45357. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  45358. paintOpenCloseButton (g, indentWidth, itemHeight,
  45359. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  45360. ->isMouseOverButton (this));
  45361. g.restoreState();
  45362. }
  45363. }
  45364. {
  45365. g.saveState();
  45366. g.setOrigin (indent, 0);
  45367. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  45368. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  45369. paintItem (g, itemW, itemHeight);
  45370. g.restoreState();
  45371. }
  45372. if (isOpen())
  45373. {
  45374. const Rectangle<int> clip (g.getClipBounds());
  45375. for (int i = 0; i < subItems.size(); ++i)
  45376. {
  45377. TreeViewItem* const ti = subItems.getUnchecked(i);
  45378. const int relY = ti->y - y;
  45379. if (relY >= clip.getBottom())
  45380. break;
  45381. if (relY + ti->totalHeight >= clip.getY())
  45382. {
  45383. g.saveState();
  45384. g.setOrigin (0, relY);
  45385. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  45386. ti->paintRecursively (g, width);
  45387. g.restoreState();
  45388. }
  45389. }
  45390. }
  45391. }
  45392. bool TreeViewItem::isLastOfSiblings() const throw()
  45393. {
  45394. return parentItem == 0
  45395. || parentItem->subItems.getLast() == this;
  45396. }
  45397. int TreeViewItem::getIndexInParent() const throw()
  45398. {
  45399. if (parentItem == 0)
  45400. return 0;
  45401. return parentItem->subItems.indexOf (this);
  45402. }
  45403. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  45404. {
  45405. return (parentItem == 0) ? this
  45406. : parentItem->getTopLevelItem();
  45407. }
  45408. int TreeViewItem::getNumRows() const throw()
  45409. {
  45410. int num = 1;
  45411. if (isOpen())
  45412. {
  45413. for (int i = subItems.size(); --i >= 0;)
  45414. num += subItems.getUnchecked(i)->getNumRows();
  45415. }
  45416. return num;
  45417. }
  45418. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  45419. {
  45420. if (index == 0)
  45421. return this;
  45422. if (index > 0 && isOpen())
  45423. {
  45424. --index;
  45425. for (int i = 0; i < subItems.size(); ++i)
  45426. {
  45427. TreeViewItem* const item = subItems.getUnchecked(i);
  45428. if (index == 0)
  45429. return item;
  45430. const int numRows = item->getNumRows();
  45431. if (numRows > index)
  45432. return item->getItemOnRow (index);
  45433. index -= numRows;
  45434. }
  45435. }
  45436. return 0;
  45437. }
  45438. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  45439. {
  45440. if (((unsigned int) targetY) < (unsigned int) totalHeight)
  45441. {
  45442. const int h = itemHeight;
  45443. if (targetY < h)
  45444. return this;
  45445. if (isOpen())
  45446. {
  45447. targetY -= h;
  45448. for (int i = 0; i < subItems.size(); ++i)
  45449. {
  45450. TreeViewItem* const ti = subItems.getUnchecked(i);
  45451. if (targetY < ti->totalHeight)
  45452. return ti->findItemRecursively (targetY);
  45453. targetY -= ti->totalHeight;
  45454. }
  45455. }
  45456. }
  45457. return 0;
  45458. }
  45459. int TreeViewItem::countSelectedItemsRecursively() const throw()
  45460. {
  45461. int total = 0;
  45462. if (isSelected())
  45463. ++total;
  45464. for (int i = subItems.size(); --i >= 0;)
  45465. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  45466. return total;
  45467. }
  45468. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  45469. {
  45470. if (isSelected())
  45471. {
  45472. if (index == 0)
  45473. return this;
  45474. --index;
  45475. }
  45476. if (index >= 0)
  45477. {
  45478. for (int i = 0; i < subItems.size(); ++i)
  45479. {
  45480. TreeViewItem* const item = subItems.getUnchecked(i);
  45481. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  45482. if (found != 0)
  45483. return found;
  45484. index -= item->countSelectedItemsRecursively();
  45485. }
  45486. }
  45487. return 0;
  45488. }
  45489. int TreeViewItem::getRowNumberInTree() const throw()
  45490. {
  45491. if (parentItem != 0 && ownerView != 0)
  45492. {
  45493. int n = 1 + parentItem->getRowNumberInTree();
  45494. int ourIndex = parentItem->subItems.indexOf (this);
  45495. jassert (ourIndex >= 0);
  45496. while (--ourIndex >= 0)
  45497. n += parentItem->subItems [ourIndex]->getNumRows();
  45498. if (parentItem->parentItem == 0
  45499. && ! ownerView->rootItemVisible)
  45500. --n;
  45501. return n;
  45502. }
  45503. else
  45504. {
  45505. return 0;
  45506. }
  45507. }
  45508. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  45509. {
  45510. drawLinesInside = drawLines;
  45511. }
  45512. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  45513. {
  45514. if (recurse && isOpen() && subItems.size() > 0)
  45515. return subItems [0];
  45516. if (parentItem != 0)
  45517. {
  45518. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  45519. if (nextIndex >= parentItem->subItems.size())
  45520. return parentItem->getNextVisibleItem (false);
  45521. return parentItem->subItems [nextIndex];
  45522. }
  45523. return 0;
  45524. }
  45525. const String TreeViewItem::getItemIdentifierString() const
  45526. {
  45527. String s;
  45528. if (parentItem != 0)
  45529. s = parentItem->getItemIdentifierString();
  45530. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  45531. }
  45532. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  45533. {
  45534. const String thisId (getUniqueName());
  45535. if (thisId == identifierString)
  45536. return this;
  45537. if (identifierString.startsWith (thisId + "/"))
  45538. {
  45539. const String remainingPath (identifierString.substring (thisId.length() + 1));
  45540. bool wasOpen = isOpen();
  45541. setOpen (true);
  45542. for (int i = subItems.size(); --i >= 0;)
  45543. {
  45544. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  45545. if (item != 0)
  45546. return item;
  45547. }
  45548. setOpen (wasOpen);
  45549. }
  45550. return 0;
  45551. }
  45552. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  45553. {
  45554. if (e.hasTagName ("CLOSED"))
  45555. {
  45556. setOpen (false);
  45557. }
  45558. else if (e.hasTagName ("OPEN"))
  45559. {
  45560. setOpen (true);
  45561. forEachXmlChildElement (e, n)
  45562. {
  45563. const String id (n->getStringAttribute ("id"));
  45564. for (int i = 0; i < subItems.size(); ++i)
  45565. {
  45566. TreeViewItem* const ti = subItems.getUnchecked(i);
  45567. if (ti->getUniqueName() == id)
  45568. {
  45569. ti->restoreOpennessState (*n);
  45570. break;
  45571. }
  45572. }
  45573. }
  45574. }
  45575. }
  45576. XmlElement* TreeViewItem::getOpennessState() const throw()
  45577. {
  45578. const String name (getUniqueName());
  45579. if (name.isNotEmpty())
  45580. {
  45581. XmlElement* e;
  45582. if (isOpen())
  45583. {
  45584. e = new XmlElement ("OPEN");
  45585. for (int i = 0; i < subItems.size(); ++i)
  45586. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  45587. }
  45588. else
  45589. {
  45590. e = new XmlElement ("CLOSED");
  45591. }
  45592. e->setAttribute ("id", name);
  45593. return e;
  45594. }
  45595. else
  45596. {
  45597. // trying to save the openness for an element that has no name - this won't
  45598. // work because it needs the names to identify what to open.
  45599. jassertfalse
  45600. }
  45601. return 0;
  45602. }
  45603. END_JUCE_NAMESPACE
  45604. /*** End of inlined file: juce_TreeView.cpp ***/
  45605. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  45606. BEGIN_JUCE_NAMESPACE
  45607. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  45608. : fileList (listToShow)
  45609. {
  45610. }
  45611. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  45612. {
  45613. }
  45614. FileBrowserListener::~FileBrowserListener()
  45615. {
  45616. }
  45617. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  45618. {
  45619. listeners.add (listener);
  45620. }
  45621. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  45622. {
  45623. listeners.remove (listener);
  45624. }
  45625. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  45626. {
  45627. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45628. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  45629. }
  45630. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  45631. {
  45632. if (fileList.getDirectory().exists())
  45633. {
  45634. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45635. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  45636. }
  45637. }
  45638. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  45639. {
  45640. if (fileList.getDirectory().exists())
  45641. {
  45642. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45643. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  45644. }
  45645. }
  45646. END_JUCE_NAMESPACE
  45647. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  45648. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  45649. BEGIN_JUCE_NAMESPACE
  45650. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  45651. TimeSliceThread& thread_)
  45652. : fileFilter (fileFilter_),
  45653. thread (thread_),
  45654. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  45655. fileFindHandle (0),
  45656. shouldStop (true)
  45657. {
  45658. }
  45659. DirectoryContentsList::~DirectoryContentsList()
  45660. {
  45661. clear();
  45662. }
  45663. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  45664. {
  45665. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  45666. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  45667. }
  45668. bool DirectoryContentsList::ignoresHiddenFiles() const
  45669. {
  45670. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  45671. }
  45672. const File& DirectoryContentsList::getDirectory() const
  45673. {
  45674. return root;
  45675. }
  45676. void DirectoryContentsList::setDirectory (const File& directory,
  45677. const bool includeDirectories,
  45678. const bool includeFiles)
  45679. {
  45680. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  45681. if (directory != root)
  45682. {
  45683. clear();
  45684. root = directory;
  45685. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  45686. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  45687. }
  45688. int newFlags = fileTypeFlags;
  45689. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  45690. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  45691. setTypeFlags (newFlags);
  45692. }
  45693. void DirectoryContentsList::setTypeFlags (const int newFlags)
  45694. {
  45695. if (fileTypeFlags != newFlags)
  45696. {
  45697. fileTypeFlags = newFlags;
  45698. refresh();
  45699. }
  45700. }
  45701. void DirectoryContentsList::clear()
  45702. {
  45703. shouldStop = true;
  45704. thread.removeTimeSliceClient (this);
  45705. fileFindHandle = 0;
  45706. if (files.size() > 0)
  45707. {
  45708. files.clear();
  45709. changed();
  45710. }
  45711. }
  45712. void DirectoryContentsList::refresh()
  45713. {
  45714. clear();
  45715. if (root.isDirectory())
  45716. {
  45717. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  45718. shouldStop = false;
  45719. thread.addTimeSliceClient (this);
  45720. }
  45721. }
  45722. int DirectoryContentsList::getNumFiles() const
  45723. {
  45724. return files.size();
  45725. }
  45726. bool DirectoryContentsList::getFileInfo (const int index,
  45727. FileInfo& result) const
  45728. {
  45729. const ScopedLock sl (fileListLock);
  45730. const FileInfo* const info = files [index];
  45731. if (info != 0)
  45732. {
  45733. result = *info;
  45734. return true;
  45735. }
  45736. return false;
  45737. }
  45738. const File DirectoryContentsList::getFile (const int index) const
  45739. {
  45740. const ScopedLock sl (fileListLock);
  45741. const FileInfo* const info = files [index];
  45742. if (info != 0)
  45743. return root.getChildFile (info->filename);
  45744. return File::nonexistent;
  45745. }
  45746. bool DirectoryContentsList::isStillLoading() const
  45747. {
  45748. return fileFindHandle != 0;
  45749. }
  45750. void DirectoryContentsList::changed()
  45751. {
  45752. sendChangeMessage (this);
  45753. }
  45754. bool DirectoryContentsList::useTimeSlice()
  45755. {
  45756. const uint32 startTime = Time::getApproximateMillisecondCounter();
  45757. bool hasChanged = false;
  45758. for (int i = 100; --i >= 0;)
  45759. {
  45760. if (! checkNextFile (hasChanged))
  45761. {
  45762. if (hasChanged)
  45763. changed();
  45764. return false;
  45765. }
  45766. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  45767. break;
  45768. }
  45769. if (hasChanged)
  45770. changed();
  45771. return true;
  45772. }
  45773. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  45774. {
  45775. if (fileFindHandle != 0)
  45776. {
  45777. bool fileFoundIsDir, isHidden, isReadOnly;
  45778. int64 fileSize;
  45779. Time modTime, creationTime;
  45780. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  45781. &modTime, &creationTime, &isReadOnly))
  45782. {
  45783. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  45784. fileSize, modTime, creationTime, isReadOnly))
  45785. {
  45786. hasChanged = true;
  45787. }
  45788. return true;
  45789. }
  45790. else
  45791. {
  45792. fileFindHandle = 0;
  45793. }
  45794. }
  45795. return false;
  45796. }
  45797. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  45798. const DirectoryContentsList::FileInfo* const second)
  45799. {
  45800. #if JUCE_WINDOWS
  45801. if (first->isDirectory != second->isDirectory)
  45802. return first->isDirectory ? -1 : 1;
  45803. #endif
  45804. return first->filename.compareIgnoreCase (second->filename);
  45805. }
  45806. bool DirectoryContentsList::addFile (const File& file,
  45807. const bool isDir,
  45808. const int64 fileSize,
  45809. const Time& modTime,
  45810. const Time& creationTime,
  45811. const bool isReadOnly)
  45812. {
  45813. if (fileFilter == 0
  45814. || ((! isDir) && fileFilter->isFileSuitable (file))
  45815. || (isDir && fileFilter->isDirectorySuitable (file)))
  45816. {
  45817. ScopedPointer <FileInfo> info (new FileInfo());
  45818. info->filename = file.getFileName();
  45819. info->fileSize = fileSize;
  45820. info->modificationTime = modTime;
  45821. info->creationTime = creationTime;
  45822. info->isDirectory = isDir;
  45823. info->isReadOnly = isReadOnly;
  45824. const ScopedLock sl (fileListLock);
  45825. for (int i = files.size(); --i >= 0;)
  45826. if (files.getUnchecked(i)->filename == info->filename)
  45827. return false;
  45828. files.addSorted (*this, info.release());
  45829. return true;
  45830. }
  45831. return false;
  45832. }
  45833. END_JUCE_NAMESPACE
  45834. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  45835. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  45836. BEGIN_JUCE_NAMESPACE
  45837. FileBrowserComponent::FileBrowserComponent (int flags_,
  45838. const File& initialFileOrDirectory,
  45839. const FileFilter* fileFilter_,
  45840. FilePreviewComponent* previewComp_)
  45841. : FileFilter (String::empty),
  45842. fileFilter (fileFilter_),
  45843. flags (flags_),
  45844. previewComp (previewComp_),
  45845. thread ("Juce FileBrowser")
  45846. {
  45847. // You need to specify one or other of the open/save flags..
  45848. jassert ((flags & (saveMode | openMode)) != 0);
  45849. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  45850. // You need to specify at least one of these flags..
  45851. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  45852. String filename;
  45853. if (initialFileOrDirectory == File::nonexistent)
  45854. {
  45855. currentRoot = File::getCurrentWorkingDirectory();
  45856. }
  45857. else if (initialFileOrDirectory.isDirectory())
  45858. {
  45859. currentRoot = initialFileOrDirectory;
  45860. }
  45861. else
  45862. {
  45863. chosenFiles.add (initialFileOrDirectory);
  45864. currentRoot = initialFileOrDirectory.getParentDirectory();
  45865. filename = initialFileOrDirectory.getFileName();
  45866. }
  45867. fileList = new DirectoryContentsList (this, thread);
  45868. if ((flags & useTreeView) != 0)
  45869. {
  45870. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  45871. if ((flags & canSelectMultipleItems) != 0)
  45872. tree->setMultiSelectEnabled (true);
  45873. addAndMakeVisible (tree);
  45874. fileListComponent = tree;
  45875. }
  45876. else
  45877. {
  45878. FileListComponent* const list = new FileListComponent (*fileList);
  45879. list->setOutlineThickness (1);
  45880. if ((flags & canSelectMultipleItems) != 0)
  45881. list->setMultipleSelectionEnabled (true);
  45882. addAndMakeVisible (list);
  45883. fileListComponent = list;
  45884. }
  45885. fileListComponent->addListener (this);
  45886. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  45887. currentPathBox->setEditableText (true);
  45888. StringArray rootNames, rootPaths;
  45889. const BigInteger separators (getRoots (rootNames, rootPaths));
  45890. for (int i = 0; i < rootNames.size(); ++i)
  45891. {
  45892. if (separators [i])
  45893. currentPathBox->addSeparator();
  45894. currentPathBox->addItem (rootNames[i], i + 1);
  45895. }
  45896. currentPathBox->addSeparator();
  45897. currentPathBox->addListener (this);
  45898. addAndMakeVisible (filenameBox = new TextEditor());
  45899. filenameBox->setMultiLine (false);
  45900. filenameBox->setSelectAllWhenFocused (true);
  45901. filenameBox->setText (filename, false);
  45902. filenameBox->addListener (this);
  45903. filenameBox->setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  45904. Label* label = new Label ("f", TRANS("file:"));
  45905. addAndMakeVisible (label);
  45906. label->attachToComponent (filenameBox, true);
  45907. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  45908. goUpButton->addButtonListener (this);
  45909. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  45910. if (previewComp != 0)
  45911. addAndMakeVisible (previewComp);
  45912. setRoot (currentRoot);
  45913. thread.startThread (4);
  45914. }
  45915. FileBrowserComponent::~FileBrowserComponent()
  45916. {
  45917. if (previewComp != 0)
  45918. removeChildComponent (previewComp);
  45919. deleteAllChildren();
  45920. fileList = 0;
  45921. thread.stopThread (10000);
  45922. }
  45923. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  45924. {
  45925. listeners.add (newListener);
  45926. }
  45927. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  45928. {
  45929. listeners.remove (listener);
  45930. }
  45931. bool FileBrowserComponent::isSaveMode() const throw()
  45932. {
  45933. return (flags & saveMode) != 0;
  45934. }
  45935. int FileBrowserComponent::getNumSelectedFiles() const throw()
  45936. {
  45937. if (chosenFiles.size() == 0 && currentFileIsValid())
  45938. return 1;
  45939. return chosenFiles.size();
  45940. }
  45941. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  45942. {
  45943. if ((flags & canSelectDirectories) != 0 && filenameBox->getText().isEmpty())
  45944. return currentRoot;
  45945. if (! filenameBox->isReadOnly())
  45946. return currentRoot.getChildFile (filenameBox->getText());
  45947. return chosenFiles[index];
  45948. }
  45949. bool FileBrowserComponent::currentFileIsValid() const
  45950. {
  45951. if (isSaveMode())
  45952. return ! getSelectedFile (0).isDirectory();
  45953. else
  45954. return getSelectedFile (0).exists();
  45955. }
  45956. const File FileBrowserComponent::getHighlightedFile() const throw()
  45957. {
  45958. return fileListComponent->getSelectedFile (0);
  45959. }
  45960. void FileBrowserComponent::deselectAllFiles()
  45961. {
  45962. fileListComponent->deselectAllFiles();
  45963. }
  45964. bool FileBrowserComponent::isFileSuitable (const File& file) const
  45965. {
  45966. return (flags & canSelectFiles) != 0 ? (fileFilter == 0 || fileFilter->isFileSuitable (file))
  45967. : false;
  45968. }
  45969. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  45970. {
  45971. return true;
  45972. }
  45973. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  45974. {
  45975. if (f.isDirectory())
  45976. return (flags & canSelectDirectories) != 0 && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  45977. return (flags & canSelectFiles) != 0 && f.exists()
  45978. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  45979. }
  45980. const File FileBrowserComponent::getRoot() const
  45981. {
  45982. return currentRoot;
  45983. }
  45984. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  45985. {
  45986. if (currentRoot != newRootDirectory)
  45987. {
  45988. fileListComponent->scrollToTop();
  45989. String path (newRootDirectory.getFullPathName());
  45990. if (path.isEmpty())
  45991. path = File::separatorString;
  45992. StringArray rootNames, rootPaths;
  45993. getRoots (rootNames, rootPaths);
  45994. if (! rootPaths.contains (path, true))
  45995. {
  45996. bool alreadyListed = false;
  45997. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  45998. {
  45999. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  46000. {
  46001. alreadyListed = true;
  46002. break;
  46003. }
  46004. }
  46005. if (! alreadyListed)
  46006. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  46007. }
  46008. }
  46009. currentRoot = newRootDirectory;
  46010. fileList->setDirectory (currentRoot, true, true);
  46011. String currentRootName (currentRoot.getFullPathName());
  46012. if (currentRootName.isEmpty())
  46013. currentRootName = File::separatorString;
  46014. currentPathBox->setText (currentRootName, true);
  46015. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  46016. && currentRoot.getParentDirectory() != currentRoot);
  46017. }
  46018. void FileBrowserComponent::goUp()
  46019. {
  46020. setRoot (getRoot().getParentDirectory());
  46021. }
  46022. void FileBrowserComponent::refresh()
  46023. {
  46024. fileList->refresh();
  46025. }
  46026. const String FileBrowserComponent::getActionVerb() const
  46027. {
  46028. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  46029. }
  46030. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  46031. {
  46032. return previewComp;
  46033. }
  46034. void FileBrowserComponent::resized()
  46035. {
  46036. getLookAndFeel()
  46037. .layoutFileBrowserComponent (*this, fileListComponent,
  46038. previewComp, currentPathBox,
  46039. filenameBox, goUpButton);
  46040. }
  46041. void FileBrowserComponent::sendListenerChangeMessage()
  46042. {
  46043. Component::BailOutChecker checker (this);
  46044. if (previewComp != 0)
  46045. previewComp->selectedFileChanged (getSelectedFile (0));
  46046. // You shouldn't delete the browser when the file gets changed!
  46047. jassert (! checker.shouldBailOut());
  46048. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46049. }
  46050. void FileBrowserComponent::selectionChanged()
  46051. {
  46052. StringArray newFilenames;
  46053. bool resetChosenFiles = true;
  46054. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  46055. {
  46056. const File f (fileListComponent->getSelectedFile (i));
  46057. if (isFileOrDirSuitable (f))
  46058. {
  46059. if (resetChosenFiles)
  46060. {
  46061. chosenFiles.clear();
  46062. resetChosenFiles = false;
  46063. }
  46064. chosenFiles.add (f);
  46065. newFilenames.add (f.getRelativePathFrom (getRoot()));
  46066. }
  46067. }
  46068. if (newFilenames.size() > 0)
  46069. filenameBox->setText (newFilenames.joinIntoString (", "), false);
  46070. sendListenerChangeMessage();
  46071. }
  46072. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  46073. {
  46074. Component::BailOutChecker checker (this);
  46075. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  46076. }
  46077. void FileBrowserComponent::fileDoubleClicked (const File& f)
  46078. {
  46079. if (f.isDirectory())
  46080. {
  46081. setRoot (f);
  46082. if ((flags & canSelectDirectories) != 0)
  46083. filenameBox->setText (String::empty);
  46084. }
  46085. else
  46086. {
  46087. Component::BailOutChecker checker (this);
  46088. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  46089. }
  46090. }
  46091. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  46092. {
  46093. (void) key;
  46094. #if JUCE_LINUX || JUCE_WINDOWS
  46095. if (key.getModifiers().isCommandDown()
  46096. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  46097. {
  46098. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  46099. fileList->refresh();
  46100. return true;
  46101. }
  46102. #endif
  46103. return false;
  46104. }
  46105. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  46106. {
  46107. sendListenerChangeMessage();
  46108. }
  46109. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  46110. {
  46111. if (filenameBox->getText().containsChar (File::separator))
  46112. {
  46113. const File f (currentRoot.getChildFile (filenameBox->getText()));
  46114. if (f.isDirectory())
  46115. {
  46116. setRoot (f);
  46117. chosenFiles.clear();
  46118. filenameBox->setText (String::empty);
  46119. }
  46120. else
  46121. {
  46122. setRoot (f.getParentDirectory());
  46123. chosenFiles.clear();
  46124. chosenFiles.add (f);
  46125. filenameBox->setText (f.getFileName());
  46126. }
  46127. }
  46128. else
  46129. {
  46130. fileDoubleClicked (getSelectedFile (0));
  46131. }
  46132. }
  46133. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  46134. {
  46135. }
  46136. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  46137. {
  46138. if (! isSaveMode())
  46139. selectionChanged();
  46140. }
  46141. void FileBrowserComponent::buttonClicked (Button*)
  46142. {
  46143. goUp();
  46144. }
  46145. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  46146. {
  46147. const String newText (currentPathBox->getText().trim().unquoted());
  46148. if (newText.isNotEmpty())
  46149. {
  46150. const int index = currentPathBox->getSelectedId() - 1;
  46151. StringArray rootNames, rootPaths;
  46152. getRoots (rootNames, rootPaths);
  46153. if (rootPaths [index].isNotEmpty())
  46154. {
  46155. setRoot (File (rootPaths [index]));
  46156. }
  46157. else
  46158. {
  46159. File f (newText);
  46160. for (;;)
  46161. {
  46162. if (f.isDirectory())
  46163. {
  46164. setRoot (f);
  46165. break;
  46166. }
  46167. if (f.getParentDirectory() == f)
  46168. break;
  46169. f = f.getParentDirectory();
  46170. }
  46171. }
  46172. }
  46173. }
  46174. const BigInteger FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  46175. {
  46176. BigInteger separators;
  46177. #if JUCE_WINDOWS
  46178. Array<File> roots;
  46179. File::findFileSystemRoots (roots);
  46180. rootPaths.clear();
  46181. for (int i = 0; i < roots.size(); ++i)
  46182. {
  46183. const File& drive = roots.getReference(i);
  46184. String name (drive.getFullPathName());
  46185. rootPaths.add (name);
  46186. if (drive.isOnHardDisk())
  46187. {
  46188. String volume (drive.getVolumeLabel());
  46189. if (volume.isEmpty())
  46190. volume = TRANS("Hard Drive");
  46191. name << " [" << drive.getVolumeLabel() << ']';
  46192. }
  46193. else if (drive.isOnCDRomDrive())
  46194. {
  46195. name << TRANS(" [CD/DVD drive]");
  46196. }
  46197. rootNames.add (name);
  46198. }
  46199. separators.setBit (rootPaths.size());
  46200. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46201. rootNames.add ("Documents");
  46202. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46203. rootNames.add ("Desktop");
  46204. #endif
  46205. #if JUCE_MAC
  46206. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46207. rootNames.add ("Home folder");
  46208. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46209. rootNames.add ("Documents");
  46210. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46211. rootNames.add ("Desktop");
  46212. separators.setBit (rootPaths.size());
  46213. Array <File> volumes;
  46214. File vol ("/Volumes");
  46215. vol.findChildFiles (volumes, File::findDirectories, false);
  46216. for (int i = 0; i < volumes.size(); ++i)
  46217. {
  46218. const File& volume = volumes.getReference(i);
  46219. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  46220. {
  46221. rootPaths.add (volume.getFullPathName());
  46222. rootNames.add (volume.getFileName());
  46223. }
  46224. }
  46225. #endif
  46226. #if JUCE_LINUX
  46227. rootPaths.add ("/");
  46228. rootNames.add ("/");
  46229. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46230. rootNames.add ("Home folder");
  46231. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46232. rootNames.add ("Desktop");
  46233. #endif
  46234. return separators;
  46235. }
  46236. END_JUCE_NAMESPACE
  46237. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  46238. /*** Start of inlined file: juce_FileChooser.cpp ***/
  46239. BEGIN_JUCE_NAMESPACE
  46240. FileChooser::FileChooser (const String& chooserBoxTitle,
  46241. const File& currentFileOrDirectory,
  46242. const String& fileFilters,
  46243. const bool useNativeDialogBox_)
  46244. : title (chooserBoxTitle),
  46245. filters (fileFilters),
  46246. startingFile (currentFileOrDirectory),
  46247. useNativeDialogBox (useNativeDialogBox_)
  46248. {
  46249. #if JUCE_LINUX
  46250. useNativeDialogBox = false;
  46251. #endif
  46252. if (! fileFilters.containsNonWhitespaceChars())
  46253. filters = "*";
  46254. }
  46255. FileChooser::~FileChooser()
  46256. {
  46257. }
  46258. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  46259. {
  46260. return showDialog (false, true, false, false, false, previewComponent);
  46261. }
  46262. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  46263. {
  46264. return showDialog (false, true, false, false, true, previewComponent);
  46265. }
  46266. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  46267. {
  46268. return showDialog (true, true, false, false, true, previewComponent);
  46269. }
  46270. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  46271. {
  46272. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  46273. }
  46274. bool FileChooser::browseForDirectory()
  46275. {
  46276. return showDialog (true, false, false, false, false, 0);
  46277. }
  46278. const File FileChooser::getResult() const
  46279. {
  46280. // if you've used a multiple-file select, you should use the getResults() method
  46281. // to retrieve all the files that were chosen.
  46282. jassert (results.size() <= 1);
  46283. return results.getFirst();
  46284. }
  46285. const Array<File>& FileChooser::getResults() const
  46286. {
  46287. return results;
  46288. }
  46289. bool FileChooser::showDialog (const bool selectsDirectories,
  46290. const bool selectsFiles,
  46291. const bool isSave,
  46292. const bool warnAboutOverwritingExistingFiles,
  46293. const bool selectMultipleFiles,
  46294. FilePreviewComponent* const previewComponent)
  46295. {
  46296. Component::SafePointer<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  46297. results.clear();
  46298. // the preview component needs to be the right size before you pass it in here..
  46299. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  46300. && previewComponent->getHeight() > 10));
  46301. #if JUCE_WINDOWS
  46302. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  46303. #elif JUCE_MAC
  46304. if (useNativeDialogBox && (previewComponent == 0))
  46305. #else
  46306. if (false)
  46307. #endif
  46308. {
  46309. showPlatformDialog (results, title, startingFile, filters,
  46310. selectsDirectories, selectsFiles, isSave,
  46311. warnAboutOverwritingExistingFiles,
  46312. selectMultipleFiles,
  46313. previewComponent);
  46314. }
  46315. else
  46316. {
  46317. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  46318. selectsDirectories ? "*" : String::empty,
  46319. String::empty);
  46320. int flags = isSave ? FileBrowserComponent::saveMode
  46321. : FileBrowserComponent::openMode;
  46322. if (selectsFiles)
  46323. flags |= FileBrowserComponent::canSelectFiles;
  46324. if (selectsDirectories)
  46325. {
  46326. flags |= FileBrowserComponent::canSelectDirectories;
  46327. if (! isSave)
  46328. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  46329. }
  46330. if (selectMultipleFiles)
  46331. flags |= FileBrowserComponent::canSelectMultipleItems;
  46332. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  46333. FileChooserDialogBox box (title, String::empty,
  46334. browserComponent,
  46335. warnAboutOverwritingExistingFiles,
  46336. browserComponent.findColour (AlertWindow::backgroundColourId));
  46337. if (box.show())
  46338. {
  46339. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  46340. results.add (browserComponent.getSelectedFile (i));
  46341. }
  46342. }
  46343. if (previouslyFocused != 0)
  46344. previouslyFocused->grabKeyboardFocus();
  46345. return results.size() > 0;
  46346. }
  46347. FilePreviewComponent::FilePreviewComponent()
  46348. {
  46349. }
  46350. FilePreviewComponent::~FilePreviewComponent()
  46351. {
  46352. }
  46353. END_JUCE_NAMESPACE
  46354. /*** End of inlined file: juce_FileChooser.cpp ***/
  46355. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  46356. BEGIN_JUCE_NAMESPACE
  46357. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  46358. const String& instructions,
  46359. FileBrowserComponent& chooserComponent,
  46360. const bool warnAboutOverwritingExistingFiles_,
  46361. const Colour& backgroundColour)
  46362. : ResizableWindow (name, backgroundColour, true),
  46363. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  46364. {
  46365. content = new ContentComponent();
  46366. content->setName (name);
  46367. content->instructions = instructions;
  46368. content->chooserComponent = &chooserComponent;
  46369. content->addAndMakeVisible (&chooserComponent);
  46370. content->okButton = new TextButton (chooserComponent.getActionVerb());
  46371. content->addAndMakeVisible (content->okButton);
  46372. content->okButton->addButtonListener (this);
  46373. content->okButton->setEnabled (chooserComponent.currentFileIsValid());
  46374. content->okButton->addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  46375. content->cancelButton = new TextButton (TRANS("Cancel"));
  46376. content->addAndMakeVisible (content->cancelButton);
  46377. content->cancelButton->addButtonListener (this);
  46378. content->cancelButton->addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  46379. setContentComponent (content);
  46380. setResizable (true, true);
  46381. setResizeLimits (300, 300, 1200, 1000);
  46382. content->chooserComponent->addListener (this);
  46383. }
  46384. FileChooserDialogBox::~FileChooserDialogBox()
  46385. {
  46386. content->chooserComponent->removeListener (this);
  46387. }
  46388. bool FileChooserDialogBox::show (int w, int h)
  46389. {
  46390. if (w <= 0)
  46391. {
  46392. Component* const previewComp = content->chooserComponent->getPreviewComponent();
  46393. if (previewComp != 0)
  46394. w = 400 + previewComp->getWidth();
  46395. else
  46396. w = 600;
  46397. }
  46398. if (h <= 0)
  46399. h = 500;
  46400. centreWithSize (w, h);
  46401. const bool ok = (runModalLoop() != 0);
  46402. setVisible (false);
  46403. return ok;
  46404. }
  46405. void FileChooserDialogBox::buttonClicked (Button* button)
  46406. {
  46407. if (button == content->okButton)
  46408. {
  46409. if (warnAboutOverwritingExistingFiles
  46410. && content->chooserComponent->isSaveMode()
  46411. && content->chooserComponent->getSelectedFile(0).exists())
  46412. {
  46413. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  46414. TRANS("File already exists"),
  46415. TRANS("There's already a file called:")
  46416. + "\n\n" + content->chooserComponent->getSelectedFile(0).getFullPathName()
  46417. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  46418. TRANS("overwrite"),
  46419. TRANS("cancel")))
  46420. {
  46421. return;
  46422. }
  46423. }
  46424. exitModalState (1);
  46425. }
  46426. else if (button == content->cancelButton)
  46427. closeButtonPressed();
  46428. }
  46429. void FileChooserDialogBox::closeButtonPressed()
  46430. {
  46431. setVisible (false);
  46432. }
  46433. void FileChooserDialogBox::selectionChanged()
  46434. {
  46435. content->okButton->setEnabled (content->chooserComponent->currentFileIsValid());
  46436. }
  46437. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  46438. {
  46439. }
  46440. void FileChooserDialogBox::fileDoubleClicked (const File&)
  46441. {
  46442. selectionChanged();
  46443. content->okButton->triggerClick();
  46444. }
  46445. FileChooserDialogBox::ContentComponent::ContentComponent()
  46446. {
  46447. setInterceptsMouseClicks (false, true);
  46448. }
  46449. FileChooserDialogBox::ContentComponent::~ContentComponent()
  46450. {
  46451. delete okButton;
  46452. delete cancelButton;
  46453. }
  46454. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  46455. {
  46456. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  46457. text.draw (g);
  46458. }
  46459. void FileChooserDialogBox::ContentComponent::resized()
  46460. {
  46461. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  46462. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  46463. const int y = roundToInt (bb.getBottom()) + 10;
  46464. const int buttonHeight = 26;
  46465. const int buttonY = getHeight() - buttonHeight - 8;
  46466. chooserComponent->setBounds (0, y, getWidth(), buttonY - y - 20);
  46467. okButton->setBounds (proportionOfWidth (0.25f), buttonY,
  46468. proportionOfWidth (0.2f), buttonHeight);
  46469. cancelButton->setBounds (proportionOfWidth (0.55f), buttonY,
  46470. proportionOfWidth (0.2f), buttonHeight);
  46471. }
  46472. END_JUCE_NAMESPACE
  46473. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  46474. /*** Start of inlined file: juce_FileFilter.cpp ***/
  46475. BEGIN_JUCE_NAMESPACE
  46476. FileFilter::FileFilter (const String& filterDescription)
  46477. : description (filterDescription)
  46478. {
  46479. }
  46480. FileFilter::~FileFilter()
  46481. {
  46482. }
  46483. const String& FileFilter::getDescription() const throw()
  46484. {
  46485. return description;
  46486. }
  46487. END_JUCE_NAMESPACE
  46488. /*** End of inlined file: juce_FileFilter.cpp ***/
  46489. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  46490. BEGIN_JUCE_NAMESPACE
  46491. Image* juce_createIconForFile (const File& file);
  46492. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  46493. : ListBox (String::empty, 0),
  46494. DirectoryContentsDisplayComponent (listToShow)
  46495. {
  46496. setModel (this);
  46497. fileList.addChangeListener (this);
  46498. }
  46499. FileListComponent::~FileListComponent()
  46500. {
  46501. fileList.removeChangeListener (this);
  46502. deleteAllChildren();
  46503. }
  46504. int FileListComponent::getNumSelectedFiles() const
  46505. {
  46506. return getNumSelectedRows();
  46507. }
  46508. const File FileListComponent::getSelectedFile (int index) const
  46509. {
  46510. return fileList.getFile (getSelectedRow (index));
  46511. }
  46512. void FileListComponent::deselectAllFiles()
  46513. {
  46514. deselectAllRows();
  46515. }
  46516. void FileListComponent::scrollToTop()
  46517. {
  46518. getVerticalScrollBar()->setCurrentRangeStart (0);
  46519. }
  46520. void FileListComponent::changeListenerCallback (void*)
  46521. {
  46522. updateContent();
  46523. if (lastDirectory != fileList.getDirectory())
  46524. {
  46525. lastDirectory = fileList.getDirectory();
  46526. deselectAllRows();
  46527. }
  46528. }
  46529. class FileListItemComponent : public Component,
  46530. public TimeSliceClient,
  46531. public AsyncUpdater
  46532. {
  46533. public:
  46534. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  46535. : owner (owner_), thread (thread_),
  46536. highlighted (false), index (0), icon (0)
  46537. {
  46538. }
  46539. ~FileListItemComponent()
  46540. {
  46541. thread.removeTimeSliceClient (this);
  46542. clearIcon();
  46543. }
  46544. void paint (Graphics& g)
  46545. {
  46546. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  46547. file.getFileName(),
  46548. icon,
  46549. fileSize, modTime,
  46550. isDirectory, highlighted,
  46551. index);
  46552. }
  46553. void mouseDown (const MouseEvent& e)
  46554. {
  46555. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  46556. owner.sendMouseClickMessage (file, e);
  46557. }
  46558. void mouseDoubleClick (const MouseEvent&)
  46559. {
  46560. owner.sendDoubleClickMessage (file);
  46561. }
  46562. void update (const File& root,
  46563. const DirectoryContentsList::FileInfo* const fileInfo,
  46564. const int index_,
  46565. const bool highlighted_)
  46566. {
  46567. thread.removeTimeSliceClient (this);
  46568. if (highlighted_ != highlighted
  46569. || index_ != index)
  46570. {
  46571. index = index_;
  46572. highlighted = highlighted_;
  46573. repaint();
  46574. }
  46575. File newFile;
  46576. String newFileSize;
  46577. String newModTime;
  46578. if (fileInfo != 0)
  46579. {
  46580. newFile = root.getChildFile (fileInfo->filename);
  46581. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  46582. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  46583. }
  46584. if (newFile != file
  46585. || fileSize != newFileSize
  46586. || modTime != newModTime)
  46587. {
  46588. file = newFile;
  46589. fileSize = newFileSize;
  46590. modTime = newModTime;
  46591. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  46592. repaint();
  46593. clearIcon();
  46594. }
  46595. if (file != File::nonexistent
  46596. && icon == 0 && ! isDirectory)
  46597. {
  46598. updateIcon (true);
  46599. if (icon == 0)
  46600. thread.addTimeSliceClient (this);
  46601. }
  46602. }
  46603. bool useTimeSlice()
  46604. {
  46605. updateIcon (false);
  46606. return false;
  46607. }
  46608. void handleAsyncUpdate()
  46609. {
  46610. repaint();
  46611. }
  46612. juce_UseDebuggingNewOperator
  46613. private:
  46614. FileListComponent& owner;
  46615. TimeSliceThread& thread;
  46616. bool highlighted;
  46617. int index;
  46618. File file;
  46619. String fileSize;
  46620. String modTime;
  46621. Image* icon;
  46622. bool isDirectory;
  46623. void clearIcon()
  46624. {
  46625. ImageCache::release (icon);
  46626. icon = 0;
  46627. }
  46628. void updateIcon (const bool onlyUpdateIfCached)
  46629. {
  46630. if (icon == 0)
  46631. {
  46632. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  46633. Image* im = ImageCache::getFromHashCode (hashCode);
  46634. if (im == 0 && ! onlyUpdateIfCached)
  46635. {
  46636. im = juce_createIconForFile (file);
  46637. if (im != 0)
  46638. ImageCache::addImageToCache (im, hashCode);
  46639. }
  46640. if (im != 0)
  46641. {
  46642. icon = im;
  46643. triggerAsyncUpdate();
  46644. }
  46645. }
  46646. }
  46647. };
  46648. int FileListComponent::getNumRows()
  46649. {
  46650. return fileList.getNumFiles();
  46651. }
  46652. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  46653. {
  46654. }
  46655. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  46656. {
  46657. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  46658. if (comp == 0)
  46659. {
  46660. delete existingComponentToUpdate;
  46661. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  46662. }
  46663. DirectoryContentsList::FileInfo fileInfo;
  46664. if (fileList.getFileInfo (row, fileInfo))
  46665. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  46666. else
  46667. comp->update (fileList.getDirectory(), 0, row, isSelected);
  46668. return comp;
  46669. }
  46670. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  46671. {
  46672. sendSelectionChangeMessage();
  46673. }
  46674. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  46675. {
  46676. }
  46677. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  46678. {
  46679. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  46680. }
  46681. END_JUCE_NAMESPACE
  46682. /*** End of inlined file: juce_FileListComponent.cpp ***/
  46683. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  46684. BEGIN_JUCE_NAMESPACE
  46685. FilenameComponent::FilenameComponent (const String& name,
  46686. const File& currentFile,
  46687. const bool canEditFilename,
  46688. const bool isDirectory,
  46689. const bool isForSaving,
  46690. const String& fileBrowserWildcard,
  46691. const String& enforcedSuffix_,
  46692. const String& textWhenNothingSelected)
  46693. : Component (name),
  46694. maxRecentFiles (30),
  46695. isDir (isDirectory),
  46696. isSaving (isForSaving),
  46697. isFileDragOver (false),
  46698. wildcard (fileBrowserWildcard),
  46699. enforcedSuffix (enforcedSuffix_)
  46700. {
  46701. addAndMakeVisible (filenameBox = new ComboBox ("fn"));
  46702. filenameBox->setEditableText (canEditFilename);
  46703. filenameBox->addListener (this);
  46704. filenameBox->setTextWhenNothingSelected (textWhenNothingSelected);
  46705. filenameBox->setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  46706. browseButton = 0;
  46707. setBrowseButtonText ("...");
  46708. setCurrentFile (currentFile, true);
  46709. }
  46710. FilenameComponent::~FilenameComponent()
  46711. {
  46712. deleteAllChildren();
  46713. }
  46714. void FilenameComponent::paintOverChildren (Graphics& g)
  46715. {
  46716. if (isFileDragOver)
  46717. {
  46718. g.setColour (Colours::red.withAlpha (0.2f));
  46719. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  46720. }
  46721. }
  46722. void FilenameComponent::resized()
  46723. {
  46724. getLookAndFeel().layoutFilenameComponent (*this, filenameBox, browseButton);
  46725. }
  46726. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  46727. {
  46728. browseButtonText = newBrowseButtonText;
  46729. lookAndFeelChanged();
  46730. }
  46731. void FilenameComponent::lookAndFeelChanged()
  46732. {
  46733. deleteAndZero (browseButton);
  46734. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  46735. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  46736. resized();
  46737. browseButton->addButtonListener (this);
  46738. }
  46739. void FilenameComponent::setTooltip (const String& newTooltip)
  46740. {
  46741. SettableTooltipClient::setTooltip (newTooltip);
  46742. filenameBox->setTooltip (newTooltip);
  46743. }
  46744. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  46745. {
  46746. defaultBrowseFile = newDefaultDirectory;
  46747. }
  46748. void FilenameComponent::buttonClicked (Button*)
  46749. {
  46750. FileChooser fc (TRANS("Choose a new file"),
  46751. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  46752. : getCurrentFile(),
  46753. wildcard);
  46754. if (isDir ? fc.browseForDirectory()
  46755. : (isSaving ? fc.browseForFileToSave (false)
  46756. : fc.browseForFileToOpen()))
  46757. {
  46758. setCurrentFile (fc.getResult(), true);
  46759. }
  46760. }
  46761. void FilenameComponent::comboBoxChanged (ComboBox*)
  46762. {
  46763. setCurrentFile (getCurrentFile(), true);
  46764. }
  46765. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  46766. {
  46767. return true;
  46768. }
  46769. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  46770. {
  46771. isFileDragOver = false;
  46772. repaint();
  46773. const File f (filenames[0]);
  46774. if (f.exists() && (f.isDirectory() == isDir))
  46775. setCurrentFile (f, true);
  46776. }
  46777. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  46778. {
  46779. isFileDragOver = true;
  46780. repaint();
  46781. }
  46782. void FilenameComponent::fileDragExit (const StringArray&)
  46783. {
  46784. isFileDragOver = false;
  46785. repaint();
  46786. }
  46787. const File FilenameComponent::getCurrentFile() const
  46788. {
  46789. File f (filenameBox->getText());
  46790. if (enforcedSuffix.isNotEmpty())
  46791. f = f.withFileExtension (enforcedSuffix);
  46792. return f;
  46793. }
  46794. void FilenameComponent::setCurrentFile (File newFile,
  46795. const bool addToRecentlyUsedList,
  46796. const bool sendChangeNotification)
  46797. {
  46798. if (enforcedSuffix.isNotEmpty())
  46799. newFile = newFile.withFileExtension (enforcedSuffix);
  46800. if (newFile.getFullPathName() != lastFilename)
  46801. {
  46802. lastFilename = newFile.getFullPathName();
  46803. if (addToRecentlyUsedList)
  46804. addRecentlyUsedFile (newFile);
  46805. filenameBox->setText (lastFilename, true);
  46806. if (sendChangeNotification)
  46807. triggerAsyncUpdate();
  46808. }
  46809. }
  46810. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  46811. {
  46812. filenameBox->setEditableText (shouldBeEditable);
  46813. }
  46814. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  46815. {
  46816. StringArray names;
  46817. for (int i = 0; i < filenameBox->getNumItems(); ++i)
  46818. names.add (filenameBox->getItemText (i));
  46819. return names;
  46820. }
  46821. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  46822. {
  46823. if (filenames != getRecentlyUsedFilenames())
  46824. {
  46825. filenameBox->clear();
  46826. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  46827. filenameBox->addItem (filenames[i], i + 1);
  46828. }
  46829. }
  46830. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  46831. {
  46832. maxRecentFiles = jmax (1, newMaximum);
  46833. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  46834. }
  46835. void FilenameComponent::addRecentlyUsedFile (const File& file)
  46836. {
  46837. StringArray files (getRecentlyUsedFilenames());
  46838. if (file.getFullPathName().isNotEmpty())
  46839. {
  46840. files.removeString (file.getFullPathName(), true);
  46841. files.insert (0, file.getFullPathName());
  46842. setRecentlyUsedFilenames (files);
  46843. }
  46844. }
  46845. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  46846. {
  46847. listeners.add (listener);
  46848. }
  46849. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  46850. {
  46851. listeners.remove (listener);
  46852. }
  46853. void FilenameComponent::handleAsyncUpdate()
  46854. {
  46855. Component::BailOutChecker checker (this);
  46856. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  46857. }
  46858. END_JUCE_NAMESPACE
  46859. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  46860. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  46861. BEGIN_JUCE_NAMESPACE
  46862. FileSearchPathListComponent::FileSearchPathListComponent()
  46863. {
  46864. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  46865. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  46866. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  46867. listBox->setOutlineThickness (1);
  46868. addAndMakeVisible (addButton = new TextButton ("+"));
  46869. addButton->addButtonListener (this);
  46870. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  46871. addAndMakeVisible (removeButton = new TextButton ("-"));
  46872. removeButton->addButtonListener (this);
  46873. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  46874. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  46875. changeButton->addButtonListener (this);
  46876. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  46877. upButton->addButtonListener (this);
  46878. {
  46879. Path arrowPath;
  46880. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0f, 40.0f, 100.0f, 50.0f);
  46881. DrawablePath arrowImage;
  46882. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  46883. arrowImage.setPath (arrowPath);
  46884. upButton->setImages (&arrowImage);
  46885. }
  46886. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  46887. downButton->addButtonListener (this);
  46888. {
  46889. Path arrowPath;
  46890. arrowPath.addArrow (50.0f, 0.0f, 50.0f, 100.0f, 40.0f, 100.0f, 50.0f);
  46891. DrawablePath arrowImage;
  46892. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  46893. arrowImage.setPath (arrowPath);
  46894. downButton->setImages (&arrowImage);
  46895. }
  46896. updateButtons();
  46897. }
  46898. FileSearchPathListComponent::~FileSearchPathListComponent()
  46899. {
  46900. deleteAllChildren();
  46901. }
  46902. void FileSearchPathListComponent::updateButtons()
  46903. {
  46904. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  46905. removeButton->setEnabled (anythingSelected);
  46906. changeButton->setEnabled (anythingSelected);
  46907. upButton->setEnabled (anythingSelected);
  46908. downButton->setEnabled (anythingSelected);
  46909. }
  46910. void FileSearchPathListComponent::changed()
  46911. {
  46912. listBox->updateContent();
  46913. listBox->repaint();
  46914. updateButtons();
  46915. }
  46916. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  46917. {
  46918. if (newPath.toString() != path.toString())
  46919. {
  46920. path = newPath;
  46921. changed();
  46922. }
  46923. }
  46924. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  46925. {
  46926. defaultBrowseTarget = newDefaultDirectory;
  46927. }
  46928. int FileSearchPathListComponent::getNumRows()
  46929. {
  46930. return path.getNumPaths();
  46931. }
  46932. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  46933. {
  46934. if (rowIsSelected)
  46935. g.fillAll (findColour (TextEditor::highlightColourId));
  46936. g.setColour (findColour (ListBox::textColourId));
  46937. Font f (height * 0.7f);
  46938. f.setHorizontalScale (0.9f);
  46939. g.setFont (f);
  46940. g.drawText (path [rowNumber].getFullPathName(),
  46941. 4, 0, width - 6, height,
  46942. Justification::centredLeft, true);
  46943. }
  46944. void FileSearchPathListComponent::deleteKeyPressed (int row)
  46945. {
  46946. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  46947. {
  46948. path.remove (row);
  46949. changed();
  46950. }
  46951. }
  46952. void FileSearchPathListComponent::returnKeyPressed (int row)
  46953. {
  46954. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  46955. if (chooser.browseForDirectory())
  46956. {
  46957. path.remove (row);
  46958. path.add (chooser.getResult(), row);
  46959. changed();
  46960. }
  46961. }
  46962. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  46963. {
  46964. returnKeyPressed (row);
  46965. }
  46966. void FileSearchPathListComponent::selectedRowsChanged (int)
  46967. {
  46968. updateButtons();
  46969. }
  46970. void FileSearchPathListComponent::paint (Graphics& g)
  46971. {
  46972. g.fillAll (findColour (backgroundColourId));
  46973. }
  46974. void FileSearchPathListComponent::resized()
  46975. {
  46976. const int buttonH = 22;
  46977. const int buttonY = getHeight() - buttonH - 4;
  46978. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  46979. addButton->setBounds (2, buttonY, buttonH, buttonH);
  46980. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  46981. changeButton->changeWidthToFitText (buttonH);
  46982. downButton->setSize (buttonH * 2, buttonH);
  46983. upButton->setSize (buttonH * 2, buttonH);
  46984. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  46985. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  46986. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  46987. }
  46988. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  46989. {
  46990. return true;
  46991. }
  46992. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  46993. {
  46994. for (int i = filenames.size(); --i >= 0;)
  46995. {
  46996. const File f (filenames[i]);
  46997. if (f.isDirectory())
  46998. {
  46999. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  47000. path.add (f, row);
  47001. changed();
  47002. }
  47003. }
  47004. }
  47005. void FileSearchPathListComponent::buttonClicked (Button* button)
  47006. {
  47007. const int currentRow = listBox->getSelectedRow();
  47008. if (button == removeButton)
  47009. {
  47010. deleteKeyPressed (currentRow);
  47011. }
  47012. else if (button == addButton)
  47013. {
  47014. File start (defaultBrowseTarget);
  47015. if (start == File::nonexistent)
  47016. start = path [0];
  47017. if (start == File::nonexistent)
  47018. start = File::getCurrentWorkingDirectory();
  47019. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  47020. if (chooser.browseForDirectory())
  47021. {
  47022. path.add (chooser.getResult(), currentRow);
  47023. }
  47024. }
  47025. else if (button == changeButton)
  47026. {
  47027. returnKeyPressed (currentRow);
  47028. }
  47029. else if (button == upButton)
  47030. {
  47031. if (currentRow > 0 && currentRow < path.getNumPaths())
  47032. {
  47033. const File f (path[currentRow]);
  47034. path.remove (currentRow);
  47035. path.add (f, currentRow - 1);
  47036. listBox->selectRow (currentRow - 1);
  47037. }
  47038. }
  47039. else if (button == downButton)
  47040. {
  47041. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  47042. {
  47043. const File f (path[currentRow]);
  47044. path.remove (currentRow);
  47045. path.add (f, currentRow + 1);
  47046. listBox->selectRow (currentRow + 1);
  47047. }
  47048. }
  47049. changed();
  47050. }
  47051. END_JUCE_NAMESPACE
  47052. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47053. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  47054. BEGIN_JUCE_NAMESPACE
  47055. Image* juce_createIconForFile (const File& file);
  47056. class FileListTreeItem : public TreeViewItem,
  47057. public TimeSliceClient,
  47058. public AsyncUpdater,
  47059. public ChangeListener
  47060. {
  47061. public:
  47062. FileListTreeItem (FileTreeComponent& owner_,
  47063. DirectoryContentsList* const parentContentsList_,
  47064. const int indexInContentsList_,
  47065. const File& file_,
  47066. TimeSliceThread& thread_)
  47067. : file (file_),
  47068. owner (owner_),
  47069. parentContentsList (parentContentsList_),
  47070. indexInContentsList (indexInContentsList_),
  47071. subContentsList (0),
  47072. canDeleteSubContentsList (false),
  47073. thread (thread_),
  47074. icon (0)
  47075. {
  47076. DirectoryContentsList::FileInfo fileInfo;
  47077. if (parentContentsList_ != 0
  47078. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  47079. {
  47080. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  47081. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  47082. isDirectory = fileInfo.isDirectory;
  47083. }
  47084. else
  47085. {
  47086. isDirectory = true;
  47087. }
  47088. }
  47089. ~FileListTreeItem()
  47090. {
  47091. thread.removeTimeSliceClient (this);
  47092. clearSubItems();
  47093. ImageCache::release (icon);
  47094. if (canDeleteSubContentsList)
  47095. delete subContentsList;
  47096. }
  47097. bool mightContainSubItems() { return isDirectory; }
  47098. const String getUniqueName() const { return file.getFullPathName(); }
  47099. int getItemHeight() const { return 22; }
  47100. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  47101. void itemOpennessChanged (bool isNowOpen)
  47102. {
  47103. if (isNowOpen)
  47104. {
  47105. clearSubItems();
  47106. isDirectory = file.isDirectory();
  47107. if (isDirectory)
  47108. {
  47109. if (subContentsList == 0)
  47110. {
  47111. jassert (parentContentsList != 0);
  47112. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  47113. l->setDirectory (file, true, true);
  47114. setSubContentsList (l);
  47115. canDeleteSubContentsList = true;
  47116. }
  47117. changeListenerCallback (0);
  47118. }
  47119. }
  47120. }
  47121. void setSubContentsList (DirectoryContentsList* newList)
  47122. {
  47123. jassert (subContentsList == 0);
  47124. subContentsList = newList;
  47125. newList->addChangeListener (this);
  47126. }
  47127. void changeListenerCallback (void*)
  47128. {
  47129. clearSubItems();
  47130. if (isOpen() && subContentsList != 0)
  47131. {
  47132. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  47133. {
  47134. FileListTreeItem* const item
  47135. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  47136. addSubItem (item);
  47137. }
  47138. }
  47139. }
  47140. void paintItem (Graphics& g, int width, int height)
  47141. {
  47142. if (file != File::nonexistent)
  47143. {
  47144. updateIcon (true);
  47145. if (icon == 0)
  47146. thread.addTimeSliceClient (this);
  47147. }
  47148. owner.getLookAndFeel()
  47149. .drawFileBrowserRow (g, width, height,
  47150. file.getFileName(),
  47151. icon,
  47152. fileSize, modTime,
  47153. isDirectory, isSelected(),
  47154. indexInContentsList);
  47155. }
  47156. void itemClicked (const MouseEvent& e)
  47157. {
  47158. owner.sendMouseClickMessage (file, e);
  47159. }
  47160. void itemDoubleClicked (const MouseEvent& e)
  47161. {
  47162. TreeViewItem::itemDoubleClicked (e);
  47163. owner.sendDoubleClickMessage (file);
  47164. }
  47165. void itemSelectionChanged (bool)
  47166. {
  47167. owner.sendSelectionChangeMessage();
  47168. }
  47169. bool useTimeSlice()
  47170. {
  47171. updateIcon (false);
  47172. thread.removeTimeSliceClient (this);
  47173. return false;
  47174. }
  47175. void handleAsyncUpdate()
  47176. {
  47177. owner.repaint();
  47178. }
  47179. const File file;
  47180. juce_UseDebuggingNewOperator
  47181. private:
  47182. FileTreeComponent& owner;
  47183. DirectoryContentsList* parentContentsList;
  47184. int indexInContentsList;
  47185. DirectoryContentsList* subContentsList;
  47186. bool isDirectory, canDeleteSubContentsList;
  47187. TimeSliceThread& thread;
  47188. Image* icon;
  47189. String fileSize;
  47190. String modTime;
  47191. void updateIcon (const bool onlyUpdateIfCached)
  47192. {
  47193. if (icon == 0)
  47194. {
  47195. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47196. Image* im = ImageCache::getFromHashCode (hashCode);
  47197. if (im == 0 && ! onlyUpdateIfCached)
  47198. {
  47199. im = juce_createIconForFile (file);
  47200. if (im != 0)
  47201. ImageCache::addImageToCache (im, hashCode);
  47202. }
  47203. if (im != 0)
  47204. {
  47205. icon = im;
  47206. triggerAsyncUpdate();
  47207. }
  47208. }
  47209. }
  47210. };
  47211. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  47212. : DirectoryContentsDisplayComponent (listToShow)
  47213. {
  47214. FileListTreeItem* const root
  47215. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  47216. listToShow.getTimeSliceThread());
  47217. root->setSubContentsList (&listToShow);
  47218. setRootItemVisible (false);
  47219. setRootItem (root);
  47220. }
  47221. FileTreeComponent::~FileTreeComponent()
  47222. {
  47223. deleteRootItem();
  47224. }
  47225. const File FileTreeComponent::getSelectedFile (const int index) const
  47226. {
  47227. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  47228. return item != 0 ? item->file
  47229. : File::nonexistent;
  47230. }
  47231. void FileTreeComponent::deselectAllFiles()
  47232. {
  47233. clearSelectedItems();
  47234. }
  47235. void FileTreeComponent::scrollToTop()
  47236. {
  47237. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  47238. }
  47239. void FileTreeComponent::setDragAndDropDescription (const String& description)
  47240. {
  47241. dragAndDropDescription = description;
  47242. }
  47243. END_JUCE_NAMESPACE
  47244. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  47245. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  47246. BEGIN_JUCE_NAMESPACE
  47247. ImagePreviewComponent::ImagePreviewComponent()
  47248. {
  47249. }
  47250. ImagePreviewComponent::~ImagePreviewComponent()
  47251. {
  47252. }
  47253. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  47254. {
  47255. const int availableW = proportionOfWidth (0.97f);
  47256. const int availableH = getHeight() - 13 * 4;
  47257. const double scale = jmin (1.0,
  47258. availableW / (double) w,
  47259. availableH / (double) h);
  47260. w = roundToInt (scale * w);
  47261. h = roundToInt (scale * h);
  47262. }
  47263. void ImagePreviewComponent::selectedFileChanged (const File& file)
  47264. {
  47265. if (fileToLoad != file)
  47266. {
  47267. fileToLoad = file;
  47268. startTimer (100);
  47269. }
  47270. }
  47271. void ImagePreviewComponent::timerCallback()
  47272. {
  47273. stopTimer();
  47274. currentThumbnail = 0;
  47275. currentDetails = String::empty;
  47276. repaint();
  47277. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  47278. if (in != 0)
  47279. {
  47280. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  47281. if (format != 0)
  47282. {
  47283. currentThumbnail = format->decodeImage (*in);
  47284. if (currentThumbnail != 0)
  47285. {
  47286. int w = currentThumbnail->getWidth();
  47287. int h = currentThumbnail->getHeight();
  47288. currentDetails
  47289. << fileToLoad.getFileName() << "\n"
  47290. << format->getFormatName() << "\n"
  47291. << w << " x " << h << " pixels\n"
  47292. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  47293. getThumbSize (w, h);
  47294. currentThumbnail = currentThumbnail->createCopy (w, h);
  47295. }
  47296. }
  47297. }
  47298. }
  47299. void ImagePreviewComponent::paint (Graphics& g)
  47300. {
  47301. if (currentThumbnail != 0)
  47302. {
  47303. g.setFont (13.0f);
  47304. int w = currentThumbnail->getWidth();
  47305. int h = currentThumbnail->getHeight();
  47306. getThumbSize (w, h);
  47307. const int numLines = 4;
  47308. const int totalH = 13 * numLines + h + 4;
  47309. const int y = (getHeight() - totalH) / 2;
  47310. g.drawImageWithin (currentThumbnail,
  47311. (getWidth() - w) / 2, y, w, h,
  47312. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  47313. false);
  47314. g.drawFittedText (currentDetails,
  47315. 0, y + h + 4, getWidth(), 100,
  47316. Justification::centredTop, numLines);
  47317. }
  47318. }
  47319. END_JUCE_NAMESPACE
  47320. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  47321. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  47322. BEGIN_JUCE_NAMESPACE
  47323. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  47324. const String& directoryWildcardPatterns,
  47325. const String& description_)
  47326. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  47327. : (description_ + " (" + fileWildcardPatterns + ")"))
  47328. {
  47329. parse (fileWildcardPatterns, fileWildcards);
  47330. parse (directoryWildcardPatterns, directoryWildcards);
  47331. }
  47332. WildcardFileFilter::~WildcardFileFilter()
  47333. {
  47334. }
  47335. bool WildcardFileFilter::isFileSuitable (const File& file) const
  47336. {
  47337. return match (file, fileWildcards);
  47338. }
  47339. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  47340. {
  47341. return match (file, directoryWildcards);
  47342. }
  47343. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  47344. {
  47345. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  47346. result.trim();
  47347. result.removeEmptyStrings();
  47348. // special case for *.*, because people use it to mean "any file", but it
  47349. // would actually ignore files with no extension.
  47350. for (int i = result.size(); --i >= 0;)
  47351. if (result[i] == "*.*")
  47352. result.set (i, "*");
  47353. }
  47354. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  47355. {
  47356. const String filename (file.getFileName());
  47357. for (int i = wildcards.size(); --i >= 0;)
  47358. if (filename.matchesWildcard (wildcards[i], true))
  47359. return true;
  47360. return false;
  47361. }
  47362. END_JUCE_NAMESPACE
  47363. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  47364. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  47365. BEGIN_JUCE_NAMESPACE
  47366. KeyboardFocusTraverser::KeyboardFocusTraverser()
  47367. {
  47368. }
  47369. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  47370. {
  47371. }
  47372. namespace KeyboardFocusHelpers
  47373. {
  47374. // This will sort a set of components, so that they are ordered in terms of
  47375. // left-to-right and then top-to-bottom.
  47376. class ScreenPositionComparator
  47377. {
  47378. public:
  47379. ScreenPositionComparator() {}
  47380. static int compareElements (const Component* const first, const Component* const second)
  47381. {
  47382. int explicitOrder1 = first->getExplicitFocusOrder();
  47383. if (explicitOrder1 <= 0)
  47384. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  47385. int explicitOrder2 = second->getExplicitFocusOrder();
  47386. if (explicitOrder2 <= 0)
  47387. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  47388. if (explicitOrder1 != explicitOrder2)
  47389. return explicitOrder1 - explicitOrder2;
  47390. const int diff = first->getY() - second->getY();
  47391. return (diff == 0) ? first->getX() - second->getX()
  47392. : diff;
  47393. }
  47394. };
  47395. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  47396. {
  47397. if (parent->getNumChildComponents() > 0)
  47398. {
  47399. Array <Component*> localComps;
  47400. ScreenPositionComparator comparator;
  47401. int i;
  47402. for (i = parent->getNumChildComponents(); --i >= 0;)
  47403. {
  47404. Component* const c = parent->getChildComponent (i);
  47405. if (c->isVisible() && c->isEnabled())
  47406. localComps.addSorted (comparator, c);
  47407. }
  47408. for (i = 0; i < localComps.size(); ++i)
  47409. {
  47410. Component* const c = localComps.getUnchecked (i);
  47411. if (c->getWantsKeyboardFocus())
  47412. comps.add (c);
  47413. if (! c->isFocusContainer())
  47414. findAllFocusableComponents (c, comps);
  47415. }
  47416. }
  47417. }
  47418. }
  47419. static Component* getIncrementedComponent (Component* const current, const int delta)
  47420. {
  47421. Component* focusContainer = current->getParentComponent();
  47422. if (focusContainer != 0)
  47423. {
  47424. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  47425. focusContainer = focusContainer->getParentComponent();
  47426. if (focusContainer != 0)
  47427. {
  47428. Array <Component*> comps;
  47429. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  47430. if (comps.size() > 0)
  47431. {
  47432. const int index = comps.indexOf (current);
  47433. return comps [(index + comps.size() + delta) % comps.size()];
  47434. }
  47435. }
  47436. }
  47437. return 0;
  47438. }
  47439. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  47440. {
  47441. return getIncrementedComponent (current, 1);
  47442. }
  47443. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  47444. {
  47445. return getIncrementedComponent (current, -1);
  47446. }
  47447. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  47448. {
  47449. Array <Component*> comps;
  47450. if (parentComponent != 0)
  47451. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  47452. return comps.getFirst();
  47453. }
  47454. END_JUCE_NAMESPACE
  47455. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  47456. /*** Start of inlined file: juce_KeyListener.cpp ***/
  47457. BEGIN_JUCE_NAMESPACE
  47458. bool KeyListener::keyStateChanged (const bool, Component*)
  47459. {
  47460. return false;
  47461. }
  47462. END_JUCE_NAMESPACE
  47463. /*** End of inlined file: juce_KeyListener.cpp ***/
  47464. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  47465. BEGIN_JUCE_NAMESPACE
  47466. // N.B. these two includes are put here deliberately to avoid problems with
  47467. // old GCCs failing on long include paths
  47468. const int maxKeys = 3;
  47469. class KeyMappingChangeButton : public Button
  47470. {
  47471. public:
  47472. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  47473. const CommandID commandID_,
  47474. const String& keyName,
  47475. const int keyNum_)
  47476. : Button (keyName),
  47477. owner (owner_),
  47478. commandID (commandID_),
  47479. keyNum (keyNum_)
  47480. {
  47481. setWantsKeyboardFocus (false);
  47482. setTriggeredOnMouseDown (keyNum >= 0);
  47483. if (keyNum_ < 0)
  47484. setTooltip (TRANS("adds a new key-mapping"));
  47485. else
  47486. setTooltip (TRANS("click to change this key-mapping"));
  47487. }
  47488. ~KeyMappingChangeButton()
  47489. {
  47490. }
  47491. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  47492. {
  47493. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  47494. keyNum >= 0 ? getName() : String::empty);
  47495. }
  47496. void clicked()
  47497. {
  47498. if (keyNum >= 0)
  47499. {
  47500. // existing key clicked..
  47501. PopupMenu m;
  47502. m.addItem (1, TRANS("change this key-mapping"));
  47503. m.addSeparator();
  47504. m.addItem (2, TRANS("remove this key-mapping"));
  47505. const int res = m.show();
  47506. if (res == 1)
  47507. {
  47508. owner->assignNewKey (commandID, keyNum);
  47509. }
  47510. else if (res == 2)
  47511. {
  47512. owner->getMappings()->removeKeyPress (commandID, keyNum);
  47513. }
  47514. }
  47515. else
  47516. {
  47517. // + button pressed..
  47518. owner->assignNewKey (commandID, -1);
  47519. }
  47520. }
  47521. void fitToContent (const int h) throw()
  47522. {
  47523. if (keyNum < 0)
  47524. {
  47525. setSize (h, h);
  47526. }
  47527. else
  47528. {
  47529. Font f (h * 0.6f);
  47530. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  47531. }
  47532. }
  47533. juce_UseDebuggingNewOperator
  47534. private:
  47535. KeyMappingEditorComponent* const owner;
  47536. const CommandID commandID;
  47537. const int keyNum;
  47538. KeyMappingChangeButton (const KeyMappingChangeButton&);
  47539. KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  47540. };
  47541. class KeyMappingItemComponent : public Component
  47542. {
  47543. public:
  47544. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  47545. const CommandID commandID_)
  47546. : owner (owner_),
  47547. commandID (commandID_)
  47548. {
  47549. setInterceptsMouseClicks (false, true);
  47550. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  47551. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  47552. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  47553. {
  47554. KeyMappingChangeButton* const kb
  47555. = new KeyMappingChangeButton (owner_, commandID,
  47556. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  47557. kb->setEnabled (! isReadOnly);
  47558. addAndMakeVisible (kb);
  47559. }
  47560. KeyMappingChangeButton* const kb
  47561. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  47562. addChildComponent (kb);
  47563. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  47564. }
  47565. ~KeyMappingItemComponent()
  47566. {
  47567. deleteAllChildren();
  47568. }
  47569. void paint (Graphics& g)
  47570. {
  47571. g.setFont (getHeight() * 0.7f);
  47572. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  47573. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  47574. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  47575. Justification::centredLeft, true);
  47576. }
  47577. void resized()
  47578. {
  47579. int x = getWidth() - 4;
  47580. for (int i = getNumChildComponents(); --i >= 0;)
  47581. {
  47582. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  47583. kb->fitToContent (getHeight() - 2);
  47584. kb->setTopRightPosition (x, 1);
  47585. x -= kb->getWidth() + 5;
  47586. }
  47587. }
  47588. juce_UseDebuggingNewOperator
  47589. private:
  47590. KeyMappingEditorComponent* const owner;
  47591. const CommandID commandID;
  47592. KeyMappingItemComponent (const KeyMappingItemComponent&);
  47593. KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  47594. };
  47595. class KeyMappingTreeViewItem : public TreeViewItem
  47596. {
  47597. public:
  47598. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  47599. const CommandID commandID_)
  47600. : owner (owner_),
  47601. commandID (commandID_)
  47602. {
  47603. }
  47604. ~KeyMappingTreeViewItem()
  47605. {
  47606. }
  47607. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  47608. bool mightContainSubItems() { return false; }
  47609. int getItemHeight() const { return 20; }
  47610. Component* createItemComponent()
  47611. {
  47612. return new KeyMappingItemComponent (owner, commandID);
  47613. }
  47614. juce_UseDebuggingNewOperator
  47615. private:
  47616. KeyMappingEditorComponent* const owner;
  47617. const CommandID commandID;
  47618. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  47619. KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  47620. };
  47621. class KeyCategoryTreeViewItem : public TreeViewItem
  47622. {
  47623. public:
  47624. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  47625. const String& name)
  47626. : owner (owner_),
  47627. categoryName (name)
  47628. {
  47629. }
  47630. ~KeyCategoryTreeViewItem()
  47631. {
  47632. }
  47633. const String getUniqueName() const { return categoryName + "_cat"; }
  47634. bool mightContainSubItems() { return true; }
  47635. int getItemHeight() const { return 28; }
  47636. void paintItem (Graphics& g, int width, int height)
  47637. {
  47638. g.setFont (height * 0.6f, Font::bold);
  47639. g.setColour (owner->findColour (KeyMappingEditorComponent::textColourId));
  47640. g.drawText (categoryName,
  47641. 2, 0, width - 2, height,
  47642. Justification::centredLeft, true);
  47643. }
  47644. void itemOpennessChanged (bool isNowOpen)
  47645. {
  47646. if (isNowOpen)
  47647. {
  47648. if (getNumSubItems() == 0)
  47649. {
  47650. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  47651. for (int i = 0; i < commands.size(); ++i)
  47652. {
  47653. if (owner->shouldCommandBeIncluded (commands[i]))
  47654. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  47655. }
  47656. }
  47657. }
  47658. else
  47659. {
  47660. clearSubItems();
  47661. }
  47662. }
  47663. juce_UseDebuggingNewOperator
  47664. private:
  47665. KeyMappingEditorComponent* owner;
  47666. String categoryName;
  47667. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  47668. KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  47669. };
  47670. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  47671. const bool showResetToDefaultButton)
  47672. : mappings (mappingManager)
  47673. {
  47674. jassert (mappingManager != 0); // can't be null!
  47675. mappingManager->addChangeListener (this);
  47676. setLinesDrawnForSubItems (false);
  47677. resetButton = 0;
  47678. if (showResetToDefaultButton)
  47679. {
  47680. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  47681. resetButton->addButtonListener (this);
  47682. }
  47683. addAndMakeVisible (tree = new TreeView());
  47684. tree->setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  47685. tree->setRootItemVisible (false);
  47686. tree->setDefaultOpenness (true);
  47687. tree->setRootItem (this);
  47688. }
  47689. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  47690. {
  47691. mappings->removeChangeListener (this);
  47692. deleteAllChildren();
  47693. }
  47694. bool KeyMappingEditorComponent::mightContainSubItems()
  47695. {
  47696. return true;
  47697. }
  47698. const String KeyMappingEditorComponent::getUniqueName() const
  47699. {
  47700. return "keys";
  47701. }
  47702. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  47703. const Colour& textColour)
  47704. {
  47705. setColour (backgroundColourId, mainBackground);
  47706. setColour (textColourId, textColour);
  47707. tree->setColour (TreeView::backgroundColourId, mainBackground);
  47708. }
  47709. void KeyMappingEditorComponent::parentHierarchyChanged()
  47710. {
  47711. changeListenerCallback (0);
  47712. }
  47713. void KeyMappingEditorComponent::resized()
  47714. {
  47715. int h = getHeight();
  47716. if (resetButton != 0)
  47717. {
  47718. const int buttonHeight = 20;
  47719. h -= buttonHeight + 8;
  47720. int x = getWidth() - 8;
  47721. resetButton->changeWidthToFitText (buttonHeight);
  47722. resetButton->setTopRightPosition (x, h + 6);
  47723. }
  47724. tree->setBounds (0, 0, getWidth(), h);
  47725. }
  47726. void KeyMappingEditorComponent::buttonClicked (Button* button)
  47727. {
  47728. if (button == resetButton)
  47729. {
  47730. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  47731. TRANS("Reset to defaults"),
  47732. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  47733. TRANS("Reset")))
  47734. {
  47735. mappings->resetToDefaultMappings();
  47736. }
  47737. }
  47738. }
  47739. void KeyMappingEditorComponent::changeListenerCallback (void*)
  47740. {
  47741. ScopedPointer <XmlElement> oldOpenness (tree->getOpennessState (true));
  47742. clearSubItems();
  47743. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  47744. for (int i = 0; i < categories.size(); ++i)
  47745. {
  47746. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  47747. int count = 0;
  47748. for (int j = 0; j < commands.size(); ++j)
  47749. if (shouldCommandBeIncluded (commands[j]))
  47750. ++count;
  47751. if (count > 0)
  47752. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  47753. }
  47754. if (oldOpenness != 0)
  47755. tree->restoreOpennessState (*oldOpenness);
  47756. }
  47757. class KeyEntryWindow : public AlertWindow
  47758. {
  47759. public:
  47760. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  47761. : AlertWindow (TRANS("New key-mapping"),
  47762. TRANS("Please press a key combination now..."),
  47763. AlertWindow::NoIcon),
  47764. owner (owner_)
  47765. {
  47766. addButton (TRANS("ok"), 1);
  47767. addButton (TRANS("cancel"), 0);
  47768. // (avoid return + escape keys getting processed by the buttons..)
  47769. for (int i = getNumChildComponents(); --i >= 0;)
  47770. getChildComponent (i)->setWantsKeyboardFocus (false);
  47771. setWantsKeyboardFocus (true);
  47772. grabKeyboardFocus();
  47773. }
  47774. ~KeyEntryWindow()
  47775. {
  47776. }
  47777. bool keyPressed (const KeyPress& key)
  47778. {
  47779. lastPress = key;
  47780. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  47781. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  47782. if (previousCommand != 0)
  47783. {
  47784. message << "\n\n"
  47785. << TRANS("(Currently assigned to \"")
  47786. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  47787. << "\")";
  47788. }
  47789. setMessage (message);
  47790. return true;
  47791. }
  47792. bool keyStateChanged (bool)
  47793. {
  47794. return true;
  47795. }
  47796. KeyPress lastPress;
  47797. juce_UseDebuggingNewOperator
  47798. private:
  47799. KeyMappingEditorComponent* owner;
  47800. KeyEntryWindow (const KeyEntryWindow&);
  47801. KeyEntryWindow& operator= (const KeyEntryWindow&);
  47802. };
  47803. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  47804. {
  47805. KeyEntryWindow entryWindow (this);
  47806. if (entryWindow.runModalLoop() != 0)
  47807. {
  47808. entryWindow.setVisible (false);
  47809. if (entryWindow.lastPress.isValid())
  47810. {
  47811. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  47812. if (previousCommand != 0)
  47813. {
  47814. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  47815. TRANS("Change key-mapping"),
  47816. TRANS("This key is already assigned to the command \"")
  47817. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  47818. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  47819. TRANS("re-assign"),
  47820. TRANS("cancel")))
  47821. {
  47822. return;
  47823. }
  47824. }
  47825. mappings->removeKeyPress (entryWindow.lastPress);
  47826. if (index >= 0)
  47827. mappings->removeKeyPress (commandID, index);
  47828. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  47829. }
  47830. }
  47831. }
  47832. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  47833. {
  47834. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  47835. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  47836. }
  47837. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  47838. {
  47839. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  47840. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  47841. }
  47842. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  47843. {
  47844. return key.getTextDescription();
  47845. }
  47846. END_JUCE_NAMESPACE
  47847. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  47848. /*** Start of inlined file: juce_KeyPress.cpp ***/
  47849. BEGIN_JUCE_NAMESPACE
  47850. KeyPress::KeyPress() throw()
  47851. : keyCode (0),
  47852. mods (0),
  47853. textCharacter (0)
  47854. {
  47855. }
  47856. KeyPress::KeyPress (const int keyCode_,
  47857. const ModifierKeys& mods_,
  47858. const juce_wchar textCharacter_) throw()
  47859. : keyCode (keyCode_),
  47860. mods (mods_),
  47861. textCharacter (textCharacter_)
  47862. {
  47863. }
  47864. KeyPress::KeyPress (const int keyCode_) throw()
  47865. : keyCode (keyCode_),
  47866. textCharacter (0)
  47867. {
  47868. }
  47869. KeyPress::KeyPress (const KeyPress& other) throw()
  47870. : keyCode (other.keyCode),
  47871. mods (other.mods),
  47872. textCharacter (other.textCharacter)
  47873. {
  47874. }
  47875. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  47876. {
  47877. keyCode = other.keyCode;
  47878. mods = other.mods;
  47879. textCharacter = other.textCharacter;
  47880. return *this;
  47881. }
  47882. bool KeyPress::operator== (const KeyPress& other) const throw()
  47883. {
  47884. return mods.getRawFlags() == other.mods.getRawFlags()
  47885. && (textCharacter == other.textCharacter
  47886. || textCharacter == 0
  47887. || other.textCharacter == 0)
  47888. && (keyCode == other.keyCode
  47889. || (keyCode < 256
  47890. && other.keyCode < 256
  47891. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  47892. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  47893. }
  47894. bool KeyPress::operator!= (const KeyPress& other) const throw()
  47895. {
  47896. return ! operator== (other);
  47897. }
  47898. bool KeyPress::isCurrentlyDown() const
  47899. {
  47900. return isKeyCurrentlyDown (keyCode)
  47901. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  47902. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  47903. }
  47904. namespace KeyPressHelpers
  47905. {
  47906. struct KeyNameAndCode
  47907. {
  47908. const char* name;
  47909. int code;
  47910. };
  47911. static const KeyNameAndCode translations[] =
  47912. {
  47913. { "spacebar", KeyPress::spaceKey },
  47914. { "return", KeyPress::returnKey },
  47915. { "escape", KeyPress::escapeKey },
  47916. { "backspace", KeyPress::backspaceKey },
  47917. { "cursor left", KeyPress::leftKey },
  47918. { "cursor right", KeyPress::rightKey },
  47919. { "cursor up", KeyPress::upKey },
  47920. { "cursor down", KeyPress::downKey },
  47921. { "page up", KeyPress::pageUpKey },
  47922. { "page down", KeyPress::pageDownKey },
  47923. { "home", KeyPress::homeKey },
  47924. { "end", KeyPress::endKey },
  47925. { "delete", KeyPress::deleteKey },
  47926. { "insert", KeyPress::insertKey },
  47927. { "tab", KeyPress::tabKey },
  47928. { "play", KeyPress::playKey },
  47929. { "stop", KeyPress::stopKey },
  47930. { "fast forward", KeyPress::fastForwardKey },
  47931. { "rewind", KeyPress::rewindKey }
  47932. };
  47933. static const String numberPadPrefix() { return "numpad "; }
  47934. }
  47935. const KeyPress KeyPress::createFromDescription (const String& desc)
  47936. {
  47937. int modifiers = 0;
  47938. if (desc.containsWholeWordIgnoreCase ("ctrl")
  47939. || desc.containsWholeWordIgnoreCase ("control")
  47940. || desc.containsWholeWordIgnoreCase ("ctl"))
  47941. modifiers |= ModifierKeys::ctrlModifier;
  47942. if (desc.containsWholeWordIgnoreCase ("shift")
  47943. || desc.containsWholeWordIgnoreCase ("shft"))
  47944. modifiers |= ModifierKeys::shiftModifier;
  47945. if (desc.containsWholeWordIgnoreCase ("alt")
  47946. || desc.containsWholeWordIgnoreCase ("option"))
  47947. modifiers |= ModifierKeys::altModifier;
  47948. if (desc.containsWholeWordIgnoreCase ("command")
  47949. || desc.containsWholeWordIgnoreCase ("cmd"))
  47950. modifiers |= ModifierKeys::commandModifier;
  47951. int key = 0;
  47952. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  47953. {
  47954. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  47955. {
  47956. key = KeyPressHelpers::translations[i].code;
  47957. break;
  47958. }
  47959. }
  47960. if (key == 0)
  47961. {
  47962. // see if it's a numpad key..
  47963. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  47964. {
  47965. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  47966. if (lastChar >= '0' && lastChar <= '9')
  47967. key = numberPad0 + lastChar - '0';
  47968. else if (lastChar == '+')
  47969. key = numberPadAdd;
  47970. else if (lastChar == '-')
  47971. key = numberPadSubtract;
  47972. else if (lastChar == '*')
  47973. key = numberPadMultiply;
  47974. else if (lastChar == '/')
  47975. key = numberPadDivide;
  47976. else if (lastChar == '.')
  47977. key = numberPadDecimalPoint;
  47978. else if (lastChar == '=')
  47979. key = numberPadEquals;
  47980. else if (desc.endsWith ("separator"))
  47981. key = numberPadSeparator;
  47982. else if (desc.endsWith ("delete"))
  47983. key = numberPadDelete;
  47984. }
  47985. if (key == 0)
  47986. {
  47987. // see if it's a function key..
  47988. for (int i = 1; i <= 12; ++i)
  47989. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  47990. key = F1Key + i - 1;
  47991. if (key == 0)
  47992. {
  47993. // give up and use the hex code..
  47994. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  47995. .toLowerCase()
  47996. .retainCharacters ("0123456789abcdef")
  47997. .getHexValue32();
  47998. if (hexCode > 0)
  47999. key = hexCode;
  48000. else
  48001. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  48002. }
  48003. }
  48004. }
  48005. return KeyPress (key, ModifierKeys (modifiers), 0);
  48006. }
  48007. const String KeyPress::getTextDescription() const
  48008. {
  48009. String desc;
  48010. if (keyCode > 0)
  48011. {
  48012. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  48013. // want to store it as being a slash, not shift+whatever.
  48014. if (textCharacter == '/')
  48015. return "/";
  48016. if (mods.isCtrlDown())
  48017. desc << "ctrl + ";
  48018. if (mods.isShiftDown())
  48019. desc << "shift + ";
  48020. #if JUCE_MAC
  48021. // only do this on the mac, because on Windows ctrl and command are the same,
  48022. // and this would get confusing
  48023. if (mods.isCommandDown())
  48024. desc << "command + ";
  48025. if (mods.isAltDown())
  48026. desc << "option + ";
  48027. #else
  48028. if (mods.isAltDown())
  48029. desc << "alt + ";
  48030. #endif
  48031. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48032. if (keyCode == KeyPressHelpers::translations[i].code)
  48033. return desc + KeyPressHelpers::translations[i].name;
  48034. if (keyCode >= F1Key && keyCode <= F16Key)
  48035. desc << 'F' << (1 + keyCode - F1Key);
  48036. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  48037. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  48038. else if (keyCode >= 33 && keyCode < 176)
  48039. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  48040. else if (keyCode == numberPadAdd)
  48041. desc << KeyPressHelpers::numberPadPrefix() << '+';
  48042. else if (keyCode == numberPadSubtract)
  48043. desc << KeyPressHelpers::numberPadPrefix() << '-';
  48044. else if (keyCode == numberPadMultiply)
  48045. desc << KeyPressHelpers::numberPadPrefix() << '*';
  48046. else if (keyCode == numberPadDivide)
  48047. desc << KeyPressHelpers::numberPadPrefix() << '/';
  48048. else if (keyCode == numberPadSeparator)
  48049. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  48050. else if (keyCode == numberPadDecimalPoint)
  48051. desc << KeyPressHelpers::numberPadPrefix() << '.';
  48052. else if (keyCode == numberPadDelete)
  48053. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  48054. else
  48055. desc << '#' << String::toHexString (keyCode);
  48056. }
  48057. return desc;
  48058. }
  48059. END_JUCE_NAMESPACE
  48060. /*** End of inlined file: juce_KeyPress.cpp ***/
  48061. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  48062. BEGIN_JUCE_NAMESPACE
  48063. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  48064. : commandManager (commandManager_)
  48065. {
  48066. // A manager is needed to get the descriptions of commands, and will be called when
  48067. // a command is invoked. So you can't leave this null..
  48068. jassert (commandManager_ != 0);
  48069. Desktop::getInstance().addFocusChangeListener (this);
  48070. }
  48071. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  48072. : commandManager (other.commandManager)
  48073. {
  48074. Desktop::getInstance().addFocusChangeListener (this);
  48075. }
  48076. KeyPressMappingSet::~KeyPressMappingSet()
  48077. {
  48078. Desktop::getInstance().removeFocusChangeListener (this);
  48079. }
  48080. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  48081. {
  48082. for (int i = 0; i < mappings.size(); ++i)
  48083. if (mappings.getUnchecked(i)->commandID == commandID)
  48084. return mappings.getUnchecked (i)->keypresses;
  48085. return Array <KeyPress> ();
  48086. }
  48087. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  48088. const KeyPress& newKeyPress,
  48089. int insertIndex)
  48090. {
  48091. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  48092. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  48093. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  48094. && ! newKeyPress.getModifiers().isShiftDown()));
  48095. if (findCommandForKeyPress (newKeyPress) != commandID)
  48096. {
  48097. removeKeyPress (newKeyPress);
  48098. if (newKeyPress.isValid())
  48099. {
  48100. for (int i = mappings.size(); --i >= 0;)
  48101. {
  48102. if (mappings.getUnchecked(i)->commandID == commandID)
  48103. {
  48104. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  48105. sendChangeMessage (this);
  48106. return;
  48107. }
  48108. }
  48109. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48110. if (ci != 0)
  48111. {
  48112. CommandMapping* const cm = new CommandMapping();
  48113. cm->commandID = commandID;
  48114. cm->keypresses.add (newKeyPress);
  48115. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  48116. mappings.add (cm);
  48117. sendChangeMessage (this);
  48118. }
  48119. }
  48120. }
  48121. }
  48122. void KeyPressMappingSet::resetToDefaultMappings()
  48123. {
  48124. mappings.clear();
  48125. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  48126. {
  48127. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  48128. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48129. {
  48130. addKeyPress (ci->commandID,
  48131. ci->defaultKeypresses.getReference (j));
  48132. }
  48133. }
  48134. sendChangeMessage (this);
  48135. }
  48136. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  48137. {
  48138. clearAllKeyPresses (commandID);
  48139. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48140. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48141. {
  48142. addKeyPress (ci->commandID,
  48143. ci->defaultKeypresses.getReference (j));
  48144. }
  48145. }
  48146. void KeyPressMappingSet::clearAllKeyPresses()
  48147. {
  48148. if (mappings.size() > 0)
  48149. {
  48150. sendChangeMessage (this);
  48151. mappings.clear();
  48152. }
  48153. }
  48154. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  48155. {
  48156. for (int i = mappings.size(); --i >= 0;)
  48157. {
  48158. if (mappings.getUnchecked(i)->commandID == commandID)
  48159. {
  48160. mappings.remove (i);
  48161. sendChangeMessage (this);
  48162. }
  48163. }
  48164. }
  48165. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  48166. {
  48167. if (keypress.isValid())
  48168. {
  48169. for (int i = mappings.size(); --i >= 0;)
  48170. {
  48171. CommandMapping* const cm = mappings.getUnchecked(i);
  48172. for (int j = cm->keypresses.size(); --j >= 0;)
  48173. {
  48174. if (keypress == cm->keypresses [j])
  48175. {
  48176. cm->keypresses.remove (j);
  48177. sendChangeMessage (this);
  48178. }
  48179. }
  48180. }
  48181. }
  48182. }
  48183. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  48184. {
  48185. for (int i = mappings.size(); --i >= 0;)
  48186. {
  48187. if (mappings.getUnchecked(i)->commandID == commandID)
  48188. {
  48189. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  48190. sendChangeMessage (this);
  48191. break;
  48192. }
  48193. }
  48194. }
  48195. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  48196. {
  48197. for (int i = 0; i < mappings.size(); ++i)
  48198. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  48199. return mappings.getUnchecked(i)->commandID;
  48200. return 0;
  48201. }
  48202. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  48203. {
  48204. for (int i = mappings.size(); --i >= 0;)
  48205. if (mappings.getUnchecked(i)->commandID == commandID)
  48206. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  48207. return false;
  48208. }
  48209. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  48210. const KeyPress& key,
  48211. const bool isKeyDown,
  48212. const int millisecsSinceKeyPressed,
  48213. Component* const originatingComponent) const
  48214. {
  48215. ApplicationCommandTarget::InvocationInfo info (commandID);
  48216. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  48217. info.isKeyDown = isKeyDown;
  48218. info.keyPress = key;
  48219. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  48220. info.originatingComponent = originatingComponent;
  48221. commandManager->invoke (info, false);
  48222. }
  48223. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  48224. {
  48225. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  48226. {
  48227. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  48228. {
  48229. // if the XML was created as a set of differences from the default mappings,
  48230. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  48231. resetToDefaultMappings();
  48232. }
  48233. else
  48234. {
  48235. // if the XML was created calling createXml (false), then we need to clear all
  48236. // the keys and treat the xml as describing the entire set of mappings.
  48237. clearAllKeyPresses();
  48238. }
  48239. forEachXmlChildElement (xmlVersion, map)
  48240. {
  48241. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  48242. if (commandId != 0)
  48243. {
  48244. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  48245. if (map->hasTagName ("MAPPING"))
  48246. {
  48247. addKeyPress (commandId, key);
  48248. }
  48249. else if (map->hasTagName ("UNMAPPING"))
  48250. {
  48251. if (containsMapping (commandId, key))
  48252. removeKeyPress (key);
  48253. }
  48254. }
  48255. }
  48256. return true;
  48257. }
  48258. return false;
  48259. }
  48260. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  48261. {
  48262. ScopedPointer <KeyPressMappingSet> defaultSet;
  48263. if (saveDifferencesFromDefaultSet)
  48264. {
  48265. defaultSet = new KeyPressMappingSet (commandManager);
  48266. defaultSet->resetToDefaultMappings();
  48267. }
  48268. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  48269. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  48270. int i;
  48271. for (i = 0; i < mappings.size(); ++i)
  48272. {
  48273. const CommandMapping* const cm = mappings.getUnchecked(i);
  48274. for (int j = 0; j < cm->keypresses.size(); ++j)
  48275. {
  48276. if (defaultSet == 0
  48277. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48278. {
  48279. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  48280. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48281. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48282. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48283. }
  48284. }
  48285. }
  48286. if (defaultSet != 0)
  48287. {
  48288. for (i = 0; i < defaultSet->mappings.size(); ++i)
  48289. {
  48290. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  48291. for (int j = 0; j < cm->keypresses.size(); ++j)
  48292. {
  48293. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48294. {
  48295. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  48296. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48297. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48298. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48299. }
  48300. }
  48301. }
  48302. }
  48303. return doc;
  48304. }
  48305. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  48306. Component* originatingComponent)
  48307. {
  48308. bool used = false;
  48309. const CommandID commandID = findCommandForKeyPress (key);
  48310. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48311. if (ci != 0
  48312. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  48313. {
  48314. ApplicationCommandInfo info (0);
  48315. if (commandManager->getTargetForCommand (commandID, info) != 0
  48316. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  48317. {
  48318. invokeCommand (commandID, key, true, 0, originatingComponent);
  48319. used = true;
  48320. }
  48321. else
  48322. {
  48323. if (originatingComponent != 0)
  48324. originatingComponent->getLookAndFeel().playAlertSound();
  48325. }
  48326. }
  48327. return used;
  48328. }
  48329. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  48330. {
  48331. bool used = false;
  48332. const uint32 now = Time::getMillisecondCounter();
  48333. for (int i = mappings.size(); --i >= 0;)
  48334. {
  48335. CommandMapping* const cm = mappings.getUnchecked(i);
  48336. if (cm->wantsKeyUpDownCallbacks)
  48337. {
  48338. for (int j = cm->keypresses.size(); --j >= 0;)
  48339. {
  48340. const KeyPress key (cm->keypresses.getReference (j));
  48341. const bool isDown = key.isCurrentlyDown();
  48342. int keyPressEntryIndex = 0;
  48343. bool wasDown = false;
  48344. for (int k = keysDown.size(); --k >= 0;)
  48345. {
  48346. if (key == keysDown.getUnchecked(k)->key)
  48347. {
  48348. keyPressEntryIndex = k;
  48349. wasDown = true;
  48350. used = true;
  48351. break;
  48352. }
  48353. }
  48354. if (isDown != wasDown)
  48355. {
  48356. int millisecs = 0;
  48357. if (isDown)
  48358. {
  48359. KeyPressTime* const k = new KeyPressTime();
  48360. k->key = key;
  48361. k->timeWhenPressed = now;
  48362. keysDown.add (k);
  48363. }
  48364. else
  48365. {
  48366. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  48367. if (now > pressTime)
  48368. millisecs = now - pressTime;
  48369. keysDown.remove (keyPressEntryIndex);
  48370. }
  48371. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  48372. used = true;
  48373. }
  48374. }
  48375. }
  48376. }
  48377. return used;
  48378. }
  48379. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  48380. {
  48381. if (focusedComponent != 0)
  48382. focusedComponent->keyStateChanged (false);
  48383. }
  48384. END_JUCE_NAMESPACE
  48385. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  48386. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  48387. BEGIN_JUCE_NAMESPACE
  48388. ModifierKeys::ModifierKeys (const int flags_) throw()
  48389. : flags (flags_)
  48390. {
  48391. }
  48392. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  48393. : flags (other.flags)
  48394. {
  48395. }
  48396. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  48397. {
  48398. flags = other.flags;
  48399. return *this;
  48400. }
  48401. ModifierKeys ModifierKeys::currentModifiers;
  48402. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  48403. {
  48404. return currentModifiers;
  48405. }
  48406. int ModifierKeys::getNumMouseButtonsDown() const throw()
  48407. {
  48408. int num = 0;
  48409. if (isLeftButtonDown()) ++num;
  48410. if (isRightButtonDown()) ++num;
  48411. if (isMiddleButtonDown()) ++num;
  48412. return num;
  48413. }
  48414. END_JUCE_NAMESPACE
  48415. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  48416. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  48417. BEGIN_JUCE_NAMESPACE
  48418. class ComponentAnimator::AnimationTask
  48419. {
  48420. public:
  48421. AnimationTask (Component* const comp)
  48422. : component (comp)
  48423. {
  48424. }
  48425. Component::SafePointer<Component> component;
  48426. Rectangle<int> destination;
  48427. int msElapsed, msTotal;
  48428. double startSpeed, midSpeed, endSpeed, lastProgress;
  48429. double left, top, right, bottom;
  48430. bool useTimeslice (const int elapsed)
  48431. {
  48432. if (component == 0)
  48433. return false;
  48434. msElapsed += elapsed;
  48435. double newProgress = msElapsed / (double) msTotal;
  48436. if (newProgress >= 0 && newProgress < 1.0)
  48437. {
  48438. newProgress = timeToDistance (newProgress);
  48439. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  48440. jassert (newProgress >= lastProgress);
  48441. lastProgress = newProgress;
  48442. left += (destination.getX() - left) * delta;
  48443. top += (destination.getY() - top) * delta;
  48444. right += (destination.getRight() - right) * delta;
  48445. bottom += (destination.getBottom() - bottom) * delta;
  48446. if (delta < 1.0)
  48447. {
  48448. const Rectangle<int> newBounds (roundToInt (left),
  48449. roundToInt (top),
  48450. roundToInt (right - left),
  48451. roundToInt (bottom - top));
  48452. if (newBounds != destination)
  48453. {
  48454. component->setBounds (newBounds);
  48455. return true;
  48456. }
  48457. }
  48458. }
  48459. component->setBounds (destination);
  48460. return false;
  48461. }
  48462. void moveToFinalDestination()
  48463. {
  48464. if (component != 0)
  48465. component->setBounds (destination);
  48466. }
  48467. private:
  48468. inline double timeToDistance (const double time) const
  48469. {
  48470. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  48471. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  48472. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  48473. }
  48474. };
  48475. ComponentAnimator::ComponentAnimator()
  48476. : lastTime (0)
  48477. {
  48478. }
  48479. ComponentAnimator::~ComponentAnimator()
  48480. {
  48481. cancelAllAnimations (false);
  48482. jassert (tasks.size() == 0);
  48483. }
  48484. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  48485. {
  48486. for (int i = tasks.size(); --i >= 0;)
  48487. if (component == tasks.getUnchecked(i)->component.getComponent())
  48488. return tasks.getUnchecked(i);
  48489. return 0;
  48490. }
  48491. void ComponentAnimator::animateComponent (Component* const component,
  48492. const Rectangle<int>& finalPosition,
  48493. const int millisecondsToSpendMoving,
  48494. const double startSpeed,
  48495. const double endSpeed)
  48496. {
  48497. if (component != 0)
  48498. {
  48499. AnimationTask* at = findTaskFor (component);
  48500. if (at == 0)
  48501. {
  48502. at = new AnimationTask (component);
  48503. tasks.add (at);
  48504. sendChangeMessage (this);
  48505. }
  48506. at->msElapsed = 0;
  48507. at->lastProgress = 0;
  48508. at->msTotal = jmax (1, millisecondsToSpendMoving);
  48509. at->destination = finalPosition;
  48510. // the speeds must be 0 or greater!
  48511. jassert (startSpeed >= 0 && endSpeed >= 0)
  48512. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  48513. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  48514. at->midSpeed = invTotalDistance;
  48515. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  48516. at->left = component->getX();
  48517. at->top = component->getY();
  48518. at->right = component->getRight();
  48519. at->bottom = component->getBottom();
  48520. if (! isTimerRunning())
  48521. {
  48522. lastTime = Time::getMillisecondCounter();
  48523. startTimer (1000 / 50);
  48524. }
  48525. }
  48526. }
  48527. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  48528. {
  48529. for (int i = tasks.size(); --i >= 0;)
  48530. {
  48531. AnimationTask* const at = tasks.getUnchecked(i);
  48532. if (moveComponentsToTheirFinalPositions)
  48533. at->moveToFinalDestination();
  48534. delete at;
  48535. tasks.remove (i);
  48536. sendChangeMessage (this);
  48537. }
  48538. }
  48539. void ComponentAnimator::cancelAnimation (Component* const component,
  48540. const bool moveComponentToItsFinalPosition)
  48541. {
  48542. AnimationTask* const at = findTaskFor (component);
  48543. if (at != 0)
  48544. {
  48545. if (moveComponentToItsFinalPosition)
  48546. at->moveToFinalDestination();
  48547. tasks.removeValue (at);
  48548. delete at;
  48549. sendChangeMessage (this);
  48550. }
  48551. }
  48552. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  48553. {
  48554. AnimationTask* const at = findTaskFor (component);
  48555. if (at != 0)
  48556. return at->destination;
  48557. else if (component != 0)
  48558. return component->getBounds();
  48559. return Rectangle<int>();
  48560. }
  48561. bool ComponentAnimator::isAnimating (Component* component) const
  48562. {
  48563. return findTaskFor (component) != 0;
  48564. }
  48565. void ComponentAnimator::timerCallback()
  48566. {
  48567. const uint32 timeNow = Time::getMillisecondCounter();
  48568. if (lastTime == 0 || lastTime == timeNow)
  48569. lastTime = timeNow;
  48570. const int elapsed = timeNow - lastTime;
  48571. for (int i = tasks.size(); --i >= 0;)
  48572. {
  48573. AnimationTask* const at = tasks.getUnchecked(i);
  48574. if (! at->useTimeslice (elapsed))
  48575. {
  48576. tasks.remove (i);
  48577. delete at;
  48578. sendChangeMessage (this);
  48579. }
  48580. }
  48581. lastTime = timeNow;
  48582. if (tasks.size() == 0)
  48583. stopTimer();
  48584. }
  48585. END_JUCE_NAMESPACE
  48586. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  48587. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  48588. BEGIN_JUCE_NAMESPACE
  48589. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  48590. : minW (0),
  48591. maxW (0x3fffffff),
  48592. minH (0),
  48593. maxH (0x3fffffff),
  48594. minOffTop (0),
  48595. minOffLeft (0),
  48596. minOffBottom (0),
  48597. minOffRight (0),
  48598. aspectRatio (0.0)
  48599. {
  48600. }
  48601. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  48602. {
  48603. }
  48604. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  48605. {
  48606. minW = minimumWidth;
  48607. }
  48608. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  48609. {
  48610. maxW = maximumWidth;
  48611. }
  48612. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  48613. {
  48614. minH = minimumHeight;
  48615. }
  48616. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  48617. {
  48618. maxH = maximumHeight;
  48619. }
  48620. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  48621. {
  48622. jassert (maxW >= minimumWidth);
  48623. jassert (maxH >= minimumHeight);
  48624. jassert (minimumWidth > 0 && minimumHeight > 0);
  48625. minW = minimumWidth;
  48626. minH = minimumHeight;
  48627. if (minW > maxW)
  48628. maxW = minW;
  48629. if (minH > maxH)
  48630. maxH = minH;
  48631. }
  48632. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  48633. {
  48634. jassert (maximumWidth >= minW);
  48635. jassert (maximumHeight >= minH);
  48636. jassert (maximumWidth > 0 && maximumHeight > 0);
  48637. maxW = jmax (minW, maximumWidth);
  48638. maxH = jmax (minH, maximumHeight);
  48639. }
  48640. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  48641. const int minimumHeight,
  48642. const int maximumWidth,
  48643. const int maximumHeight) throw()
  48644. {
  48645. jassert (maximumWidth >= minimumWidth);
  48646. jassert (maximumHeight >= minimumHeight);
  48647. jassert (maximumWidth > 0 && maximumHeight > 0);
  48648. jassert (minimumWidth > 0 && minimumHeight > 0);
  48649. minW = jmax (0, minimumWidth);
  48650. minH = jmax (0, minimumHeight);
  48651. maxW = jmax (minW, maximumWidth);
  48652. maxH = jmax (minH, maximumHeight);
  48653. }
  48654. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  48655. const int minimumWhenOffTheLeft,
  48656. const int minimumWhenOffTheBottom,
  48657. const int minimumWhenOffTheRight) throw()
  48658. {
  48659. minOffTop = minimumWhenOffTheTop;
  48660. minOffLeft = minimumWhenOffTheLeft;
  48661. minOffBottom = minimumWhenOffTheBottom;
  48662. minOffRight = minimumWhenOffTheRight;
  48663. }
  48664. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  48665. {
  48666. aspectRatio = jmax (0.0, widthOverHeight);
  48667. }
  48668. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  48669. {
  48670. return aspectRatio;
  48671. }
  48672. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  48673. const Rectangle<int>& targetBounds,
  48674. const bool isStretchingTop,
  48675. const bool isStretchingLeft,
  48676. const bool isStretchingBottom,
  48677. const bool isStretchingRight)
  48678. {
  48679. jassert (component != 0);
  48680. Rectangle<int> limits, bounds (targetBounds);
  48681. BorderSize border;
  48682. Component* const parent = component->getParentComponent();
  48683. if (parent == 0)
  48684. {
  48685. ComponentPeer* peer = component->getPeer();
  48686. if (peer != 0)
  48687. border = peer->getFrameSize();
  48688. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  48689. }
  48690. else
  48691. {
  48692. limits.setSize (parent->getWidth(), parent->getHeight());
  48693. }
  48694. border.addTo (bounds);
  48695. checkBounds (bounds,
  48696. border.addedTo (component->getBounds()), limits,
  48697. isStretchingTop, isStretchingLeft,
  48698. isStretchingBottom, isStretchingRight);
  48699. border.subtractFrom (bounds);
  48700. applyBoundsToComponent (component, bounds);
  48701. }
  48702. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  48703. {
  48704. setBoundsForComponent (component, component->getBounds(),
  48705. false, false, false, false);
  48706. }
  48707. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  48708. const Rectangle<int>& bounds)
  48709. {
  48710. component->setBounds (bounds);
  48711. }
  48712. void ComponentBoundsConstrainer::resizeStart()
  48713. {
  48714. }
  48715. void ComponentBoundsConstrainer::resizeEnd()
  48716. {
  48717. }
  48718. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  48719. const Rectangle<int>& old,
  48720. const Rectangle<int>& limits,
  48721. const bool isStretchingTop,
  48722. const bool isStretchingLeft,
  48723. const bool isStretchingBottom,
  48724. const bool isStretchingRight)
  48725. {
  48726. int x = bounds.getX();
  48727. int y = bounds.getY();
  48728. int w = bounds.getWidth();
  48729. int h = bounds.getHeight();
  48730. // constrain the size if it's being stretched..
  48731. if (isStretchingLeft)
  48732. {
  48733. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  48734. w = old.getRight() - x;
  48735. }
  48736. if (isStretchingRight)
  48737. {
  48738. w = jlimit (minW, maxW, w);
  48739. }
  48740. if (isStretchingTop)
  48741. {
  48742. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  48743. h = old.getBottom() - y;
  48744. }
  48745. if (isStretchingBottom)
  48746. {
  48747. h = jlimit (minH, maxH, h);
  48748. }
  48749. // constrain the aspect ratio if one has been specified..
  48750. if (aspectRatio > 0.0 && w > 0 && h > 0)
  48751. {
  48752. bool adjustWidth;
  48753. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  48754. {
  48755. adjustWidth = true;
  48756. }
  48757. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  48758. {
  48759. adjustWidth = false;
  48760. }
  48761. else
  48762. {
  48763. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  48764. const double newRatio = std::abs (w / (double) h);
  48765. adjustWidth = (oldRatio > newRatio);
  48766. }
  48767. if (adjustWidth)
  48768. {
  48769. w = roundToInt (h * aspectRatio);
  48770. if (w > maxW || w < minW)
  48771. {
  48772. w = jlimit (minW, maxW, w);
  48773. h = roundToInt (w / aspectRatio);
  48774. }
  48775. }
  48776. else
  48777. {
  48778. h = roundToInt (w / aspectRatio);
  48779. if (h > maxH || h < minH)
  48780. {
  48781. h = jlimit (minH, maxH, h);
  48782. w = roundToInt (h * aspectRatio);
  48783. }
  48784. }
  48785. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  48786. {
  48787. x = old.getX() + (old.getWidth() - w) / 2;
  48788. }
  48789. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  48790. {
  48791. y = old.getY() + (old.getHeight() - h) / 2;
  48792. }
  48793. else
  48794. {
  48795. if (isStretchingLeft)
  48796. x = old.getRight() - w;
  48797. if (isStretchingTop)
  48798. y = old.getBottom() - h;
  48799. }
  48800. }
  48801. // ...and constrain the position if limits have been set for that.
  48802. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  48803. {
  48804. if (minOffTop > 0)
  48805. {
  48806. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  48807. if (y < limit)
  48808. {
  48809. if (isStretchingTop)
  48810. h -= (limit - y);
  48811. y = limit;
  48812. }
  48813. }
  48814. if (minOffLeft > 0)
  48815. {
  48816. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  48817. if (x < limit)
  48818. {
  48819. if (isStretchingLeft)
  48820. w -= (limit - x);
  48821. x = limit;
  48822. }
  48823. }
  48824. if (minOffBottom > 0)
  48825. {
  48826. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  48827. if (y > limit)
  48828. {
  48829. if (isStretchingBottom)
  48830. h += (limit - y);
  48831. else
  48832. y = limit;
  48833. }
  48834. }
  48835. if (minOffRight > 0)
  48836. {
  48837. const int limit = limits.getRight() - jmin (minOffRight, w);
  48838. if (x > limit)
  48839. {
  48840. if (isStretchingRight)
  48841. w += (limit - x);
  48842. else
  48843. x = limit;
  48844. }
  48845. }
  48846. }
  48847. jassert (w >= 0 && h >= 0);
  48848. bounds = Rectangle<int> (x, y, w, h);
  48849. }
  48850. END_JUCE_NAMESPACE
  48851. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  48852. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  48853. BEGIN_JUCE_NAMESPACE
  48854. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  48855. : component (component_),
  48856. lastPeer (0),
  48857. reentrant (false)
  48858. {
  48859. jassert (component != 0); // can't use this with a null pointer..
  48860. component->addComponentListener (this);
  48861. registerWithParentComps();
  48862. }
  48863. ComponentMovementWatcher::~ComponentMovementWatcher()
  48864. {
  48865. component->removeComponentListener (this);
  48866. unregister();
  48867. }
  48868. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  48869. {
  48870. // agh! don't delete the target component without deleting this object first!
  48871. jassert (component != 0);
  48872. if (! reentrant)
  48873. {
  48874. reentrant = true;
  48875. ComponentPeer* const peer = component->getPeer();
  48876. if (peer != lastPeer)
  48877. {
  48878. componentPeerChanged();
  48879. if (component == 0)
  48880. return;
  48881. lastPeer = peer;
  48882. }
  48883. unregister();
  48884. registerWithParentComps();
  48885. reentrant = false;
  48886. componentMovedOrResized (*component, true, true);
  48887. }
  48888. }
  48889. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  48890. {
  48891. // agh! don't delete the target component without deleting this object first!
  48892. jassert (component != 0);
  48893. if (wasMoved)
  48894. {
  48895. const Point<int> pos (component->relativePositionToOtherComponent (component->getTopLevelComponent(), Point<int>()));
  48896. wasMoved = lastBounds.getPosition() != pos;
  48897. lastBounds.setPosition (pos);
  48898. }
  48899. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  48900. lastBounds.setSize (component->getWidth(), component->getHeight());
  48901. if (wasMoved || wasResized)
  48902. componentMovedOrResized (wasMoved, wasResized);
  48903. }
  48904. void ComponentMovementWatcher::registerWithParentComps() throw()
  48905. {
  48906. Component* p = component->getParentComponent();
  48907. while (p != 0)
  48908. {
  48909. p->addComponentListener (this);
  48910. registeredParentComps.add (p);
  48911. p = p->getParentComponent();
  48912. }
  48913. }
  48914. void ComponentMovementWatcher::unregister() throw()
  48915. {
  48916. for (int i = registeredParentComps.size(); --i >= 0;)
  48917. static_cast <Component*> (registeredParentComps.getUnchecked(i))->removeComponentListener (this);
  48918. registeredParentComps.clear();
  48919. }
  48920. END_JUCE_NAMESPACE
  48921. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  48922. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  48923. BEGIN_JUCE_NAMESPACE
  48924. GroupComponent::GroupComponent (const String& componentName,
  48925. const String& labelText)
  48926. : Component (componentName),
  48927. text (labelText),
  48928. justification (Justification::left)
  48929. {
  48930. setInterceptsMouseClicks (false, true);
  48931. }
  48932. GroupComponent::~GroupComponent()
  48933. {
  48934. }
  48935. void GroupComponent::setText (const String& newText)
  48936. {
  48937. if (text != newText)
  48938. {
  48939. text = newText;
  48940. repaint();
  48941. }
  48942. }
  48943. const String GroupComponent::getText() const
  48944. {
  48945. return text;
  48946. }
  48947. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  48948. {
  48949. if (justification.getFlags() != newJustification.getFlags())
  48950. {
  48951. justification = newJustification;
  48952. repaint();
  48953. }
  48954. }
  48955. void GroupComponent::paint (Graphics& g)
  48956. {
  48957. getLookAndFeel()
  48958. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  48959. text, justification,
  48960. *this);
  48961. }
  48962. void GroupComponent::enablementChanged()
  48963. {
  48964. repaint();
  48965. }
  48966. void GroupComponent::colourChanged()
  48967. {
  48968. repaint();
  48969. }
  48970. END_JUCE_NAMESPACE
  48971. /*** End of inlined file: juce_GroupComponent.cpp ***/
  48972. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  48973. BEGIN_JUCE_NAMESPACE
  48974. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  48975. : DocumentWindow (String::empty, backgroundColour,
  48976. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  48977. {
  48978. }
  48979. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  48980. {
  48981. }
  48982. void MultiDocumentPanelWindow::maximiseButtonPressed()
  48983. {
  48984. MultiDocumentPanel* const owner = getOwner();
  48985. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  48986. if (owner != 0)
  48987. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  48988. }
  48989. void MultiDocumentPanelWindow::closeButtonPressed()
  48990. {
  48991. MultiDocumentPanel* const owner = getOwner();
  48992. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  48993. if (owner != 0)
  48994. owner->closeDocument (getContentComponent(), true);
  48995. }
  48996. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  48997. {
  48998. DocumentWindow::activeWindowStatusChanged();
  48999. updateOrder();
  49000. }
  49001. void MultiDocumentPanelWindow::broughtToFront()
  49002. {
  49003. DocumentWindow::broughtToFront();
  49004. updateOrder();
  49005. }
  49006. void MultiDocumentPanelWindow::updateOrder()
  49007. {
  49008. MultiDocumentPanel* const owner = getOwner();
  49009. if (owner != 0)
  49010. owner->updateOrder();
  49011. }
  49012. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  49013. {
  49014. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49015. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49016. }
  49017. class MDITabbedComponentInternal : public TabbedComponent
  49018. {
  49019. public:
  49020. MDITabbedComponentInternal()
  49021. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  49022. {
  49023. }
  49024. ~MDITabbedComponentInternal()
  49025. {
  49026. }
  49027. void currentTabChanged (int, const String&)
  49028. {
  49029. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49030. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49031. if (owner != 0)
  49032. owner->updateOrder();
  49033. }
  49034. };
  49035. MultiDocumentPanel::MultiDocumentPanel()
  49036. : mode (MaximisedWindowsWithTabs),
  49037. tabComponent (0),
  49038. backgroundColour (Colours::lightblue),
  49039. maximumNumDocuments (0),
  49040. numDocsBeforeTabsUsed (0)
  49041. {
  49042. setOpaque (true);
  49043. }
  49044. MultiDocumentPanel::~MultiDocumentPanel()
  49045. {
  49046. closeAllDocuments (false);
  49047. }
  49048. static bool shouldDeleteComp (Component* const c)
  49049. {
  49050. return c->getProperties() ["mdiDocumentDelete_"];
  49051. }
  49052. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  49053. {
  49054. while (components.size() > 0)
  49055. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  49056. return false;
  49057. return true;
  49058. }
  49059. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  49060. {
  49061. return new MultiDocumentPanelWindow (backgroundColour);
  49062. }
  49063. void MultiDocumentPanel::addWindow (Component* component)
  49064. {
  49065. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  49066. dw->setResizable (true, false);
  49067. dw->setContentComponent (component, false, true);
  49068. dw->setName (component->getName());
  49069. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  49070. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  49071. int x = 4;
  49072. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  49073. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  49074. x += 16;
  49075. dw->setTopLeftPosition (x, x);
  49076. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  49077. if (pos.toString().isNotEmpty())
  49078. dw->restoreWindowStateFromString (pos.toString());
  49079. addAndMakeVisible (dw);
  49080. dw->toFront (true);
  49081. }
  49082. bool MultiDocumentPanel::addDocument (Component* const component,
  49083. const Colour& docColour,
  49084. const bool deleteWhenRemoved)
  49085. {
  49086. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  49087. // with a frame-within-a-frame! Just pass in the bare content component.
  49088. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  49089. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  49090. return false;
  49091. components.add (component);
  49092. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  49093. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  49094. component->addComponentListener (this);
  49095. if (mode == FloatingWindows)
  49096. {
  49097. if (isFullscreenWhenOneDocument())
  49098. {
  49099. if (components.size() == 1)
  49100. {
  49101. addAndMakeVisible (component);
  49102. }
  49103. else
  49104. {
  49105. if (components.size() == 2)
  49106. addWindow (components.getFirst());
  49107. addWindow (component);
  49108. }
  49109. }
  49110. else
  49111. {
  49112. addWindow (component);
  49113. }
  49114. }
  49115. else
  49116. {
  49117. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  49118. {
  49119. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  49120. Array <Component*> temp (components);
  49121. for (int i = 0; i < temp.size(); ++i)
  49122. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  49123. resized();
  49124. }
  49125. else
  49126. {
  49127. if (tabComponent != 0)
  49128. tabComponent->addTab (component->getName(), docColour, component, false);
  49129. else
  49130. addAndMakeVisible (component);
  49131. }
  49132. setActiveDocument (component);
  49133. }
  49134. resized();
  49135. activeDocumentChanged();
  49136. return true;
  49137. }
  49138. bool MultiDocumentPanel::closeDocument (Component* component,
  49139. const bool checkItsOkToCloseFirst)
  49140. {
  49141. if (components.contains (component))
  49142. {
  49143. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  49144. return false;
  49145. component->removeComponentListener (this);
  49146. const bool shouldDelete = shouldDeleteComp (component);
  49147. component->getProperties().remove ("mdiDocumentDelete_");
  49148. component->getProperties().remove ("mdiDocumentBkg_");
  49149. if (mode == FloatingWindows)
  49150. {
  49151. for (int i = getNumChildComponents(); --i >= 0;)
  49152. {
  49153. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49154. if (dw != 0 && dw->getContentComponent() == component)
  49155. {
  49156. dw->setContentComponent (0, false);
  49157. delete dw;
  49158. break;
  49159. }
  49160. }
  49161. if (shouldDelete)
  49162. delete component;
  49163. components.removeValue (component);
  49164. if (isFullscreenWhenOneDocument() && components.size() == 1)
  49165. {
  49166. for (int i = getNumChildComponents(); --i >= 0;)
  49167. {
  49168. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49169. if (dw != 0)
  49170. {
  49171. dw->setContentComponent (0, false);
  49172. delete dw;
  49173. }
  49174. }
  49175. addAndMakeVisible (components.getFirst());
  49176. }
  49177. }
  49178. else
  49179. {
  49180. jassert (components.indexOf (component) >= 0);
  49181. if (tabComponent != 0)
  49182. {
  49183. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49184. if (tabComponent->getTabContentComponent (i) == component)
  49185. tabComponent->removeTab (i);
  49186. }
  49187. else
  49188. {
  49189. removeChildComponent (component);
  49190. }
  49191. if (shouldDelete)
  49192. delete component;
  49193. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  49194. deleteAndZero (tabComponent);
  49195. components.removeValue (component);
  49196. if (components.size() > 0 && tabComponent == 0)
  49197. addAndMakeVisible (components.getFirst());
  49198. }
  49199. resized();
  49200. activeDocumentChanged();
  49201. }
  49202. else
  49203. {
  49204. jassertfalse
  49205. }
  49206. return true;
  49207. }
  49208. int MultiDocumentPanel::getNumDocuments() const throw()
  49209. {
  49210. return components.size();
  49211. }
  49212. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  49213. {
  49214. return components [index];
  49215. }
  49216. Component* MultiDocumentPanel::getActiveDocument() const throw()
  49217. {
  49218. if (mode == FloatingWindows)
  49219. {
  49220. for (int i = getNumChildComponents(); --i >= 0;)
  49221. {
  49222. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49223. if (dw != 0 && dw->isActiveWindow())
  49224. return dw->getContentComponent();
  49225. }
  49226. }
  49227. return components.getLast();
  49228. }
  49229. void MultiDocumentPanel::setActiveDocument (Component* component)
  49230. {
  49231. if (mode == FloatingWindows)
  49232. {
  49233. component = getContainerComp (component);
  49234. if (component != 0)
  49235. component->toFront (true);
  49236. }
  49237. else if (tabComponent != 0)
  49238. {
  49239. jassert (components.indexOf (component) >= 0);
  49240. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49241. {
  49242. if (tabComponent->getTabContentComponent (i) == component)
  49243. {
  49244. tabComponent->setCurrentTabIndex (i);
  49245. break;
  49246. }
  49247. }
  49248. }
  49249. else
  49250. {
  49251. component->grabKeyboardFocus();
  49252. }
  49253. }
  49254. void MultiDocumentPanel::activeDocumentChanged()
  49255. {
  49256. }
  49257. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  49258. {
  49259. maximumNumDocuments = newNumber;
  49260. }
  49261. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  49262. {
  49263. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  49264. }
  49265. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  49266. {
  49267. return numDocsBeforeTabsUsed != 0;
  49268. }
  49269. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  49270. {
  49271. if (mode != newLayoutMode)
  49272. {
  49273. mode = newLayoutMode;
  49274. if (mode == FloatingWindows)
  49275. {
  49276. deleteAndZero (tabComponent);
  49277. }
  49278. else
  49279. {
  49280. for (int i = getNumChildComponents(); --i >= 0;)
  49281. {
  49282. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49283. if (dw != 0)
  49284. {
  49285. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  49286. dw->setContentComponent (0, false);
  49287. delete dw;
  49288. }
  49289. }
  49290. }
  49291. resized();
  49292. const Array <Component*> tempComps (components);
  49293. components.clear();
  49294. for (int i = 0; i < tempComps.size(); ++i)
  49295. {
  49296. Component* const c = tempComps.getUnchecked(i);
  49297. addDocument (c,
  49298. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  49299. shouldDeleteComp (c));
  49300. }
  49301. }
  49302. }
  49303. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  49304. {
  49305. if (backgroundColour != newBackgroundColour)
  49306. {
  49307. backgroundColour = newBackgroundColour;
  49308. setOpaque (newBackgroundColour.isOpaque());
  49309. repaint();
  49310. }
  49311. }
  49312. void MultiDocumentPanel::paint (Graphics& g)
  49313. {
  49314. g.fillAll (backgroundColour);
  49315. }
  49316. void MultiDocumentPanel::resized()
  49317. {
  49318. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  49319. {
  49320. for (int i = getNumChildComponents(); --i >= 0;)
  49321. getChildComponent (i)->setBounds (0, 0, getWidth(), getHeight());
  49322. }
  49323. setWantsKeyboardFocus (components.size() == 0);
  49324. }
  49325. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  49326. {
  49327. if (mode == FloatingWindows)
  49328. {
  49329. for (int i = 0; i < getNumChildComponents(); ++i)
  49330. {
  49331. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49332. if (dw != 0 && dw->getContentComponent() == c)
  49333. {
  49334. c = dw;
  49335. break;
  49336. }
  49337. }
  49338. }
  49339. return c;
  49340. }
  49341. void MultiDocumentPanel::componentNameChanged (Component&)
  49342. {
  49343. if (mode == FloatingWindows)
  49344. {
  49345. for (int i = 0; i < getNumChildComponents(); ++i)
  49346. {
  49347. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49348. if (dw != 0)
  49349. dw->setName (dw->getContentComponent()->getName());
  49350. }
  49351. }
  49352. else if (tabComponent != 0)
  49353. {
  49354. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49355. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  49356. }
  49357. }
  49358. void MultiDocumentPanel::updateOrder()
  49359. {
  49360. const Array <Component*> oldList (components);
  49361. if (mode == FloatingWindows)
  49362. {
  49363. components.clear();
  49364. for (int i = 0; i < getNumChildComponents(); ++i)
  49365. {
  49366. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49367. if (dw != 0)
  49368. components.add (dw->getContentComponent());
  49369. }
  49370. }
  49371. else
  49372. {
  49373. if (tabComponent != 0)
  49374. {
  49375. Component* const current = tabComponent->getCurrentContentComponent();
  49376. if (current != 0)
  49377. {
  49378. components.removeValue (current);
  49379. components.add (current);
  49380. }
  49381. }
  49382. }
  49383. if (components != oldList)
  49384. activeDocumentChanged();
  49385. }
  49386. END_JUCE_NAMESPACE
  49387. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  49388. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  49389. BEGIN_JUCE_NAMESPACE
  49390. ResizableBorderComponent::Zone::Zone (int zoneFlags) throw()
  49391. : zone (zoneFlags)
  49392. {
  49393. }
  49394. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw() : zone (other.zone) {}
  49395. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw() { zone = other.zone; return *this; }
  49396. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  49397. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  49398. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  49399. const BorderSize& border,
  49400. const Point<int>& position)
  49401. {
  49402. int z = 0;
  49403. if (totalSize.contains (position)
  49404. && ! border.subtractedFrom (totalSize).contains (position))
  49405. {
  49406. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  49407. if (position.getX() < jmax (border.getLeft(), minW))
  49408. z |= left;
  49409. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW))
  49410. z |= right;
  49411. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  49412. if (position.getY() < jmax (border.getTop(), minH))
  49413. z |= top;
  49414. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH))
  49415. z |= bottom;
  49416. }
  49417. return Zone (z);
  49418. }
  49419. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  49420. {
  49421. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  49422. switch (zone)
  49423. {
  49424. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  49425. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  49426. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  49427. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  49428. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  49429. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  49430. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  49431. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  49432. default: break;
  49433. }
  49434. return mc;
  49435. }
  49436. const Rectangle<int> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<int> b, const Point<int>& offset) const throw()
  49437. {
  49438. if (isDraggingWholeObject())
  49439. return b + offset;
  49440. if (isDraggingLeftEdge())
  49441. b.setLeft (b.getX() + offset.getX());
  49442. if (isDraggingRightEdge())
  49443. b.setWidth (jmax (0, b.getWidth() + offset.getX()));
  49444. if (isDraggingTopEdge())
  49445. b.setTop (b.getY() + offset.getY());
  49446. if (isDraggingBottomEdge())
  49447. b.setHeight (jmax (0, b.getHeight() + offset.getY()));
  49448. return b;
  49449. }
  49450. const Rectangle<float> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<float> b, const Point<float>& offset) const throw()
  49451. {
  49452. if (isDraggingWholeObject())
  49453. return b + offset;
  49454. if (isDraggingLeftEdge())
  49455. b.setLeft (b.getX() + offset.getX());
  49456. if (isDraggingRightEdge())
  49457. b.setWidth (jmax (0.0f, b.getWidth() + offset.getX()));
  49458. if (isDraggingTopEdge())
  49459. b.setTop (b.getY() + offset.getY());
  49460. if (isDraggingBottomEdge())
  49461. b.setHeight (jmax (0.0f, b.getHeight() + offset.getY()));
  49462. return b;
  49463. }
  49464. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  49465. ComponentBoundsConstrainer* const constrainer_)
  49466. : component (componentToResize),
  49467. constrainer (constrainer_),
  49468. borderSize (5),
  49469. mouseZone (0)
  49470. {
  49471. }
  49472. ResizableBorderComponent::~ResizableBorderComponent()
  49473. {
  49474. }
  49475. void ResizableBorderComponent::paint (Graphics& g)
  49476. {
  49477. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  49478. }
  49479. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  49480. {
  49481. updateMouseZone (e);
  49482. }
  49483. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  49484. {
  49485. updateMouseZone (e);
  49486. }
  49487. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  49488. {
  49489. if (component == 0)
  49490. {
  49491. jassertfalse // You've deleted the component that this resizer was supposed to be using!
  49492. return;
  49493. }
  49494. updateMouseZone (e);
  49495. originalBounds = component->getBounds();
  49496. if (constrainer != 0)
  49497. constrainer->resizeStart();
  49498. }
  49499. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  49500. {
  49501. if (component == 0)
  49502. {
  49503. jassertfalse // You've deleted the component that this resizer was supposed to be using!
  49504. return;
  49505. }
  49506. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  49507. if (constrainer != 0)
  49508. constrainer->setBoundsForComponent (component, bounds,
  49509. mouseZone.isDraggingTopEdge(),
  49510. mouseZone.isDraggingLeftEdge(),
  49511. mouseZone.isDraggingBottomEdge(),
  49512. mouseZone.isDraggingRightEdge());
  49513. else
  49514. component->setBounds (bounds);
  49515. }
  49516. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  49517. {
  49518. if (constrainer != 0)
  49519. constrainer->resizeEnd();
  49520. }
  49521. bool ResizableBorderComponent::hitTest (int x, int y)
  49522. {
  49523. return x < borderSize.getLeft()
  49524. || x >= getWidth() - borderSize.getRight()
  49525. || y < borderSize.getTop()
  49526. || y >= getHeight() - borderSize.getBottom();
  49527. }
  49528. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize)
  49529. {
  49530. if (borderSize != newBorderSize)
  49531. {
  49532. borderSize = newBorderSize;
  49533. repaint();
  49534. }
  49535. }
  49536. const BorderSize ResizableBorderComponent::getBorderThickness() const
  49537. {
  49538. return borderSize;
  49539. }
  49540. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  49541. {
  49542. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  49543. if (mouseZone != newZone)
  49544. {
  49545. mouseZone = newZone;
  49546. setMouseCursor (newZone.getMouseCursor());
  49547. }
  49548. }
  49549. END_JUCE_NAMESPACE
  49550. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  49551. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  49552. BEGIN_JUCE_NAMESPACE
  49553. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  49554. ComponentBoundsConstrainer* const constrainer_)
  49555. : component (componentToResize),
  49556. constrainer (constrainer_)
  49557. {
  49558. setRepaintsOnMouseActivity (true);
  49559. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  49560. }
  49561. ResizableCornerComponent::~ResizableCornerComponent()
  49562. {
  49563. }
  49564. void ResizableCornerComponent::paint (Graphics& g)
  49565. {
  49566. getLookAndFeel()
  49567. .drawCornerResizer (g, getWidth(), getHeight(),
  49568. isMouseOverOrDragging(),
  49569. isMouseButtonDown());
  49570. }
  49571. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  49572. {
  49573. if (component == 0)
  49574. {
  49575. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  49576. return;
  49577. }
  49578. originalBounds = component->getBounds();
  49579. if (constrainer != 0)
  49580. constrainer->resizeStart();
  49581. }
  49582. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  49583. {
  49584. if (component == 0)
  49585. {
  49586. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  49587. return;
  49588. }
  49589. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  49590. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  49591. if (constrainer != 0)
  49592. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  49593. else
  49594. component->setBounds (r);
  49595. }
  49596. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  49597. {
  49598. if (constrainer != 0)
  49599. constrainer->resizeStart();
  49600. }
  49601. bool ResizableCornerComponent::hitTest (int x, int y)
  49602. {
  49603. if (getWidth() <= 0)
  49604. return false;
  49605. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  49606. return y >= yAtX - getHeight() / 4;
  49607. }
  49608. END_JUCE_NAMESPACE
  49609. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  49610. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  49611. BEGIN_JUCE_NAMESPACE
  49612. class ScrollBar::ScrollbarButton : public Button
  49613. {
  49614. public:
  49615. int direction;
  49616. ScrollbarButton (const int direction_, ScrollBar& owner_)
  49617. : Button (String::empty),
  49618. direction (direction_),
  49619. owner (owner_)
  49620. {
  49621. setWantsKeyboardFocus (false);
  49622. }
  49623. ~ScrollbarButton()
  49624. {
  49625. }
  49626. void paintButton (Graphics& g, bool over, bool down)
  49627. {
  49628. getLookAndFeel()
  49629. .drawScrollbarButton (g, owner,
  49630. getWidth(), getHeight(),
  49631. direction,
  49632. owner.isVertical(),
  49633. over, down);
  49634. }
  49635. void clicked()
  49636. {
  49637. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  49638. }
  49639. juce_UseDebuggingNewOperator
  49640. private:
  49641. ScrollBar& owner;
  49642. ScrollbarButton (const ScrollbarButton&);
  49643. ScrollbarButton& operator= (const ScrollbarButton&);
  49644. };
  49645. ScrollBar::ScrollBar (const bool vertical_,
  49646. const bool buttonsAreVisible)
  49647. : totalRange (0.0, 1.0),
  49648. visibleRange (0.0, 0.1),
  49649. singleStepSize (0.1),
  49650. thumbAreaStart (0),
  49651. thumbAreaSize (0),
  49652. thumbStart (0),
  49653. thumbSize (0),
  49654. initialDelayInMillisecs (100),
  49655. repeatDelayInMillisecs (50),
  49656. minimumDelayInMillisecs (10),
  49657. vertical (vertical_),
  49658. isDraggingThumb (false),
  49659. autohides (true),
  49660. upButton (0),
  49661. downButton (0)
  49662. {
  49663. setButtonVisibility (buttonsAreVisible);
  49664. setRepaintsOnMouseActivity (true);
  49665. setFocusContainer (true);
  49666. }
  49667. ScrollBar::~ScrollBar()
  49668. {
  49669. deleteAllChildren();
  49670. }
  49671. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  49672. {
  49673. if (totalRange != newRangeLimit)
  49674. {
  49675. totalRange = newRangeLimit;
  49676. setCurrentRange (visibleRange);
  49677. updateThumbPosition();
  49678. }
  49679. }
  49680. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  49681. {
  49682. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  49683. setRangeLimits (Range<double> (newMinimum, newMaximum));
  49684. }
  49685. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  49686. {
  49687. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  49688. if (visibleRange != constrainedRange)
  49689. {
  49690. visibleRange = constrainedRange;
  49691. updateThumbPosition();
  49692. triggerAsyncUpdate();
  49693. }
  49694. }
  49695. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  49696. {
  49697. setCurrentRange (Range<double> (newStart, newStart + newSize));
  49698. }
  49699. void ScrollBar::setCurrentRangeStart (const double newStart)
  49700. {
  49701. setCurrentRange (visibleRange.movedToStartAt (newStart));
  49702. }
  49703. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  49704. {
  49705. singleStepSize = newSingleStepSize;
  49706. }
  49707. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  49708. {
  49709. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  49710. }
  49711. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  49712. {
  49713. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  49714. }
  49715. void ScrollBar::scrollToTop()
  49716. {
  49717. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  49718. }
  49719. void ScrollBar::scrollToBottom()
  49720. {
  49721. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  49722. }
  49723. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  49724. const int repeatDelayInMillisecs_,
  49725. const int minimumDelayInMillisecs_)
  49726. {
  49727. initialDelayInMillisecs = initialDelayInMillisecs_;
  49728. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  49729. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  49730. if (upButton != 0)
  49731. {
  49732. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  49733. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  49734. }
  49735. }
  49736. void ScrollBar::addListener (ScrollBarListener* const listener)
  49737. {
  49738. listeners.add (listener);
  49739. }
  49740. void ScrollBar::removeListener (ScrollBarListener* const listener)
  49741. {
  49742. listeners.remove (listener);
  49743. }
  49744. void ScrollBar::handleAsyncUpdate()
  49745. {
  49746. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  49747. listeners.call (&ScrollBarListener::scrollBarMoved, this, start);
  49748. }
  49749. void ScrollBar::updateThumbPosition()
  49750. {
  49751. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  49752. : thumbAreaSize);
  49753. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  49754. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  49755. if (newThumbSize > thumbAreaSize)
  49756. newThumbSize = thumbAreaSize;
  49757. int newThumbStart = thumbAreaStart;
  49758. if (totalRange.getLength() > visibleRange.getLength())
  49759. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  49760. / (totalRange.getLength() - visibleRange.getLength()));
  49761. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  49762. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  49763. {
  49764. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  49765. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  49766. if (vertical)
  49767. repaint (0, repaintStart, getWidth(), repaintSize);
  49768. else
  49769. repaint (repaintStart, 0, repaintSize, getHeight());
  49770. thumbStart = newThumbStart;
  49771. thumbSize = newThumbSize;
  49772. }
  49773. }
  49774. void ScrollBar::setOrientation (const bool shouldBeVertical)
  49775. {
  49776. if (vertical != shouldBeVertical)
  49777. {
  49778. vertical = shouldBeVertical;
  49779. if (upButton != 0)
  49780. {
  49781. upButton->direction = vertical ? 0 : 3;
  49782. downButton->direction = vertical ? 2 : 1;
  49783. }
  49784. updateThumbPosition();
  49785. }
  49786. }
  49787. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  49788. {
  49789. delete upButton;
  49790. upButton = 0;
  49791. delete downButton;
  49792. downButton = 0;
  49793. if (buttonsAreVisible)
  49794. {
  49795. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  49796. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  49797. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  49798. }
  49799. updateThumbPosition();
  49800. }
  49801. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  49802. {
  49803. autohides = shouldHideWhenFullRange;
  49804. updateThumbPosition();
  49805. }
  49806. bool ScrollBar::autoHides() const throw()
  49807. {
  49808. return autohides;
  49809. }
  49810. void ScrollBar::paint (Graphics& g)
  49811. {
  49812. if (thumbAreaSize > 0)
  49813. {
  49814. LookAndFeel& lf = getLookAndFeel();
  49815. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  49816. ? thumbSize : 0;
  49817. if (vertical)
  49818. {
  49819. lf.drawScrollbar (g, *this,
  49820. 0, thumbAreaStart,
  49821. getWidth(), thumbAreaSize,
  49822. vertical,
  49823. thumbStart, thumb,
  49824. isMouseOver(), isMouseButtonDown());
  49825. }
  49826. else
  49827. {
  49828. lf.drawScrollbar (g, *this,
  49829. thumbAreaStart, 0,
  49830. thumbAreaSize, getHeight(),
  49831. vertical,
  49832. thumbStart, thumb,
  49833. isMouseOver(), isMouseButtonDown());
  49834. }
  49835. }
  49836. }
  49837. void ScrollBar::lookAndFeelChanged()
  49838. {
  49839. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  49840. }
  49841. void ScrollBar::resized()
  49842. {
  49843. const int length = ((vertical) ? getHeight() : getWidth());
  49844. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  49845. : 0;
  49846. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  49847. {
  49848. thumbAreaStart = length >> 1;
  49849. thumbAreaSize = 0;
  49850. }
  49851. else
  49852. {
  49853. thumbAreaStart = buttonSize;
  49854. thumbAreaSize = length - (buttonSize << 1);
  49855. }
  49856. if (upButton != 0)
  49857. {
  49858. if (vertical)
  49859. {
  49860. upButton->setBounds (0, 0, getWidth(), buttonSize);
  49861. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  49862. }
  49863. else
  49864. {
  49865. upButton->setBounds (0, 0, buttonSize, getHeight());
  49866. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  49867. }
  49868. }
  49869. updateThumbPosition();
  49870. }
  49871. void ScrollBar::mouseDown (const MouseEvent& e)
  49872. {
  49873. isDraggingThumb = false;
  49874. lastMousePos = vertical ? e.y : e.x;
  49875. dragStartMousePos = lastMousePos;
  49876. dragStartRange = visibleRange.getStart();
  49877. if (dragStartMousePos < thumbStart)
  49878. {
  49879. moveScrollbarInPages (-1);
  49880. startTimer (400);
  49881. }
  49882. else if (dragStartMousePos >= thumbStart + thumbSize)
  49883. {
  49884. moveScrollbarInPages (1);
  49885. startTimer (400);
  49886. }
  49887. else
  49888. {
  49889. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  49890. && (thumbAreaSize > thumbSize);
  49891. }
  49892. }
  49893. void ScrollBar::mouseDrag (const MouseEvent& e)
  49894. {
  49895. if (isDraggingThumb)
  49896. {
  49897. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  49898. setCurrentRangeStart (dragStartRange
  49899. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  49900. / (thumbAreaSize - thumbSize));
  49901. }
  49902. else
  49903. {
  49904. lastMousePos = (vertical) ? e.y : e.x;
  49905. }
  49906. }
  49907. void ScrollBar::mouseUp (const MouseEvent&)
  49908. {
  49909. isDraggingThumb = false;
  49910. stopTimer();
  49911. repaint();
  49912. }
  49913. void ScrollBar::mouseWheelMove (const MouseEvent&,
  49914. float wheelIncrementX,
  49915. float wheelIncrementY)
  49916. {
  49917. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  49918. if (increment < 0)
  49919. increment = jmin (increment * 10.0f, -1.0f);
  49920. else if (increment > 0)
  49921. increment = jmax (increment * 10.0f, 1.0f);
  49922. setCurrentRange (visibleRange - singleStepSize * increment);
  49923. }
  49924. void ScrollBar::timerCallback()
  49925. {
  49926. if (isMouseButtonDown())
  49927. {
  49928. startTimer (40);
  49929. if (lastMousePos < thumbStart)
  49930. setCurrentRange (visibleRange - visibleRange.getLength());
  49931. else if (lastMousePos > thumbStart + thumbSize)
  49932. setCurrentRangeStart (visibleRange.getEnd());
  49933. }
  49934. else
  49935. {
  49936. stopTimer();
  49937. }
  49938. }
  49939. bool ScrollBar::keyPressed (const KeyPress& key)
  49940. {
  49941. if (! isVisible())
  49942. return false;
  49943. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  49944. moveScrollbarInSteps (-1);
  49945. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  49946. moveScrollbarInSteps (1);
  49947. else if (key.isKeyCode (KeyPress::pageUpKey))
  49948. moveScrollbarInPages (-1);
  49949. else if (key.isKeyCode (KeyPress::pageDownKey))
  49950. moveScrollbarInPages (1);
  49951. else if (key.isKeyCode (KeyPress::homeKey))
  49952. scrollToTop();
  49953. else if (key.isKeyCode (KeyPress::endKey))
  49954. scrollToBottom();
  49955. else
  49956. return false;
  49957. return true;
  49958. }
  49959. END_JUCE_NAMESPACE
  49960. /*** End of inlined file: juce_ScrollBar.cpp ***/
  49961. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  49962. BEGIN_JUCE_NAMESPACE
  49963. StretchableLayoutManager::StretchableLayoutManager()
  49964. : totalSize (0)
  49965. {
  49966. }
  49967. StretchableLayoutManager::~StretchableLayoutManager()
  49968. {
  49969. }
  49970. void StretchableLayoutManager::clearAllItems()
  49971. {
  49972. items.clear();
  49973. totalSize = 0;
  49974. }
  49975. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  49976. const double minimumSize,
  49977. const double maximumSize,
  49978. const double preferredSize)
  49979. {
  49980. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  49981. if (layout == 0)
  49982. {
  49983. layout = new ItemLayoutProperties();
  49984. layout->itemIndex = itemIndex;
  49985. int i;
  49986. for (i = 0; i < items.size(); ++i)
  49987. if (items.getUnchecked (i)->itemIndex > itemIndex)
  49988. break;
  49989. items.insert (i, layout);
  49990. }
  49991. layout->minSize = minimumSize;
  49992. layout->maxSize = maximumSize;
  49993. layout->preferredSize = preferredSize;
  49994. layout->currentSize = 0;
  49995. }
  49996. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  49997. double& minimumSize,
  49998. double& maximumSize,
  49999. double& preferredSize) const
  50000. {
  50001. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50002. if (layout != 0)
  50003. {
  50004. minimumSize = layout->minSize;
  50005. maximumSize = layout->maxSize;
  50006. preferredSize = layout->preferredSize;
  50007. return true;
  50008. }
  50009. return false;
  50010. }
  50011. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  50012. {
  50013. totalSize = newTotalSize;
  50014. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  50015. }
  50016. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  50017. {
  50018. int pos = 0;
  50019. for (int i = 0; i < itemIndex; ++i)
  50020. {
  50021. const ItemLayoutProperties* const layout = getInfoFor (i);
  50022. if (layout != 0)
  50023. pos += layout->currentSize;
  50024. }
  50025. return pos;
  50026. }
  50027. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  50028. {
  50029. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50030. if (layout != 0)
  50031. return layout->currentSize;
  50032. return 0;
  50033. }
  50034. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  50035. {
  50036. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50037. if (layout != 0)
  50038. return -layout->currentSize / (double) totalSize;
  50039. return 0;
  50040. }
  50041. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  50042. int newPosition)
  50043. {
  50044. for (int i = items.size(); --i >= 0;)
  50045. {
  50046. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  50047. if (layout->itemIndex == itemIndex)
  50048. {
  50049. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  50050. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  50051. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  50052. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  50053. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  50054. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  50055. endPos += layout->currentSize;
  50056. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  50057. updatePrefSizesToMatchCurrentPositions();
  50058. break;
  50059. }
  50060. }
  50061. }
  50062. void StretchableLayoutManager::layOutComponents (Component** const components,
  50063. int numComponents,
  50064. int x, int y, int w, int h,
  50065. const bool vertically,
  50066. const bool resizeOtherDimension)
  50067. {
  50068. setTotalSize (vertically ? h : w);
  50069. int pos = vertically ? y : x;
  50070. for (int i = 0; i < numComponents; ++i)
  50071. {
  50072. const ItemLayoutProperties* const layout = getInfoFor (i);
  50073. if (layout != 0)
  50074. {
  50075. Component* const c = components[i];
  50076. if (c != 0)
  50077. {
  50078. if (i == numComponents - 1)
  50079. {
  50080. // if it's the last item, crop it to exactly fit the available space..
  50081. if (resizeOtherDimension)
  50082. {
  50083. if (vertically)
  50084. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  50085. else
  50086. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  50087. }
  50088. else
  50089. {
  50090. if (vertically)
  50091. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  50092. else
  50093. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  50094. }
  50095. }
  50096. else
  50097. {
  50098. if (resizeOtherDimension)
  50099. {
  50100. if (vertically)
  50101. c->setBounds (x, pos, w, layout->currentSize);
  50102. else
  50103. c->setBounds (pos, y, layout->currentSize, h);
  50104. }
  50105. else
  50106. {
  50107. if (vertically)
  50108. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  50109. else
  50110. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  50111. }
  50112. }
  50113. }
  50114. pos += layout->currentSize;
  50115. }
  50116. }
  50117. }
  50118. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  50119. {
  50120. for (int i = items.size(); --i >= 0;)
  50121. if (items.getUnchecked(i)->itemIndex == itemIndex)
  50122. return items.getUnchecked(i);
  50123. return 0;
  50124. }
  50125. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  50126. const int endIndex,
  50127. const int availableSpace,
  50128. int startPos)
  50129. {
  50130. // calculate the total sizes
  50131. int i;
  50132. double totalIdealSize = 0.0;
  50133. int totalMinimums = 0;
  50134. for (i = startIndex; i < endIndex; ++i)
  50135. {
  50136. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50137. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  50138. totalMinimums += layout->currentSize;
  50139. totalIdealSize += sizeToRealSize (layout->preferredSize, availableSpace);
  50140. }
  50141. if (totalIdealSize <= 0)
  50142. totalIdealSize = 1.0;
  50143. // now calc the best sizes..
  50144. int extraSpace = availableSpace - totalMinimums;
  50145. while (extraSpace > 0)
  50146. {
  50147. int numWantingMoreSpace = 0;
  50148. int numHavingTakenExtraSpace = 0;
  50149. // first figure out how many comps want a slice of the extra space..
  50150. for (i = startIndex; i < endIndex; ++i)
  50151. {
  50152. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50153. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  50154. const int bestSize = jlimit (layout->currentSize,
  50155. jmax (layout->currentSize,
  50156. sizeToRealSize (layout->maxSize, totalSize)),
  50157. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  50158. if (bestSize > layout->currentSize)
  50159. ++numWantingMoreSpace;
  50160. }
  50161. // ..share out the extra space..
  50162. for (i = startIndex; i < endIndex; ++i)
  50163. {
  50164. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50165. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  50166. int bestSize = jlimit (layout->currentSize,
  50167. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  50168. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  50169. const int extraWanted = bestSize - layout->currentSize;
  50170. if (extraWanted > 0)
  50171. {
  50172. const int extraAllowed = jmin (extraWanted,
  50173. extraSpace / jmax (1, numWantingMoreSpace));
  50174. if (extraAllowed > 0)
  50175. {
  50176. ++numHavingTakenExtraSpace;
  50177. --numWantingMoreSpace;
  50178. layout->currentSize += extraAllowed;
  50179. extraSpace -= extraAllowed;
  50180. }
  50181. }
  50182. }
  50183. if (numHavingTakenExtraSpace <= 0)
  50184. break;
  50185. }
  50186. // ..and calculate the end position
  50187. for (i = startIndex; i < endIndex; ++i)
  50188. {
  50189. ItemLayoutProperties* const layout = items.getUnchecked(i);
  50190. startPos += layout->currentSize;
  50191. }
  50192. return startPos;
  50193. }
  50194. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  50195. const int endIndex) const
  50196. {
  50197. int totalMinimums = 0;
  50198. for (int i = startIndex; i < endIndex; ++i)
  50199. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  50200. return totalMinimums;
  50201. }
  50202. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  50203. {
  50204. int totalMaximums = 0;
  50205. for (int i = startIndex; i < endIndex; ++i)
  50206. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  50207. return totalMaximums;
  50208. }
  50209. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  50210. {
  50211. for (int i = 0; i < items.size(); ++i)
  50212. {
  50213. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50214. layout->preferredSize
  50215. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  50216. : getItemCurrentAbsoluteSize (i);
  50217. }
  50218. }
  50219. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  50220. {
  50221. if (size < 0)
  50222. size *= -totalSpace;
  50223. return roundToInt (size);
  50224. }
  50225. END_JUCE_NAMESPACE
  50226. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  50227. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  50228. BEGIN_JUCE_NAMESPACE
  50229. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  50230. const int itemIndex_,
  50231. const bool isVertical_)
  50232. : layout (layout_),
  50233. itemIndex (itemIndex_),
  50234. isVertical (isVertical_)
  50235. {
  50236. setRepaintsOnMouseActivity (true);
  50237. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  50238. : MouseCursor::UpDownResizeCursor));
  50239. }
  50240. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  50241. {
  50242. }
  50243. void StretchableLayoutResizerBar::paint (Graphics& g)
  50244. {
  50245. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  50246. getWidth(), getHeight(),
  50247. isVertical,
  50248. isMouseOver(),
  50249. isMouseButtonDown());
  50250. }
  50251. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  50252. {
  50253. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  50254. }
  50255. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  50256. {
  50257. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  50258. : e.getDistanceFromDragStartY());
  50259. layout->setItemPosition (itemIndex, desiredPos);
  50260. hasBeenMoved();
  50261. }
  50262. void StretchableLayoutResizerBar::hasBeenMoved()
  50263. {
  50264. if (getParentComponent() != 0)
  50265. getParentComponent()->resized();
  50266. }
  50267. END_JUCE_NAMESPACE
  50268. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  50269. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  50270. BEGIN_JUCE_NAMESPACE
  50271. StretchableObjectResizer::StretchableObjectResizer()
  50272. {
  50273. }
  50274. StretchableObjectResizer::~StretchableObjectResizer()
  50275. {
  50276. }
  50277. void StretchableObjectResizer::addItem (const double size,
  50278. const double minSize, const double maxSize,
  50279. const int order)
  50280. {
  50281. // the order must be >= 0 but less than the maximum integer value.
  50282. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  50283. Item* const item = new Item();
  50284. item->size = size;
  50285. item->minSize = minSize;
  50286. item->maxSize = maxSize;
  50287. item->order = order;
  50288. items.add (item);
  50289. }
  50290. double StretchableObjectResizer::getItemSize (const int index) const throw()
  50291. {
  50292. const Item* const it = items [index];
  50293. return it != 0 ? it->size : 0;
  50294. }
  50295. void StretchableObjectResizer::resizeToFit (const double targetSize)
  50296. {
  50297. int order = 0;
  50298. for (;;)
  50299. {
  50300. double currentSize = 0;
  50301. double minSize = 0;
  50302. double maxSize = 0;
  50303. int nextHighestOrder = std::numeric_limits<int>::max();
  50304. for (int i = 0; i < items.size(); ++i)
  50305. {
  50306. const Item* const it = items.getUnchecked(i);
  50307. currentSize += it->size;
  50308. if (it->order <= order)
  50309. {
  50310. minSize += it->minSize;
  50311. maxSize += it->maxSize;
  50312. }
  50313. else
  50314. {
  50315. minSize += it->size;
  50316. maxSize += it->size;
  50317. nextHighestOrder = jmin (nextHighestOrder, it->order);
  50318. }
  50319. }
  50320. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  50321. if (thisIterationTarget >= currentSize)
  50322. {
  50323. const double availableExtraSpace = maxSize - currentSize;
  50324. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  50325. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  50326. for (int i = 0; i < items.size(); ++i)
  50327. {
  50328. Item* const it = items.getUnchecked(i);
  50329. if (it->order <= order)
  50330. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  50331. }
  50332. }
  50333. else
  50334. {
  50335. const double amountOfSlack = currentSize - minSize;
  50336. const double targetAmountOfSlack = thisIterationTarget - minSize;
  50337. const double scale = targetAmountOfSlack / amountOfSlack;
  50338. for (int i = 0; i < items.size(); ++i)
  50339. {
  50340. Item* const it = items.getUnchecked(i);
  50341. if (it->order <= order)
  50342. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  50343. }
  50344. }
  50345. if (nextHighestOrder < std::numeric_limits<int>::max())
  50346. order = nextHighestOrder;
  50347. else
  50348. break;
  50349. }
  50350. }
  50351. END_JUCE_NAMESPACE
  50352. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  50353. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  50354. BEGIN_JUCE_NAMESPACE
  50355. TabBarButton::TabBarButton (const String& name,
  50356. TabbedButtonBar* const owner_,
  50357. const int index)
  50358. : Button (name),
  50359. owner (owner_),
  50360. tabIndex (index),
  50361. overlapPixels (0)
  50362. {
  50363. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  50364. setComponentEffect (&shadow);
  50365. setWantsKeyboardFocus (false);
  50366. }
  50367. TabBarButton::~TabBarButton()
  50368. {
  50369. }
  50370. void TabBarButton::paintButton (Graphics& g,
  50371. bool isMouseOverButton,
  50372. bool isButtonDown)
  50373. {
  50374. int x, y, w, h;
  50375. getActiveArea (x, y, w, h);
  50376. g.setOrigin (x, y);
  50377. getLookAndFeel()
  50378. .drawTabButton (g, w, h,
  50379. owner->getTabBackgroundColour (tabIndex),
  50380. tabIndex, getButtonText(), *this,
  50381. owner->getOrientation(),
  50382. isMouseOverButton, isButtonDown,
  50383. getToggleState());
  50384. }
  50385. void TabBarButton::clicked (const ModifierKeys& mods)
  50386. {
  50387. if (mods.isPopupMenu())
  50388. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  50389. else
  50390. owner->setCurrentTabIndex (tabIndex);
  50391. }
  50392. bool TabBarButton::hitTest (int mx, int my)
  50393. {
  50394. int x, y, w, h;
  50395. getActiveArea (x, y, w, h);
  50396. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  50397. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  50398. {
  50399. if (((unsigned int) mx) < (unsigned int) getWidth()
  50400. && my >= y + overlapPixels
  50401. && my < y + h - overlapPixels)
  50402. return true;
  50403. }
  50404. else
  50405. {
  50406. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  50407. && ((unsigned int) my) < (unsigned int) getHeight())
  50408. return true;
  50409. }
  50410. Path p;
  50411. getLookAndFeel()
  50412. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  50413. owner->getOrientation(),
  50414. false, false, getToggleState());
  50415. return p.contains ((float) (mx - x),
  50416. (float) (my - y));
  50417. }
  50418. int TabBarButton::getBestTabLength (const int depth)
  50419. {
  50420. return jlimit (depth * 2,
  50421. depth * 7,
  50422. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  50423. }
  50424. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  50425. {
  50426. x = 0;
  50427. y = 0;
  50428. int r = getWidth();
  50429. int b = getHeight();
  50430. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  50431. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  50432. r -= spaceAroundImage;
  50433. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  50434. x += spaceAroundImage;
  50435. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  50436. y += spaceAroundImage;
  50437. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  50438. b -= spaceAroundImage;
  50439. w = r - x;
  50440. h = b - y;
  50441. }
  50442. class TabAreaBehindFrontButtonComponent : public Component
  50443. {
  50444. public:
  50445. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  50446. : owner (owner_)
  50447. {
  50448. setInterceptsMouseClicks (false, false);
  50449. }
  50450. ~TabAreaBehindFrontButtonComponent()
  50451. {
  50452. }
  50453. void paint (Graphics& g)
  50454. {
  50455. getLookAndFeel()
  50456. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  50457. *owner, owner->getOrientation());
  50458. }
  50459. void enablementChanged()
  50460. {
  50461. repaint();
  50462. }
  50463. private:
  50464. TabbedButtonBar* const owner;
  50465. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  50466. TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  50467. };
  50468. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  50469. : orientation (orientation_),
  50470. currentTabIndex (-1),
  50471. extraTabsButton (0)
  50472. {
  50473. setInterceptsMouseClicks (false, true);
  50474. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  50475. setFocusContainer (true);
  50476. }
  50477. TabbedButtonBar::~TabbedButtonBar()
  50478. {
  50479. deleteAllChildren();
  50480. }
  50481. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  50482. {
  50483. orientation = newOrientation;
  50484. for (int i = getNumChildComponents(); --i >= 0;)
  50485. getChildComponent (i)->resized();
  50486. resized();
  50487. }
  50488. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  50489. {
  50490. return new TabBarButton (name, this, index);
  50491. }
  50492. void TabbedButtonBar::clearTabs()
  50493. {
  50494. tabs.clear();
  50495. tabColours.clear();
  50496. currentTabIndex = -1;
  50497. deleteAndZero (extraTabsButton);
  50498. removeChildComponent (behindFrontTab);
  50499. deleteAllChildren();
  50500. addChildComponent (behindFrontTab);
  50501. setCurrentTabIndex (-1);
  50502. }
  50503. void TabbedButtonBar::addTab (const String& tabName,
  50504. const Colour& tabBackgroundColour,
  50505. int insertIndex)
  50506. {
  50507. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  50508. if (tabName.isNotEmpty())
  50509. {
  50510. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  50511. insertIndex = tabs.size();
  50512. for (int i = tabs.size(); --i >= insertIndex;)
  50513. {
  50514. TabBarButton* const tb = getTabButton (i);
  50515. if (tb != 0)
  50516. tb->tabIndex++;
  50517. }
  50518. tabs.insert (insertIndex, tabName);
  50519. tabColours.insert (insertIndex, tabBackgroundColour);
  50520. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  50521. jassert (tb != 0); // your createTabButton() mustn't return zero!
  50522. addAndMakeVisible (tb, insertIndex);
  50523. resized();
  50524. if (currentTabIndex < 0)
  50525. setCurrentTabIndex (0);
  50526. }
  50527. }
  50528. void TabbedButtonBar::setTabName (const int tabIndex,
  50529. const String& newName)
  50530. {
  50531. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  50532. && tabs[tabIndex] != newName)
  50533. {
  50534. tabs.set (tabIndex, newName);
  50535. TabBarButton* const tb = getTabButton (tabIndex);
  50536. if (tb != 0)
  50537. tb->setButtonText (newName);
  50538. resized();
  50539. }
  50540. }
  50541. void TabbedButtonBar::removeTab (const int tabIndex)
  50542. {
  50543. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  50544. {
  50545. const int oldTabIndex = currentTabIndex;
  50546. if (currentTabIndex == tabIndex)
  50547. currentTabIndex = -1;
  50548. tabs.remove (tabIndex);
  50549. tabColours.remove (tabIndex);
  50550. delete getTabButton (tabIndex);
  50551. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  50552. {
  50553. TabBarButton* const tb = getTabButton (i);
  50554. if (tb != 0)
  50555. tb->tabIndex--;
  50556. }
  50557. resized();
  50558. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  50559. }
  50560. }
  50561. void TabbedButtonBar::moveTab (const int currentIndex,
  50562. const int newIndex)
  50563. {
  50564. tabs.move (currentIndex, newIndex);
  50565. tabColours.move (currentIndex, newIndex);
  50566. resized();
  50567. }
  50568. int TabbedButtonBar::getNumTabs() const
  50569. {
  50570. return tabs.size();
  50571. }
  50572. const StringArray TabbedButtonBar::getTabNames() const
  50573. {
  50574. return tabs;
  50575. }
  50576. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  50577. {
  50578. if (currentTabIndex != newIndex)
  50579. {
  50580. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  50581. newIndex = -1;
  50582. currentTabIndex = newIndex;
  50583. for (int i = 0; i < getNumChildComponents(); ++i)
  50584. {
  50585. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50586. if (tb != 0)
  50587. tb->setToggleState (tb->tabIndex == newIndex, false);
  50588. }
  50589. resized();
  50590. if (sendChangeMessage_)
  50591. sendChangeMessage (this);
  50592. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  50593. }
  50594. }
  50595. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  50596. {
  50597. for (int i = getNumChildComponents(); --i >= 0;)
  50598. {
  50599. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50600. if (tb != 0 && tb->tabIndex == index)
  50601. return tb;
  50602. }
  50603. return 0;
  50604. }
  50605. void TabbedButtonBar::lookAndFeelChanged()
  50606. {
  50607. deleteAndZero (extraTabsButton);
  50608. resized();
  50609. }
  50610. void TabbedButtonBar::resized()
  50611. {
  50612. const double minimumScale = 0.7;
  50613. int depth = getWidth();
  50614. int length = getHeight();
  50615. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50616. swapVariables (depth, length);
  50617. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  50618. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  50619. int i, totalLength = overlap;
  50620. int numVisibleButtons = tabs.size();
  50621. for (i = 0; i < getNumChildComponents(); ++i)
  50622. {
  50623. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50624. if (tb != 0)
  50625. {
  50626. totalLength += tb->getBestTabLength (depth) - overlap;
  50627. tb->overlapPixels = overlap / 2;
  50628. }
  50629. }
  50630. double scale = 1.0;
  50631. if (totalLength > length)
  50632. scale = jmax (minimumScale, length / (double) totalLength);
  50633. const bool isTooBig = totalLength * scale > length;
  50634. int tabsButtonPos = 0;
  50635. if (isTooBig)
  50636. {
  50637. if (extraTabsButton == 0)
  50638. {
  50639. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  50640. extraTabsButton->addButtonListener (this);
  50641. extraTabsButton->setAlwaysOnTop (true);
  50642. extraTabsButton->setTriggeredOnMouseDown (true);
  50643. }
  50644. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  50645. extraTabsButton->setSize (buttonSize, buttonSize);
  50646. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50647. {
  50648. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  50649. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  50650. }
  50651. else
  50652. {
  50653. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  50654. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  50655. }
  50656. totalLength = 0;
  50657. for (i = 0; i < tabs.size(); ++i)
  50658. {
  50659. TabBarButton* const tb = getTabButton (i);
  50660. if (tb != 0)
  50661. {
  50662. const int newLength = totalLength + tb->getBestTabLength (depth);
  50663. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  50664. {
  50665. totalLength += overlap;
  50666. break;
  50667. }
  50668. numVisibleButtons = i + 1;
  50669. totalLength = newLength - overlap;
  50670. }
  50671. }
  50672. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  50673. }
  50674. else
  50675. {
  50676. deleteAndZero (extraTabsButton);
  50677. }
  50678. int pos = 0;
  50679. TabBarButton* frontTab = 0;
  50680. for (i = 0; i < tabs.size(); ++i)
  50681. {
  50682. TabBarButton* const tb = getTabButton (i);
  50683. if (tb != 0)
  50684. {
  50685. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  50686. if (i < numVisibleButtons)
  50687. {
  50688. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50689. tb->setBounds (pos, 0, bestLength, getHeight());
  50690. else
  50691. tb->setBounds (0, pos, getWidth(), bestLength);
  50692. tb->toBack();
  50693. if (tb->tabIndex == currentTabIndex)
  50694. frontTab = tb;
  50695. tb->setVisible (true);
  50696. }
  50697. else
  50698. {
  50699. tb->setVisible (false);
  50700. }
  50701. pos += bestLength - overlap;
  50702. }
  50703. }
  50704. behindFrontTab->setBounds (0, 0, getWidth(), getHeight());
  50705. if (frontTab != 0)
  50706. {
  50707. frontTab->toFront (false);
  50708. behindFrontTab->toBehind (frontTab);
  50709. }
  50710. }
  50711. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  50712. {
  50713. return tabColours [tabIndex];
  50714. }
  50715. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  50716. {
  50717. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  50718. && tabColours [tabIndex] != newColour)
  50719. {
  50720. tabColours.set (tabIndex, newColour);
  50721. repaint();
  50722. }
  50723. }
  50724. void TabbedButtonBar::buttonClicked (Button* button)
  50725. {
  50726. if (extraTabsButton == button)
  50727. {
  50728. PopupMenu m;
  50729. for (int i = 0; i < tabs.size(); ++i)
  50730. {
  50731. TabBarButton* const tb = getTabButton (i);
  50732. if (tb != 0 && ! tb->isVisible())
  50733. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  50734. }
  50735. const int res = m.showAt (extraTabsButton);
  50736. if (res != 0)
  50737. setCurrentTabIndex (res - 1);
  50738. }
  50739. }
  50740. void TabbedButtonBar::currentTabChanged (const int, const String&)
  50741. {
  50742. }
  50743. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  50744. {
  50745. }
  50746. END_JUCE_NAMESPACE
  50747. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  50748. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  50749. BEGIN_JUCE_NAMESPACE
  50750. class TabCompButtonBar : public TabbedButtonBar
  50751. {
  50752. public:
  50753. TabCompButtonBar (TabbedComponent* const owner_,
  50754. const TabbedButtonBar::Orientation orientation_)
  50755. : TabbedButtonBar (orientation_),
  50756. owner (owner_)
  50757. {
  50758. }
  50759. ~TabCompButtonBar()
  50760. {
  50761. }
  50762. void currentTabChanged (int newCurrentTabIndex,
  50763. const String& newTabName)
  50764. {
  50765. owner->changeCallback (newCurrentTabIndex, newTabName);
  50766. }
  50767. void popupMenuClickOnTab (int tabIndex,
  50768. const String& tabName)
  50769. {
  50770. owner->popupMenuClickOnTab (tabIndex, tabName);
  50771. }
  50772. const Colour getTabBackgroundColour (const int tabIndex)
  50773. {
  50774. return owner->tabs->getTabBackgroundColour (tabIndex);
  50775. }
  50776. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  50777. {
  50778. return owner->createTabButton (tabName, tabIndex);
  50779. }
  50780. juce_UseDebuggingNewOperator
  50781. private:
  50782. TabbedComponent* const owner;
  50783. TabCompButtonBar (const TabCompButtonBar&);
  50784. TabCompButtonBar& operator= (const TabCompButtonBar&);
  50785. };
  50786. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  50787. : panelComponent (0),
  50788. tabDepth (30),
  50789. outlineThickness (1),
  50790. edgeIndent (0)
  50791. {
  50792. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  50793. }
  50794. TabbedComponent::~TabbedComponent()
  50795. {
  50796. clearTabs();
  50797. delete tabs;
  50798. }
  50799. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  50800. {
  50801. tabs->setOrientation (orientation);
  50802. resized();
  50803. }
  50804. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  50805. {
  50806. return tabs->getOrientation();
  50807. }
  50808. void TabbedComponent::setTabBarDepth (const int newDepth)
  50809. {
  50810. if (tabDepth != newDepth)
  50811. {
  50812. tabDepth = newDepth;
  50813. resized();
  50814. }
  50815. }
  50816. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  50817. {
  50818. return new TabBarButton (tabName, tabs, tabIndex);
  50819. }
  50820. void TabbedComponent::clearTabs()
  50821. {
  50822. if (panelComponent != 0)
  50823. {
  50824. panelComponent->setVisible (false);
  50825. removeChildComponent (panelComponent);
  50826. panelComponent = 0;
  50827. }
  50828. tabs->clearTabs();
  50829. for (int i = contentComponents.size(); --i >= 0;)
  50830. {
  50831. Component* const c = contentComponents.getUnchecked(i);
  50832. // be careful not to delete these components until they've been removed from the tab component
  50833. jassert (c == 0 || c->isValidComponent());
  50834. if (c != 0 && (bool) c->getProperties() ["deleteByTabComp_"])
  50835. delete c;
  50836. }
  50837. contentComponents.clear();
  50838. }
  50839. void TabbedComponent::addTab (const String& tabName,
  50840. const Colour& tabBackgroundColour,
  50841. Component* const contentComponent,
  50842. const bool deleteComponentWhenNotNeeded,
  50843. const int insertIndex)
  50844. {
  50845. contentComponents.insert (insertIndex, contentComponent);
  50846. if (contentComponent != 0)
  50847. contentComponent->getProperties().set ("deleteByTabComp_", deleteComponentWhenNotNeeded);
  50848. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  50849. }
  50850. void TabbedComponent::setTabName (const int tabIndex,
  50851. const String& newName)
  50852. {
  50853. tabs->setTabName (tabIndex, newName);
  50854. }
  50855. void TabbedComponent::removeTab (const int tabIndex)
  50856. {
  50857. Component* const c = contentComponents [tabIndex];
  50858. if (c != 0 && (bool) c->getProperties() ["deleteByTabComp_"])
  50859. {
  50860. if (c == panelComponent)
  50861. panelComponent = 0;
  50862. delete c;
  50863. }
  50864. contentComponents.remove (tabIndex);
  50865. tabs->removeTab (tabIndex);
  50866. }
  50867. int TabbedComponent::getNumTabs() const
  50868. {
  50869. return tabs->getNumTabs();
  50870. }
  50871. const StringArray TabbedComponent::getTabNames() const
  50872. {
  50873. return tabs->getTabNames();
  50874. }
  50875. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  50876. {
  50877. return contentComponents [tabIndex];
  50878. }
  50879. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  50880. {
  50881. return tabs->getTabBackgroundColour (tabIndex);
  50882. }
  50883. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  50884. {
  50885. tabs->setTabBackgroundColour (tabIndex, newColour);
  50886. if (getCurrentTabIndex() == tabIndex)
  50887. repaint();
  50888. }
  50889. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  50890. {
  50891. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  50892. }
  50893. int TabbedComponent::getCurrentTabIndex() const
  50894. {
  50895. return tabs->getCurrentTabIndex();
  50896. }
  50897. const String& TabbedComponent::getCurrentTabName() const
  50898. {
  50899. return tabs->getCurrentTabName();
  50900. }
  50901. void TabbedComponent::setOutline (int thickness)
  50902. {
  50903. outlineThickness = thickness;
  50904. repaint();
  50905. }
  50906. void TabbedComponent::setIndent (const int indentThickness)
  50907. {
  50908. edgeIndent = indentThickness;
  50909. }
  50910. void TabbedComponent::paint (Graphics& g)
  50911. {
  50912. g.fillAll (findColour (backgroundColourId));
  50913. const TabbedButtonBar::Orientation o = getOrientation();
  50914. int x = 0;
  50915. int y = 0;
  50916. int r = getWidth();
  50917. int b = getHeight();
  50918. if (o == TabbedButtonBar::TabsAtTop)
  50919. y += tabDepth;
  50920. else if (o == TabbedButtonBar::TabsAtBottom)
  50921. b -= tabDepth;
  50922. else if (o == TabbedButtonBar::TabsAtLeft)
  50923. x += tabDepth;
  50924. else if (o == TabbedButtonBar::TabsAtRight)
  50925. r -= tabDepth;
  50926. g.reduceClipRegion (x, y, r - x, b - y);
  50927. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  50928. if (outlineThickness > 0)
  50929. {
  50930. if (o == TabbedButtonBar::TabsAtTop)
  50931. --y;
  50932. else if (o == TabbedButtonBar::TabsAtBottom)
  50933. ++b;
  50934. else if (o == TabbedButtonBar::TabsAtLeft)
  50935. --x;
  50936. else if (o == TabbedButtonBar::TabsAtRight)
  50937. ++r;
  50938. g.setColour (findColour (outlineColourId));
  50939. g.drawRect (x, y, r - x, b - y, outlineThickness);
  50940. }
  50941. }
  50942. void TabbedComponent::resized()
  50943. {
  50944. const TabbedButtonBar::Orientation o = getOrientation();
  50945. const int indent = edgeIndent + outlineThickness;
  50946. BorderSize indents (indent);
  50947. if (o == TabbedButtonBar::TabsAtTop)
  50948. {
  50949. tabs->setBounds (0, 0, getWidth(), tabDepth);
  50950. indents.setTop (tabDepth + edgeIndent);
  50951. }
  50952. else if (o == TabbedButtonBar::TabsAtBottom)
  50953. {
  50954. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  50955. indents.setBottom (tabDepth + edgeIndent);
  50956. }
  50957. else if (o == TabbedButtonBar::TabsAtLeft)
  50958. {
  50959. tabs->setBounds (0, 0, tabDepth, getHeight());
  50960. indents.setLeft (tabDepth + edgeIndent);
  50961. }
  50962. else if (o == TabbedButtonBar::TabsAtRight)
  50963. {
  50964. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  50965. indents.setRight (tabDepth + edgeIndent);
  50966. }
  50967. const Rectangle<int> bounds (indents.subtractedFrom (getLocalBounds()));
  50968. for (int i = contentComponents.size(); --i >= 0;)
  50969. if (contentComponents.getUnchecked (i) != 0)
  50970. contentComponents.getUnchecked (i)->setBounds (bounds);
  50971. }
  50972. void TabbedComponent::lookAndFeelChanged()
  50973. {
  50974. for (int i = contentComponents.size(); --i >= 0;)
  50975. if (contentComponents.getUnchecked (i) != 0)
  50976. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  50977. }
  50978. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  50979. const String& newTabName)
  50980. {
  50981. if (panelComponent != 0)
  50982. {
  50983. panelComponent->setVisible (false);
  50984. removeChildComponent (panelComponent);
  50985. panelComponent = 0;
  50986. }
  50987. if (getCurrentTabIndex() >= 0)
  50988. {
  50989. panelComponent = contentComponents [getCurrentTabIndex()];
  50990. if (panelComponent != 0)
  50991. {
  50992. // do these ops as two stages instead of addAndMakeVisible() so that the
  50993. // component has always got a parent when it gets the visibilityChanged() callback
  50994. addChildComponent (panelComponent);
  50995. panelComponent->setVisible (true);
  50996. panelComponent->toFront (true);
  50997. }
  50998. repaint();
  50999. }
  51000. resized();
  51001. currentTabChanged (newCurrentTabIndex, newTabName);
  51002. }
  51003. void TabbedComponent::currentTabChanged (const int, const String&)
  51004. {
  51005. }
  51006. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  51007. {
  51008. }
  51009. END_JUCE_NAMESPACE
  51010. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  51011. /*** Start of inlined file: juce_Viewport.cpp ***/
  51012. BEGIN_JUCE_NAMESPACE
  51013. Viewport::Viewport (const String& componentName)
  51014. : Component (componentName),
  51015. contentComp (0),
  51016. scrollBarThickness (0),
  51017. singleStepX (16),
  51018. singleStepY (16),
  51019. showHScrollbar (true),
  51020. showVScrollbar (true)
  51021. {
  51022. // content holder is used to clip the contents so they don't overlap the scrollbars
  51023. addAndMakeVisible (contentHolder = new Component());
  51024. contentHolder->setInterceptsMouseClicks (false, true);
  51025. verticalScrollBar = new ScrollBar (true);
  51026. horizontalScrollBar = new ScrollBar (false);
  51027. addChildComponent (verticalScrollBar);
  51028. addChildComponent (horizontalScrollBar);
  51029. verticalScrollBar->addListener (this);
  51030. horizontalScrollBar->addListener (this);
  51031. setInterceptsMouseClicks (false, true);
  51032. setWantsKeyboardFocus (true);
  51033. }
  51034. Viewport::~Viewport()
  51035. {
  51036. contentHolder->deleteAllChildren();
  51037. deleteAllChildren();
  51038. }
  51039. void Viewport::visibleAreaChanged (int, int, int, int)
  51040. {
  51041. }
  51042. void Viewport::setViewedComponent (Component* const newViewedComponent)
  51043. {
  51044. if (contentComp.getComponent() != newViewedComponent)
  51045. {
  51046. {
  51047. ScopedPointer<Component> oldCompDeleter (contentComp);
  51048. contentComp = 0;
  51049. }
  51050. contentComp = newViewedComponent;
  51051. if (contentComp != 0)
  51052. {
  51053. contentComp->setTopLeftPosition (0, 0);
  51054. contentHolder->addAndMakeVisible (contentComp);
  51055. contentComp->addComponentListener (this);
  51056. }
  51057. updateVisibleRegion();
  51058. }
  51059. }
  51060. int Viewport::getMaximumVisibleWidth() const throw()
  51061. {
  51062. return jmax (0, getWidth() - (verticalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  51063. }
  51064. int Viewport::getMaximumVisibleHeight() const throw()
  51065. {
  51066. return jmax (0, getHeight() - (horizontalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  51067. }
  51068. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  51069. {
  51070. if (contentComp != 0)
  51071. contentComp->setTopLeftPosition (-xPixelsOffset,
  51072. -yPixelsOffset);
  51073. }
  51074. void Viewport::setViewPositionProportionately (const double x, const double y)
  51075. {
  51076. if (contentComp != 0)
  51077. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  51078. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  51079. }
  51080. bool Viewport::autoScroll (int mouseX, int mouseY, int activeBorderThickness, int maximumSpeed)
  51081. {
  51082. if (contentComp != 0)
  51083. {
  51084. int dx = 0, dy = 0;
  51085. if (horizontalScrollBar->isVisible())
  51086. {
  51087. if (mouseX < activeBorderThickness)
  51088. dx = activeBorderThickness - mouseX;
  51089. else if (mouseX >= contentHolder->getWidth() - activeBorderThickness)
  51090. dx = (contentHolder->getWidth() - activeBorderThickness) - mouseX;
  51091. if (dx < 0)
  51092. dx = jmax (dx, -maximumSpeed, contentHolder->getWidth() - contentComp->getRight());
  51093. else
  51094. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  51095. }
  51096. if (verticalScrollBar->isVisible())
  51097. {
  51098. if (mouseY < activeBorderThickness)
  51099. dy = activeBorderThickness - mouseY;
  51100. else if (mouseY >= contentHolder->getHeight() - activeBorderThickness)
  51101. dy = (contentHolder->getHeight() - activeBorderThickness) - mouseY;
  51102. if (dy < 0)
  51103. dy = jmax (dy, -maximumSpeed, contentHolder->getHeight() - contentComp->getBottom());
  51104. else
  51105. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  51106. }
  51107. if (dx != 0 || dy != 0)
  51108. {
  51109. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  51110. contentComp->getY() + dy);
  51111. return true;
  51112. }
  51113. }
  51114. return false;
  51115. }
  51116. void Viewport::componentMovedOrResized (Component&, bool, bool)
  51117. {
  51118. updateVisibleRegion();
  51119. }
  51120. void Viewport::resized()
  51121. {
  51122. updateVisibleRegion();
  51123. }
  51124. void Viewport::updateVisibleRegion()
  51125. {
  51126. if (contentComp != 0)
  51127. {
  51128. Rectangle<int> newViewPos;
  51129. newViewPos.setPosition (-contentComp->getPosition());
  51130. if (newViewPos.getX() == 0 && newViewPos.getY() == 0
  51131. && contentComp->getWidth() <= getWidth()
  51132. && contentComp->getHeight() <= getHeight())
  51133. {
  51134. horizontalScrollBar->setVisible (! horizontalScrollBar->autoHides());
  51135. verticalScrollBar->setVisible (! verticalScrollBar->autoHides());
  51136. }
  51137. horizontalScrollBar->setRangeLimits (0.0, contentComp->getWidth());
  51138. horizontalScrollBar->setCurrentRange (newViewPos.getX(), getMaximumVisibleWidth());
  51139. horizontalScrollBar->setSingleStepSize (singleStepX);
  51140. if (! (contentComp->getWidth() > 0 && showHScrollbar && getHeight() > getScrollBarThickness()))
  51141. horizontalScrollBar->setVisible (! horizontalScrollBar->autoHides());
  51142. verticalScrollBar->setRangeLimits (0.0, contentComp->getHeight());
  51143. verticalScrollBar->setCurrentRange (newViewPos.getY(), getMaximumVisibleHeight());
  51144. verticalScrollBar->setSingleStepSize (singleStepY);
  51145. if (! (contentComp->getHeight() > 0 && showVScrollbar && getWidth() > getScrollBarThickness()))
  51146. verticalScrollBar->setVisible (! verticalScrollBar->autoHides());
  51147. if (verticalScrollBar->isVisible())
  51148. {
  51149. horizontalScrollBar->setCurrentRange (newViewPos.getX(), getMaximumVisibleWidth());
  51150. verticalScrollBar->setCurrentRange (newViewPos.getY(), getMaximumVisibleHeight());
  51151. verticalScrollBar
  51152. ->setBounds (getMaximumVisibleWidth(), 0,
  51153. getScrollBarThickness(), getMaximumVisibleHeight());
  51154. }
  51155. if (horizontalScrollBar->isVisible())
  51156. {
  51157. horizontalScrollBar->setCurrentRange (newViewPos.getX(), getMaximumVisibleWidth());
  51158. horizontalScrollBar
  51159. ->setBounds (0, getMaximumVisibleHeight(),
  51160. getMaximumVisibleWidth(), getScrollBarThickness());
  51161. }
  51162. contentHolder->setSize (getMaximumVisibleWidth(),
  51163. getMaximumVisibleHeight());
  51164. newViewPos.setSize (jmin (contentComp->getRight(), getMaximumVisibleWidth()),
  51165. jmin (contentComp->getBottom(), getMaximumVisibleHeight()));
  51166. if (lastViewPos != newViewPos)
  51167. {
  51168. lastViewPos = newViewPos;
  51169. visibleAreaChanged (newViewPos.getX(), newViewPos.getY(), newViewPos.getWidth(), newViewPos.getHeight());
  51170. }
  51171. horizontalScrollBar->handleUpdateNowIfNeeded();
  51172. verticalScrollBar->handleUpdateNowIfNeeded();
  51173. }
  51174. else
  51175. {
  51176. horizontalScrollBar->setVisible (! horizontalScrollBar->autoHides());
  51177. verticalScrollBar->setVisible (! verticalScrollBar->autoHides());
  51178. }
  51179. }
  51180. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  51181. {
  51182. singleStepX = stepX;
  51183. singleStepY = stepY;
  51184. updateVisibleRegion();
  51185. }
  51186. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  51187. const bool showHorizontalScrollbarIfNeeded)
  51188. {
  51189. if (showVScrollbar != showVerticalScrollbarIfNeeded
  51190. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  51191. {
  51192. showVScrollbar = showVerticalScrollbarIfNeeded;
  51193. showHScrollbar = showHorizontalScrollbarIfNeeded;
  51194. horizontalScrollBar->setVisible (true);
  51195. verticalScrollBar->setVisible (true);
  51196. updateVisibleRegion();
  51197. }
  51198. }
  51199. void Viewport::setScrollBarThickness (const int thickness)
  51200. {
  51201. scrollBarThickness = thickness;
  51202. updateVisibleRegion();
  51203. }
  51204. int Viewport::getScrollBarThickness() const throw()
  51205. {
  51206. return (scrollBarThickness > 0) ? scrollBarThickness
  51207. : getLookAndFeel().getDefaultScrollbarWidth();
  51208. }
  51209. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  51210. {
  51211. verticalScrollBar->setButtonVisibility (buttonsVisible);
  51212. horizontalScrollBar->setButtonVisibility (buttonsVisible);
  51213. }
  51214. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  51215. {
  51216. if (scrollBarThatHasMoved == horizontalScrollBar)
  51217. {
  51218. setViewPosition (roundToInt (newRangeStart), getViewPositionY());
  51219. }
  51220. else if (scrollBarThatHasMoved == verticalScrollBar)
  51221. {
  51222. setViewPosition (getViewPositionX(), roundToInt (newRangeStart));
  51223. }
  51224. }
  51225. void Viewport::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  51226. {
  51227. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  51228. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  51229. }
  51230. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  51231. {
  51232. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  51233. {
  51234. const bool hasVertBar = verticalScrollBar->isVisible();
  51235. const bool hasHorzBar = horizontalScrollBar->isVisible();
  51236. if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  51237. {
  51238. if (wheelIncrementX == 0 && ! hasVertBar)
  51239. wheelIncrementX = wheelIncrementY;
  51240. horizontalScrollBar->mouseWheelMove (e.getEventRelativeTo (horizontalScrollBar),
  51241. wheelIncrementX, wheelIncrementY);
  51242. return true;
  51243. }
  51244. else if (hasVertBar && wheelIncrementY != 0)
  51245. {
  51246. verticalScrollBar->mouseWheelMove (e.getEventRelativeTo (verticalScrollBar),
  51247. wheelIncrementX, wheelIncrementY);
  51248. return true;
  51249. }
  51250. }
  51251. return false;
  51252. }
  51253. bool Viewport::keyPressed (const KeyPress& key)
  51254. {
  51255. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  51256. || key.isKeyCode (KeyPress::downKey)
  51257. || key.isKeyCode (KeyPress::pageUpKey)
  51258. || key.isKeyCode (KeyPress::pageDownKey)
  51259. || key.isKeyCode (KeyPress::homeKey)
  51260. || key.isKeyCode (KeyPress::endKey);
  51261. if (verticalScrollBar->isVisible() && isUpDownKey)
  51262. return verticalScrollBar->keyPressed (key);
  51263. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  51264. || key.isKeyCode (KeyPress::rightKey);
  51265. if (horizontalScrollBar->isVisible() && (isUpDownKey || isLeftRightKey))
  51266. return horizontalScrollBar->keyPressed (key);
  51267. return false;
  51268. }
  51269. END_JUCE_NAMESPACE
  51270. /*** End of inlined file: juce_Viewport.cpp ***/
  51271. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  51272. BEGIN_JUCE_NAMESPACE
  51273. static const Colour createBaseColour (const Colour& buttonColour,
  51274. const bool hasKeyboardFocus,
  51275. const bool isMouseOverButton,
  51276. const bool isButtonDown) throw()
  51277. {
  51278. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  51279. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  51280. if (isButtonDown)
  51281. return baseColour.contrasting (0.2f);
  51282. else if (isMouseOverButton)
  51283. return baseColour.contrasting (0.1f);
  51284. return baseColour;
  51285. }
  51286. LookAndFeel::LookAndFeel()
  51287. {
  51288. /* if this fails it means you're trying to create a LookAndFeel object before
  51289. the static Colours have been initialised. That ain't gonna work. It probably
  51290. means that you're using a static LookAndFeel object and that your compiler has
  51291. decided to intialise it before the Colours class.
  51292. */
  51293. jassert (Colours::white == Colour (0xffffffff));
  51294. // set up the standard set of colours..
  51295. const int textButtonColour = 0xffbbbbff;
  51296. const int textHighlightColour = 0x401111ee;
  51297. const int standardOutlineColour = 0xb2808080;
  51298. static const int standardColours[] =
  51299. {
  51300. TextButton::buttonColourId, textButtonColour,
  51301. TextButton::buttonOnColourId, 0xff4444ff,
  51302. TextButton::textColourOnId, 0xff000000,
  51303. TextButton::textColourOffId, 0xff000000,
  51304. ComboBox::buttonColourId, 0xffbbbbff,
  51305. ComboBox::outlineColourId, standardOutlineColour,
  51306. ToggleButton::textColourId, 0xff000000,
  51307. TextEditor::backgroundColourId, 0xffffffff,
  51308. TextEditor::textColourId, 0xff000000,
  51309. TextEditor::highlightColourId, textHighlightColour,
  51310. TextEditor::highlightedTextColourId, 0xff000000,
  51311. TextEditor::caretColourId, 0xff000000,
  51312. TextEditor::outlineColourId, 0x00000000,
  51313. TextEditor::focusedOutlineColourId, textButtonColour,
  51314. TextEditor::shadowColourId, 0x38000000,
  51315. Label::backgroundColourId, 0x00000000,
  51316. Label::textColourId, 0xff000000,
  51317. Label::outlineColourId, 0x00000000,
  51318. ScrollBar::backgroundColourId, 0x00000000,
  51319. ScrollBar::thumbColourId, 0xffffffff,
  51320. ScrollBar::trackColourId, 0xffffffff,
  51321. TreeView::linesColourId, 0x4c000000,
  51322. TreeView::backgroundColourId, 0x00000000,
  51323. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  51324. PopupMenu::backgroundColourId, 0xffffffff,
  51325. PopupMenu::textColourId, 0xff000000,
  51326. PopupMenu::headerTextColourId, 0xff000000,
  51327. PopupMenu::highlightedTextColourId, 0xffffffff,
  51328. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  51329. ComboBox::textColourId, 0xff000000,
  51330. ComboBox::backgroundColourId, 0xffffffff,
  51331. ComboBox::arrowColourId, 0x99000000,
  51332. ListBox::backgroundColourId, 0xffffffff,
  51333. ListBox::outlineColourId, standardOutlineColour,
  51334. ListBox::textColourId, 0xff000000,
  51335. Slider::backgroundColourId, 0x00000000,
  51336. Slider::thumbColourId, textButtonColour,
  51337. Slider::trackColourId, 0x7fffffff,
  51338. Slider::rotarySliderFillColourId, 0x7f0000ff,
  51339. Slider::rotarySliderOutlineColourId, 0x66000000,
  51340. Slider::textBoxTextColourId, 0xff000000,
  51341. Slider::textBoxBackgroundColourId, 0xffffffff,
  51342. Slider::textBoxHighlightColourId, textHighlightColour,
  51343. Slider::textBoxOutlineColourId, standardOutlineColour,
  51344. ResizableWindow::backgroundColourId, 0xff777777,
  51345. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  51346. AlertWindow::backgroundColourId, 0xffededed,
  51347. AlertWindow::textColourId, 0xff000000,
  51348. AlertWindow::outlineColourId, 0xff666666,
  51349. ProgressBar::backgroundColourId, 0xffeeeeee,
  51350. ProgressBar::foregroundColourId, 0xffaaaaee,
  51351. TooltipWindow::backgroundColourId, 0xffeeeebb,
  51352. TooltipWindow::textColourId, 0xff000000,
  51353. TooltipWindow::outlineColourId, 0x4c000000,
  51354. TabbedComponent::backgroundColourId, 0x00000000,
  51355. TabbedComponent::outlineColourId, 0xff777777,
  51356. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  51357. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  51358. Toolbar::backgroundColourId, 0xfff6f8f9,
  51359. Toolbar::separatorColourId, 0x4c000000,
  51360. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  51361. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  51362. Toolbar::labelTextColourId, 0xff000000,
  51363. Toolbar::editingModeOutlineColourId, 0xffff0000,
  51364. HyperlinkButton::textColourId, 0xcc1111ee,
  51365. GroupComponent::outlineColourId, 0x66000000,
  51366. GroupComponent::textColourId, 0xff000000,
  51367. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  51368. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  51369. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  51370. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  51371. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  51372. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  51373. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  51374. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  51375. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  51376. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  51377. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  51378. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  51379. CodeEditorComponent::backgroundColourId, 0xffffffff,
  51380. CodeEditorComponent::caretColourId, 0xff000000,
  51381. CodeEditorComponent::highlightColourId, textHighlightColour,
  51382. CodeEditorComponent::defaultTextColourId, 0xff000000,
  51383. ColourSelector::backgroundColourId, 0xffe5e5e5,
  51384. ColourSelector::labelTextColourId, 0xff000000,
  51385. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  51386. KeyMappingEditorComponent::textColourId, 0xff000000,
  51387. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  51388. FileChooserDialogBox::titleTextColourId, 0xff000000,
  51389. };
  51390. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  51391. setColour (standardColours [i], Colour (standardColours [i + 1]));
  51392. static String defaultSansName, defaultSerifName, defaultFixedName;
  51393. if (defaultSansName.isEmpty())
  51394. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName);
  51395. defaultSans = defaultSansName;
  51396. defaultSerif = defaultSerifName;
  51397. defaultFixed = defaultFixedName;
  51398. }
  51399. LookAndFeel::~LookAndFeel()
  51400. {
  51401. }
  51402. const Colour LookAndFeel::findColour (const int colourId) const throw()
  51403. {
  51404. const int index = colourIds.indexOf (colourId);
  51405. if (index >= 0)
  51406. return colours [index];
  51407. jassertfalse
  51408. return Colours::black;
  51409. }
  51410. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  51411. {
  51412. const int index = colourIds.indexOf (colourId);
  51413. if (index >= 0)
  51414. colours.set (index, colour);
  51415. colourIds.add (colourId);
  51416. colours.add (colour);
  51417. }
  51418. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  51419. {
  51420. return colourIds.contains (colourId);
  51421. }
  51422. static LookAndFeel* defaultLF = 0;
  51423. static LookAndFeel* currentDefaultLF = 0;
  51424. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  51425. {
  51426. // if this happens, your app hasn't initialised itself properly.. if you're
  51427. // trying to hack your own main() function, have a look at
  51428. // JUCEApplication::initialiseForGUI()
  51429. jassert (currentDefaultLF != 0);
  51430. return *currentDefaultLF;
  51431. }
  51432. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  51433. {
  51434. if (newDefaultLookAndFeel == 0)
  51435. {
  51436. if (defaultLF == 0)
  51437. defaultLF = new LookAndFeel();
  51438. newDefaultLookAndFeel = defaultLF;
  51439. }
  51440. currentDefaultLF = newDefaultLookAndFeel;
  51441. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  51442. {
  51443. Component* const c = Desktop::getInstance().getComponent (i);
  51444. if (c != 0)
  51445. c->sendLookAndFeelChange();
  51446. }
  51447. }
  51448. void LookAndFeel::clearDefaultLookAndFeel() throw()
  51449. {
  51450. if (currentDefaultLF == defaultLF)
  51451. currentDefaultLF = 0;
  51452. deleteAndZero (defaultLF);
  51453. }
  51454. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  51455. {
  51456. String faceName (font.getTypefaceName());
  51457. if (faceName == Font::getDefaultSansSerifFontName())
  51458. faceName = defaultSans;
  51459. else if (faceName == Font::getDefaultSerifFontName())
  51460. faceName = defaultSerif;
  51461. else if (faceName == Font::getDefaultMonospacedFontName())
  51462. faceName = defaultFixed;
  51463. Font f (font);
  51464. f.setTypefaceName (faceName);
  51465. return Typeface::createSystemTypefaceFor (f);
  51466. }
  51467. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  51468. {
  51469. defaultSans = newName;
  51470. }
  51471. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  51472. {
  51473. return component.getMouseCursor();
  51474. }
  51475. void LookAndFeel::drawButtonBackground (Graphics& g,
  51476. Button& button,
  51477. const Colour& backgroundColour,
  51478. bool isMouseOverButton,
  51479. bool isButtonDown)
  51480. {
  51481. const int width = button.getWidth();
  51482. const int height = button.getHeight();
  51483. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  51484. const float halfThickness = outlineThickness * 0.5f;
  51485. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  51486. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  51487. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  51488. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  51489. const Colour baseColour (createBaseColour (backgroundColour,
  51490. button.hasKeyboardFocus (true),
  51491. isMouseOverButton, isButtonDown)
  51492. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  51493. drawGlassLozenge (g,
  51494. indentL,
  51495. indentT,
  51496. width - indentL - indentR,
  51497. height - indentT - indentB,
  51498. baseColour, outlineThickness, -1.0f,
  51499. button.isConnectedOnLeft(),
  51500. button.isConnectedOnRight(),
  51501. button.isConnectedOnTop(),
  51502. button.isConnectedOnBottom());
  51503. }
  51504. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  51505. {
  51506. return button.getFont();
  51507. }
  51508. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  51509. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  51510. {
  51511. Font font (getFontForTextButton (button));
  51512. g.setFont (font);
  51513. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  51514. : TextButton::textColourOffId)
  51515. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  51516. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  51517. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  51518. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  51519. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  51520. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  51521. g.drawFittedText (button.getButtonText(),
  51522. leftIndent,
  51523. yIndent,
  51524. button.getWidth() - leftIndent - rightIndent,
  51525. button.getHeight() - yIndent * 2,
  51526. Justification::centred, 2);
  51527. }
  51528. void LookAndFeel::drawTickBox (Graphics& g,
  51529. Component& component,
  51530. float x, float y, float w, float h,
  51531. const bool ticked,
  51532. const bool isEnabled,
  51533. const bool isMouseOverButton,
  51534. const bool isButtonDown)
  51535. {
  51536. const float boxSize = w * 0.7f;
  51537. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  51538. createBaseColour (component.findColour (TextButton::buttonColourId)
  51539. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  51540. true,
  51541. isMouseOverButton,
  51542. isButtonDown),
  51543. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  51544. if (ticked)
  51545. {
  51546. Path tick;
  51547. tick.startNewSubPath (1.5f, 3.0f);
  51548. tick.lineTo (3.0f, 6.0f);
  51549. tick.lineTo (6.0f, 0.0f);
  51550. g.setColour (isEnabled ? Colours::black : Colours::grey);
  51551. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  51552. .translated (x, y));
  51553. g.strokePath (tick, PathStrokeType (2.5f), trans);
  51554. }
  51555. }
  51556. void LookAndFeel::drawToggleButton (Graphics& g,
  51557. ToggleButton& button,
  51558. bool isMouseOverButton,
  51559. bool isButtonDown)
  51560. {
  51561. if (button.hasKeyboardFocus (true))
  51562. {
  51563. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  51564. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  51565. }
  51566. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  51567. const float tickWidth = fontSize * 1.1f;
  51568. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  51569. tickWidth, tickWidth,
  51570. button.getToggleState(),
  51571. button.isEnabled(),
  51572. isMouseOverButton,
  51573. isButtonDown);
  51574. g.setColour (button.findColour (ToggleButton::textColourId));
  51575. g.setFont (fontSize);
  51576. if (! button.isEnabled())
  51577. g.setOpacity (0.5f);
  51578. const int textX = (int) tickWidth + 5;
  51579. g.drawFittedText (button.getButtonText(),
  51580. textX, 0,
  51581. button.getWidth() - textX - 2, button.getHeight(),
  51582. Justification::centredLeft, 10);
  51583. }
  51584. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  51585. {
  51586. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  51587. const int tickWidth = jmin (24, button.getHeight());
  51588. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  51589. button.getHeight());
  51590. }
  51591. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  51592. const String& message,
  51593. const String& button1,
  51594. const String& button2,
  51595. const String& button3,
  51596. AlertWindow::AlertIconType iconType,
  51597. int numButtons,
  51598. Component* associatedComponent)
  51599. {
  51600. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  51601. if (numButtons == 1)
  51602. {
  51603. aw->addButton (button1, 0,
  51604. KeyPress (KeyPress::escapeKey, 0, 0),
  51605. KeyPress (KeyPress::returnKey, 0, 0));
  51606. }
  51607. else
  51608. {
  51609. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  51610. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  51611. if (button1ShortCut == button2ShortCut)
  51612. button2ShortCut = KeyPress();
  51613. if (numButtons == 2)
  51614. {
  51615. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  51616. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  51617. }
  51618. else if (numButtons == 3)
  51619. {
  51620. aw->addButton (button1, 1, button1ShortCut);
  51621. aw->addButton (button2, 2, button2ShortCut);
  51622. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  51623. }
  51624. }
  51625. return aw;
  51626. }
  51627. void LookAndFeel::drawAlertBox (Graphics& g,
  51628. AlertWindow& alert,
  51629. const Rectangle<int>& textArea,
  51630. TextLayout& textLayout)
  51631. {
  51632. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  51633. int iconSpaceUsed = 0;
  51634. Justification alignment (Justification::horizontallyCentred);
  51635. const int iconWidth = 80;
  51636. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  51637. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  51638. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  51639. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  51640. iconSize, iconSize);
  51641. if (alert.getAlertType() != AlertWindow::NoIcon)
  51642. {
  51643. Path icon;
  51644. uint32 colour;
  51645. char character;
  51646. if (alert.getAlertType() == AlertWindow::WarningIcon)
  51647. {
  51648. colour = 0x55ff5555;
  51649. character = '!';
  51650. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  51651. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  51652. (float) iconRect.getX(), (float) iconRect.getBottom());
  51653. icon = icon.createPathWithRoundedCorners (5.0f);
  51654. }
  51655. else
  51656. {
  51657. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  51658. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  51659. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  51660. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  51661. }
  51662. GlyphArrangement ga;
  51663. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  51664. String::charToString (character),
  51665. (float) iconRect.getX(), (float) iconRect.getY(),
  51666. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  51667. Justification::centred, false);
  51668. ga.createPath (icon);
  51669. icon.setUsingNonZeroWinding (false);
  51670. g.setColour (Colour (colour));
  51671. g.fillPath (icon);
  51672. iconSpaceUsed = iconWidth;
  51673. alignment = Justification::left;
  51674. }
  51675. g.setColour (alert.findColour (AlertWindow::textColourId));
  51676. textLayout.drawWithin (g,
  51677. textArea.getX() + iconSpaceUsed, textArea.getY(),
  51678. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  51679. alignment.getFlags() | Justification::top);
  51680. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  51681. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  51682. }
  51683. int LookAndFeel::getAlertBoxWindowFlags()
  51684. {
  51685. return ComponentPeer::windowAppearsOnTaskbar
  51686. | ComponentPeer::windowHasDropShadow;
  51687. }
  51688. int LookAndFeel::getAlertWindowButtonHeight()
  51689. {
  51690. return 28;
  51691. }
  51692. const Font LookAndFeel::getAlertWindowFont()
  51693. {
  51694. return Font (12.0f);
  51695. }
  51696. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  51697. int width, int height,
  51698. double progress, const String& textToShow)
  51699. {
  51700. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  51701. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  51702. g.fillAll (background);
  51703. if (progress >= 0.0f && progress < 1.0f)
  51704. {
  51705. drawGlassLozenge (g, 1.0f, 1.0f,
  51706. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  51707. (float) (height - 2),
  51708. foreground,
  51709. 0.5f, 0.0f,
  51710. true, true, true, true);
  51711. }
  51712. else
  51713. {
  51714. // spinning bar..
  51715. g.setColour (foreground);
  51716. const int stripeWidth = height * 2;
  51717. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  51718. Path p;
  51719. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  51720. p.addQuadrilateral (x, 0.0f,
  51721. x + stripeWidth * 0.5f, 0.0f,
  51722. x, (float) height,
  51723. x - stripeWidth * 0.5f, (float) height);
  51724. Image im (Image::ARGB, width, height, true);
  51725. {
  51726. Graphics g2 (im);
  51727. drawGlassLozenge (g2, 1.0f, 1.0f,
  51728. (float) (width - 2),
  51729. (float) (height - 2),
  51730. foreground,
  51731. 0.5f, 0.0f,
  51732. true, true, true, true);
  51733. }
  51734. g.setTiledImageFill (im, 0, 0, 0.85f);
  51735. g.fillPath (p);
  51736. }
  51737. if (textToShow.isNotEmpty())
  51738. {
  51739. g.setColour (Colour::contrasting (background, foreground));
  51740. g.setFont (height * 0.6f);
  51741. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  51742. }
  51743. }
  51744. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  51745. {
  51746. const float radius = jmin (w, h) * 0.4f;
  51747. const float thickness = radius * 0.15f;
  51748. Path p;
  51749. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  51750. radius * 0.6f, thickness,
  51751. thickness * 0.5f);
  51752. const float cx = x + w * 0.5f;
  51753. const float cy = y + h * 0.5f;
  51754. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  51755. for (int i = 0; i < 12; ++i)
  51756. {
  51757. const int n = (i + 12 - animationIndex) % 12;
  51758. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  51759. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  51760. .translated (cx, cy));
  51761. }
  51762. }
  51763. void LookAndFeel::drawScrollbarButton (Graphics& g,
  51764. ScrollBar& scrollbar,
  51765. int width, int height,
  51766. int buttonDirection,
  51767. bool /*isScrollbarVertical*/,
  51768. bool /*isMouseOverButton*/,
  51769. bool isButtonDown)
  51770. {
  51771. Path p;
  51772. if (buttonDirection == 0)
  51773. p.addTriangle (width * 0.5f, height * 0.2f,
  51774. width * 0.1f, height * 0.7f,
  51775. width * 0.9f, height * 0.7f);
  51776. else if (buttonDirection == 1)
  51777. p.addTriangle (width * 0.8f, height * 0.5f,
  51778. width * 0.3f, height * 0.1f,
  51779. width * 0.3f, height * 0.9f);
  51780. else if (buttonDirection == 2)
  51781. p.addTriangle (width * 0.5f, height * 0.8f,
  51782. width * 0.1f, height * 0.3f,
  51783. width * 0.9f, height * 0.3f);
  51784. else if (buttonDirection == 3)
  51785. p.addTriangle (width * 0.2f, height * 0.5f,
  51786. width * 0.7f, height * 0.1f,
  51787. width * 0.7f, height * 0.9f);
  51788. if (isButtonDown)
  51789. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  51790. else
  51791. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  51792. g.fillPath (p);
  51793. g.setColour (Colour (0x80000000));
  51794. g.strokePath (p, PathStrokeType (0.5f));
  51795. }
  51796. void LookAndFeel::drawScrollbar (Graphics& g,
  51797. ScrollBar& scrollbar,
  51798. int x, int y,
  51799. int width, int height,
  51800. bool isScrollbarVertical,
  51801. int thumbStartPosition,
  51802. int thumbSize,
  51803. bool /*isMouseOver*/,
  51804. bool /*isMouseDown*/)
  51805. {
  51806. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  51807. Path slotPath, thumbPath;
  51808. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  51809. const float slotIndentx2 = slotIndent * 2.0f;
  51810. const float thumbIndent = slotIndent + 1.0f;
  51811. const float thumbIndentx2 = thumbIndent * 2.0f;
  51812. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  51813. if (isScrollbarVertical)
  51814. {
  51815. slotPath.addRoundedRectangle (x + slotIndent,
  51816. y + slotIndent,
  51817. width - slotIndentx2,
  51818. height - slotIndentx2,
  51819. (width - slotIndentx2) * 0.5f);
  51820. if (thumbSize > 0)
  51821. thumbPath.addRoundedRectangle (x + thumbIndent,
  51822. thumbStartPosition + thumbIndent,
  51823. width - thumbIndentx2,
  51824. thumbSize - thumbIndentx2,
  51825. (width - thumbIndentx2) * 0.5f);
  51826. gx1 = (float) x;
  51827. gx2 = x + width * 0.7f;
  51828. }
  51829. else
  51830. {
  51831. slotPath.addRoundedRectangle (x + slotIndent,
  51832. y + slotIndent,
  51833. width - slotIndentx2,
  51834. height - slotIndentx2,
  51835. (height - slotIndentx2) * 0.5f);
  51836. if (thumbSize > 0)
  51837. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  51838. y + thumbIndent,
  51839. thumbSize - thumbIndentx2,
  51840. height - thumbIndentx2,
  51841. (height - thumbIndentx2) * 0.5f);
  51842. gy1 = (float) y;
  51843. gy2 = y + height * 0.7f;
  51844. }
  51845. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  51846. g.setGradientFill (ColourGradient (thumbColour.overlaidWith (Colour (0x44000000)), gx1, gy1,
  51847. thumbColour.overlaidWith (Colour (0x19000000)), gx2, gy2, false));
  51848. g.fillPath (slotPath);
  51849. if (isScrollbarVertical)
  51850. {
  51851. gx1 = x + width * 0.6f;
  51852. gx2 = (float) x + width;
  51853. }
  51854. else
  51855. {
  51856. gy1 = y + height * 0.6f;
  51857. gy2 = (float) y + height;
  51858. }
  51859. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  51860. Colour (0x19000000), gx2, gy2, false));
  51861. g.fillPath (slotPath);
  51862. g.setColour (thumbColour);
  51863. g.fillPath (thumbPath);
  51864. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  51865. Colours::transparentBlack, gx2, gy2, false));
  51866. g.saveState();
  51867. if (isScrollbarVertical)
  51868. g.reduceClipRegion (x + width / 2, y, width, height);
  51869. else
  51870. g.reduceClipRegion (x, y + height / 2, width, height);
  51871. g.fillPath (thumbPath);
  51872. g.restoreState();
  51873. g.setColour (Colour (0x4c000000));
  51874. g.strokePath (thumbPath, PathStrokeType (0.4f));
  51875. }
  51876. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  51877. {
  51878. return 0;
  51879. }
  51880. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  51881. {
  51882. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  51883. }
  51884. int LookAndFeel::getDefaultScrollbarWidth()
  51885. {
  51886. return 18;
  51887. }
  51888. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  51889. {
  51890. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  51891. : scrollbar.getHeight());
  51892. }
  51893. const Path LookAndFeel::getTickShape (const float height)
  51894. {
  51895. static const unsigned char tickShapeData[] =
  51896. {
  51897. 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,
  51898. 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,
  51899. 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,
  51900. 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,
  51901. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  51902. };
  51903. Path p;
  51904. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  51905. p.scaleToFit (0, 0, height * 2.0f, height, true);
  51906. return p;
  51907. }
  51908. const Path LookAndFeel::getCrossShape (const float height)
  51909. {
  51910. static const unsigned char crossShapeData[] =
  51911. {
  51912. 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,
  51913. 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,
  51914. 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,
  51915. 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,
  51916. 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,
  51917. 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,
  51918. 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
  51919. };
  51920. Path p;
  51921. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  51922. p.scaleToFit (0, 0, height * 2.0f, height, true);
  51923. return p;
  51924. }
  51925. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  51926. {
  51927. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  51928. x += (w - boxSize) >> 1;
  51929. y += (h - boxSize) >> 1;
  51930. w = boxSize;
  51931. h = boxSize;
  51932. g.setColour (Colour (0xe5ffffff));
  51933. g.fillRect (x, y, w, h);
  51934. g.setColour (Colour (0x80000000));
  51935. g.drawRect (x, y, w, h);
  51936. const float size = boxSize / 2 + 1.0f;
  51937. const float centre = (float) (boxSize / 2);
  51938. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  51939. if (isPlus)
  51940. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  51941. }
  51942. void LookAndFeel::drawBubble (Graphics& g,
  51943. float tipX, float tipY,
  51944. float boxX, float boxY,
  51945. float boxW, float boxH)
  51946. {
  51947. int side = 0;
  51948. if (tipX < boxX)
  51949. side = 1;
  51950. else if (tipX > boxX + boxW)
  51951. side = 3;
  51952. else if (tipY > boxY + boxH)
  51953. side = 2;
  51954. const float indent = 2.0f;
  51955. Path p;
  51956. p.addBubble (boxX + indent,
  51957. boxY + indent,
  51958. boxW - indent * 2.0f,
  51959. boxH - indent * 2.0f,
  51960. 5.0f,
  51961. tipX, tipY,
  51962. side,
  51963. 0.5f,
  51964. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  51965. //xxx need to take comp as param for colour
  51966. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  51967. g.fillPath (p);
  51968. //xxx as above
  51969. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  51970. g.strokePath (p, PathStrokeType (1.33f));
  51971. }
  51972. const Font LookAndFeel::getPopupMenuFont()
  51973. {
  51974. return Font (17.0f);
  51975. }
  51976. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  51977. const bool isSeparator,
  51978. int standardMenuItemHeight,
  51979. int& idealWidth,
  51980. int& idealHeight)
  51981. {
  51982. if (isSeparator)
  51983. {
  51984. idealWidth = 50;
  51985. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  51986. }
  51987. else
  51988. {
  51989. Font font (getPopupMenuFont());
  51990. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  51991. font.setHeight (standardMenuItemHeight / 1.3f);
  51992. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  51993. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  51994. }
  51995. }
  51996. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  51997. {
  51998. const Colour background (findColour (PopupMenu::backgroundColourId));
  51999. g.fillAll (background);
  52000. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  52001. for (int i = 0; i < height; i += 3)
  52002. g.fillRect (0, i, width, 1);
  52003. #if ! JUCE_MAC
  52004. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  52005. g.drawRect (0, 0, width, height);
  52006. #endif
  52007. }
  52008. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  52009. int width, int height,
  52010. bool isScrollUpArrow)
  52011. {
  52012. const Colour background (findColour (PopupMenu::backgroundColourId));
  52013. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  52014. background.withAlpha (0.0f),
  52015. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  52016. false));
  52017. g.fillRect (1, 1, width - 2, height - 2);
  52018. const float hw = width * 0.5f;
  52019. const float arrowW = height * 0.3f;
  52020. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  52021. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  52022. Path p;
  52023. p.addTriangle (hw - arrowW, y1,
  52024. hw + arrowW, y1,
  52025. hw, y2);
  52026. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  52027. g.fillPath (p);
  52028. }
  52029. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  52030. int width, int height,
  52031. const bool isSeparator,
  52032. const bool isActive,
  52033. const bool isHighlighted,
  52034. const bool isTicked,
  52035. const bool hasSubMenu,
  52036. const String& text,
  52037. const String& shortcutKeyText,
  52038. Image* image,
  52039. const Colour* const textColourToUse)
  52040. {
  52041. const float halfH = height * 0.5f;
  52042. if (isSeparator)
  52043. {
  52044. const float separatorIndent = 5.5f;
  52045. g.setColour (Colour (0x33000000));
  52046. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  52047. g.setColour (Colour (0x66ffffff));
  52048. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  52049. }
  52050. else
  52051. {
  52052. Colour textColour (findColour (PopupMenu::textColourId));
  52053. if (textColourToUse != 0)
  52054. textColour = *textColourToUse;
  52055. if (isHighlighted)
  52056. {
  52057. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  52058. g.fillRect (1, 1, width - 2, height - 2);
  52059. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  52060. }
  52061. else
  52062. {
  52063. g.setColour (textColour);
  52064. }
  52065. if (! isActive)
  52066. g.setOpacity (0.3f);
  52067. Font font (getPopupMenuFont());
  52068. if (font.getHeight() > height / 1.3f)
  52069. font.setHeight (height / 1.3f);
  52070. g.setFont (font);
  52071. const int leftBorder = (height * 5) / 4;
  52072. const int rightBorder = 4;
  52073. if (image != 0)
  52074. {
  52075. g.drawImageWithin (image,
  52076. 2, 1, leftBorder - 4, height - 2,
  52077. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  52078. }
  52079. else if (isTicked)
  52080. {
  52081. const Path tick (getTickShape (1.0f));
  52082. const float th = font.getAscent();
  52083. const float ty = halfH - th * 0.5f;
  52084. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  52085. th, true));
  52086. }
  52087. g.drawFittedText (text,
  52088. leftBorder, 0,
  52089. width - (leftBorder + rightBorder), height,
  52090. Justification::centredLeft, 1);
  52091. if (shortcutKeyText.isNotEmpty())
  52092. {
  52093. Font f2 (font);
  52094. f2.setHeight (f2.getHeight() * 0.75f);
  52095. f2.setHorizontalScale (0.95f);
  52096. g.setFont (f2);
  52097. g.drawText (shortcutKeyText,
  52098. leftBorder,
  52099. 0,
  52100. width - (leftBorder + rightBorder + 4),
  52101. height,
  52102. Justification::centredRight,
  52103. true);
  52104. }
  52105. if (hasSubMenu)
  52106. {
  52107. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  52108. const float x = width - height * 0.6f;
  52109. Path p;
  52110. p.addTriangle (x, halfH - arrowH * 0.5f,
  52111. x, halfH + arrowH * 0.5f,
  52112. x + arrowH * 0.6f, halfH);
  52113. g.fillPath (p);
  52114. }
  52115. }
  52116. }
  52117. int LookAndFeel::getMenuWindowFlags()
  52118. {
  52119. return ComponentPeer::windowHasDropShadow;
  52120. }
  52121. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  52122. bool, MenuBarComponent& menuBar)
  52123. {
  52124. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  52125. if (menuBar.isEnabled())
  52126. {
  52127. drawShinyButtonShape (g,
  52128. -4.0f, 0.0f,
  52129. width + 8.0f, (float) height,
  52130. 0.0f,
  52131. baseColour,
  52132. 0.4f,
  52133. true, true, true, true);
  52134. }
  52135. else
  52136. {
  52137. g.fillAll (baseColour);
  52138. }
  52139. }
  52140. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  52141. {
  52142. return Font (menuBar.getHeight() * 0.7f);
  52143. }
  52144. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  52145. {
  52146. return getMenuBarFont (menuBar, itemIndex, itemText)
  52147. .getStringWidth (itemText) + menuBar.getHeight();
  52148. }
  52149. void LookAndFeel::drawMenuBarItem (Graphics& g,
  52150. int width, int height,
  52151. int itemIndex,
  52152. const String& itemText,
  52153. bool isMouseOverItem,
  52154. bool isMenuOpen,
  52155. bool /*isMouseOverBar*/,
  52156. MenuBarComponent& menuBar)
  52157. {
  52158. if (! menuBar.isEnabled())
  52159. {
  52160. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  52161. .withMultipliedAlpha (0.5f));
  52162. }
  52163. else if (isMenuOpen || isMouseOverItem)
  52164. {
  52165. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  52166. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  52167. }
  52168. else
  52169. {
  52170. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  52171. }
  52172. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  52173. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  52174. }
  52175. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  52176. TextEditor& textEditor)
  52177. {
  52178. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  52179. }
  52180. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  52181. {
  52182. if (textEditor.isEnabled())
  52183. {
  52184. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  52185. {
  52186. const int border = 2;
  52187. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  52188. g.drawRect (0, 0, width, height, border);
  52189. g.setOpacity (1.0f);
  52190. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  52191. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  52192. }
  52193. else
  52194. {
  52195. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  52196. g.drawRect (0, 0, width, height);
  52197. g.setOpacity (1.0f);
  52198. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  52199. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  52200. }
  52201. }
  52202. }
  52203. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  52204. const bool isButtonDown,
  52205. int buttonX, int buttonY,
  52206. int buttonW, int buttonH,
  52207. ComboBox& box)
  52208. {
  52209. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  52210. if (box.isEnabled() && box.hasKeyboardFocus (false))
  52211. {
  52212. g.setColour (box.findColour (TextButton::buttonColourId));
  52213. g.drawRect (0, 0, width, height, 2);
  52214. }
  52215. else
  52216. {
  52217. g.setColour (box.findColour (ComboBox::outlineColourId));
  52218. g.drawRect (0, 0, width, height);
  52219. }
  52220. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  52221. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  52222. box.hasKeyboardFocus (true),
  52223. false, isButtonDown)
  52224. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  52225. drawGlassLozenge (g,
  52226. buttonX + outlineThickness, buttonY + outlineThickness,
  52227. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  52228. baseColour, outlineThickness, -1.0f,
  52229. true, true, true, true);
  52230. if (box.isEnabled())
  52231. {
  52232. const float arrowX = 0.3f;
  52233. const float arrowH = 0.2f;
  52234. Path p;
  52235. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  52236. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  52237. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  52238. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  52239. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  52240. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  52241. g.setColour (box.findColour (ComboBox::arrowColourId));
  52242. g.fillPath (p);
  52243. }
  52244. }
  52245. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  52246. {
  52247. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  52248. }
  52249. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  52250. {
  52251. return new Label (String::empty, String::empty);
  52252. }
  52253. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  52254. {
  52255. label.setBounds (1, 1,
  52256. box.getWidth() + 3 - box.getHeight(),
  52257. box.getHeight() - 2);
  52258. label.setFont (getComboBoxFont (box));
  52259. }
  52260. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  52261. {
  52262. g.fillAll (label.findColour (Label::backgroundColourId));
  52263. if (! label.isBeingEdited())
  52264. {
  52265. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  52266. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  52267. g.setFont (label.getFont());
  52268. g.drawFittedText (label.getText(),
  52269. label.getHorizontalBorderSize(),
  52270. label.getVerticalBorderSize(),
  52271. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  52272. label.getHeight() - 2 * label.getVerticalBorderSize(),
  52273. label.getJustificationType(),
  52274. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  52275. label.getMinimumHorizontalScale());
  52276. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  52277. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  52278. }
  52279. else if (label.isEnabled())
  52280. {
  52281. g.setColour (label.findColour (Label::outlineColourId));
  52282. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  52283. }
  52284. }
  52285. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  52286. int x, int y,
  52287. int width, int height,
  52288. float /*sliderPos*/,
  52289. float /*minSliderPos*/,
  52290. float /*maxSliderPos*/,
  52291. const Slider::SliderStyle /*style*/,
  52292. Slider& slider)
  52293. {
  52294. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  52295. const Colour trackColour (slider.findColour (Slider::trackColourId));
  52296. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  52297. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  52298. Path indent;
  52299. if (slider.isHorizontal())
  52300. {
  52301. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  52302. const float ih = sliderRadius;
  52303. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  52304. gradCol2, 0.0f, iy + ih, false));
  52305. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  52306. width + sliderRadius, ih,
  52307. 5.0f);
  52308. g.fillPath (indent);
  52309. }
  52310. else
  52311. {
  52312. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  52313. const float iw = sliderRadius;
  52314. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  52315. gradCol2, ix + iw, 0.0f, false));
  52316. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  52317. iw, height + sliderRadius,
  52318. 5.0f);
  52319. g.fillPath (indent);
  52320. }
  52321. g.setColour (Colour (0x4c000000));
  52322. g.strokePath (indent, PathStrokeType (0.5f));
  52323. }
  52324. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  52325. int x, int y,
  52326. int width, int height,
  52327. float sliderPos,
  52328. float minSliderPos,
  52329. float maxSliderPos,
  52330. const Slider::SliderStyle style,
  52331. Slider& slider)
  52332. {
  52333. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  52334. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  52335. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  52336. slider.isMouseOverOrDragging() && slider.isEnabled(),
  52337. slider.isMouseButtonDown() && slider.isEnabled()));
  52338. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  52339. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  52340. {
  52341. float kx, ky;
  52342. if (style == Slider::LinearVertical)
  52343. {
  52344. kx = x + width * 0.5f;
  52345. ky = sliderPos;
  52346. }
  52347. else
  52348. {
  52349. kx = sliderPos;
  52350. ky = y + height * 0.5f;
  52351. }
  52352. drawGlassSphere (g,
  52353. kx - sliderRadius,
  52354. ky - sliderRadius,
  52355. sliderRadius * 2.0f,
  52356. knobColour, outlineThickness);
  52357. }
  52358. else
  52359. {
  52360. if (style == Slider::ThreeValueVertical)
  52361. {
  52362. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  52363. sliderPos - sliderRadius,
  52364. sliderRadius * 2.0f,
  52365. knobColour, outlineThickness);
  52366. }
  52367. else if (style == Slider::ThreeValueHorizontal)
  52368. {
  52369. drawGlassSphere (g,sliderPos - sliderRadius,
  52370. y + height * 0.5f - sliderRadius,
  52371. sliderRadius * 2.0f,
  52372. knobColour, outlineThickness);
  52373. }
  52374. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  52375. {
  52376. const float sr = jmin (sliderRadius, width * 0.4f);
  52377. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  52378. minSliderPos - sliderRadius,
  52379. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  52380. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  52381. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  52382. }
  52383. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  52384. {
  52385. const float sr = jmin (sliderRadius, height * 0.4f);
  52386. drawGlassPointer (g, minSliderPos - sr,
  52387. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  52388. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  52389. drawGlassPointer (g, maxSliderPos - sliderRadius,
  52390. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  52391. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  52392. }
  52393. }
  52394. }
  52395. void LookAndFeel::drawLinearSlider (Graphics& g,
  52396. int x, int y,
  52397. int width, int height,
  52398. float sliderPos,
  52399. float minSliderPos,
  52400. float maxSliderPos,
  52401. const Slider::SliderStyle style,
  52402. Slider& slider)
  52403. {
  52404. g.fillAll (slider.findColour (Slider::backgroundColourId));
  52405. if (style == Slider::LinearBar)
  52406. {
  52407. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  52408. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  52409. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  52410. false,
  52411. isMouseOver,
  52412. isMouseOver || slider.isMouseButtonDown()));
  52413. drawShinyButtonShape (g,
  52414. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  52415. baseColour,
  52416. slider.isEnabled() ? 0.9f : 0.3f,
  52417. true, true, true, true);
  52418. }
  52419. else
  52420. {
  52421. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  52422. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  52423. }
  52424. }
  52425. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  52426. {
  52427. return jmin (7,
  52428. slider.getHeight() / 2,
  52429. slider.getWidth() / 2) + 2;
  52430. }
  52431. void LookAndFeel::drawRotarySlider (Graphics& g,
  52432. int x, int y,
  52433. int width, int height,
  52434. float sliderPos,
  52435. const float rotaryStartAngle,
  52436. const float rotaryEndAngle,
  52437. Slider& slider)
  52438. {
  52439. const float radius = jmin (width / 2, height / 2) - 2.0f;
  52440. const float centreX = x + width * 0.5f;
  52441. const float centreY = y + height * 0.5f;
  52442. const float rx = centreX - radius;
  52443. const float ry = centreY - radius;
  52444. const float rw = radius * 2.0f;
  52445. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  52446. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  52447. if (radius > 12.0f)
  52448. {
  52449. if (slider.isEnabled())
  52450. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  52451. else
  52452. g.setColour (Colour (0x80808080));
  52453. const float thickness = 0.7f;
  52454. {
  52455. Path filledArc;
  52456. filledArc.addPieSegment (rx, ry, rw, rw,
  52457. rotaryStartAngle,
  52458. angle,
  52459. thickness);
  52460. g.fillPath (filledArc);
  52461. }
  52462. if (thickness > 0)
  52463. {
  52464. const float innerRadius = radius * 0.2f;
  52465. Path p;
  52466. p.addTriangle (-innerRadius, 0.0f,
  52467. 0.0f, -radius * thickness * 1.1f,
  52468. innerRadius, 0.0f);
  52469. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  52470. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  52471. }
  52472. if (slider.isEnabled())
  52473. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  52474. else
  52475. g.setColour (Colour (0x80808080));
  52476. Path outlineArc;
  52477. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  52478. outlineArc.closeSubPath();
  52479. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  52480. }
  52481. else
  52482. {
  52483. if (slider.isEnabled())
  52484. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  52485. else
  52486. g.setColour (Colour (0x80808080));
  52487. Path p;
  52488. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  52489. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  52490. p.addLineSegment (0.0f, 0.0f, 0.0f, -radius, rw * 0.2f);
  52491. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  52492. }
  52493. }
  52494. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  52495. {
  52496. return new TextButton (isIncrement ? "+" : "-", String::empty);
  52497. }
  52498. class SliderLabelComp : public Label
  52499. {
  52500. public:
  52501. SliderLabelComp() : Label (String::empty, String::empty) {}
  52502. ~SliderLabelComp() {}
  52503. void mouseWheelMove (const MouseEvent&, float, float) {}
  52504. };
  52505. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  52506. {
  52507. Label* const l = new SliderLabelComp();
  52508. l->setJustificationType (Justification::centred);
  52509. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  52510. l->setColour (Label::backgroundColourId,
  52511. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  52512. : slider.findColour (Slider::textBoxBackgroundColourId));
  52513. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  52514. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  52515. l->setColour (TextEditor::backgroundColourId,
  52516. slider.findColour (Slider::textBoxBackgroundColourId)
  52517. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  52518. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  52519. return l;
  52520. }
  52521. ImageEffectFilter* LookAndFeel::getSliderEffect()
  52522. {
  52523. return 0;
  52524. }
  52525. static const TextLayout layoutTooltipText (const String& text) throw()
  52526. {
  52527. const float tooltipFontSize = 12.0f;
  52528. const int maxToolTipWidth = 400;
  52529. const Font f (tooltipFontSize, Font::bold);
  52530. TextLayout tl (text, f);
  52531. tl.layout (maxToolTipWidth, Justification::left, true);
  52532. return tl;
  52533. }
  52534. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  52535. {
  52536. const TextLayout tl (layoutTooltipText (tipText));
  52537. width = tl.getWidth() + 14;
  52538. height = tl.getHeight() + 6;
  52539. }
  52540. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  52541. {
  52542. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  52543. const Colour textCol (findColour (TooltipWindow::textColourId));
  52544. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  52545. g.setColour (findColour (TooltipWindow::outlineColourId));
  52546. g.drawRect (0, 0, width, height, 1);
  52547. #endif
  52548. const TextLayout tl (layoutTooltipText (text));
  52549. g.setColour (findColour (TooltipWindow::textColourId));
  52550. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  52551. }
  52552. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  52553. {
  52554. return new TextButton (text, TRANS("click to browse for a different file"));
  52555. }
  52556. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  52557. ComboBox* filenameBox,
  52558. Button* browseButton)
  52559. {
  52560. browseButton->setSize (80, filenameComp.getHeight());
  52561. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  52562. if (tb != 0)
  52563. tb->changeWidthToFitText();
  52564. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  52565. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  52566. }
  52567. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  52568. int imageX, int imageY, int imageW, int imageH,
  52569. const Colour& overlayColour,
  52570. float imageOpacity,
  52571. ImageButton& button)
  52572. {
  52573. if (! button.isEnabled())
  52574. imageOpacity *= 0.3f;
  52575. if (! overlayColour.isOpaque())
  52576. {
  52577. g.setOpacity (imageOpacity);
  52578. g.drawImage (image, imageX, imageY, imageW, imageH,
  52579. 0, 0, image->getWidth(), image->getHeight(), false);
  52580. }
  52581. if (! overlayColour.isTransparent())
  52582. {
  52583. g.setColour (overlayColour);
  52584. g.drawImage (image, imageX, imageY, imageW, imageH,
  52585. 0, 0, image->getWidth(), image->getHeight(), true);
  52586. }
  52587. }
  52588. void LookAndFeel::drawCornerResizer (Graphics& g,
  52589. int w, int h,
  52590. bool /*isMouseOver*/,
  52591. bool /*isMouseDragging*/)
  52592. {
  52593. const float lineThickness = jmin (w, h) * 0.075f;
  52594. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  52595. {
  52596. g.setColour (Colours::lightgrey);
  52597. g.drawLine (w * i,
  52598. h + 1.0f,
  52599. w + 1.0f,
  52600. h * i,
  52601. lineThickness);
  52602. g.setColour (Colours::darkgrey);
  52603. g.drawLine (w * i + lineThickness,
  52604. h + 1.0f,
  52605. w + 1.0f,
  52606. h * i + lineThickness,
  52607. lineThickness);
  52608. }
  52609. }
  52610. void LookAndFeel::drawResizableFrame (Graphics&, int /*w*/, int /*h*/,
  52611. const BorderSize& /*borders*/)
  52612. {
  52613. }
  52614. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  52615. const BorderSize& /*border*/, ResizableWindow& window)
  52616. {
  52617. g.fillAll (window.getBackgroundColour());
  52618. }
  52619. void LookAndFeel::drawResizableWindowBorder (Graphics& g, int w, int h,
  52620. const BorderSize& border, ResizableWindow&)
  52621. {
  52622. g.setColour (Colour (0x80000000));
  52623. g.drawRect (0, 0, w, h);
  52624. g.setColour (Colour (0x19000000));
  52625. g.drawRect (border.getLeft() - 1,
  52626. border.getTop() - 1,
  52627. w + 2 - border.getLeftAndRight(),
  52628. h + 2 - border.getTopAndBottom());
  52629. }
  52630. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  52631. Graphics& g, int w, int h,
  52632. int titleSpaceX, int titleSpaceW,
  52633. const Image* icon,
  52634. bool drawTitleTextOnLeft)
  52635. {
  52636. const bool isActive = window.isActiveWindow();
  52637. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  52638. 0.0f, 0.0f,
  52639. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  52640. 0.0f, (float) h, false));
  52641. g.fillAll();
  52642. Font font (h * 0.65f, Font::bold);
  52643. g.setFont (font);
  52644. int textW = font.getStringWidth (window.getName());
  52645. int iconW = 0;
  52646. int iconH = 0;
  52647. if (icon != 0)
  52648. {
  52649. iconH = (int) font.getHeight();
  52650. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  52651. }
  52652. textW = jmin (titleSpaceW, textW + iconW);
  52653. int textX = drawTitleTextOnLeft ? titleSpaceX
  52654. : jmax (titleSpaceX, (w - textW) / 2);
  52655. if (textX + textW > titleSpaceX + titleSpaceW)
  52656. textX = titleSpaceX + titleSpaceW - textW;
  52657. if (icon != 0)
  52658. {
  52659. g.setOpacity (isActive ? 1.0f : 0.6f);
  52660. g.drawImageWithin (icon, textX, (h - iconH) / 2, iconW, iconH,
  52661. RectanglePlacement::centred, false);
  52662. textX += iconW;
  52663. textW -= iconW;
  52664. }
  52665. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  52666. g.setColour (findColour (DocumentWindow::textColourId));
  52667. else
  52668. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  52669. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  52670. }
  52671. class GlassWindowButton : public Button
  52672. {
  52673. public:
  52674. GlassWindowButton (const String& name, const Colour& col,
  52675. const Path& normalShape_,
  52676. const Path& toggledShape_) throw()
  52677. : Button (name),
  52678. colour (col),
  52679. normalShape (normalShape_),
  52680. toggledShape (toggledShape_)
  52681. {
  52682. }
  52683. ~GlassWindowButton()
  52684. {
  52685. }
  52686. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  52687. {
  52688. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  52689. if (! isEnabled())
  52690. alpha *= 0.5f;
  52691. float x = 0, y = 0, diam;
  52692. if (getWidth() < getHeight())
  52693. {
  52694. diam = (float) getWidth();
  52695. y = (getHeight() - getWidth()) * 0.5f;
  52696. }
  52697. else
  52698. {
  52699. diam = (float) getHeight();
  52700. y = (getWidth() - getHeight()) * 0.5f;
  52701. }
  52702. x += diam * 0.05f;
  52703. y += diam * 0.05f;
  52704. diam *= 0.9f;
  52705. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  52706. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  52707. g.fillEllipse (x, y, diam, diam);
  52708. x += 2.0f;
  52709. y += 2.0f;
  52710. diam -= 4.0f;
  52711. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  52712. Path& p = getToggleState() ? toggledShape : normalShape;
  52713. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  52714. diam * 0.4f, diam * 0.4f, true));
  52715. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  52716. g.fillPath (p, t);
  52717. }
  52718. juce_UseDebuggingNewOperator
  52719. private:
  52720. Colour colour;
  52721. Path normalShape, toggledShape;
  52722. GlassWindowButton (const GlassWindowButton&);
  52723. GlassWindowButton& operator= (const GlassWindowButton&);
  52724. };
  52725. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  52726. {
  52727. Path shape;
  52728. const float crossThickness = 0.25f;
  52729. if (buttonType == DocumentWindow::closeButton)
  52730. {
  52731. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, crossThickness * 1.4f);
  52732. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, crossThickness * 1.4f);
  52733. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  52734. }
  52735. else if (buttonType == DocumentWindow::minimiseButton)
  52736. {
  52737. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  52738. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  52739. }
  52740. else if (buttonType == DocumentWindow::maximiseButton)
  52741. {
  52742. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, crossThickness);
  52743. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  52744. Path fullscreenShape;
  52745. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  52746. fullscreenShape.lineTo (0.0f, 100.0f);
  52747. fullscreenShape.lineTo (0.0f, 0.0f);
  52748. fullscreenShape.lineTo (100.0f, 0.0f);
  52749. fullscreenShape.lineTo (100.0f, 45.0f);
  52750. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  52751. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  52752. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  52753. }
  52754. jassertfalse
  52755. return 0;
  52756. }
  52757. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  52758. int titleBarX,
  52759. int titleBarY,
  52760. int titleBarW,
  52761. int titleBarH,
  52762. Button* minimiseButton,
  52763. Button* maximiseButton,
  52764. Button* closeButton,
  52765. bool positionTitleBarButtonsOnLeft)
  52766. {
  52767. const int buttonW = titleBarH - titleBarH / 8;
  52768. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  52769. : titleBarX + titleBarW - buttonW - buttonW / 4;
  52770. if (closeButton != 0)
  52771. {
  52772. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  52773. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  52774. }
  52775. if (positionTitleBarButtonsOnLeft)
  52776. swapVariables (minimiseButton, maximiseButton);
  52777. if (maximiseButton != 0)
  52778. {
  52779. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  52780. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  52781. }
  52782. if (minimiseButton != 0)
  52783. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  52784. }
  52785. int LookAndFeel::getDefaultMenuBarHeight()
  52786. {
  52787. return 24;
  52788. }
  52789. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  52790. {
  52791. return new DropShadower (0.4f, 1, 5, 10);
  52792. }
  52793. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  52794. int w, int h,
  52795. bool /*isVerticalBar*/,
  52796. bool isMouseOver,
  52797. bool isMouseDragging)
  52798. {
  52799. float alpha = 0.5f;
  52800. if (isMouseOver || isMouseDragging)
  52801. {
  52802. g.fillAll (Colour (0x190000ff));
  52803. alpha = 1.0f;
  52804. }
  52805. const float cx = w * 0.5f;
  52806. const float cy = h * 0.5f;
  52807. const float cr = jmin (w, h) * 0.4f;
  52808. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  52809. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  52810. true));
  52811. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  52812. }
  52813. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  52814. const String& text,
  52815. const Justification& position,
  52816. GroupComponent& group)
  52817. {
  52818. const float textH = 15.0f;
  52819. const float indent = 3.0f;
  52820. const float textEdgeGap = 4.0f;
  52821. float cs = 5.0f;
  52822. Font f (textH);
  52823. Path p;
  52824. float x = indent;
  52825. float y = f.getAscent() - 3.0f;
  52826. float w = jmax (0.0f, width - x * 2.0f);
  52827. float h = jmax (0.0f, height - y - indent);
  52828. cs = jmin (cs, w * 0.5f, h * 0.5f);
  52829. const float cs2 = 2.0f * cs;
  52830. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  52831. float textX = cs + textEdgeGap;
  52832. if (position.testFlags (Justification::horizontallyCentred))
  52833. textX = cs + (w - cs2 - textW) * 0.5f;
  52834. else if (position.testFlags (Justification::right))
  52835. textX = w - cs - textW - textEdgeGap;
  52836. p.startNewSubPath (x + textX + textW, y);
  52837. p.lineTo (x + w - cs, y);
  52838. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  52839. p.lineTo (x + w, y + h - cs);
  52840. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  52841. p.lineTo (x + cs, y + h);
  52842. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  52843. p.lineTo (x, y + cs);
  52844. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  52845. p.lineTo (x + textX, y);
  52846. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  52847. g.setColour (group.findColour (GroupComponent::outlineColourId)
  52848. .withMultipliedAlpha (alpha));
  52849. g.strokePath (p, PathStrokeType (2.0f));
  52850. g.setColour (group.findColour (GroupComponent::textColourId)
  52851. .withMultipliedAlpha (alpha));
  52852. g.setFont (f);
  52853. g.drawText (text,
  52854. roundToInt (x + textX), 0,
  52855. roundToInt (textW),
  52856. roundToInt (textH),
  52857. Justification::centred, true);
  52858. }
  52859. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  52860. {
  52861. return 1 + tabDepth / 3;
  52862. }
  52863. int LookAndFeel::getTabButtonSpaceAroundImage()
  52864. {
  52865. return 4;
  52866. }
  52867. void LookAndFeel::createTabButtonShape (Path& p,
  52868. int width, int height,
  52869. int /*tabIndex*/,
  52870. const String& /*text*/,
  52871. Button& /*button*/,
  52872. TabbedButtonBar::Orientation orientation,
  52873. const bool /*isMouseOver*/,
  52874. const bool /*isMouseDown*/,
  52875. const bool /*isFrontTab*/)
  52876. {
  52877. const float w = (float) width;
  52878. const float h = (float) height;
  52879. float length = w;
  52880. float depth = h;
  52881. if (orientation == TabbedButtonBar::TabsAtLeft
  52882. || orientation == TabbedButtonBar::TabsAtRight)
  52883. {
  52884. swapVariables (length, depth);
  52885. }
  52886. const float indent = (float) getTabButtonOverlap ((int) depth);
  52887. const float overhang = 4.0f;
  52888. if (orientation == TabbedButtonBar::TabsAtLeft)
  52889. {
  52890. p.startNewSubPath (w, 0.0f);
  52891. p.lineTo (0.0f, indent);
  52892. p.lineTo (0.0f, h - indent);
  52893. p.lineTo (w, h);
  52894. p.lineTo (w + overhang, h + overhang);
  52895. p.lineTo (w + overhang, -overhang);
  52896. }
  52897. else if (orientation == TabbedButtonBar::TabsAtRight)
  52898. {
  52899. p.startNewSubPath (0.0f, 0.0f);
  52900. p.lineTo (w, indent);
  52901. p.lineTo (w, h - indent);
  52902. p.lineTo (0.0f, h);
  52903. p.lineTo (-overhang, h + overhang);
  52904. p.lineTo (-overhang, -overhang);
  52905. }
  52906. else if (orientation == TabbedButtonBar::TabsAtBottom)
  52907. {
  52908. p.startNewSubPath (0.0f, 0.0f);
  52909. p.lineTo (indent, h);
  52910. p.lineTo (w - indent, h);
  52911. p.lineTo (w, 0.0f);
  52912. p.lineTo (w + overhang, -overhang);
  52913. p.lineTo (-overhang, -overhang);
  52914. }
  52915. else
  52916. {
  52917. p.startNewSubPath (0.0f, h);
  52918. p.lineTo (indent, 0.0f);
  52919. p.lineTo (w - indent, 0.0f);
  52920. p.lineTo (w, h);
  52921. p.lineTo (w + overhang, h + overhang);
  52922. p.lineTo (-overhang, h + overhang);
  52923. }
  52924. p.closeSubPath();
  52925. p = p.createPathWithRoundedCorners (3.0f);
  52926. }
  52927. void LookAndFeel::fillTabButtonShape (Graphics& g,
  52928. const Path& path,
  52929. const Colour& preferredColour,
  52930. int /*tabIndex*/,
  52931. const String& /*text*/,
  52932. Button& button,
  52933. TabbedButtonBar::Orientation /*orientation*/,
  52934. const bool /*isMouseOver*/,
  52935. const bool /*isMouseDown*/,
  52936. const bool isFrontTab)
  52937. {
  52938. g.setColour (isFrontTab ? preferredColour
  52939. : preferredColour.withMultipliedAlpha (0.9f));
  52940. g.fillPath (path);
  52941. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  52942. : TabbedButtonBar::tabOutlineColourId, false)
  52943. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52944. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  52945. }
  52946. void LookAndFeel::drawTabButtonText (Graphics& g,
  52947. int x, int y, int w, int h,
  52948. const Colour& preferredBackgroundColour,
  52949. int /*tabIndex*/,
  52950. const String& text,
  52951. Button& button,
  52952. TabbedButtonBar::Orientation orientation,
  52953. const bool isMouseOver,
  52954. const bool isMouseDown,
  52955. const bool isFrontTab)
  52956. {
  52957. int length = w;
  52958. int depth = h;
  52959. if (orientation == TabbedButtonBar::TabsAtLeft
  52960. || orientation == TabbedButtonBar::TabsAtRight)
  52961. {
  52962. swapVariables (length, depth);
  52963. }
  52964. Font font (depth * 0.6f);
  52965. font.setUnderline (button.hasKeyboardFocus (false));
  52966. GlyphArrangement textLayout;
  52967. textLayout.addFittedText (font, text.trim(),
  52968. 0.0f, 0.0f, (float) length, (float) depth,
  52969. Justification::centred,
  52970. jmax (1, depth / 12));
  52971. AffineTransform transform;
  52972. if (orientation == TabbedButtonBar::TabsAtLeft)
  52973. {
  52974. transform = transform.rotated (float_Pi * -0.5f)
  52975. .translated ((float) x, (float) (y + h));
  52976. }
  52977. else if (orientation == TabbedButtonBar::TabsAtRight)
  52978. {
  52979. transform = transform.rotated (float_Pi * 0.5f)
  52980. .translated ((float) (x + w), (float) y);
  52981. }
  52982. else
  52983. {
  52984. transform = transform.translated ((float) x, (float) y);
  52985. }
  52986. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  52987. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  52988. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  52989. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  52990. else
  52991. g.setColour (preferredBackgroundColour.contrasting());
  52992. if (! (isMouseOver || isMouseDown))
  52993. g.setOpacity (0.8f);
  52994. if (! button.isEnabled())
  52995. g.setOpacity (0.3f);
  52996. textLayout.draw (g, transform);
  52997. }
  52998. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  52999. const String& text,
  53000. int tabDepth,
  53001. Button&)
  53002. {
  53003. Font f (tabDepth * 0.6f);
  53004. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  53005. }
  53006. void LookAndFeel::drawTabButton (Graphics& g,
  53007. int w, int h,
  53008. const Colour& preferredColour,
  53009. int tabIndex,
  53010. const String& text,
  53011. Button& button,
  53012. TabbedButtonBar::Orientation orientation,
  53013. const bool isMouseOver,
  53014. const bool isMouseDown,
  53015. const bool isFrontTab)
  53016. {
  53017. int length = w;
  53018. int depth = h;
  53019. if (orientation == TabbedButtonBar::TabsAtLeft
  53020. || orientation == TabbedButtonBar::TabsAtRight)
  53021. {
  53022. swapVariables (length, depth);
  53023. }
  53024. Path tabShape;
  53025. createTabButtonShape (tabShape, w, h,
  53026. tabIndex, text, button, orientation,
  53027. isMouseOver, isMouseDown, isFrontTab);
  53028. fillTabButtonShape (g, tabShape, preferredColour,
  53029. tabIndex, text, button, orientation,
  53030. isMouseOver, isMouseDown, isFrontTab);
  53031. const int indent = getTabButtonOverlap (depth);
  53032. int x = 0, y = 0;
  53033. if (orientation == TabbedButtonBar::TabsAtLeft
  53034. || orientation == TabbedButtonBar::TabsAtRight)
  53035. {
  53036. y += indent;
  53037. h -= indent * 2;
  53038. }
  53039. else
  53040. {
  53041. x += indent;
  53042. w -= indent * 2;
  53043. }
  53044. drawTabButtonText (g, x, y, w, h, preferredColour,
  53045. tabIndex, text, button, orientation,
  53046. isMouseOver, isMouseDown, isFrontTab);
  53047. }
  53048. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  53049. int w, int h,
  53050. TabbedButtonBar& tabBar,
  53051. TabbedButtonBar::Orientation orientation)
  53052. {
  53053. const float shadowSize = 0.2f;
  53054. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  53055. Rectangle<int> shadowRect;
  53056. if (orientation == TabbedButtonBar::TabsAtLeft)
  53057. {
  53058. x1 = (float) w;
  53059. x2 = w * (1.0f - shadowSize);
  53060. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  53061. }
  53062. else if (orientation == TabbedButtonBar::TabsAtRight)
  53063. {
  53064. x2 = w * shadowSize;
  53065. shadowRect.setBounds (0, 0, (int) x2, h);
  53066. }
  53067. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53068. {
  53069. y2 = h * shadowSize;
  53070. shadowRect.setBounds (0, 0, w, (int) y2);
  53071. }
  53072. else
  53073. {
  53074. y1 = (float) h;
  53075. y2 = h * (1.0f - shadowSize);
  53076. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  53077. }
  53078. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  53079. Colours::transparentBlack, x2, y2, false));
  53080. shadowRect.expand (2, 2);
  53081. g.fillRect (shadowRect);
  53082. g.setColour (Colour (0x80000000));
  53083. if (orientation == TabbedButtonBar::TabsAtLeft)
  53084. {
  53085. g.fillRect (w - 1, 0, 1, h);
  53086. }
  53087. else if (orientation == TabbedButtonBar::TabsAtRight)
  53088. {
  53089. g.fillRect (0, 0, 1, h);
  53090. }
  53091. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53092. {
  53093. g.fillRect (0, 0, w, 1);
  53094. }
  53095. else
  53096. {
  53097. g.fillRect (0, h - 1, w, 1);
  53098. }
  53099. }
  53100. Button* LookAndFeel::createTabBarExtrasButton()
  53101. {
  53102. const float thickness = 7.0f;
  53103. const float indent = 22.0f;
  53104. Path p;
  53105. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  53106. DrawablePath ellipse;
  53107. ellipse.setPath (p);
  53108. ellipse.setFill (Colour (0x99ffffff));
  53109. p.clear();
  53110. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  53111. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  53112. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  53113. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  53114. p.setUsingNonZeroWinding (false);
  53115. DrawablePath dp;
  53116. dp.setPath (p);
  53117. dp.setFill (Colour (0x59000000));
  53118. DrawableComposite normalImage;
  53119. normalImage.insertDrawable (ellipse);
  53120. normalImage.insertDrawable (dp);
  53121. dp.setFill (Colour (0xcc000000));
  53122. DrawableComposite overImage;
  53123. overImage.insertDrawable (ellipse);
  53124. overImage.insertDrawable (dp);
  53125. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  53126. db->setImages (&normalImage, &overImage, 0);
  53127. return db;
  53128. }
  53129. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  53130. {
  53131. g.fillAll (Colours::white);
  53132. const int w = header.getWidth();
  53133. const int h = header.getHeight();
  53134. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  53135. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  53136. false));
  53137. g.fillRect (0, h / 2, w, h);
  53138. g.setColour (Colour (0x33000000));
  53139. g.fillRect (0, h - 1, w, 1);
  53140. for (int i = header.getNumColumns (true); --i >= 0;)
  53141. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  53142. }
  53143. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  53144. int width, int height,
  53145. bool isMouseOver, bool isMouseDown,
  53146. int columnFlags)
  53147. {
  53148. if (isMouseDown)
  53149. g.fillAll (Colour (0x8899aadd));
  53150. else if (isMouseOver)
  53151. g.fillAll (Colour (0x5599aadd));
  53152. int rightOfText = width - 4;
  53153. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  53154. {
  53155. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  53156. const float bottom = height - top;
  53157. const float w = height * 0.5f;
  53158. const float x = rightOfText - (w * 1.25f);
  53159. rightOfText = (int) x;
  53160. Path sortArrow;
  53161. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  53162. g.setColour (Colour (0x99000000));
  53163. g.fillPath (sortArrow);
  53164. }
  53165. g.setColour (Colours::black);
  53166. g.setFont (height * 0.5f, Font::bold);
  53167. const int textX = 4;
  53168. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  53169. }
  53170. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  53171. {
  53172. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  53173. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  53174. background.darker (0.1f),
  53175. toolbar.isVertical() ? w - 1.0f : 0.0f,
  53176. toolbar.isVertical() ? 0.0f : h - 1.0f,
  53177. false));
  53178. g.fillAll();
  53179. }
  53180. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  53181. {
  53182. return createTabBarExtrasButton();
  53183. }
  53184. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  53185. bool isMouseOver, bool isMouseDown,
  53186. ToolbarItemComponent& component)
  53187. {
  53188. if (isMouseDown)
  53189. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  53190. else if (isMouseOver)
  53191. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  53192. }
  53193. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  53194. const String& text, ToolbarItemComponent& component)
  53195. {
  53196. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  53197. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  53198. const float fontHeight = jmin (14.0f, height * 0.85f);
  53199. g.setFont (fontHeight);
  53200. g.drawFittedText (text,
  53201. x, y, width, height,
  53202. Justification::centred,
  53203. jmax (1, height / (int) fontHeight));
  53204. }
  53205. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  53206. bool isOpen, int width, int height)
  53207. {
  53208. const int buttonSize = (height * 3) / 4;
  53209. const int buttonIndent = (height - buttonSize) / 2;
  53210. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  53211. const int textX = buttonIndent * 2 + buttonSize + 2;
  53212. g.setColour (Colours::black);
  53213. g.setFont (height * 0.7f, Font::bold);
  53214. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  53215. }
  53216. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  53217. PropertyComponent&)
  53218. {
  53219. g.setColour (Colour (0x66ffffff));
  53220. g.fillRect (0, 0, width, height - 1);
  53221. }
  53222. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  53223. PropertyComponent& component)
  53224. {
  53225. g.setColour (Colours::black);
  53226. if (! component.isEnabled())
  53227. g.setOpacity (0.6f);
  53228. g.setFont (jmin (height, 24) * 0.65f);
  53229. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  53230. g.drawFittedText (component.getName(),
  53231. 3, r.getY(), r.getX() - 5, r.getHeight(),
  53232. Justification::centredLeft, 2);
  53233. }
  53234. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  53235. {
  53236. return Rectangle<int> (component.getWidth() / 3, 1,
  53237. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  53238. }
  53239. void LookAndFeel::createFileChooserHeaderText (const String& title,
  53240. const String& instructions,
  53241. GlyphArrangement& text,
  53242. int width)
  53243. {
  53244. text.clear();
  53245. text.addJustifiedText (Font (17.0f, Font::bold), title,
  53246. 8.0f, 22.0f, width - 16.0f,
  53247. Justification::centred);
  53248. text.addJustifiedText (Font (14.0f), instructions,
  53249. 8.0f, 24.0f + 16.0f, width - 16.0f,
  53250. Justification::centred);
  53251. }
  53252. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  53253. const String& filename, Image* icon,
  53254. const String& fileSizeDescription,
  53255. const String& fileTimeDescription,
  53256. const bool isDirectory,
  53257. const bool isItemSelected,
  53258. const int /*itemIndex*/)
  53259. {
  53260. if (isItemSelected)
  53261. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  53262. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  53263. g.setFont (height * 0.7f);
  53264. Image* im = icon;
  53265. Image* toRelease = 0;
  53266. if (im == 0)
  53267. {
  53268. toRelease = im = (isDirectory ? getDefaultFolderImage()
  53269. : getDefaultDocumentFileImage());
  53270. }
  53271. const int x = 32;
  53272. if (im != 0)
  53273. {
  53274. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  53275. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  53276. false);
  53277. ImageCache::release (toRelease);
  53278. }
  53279. if (width > 450 && ! isDirectory)
  53280. {
  53281. const int sizeX = roundToInt (width * 0.7f);
  53282. const int dateX = roundToInt (width * 0.8f);
  53283. g.drawFittedText (filename,
  53284. x, 0, sizeX - x, height,
  53285. Justification::centredLeft, 1);
  53286. g.setFont (height * 0.5f);
  53287. g.setColour (Colours::darkgrey);
  53288. if (! isDirectory)
  53289. {
  53290. g.drawFittedText (fileSizeDescription,
  53291. sizeX, 0, dateX - sizeX - 8, height,
  53292. Justification::centredRight, 1);
  53293. g.drawFittedText (fileTimeDescription,
  53294. dateX, 0, width - 8 - dateX, height,
  53295. Justification::centredRight, 1);
  53296. }
  53297. }
  53298. else
  53299. {
  53300. g.drawFittedText (filename,
  53301. x, 0, width - x, height,
  53302. Justification::centredLeft, 1);
  53303. }
  53304. }
  53305. Button* LookAndFeel::createFileBrowserGoUpButton()
  53306. {
  53307. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  53308. Path arrowPath;
  53309. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0f, 40.0f, 100.0f, 50.0f);
  53310. DrawablePath arrowImage;
  53311. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  53312. arrowImage.setPath (arrowPath);
  53313. goUpButton->setImages (&arrowImage);
  53314. return goUpButton;
  53315. }
  53316. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  53317. DirectoryContentsDisplayComponent* fileListComponent,
  53318. FilePreviewComponent* previewComp,
  53319. ComboBox* currentPathBox,
  53320. TextEditor* filenameBox,
  53321. Button* goUpButton)
  53322. {
  53323. const int x = 8;
  53324. int w = browserComp.getWidth() - x - x;
  53325. if (previewComp != 0)
  53326. {
  53327. const int previewWidth = w / 3;
  53328. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  53329. w -= previewWidth + 4;
  53330. }
  53331. int y = 4;
  53332. const int controlsHeight = 22;
  53333. const int bottomSectionHeight = controlsHeight + 8;
  53334. const int upButtonWidth = 50;
  53335. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  53336. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  53337. y += controlsHeight + 4;
  53338. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  53339. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  53340. y = listAsComp->getBottom() + 4;
  53341. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  53342. }
  53343. Image* LookAndFeel::getDefaultFolderImage()
  53344. {
  53345. 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,
  53346. 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,
  53347. 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,
  53348. 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,
  53349. 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,
  53350. 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,
  53351. 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,
  53352. 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,
  53353. 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,
  53354. 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,
  53355. 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,
  53356. 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,
  53357. 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,
  53358. 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,
  53359. 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,
  53360. 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,
  53361. 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,
  53362. 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,
  53363. 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,
  53364. 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,
  53365. 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,
  53366. 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,
  53367. 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,
  53368. 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,
  53369. 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,
  53370. 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,
  53371. 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,
  53372. 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,
  53373. 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,
  53374. 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,
  53375. 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,
  53376. 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,
  53377. 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,
  53378. 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,
  53379. 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,
  53380. 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,
  53381. 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,
  53382. 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,
  53383. 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,
  53384. 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,
  53385. 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,
  53386. 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,
  53387. 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,
  53388. 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};
  53389. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  53390. }
  53391. Image* LookAndFeel::getDefaultDocumentFileImage()
  53392. {
  53393. 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,
  53394. 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,
  53395. 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,
  53396. 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,
  53397. 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,
  53398. 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,
  53399. 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,
  53400. 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,
  53401. 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,
  53402. 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,
  53403. 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,
  53404. 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,
  53405. 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,
  53406. 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,
  53407. 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,
  53408. 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,
  53409. 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,
  53410. 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,
  53411. 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,
  53412. 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,
  53413. 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,
  53414. 174,66,96,130,0,0};
  53415. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  53416. }
  53417. void LookAndFeel::playAlertSound()
  53418. {
  53419. PlatformUtilities::beep();
  53420. }
  53421. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  53422. {
  53423. g.setColour (Colours::white.withAlpha (0.7f));
  53424. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  53425. g.setColour (Colours::black.withAlpha (0.2f));
  53426. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  53427. const int totalBlocks = 7;
  53428. const int numBlocks = roundToInt (totalBlocks * level);
  53429. const float w = (width - 6.0f) / (float) totalBlocks;
  53430. for (int i = 0; i < totalBlocks; ++i)
  53431. {
  53432. if (i >= numBlocks)
  53433. g.setColour (Colours::lightblue.withAlpha (0.6f));
  53434. else
  53435. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  53436. : Colours::red);
  53437. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  53438. }
  53439. }
  53440. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  53441. {
  53442. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  53443. if (keyDescription.isNotEmpty())
  53444. {
  53445. if (button.isEnabled())
  53446. {
  53447. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  53448. g.fillAll (textColour.withAlpha (alpha));
  53449. g.setOpacity (0.3f);
  53450. g.drawBevel (0, 0, width, height, 2);
  53451. }
  53452. g.setColour (textColour);
  53453. g.setFont (height * 0.6f);
  53454. g.drawFittedText (keyDescription,
  53455. 3, 0, width - 6, height,
  53456. Justification::centred, 1);
  53457. }
  53458. else
  53459. {
  53460. const float thickness = 7.0f;
  53461. const float indent = 22.0f;
  53462. Path p;
  53463. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  53464. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  53465. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  53466. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  53467. p.setUsingNonZeroWinding (false);
  53468. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  53469. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  53470. }
  53471. if (button.hasKeyboardFocus (false))
  53472. {
  53473. g.setColour (textColour.withAlpha (0.4f));
  53474. g.drawRect (0, 0, width, height);
  53475. }
  53476. }
  53477. static void createRoundedPath (Path& p,
  53478. const float x, const float y,
  53479. const float w, const float h,
  53480. const float cs,
  53481. const bool curveTopLeft, const bool curveTopRight,
  53482. const bool curveBottomLeft, const bool curveBottomRight) throw()
  53483. {
  53484. const float cs2 = 2.0f * cs;
  53485. if (curveTopLeft)
  53486. {
  53487. p.startNewSubPath (x, y + cs);
  53488. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53489. }
  53490. else
  53491. {
  53492. p.startNewSubPath (x, y);
  53493. }
  53494. if (curveTopRight)
  53495. {
  53496. p.lineTo (x + w - cs, y);
  53497. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  53498. }
  53499. else
  53500. {
  53501. p.lineTo (x + w, y);
  53502. }
  53503. if (curveBottomRight)
  53504. {
  53505. p.lineTo (x + w, y + h - cs);
  53506. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53507. }
  53508. else
  53509. {
  53510. p.lineTo (x + w, y + h);
  53511. }
  53512. if (curveBottomLeft)
  53513. {
  53514. p.lineTo (x + cs, y + h);
  53515. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53516. }
  53517. else
  53518. {
  53519. p.lineTo (x, y + h);
  53520. }
  53521. p.closeSubPath();
  53522. }
  53523. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  53524. float x, float y, float w, float h,
  53525. float maxCornerSize,
  53526. const Colour& baseColour,
  53527. const float strokeWidth,
  53528. const bool flatOnLeft,
  53529. const bool flatOnRight,
  53530. const bool flatOnTop,
  53531. const bool flatOnBottom) throw()
  53532. {
  53533. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  53534. return;
  53535. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  53536. Path outline;
  53537. createRoundedPath (outline, x, y, w, h, cs,
  53538. ! (flatOnLeft || flatOnTop),
  53539. ! (flatOnRight || flatOnTop),
  53540. ! (flatOnLeft || flatOnBottom),
  53541. ! (flatOnRight || flatOnBottom));
  53542. ColourGradient cg (baseColour, 0.0f, y,
  53543. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  53544. false);
  53545. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  53546. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  53547. g.setGradientFill (cg);
  53548. g.fillPath (outline);
  53549. g.setColour (Colour (0x80000000));
  53550. g.strokePath (outline, PathStrokeType (strokeWidth));
  53551. }
  53552. void LookAndFeel::drawGlassSphere (Graphics& g,
  53553. const float x, const float y,
  53554. const float diameter,
  53555. const Colour& colour,
  53556. const float outlineThickness) throw()
  53557. {
  53558. if (diameter <= outlineThickness)
  53559. return;
  53560. Path p;
  53561. p.addEllipse (x, y, diameter, diameter);
  53562. {
  53563. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  53564. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  53565. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  53566. g.setGradientFill (cg);
  53567. g.fillPath (p);
  53568. }
  53569. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  53570. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  53571. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  53572. ColourGradient cg (Colours::transparentBlack,
  53573. x + diameter * 0.5f, y + diameter * 0.5f,
  53574. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  53575. x, y + diameter * 0.5f, true);
  53576. cg.addColour (0.7, Colours::transparentBlack);
  53577. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  53578. g.setGradientFill (cg);
  53579. g.fillPath (p);
  53580. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  53581. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  53582. }
  53583. void LookAndFeel::drawGlassPointer (Graphics& g,
  53584. const float x, const float y,
  53585. const float diameter,
  53586. const Colour& colour, const float outlineThickness,
  53587. const int direction) throw()
  53588. {
  53589. if (diameter <= outlineThickness)
  53590. return;
  53591. Path p;
  53592. p.startNewSubPath (x + diameter * 0.5f, y);
  53593. p.lineTo (x + diameter, y + diameter * 0.6f);
  53594. p.lineTo (x + diameter, y + diameter);
  53595. p.lineTo (x, y + diameter);
  53596. p.lineTo (x, y + diameter * 0.6f);
  53597. p.closeSubPath();
  53598. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  53599. {
  53600. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  53601. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  53602. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  53603. g.setGradientFill (cg);
  53604. g.fillPath (p);
  53605. }
  53606. ColourGradient cg (Colours::transparentBlack,
  53607. x + diameter * 0.5f, y + diameter * 0.5f,
  53608. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  53609. x - diameter * 0.2f, y + diameter * 0.5f, true);
  53610. cg.addColour (0.5, Colours::transparentBlack);
  53611. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  53612. g.setGradientFill (cg);
  53613. g.fillPath (p);
  53614. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  53615. g.strokePath (p, PathStrokeType (outlineThickness));
  53616. }
  53617. void LookAndFeel::drawGlassLozenge (Graphics& g,
  53618. const float x, const float y,
  53619. const float width, const float height,
  53620. const Colour& colour,
  53621. const float outlineThickness,
  53622. const float cornerSize,
  53623. const bool flatOnLeft,
  53624. const bool flatOnRight,
  53625. const bool flatOnTop,
  53626. const bool flatOnBottom) throw()
  53627. {
  53628. if (width <= outlineThickness || height <= outlineThickness)
  53629. return;
  53630. const int intX = (int) x;
  53631. const int intY = (int) y;
  53632. const int intW = (int) width;
  53633. const int intH = (int) height;
  53634. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  53635. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  53636. const int intEdge = (int) edgeBlurRadius;
  53637. Path outline;
  53638. createRoundedPath (outline, x, y, width, height, cs,
  53639. ! (flatOnLeft || flatOnTop),
  53640. ! (flatOnRight || flatOnTop),
  53641. ! (flatOnLeft || flatOnBottom),
  53642. ! (flatOnRight || flatOnBottom));
  53643. {
  53644. ColourGradient cg (colour.darker (0.2f), 0, y,
  53645. colour.darker (0.2f), 0, y + height, false);
  53646. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  53647. cg.addColour (0.4, colour);
  53648. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  53649. g.setGradientFill (cg);
  53650. g.fillPath (outline);
  53651. }
  53652. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  53653. colour.darker (0.2f), x, y + height * 0.5f, true);
  53654. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  53655. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  53656. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  53657. {
  53658. g.saveState();
  53659. g.setGradientFill (cg);
  53660. g.reduceClipRegion (intX, intY, intEdge, intH);
  53661. g.fillPath (outline);
  53662. g.restoreState();
  53663. }
  53664. if (! (flatOnRight || flatOnTop || flatOnBottom))
  53665. {
  53666. cg.x1 = x + width - edgeBlurRadius;
  53667. cg.x2 = x + width;
  53668. g.saveState();
  53669. g.setGradientFill (cg);
  53670. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  53671. g.fillPath (outline);
  53672. g.restoreState();
  53673. }
  53674. {
  53675. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  53676. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  53677. Path highlight;
  53678. createRoundedPath (highlight,
  53679. x + leftIndent,
  53680. y + cs * 0.1f,
  53681. width - (leftIndent + rightIndent),
  53682. height * 0.4f, cs * 0.4f,
  53683. ! (flatOnLeft || flatOnTop),
  53684. ! (flatOnRight || flatOnTop),
  53685. ! (flatOnLeft || flatOnBottom),
  53686. ! (flatOnRight || flatOnBottom));
  53687. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  53688. Colours::transparentWhite, 0, y + height * 0.4f, false));
  53689. g.fillPath (highlight);
  53690. }
  53691. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  53692. g.strokePath (outline, PathStrokeType (outlineThickness));
  53693. }
  53694. END_JUCE_NAMESPACE
  53695. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  53696. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  53697. BEGIN_JUCE_NAMESPACE
  53698. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  53699. {
  53700. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  53701. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  53702. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  53703. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  53704. setColour (Slider::thumbColourId, Colours::white);
  53705. setColour (Slider::trackColourId, Colour (0x7f000000));
  53706. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  53707. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  53708. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  53709. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  53710. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  53711. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  53712. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  53713. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  53714. }
  53715. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  53716. {
  53717. }
  53718. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  53719. Button& button,
  53720. const Colour& backgroundColour,
  53721. bool isMouseOverButton,
  53722. bool isButtonDown)
  53723. {
  53724. const int width = button.getWidth();
  53725. const int height = button.getHeight();
  53726. const float indent = 2.0f;
  53727. const int cornerSize = jmin (roundToInt (width * 0.4f),
  53728. roundToInt (height * 0.4f));
  53729. Path p;
  53730. p.addRoundedRectangle (indent, indent,
  53731. width - indent * 2.0f,
  53732. height - indent * 2.0f,
  53733. (float) cornerSize);
  53734. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  53735. if (isMouseOverButton)
  53736. {
  53737. if (isButtonDown)
  53738. bc = bc.brighter();
  53739. else if (bc.getBrightness() > 0.5f)
  53740. bc = bc.darker (0.1f);
  53741. else
  53742. bc = bc.brighter (0.1f);
  53743. }
  53744. g.setColour (bc);
  53745. g.fillPath (p);
  53746. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  53747. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  53748. }
  53749. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  53750. Component& /*component*/,
  53751. float x, float y, float w, float h,
  53752. const bool ticked,
  53753. const bool isEnabled,
  53754. const bool /*isMouseOverButton*/,
  53755. const bool isButtonDown)
  53756. {
  53757. Path box;
  53758. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  53759. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  53760. : Colours::lightgrey.withAlpha (0.1f));
  53761. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  53762. g.fillPath (box, trans);
  53763. g.setColour (Colours::black.withAlpha (0.6f));
  53764. g.strokePath (box, PathStrokeType (0.9f), trans);
  53765. if (ticked)
  53766. {
  53767. Path tick;
  53768. tick.startNewSubPath (1.5f, 3.0f);
  53769. tick.lineTo (3.0f, 6.0f);
  53770. tick.lineTo (6.0f, 0.0f);
  53771. g.setColour (isEnabled ? Colours::black : Colours::grey);
  53772. g.strokePath (tick, PathStrokeType (2.5f), trans);
  53773. }
  53774. }
  53775. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  53776. ToggleButton& button,
  53777. bool isMouseOverButton,
  53778. bool isButtonDown)
  53779. {
  53780. if (button.hasKeyboardFocus (true))
  53781. {
  53782. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  53783. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  53784. }
  53785. const int tickWidth = jmin (20, button.getHeight() - 4);
  53786. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  53787. (float) tickWidth, (float) tickWidth,
  53788. button.getToggleState(),
  53789. button.isEnabled(),
  53790. isMouseOverButton,
  53791. isButtonDown);
  53792. g.setColour (button.findColour (ToggleButton::textColourId));
  53793. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  53794. if (! button.isEnabled())
  53795. g.setOpacity (0.5f);
  53796. const int textX = tickWidth + 5;
  53797. g.drawFittedText (button.getButtonText(),
  53798. textX, 4,
  53799. button.getWidth() - textX - 2, button.getHeight() - 8,
  53800. Justification::centredLeft, 10);
  53801. }
  53802. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  53803. int width, int height,
  53804. double progress, const String& textToShow)
  53805. {
  53806. if (progress < 0 || progress >= 1.0)
  53807. {
  53808. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  53809. }
  53810. else
  53811. {
  53812. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  53813. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  53814. g.fillAll (background);
  53815. g.setColour (foreground);
  53816. g.fillRect (1, 1,
  53817. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  53818. height - 2);
  53819. if (textToShow.isNotEmpty())
  53820. {
  53821. g.setColour (Colour::contrasting (background, foreground));
  53822. g.setFont (height * 0.6f);
  53823. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  53824. }
  53825. }
  53826. }
  53827. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  53828. ScrollBar& bar,
  53829. int width, int height,
  53830. int buttonDirection,
  53831. bool isScrollbarVertical,
  53832. bool isMouseOverButton,
  53833. bool isButtonDown)
  53834. {
  53835. if (isScrollbarVertical)
  53836. width -= 2;
  53837. else
  53838. height -= 2;
  53839. Path p;
  53840. if (buttonDirection == 0)
  53841. p.addTriangle (width * 0.5f, height * 0.2f,
  53842. width * 0.1f, height * 0.7f,
  53843. width * 0.9f, height * 0.7f);
  53844. else if (buttonDirection == 1)
  53845. p.addTriangle (width * 0.8f, height * 0.5f,
  53846. width * 0.3f, height * 0.1f,
  53847. width * 0.3f, height * 0.9f);
  53848. else if (buttonDirection == 2)
  53849. p.addTriangle (width * 0.5f, height * 0.8f,
  53850. width * 0.1f, height * 0.3f,
  53851. width * 0.9f, height * 0.3f);
  53852. else if (buttonDirection == 3)
  53853. p.addTriangle (width * 0.2f, height * 0.5f,
  53854. width * 0.7f, height * 0.1f,
  53855. width * 0.7f, height * 0.9f);
  53856. if (isButtonDown)
  53857. g.setColour (Colours::white);
  53858. else if (isMouseOverButton)
  53859. g.setColour (Colours::white.withAlpha (0.7f));
  53860. else
  53861. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  53862. g.fillPath (p);
  53863. g.setColour (Colours::black.withAlpha (0.5f));
  53864. g.strokePath (p, PathStrokeType (0.5f));
  53865. }
  53866. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  53867. ScrollBar& bar,
  53868. int x, int y,
  53869. int width, int height,
  53870. bool isScrollbarVertical,
  53871. int thumbStartPosition,
  53872. int thumbSize,
  53873. bool isMouseOver,
  53874. bool isMouseDown)
  53875. {
  53876. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  53877. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  53878. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  53879. if (thumbSize > 0.0f)
  53880. {
  53881. Rectangle<int> thumb;
  53882. if (isScrollbarVertical)
  53883. {
  53884. width -= 2;
  53885. g.fillRect (x + roundToInt (width * 0.35f), y,
  53886. roundToInt (width * 0.3f), height);
  53887. thumb.setBounds (x + 1, thumbStartPosition,
  53888. width - 2, thumbSize);
  53889. }
  53890. else
  53891. {
  53892. height -= 2;
  53893. g.fillRect (x, y + roundToInt (height * 0.35f),
  53894. width, roundToInt (height * 0.3f));
  53895. thumb.setBounds (thumbStartPosition, y + 1,
  53896. thumbSize, height - 2);
  53897. }
  53898. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  53899. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  53900. g.fillRect (thumb);
  53901. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  53902. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  53903. if (thumbSize > 16)
  53904. {
  53905. for (int i = 3; --i >= 0;)
  53906. {
  53907. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  53908. g.setColour (Colours::black.withAlpha (0.15f));
  53909. if (isScrollbarVertical)
  53910. {
  53911. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  53912. g.setColour (Colours::white.withAlpha (0.15f));
  53913. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  53914. }
  53915. else
  53916. {
  53917. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  53918. g.setColour (Colours::white.withAlpha (0.15f));
  53919. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  53920. }
  53921. }
  53922. }
  53923. }
  53924. }
  53925. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  53926. {
  53927. return &scrollbarShadow;
  53928. }
  53929. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  53930. {
  53931. g.fillAll (findColour (PopupMenu::backgroundColourId));
  53932. g.setColour (Colours::black.withAlpha (0.6f));
  53933. g.drawRect (0, 0, width, height);
  53934. }
  53935. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  53936. bool, MenuBarComponent& menuBar)
  53937. {
  53938. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  53939. }
  53940. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  53941. {
  53942. if (textEditor.isEnabled())
  53943. {
  53944. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  53945. g.drawRect (0, 0, width, height);
  53946. }
  53947. }
  53948. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  53949. const bool isButtonDown,
  53950. int buttonX, int buttonY,
  53951. int buttonW, int buttonH,
  53952. ComboBox& box)
  53953. {
  53954. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  53955. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  53956. : ComboBox::backgroundColourId));
  53957. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  53958. g.setColour (box.findColour (ComboBox::outlineColourId));
  53959. g.drawRect (0, 0, width, height);
  53960. const float arrowX = 0.2f;
  53961. const float arrowH = 0.3f;
  53962. if (box.isEnabled())
  53963. {
  53964. Path p;
  53965. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  53966. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  53967. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  53968. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  53969. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  53970. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  53971. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  53972. : ComboBox::buttonColourId));
  53973. g.fillPath (p);
  53974. }
  53975. }
  53976. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  53977. {
  53978. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  53979. f.setHorizontalScale (0.9f);
  53980. return f;
  53981. }
  53982. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  53983. {
  53984. Path p;
  53985. p.addTriangle (x1, y1, x2, y2, x3, y3);
  53986. g.setColour (fill);
  53987. g.fillPath (p);
  53988. g.setColour (outline);
  53989. g.strokePath (p, PathStrokeType (0.3f));
  53990. }
  53991. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  53992. int x, int y,
  53993. int w, int h,
  53994. float sliderPos,
  53995. float minSliderPos,
  53996. float maxSliderPos,
  53997. const Slider::SliderStyle style,
  53998. Slider& slider)
  53999. {
  54000. g.fillAll (slider.findColour (Slider::backgroundColourId));
  54001. if (style == Slider::LinearBar)
  54002. {
  54003. g.setColour (slider.findColour (Slider::thumbColourId));
  54004. g.fillRect (x, y, (int) sliderPos - x, h);
  54005. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  54006. g.drawRect (x, y, (int) sliderPos - x, h);
  54007. }
  54008. else
  54009. {
  54010. g.setColour (slider.findColour (Slider::trackColourId)
  54011. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  54012. if (slider.isHorizontal())
  54013. {
  54014. g.fillRect (x, y + roundToInt (h * 0.6f),
  54015. w, roundToInt (h * 0.2f));
  54016. }
  54017. else
  54018. {
  54019. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  54020. jmin (4, roundToInt (w * 0.2f)), h);
  54021. }
  54022. float alpha = 0.35f;
  54023. if (slider.isEnabled())
  54024. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  54025. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  54026. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  54027. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  54028. {
  54029. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  54030. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  54031. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  54032. fill, outline);
  54033. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  54034. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  54035. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  54036. fill, outline);
  54037. }
  54038. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  54039. {
  54040. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54041. minSliderPos - 7.0f, y + h * 0.9f ,
  54042. minSliderPos, y + h * 0.9f,
  54043. fill, outline);
  54044. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54045. maxSliderPos, y + h * 0.9f,
  54046. maxSliderPos + 7.0f, y + h * 0.9f,
  54047. fill, outline);
  54048. }
  54049. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  54050. {
  54051. drawTriangle (g, sliderPos, y + h * 0.9f,
  54052. sliderPos - 7.0f, y + h * 0.2f,
  54053. sliderPos + 7.0f, y + h * 0.2f,
  54054. fill, outline);
  54055. }
  54056. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  54057. {
  54058. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  54059. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  54060. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  54061. fill, outline);
  54062. }
  54063. }
  54064. }
  54065. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  54066. {
  54067. if (isIncrement)
  54068. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  54069. else
  54070. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  54071. }
  54072. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  54073. {
  54074. return &scrollbarShadow;
  54075. }
  54076. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  54077. {
  54078. return 8;
  54079. }
  54080. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  54081. int w, int h,
  54082. bool isMouseOver,
  54083. bool isMouseDragging)
  54084. {
  54085. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  54086. : Colours::darkgrey);
  54087. const float lineThickness = jmin (w, h) * 0.1f;
  54088. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  54089. {
  54090. g.drawLine (w * i,
  54091. h + 1.0f,
  54092. w + 1.0f,
  54093. h * i,
  54094. lineThickness);
  54095. }
  54096. }
  54097. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  54098. {
  54099. Path shape;
  54100. if (buttonType == DocumentWindow::closeButton)
  54101. {
  54102. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, 0.35f);
  54103. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, 0.35f);
  54104. ShapeButton* const b = new ShapeButton ("close",
  54105. Colour (0x7fff3333),
  54106. Colour (0xd7ff3333),
  54107. Colour (0xf7ff3333));
  54108. b->setShape (shape, true, true, true);
  54109. return b;
  54110. }
  54111. else if (buttonType == DocumentWindow::minimiseButton)
  54112. {
  54113. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  54114. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  54115. DrawablePath dp;
  54116. dp.setPath (shape);
  54117. dp.setFill (Colours::black.withAlpha (0.3f));
  54118. b->setImages (&dp);
  54119. return b;
  54120. }
  54121. else if (buttonType == DocumentWindow::maximiseButton)
  54122. {
  54123. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, 0.25f);
  54124. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  54125. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  54126. DrawablePath dp;
  54127. dp.setPath (shape);
  54128. dp.setFill (Colours::black.withAlpha (0.3f));
  54129. b->setImages (&dp);
  54130. return b;
  54131. }
  54132. jassertfalse
  54133. return 0;
  54134. }
  54135. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  54136. int titleBarX,
  54137. int titleBarY,
  54138. int titleBarW,
  54139. int titleBarH,
  54140. Button* minimiseButton,
  54141. Button* maximiseButton,
  54142. Button* closeButton,
  54143. bool positionTitleBarButtonsOnLeft)
  54144. {
  54145. titleBarY += titleBarH / 8;
  54146. titleBarH -= titleBarH / 4;
  54147. const int buttonW = titleBarH;
  54148. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  54149. : titleBarX + titleBarW - buttonW - 4;
  54150. if (closeButton != 0)
  54151. {
  54152. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  54153. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  54154. : -(buttonW + buttonW / 5);
  54155. }
  54156. if (positionTitleBarButtonsOnLeft)
  54157. swapVariables (minimiseButton, maximiseButton);
  54158. if (maximiseButton != 0)
  54159. {
  54160. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  54161. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  54162. }
  54163. if (minimiseButton != 0)
  54164. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  54165. }
  54166. END_JUCE_NAMESPACE
  54167. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54168. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  54169. BEGIN_JUCE_NAMESPACE
  54170. class DummyMenuComponent : public Component
  54171. {
  54172. DummyMenuComponent (const DummyMenuComponent&);
  54173. DummyMenuComponent& operator= (const DummyMenuComponent&);
  54174. public:
  54175. DummyMenuComponent() {}
  54176. ~DummyMenuComponent() {}
  54177. void inputAttemptWhenModal()
  54178. {
  54179. exitModalState (0);
  54180. }
  54181. };
  54182. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  54183. : model (0),
  54184. itemUnderMouse (-1),
  54185. currentPopupIndex (-1),
  54186. indexToShowAgain (-1),
  54187. lastMouseX (0),
  54188. lastMouseY (0),
  54189. inModalState (false)
  54190. {
  54191. setRepaintsOnMouseActivity (true);
  54192. setWantsKeyboardFocus (false);
  54193. setMouseClickGrabsKeyboardFocus (false);
  54194. setModel (model_);
  54195. }
  54196. MenuBarComponent::~MenuBarComponent()
  54197. {
  54198. setModel (0);
  54199. Desktop::getInstance().removeGlobalMouseListener (this);
  54200. currentPopup = 0;
  54201. }
  54202. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  54203. {
  54204. if (model != newModel)
  54205. {
  54206. if (model != 0)
  54207. model->removeListener (this);
  54208. model = newModel;
  54209. if (model != 0)
  54210. model->addListener (this);
  54211. repaint();
  54212. menuBarItemsChanged (0);
  54213. }
  54214. }
  54215. void MenuBarComponent::paint (Graphics& g)
  54216. {
  54217. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  54218. getLookAndFeel().drawMenuBarBackground (g,
  54219. getWidth(),
  54220. getHeight(),
  54221. isMouseOverBar,
  54222. *this);
  54223. if (model != 0)
  54224. {
  54225. for (int i = 0; i < menuNames.size(); ++i)
  54226. {
  54227. g.saveState();
  54228. g.setOrigin (xPositions [i], 0);
  54229. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  54230. getLookAndFeel().drawMenuBarItem (g,
  54231. xPositions[i + 1] - xPositions[i],
  54232. getHeight(),
  54233. i,
  54234. menuNames[i],
  54235. i == itemUnderMouse,
  54236. i == currentPopupIndex,
  54237. isMouseOverBar,
  54238. *this);
  54239. g.restoreState();
  54240. }
  54241. }
  54242. }
  54243. void MenuBarComponent::resized()
  54244. {
  54245. xPositions.clear();
  54246. int x = 2;
  54247. xPositions.add (x);
  54248. for (int i = 0; i < menuNames.size(); ++i)
  54249. {
  54250. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  54251. xPositions.add (x);
  54252. }
  54253. }
  54254. int MenuBarComponent::getItemAt (const int x, const int y)
  54255. {
  54256. for (int i = 0; i < xPositions.size(); ++i)
  54257. if (x >= xPositions[i] && x < xPositions[i + 1])
  54258. return reallyContains (x, y, true) ? i : -1;
  54259. return -1;
  54260. }
  54261. void MenuBarComponent::repaintMenuItem (int index)
  54262. {
  54263. if (((unsigned int) index) < (unsigned int) xPositions.size())
  54264. {
  54265. const int x1 = xPositions [index];
  54266. const int x2 = xPositions [index + 1];
  54267. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  54268. }
  54269. }
  54270. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  54271. {
  54272. const int newItem = getItemAt (x, y);
  54273. if (itemUnderMouse != newItem)
  54274. {
  54275. repaintMenuItem (itemUnderMouse);
  54276. itemUnderMouse = newItem;
  54277. repaintMenuItem (itemUnderMouse);
  54278. }
  54279. }
  54280. void MenuBarComponent::hideCurrentMenu()
  54281. {
  54282. currentPopup = 0;
  54283. repaint();
  54284. }
  54285. void MenuBarComponent::showMenu (int index)
  54286. {
  54287. if (index != currentPopupIndex)
  54288. {
  54289. if (inModalState)
  54290. {
  54291. hideCurrentMenu();
  54292. indexToShowAgain = index;
  54293. return;
  54294. }
  54295. indexToShowAgain = -1;
  54296. currentPopupIndex = -1;
  54297. itemUnderMouse = index;
  54298. currentPopup = 0;
  54299. menuBarItemsChanged (0);
  54300. Component::SafePointer<Component> prevFocused (getCurrentlyFocusedComponent());
  54301. Component::SafePointer<Component> deletionChecker (this);
  54302. enterModalState (false);
  54303. inModalState = true;
  54304. int result = 0;
  54305. ApplicationCommandManager* managerOfChosenCommand = 0;
  54306. Desktop::getInstance().addGlobalMouseListener (this);
  54307. for (;;)
  54308. {
  54309. const int x = getScreenX() + xPositions [itemUnderMouse];
  54310. const int w = xPositions [itemUnderMouse + 1] - xPositions [itemUnderMouse];
  54311. currentPopupIndex = itemUnderMouse;
  54312. indexToShowAgain = -1;
  54313. repaint();
  54314. if (((unsigned int) itemUnderMouse) < (unsigned int) menuNames.size())
  54315. {
  54316. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  54317. menuNames [itemUnderMouse]));
  54318. if (m.lookAndFeel == 0)
  54319. m.setLookAndFeel (&getLookAndFeel());
  54320. currentPopup = m.createMenuComponent (x, getScreenY(),
  54321. w, getHeight(),
  54322. 0, w, 0, 0,
  54323. true, this,
  54324. &managerOfChosenCommand,
  54325. this);
  54326. }
  54327. if (currentPopup == 0)
  54328. {
  54329. currentPopup = new DummyMenuComponent();
  54330. addAndMakeVisible (currentPopup);
  54331. }
  54332. currentPopup->enterModalState (false);
  54333. currentPopup->toFront (false); // need to do this after making it modal, or it could
  54334. // be stuck behind other comps that are already modal..
  54335. result = currentPopup->runModalLoop();
  54336. if (deletionChecker == 0)
  54337. return;
  54338. const int lastPopupIndex = currentPopupIndex;
  54339. currentPopup = 0;
  54340. currentPopupIndex = -1;
  54341. if (result != 0)
  54342. {
  54343. topLevelIndexClicked = lastPopupIndex;
  54344. break;
  54345. }
  54346. else if (indexToShowAgain >= 0)
  54347. {
  54348. menuBarItemsChanged (0);
  54349. repaint();
  54350. itemUnderMouse = indexToShowAgain;
  54351. if (((unsigned int) itemUnderMouse) >= (unsigned int) menuNames.size())
  54352. break;
  54353. }
  54354. else
  54355. {
  54356. break;
  54357. }
  54358. }
  54359. Desktop::getInstance().removeGlobalMouseListener (this);
  54360. inModalState = false;
  54361. exitModalState (0);
  54362. if (prevFocused != 0)
  54363. prevFocused->grabKeyboardFocus();
  54364. const Point<int> mousePos (getMouseXYRelative());
  54365. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  54366. repaint();
  54367. if (result != 0)
  54368. {
  54369. if (managerOfChosenCommand != 0)
  54370. {
  54371. ApplicationCommandTarget::InvocationInfo info (result);
  54372. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  54373. managerOfChosenCommand->invoke (info, true);
  54374. }
  54375. postCommandMessage (result);
  54376. }
  54377. }
  54378. }
  54379. void MenuBarComponent::handleCommandMessage (int commandId)
  54380. {
  54381. if (model != 0)
  54382. model->menuItemSelected (commandId, topLevelIndexClicked);
  54383. }
  54384. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  54385. {
  54386. if (e.eventComponent == this)
  54387. updateItemUnderMouse (e.x, e.y);
  54388. }
  54389. void MenuBarComponent::mouseExit (const MouseEvent& e)
  54390. {
  54391. if (e.eventComponent == this)
  54392. updateItemUnderMouse (e.x, e.y);
  54393. }
  54394. void MenuBarComponent::mouseDown (const MouseEvent& e)
  54395. {
  54396. if (currentPopupIndex < 0)
  54397. {
  54398. const MouseEvent e2 (e.getEventRelativeTo (this));
  54399. updateItemUnderMouse (e2.x, e2.y);
  54400. currentPopupIndex = -2;
  54401. showMenu (itemUnderMouse);
  54402. }
  54403. }
  54404. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  54405. {
  54406. const MouseEvent e2 (e.getEventRelativeTo (this));
  54407. const int item = getItemAt (e2.x, e2.y);
  54408. if (item >= 0)
  54409. showMenu (item);
  54410. }
  54411. void MenuBarComponent::mouseUp (const MouseEvent& e)
  54412. {
  54413. const MouseEvent e2 (e.getEventRelativeTo (this));
  54414. updateItemUnderMouse (e2.x, e2.y);
  54415. if (itemUnderMouse < 0 && dynamic_cast <DummyMenuComponent*> (static_cast <Component*> (currentPopup)) != 0)
  54416. hideCurrentMenu();
  54417. }
  54418. void MenuBarComponent::mouseMove (const MouseEvent& e)
  54419. {
  54420. const MouseEvent e2 (e.getEventRelativeTo (this));
  54421. if (lastMouseX != e2.x || lastMouseY != e2.y)
  54422. {
  54423. if (currentPopupIndex >= 0)
  54424. {
  54425. const int item = getItemAt (e2.x, e2.y);
  54426. if (item >= 0)
  54427. showMenu (item);
  54428. }
  54429. else
  54430. {
  54431. updateItemUnderMouse (e2.x, e2.y);
  54432. }
  54433. lastMouseX = e2.x;
  54434. lastMouseY = e2.y;
  54435. }
  54436. }
  54437. bool MenuBarComponent::keyPressed (const KeyPress& key)
  54438. {
  54439. bool used = false;
  54440. const int numMenus = menuNames.size();
  54441. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  54442. if (key.isKeyCode (KeyPress::leftKey))
  54443. {
  54444. showMenu ((currentIndex + numMenus - 1) % numMenus);
  54445. used = true;
  54446. }
  54447. else if (key.isKeyCode (KeyPress::rightKey))
  54448. {
  54449. showMenu ((currentIndex + 1) % numMenus);
  54450. used = true;
  54451. }
  54452. return used;
  54453. }
  54454. void MenuBarComponent::inputAttemptWhenModal()
  54455. {
  54456. hideCurrentMenu();
  54457. }
  54458. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  54459. {
  54460. StringArray newNames;
  54461. if (model != 0)
  54462. newNames = model->getMenuBarNames();
  54463. if (newNames != menuNames)
  54464. {
  54465. menuNames = newNames;
  54466. repaint();
  54467. resized();
  54468. }
  54469. }
  54470. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  54471. const ApplicationCommandTarget::InvocationInfo& info)
  54472. {
  54473. if (model == 0
  54474. || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  54475. return;
  54476. for (int i = 0; i < menuNames.size(); ++i)
  54477. {
  54478. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  54479. if (menu.containsCommandItem (info.commandID))
  54480. {
  54481. itemUnderMouse = i;
  54482. repaintMenuItem (i);
  54483. startTimer (200);
  54484. break;
  54485. }
  54486. }
  54487. }
  54488. void MenuBarComponent::timerCallback()
  54489. {
  54490. stopTimer();
  54491. const Point<int> mousePos (getMouseXYRelative());
  54492. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  54493. }
  54494. END_JUCE_NAMESPACE
  54495. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  54496. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  54497. BEGIN_JUCE_NAMESPACE
  54498. MenuBarModel::MenuBarModel() throw()
  54499. : manager (0)
  54500. {
  54501. }
  54502. MenuBarModel::~MenuBarModel()
  54503. {
  54504. setApplicationCommandManagerToWatch (0);
  54505. }
  54506. void MenuBarModel::menuItemsChanged()
  54507. {
  54508. triggerAsyncUpdate();
  54509. }
  54510. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  54511. {
  54512. if (manager != newManager)
  54513. {
  54514. if (manager != 0)
  54515. manager->removeListener (this);
  54516. manager = newManager;
  54517. if (manager != 0)
  54518. manager->addListener (this);
  54519. }
  54520. }
  54521. void MenuBarModel::addListener (MenuBarModelListener* const newListener) throw()
  54522. {
  54523. listeners.add (newListener);
  54524. }
  54525. void MenuBarModel::removeListener (MenuBarModelListener* const listenerToRemove) throw()
  54526. {
  54527. // Trying to remove a listener that isn't on the list!
  54528. // If this assertion happens because this object is a dangling pointer, make sure you've not
  54529. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  54530. jassert (listeners.contains (listenerToRemove));
  54531. listeners.remove (listenerToRemove);
  54532. }
  54533. void MenuBarModel::handleAsyncUpdate()
  54534. {
  54535. listeners.call (&MenuBarModelListener::menuBarItemsChanged, this);
  54536. }
  54537. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  54538. {
  54539. listeners.call (&MenuBarModelListener::menuCommandInvoked, this, info);
  54540. }
  54541. void MenuBarModel::applicationCommandListChanged()
  54542. {
  54543. menuItemsChanged();
  54544. }
  54545. END_JUCE_NAMESPACE
  54546. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  54547. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  54548. BEGIN_JUCE_NAMESPACE
  54549. class PopupMenu::Item
  54550. {
  54551. public:
  54552. Item()
  54553. : itemId (0), active (true), isSeparator (true), isTicked (false),
  54554. usesColour (false), customComp (0), commandManager (0)
  54555. {
  54556. }
  54557. Item (const int itemId_,
  54558. const String& text_,
  54559. const bool active_,
  54560. const bool isTicked_,
  54561. const Image* im,
  54562. const Colour& textColour_,
  54563. const bool usesColour_,
  54564. PopupMenuCustomComponent* const customComp_,
  54565. const PopupMenu* const subMenu_,
  54566. ApplicationCommandManager* const commandManager_)
  54567. : itemId (itemId_), text (text_), textColour (textColour_),
  54568. active (active_), isSeparator (false), isTicked (isTicked_),
  54569. usesColour (usesColour_), customComp (customComp_),
  54570. commandManager (commandManager_)
  54571. {
  54572. if (subMenu_ != 0)
  54573. subMenu = new PopupMenu (*subMenu_);
  54574. if (im != 0)
  54575. image = im->createCopy();
  54576. if (commandManager_ != 0 && itemId_ != 0)
  54577. {
  54578. String shortcutKey;
  54579. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  54580. ->getKeyPressesAssignedToCommand (itemId_));
  54581. for (int i = 0; i < keyPresses.size(); ++i)
  54582. {
  54583. const String key (keyPresses.getReference(i).getTextDescription());
  54584. if (shortcutKey.isNotEmpty())
  54585. shortcutKey << ", ";
  54586. if (key.length() == 1)
  54587. shortcutKey << "shortcut: '" << key << '\'';
  54588. else
  54589. shortcutKey << key;
  54590. }
  54591. shortcutKey = shortcutKey.trim();
  54592. if (shortcutKey.isNotEmpty())
  54593. text << "<end>" << shortcutKey;
  54594. }
  54595. }
  54596. Item (const Item& other)
  54597. : itemId (other.itemId),
  54598. text (other.text),
  54599. textColour (other.textColour),
  54600. active (other.active),
  54601. isSeparator (other.isSeparator),
  54602. isTicked (other.isTicked),
  54603. usesColour (other.usesColour),
  54604. customComp (other.customComp),
  54605. commandManager (other.commandManager)
  54606. {
  54607. if (other.subMenu != 0)
  54608. subMenu = new PopupMenu (*(other.subMenu));
  54609. if (other.image != 0)
  54610. image = other.image->createCopy();
  54611. }
  54612. ~Item()
  54613. {
  54614. customComp = 0;
  54615. }
  54616. bool canBeTriggered() const throw()
  54617. {
  54618. return active && ! (isSeparator || (subMenu != 0));
  54619. }
  54620. bool hasActiveSubMenu() const throw()
  54621. {
  54622. return active && (subMenu != 0);
  54623. }
  54624. const int itemId;
  54625. String text;
  54626. const Colour textColour;
  54627. const bool active, isSeparator, isTicked, usesColour;
  54628. ScopedPointer <Image> image;
  54629. ReferenceCountedObjectPtr <PopupMenuCustomComponent> customComp;
  54630. ScopedPointer <PopupMenu> subMenu;
  54631. ApplicationCommandManager* const commandManager;
  54632. juce_UseDebuggingNewOperator
  54633. private:
  54634. Item& operator= (const Item&);
  54635. };
  54636. class PopupMenu::ItemComponent : public Component
  54637. {
  54638. public:
  54639. ItemComponent (const PopupMenu::Item& itemInfo_)
  54640. : itemInfo (itemInfo_),
  54641. isHighlighted (false)
  54642. {
  54643. if (itemInfo.customComp != 0)
  54644. addAndMakeVisible (itemInfo.customComp);
  54645. }
  54646. ~ItemComponent()
  54647. {
  54648. if (itemInfo.customComp != 0)
  54649. removeChildComponent (itemInfo.customComp);
  54650. }
  54651. void getIdealSize (int& idealWidth,
  54652. int& idealHeight,
  54653. const int standardItemHeight)
  54654. {
  54655. if (itemInfo.customComp != 0)
  54656. {
  54657. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  54658. }
  54659. else
  54660. {
  54661. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  54662. itemInfo.isSeparator,
  54663. standardItemHeight,
  54664. idealWidth,
  54665. idealHeight);
  54666. }
  54667. }
  54668. void paint (Graphics& g)
  54669. {
  54670. if (itemInfo.customComp == 0)
  54671. {
  54672. String mainText (itemInfo.text);
  54673. String endText;
  54674. const int endIndex = mainText.indexOf ("<end>");
  54675. if (endIndex >= 0)
  54676. {
  54677. endText = mainText.substring (endIndex + 5).trim();
  54678. mainText = mainText.substring (0, endIndex);
  54679. }
  54680. getLookAndFeel()
  54681. .drawPopupMenuItem (g, getWidth(), getHeight(),
  54682. itemInfo.isSeparator,
  54683. itemInfo.active,
  54684. isHighlighted,
  54685. itemInfo.isTicked,
  54686. itemInfo.subMenu != 0,
  54687. mainText, endText,
  54688. itemInfo.image,
  54689. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  54690. }
  54691. }
  54692. void resized()
  54693. {
  54694. if (getNumChildComponents() > 0)
  54695. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  54696. }
  54697. void setHighlighted (bool shouldBeHighlighted)
  54698. {
  54699. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  54700. if (isHighlighted != shouldBeHighlighted)
  54701. {
  54702. isHighlighted = shouldBeHighlighted;
  54703. if (itemInfo.customComp != 0)
  54704. {
  54705. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  54706. itemInfo.customComp->repaint();
  54707. }
  54708. repaint();
  54709. }
  54710. }
  54711. PopupMenu::Item itemInfo;
  54712. juce_UseDebuggingNewOperator
  54713. private:
  54714. bool isHighlighted;
  54715. ItemComponent (const ItemComponent&);
  54716. ItemComponent& operator= (const ItemComponent&);
  54717. };
  54718. namespace PopupMenuSettings
  54719. {
  54720. static const int scrollZone = 24;
  54721. static const int borderSize = 2;
  54722. static const int timerInterval = 50;
  54723. static const int dismissCommandId = 0x6287345f;
  54724. }
  54725. class PopupMenu::Window : public Component,
  54726. private Timer
  54727. {
  54728. public:
  54729. Window()
  54730. : Component ("menu"),
  54731. owner (0),
  54732. currentChild (0),
  54733. activeSubMenu (0),
  54734. menuBarComponent (0),
  54735. managerOfChosenCommand (0),
  54736. minimumWidth (0),
  54737. maximumNumColumns (7),
  54738. standardItemHeight (0),
  54739. isOver (false),
  54740. hasBeenOver (false),
  54741. isDown (false),
  54742. needsToScroll (false),
  54743. hideOnExit (false),
  54744. disableMouseMoves (false),
  54745. hasAnyJuceCompHadFocus (false),
  54746. numColumns (0),
  54747. contentHeight (0),
  54748. childYOffset (0),
  54749. timeEnteredCurrentChildComp (0),
  54750. scrollAcceleration (1.0)
  54751. {
  54752. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  54753. setWantsKeyboardFocus (true);
  54754. setMouseClickGrabsKeyboardFocus (false);
  54755. setOpaque (true);
  54756. setAlwaysOnTop (true);
  54757. Desktop::getInstance().addGlobalMouseListener (this);
  54758. getActiveWindows().add (this);
  54759. }
  54760. ~Window()
  54761. {
  54762. getActiveWindows().removeValue (this);
  54763. Desktop::getInstance().removeGlobalMouseListener (this);
  54764. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  54765. activeSubMenu = 0;
  54766. deleteAllChildren();
  54767. }
  54768. static Window* create (const PopupMenu& menu,
  54769. const bool dismissOnMouseUp,
  54770. Window* const owner_,
  54771. const int minX, const int maxX,
  54772. const int minY, const int maxY,
  54773. const int minimumWidth,
  54774. const int maximumNumColumns,
  54775. const int standardItemHeight,
  54776. const bool alignToRectangle,
  54777. const int itemIdThatMustBeVisible,
  54778. Component* const menuBarComponent,
  54779. ApplicationCommandManager** managerOfChosenCommand,
  54780. Component* const componentAttachedTo)
  54781. {
  54782. if (menu.items.size() > 0)
  54783. {
  54784. int totalItems = 0;
  54785. ScopedPointer <Window> mw (new Window());
  54786. mw->setLookAndFeel (menu.lookAndFeel);
  54787. mw->setWantsKeyboardFocus (false);
  54788. mw->minimumWidth = minimumWidth;
  54789. mw->maximumNumColumns = maximumNumColumns;
  54790. mw->standardItemHeight = standardItemHeight;
  54791. mw->dismissOnMouseUp = dismissOnMouseUp;
  54792. for (int i = 0; i < menu.items.size(); ++i)
  54793. {
  54794. PopupMenu::Item* const item = menu.items.getUnchecked(i);
  54795. mw->addItem (*item);
  54796. ++totalItems;
  54797. }
  54798. if (totalItems > 0)
  54799. {
  54800. mw->owner = owner_;
  54801. mw->menuBarComponent = menuBarComponent;
  54802. mw->managerOfChosenCommand = managerOfChosenCommand;
  54803. mw->componentAttachedTo = componentAttachedTo;
  54804. mw->componentAttachedToOriginal = componentAttachedTo;
  54805. mw->calculateWindowPos (minX, maxX, minY, maxY, alignToRectangle);
  54806. mw->setTopLeftPosition (mw->windowPos.getX(),
  54807. mw->windowPos.getY());
  54808. mw->updateYPositions();
  54809. if (itemIdThatMustBeVisible != 0)
  54810. {
  54811. const int y = minY - mw->windowPos.getY();
  54812. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  54813. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  54814. }
  54815. mw->resizeToBestWindowPos();
  54816. mw->addToDesktop (ComponentPeer::windowIsTemporary
  54817. | mw->getLookAndFeel().getMenuWindowFlags());
  54818. return mw.release();
  54819. }
  54820. }
  54821. return 0;
  54822. }
  54823. void paint (Graphics& g)
  54824. {
  54825. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  54826. }
  54827. void paintOverChildren (Graphics& g)
  54828. {
  54829. if (isScrolling())
  54830. {
  54831. LookAndFeel& lf = getLookAndFeel();
  54832. if (isScrollZoneActive (false))
  54833. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  54834. if (isScrollZoneActive (true))
  54835. {
  54836. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  54837. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  54838. }
  54839. }
  54840. }
  54841. bool isScrollZoneActive (bool bottomOne) const
  54842. {
  54843. return isScrolling()
  54844. && (bottomOne
  54845. ? childYOffset < contentHeight - windowPos.getHeight()
  54846. : childYOffset > 0);
  54847. }
  54848. void addItem (const PopupMenu::Item& item)
  54849. {
  54850. PopupMenu::ItemComponent* const mic = new PopupMenu::ItemComponent (item);
  54851. addAndMakeVisible (mic);
  54852. int itemW = 80;
  54853. int itemH = 16;
  54854. mic->getIdealSize (itemW, itemH, standardItemHeight);
  54855. mic->setSize (itemW, jlimit (2, 600, itemH));
  54856. mic->addMouseListener (this, false);
  54857. }
  54858. // hide this and all sub-comps
  54859. void hide (const PopupMenu::Item* const item)
  54860. {
  54861. if (isVisible())
  54862. {
  54863. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  54864. activeSubMenu = 0;
  54865. currentChild = 0;
  54866. exitModalState (item != 0 ? item->itemId : 0);
  54867. setVisible (false);
  54868. if (item != 0
  54869. && item->commandManager != 0
  54870. && item->itemId != 0)
  54871. {
  54872. *managerOfChosenCommand = item->commandManager;
  54873. }
  54874. }
  54875. }
  54876. void dismissMenu (const PopupMenu::Item* const item)
  54877. {
  54878. if (owner != 0)
  54879. {
  54880. owner->dismissMenu (item);
  54881. }
  54882. else
  54883. {
  54884. if (item != 0)
  54885. {
  54886. // need a copy of this on the stack as the one passed in will get deleted during this call
  54887. const PopupMenu::Item mi (*item);
  54888. hide (&mi);
  54889. }
  54890. else
  54891. {
  54892. hide (0);
  54893. }
  54894. }
  54895. }
  54896. void mouseMove (const MouseEvent&)
  54897. {
  54898. timerCallback();
  54899. }
  54900. void mouseDown (const MouseEvent&)
  54901. {
  54902. timerCallback();
  54903. }
  54904. void mouseDrag (const MouseEvent&)
  54905. {
  54906. timerCallback();
  54907. }
  54908. void mouseUp (const MouseEvent&)
  54909. {
  54910. timerCallback();
  54911. }
  54912. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  54913. {
  54914. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  54915. lastMouse = Point<int> (-1, -1);
  54916. }
  54917. bool keyPressed (const KeyPress& key)
  54918. {
  54919. if (key.isKeyCode (KeyPress::downKey))
  54920. {
  54921. selectNextItem (1);
  54922. }
  54923. else if (key.isKeyCode (KeyPress::upKey))
  54924. {
  54925. selectNextItem (-1);
  54926. }
  54927. else if (key.isKeyCode (KeyPress::leftKey))
  54928. {
  54929. if (owner != 0)
  54930. {
  54931. Component::SafePointer<Window> parentWindow (owner);
  54932. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  54933. hide (0);
  54934. if (parentWindow != 0)
  54935. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  54936. disableTimerUntilMouseMoves();
  54937. }
  54938. else if (menuBarComponent != 0)
  54939. {
  54940. menuBarComponent->keyPressed (key);
  54941. }
  54942. }
  54943. else if (key.isKeyCode (KeyPress::rightKey))
  54944. {
  54945. disableTimerUntilMouseMoves();
  54946. if (showSubMenuFor (currentChild))
  54947. {
  54948. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  54949. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  54950. activeSubMenu->selectNextItem (1);
  54951. }
  54952. else if (menuBarComponent != 0)
  54953. {
  54954. menuBarComponent->keyPressed (key);
  54955. }
  54956. }
  54957. else if (key.isKeyCode (KeyPress::returnKey))
  54958. {
  54959. triggerCurrentlyHighlightedItem();
  54960. }
  54961. else if (key.isKeyCode (KeyPress::escapeKey))
  54962. {
  54963. dismissMenu (0);
  54964. }
  54965. else
  54966. {
  54967. return false;
  54968. }
  54969. return true;
  54970. }
  54971. void inputAttemptWhenModal()
  54972. {
  54973. timerCallback();
  54974. if (! isOverAnyMenu())
  54975. {
  54976. if (componentAttachedTo != 0)
  54977. {
  54978. // we want to dismiss the menu, but if we do it synchronously, then
  54979. // the mouse-click will be allowed to pass through. That's good, except
  54980. // when the user clicks on the button that orginally popped the menu up,
  54981. // as they'll expect the menu to go away, and in fact it'll just
  54982. // come back. So only dismiss synchronously if they're not on the original
  54983. // comp that we're attached to.
  54984. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  54985. if (componentAttachedTo->reallyContains (mousePos.getX(), mousePos.getY(), true))
  54986. {
  54987. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  54988. return;
  54989. }
  54990. }
  54991. dismissMenu (0);
  54992. }
  54993. }
  54994. void handleCommandMessage (int commandId)
  54995. {
  54996. Component::handleCommandMessage (commandId);
  54997. if (commandId == PopupMenuSettings::dismissCommandId)
  54998. dismissMenu (0);
  54999. }
  55000. void timerCallback()
  55001. {
  55002. if (! isVisible())
  55003. return;
  55004. if (componentAttachedTo != componentAttachedToOriginal)
  55005. {
  55006. dismissMenu (0);
  55007. return;
  55008. }
  55009. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  55010. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  55011. return;
  55012. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  55013. // move rather than a real timer callback
  55014. const Point<int> globalMousePos (Desktop::getMousePosition());
  55015. const Point<int> localMousePos (globalPositionToRelative (globalMousePos));
  55016. const uint32 now = Time::getMillisecondCounter();
  55017. if (now > timeEnteredCurrentChildComp + 100
  55018. && reallyContains (localMousePos.getX(), localMousePos.getY(), true)
  55019. && currentChild->isValidComponent()
  55020. && (! disableMouseMoves)
  55021. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  55022. {
  55023. showSubMenuFor (currentChild);
  55024. }
  55025. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  55026. {
  55027. highlightItemUnderMouse (globalMousePos, localMousePos);
  55028. }
  55029. bool overScrollArea = false;
  55030. if (isScrolling()
  55031. && (isOver || (isDown && ((unsigned int) localMousePos.getX()) < (unsigned int) getWidth()))
  55032. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  55033. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  55034. {
  55035. if (now > lastScroll + 20)
  55036. {
  55037. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  55038. int amount = 0;
  55039. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  55040. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  55041. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  55042. lastScroll = now;
  55043. }
  55044. overScrollArea = true;
  55045. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  55046. }
  55047. else
  55048. {
  55049. scrollAcceleration = 1.0;
  55050. }
  55051. const bool wasDown = isDown;
  55052. bool isOverAny = isOverAnyMenu();
  55053. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  55054. {
  55055. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55056. isOverAny = isOverAnyMenu();
  55057. }
  55058. if (hideOnExit && hasBeenOver && ! isOverAny)
  55059. {
  55060. hide (0);
  55061. }
  55062. else
  55063. {
  55064. isDown = hasBeenOver
  55065. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  55066. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  55067. bool anyFocused = Process::isForegroundProcess();
  55068. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  55069. {
  55070. // because no component at all may have focus, our test here will
  55071. // only be triggered when something has focus and then loses it.
  55072. anyFocused = ! hasAnyJuceCompHadFocus;
  55073. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  55074. {
  55075. if (ComponentPeer::getPeer (i)->isFocused())
  55076. {
  55077. anyFocused = true;
  55078. hasAnyJuceCompHadFocus = true;
  55079. break;
  55080. }
  55081. }
  55082. }
  55083. if (! anyFocused)
  55084. {
  55085. if (now > lastFocused + 10)
  55086. {
  55087. wasHiddenBecauseOfAppChange() = true;
  55088. dismissMenu (0);
  55089. return; // may have been deleted by the previous call..
  55090. }
  55091. }
  55092. else if (wasDown && now > menuCreationTime + 250
  55093. && ! (isDown || overScrollArea))
  55094. {
  55095. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  55096. if (isOver)
  55097. {
  55098. triggerCurrentlyHighlightedItem();
  55099. }
  55100. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  55101. {
  55102. dismissMenu (0);
  55103. }
  55104. return; // may have been deleted by the previous calls..
  55105. }
  55106. else
  55107. {
  55108. lastFocused = now;
  55109. }
  55110. }
  55111. }
  55112. static Array<Window*>& getActiveWindows()
  55113. {
  55114. static Array<Window*> activeMenuWindows;
  55115. return activeMenuWindows;
  55116. }
  55117. static bool& wasHiddenBecauseOfAppChange() throw()
  55118. {
  55119. static bool b = false;
  55120. return b;
  55121. }
  55122. juce_UseDebuggingNewOperator
  55123. private:
  55124. Window* owner;
  55125. PopupMenu::ItemComponent* currentChild;
  55126. ScopedPointer <Window> activeSubMenu;
  55127. Component* menuBarComponent;
  55128. ApplicationCommandManager** managerOfChosenCommand;
  55129. Component::SafePointer<Component> componentAttachedTo;
  55130. Component* componentAttachedToOriginal;
  55131. Rectangle<int> windowPos;
  55132. Point<int> lastMouse;
  55133. int minimumWidth, maximumNumColumns, standardItemHeight;
  55134. bool isOver, hasBeenOver, isDown, needsToScroll;
  55135. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  55136. int numColumns, contentHeight, childYOffset;
  55137. Array <int> columnWidths;
  55138. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  55139. double scrollAcceleration;
  55140. bool overlaps (const Rectangle<int>& r) const
  55141. {
  55142. return r.intersects (getBounds())
  55143. || (owner != 0 && owner->overlaps (r));
  55144. }
  55145. bool isOverAnyMenu() const
  55146. {
  55147. return (owner != 0) ? owner->isOverAnyMenu()
  55148. : isOverChildren();
  55149. }
  55150. bool isOverChildren() const
  55151. {
  55152. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55153. return isVisible()
  55154. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  55155. }
  55156. void updateMouseOverStatus (const Point<int>& globalMousePos)
  55157. {
  55158. const Point<int> relPos (globalPositionToRelative (globalMousePos));
  55159. isOver = reallyContains (relPos.getX(), relPos.getY(), true);
  55160. if (activeSubMenu != 0)
  55161. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55162. }
  55163. bool treeContains (const Window* const window) const throw()
  55164. {
  55165. const Window* mw = this;
  55166. while (mw->owner != 0)
  55167. mw = mw->owner;
  55168. while (mw != 0)
  55169. {
  55170. if (mw == window)
  55171. return true;
  55172. mw = mw->activeSubMenu;
  55173. }
  55174. return false;
  55175. }
  55176. void calculateWindowPos (const int minX, const int maxX,
  55177. const int minY, const int maxY,
  55178. const bool alignToRectangle)
  55179. {
  55180. const Rectangle<int> mon (Desktop::getInstance()
  55181. .getMonitorAreaContaining (Point<int> ((minX + maxX) / 2,
  55182. (minY + maxY) / 2),
  55183. #if JUCE_MAC
  55184. true));
  55185. #else
  55186. false)); // on windows, don't stop the menu overlapping the taskbar
  55187. #endif
  55188. int x, y, widthToUse, heightToUse;
  55189. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  55190. if (alignToRectangle)
  55191. {
  55192. x = minX;
  55193. const int spaceUnder = mon.getHeight() - (maxY - mon.getY());
  55194. const int spaceOver = minY - mon.getY();
  55195. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  55196. y = maxY;
  55197. else
  55198. y = minY - heightToUse;
  55199. }
  55200. else
  55201. {
  55202. bool tendTowardsRight = (minX + maxX) / 2 < mon.getCentreX();
  55203. if (owner != 0)
  55204. {
  55205. if (owner->owner != 0)
  55206. {
  55207. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  55208. > owner->owner->getX() + owner->owner->getWidth() / 2);
  55209. if (ownerGoingRight && maxX + widthToUse < mon.getRight() - 4)
  55210. tendTowardsRight = true;
  55211. else if ((! ownerGoingRight) && minX > widthToUse + 4)
  55212. tendTowardsRight = false;
  55213. }
  55214. else if (maxX + widthToUse < mon.getRight() - 32)
  55215. {
  55216. tendTowardsRight = true;
  55217. }
  55218. }
  55219. const int biggestSpace = jmax (mon.getRight() - maxX,
  55220. minX - mon.getX()) - 32;
  55221. if (biggestSpace < widthToUse)
  55222. {
  55223. layoutMenuItems (biggestSpace + (maxX - minX) / 3, widthToUse, heightToUse);
  55224. if (numColumns > 1)
  55225. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  55226. tendTowardsRight = (mon.getRight() - maxX) >= (minX - mon.getX());
  55227. }
  55228. if (tendTowardsRight)
  55229. x = jmin (mon.getRight() - widthToUse - 4, maxX);
  55230. else
  55231. x = jmax (mon.getX() + 4, minX - widthToUse);
  55232. y = minY;
  55233. if ((minY + maxY) / 2 > mon.getCentreY())
  55234. y = jmax (mon.getY(), maxY - heightToUse);
  55235. }
  55236. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  55237. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  55238. windowPos.setBounds (x, y, widthToUse, heightToUse);
  55239. // sets this flag if it's big enough to obscure any of its parent menus
  55240. hideOnExit = (owner != 0)
  55241. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  55242. }
  55243. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  55244. {
  55245. numColumns = 0;
  55246. contentHeight = 0;
  55247. const int maxMenuH = getParentHeight() - 24;
  55248. int totalW;
  55249. do
  55250. {
  55251. ++numColumns;
  55252. totalW = workOutBestSize (maxMenuW);
  55253. if (totalW > maxMenuW)
  55254. {
  55255. numColumns = jmax (1, numColumns - 1);
  55256. totalW = workOutBestSize (maxMenuW); // to update col widths
  55257. break;
  55258. }
  55259. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  55260. {
  55261. break;
  55262. }
  55263. } while (numColumns < maximumNumColumns);
  55264. const int actualH = jmin (contentHeight, maxMenuH);
  55265. needsToScroll = contentHeight > actualH;
  55266. width = updateYPositions();
  55267. height = actualH + PopupMenuSettings::borderSize * 2;
  55268. }
  55269. int workOutBestSize (const int maxMenuW)
  55270. {
  55271. int totalW = 0;
  55272. contentHeight = 0;
  55273. int childNum = 0;
  55274. for (int col = 0; col < numColumns; ++col)
  55275. {
  55276. int i, colW = 50, colH = 0;
  55277. const int numChildren = jmin (getNumChildComponents() - childNum,
  55278. (getNumChildComponents() + numColumns - 1) / numColumns);
  55279. for (i = numChildren; --i >= 0;)
  55280. {
  55281. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  55282. colH += getChildComponent (childNum + i)->getHeight();
  55283. }
  55284. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  55285. columnWidths.set (col, colW);
  55286. totalW += colW;
  55287. contentHeight = jmax (contentHeight, colH);
  55288. childNum += numChildren;
  55289. }
  55290. if (totalW < minimumWidth)
  55291. {
  55292. totalW = minimumWidth;
  55293. for (int col = 0; col < numColumns; ++col)
  55294. columnWidths.set (0, totalW / numColumns);
  55295. }
  55296. return totalW;
  55297. }
  55298. void ensureItemIsVisible (const int itemId, int wantedY)
  55299. {
  55300. jassert (itemId != 0)
  55301. for (int i = getNumChildComponents(); --i >= 0;)
  55302. {
  55303. PopupMenu::ItemComponent* const m = static_cast <PopupMenu::ItemComponent*> (getChildComponent (i));
  55304. if (m != 0
  55305. && m->itemInfo.itemId == itemId
  55306. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  55307. {
  55308. const int currentY = m->getY();
  55309. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  55310. {
  55311. if (wantedY < 0)
  55312. wantedY = jlimit (PopupMenuSettings::scrollZone,
  55313. jmax (PopupMenuSettings::scrollZone,
  55314. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  55315. currentY);
  55316. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  55317. int deltaY = wantedY - currentY;
  55318. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  55319. jmin (windowPos.getHeight(), mon.getHeight()));
  55320. const int newY = jlimit (mon.getY(),
  55321. mon.getBottom() - windowPos.getHeight(),
  55322. windowPos.getY() + deltaY);
  55323. deltaY -= newY - windowPos.getY();
  55324. childYOffset -= deltaY;
  55325. windowPos.setPosition (windowPos.getX(), newY);
  55326. updateYPositions();
  55327. }
  55328. break;
  55329. }
  55330. }
  55331. }
  55332. void resizeToBestWindowPos()
  55333. {
  55334. Rectangle<int> r (windowPos);
  55335. if (childYOffset < 0)
  55336. {
  55337. r.setBounds (r.getX(), r.getY() - childYOffset,
  55338. r.getWidth(), r.getHeight() + childYOffset);
  55339. }
  55340. else if (childYOffset > 0)
  55341. {
  55342. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  55343. if (spaceAtBottom > 0)
  55344. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  55345. }
  55346. setBounds (r);
  55347. updateYPositions();
  55348. }
  55349. void alterChildYPos (const int delta)
  55350. {
  55351. if (isScrolling())
  55352. {
  55353. childYOffset += delta;
  55354. if (delta < 0)
  55355. {
  55356. childYOffset = jmax (childYOffset, 0);
  55357. }
  55358. else if (delta > 0)
  55359. {
  55360. childYOffset = jmin (childYOffset,
  55361. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  55362. }
  55363. updateYPositions();
  55364. }
  55365. else
  55366. {
  55367. childYOffset = 0;
  55368. }
  55369. resizeToBestWindowPos();
  55370. repaint();
  55371. }
  55372. int updateYPositions()
  55373. {
  55374. int x = 0;
  55375. int childNum = 0;
  55376. for (int col = 0; col < numColumns; ++col)
  55377. {
  55378. const int numChildren = jmin (getNumChildComponents() - childNum,
  55379. (getNumChildComponents() + numColumns - 1) / numColumns);
  55380. const int colW = columnWidths [col];
  55381. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  55382. for (int i = 0; i < numChildren; ++i)
  55383. {
  55384. Component* const c = getChildComponent (childNum + i);
  55385. c->setBounds (x, y, colW, c->getHeight());
  55386. y += c->getHeight();
  55387. }
  55388. x += colW;
  55389. childNum += numChildren;
  55390. }
  55391. return x;
  55392. }
  55393. bool isScrolling() const throw()
  55394. {
  55395. return childYOffset != 0 || needsToScroll;
  55396. }
  55397. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  55398. {
  55399. if (currentChild->isValidComponent())
  55400. currentChild->setHighlighted (false);
  55401. currentChild = child;
  55402. if (currentChild != 0)
  55403. {
  55404. currentChild->setHighlighted (true);
  55405. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  55406. }
  55407. }
  55408. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  55409. {
  55410. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55411. activeSubMenu = 0;
  55412. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  55413. {
  55414. const Point<int> topLeft (childComp->relativePositionToGlobal (Point<int>()));
  55415. const Point<int> bottomRight (childComp->relativePositionToGlobal (Point<int> (childComp->getWidth(), childComp->getHeight())));
  55416. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  55417. dismissOnMouseUp,
  55418. this,
  55419. topLeft.getX(), bottomRight.getX(), topLeft.getY(), bottomRight.getY(),
  55420. 0, maximumNumColumns,
  55421. standardItemHeight,
  55422. false, 0, menuBarComponent,
  55423. managerOfChosenCommand,
  55424. componentAttachedTo);
  55425. if (activeSubMenu != 0)
  55426. {
  55427. activeSubMenu->setVisible (true);
  55428. activeSubMenu->enterModalState (false);
  55429. activeSubMenu->toFront (false);
  55430. return true;
  55431. }
  55432. }
  55433. return false;
  55434. }
  55435. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  55436. {
  55437. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  55438. if (isOver)
  55439. hasBeenOver = true;
  55440. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  55441. {
  55442. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  55443. if (disableMouseMoves && isOver)
  55444. disableMouseMoves = false;
  55445. }
  55446. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  55447. return;
  55448. bool isMovingTowardsMenu = false;
  55449. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  55450. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  55451. {
  55452. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  55453. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  55454. // extends from the last mouse pos to the submenu's rectangle..
  55455. float subX = (float) activeSubMenu->getScreenX();
  55456. if (activeSubMenu->getX() > getX())
  55457. {
  55458. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  55459. }
  55460. else
  55461. {
  55462. lastMouse += Point<int> (2, 0);
  55463. subX += activeSubMenu->getWidth();
  55464. }
  55465. Path areaTowardsSubMenu;
  55466. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(),
  55467. (float) lastMouse.getY(),
  55468. subX,
  55469. (float) activeSubMenu->getScreenY(),
  55470. subX,
  55471. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  55472. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  55473. }
  55474. lastMouse = globalMousePos;
  55475. if (! isMovingTowardsMenu)
  55476. {
  55477. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  55478. if (c == this)
  55479. c = 0;
  55480. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  55481. if (mic == 0 && c != 0)
  55482. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  55483. if (mic != currentChild
  55484. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  55485. {
  55486. if (isOver && (c != 0) && (activeSubMenu != 0))
  55487. {
  55488. activeSubMenu->hide (0);
  55489. }
  55490. if (! isOver)
  55491. mic = 0;
  55492. setCurrentlyHighlightedChild (mic);
  55493. }
  55494. }
  55495. }
  55496. void triggerCurrentlyHighlightedItem()
  55497. {
  55498. if (currentChild->isValidComponent()
  55499. && currentChild->itemInfo.canBeTriggered()
  55500. && (currentChild->itemInfo.customComp == 0
  55501. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  55502. {
  55503. dismissMenu (&currentChild->itemInfo);
  55504. }
  55505. }
  55506. void selectNextItem (const int delta)
  55507. {
  55508. disableTimerUntilMouseMoves();
  55509. PopupMenu::ItemComponent* mic = 0;
  55510. bool wasLastOne = (currentChild == 0);
  55511. const int numItems = getNumChildComponents();
  55512. for (int i = 0; i < numItems + 1; ++i)
  55513. {
  55514. int index = (delta > 0) ? i : (numItems - 1 - i);
  55515. index = (index + numItems) % numItems;
  55516. mic = dynamic_cast <PopupMenu::ItemComponent*> (getChildComponent (index));
  55517. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  55518. && wasLastOne)
  55519. break;
  55520. if (mic == currentChild)
  55521. wasLastOne = true;
  55522. }
  55523. setCurrentlyHighlightedChild (mic);
  55524. }
  55525. void disableTimerUntilMouseMoves()
  55526. {
  55527. disableMouseMoves = true;
  55528. if (owner != 0)
  55529. owner->disableTimerUntilMouseMoves();
  55530. }
  55531. Window (const Window&);
  55532. Window& operator= (const Window&);
  55533. };
  55534. PopupMenu::PopupMenu()
  55535. : lookAndFeel (0),
  55536. separatorPending (false)
  55537. {
  55538. }
  55539. PopupMenu::PopupMenu (const PopupMenu& other)
  55540. : lookAndFeel (other.lookAndFeel),
  55541. separatorPending (false)
  55542. {
  55543. items.ensureStorageAllocated (other.items.size());
  55544. for (int i = 0; i < other.items.size(); ++i)
  55545. items.add (new Item (*other.items.getUnchecked(i)));
  55546. }
  55547. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  55548. {
  55549. if (this != &other)
  55550. {
  55551. lookAndFeel = other.lookAndFeel;
  55552. clear();
  55553. items.ensureStorageAllocated (other.items.size());
  55554. for (int i = 0; i < other.items.size(); ++i)
  55555. items.add (new Item (*other.items.getUnchecked(i)));
  55556. }
  55557. return *this;
  55558. }
  55559. PopupMenu::~PopupMenu()
  55560. {
  55561. clear();
  55562. }
  55563. void PopupMenu::clear()
  55564. {
  55565. items.clear();
  55566. separatorPending = false;
  55567. }
  55568. void PopupMenu::addSeparatorIfPending()
  55569. {
  55570. if (separatorPending)
  55571. {
  55572. separatorPending = false;
  55573. if (items.size() > 0)
  55574. items.add (new Item());
  55575. }
  55576. }
  55577. void PopupMenu::addItem (const int itemResultId,
  55578. const String& itemText,
  55579. const bool isActive,
  55580. const bool isTicked,
  55581. const Image* const iconToUse)
  55582. {
  55583. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55584. // didn't pick anything, so you shouldn't use it as the id
  55585. // for an item..
  55586. addSeparatorIfPending();
  55587. items.add (new Item (itemResultId, itemText, isActive, isTicked,
  55588. iconToUse, Colours::black, false, 0, 0, 0));
  55589. }
  55590. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  55591. const int commandID,
  55592. const String& displayName)
  55593. {
  55594. jassert (commandManager != 0 && commandID != 0);
  55595. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  55596. if (registeredInfo != 0)
  55597. {
  55598. ApplicationCommandInfo info (*registeredInfo);
  55599. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  55600. addSeparatorIfPending();
  55601. items.add (new Item (commandID,
  55602. displayName.isNotEmpty() ? displayName
  55603. : info.shortName,
  55604. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  55605. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  55606. 0,
  55607. Colours::black,
  55608. false,
  55609. 0, 0,
  55610. commandManager));
  55611. }
  55612. }
  55613. void PopupMenu::addColouredItem (const int itemResultId,
  55614. const String& itemText,
  55615. const Colour& itemTextColour,
  55616. const bool isActive,
  55617. const bool isTicked,
  55618. const Image* const iconToUse)
  55619. {
  55620. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55621. // didn't pick anything, so you shouldn't use it as the id
  55622. // for an item..
  55623. addSeparatorIfPending();
  55624. items.add (new Item (itemResultId, itemText, isActive, isTicked,
  55625. iconToUse, itemTextColour, true, 0, 0, 0));
  55626. }
  55627. void PopupMenu::addCustomItem (const int itemResultId,
  55628. PopupMenuCustomComponent* const customComponent)
  55629. {
  55630. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55631. // didn't pick anything, so you shouldn't use it as the id
  55632. // for an item..
  55633. addSeparatorIfPending();
  55634. items.add (new Item (itemResultId, String::empty, true, false, 0,
  55635. Colours::black, false, customComponent, 0, 0));
  55636. }
  55637. class NormalComponentWrapper : public PopupMenuCustomComponent
  55638. {
  55639. public:
  55640. NormalComponentWrapper (Component* const comp,
  55641. const int w, const int h,
  55642. const bool triggerMenuItemAutomaticallyWhenClicked)
  55643. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  55644. width (w),
  55645. height (h)
  55646. {
  55647. addAndMakeVisible (comp);
  55648. }
  55649. ~NormalComponentWrapper() {}
  55650. void getIdealSize (int& idealWidth, int& idealHeight)
  55651. {
  55652. idealWidth = width;
  55653. idealHeight = height;
  55654. }
  55655. void resized()
  55656. {
  55657. if (getChildComponent(0) != 0)
  55658. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  55659. }
  55660. juce_UseDebuggingNewOperator
  55661. private:
  55662. const int width, height;
  55663. NormalComponentWrapper (const NormalComponentWrapper&);
  55664. NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  55665. };
  55666. void PopupMenu::addCustomItem (const int itemResultId,
  55667. Component* customComponent,
  55668. int idealWidth, int idealHeight,
  55669. const bool triggerMenuItemAutomaticallyWhenClicked)
  55670. {
  55671. addCustomItem (itemResultId,
  55672. new NormalComponentWrapper (customComponent,
  55673. idealWidth, idealHeight,
  55674. triggerMenuItemAutomaticallyWhenClicked));
  55675. }
  55676. void PopupMenu::addSubMenu (const String& subMenuName,
  55677. const PopupMenu& subMenu,
  55678. const bool isActive,
  55679. Image* const iconToUse,
  55680. const bool isTicked)
  55681. {
  55682. addSeparatorIfPending();
  55683. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  55684. iconToUse, Colours::black, false, 0, &subMenu, 0));
  55685. }
  55686. void PopupMenu::addSeparator()
  55687. {
  55688. separatorPending = true;
  55689. }
  55690. class HeaderItemComponent : public PopupMenuCustomComponent
  55691. {
  55692. public:
  55693. HeaderItemComponent (const String& name)
  55694. : PopupMenuCustomComponent (false)
  55695. {
  55696. setName (name);
  55697. }
  55698. ~HeaderItemComponent()
  55699. {
  55700. }
  55701. void paint (Graphics& g)
  55702. {
  55703. Font f (getLookAndFeel().getPopupMenuFont());
  55704. f.setBold (true);
  55705. g.setFont (f);
  55706. g.setColour (findColour (PopupMenu::headerTextColourId));
  55707. g.drawFittedText (getName(),
  55708. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  55709. Justification::bottomLeft, 1);
  55710. }
  55711. void getIdealSize (int& idealWidth,
  55712. int& idealHeight)
  55713. {
  55714. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  55715. idealHeight += idealHeight / 2;
  55716. idealWidth += idealWidth / 4;
  55717. }
  55718. juce_UseDebuggingNewOperator
  55719. };
  55720. void PopupMenu::addSectionHeader (const String& title)
  55721. {
  55722. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  55723. }
  55724. Component* PopupMenu::createMenuComponent (const int x, const int y, const int w, const int h,
  55725. const int itemIdThatMustBeVisible,
  55726. const int minimumWidth,
  55727. const int maximumNumColumns,
  55728. const int standardItemHeight,
  55729. const bool alignToRectangle,
  55730. Component* menuBarComponent,
  55731. ApplicationCommandManager** managerOfChosenCommand,
  55732. Component* const componentAttachedTo)
  55733. {
  55734. Window* const pw
  55735. = Window::create (*this,
  55736. ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  55737. 0,
  55738. x, x + w,
  55739. y, y + h,
  55740. minimumWidth,
  55741. maximumNumColumns,
  55742. standardItemHeight,
  55743. alignToRectangle,
  55744. itemIdThatMustBeVisible,
  55745. menuBarComponent,
  55746. managerOfChosenCommand,
  55747. componentAttachedTo);
  55748. if (pw != 0)
  55749. pw->setVisible (true);
  55750. return pw;
  55751. }
  55752. int PopupMenu::showMenu (const int x, const int y, const int w, const int h,
  55753. const int itemIdThatMustBeVisible,
  55754. const int minimumWidth,
  55755. const int maximumNumColumns,
  55756. const int standardItemHeight,
  55757. const bool alignToRectangle,
  55758. Component* const componentAttachedTo)
  55759. {
  55760. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  55761. Component::SafePointer<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  55762. Window::wasHiddenBecauseOfAppChange() = false;
  55763. int result = 0;
  55764. ApplicationCommandManager* managerOfChosenCommand = 0;
  55765. ScopedPointer <Component> popupComp (createMenuComponent (x, y, w, h,
  55766. itemIdThatMustBeVisible,
  55767. minimumWidth,
  55768. maximumNumColumns > 0 ? maximumNumColumns : 7,
  55769. standardItemHeight,
  55770. alignToRectangle, 0,
  55771. &managerOfChosenCommand,
  55772. componentAttachedTo));
  55773. if (popupComp != 0)
  55774. {
  55775. popupComp->enterModalState (false);
  55776. popupComp->toFront (false); // need to do this after making it modal, or it could
  55777. // be stuck behind other comps that are already modal..
  55778. result = popupComp->runModalLoop();
  55779. popupComp = 0;
  55780. if (! Window::wasHiddenBecauseOfAppChange())
  55781. {
  55782. if (prevTopLevel != 0)
  55783. prevTopLevel->toFront (true);
  55784. if (prevFocused != 0)
  55785. prevFocused->grabKeyboardFocus();
  55786. }
  55787. }
  55788. if (managerOfChosenCommand != 0 && result != 0)
  55789. {
  55790. ApplicationCommandTarget::InvocationInfo info (result);
  55791. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  55792. managerOfChosenCommand->invoke (info, true);
  55793. }
  55794. return result;
  55795. }
  55796. int PopupMenu::show (const int itemIdThatMustBeVisible,
  55797. const int minimumWidth,
  55798. const int maximumNumColumns,
  55799. const int standardItemHeight)
  55800. {
  55801. const Point<int> mousePos (Desktop::getMousePosition());
  55802. return showAt (mousePos.getX(), mousePos.getY(),
  55803. itemIdThatMustBeVisible,
  55804. minimumWidth,
  55805. maximumNumColumns,
  55806. standardItemHeight);
  55807. }
  55808. int PopupMenu::showAt (const int screenX,
  55809. const int screenY,
  55810. const int itemIdThatMustBeVisible,
  55811. const int minimumWidth,
  55812. const int maximumNumColumns,
  55813. const int standardItemHeight)
  55814. {
  55815. return showMenu (screenX, screenY, 1, 1,
  55816. itemIdThatMustBeVisible,
  55817. minimumWidth, maximumNumColumns,
  55818. standardItemHeight,
  55819. false, 0);
  55820. }
  55821. int PopupMenu::showAt (Component* componentToAttachTo,
  55822. const int itemIdThatMustBeVisible,
  55823. const int minimumWidth,
  55824. const int maximumNumColumns,
  55825. const int standardItemHeight)
  55826. {
  55827. if (componentToAttachTo != 0)
  55828. {
  55829. return showMenu (componentToAttachTo->getScreenX(),
  55830. componentToAttachTo->getScreenY(),
  55831. componentToAttachTo->getWidth(),
  55832. componentToAttachTo->getHeight(),
  55833. itemIdThatMustBeVisible,
  55834. minimumWidth,
  55835. maximumNumColumns,
  55836. standardItemHeight,
  55837. true, componentToAttachTo);
  55838. }
  55839. else
  55840. {
  55841. return show (itemIdThatMustBeVisible,
  55842. minimumWidth,
  55843. maximumNumColumns,
  55844. standardItemHeight);
  55845. }
  55846. }
  55847. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  55848. {
  55849. for (int i = Window::getActiveWindows().size(); --i >= 0;)
  55850. {
  55851. Window* const pmw = Window::getActiveWindows()[i];
  55852. if (pmw != 0)
  55853. pmw->dismissMenu (0);
  55854. }
  55855. }
  55856. int PopupMenu::getNumItems() const throw()
  55857. {
  55858. int num = 0;
  55859. for (int i = items.size(); --i >= 0;)
  55860. if (! (items.getUnchecked(i))->isSeparator)
  55861. ++num;
  55862. return num;
  55863. }
  55864. bool PopupMenu::containsCommandItem (const int commandID) const
  55865. {
  55866. for (int i = items.size(); --i >= 0;)
  55867. {
  55868. const Item* mi = items.getUnchecked (i);
  55869. if ((mi->itemId == commandID && mi->commandManager != 0)
  55870. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  55871. {
  55872. return true;
  55873. }
  55874. }
  55875. return false;
  55876. }
  55877. bool PopupMenu::containsAnyActiveItems() const throw()
  55878. {
  55879. for (int i = items.size(); --i >= 0;)
  55880. {
  55881. const Item* const mi = items.getUnchecked (i);
  55882. if (mi->subMenu != 0)
  55883. {
  55884. if (mi->subMenu->containsAnyActiveItems())
  55885. return true;
  55886. }
  55887. else if (mi->active)
  55888. {
  55889. return true;
  55890. }
  55891. }
  55892. return false;
  55893. }
  55894. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  55895. {
  55896. lookAndFeel = newLookAndFeel;
  55897. }
  55898. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  55899. : isHighlighted (false),
  55900. isTriggeredAutomatically (isTriggeredAutomatically_)
  55901. {
  55902. }
  55903. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  55904. {
  55905. }
  55906. void PopupMenuCustomComponent::triggerMenuItem()
  55907. {
  55908. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  55909. if (mic != 0)
  55910. {
  55911. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  55912. if (pmw != 0)
  55913. {
  55914. pmw->dismissMenu (&mic->itemInfo);
  55915. }
  55916. else
  55917. {
  55918. // something must have gone wrong with the component hierarchy if this happens..
  55919. jassertfalse
  55920. }
  55921. }
  55922. else
  55923. {
  55924. // why isn't this component inside a menu? Not much point triggering the item if
  55925. // there's no menu.
  55926. jassertfalse
  55927. }
  55928. }
  55929. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  55930. : subMenu (0),
  55931. itemId (0),
  55932. isSeparator (false),
  55933. isTicked (false),
  55934. isEnabled (false),
  55935. isCustomComponent (false),
  55936. isSectionHeader (false),
  55937. customColour (0),
  55938. customImage (0),
  55939. menu (menu_),
  55940. index (0)
  55941. {
  55942. }
  55943. PopupMenu::MenuItemIterator::~MenuItemIterator()
  55944. {
  55945. }
  55946. bool PopupMenu::MenuItemIterator::next()
  55947. {
  55948. if (index >= menu.items.size())
  55949. return false;
  55950. const Item* const item = menu.items.getUnchecked (index);
  55951. ++index;
  55952. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  55953. subMenu = item->subMenu;
  55954. itemId = item->itemId;
  55955. isSeparator = item->isSeparator;
  55956. isTicked = item->isTicked;
  55957. isEnabled = item->active;
  55958. isSectionHeader = dynamic_cast <HeaderItemComponent*> ((PopupMenuCustomComponent*) item->customComp) != 0;
  55959. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  55960. customColour = item->usesColour ? &(item->textColour) : 0;
  55961. customImage = item->image;
  55962. commandManager = item->commandManager;
  55963. return true;
  55964. }
  55965. END_JUCE_NAMESPACE
  55966. /*** End of inlined file: juce_PopupMenu.cpp ***/
  55967. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  55968. BEGIN_JUCE_NAMESPACE
  55969. ComponentDragger::ComponentDragger()
  55970. : constrainer (0)
  55971. {
  55972. }
  55973. ComponentDragger::~ComponentDragger()
  55974. {
  55975. }
  55976. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  55977. ComponentBoundsConstrainer* const constrainer_)
  55978. {
  55979. jassert (componentToDrag->isValidComponent());
  55980. if (componentToDrag != 0)
  55981. {
  55982. constrainer = constrainer_;
  55983. originalPos = componentToDrag->relativePositionToGlobal (Point<int>());
  55984. }
  55985. }
  55986. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  55987. {
  55988. jassert (componentToDrag->isValidComponent());
  55989. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  55990. if (componentToDrag != 0)
  55991. {
  55992. Rectangle<int> bounds (componentToDrag->getBounds().withPosition (originalPos));
  55993. const Component* const parentComp = componentToDrag->getParentComponent();
  55994. if (parentComp != 0)
  55995. bounds.setPosition (parentComp->globalPositionToRelative (originalPos));
  55996. bounds.setPosition (bounds.getPosition() + e.getOffsetFromDragStart());
  55997. if (constrainer != 0)
  55998. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  55999. else
  56000. componentToDrag->setBounds (bounds);
  56001. }
  56002. }
  56003. END_JUCE_NAMESPACE
  56004. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  56005. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  56006. BEGIN_JUCE_NAMESPACE
  56007. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  56008. bool juce_performDragDropText (const String& text, bool& shouldStop);
  56009. class DragImageComponent : public Component,
  56010. public Timer
  56011. {
  56012. public:
  56013. DragImageComponent (Image* const im,
  56014. const String& desc,
  56015. Component* const sourceComponent,
  56016. Component* const mouseDragSource_,
  56017. DragAndDropContainer* const o,
  56018. const Point<int>& imageOffset_)
  56019. : image (im),
  56020. source (sourceComponent),
  56021. mouseDragSource (mouseDragSource_),
  56022. owner (o),
  56023. dragDesc (desc),
  56024. imageOffset (imageOffset_),
  56025. hasCheckedForExternalDrag (false),
  56026. drawImage (true)
  56027. {
  56028. setSize (im->getWidth(), im->getHeight());
  56029. if (mouseDragSource == 0)
  56030. mouseDragSource = source;
  56031. mouseDragSource->addMouseListener (this, false);
  56032. startTimer (200);
  56033. setInterceptsMouseClicks (false, false);
  56034. setAlwaysOnTop (true);
  56035. }
  56036. ~DragImageComponent()
  56037. {
  56038. if (owner->dragImageComponent == this)
  56039. owner->dragImageComponent.release();
  56040. if (mouseDragSource != 0)
  56041. {
  56042. mouseDragSource->removeMouseListener (this);
  56043. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  56044. getCurrentlyOver()->itemDragExit (dragDesc, source);
  56045. }
  56046. }
  56047. void paint (Graphics& g)
  56048. {
  56049. if (isOpaque())
  56050. g.fillAll (Colours::white);
  56051. if (drawImage)
  56052. {
  56053. g.setOpacity (1.0f);
  56054. g.drawImageAt (image, 0, 0);
  56055. }
  56056. }
  56057. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  56058. {
  56059. Component* hit = getParentComponent();
  56060. if (hit == 0)
  56061. {
  56062. hit = Desktop::getInstance().findComponentAt (screenPos);
  56063. }
  56064. else
  56065. {
  56066. const Point<int> relPos (hit->globalPositionToRelative (screenPos));
  56067. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  56068. }
  56069. // (note: use a local copy of the dragDesc member in case the callback runs
  56070. // a modal loop and deletes this object before the method completes)
  56071. const String dragDescLocal (dragDesc);
  56072. while (hit != 0)
  56073. {
  56074. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  56075. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56076. {
  56077. relativePos = hit->globalPositionToRelative (screenPos);
  56078. return ddt;
  56079. }
  56080. hit = hit->getParentComponent();
  56081. }
  56082. return 0;
  56083. }
  56084. void mouseUp (const MouseEvent& e)
  56085. {
  56086. if (e.originalComponent != this)
  56087. {
  56088. if (mouseDragSource != 0)
  56089. mouseDragSource->removeMouseListener (this);
  56090. bool dropAccepted = false;
  56091. DragAndDropTarget* ddt = 0;
  56092. Point<int> relPos;
  56093. if (isVisible())
  56094. {
  56095. setVisible (false);
  56096. ddt = findTarget (e.getScreenPosition(), relPos);
  56097. // fade this component and remove it - it'll be deleted later by the timer callback
  56098. dropAccepted = ddt != 0;
  56099. setVisible (true);
  56100. if (dropAccepted || source == 0)
  56101. {
  56102. fadeOutComponent (120);
  56103. }
  56104. else
  56105. {
  56106. const Point<int> target (source->relativePositionToGlobal (Point<int> (source->getWidth() / 2,
  56107. source->getHeight() / 2)));
  56108. const Point<int> ourCentre (relativePositionToGlobal (Point<int> (getWidth() / 2,
  56109. getHeight() / 2)));
  56110. fadeOutComponent (120,
  56111. target.getX() - ourCentre.getX(),
  56112. target.getY() - ourCentre.getY());
  56113. }
  56114. }
  56115. if (getParentComponent() != 0)
  56116. getParentComponent()->removeChildComponent (this);
  56117. if (dropAccepted && ddt != 0)
  56118. {
  56119. // (note: use a local copy of the dragDesc member in case the callback runs
  56120. // a modal loop and deletes this object before the method completes)
  56121. const String dragDescLocal (dragDesc);
  56122. currentlyOverComp = 0;
  56123. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  56124. }
  56125. // careful - this object could now be deleted..
  56126. }
  56127. }
  56128. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  56129. {
  56130. // (note: use a local copy of the dragDesc member in case the callback runs
  56131. // a modal loop and deletes this object before it returns)
  56132. const String dragDescLocal (dragDesc);
  56133. Point<int> newPos (screenPos + imageOffset);
  56134. if (getParentComponent() != 0)
  56135. newPos = getParentComponent()->globalPositionToRelative (newPos);
  56136. //if (newX != getX() || newY != getY())
  56137. {
  56138. setTopLeftPosition (newPos.getX(), newPos.getY());
  56139. Point<int> relPos;
  56140. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  56141. Component* ddtComp = dynamic_cast <Component*> (ddt);
  56142. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  56143. if (ddtComp != currentlyOverComp)
  56144. {
  56145. if (currentlyOverComp != 0 && source != 0
  56146. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  56147. {
  56148. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  56149. }
  56150. currentlyOverComp = ddtComp;
  56151. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56152. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  56153. }
  56154. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  56155. getCurrentlyOver()->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  56156. if (getCurrentlyOver() == 0
  56157. && canDoExternalDrag
  56158. && ! hasCheckedForExternalDrag)
  56159. {
  56160. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  56161. {
  56162. hasCheckedForExternalDrag = true;
  56163. StringArray files;
  56164. bool canMoveFiles = false;
  56165. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  56166. && files.size() > 0)
  56167. {
  56168. Component::SafePointer<Component> cdw (this);
  56169. setVisible (false);
  56170. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  56171. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  56172. if (cdw != 0)
  56173. delete this;
  56174. return;
  56175. }
  56176. }
  56177. }
  56178. }
  56179. }
  56180. void mouseDrag (const MouseEvent& e)
  56181. {
  56182. if (e.originalComponent != this)
  56183. updateLocation (true, e.getScreenPosition());
  56184. }
  56185. void timerCallback()
  56186. {
  56187. if (source == 0)
  56188. {
  56189. delete this;
  56190. }
  56191. else if (! isMouseButtonDownAnywhere())
  56192. {
  56193. if (mouseDragSource != 0)
  56194. mouseDragSource->removeMouseListener (this);
  56195. delete this;
  56196. }
  56197. }
  56198. private:
  56199. ScopedPointer<Image> image;
  56200. Component::SafePointer<Component> source;
  56201. Component::SafePointer<Component> mouseDragSource;
  56202. DragAndDropContainer* const owner;
  56203. Component::SafePointer<Component> currentlyOverComp;
  56204. DragAndDropTarget* getCurrentlyOver()
  56205. {
  56206. return dynamic_cast <DragAndDropTarget*> (static_cast <Component*> (currentlyOverComp));
  56207. }
  56208. String dragDesc;
  56209. const Point<int> imageOffset;
  56210. bool hasCheckedForExternalDrag, drawImage;
  56211. DragImageComponent (const DragImageComponent&);
  56212. DragImageComponent& operator= (const DragImageComponent&);
  56213. };
  56214. DragAndDropContainer::DragAndDropContainer()
  56215. {
  56216. }
  56217. DragAndDropContainer::~DragAndDropContainer()
  56218. {
  56219. dragImageComponent = 0;
  56220. }
  56221. void DragAndDropContainer::startDragging (const String& sourceDescription,
  56222. Component* sourceComponent,
  56223. Image* dragImage_,
  56224. const bool allowDraggingToExternalWindows,
  56225. const Point<int>* imageOffsetFromMouse)
  56226. {
  56227. ScopedPointer <Image> dragImage (dragImage_);
  56228. if (dragImageComponent == 0)
  56229. {
  56230. Component* const thisComp = dynamic_cast <Component*> (this);
  56231. if (thisComp == 0)
  56232. {
  56233. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  56234. return;
  56235. }
  56236. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  56237. if (draggingSource == 0 || ! draggingSource->isDragging())
  56238. {
  56239. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  56240. return;
  56241. }
  56242. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  56243. Point<int> imageOffset;
  56244. if (dragImage == 0)
  56245. {
  56246. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds());
  56247. if (dragImage->getFormat() != Image::ARGB)
  56248. {
  56249. Image* newIm = Image::createNativeImage (Image::ARGB, dragImage->getWidth(), dragImage->getHeight(), true);
  56250. Graphics g2 (*newIm);
  56251. g2.drawImageAt (dragImage, 0, 0);
  56252. dragImage = newIm;
  56253. }
  56254. dragImage->multiplyAllAlphas (0.6f);
  56255. const int lo = 150;
  56256. const int hi = 400;
  56257. Point<int> relPos (sourceComponent->globalPositionToRelative (lastMouseDown));
  56258. Point<int> clipped (dragImage->getBounds().getConstrainedPoint (relPos));
  56259. for (int y = dragImage->getHeight(); --y >= 0;)
  56260. {
  56261. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  56262. for (int x = dragImage->getWidth(); --x >= 0;)
  56263. {
  56264. const int dx = x - clipped.getX();
  56265. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  56266. if (distance > lo)
  56267. {
  56268. const float alpha = (distance > hi) ? 0
  56269. : (hi - distance) / (float) (hi - lo)
  56270. + Random::getSystemRandom().nextFloat() * 0.008f;
  56271. dragImage->multiplyAlphaAt (x, y, alpha);
  56272. }
  56273. }
  56274. }
  56275. imageOffset = -clipped;
  56276. }
  56277. else
  56278. {
  56279. if (imageOffsetFromMouse == 0)
  56280. imageOffset = -dragImage->getBounds().getCentre();
  56281. else
  56282. imageOffset = -(dragImage->getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  56283. }
  56284. dragImageComponent = new DragImageComponent (dragImage.release(), sourceDescription, sourceComponent,
  56285. draggingSource->getComponentUnderMouse(), this, imageOffset);
  56286. currentDragDesc = sourceDescription;
  56287. if (allowDraggingToExternalWindows)
  56288. {
  56289. if (! Desktop::canUseSemiTransparentWindows())
  56290. dragImageComponent->setOpaque (true);
  56291. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  56292. | ComponentPeer::windowIsTemporary
  56293. | ComponentPeer::windowIgnoresKeyPresses);
  56294. }
  56295. else
  56296. thisComp->addChildComponent (dragImageComponent);
  56297. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  56298. dragImageComponent->setVisible (true);
  56299. }
  56300. }
  56301. bool DragAndDropContainer::isDragAndDropActive() const
  56302. {
  56303. return dragImageComponent != 0;
  56304. }
  56305. const String DragAndDropContainer::getCurrentDragDescription() const
  56306. {
  56307. return (dragImageComponent != 0) ? currentDragDesc
  56308. : String::empty;
  56309. }
  56310. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  56311. {
  56312. if (c == 0)
  56313. return 0;
  56314. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  56315. return c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  56316. }
  56317. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  56318. {
  56319. return false;
  56320. }
  56321. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  56322. {
  56323. }
  56324. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  56325. {
  56326. }
  56327. void DragAndDropTarget::itemDragExit (const String&, Component*)
  56328. {
  56329. }
  56330. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  56331. {
  56332. return true;
  56333. }
  56334. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  56335. {
  56336. }
  56337. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  56338. {
  56339. }
  56340. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  56341. {
  56342. }
  56343. END_JUCE_NAMESPACE
  56344. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  56345. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  56346. BEGIN_JUCE_NAMESPACE
  56347. class MouseCursor::SharedCursorHandle
  56348. {
  56349. public:
  56350. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  56351. : handle (createStandardMouseCursor (type)),
  56352. refCount (1),
  56353. standardType (type),
  56354. isStandard (true)
  56355. {
  56356. }
  56357. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  56358. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  56359. refCount (1),
  56360. standardType (MouseCursor::NormalCursor),
  56361. isStandard (false)
  56362. {
  56363. }
  56364. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  56365. {
  56366. const ScopedLock sl (getLock());
  56367. for (int i = getCursors().size(); --i >= 0;)
  56368. {
  56369. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  56370. if (sc->standardType == type)
  56371. return sc->retain();
  56372. }
  56373. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  56374. getCursors().add (sc);
  56375. return sc;
  56376. }
  56377. SharedCursorHandle* retain() throw()
  56378. {
  56379. ++refCount;
  56380. return this;
  56381. }
  56382. void release()
  56383. {
  56384. if (--refCount == 0)
  56385. {
  56386. if (isStandard)
  56387. {
  56388. const ScopedLock sl (getLock());
  56389. getCursors().removeValue (this);
  56390. }
  56391. delete this;
  56392. }
  56393. }
  56394. void* getHandle() const throw() { return handle; }
  56395. juce_UseDebuggingNewOperator
  56396. private:
  56397. void* const handle;
  56398. Atomic <int> refCount;
  56399. const MouseCursor::StandardCursorType standardType;
  56400. const bool isStandard;
  56401. static CriticalSection& getLock()
  56402. {
  56403. static CriticalSection lock;
  56404. return lock;
  56405. }
  56406. static Array <SharedCursorHandle*>& getCursors()
  56407. {
  56408. static Array <SharedCursorHandle*> cursors;
  56409. return cursors;
  56410. }
  56411. ~SharedCursorHandle()
  56412. {
  56413. deleteMouseCursor (handle, isStandard);
  56414. }
  56415. SharedCursorHandle& operator= (const SharedCursorHandle&);
  56416. };
  56417. MouseCursor::MouseCursor()
  56418. : cursorHandle (SharedCursorHandle::createStandard (NormalCursor))
  56419. {
  56420. jassert (cursorHandle != 0);
  56421. }
  56422. MouseCursor::MouseCursor (const StandardCursorType type)
  56423. : cursorHandle (SharedCursorHandle::createStandard (type))
  56424. {
  56425. jassert (cursorHandle != 0);
  56426. }
  56427. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  56428. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  56429. {
  56430. }
  56431. MouseCursor::MouseCursor (const MouseCursor& other)
  56432. : cursorHandle (other.cursorHandle->retain())
  56433. {
  56434. }
  56435. MouseCursor::~MouseCursor()
  56436. {
  56437. cursorHandle->release();
  56438. }
  56439. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  56440. {
  56441. other.cursorHandle->retain();
  56442. cursorHandle->release();
  56443. cursorHandle = other.cursorHandle;
  56444. return *this;
  56445. }
  56446. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  56447. {
  56448. return getHandle() == other.getHandle();
  56449. }
  56450. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  56451. {
  56452. return getHandle() != other.getHandle();
  56453. }
  56454. void* MouseCursor::getHandle() const throw()
  56455. {
  56456. return cursorHandle->getHandle();
  56457. }
  56458. void MouseCursor::showWaitCursor()
  56459. {
  56460. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  56461. }
  56462. void MouseCursor::hideWaitCursor()
  56463. {
  56464. Desktop::getInstance().getMainMouseSource().revealCursor();
  56465. }
  56466. END_JUCE_NAMESPACE
  56467. /*** End of inlined file: juce_MouseCursor.cpp ***/
  56468. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  56469. BEGIN_JUCE_NAMESPACE
  56470. MouseEvent::MouseEvent (MouseInputSource& source_,
  56471. const Point<int>& position,
  56472. const ModifierKeys& mods_,
  56473. Component* const originator,
  56474. const Time& eventTime_,
  56475. const Point<int> mouseDownPos_,
  56476. const Time& mouseDownTime_,
  56477. const int numberOfClicks_,
  56478. const bool mouseWasDragged) throw()
  56479. : x (position.getX()),
  56480. y (position.getY()),
  56481. mods (mods_),
  56482. eventComponent (originator),
  56483. originalComponent (originator),
  56484. eventTime (eventTime_),
  56485. source (source_),
  56486. mouseDownPos (mouseDownPos_),
  56487. mouseDownTime (mouseDownTime_),
  56488. numberOfClicks (numberOfClicks_),
  56489. wasMovedSinceMouseDown (mouseWasDragged)
  56490. {
  56491. }
  56492. MouseEvent::~MouseEvent() throw()
  56493. {
  56494. }
  56495. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  56496. {
  56497. if (otherComponent == 0)
  56498. {
  56499. jassertfalse
  56500. return *this;
  56501. }
  56502. return MouseEvent (source, eventComponent->relativePositionToOtherComponent (otherComponent, getPosition()),
  56503. mods, originalComponent, eventTime,
  56504. eventComponent->relativePositionToOtherComponent (otherComponent, mouseDownPos),
  56505. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  56506. }
  56507. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  56508. {
  56509. return MouseEvent (source, newPosition, mods, originalComponent,
  56510. eventTime, mouseDownPos, mouseDownTime,
  56511. numberOfClicks, wasMovedSinceMouseDown);
  56512. }
  56513. bool MouseEvent::mouseWasClicked() const throw()
  56514. {
  56515. return ! wasMovedSinceMouseDown;
  56516. }
  56517. int MouseEvent::getMouseDownX() const throw()
  56518. {
  56519. return mouseDownPos.getX();
  56520. }
  56521. int MouseEvent::getMouseDownY() const throw()
  56522. {
  56523. return mouseDownPos.getY();
  56524. }
  56525. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  56526. {
  56527. return mouseDownPos;
  56528. }
  56529. int MouseEvent::getDistanceFromDragStartX() const throw()
  56530. {
  56531. return x - mouseDownPos.getX();
  56532. }
  56533. int MouseEvent::getDistanceFromDragStartY() const throw()
  56534. {
  56535. return y - mouseDownPos.getY();
  56536. }
  56537. int MouseEvent::getDistanceFromDragStart() const throw()
  56538. {
  56539. return mouseDownPos.getDistanceFrom (getPosition());
  56540. }
  56541. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  56542. {
  56543. return getPosition() - mouseDownPos;
  56544. }
  56545. int MouseEvent::getLengthOfMousePress() const throw()
  56546. {
  56547. if (mouseDownTime.toMilliseconds() > 0)
  56548. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  56549. return 0;
  56550. }
  56551. const Point<int> MouseEvent::getPosition() const throw()
  56552. {
  56553. return Point<int> (x, y);
  56554. }
  56555. int MouseEvent::getScreenX() const
  56556. {
  56557. return getScreenPosition().getX();
  56558. }
  56559. int MouseEvent::getScreenY() const
  56560. {
  56561. return getScreenPosition().getY();
  56562. }
  56563. const Point<int> MouseEvent::getScreenPosition() const
  56564. {
  56565. return eventComponent->relativePositionToGlobal (Point<int> (x, y));
  56566. }
  56567. int MouseEvent::getMouseDownScreenX() const
  56568. {
  56569. return getMouseDownScreenPosition().getX();
  56570. }
  56571. int MouseEvent::getMouseDownScreenY() const
  56572. {
  56573. return getMouseDownScreenPosition().getY();
  56574. }
  56575. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  56576. {
  56577. return eventComponent->relativePositionToGlobal (mouseDownPos);
  56578. }
  56579. static int doubleClickTimeOutMs = 400;
  56580. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  56581. {
  56582. doubleClickTimeOutMs = newTime;
  56583. }
  56584. int MouseEvent::getDoubleClickTimeout() throw()
  56585. {
  56586. return doubleClickTimeOutMs;
  56587. }
  56588. END_JUCE_NAMESPACE
  56589. /*** End of inlined file: juce_MouseEvent.cpp ***/
  56590. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  56591. BEGIN_JUCE_NAMESPACE
  56592. class MouseInputSourceInternal : public AsyncUpdater
  56593. {
  56594. public:
  56595. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  56596. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0), lastTime (0),
  56597. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  56598. mouseEventCounter (0)
  56599. {
  56600. zerostruct (mouseDowns);
  56601. }
  56602. ~MouseInputSourceInternal()
  56603. {
  56604. }
  56605. bool isDragging() const throw()
  56606. {
  56607. return buttonState.isAnyMouseButtonDown();
  56608. }
  56609. Component* getComponentUnderMouse() const
  56610. {
  56611. return static_cast <Component*> (componentUnderMouse);
  56612. }
  56613. const ModifierKeys getCurrentModifiers() const
  56614. {
  56615. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  56616. }
  56617. ComponentPeer* getPeer()
  56618. {
  56619. if (! ComponentPeer::isValidPeer (lastPeer))
  56620. lastPeer = 0;
  56621. return lastPeer;
  56622. }
  56623. Component* findComponentAt (const Point<int>& screenPos)
  56624. {
  56625. ComponentPeer* const peer = getPeer();
  56626. if (peer != 0)
  56627. {
  56628. Component* const comp = peer->getComponent();
  56629. const Point<int> relativePos (comp->globalPositionToRelative (screenPos));
  56630. // (the contains() call is needed to test for overlapping desktop windows)
  56631. if (comp->contains (relativePos.getX(), relativePos.getY()))
  56632. return comp->getComponentAt (relativePos);
  56633. }
  56634. return 0;
  56635. }
  56636. const Point<int> getScreenPosition() const throw()
  56637. {
  56638. return lastScreenPos + unboundedMouseOffset;
  56639. }
  56640. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const int64 time)
  56641. {
  56642. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56643. comp->internalMouseEnter (source, comp->globalPositionToRelative (screenPos), time);
  56644. }
  56645. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const int64 time)
  56646. {
  56647. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56648. comp->internalMouseExit (source, comp->globalPositionToRelative (screenPos), time);
  56649. }
  56650. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const int64 time)
  56651. {
  56652. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56653. comp->internalMouseMove (source, comp->globalPositionToRelative (screenPos), time);
  56654. }
  56655. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const int64 time)
  56656. {
  56657. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56658. comp->internalMouseDown (source, comp->globalPositionToRelative (screenPos), time);
  56659. }
  56660. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const int64 time)
  56661. {
  56662. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56663. comp->internalMouseDrag (source, comp->globalPositionToRelative (screenPos), time);
  56664. }
  56665. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const int64 time)
  56666. {
  56667. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56668. comp->internalMouseUp (source, comp->globalPositionToRelative (screenPos), time, getCurrentModifiers());
  56669. }
  56670. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const int64 time, float x, float y)
  56671. {
  56672. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56673. comp->internalMouseWheel (source, comp->globalPositionToRelative (screenPos), time, x, y);
  56674. }
  56675. // (returns true if the button change caused a modal event loop)
  56676. bool setButtons (const Point<int>& screenPos, const int64 time, const ModifierKeys& newButtonState)
  56677. {
  56678. if (buttonState == newButtonState)
  56679. return false;
  56680. // (ignore secondary clicks when there's already a button down)
  56681. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  56682. {
  56683. buttonState = newButtonState;
  56684. return false;
  56685. }
  56686. const int lastCounter = mouseEventCounter;
  56687. if (buttonState.isAnyMouseButtonDown())
  56688. {
  56689. Component* const current = getComponentUnderMouse();
  56690. if (current != 0)
  56691. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  56692. enableUnboundedMouseMovement (false, false);
  56693. }
  56694. buttonState = newButtonState;
  56695. if (buttonState.isAnyMouseButtonDown())
  56696. {
  56697. Desktop::getInstance().incrementMouseClickCounter();
  56698. Component* const current = getComponentUnderMouse();
  56699. if (current != 0)
  56700. {
  56701. registerMouseDown (screenPos, time, current);
  56702. sendMouseDown (current, screenPos, time);
  56703. }
  56704. }
  56705. return lastCounter != mouseEventCounter;
  56706. }
  56707. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const int64 time)
  56708. {
  56709. Component* current = getComponentUnderMouse();
  56710. if (newComponent != current)
  56711. {
  56712. Component::SafePointer<Component> safeNewComp (newComponent);
  56713. const ModifierKeys originalButtonState (buttonState);
  56714. if (current != 0)
  56715. {
  56716. setButtons (screenPos, time, ModifierKeys());
  56717. sendMouseExit (current, screenPos, time);
  56718. buttonState = originalButtonState;
  56719. }
  56720. componentUnderMouse = safeNewComp;
  56721. current = getComponentUnderMouse();
  56722. if (current != 0)
  56723. sendMouseEnter (current, screenPos, time);
  56724. revealCursor (false);
  56725. setButtons (screenPos, time, originalButtonState);
  56726. }
  56727. }
  56728. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const int64 time)
  56729. {
  56730. ModifierKeys::updateCurrentModifiers();
  56731. if (newPeer != lastPeer)
  56732. {
  56733. setComponentUnderMouse (0, screenPos, time);
  56734. lastPeer = newPeer;
  56735. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  56736. }
  56737. }
  56738. void setScreenPos (const Point<int>& newScreenPos, const int64 time, const bool forceUpdate)
  56739. {
  56740. if (! isDragging())
  56741. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  56742. if (newScreenPos != lastScreenPos || forceUpdate)
  56743. {
  56744. cancelPendingUpdate();
  56745. lastScreenPos = newScreenPos;
  56746. Component* const current = getComponentUnderMouse();
  56747. if (current != 0)
  56748. {
  56749. if (isDragging())
  56750. {
  56751. registerMouseDrag (newScreenPos);
  56752. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  56753. if (isUnboundedMouseModeOn)
  56754. handleUnboundedDrag (current);
  56755. }
  56756. else
  56757. {
  56758. sendMouseMove (current, newScreenPos, time);
  56759. }
  56760. }
  56761. revealCursor (false);
  56762. }
  56763. }
  56764. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& newMods)
  56765. {
  56766. jassert (newPeer != 0);
  56767. lastTime = time;
  56768. ++mouseEventCounter;
  56769. const Point<int> screenPos (newPeer->relativePositionToGlobal (positionWithinPeer));
  56770. if (isDragging() && newMods.isAnyMouseButtonDown())
  56771. {
  56772. setScreenPos (screenPos, time, false);
  56773. }
  56774. else
  56775. {
  56776. setPeer (newPeer, screenPos, time);
  56777. ComponentPeer* peer = getPeer();
  56778. if (peer != 0)
  56779. {
  56780. if (setButtons (screenPos, time, newMods))
  56781. return; // some modal events have been dispatched, so the current event is now out-of-date
  56782. peer = getPeer();
  56783. if (peer != 0)
  56784. setScreenPos (screenPos, time, false);
  56785. }
  56786. }
  56787. }
  56788. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, int64 time, float x, float y)
  56789. {
  56790. jassert (peer != 0);
  56791. lastTime = time;
  56792. ++mouseEventCounter;
  56793. const Point<int> screenPos (peer->relativePositionToGlobal (positionWithinPeer));
  56794. setPeer (peer, screenPos, time);
  56795. setScreenPos (screenPos, time, false);
  56796. triggerFakeMove();
  56797. if (! isDragging())
  56798. {
  56799. Component* current = getComponentUnderMouse();
  56800. if (current != 0)
  56801. sendMouseWheel (current, screenPos, time, x, y);
  56802. }
  56803. }
  56804. const Time getLastMouseDownTime() const throw()
  56805. {
  56806. return Time (mouseDowns[0].time);
  56807. }
  56808. const Point<int> getLastMouseDownPosition() const throw()
  56809. {
  56810. return mouseDowns[0].position;
  56811. }
  56812. int getNumberOfMultipleClicks() const throw()
  56813. {
  56814. int numClicks = 0;
  56815. if (mouseDowns[0].time != 0)
  56816. {
  56817. if (! mouseMovedSignificantlySincePressed)
  56818. ++numClicks;
  56819. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  56820. {
  56821. if (mouseDowns[0].time - mouseDowns[i].time < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  56822. && abs (mouseDowns[0].position.getX() - mouseDowns[i].position.getX()) < 8
  56823. && abs (mouseDowns[0].position.getY() - mouseDowns[i].position.getY()) < 8
  56824. && mouseDowns[0].component == mouseDowns[i].component)
  56825. {
  56826. ++numClicks;
  56827. }
  56828. else
  56829. {
  56830. break;
  56831. }
  56832. }
  56833. }
  56834. return numClicks;
  56835. }
  56836. bool hasMouseMovedSignificantlySincePressed() const throw()
  56837. {
  56838. return mouseMovedSignificantlySincePressed
  56839. || lastTime > mouseDowns[0].time + 300;
  56840. }
  56841. void triggerFakeMove()
  56842. {
  56843. triggerAsyncUpdate();
  56844. }
  56845. void handleAsyncUpdate()
  56846. {
  56847. if (! isDragging())
  56848. setScreenPos (Desktop::getMousePosition(), jmax (lastTime, Time::currentTimeMillis()), true);
  56849. }
  56850. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  56851. {
  56852. enable = enable && isDragging();
  56853. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  56854. if (enable != isUnboundedMouseModeOn)
  56855. {
  56856. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  56857. {
  56858. // when released, return the mouse to within the component's bounds
  56859. Component* current = getComponentUnderMouse();
  56860. if (current != 0)
  56861. Desktop::setMousePosition (current->getScreenBounds()
  56862. .getConstrainedPoint (current->getMouseXYRelative()));
  56863. }
  56864. isUnboundedMouseModeOn = enable;
  56865. unboundedMouseOffset = Point<int>();
  56866. revealCursor (true);
  56867. }
  56868. }
  56869. void handleUnboundedDrag (Component* current)
  56870. {
  56871. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  56872. if (! screenArea.contains (lastScreenPos))
  56873. {
  56874. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  56875. unboundedMouseOffset += (lastScreenPos - componentCentre);
  56876. Desktop::setMousePosition (componentCentre);
  56877. }
  56878. else if (isCursorVisibleUntilOffscreen
  56879. && (! unboundedMouseOffset.isOrigin())
  56880. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  56881. {
  56882. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  56883. unboundedMouseOffset = Point<int>();
  56884. }
  56885. }
  56886. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  56887. {
  56888. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  56889. {
  56890. cursor = MouseCursor::NoCursor;
  56891. forcedUpdate = true;
  56892. }
  56893. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  56894. {
  56895. currentCursorHandle = cursor.getHandle();
  56896. cursor.showInWindow (getPeer());
  56897. }
  56898. }
  56899. void hideCursor()
  56900. {
  56901. showMouseCursor (MouseCursor::NoCursor, true);
  56902. }
  56903. void revealCursor (bool forcedUpdate)
  56904. {
  56905. MouseCursor mc (MouseCursor::NormalCursor);
  56906. Component* current = getComponentUnderMouse();
  56907. if (current != 0)
  56908. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  56909. showMouseCursor (mc, forcedUpdate);
  56910. }
  56911. int index;
  56912. bool isMouseDevice;
  56913. Point<int> lastScreenPos;
  56914. ModifierKeys buttonState;
  56915. private:
  56916. MouseInputSource& source;
  56917. Component::SafePointer<Component> componentUnderMouse;
  56918. ComponentPeer* lastPeer;
  56919. Point<int> unboundedMouseOffset;
  56920. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  56921. void* currentCursorHandle;
  56922. int mouseEventCounter;
  56923. struct RecentMouseDown
  56924. {
  56925. Point<int> position;
  56926. int64 time;
  56927. Component* component;
  56928. };
  56929. RecentMouseDown mouseDowns[4];
  56930. bool mouseMovedSignificantlySincePressed;
  56931. int64 lastTime;
  56932. void registerMouseDown (const Point<int>& screenPos, const int64 time, Component* const component) throw()
  56933. {
  56934. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  56935. mouseDowns[i] = mouseDowns[i - 1];
  56936. mouseDowns[0].position = screenPos;
  56937. mouseDowns[0].time = time;
  56938. mouseDowns[0].component = component;
  56939. mouseMovedSignificantlySincePressed = false;
  56940. }
  56941. void registerMouseDrag (const Point<int>& screenPos) throw()
  56942. {
  56943. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  56944. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  56945. }
  56946. MouseInputSourceInternal (const MouseInputSourceInternal&);
  56947. MouseInputSourceInternal& operator= (const MouseInputSourceInternal&);
  56948. };
  56949. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  56950. {
  56951. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  56952. }
  56953. MouseInputSource::~MouseInputSource()
  56954. {
  56955. }
  56956. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  56957. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  56958. bool MouseInputSource::canHover() const { return isMouse(); }
  56959. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  56960. int MouseInputSource::getIndex() const { return pimpl->index; }
  56961. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  56962. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  56963. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  56964. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  56965. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  56966. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  56967. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  56968. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  56969. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  56970. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  56971. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  56972. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  56973. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  56974. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  56975. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  56976. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  56977. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  56978. {
  56979. pimpl->handleEvent (peer, positionWithinPeer, time, mods.withOnlyMouseButtons());
  56980. }
  56981. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  56982. {
  56983. pimpl->handleWheel (peer, positionWithinPeer, time, x, y);
  56984. }
  56985. END_JUCE_NAMESPACE
  56986. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  56987. /*** Start of inlined file: juce_MouseHoverDetector.cpp ***/
  56988. BEGIN_JUCE_NAMESPACE
  56989. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  56990. : source (0),
  56991. hoverTimeMillisecs (hoverTimeMillisecs_),
  56992. hasJustHovered (false)
  56993. {
  56994. internalTimer.owner = this;
  56995. }
  56996. MouseHoverDetector::~MouseHoverDetector()
  56997. {
  56998. setHoverComponent (0);
  56999. }
  57000. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  57001. {
  57002. hoverTimeMillisecs = newTimeInMillisecs;
  57003. }
  57004. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  57005. {
  57006. if (source != newSourceComponent)
  57007. {
  57008. internalTimer.stopTimer();
  57009. hasJustHovered = false;
  57010. if (source != 0)
  57011. {
  57012. // ! you need to delete the hover detector before deleting its component
  57013. jassert (source->isValidComponent());
  57014. source->removeMouseListener (&internalTimer);
  57015. }
  57016. source = newSourceComponent;
  57017. if (newSourceComponent != 0)
  57018. newSourceComponent->addMouseListener (&internalTimer, false);
  57019. }
  57020. }
  57021. void MouseHoverDetector::hoverTimerCallback()
  57022. {
  57023. internalTimer.stopTimer();
  57024. if (source != 0)
  57025. {
  57026. const Point<int> pos (source->getMouseXYRelative());
  57027. if (source->reallyContains (pos.getX(), pos.getY(), false))
  57028. {
  57029. hasJustHovered = true;
  57030. mouseHovered (pos.getX(), pos.getY());
  57031. }
  57032. }
  57033. }
  57034. void MouseHoverDetector::checkJustHoveredCallback()
  57035. {
  57036. if (hasJustHovered)
  57037. {
  57038. hasJustHovered = false;
  57039. mouseMovedAfterHover();
  57040. }
  57041. }
  57042. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  57043. {
  57044. owner->hoverTimerCallback();
  57045. }
  57046. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  57047. {
  57048. stopTimer();
  57049. owner->checkJustHoveredCallback();
  57050. }
  57051. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  57052. {
  57053. stopTimer();
  57054. owner->checkJustHoveredCallback();
  57055. }
  57056. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  57057. {
  57058. stopTimer();
  57059. owner->checkJustHoveredCallback();
  57060. }
  57061. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  57062. {
  57063. stopTimer();
  57064. owner->checkJustHoveredCallback();
  57065. }
  57066. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  57067. {
  57068. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  57069. {
  57070. lastX = e.x;
  57071. lastY = e.y;
  57072. if (owner->source != 0)
  57073. startTimer (owner->hoverTimeMillisecs);
  57074. owner->checkJustHoveredCallback();
  57075. }
  57076. }
  57077. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  57078. {
  57079. stopTimer();
  57080. owner->checkJustHoveredCallback();
  57081. }
  57082. END_JUCE_NAMESPACE
  57083. /*** End of inlined file: juce_MouseHoverDetector.cpp ***/
  57084. /*** Start of inlined file: juce_MouseListener.cpp ***/
  57085. BEGIN_JUCE_NAMESPACE
  57086. void MouseListener::mouseEnter (const MouseEvent&)
  57087. {
  57088. }
  57089. void MouseListener::mouseExit (const MouseEvent&)
  57090. {
  57091. }
  57092. void MouseListener::mouseDown (const MouseEvent&)
  57093. {
  57094. }
  57095. void MouseListener::mouseUp (const MouseEvent&)
  57096. {
  57097. }
  57098. void MouseListener::mouseDrag (const MouseEvent&)
  57099. {
  57100. }
  57101. void MouseListener::mouseMove (const MouseEvent&)
  57102. {
  57103. }
  57104. void MouseListener::mouseDoubleClick (const MouseEvent&)
  57105. {
  57106. }
  57107. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  57108. {
  57109. }
  57110. END_JUCE_NAMESPACE
  57111. /*** End of inlined file: juce_MouseListener.cpp ***/
  57112. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57113. BEGIN_JUCE_NAMESPACE
  57114. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  57115. const String& buttonTextWhenTrue,
  57116. const String& buttonTextWhenFalse)
  57117. : PropertyComponent (name),
  57118. onText (buttonTextWhenTrue),
  57119. offText (buttonTextWhenFalse)
  57120. {
  57121. createButton();
  57122. button->addButtonListener (this);
  57123. }
  57124. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  57125. const String& name,
  57126. const String& buttonText)
  57127. : PropertyComponent (name),
  57128. onText (buttonText),
  57129. offText (buttonText)
  57130. {
  57131. createButton();
  57132. button->setButtonText (buttonText);
  57133. button->getToggleStateValue().referTo (valueToControl);
  57134. button->setClickingTogglesState (true);
  57135. }
  57136. BooleanPropertyComponent::~BooleanPropertyComponent()
  57137. {
  57138. deleteAllChildren();
  57139. }
  57140. void BooleanPropertyComponent::createButton()
  57141. {
  57142. addAndMakeVisible (button = new ToggleButton (String::empty));
  57143. button->setClickingTogglesState (false);
  57144. }
  57145. void BooleanPropertyComponent::setState (const bool newState)
  57146. {
  57147. button->setToggleState (newState, true);
  57148. }
  57149. bool BooleanPropertyComponent::getState() const
  57150. {
  57151. return button->getToggleState();
  57152. }
  57153. void BooleanPropertyComponent::paint (Graphics& g)
  57154. {
  57155. PropertyComponent::paint (g);
  57156. g.setColour (Colours::white);
  57157. g.fillRect (button->getBounds());
  57158. g.setColour (findColour (ComboBox::outlineColourId));
  57159. g.drawRect (button->getBounds());
  57160. }
  57161. void BooleanPropertyComponent::refresh()
  57162. {
  57163. button->setToggleState (getState(), false);
  57164. button->setButtonText (button->getToggleState() ? onText : offText);
  57165. }
  57166. void BooleanPropertyComponent::buttonClicked (Button*)
  57167. {
  57168. setState (! getState());
  57169. }
  57170. END_JUCE_NAMESPACE
  57171. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57172. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57173. BEGIN_JUCE_NAMESPACE
  57174. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  57175. const bool triggerOnMouseDown)
  57176. : PropertyComponent (name)
  57177. {
  57178. addAndMakeVisible (button = new TextButton (String::empty));
  57179. button->setTriggeredOnMouseDown (triggerOnMouseDown);
  57180. button->addButtonListener (this);
  57181. }
  57182. ButtonPropertyComponent::~ButtonPropertyComponent()
  57183. {
  57184. deleteAllChildren();
  57185. }
  57186. void ButtonPropertyComponent::refresh()
  57187. {
  57188. button->setButtonText (getButtonText());
  57189. }
  57190. void ButtonPropertyComponent::buttonClicked (Button*)
  57191. {
  57192. buttonClicked();
  57193. }
  57194. END_JUCE_NAMESPACE
  57195. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57196. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57197. BEGIN_JUCE_NAMESPACE
  57198. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  57199. : PropertyComponent (name),
  57200. comboBox (0)
  57201. {
  57202. }
  57203. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  57204. const String& name,
  57205. const StringArray& choices_,
  57206. const Array <int>* choiceIDs)
  57207. : PropertyComponent (name),
  57208. choices (choices_),
  57209. comboBox (0)
  57210. {
  57211. createComboBox (choiceIDs);
  57212. comboBox->getSelectedIdAsValue().referTo (valueToControl);
  57213. }
  57214. ChoicePropertyComponent::~ChoicePropertyComponent()
  57215. {
  57216. deleteAllChildren();
  57217. }
  57218. void ChoicePropertyComponent::createComboBox (const Array <int>* choiceIDs)
  57219. {
  57220. // The array of IDs must contain the same number of values as the choices list!
  57221. jassert (choiceIDs == 0 || choiceIDs->size() == choices.size());
  57222. addAndMakeVisible (comboBox = new ComboBox (String::empty));
  57223. int itemId = 0;
  57224. for (int i = 0; i < choices.size(); ++i)
  57225. {
  57226. if (choices[i].isNotEmpty())
  57227. comboBox->addItem (choices[i], choiceIDs == 0 ? ++itemId
  57228. : ((*choiceIDs)[i]));
  57229. else
  57230. comboBox->addSeparator();
  57231. }
  57232. comboBox->setEditableText (false);
  57233. }
  57234. void ChoicePropertyComponent::setIndex (const int newIndex)
  57235. {
  57236. comboBox->setSelectedId (comboBox->getItemId (newIndex));
  57237. }
  57238. int ChoicePropertyComponent::getIndex() const
  57239. {
  57240. return comboBox->getSelectedItemIndex();
  57241. }
  57242. const StringArray& ChoicePropertyComponent::getChoices() const
  57243. {
  57244. return choices;
  57245. }
  57246. void ChoicePropertyComponent::refresh()
  57247. {
  57248. if (comboBox == 0)
  57249. {
  57250. createComboBox (0);
  57251. comboBox->addListener (this);
  57252. }
  57253. comboBox->setSelectedId (getIndex() + 1, true);
  57254. }
  57255. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  57256. {
  57257. const int newIndex = comboBox->getSelectedId() - 1;
  57258. if (newIndex != getIndex())
  57259. setIndex (newIndex);
  57260. }
  57261. END_JUCE_NAMESPACE
  57262. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57263. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  57264. BEGIN_JUCE_NAMESPACE
  57265. PropertyComponent::PropertyComponent (const String& name,
  57266. const int preferredHeight_)
  57267. : Component (name),
  57268. preferredHeight (preferredHeight_)
  57269. {
  57270. jassert (name.isNotEmpty());
  57271. }
  57272. PropertyComponent::~PropertyComponent()
  57273. {
  57274. }
  57275. void PropertyComponent::paint (Graphics& g)
  57276. {
  57277. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  57278. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  57279. }
  57280. void PropertyComponent::resized()
  57281. {
  57282. if (getNumChildComponents() > 0)
  57283. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  57284. }
  57285. void PropertyComponent::enablementChanged()
  57286. {
  57287. repaint();
  57288. }
  57289. END_JUCE_NAMESPACE
  57290. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  57291. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  57292. BEGIN_JUCE_NAMESPACE
  57293. class PropertyPanel::PropertyHolderComponent : public Component
  57294. {
  57295. public:
  57296. PropertyHolderComponent()
  57297. {
  57298. }
  57299. ~PropertyHolderComponent()
  57300. {
  57301. deleteAllChildren();
  57302. }
  57303. void paint (Graphics&)
  57304. {
  57305. }
  57306. void updateLayout (int width);
  57307. void refreshAll() const;
  57308. private:
  57309. PropertyHolderComponent (const PropertyHolderComponent&);
  57310. PropertyHolderComponent& operator= (const PropertyHolderComponent&);
  57311. };
  57312. class PropertySectionComponent : public Component
  57313. {
  57314. public:
  57315. PropertySectionComponent (const String& sectionTitle,
  57316. const Array <PropertyComponent*>& newProperties,
  57317. const bool open)
  57318. : Component (sectionTitle),
  57319. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  57320. isOpen_ (open)
  57321. {
  57322. for (int i = newProperties.size(); --i >= 0;)
  57323. {
  57324. addAndMakeVisible (newProperties.getUnchecked(i));
  57325. newProperties.getUnchecked(i)->refresh();
  57326. }
  57327. }
  57328. ~PropertySectionComponent()
  57329. {
  57330. deleteAllChildren();
  57331. }
  57332. void paint (Graphics& g)
  57333. {
  57334. if (titleHeight > 0)
  57335. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  57336. }
  57337. void resized()
  57338. {
  57339. int y = titleHeight;
  57340. for (int i = getNumChildComponents(); --i >= 0;)
  57341. {
  57342. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57343. if (pec != 0)
  57344. {
  57345. const int prefH = pec->getPreferredHeight();
  57346. pec->setBounds (1, y, getWidth() - 2, prefH);
  57347. y += prefH;
  57348. }
  57349. }
  57350. }
  57351. int getPreferredHeight() const
  57352. {
  57353. int y = titleHeight;
  57354. if (isOpen())
  57355. {
  57356. for (int i = 0; i < getNumChildComponents(); ++i)
  57357. {
  57358. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57359. if (pec != 0)
  57360. y += pec->getPreferredHeight();
  57361. }
  57362. }
  57363. return y;
  57364. }
  57365. void setOpen (const bool open)
  57366. {
  57367. if (isOpen_ != open)
  57368. {
  57369. isOpen_ = open;
  57370. for (int i = 0; i < getNumChildComponents(); ++i)
  57371. {
  57372. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57373. if (pec != 0)
  57374. pec->setVisible (open);
  57375. }
  57376. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  57377. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  57378. if (pp != 0)
  57379. pp->resized();
  57380. }
  57381. }
  57382. bool isOpen() const
  57383. {
  57384. return isOpen_;
  57385. }
  57386. void refreshAll() const
  57387. {
  57388. for (int i = 0; i < getNumChildComponents(); ++i)
  57389. {
  57390. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57391. if (pec != 0)
  57392. pec->refresh();
  57393. }
  57394. }
  57395. void mouseDown (const MouseEvent&)
  57396. {
  57397. }
  57398. void mouseUp (const MouseEvent& e)
  57399. {
  57400. if (e.getMouseDownX() < titleHeight
  57401. && e.x < titleHeight
  57402. && e.y < titleHeight
  57403. && e.getNumberOfClicks() != 2)
  57404. {
  57405. setOpen (! isOpen());
  57406. }
  57407. }
  57408. void mouseDoubleClick (const MouseEvent& e)
  57409. {
  57410. if (e.y < titleHeight)
  57411. setOpen (! isOpen());
  57412. }
  57413. private:
  57414. int titleHeight;
  57415. bool isOpen_;
  57416. PropertySectionComponent (const PropertySectionComponent&);
  57417. PropertySectionComponent& operator= (const PropertySectionComponent&);
  57418. };
  57419. void PropertyPanel::PropertyHolderComponent::updateLayout (const int width)
  57420. {
  57421. int y = 0;
  57422. for (int i = getNumChildComponents(); --i >= 0;)
  57423. {
  57424. PropertySectionComponent* const section
  57425. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  57426. if (section != 0)
  57427. {
  57428. const int prefH = section->getPreferredHeight();
  57429. section->setBounds (0, y, width, prefH);
  57430. y += prefH;
  57431. }
  57432. }
  57433. setSize (width, y);
  57434. repaint();
  57435. }
  57436. void PropertyPanel::PropertyHolderComponent::refreshAll() const
  57437. {
  57438. for (int i = getNumChildComponents(); --i >= 0;)
  57439. {
  57440. PropertySectionComponent* const section
  57441. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  57442. if (section != 0)
  57443. section->refreshAll();
  57444. }
  57445. }
  57446. PropertyPanel::PropertyPanel()
  57447. {
  57448. messageWhenEmpty = TRANS("(nothing selected)");
  57449. addAndMakeVisible (viewport = new Viewport());
  57450. viewport->setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  57451. viewport->setFocusContainer (true);
  57452. }
  57453. PropertyPanel::~PropertyPanel()
  57454. {
  57455. clear();
  57456. deleteAllChildren();
  57457. }
  57458. void PropertyPanel::paint (Graphics& g)
  57459. {
  57460. if (propertyHolderComponent->getNumChildComponents() == 0)
  57461. {
  57462. g.setColour (Colours::black.withAlpha (0.5f));
  57463. g.setFont (14.0f);
  57464. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  57465. Justification::centred, true);
  57466. }
  57467. }
  57468. void PropertyPanel::resized()
  57469. {
  57470. viewport->setBounds (0, 0, getWidth(), getHeight());
  57471. updatePropHolderLayout();
  57472. }
  57473. void PropertyPanel::clear()
  57474. {
  57475. if (propertyHolderComponent->getNumChildComponents() > 0)
  57476. {
  57477. propertyHolderComponent->deleteAllChildren();
  57478. repaint();
  57479. }
  57480. }
  57481. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  57482. {
  57483. if (propertyHolderComponent->getNumChildComponents() == 0)
  57484. repaint();
  57485. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  57486. newProperties,
  57487. true), 0);
  57488. updatePropHolderLayout();
  57489. }
  57490. void PropertyPanel::addSection (const String& sectionTitle,
  57491. const Array <PropertyComponent*>& newProperties,
  57492. const bool shouldBeOpen)
  57493. {
  57494. jassert (sectionTitle.isNotEmpty());
  57495. if (propertyHolderComponent->getNumChildComponents() == 0)
  57496. repaint();
  57497. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  57498. newProperties,
  57499. shouldBeOpen), 0);
  57500. updatePropHolderLayout();
  57501. }
  57502. void PropertyPanel::updatePropHolderLayout() const
  57503. {
  57504. const int maxWidth = viewport->getMaximumVisibleWidth();
  57505. propertyHolderComponent->updateLayout (maxWidth);
  57506. const int newMaxWidth = viewport->getMaximumVisibleWidth();
  57507. if (maxWidth != newMaxWidth)
  57508. {
  57509. // need to do this twice because of scrollbars changing the size, etc.
  57510. propertyHolderComponent->updateLayout (newMaxWidth);
  57511. }
  57512. }
  57513. void PropertyPanel::refreshAll() const
  57514. {
  57515. propertyHolderComponent->refreshAll();
  57516. }
  57517. const StringArray PropertyPanel::getSectionNames() const
  57518. {
  57519. StringArray s;
  57520. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57521. {
  57522. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57523. if (section != 0 && section->getName().isNotEmpty())
  57524. s.add (section->getName());
  57525. }
  57526. return s;
  57527. }
  57528. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  57529. {
  57530. int index = 0;
  57531. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57532. {
  57533. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57534. if (section != 0 && section->getName().isNotEmpty())
  57535. {
  57536. if (index == sectionIndex)
  57537. return section->isOpen();
  57538. ++index;
  57539. }
  57540. }
  57541. return false;
  57542. }
  57543. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  57544. {
  57545. int index = 0;
  57546. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57547. {
  57548. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57549. if (section != 0 && section->getName().isNotEmpty())
  57550. {
  57551. if (index == sectionIndex)
  57552. {
  57553. section->setOpen (shouldBeOpen);
  57554. break;
  57555. }
  57556. ++index;
  57557. }
  57558. }
  57559. }
  57560. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  57561. {
  57562. int index = 0;
  57563. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57564. {
  57565. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57566. if (section != 0 && section->getName().isNotEmpty())
  57567. {
  57568. if (index == sectionIndex)
  57569. {
  57570. section->setEnabled (shouldBeEnabled);
  57571. break;
  57572. }
  57573. ++index;
  57574. }
  57575. }
  57576. }
  57577. XmlElement* PropertyPanel::getOpennessState() const
  57578. {
  57579. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  57580. xml->setAttribute ("scrollPos", viewport->getViewPositionY());
  57581. const StringArray sections (getSectionNames());
  57582. for (int i = 0; i < sections.size(); ++i)
  57583. {
  57584. if (sections[i].isNotEmpty())
  57585. {
  57586. XmlElement* const e = xml->createNewChildElement ("SECTION");
  57587. e->setAttribute ("name", sections[i]);
  57588. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  57589. }
  57590. }
  57591. return xml;
  57592. }
  57593. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  57594. {
  57595. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  57596. {
  57597. const StringArray sections (getSectionNames());
  57598. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  57599. {
  57600. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  57601. e->getBoolAttribute ("open"));
  57602. }
  57603. viewport->setViewPosition (viewport->getViewPositionX(),
  57604. xml.getIntAttribute ("scrollPos", viewport->getViewPositionY()));
  57605. }
  57606. }
  57607. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  57608. {
  57609. if (messageWhenEmpty != newMessage)
  57610. {
  57611. messageWhenEmpty = newMessage;
  57612. repaint();
  57613. }
  57614. }
  57615. const String& PropertyPanel::getMessageWhenEmpty() const
  57616. {
  57617. return messageWhenEmpty;
  57618. }
  57619. END_JUCE_NAMESPACE
  57620. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  57621. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  57622. BEGIN_JUCE_NAMESPACE
  57623. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  57624. const double rangeMin,
  57625. const double rangeMax,
  57626. const double interval,
  57627. const double skewFactor)
  57628. : PropertyComponent (name)
  57629. {
  57630. addAndMakeVisible (slider = new Slider (name));
  57631. slider->setRange (rangeMin, rangeMax, interval);
  57632. slider->setSkewFactor (skewFactor);
  57633. slider->setSliderStyle (Slider::LinearBar);
  57634. slider->addListener (this);
  57635. }
  57636. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  57637. const String& name,
  57638. const double rangeMin,
  57639. const double rangeMax,
  57640. const double interval,
  57641. const double skewFactor)
  57642. : PropertyComponent (name)
  57643. {
  57644. addAndMakeVisible (slider = new Slider (name));
  57645. slider->setRange (rangeMin, rangeMax, interval);
  57646. slider->setSkewFactor (skewFactor);
  57647. slider->setSliderStyle (Slider::LinearBar);
  57648. slider->getValueObject().referTo (valueToControl);
  57649. }
  57650. SliderPropertyComponent::~SliderPropertyComponent()
  57651. {
  57652. deleteAllChildren();
  57653. }
  57654. void SliderPropertyComponent::setValue (const double /*newValue*/)
  57655. {
  57656. }
  57657. double SliderPropertyComponent::getValue() const
  57658. {
  57659. return slider->getValue();
  57660. }
  57661. void SliderPropertyComponent::refresh()
  57662. {
  57663. slider->setValue (getValue(), false);
  57664. }
  57665. void SliderPropertyComponent::sliderValueChanged (Slider*)
  57666. {
  57667. if (getValue() != slider->getValue())
  57668. setValue (slider->getValue());
  57669. }
  57670. END_JUCE_NAMESPACE
  57671. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  57672. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  57673. BEGIN_JUCE_NAMESPACE
  57674. class TextPropLabel : public Label
  57675. {
  57676. TextPropertyComponent& owner;
  57677. int maxChars;
  57678. bool isMultiline;
  57679. public:
  57680. TextPropLabel (TextPropertyComponent& owner_,
  57681. const int maxChars_, const bool isMultiline_)
  57682. : Label (String::empty, String::empty),
  57683. owner (owner_),
  57684. maxChars (maxChars_),
  57685. isMultiline (isMultiline_)
  57686. {
  57687. setEditable (true, true, false);
  57688. setColour (backgroundColourId, Colours::white);
  57689. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  57690. }
  57691. ~TextPropLabel()
  57692. {
  57693. }
  57694. TextEditor* createEditorComponent()
  57695. {
  57696. TextEditor* const textEditor = Label::createEditorComponent();
  57697. textEditor->setInputRestrictions (maxChars);
  57698. if (isMultiline)
  57699. {
  57700. textEditor->setMultiLine (true, true);
  57701. textEditor->setReturnKeyStartsNewLine (true);
  57702. }
  57703. return textEditor;
  57704. }
  57705. void textWasEdited()
  57706. {
  57707. owner.textWasEdited();
  57708. }
  57709. };
  57710. TextPropertyComponent::TextPropertyComponent (const String& name,
  57711. const int maxNumChars,
  57712. const bool isMultiLine)
  57713. : PropertyComponent (name)
  57714. {
  57715. createEditor (maxNumChars, isMultiLine);
  57716. }
  57717. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  57718. const String& name,
  57719. const int maxNumChars,
  57720. const bool isMultiLine)
  57721. : PropertyComponent (name)
  57722. {
  57723. createEditor (maxNumChars, isMultiLine);
  57724. textEditor->getTextValue().referTo (valueToControl);
  57725. }
  57726. TextPropertyComponent::~TextPropertyComponent()
  57727. {
  57728. deleteAllChildren();
  57729. }
  57730. void TextPropertyComponent::setText (const String& newText)
  57731. {
  57732. textEditor->setText (newText, true);
  57733. }
  57734. const String TextPropertyComponent::getText() const
  57735. {
  57736. return textEditor->getText();
  57737. }
  57738. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  57739. {
  57740. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  57741. if (isMultiLine)
  57742. {
  57743. textEditor->setJustificationType (Justification::topLeft);
  57744. preferredHeight = 120;
  57745. }
  57746. }
  57747. void TextPropertyComponent::refresh()
  57748. {
  57749. textEditor->setText (getText(), false);
  57750. }
  57751. void TextPropertyComponent::textWasEdited()
  57752. {
  57753. const String newText (textEditor->getText());
  57754. if (getText() != newText)
  57755. setText (newText);
  57756. }
  57757. END_JUCE_NAMESPACE
  57758. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  57759. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  57760. BEGIN_JUCE_NAMESPACE
  57761. class SimpleDeviceManagerInputLevelMeter : public Component,
  57762. public Timer
  57763. {
  57764. public:
  57765. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  57766. : manager (manager_),
  57767. level (0)
  57768. {
  57769. startTimer (50);
  57770. manager->enableInputLevelMeasurement (true);
  57771. }
  57772. ~SimpleDeviceManagerInputLevelMeter()
  57773. {
  57774. manager->enableInputLevelMeasurement (false);
  57775. }
  57776. void timerCallback()
  57777. {
  57778. const float newLevel = (float) manager->getCurrentInputLevel();
  57779. if (std::abs (level - newLevel) > 0.005f)
  57780. {
  57781. level = newLevel;
  57782. repaint();
  57783. }
  57784. }
  57785. void paint (Graphics& g)
  57786. {
  57787. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  57788. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  57789. }
  57790. private:
  57791. AudioDeviceManager* const manager;
  57792. float level;
  57793. SimpleDeviceManagerInputLevelMeter (const SimpleDeviceManagerInputLevelMeter&);
  57794. SimpleDeviceManagerInputLevelMeter& operator= (const SimpleDeviceManagerInputLevelMeter&);
  57795. };
  57796. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  57797. public ListBoxModel
  57798. {
  57799. public:
  57800. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  57801. const String& noItemsMessage_,
  57802. const int minNumber_,
  57803. const int maxNumber_)
  57804. : ListBox (String::empty, 0),
  57805. deviceManager (deviceManager_),
  57806. noItemsMessage (noItemsMessage_),
  57807. minNumber (minNumber_),
  57808. maxNumber (maxNumber_)
  57809. {
  57810. items = MidiInput::getDevices();
  57811. setModel (this);
  57812. setOutlineThickness (1);
  57813. }
  57814. ~MidiInputSelectorComponentListBox()
  57815. {
  57816. }
  57817. int getNumRows()
  57818. {
  57819. return items.size();
  57820. }
  57821. void paintListBoxItem (int row,
  57822. Graphics& g,
  57823. int width, int height,
  57824. bool rowIsSelected)
  57825. {
  57826. if (((unsigned int) row) < (unsigned int) items.size())
  57827. {
  57828. if (rowIsSelected)
  57829. g.fillAll (findColour (TextEditor::highlightColourId)
  57830. .withMultipliedAlpha (0.3f));
  57831. const String item (items [row]);
  57832. bool enabled = deviceManager.isMidiInputEnabled (item);
  57833. const int x = getTickX();
  57834. const float tickW = height * 0.75f;
  57835. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  57836. enabled, true, true, false);
  57837. g.setFont (height * 0.6f);
  57838. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  57839. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  57840. }
  57841. }
  57842. void listBoxItemClicked (int row, const MouseEvent& e)
  57843. {
  57844. selectRow (row);
  57845. if (e.x < getTickX())
  57846. flipEnablement (row);
  57847. }
  57848. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  57849. {
  57850. flipEnablement (row);
  57851. }
  57852. void returnKeyPressed (int row)
  57853. {
  57854. flipEnablement (row);
  57855. }
  57856. void paint (Graphics& g)
  57857. {
  57858. ListBox::paint (g);
  57859. if (items.size() == 0)
  57860. {
  57861. g.setColour (Colours::grey);
  57862. g.setFont (13.0f);
  57863. g.drawText (noItemsMessage,
  57864. 0, 0, getWidth(), getHeight() / 2,
  57865. Justification::centred, true);
  57866. }
  57867. }
  57868. int getBestHeight (const int preferredHeight)
  57869. {
  57870. const int extra = getOutlineThickness() * 2;
  57871. return jmax (getRowHeight() * 2 + extra,
  57872. jmin (getRowHeight() * getNumRows() + extra,
  57873. preferredHeight));
  57874. }
  57875. juce_UseDebuggingNewOperator
  57876. private:
  57877. AudioDeviceManager& deviceManager;
  57878. const String noItemsMessage;
  57879. StringArray items;
  57880. int minNumber, maxNumber;
  57881. void flipEnablement (const int row)
  57882. {
  57883. if (((unsigned int) row) < (unsigned int) items.size())
  57884. {
  57885. const String item (items [row]);
  57886. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  57887. }
  57888. }
  57889. int getTickX() const
  57890. {
  57891. return getRowHeight() + 5;
  57892. }
  57893. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  57894. MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  57895. };
  57896. class AudioDeviceSettingsPanel : public Component,
  57897. public ComboBoxListener,
  57898. public ChangeListener,
  57899. public ButtonListener
  57900. {
  57901. public:
  57902. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  57903. AudioIODeviceType::DeviceSetupDetails& setup_,
  57904. const bool hideAdvancedOptionsWithButton)
  57905. : type (type_),
  57906. setup (setup_)
  57907. {
  57908. sampleRateDropDown = 0;
  57909. sampleRateLabel = 0;
  57910. bufferSizeDropDown = 0;
  57911. bufferSizeLabel = 0;
  57912. outputDeviceDropDown = 0;
  57913. outputDeviceLabel = 0;
  57914. inputDeviceDropDown = 0;
  57915. inputDeviceLabel = 0;
  57916. testButton = 0;
  57917. inputLevelMeter = 0;
  57918. showUIButton = 0;
  57919. inputChanList = 0;
  57920. outputChanList = 0;
  57921. inputChanLabel = 0;
  57922. outputChanLabel = 0;
  57923. showAdvancedSettingsButton = 0;
  57924. if (hideAdvancedOptionsWithButton)
  57925. {
  57926. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  57927. showAdvancedSettingsButton->addButtonListener (this);
  57928. }
  57929. type->scanForDevices();
  57930. setup.manager->addChangeListener (this);
  57931. changeListenerCallback (0);
  57932. }
  57933. ~AudioDeviceSettingsPanel()
  57934. {
  57935. setup.manager->removeChangeListener (this);
  57936. deleteAndZero (outputDeviceLabel);
  57937. deleteAndZero (inputDeviceLabel);
  57938. deleteAndZero (sampleRateLabel);
  57939. deleteAndZero (bufferSizeLabel);
  57940. deleteAndZero (showUIButton);
  57941. deleteAndZero (inputChanLabel);
  57942. deleteAndZero (outputChanLabel);
  57943. deleteAndZero (showAdvancedSettingsButton);
  57944. deleteAllChildren();
  57945. }
  57946. void resized()
  57947. {
  57948. const int lx = proportionOfWidth (0.35f);
  57949. const int w = proportionOfWidth (0.4f);
  57950. const int h = 24;
  57951. const int space = 6;
  57952. const int dh = h + space;
  57953. int y = 0;
  57954. if (outputDeviceDropDown != 0)
  57955. {
  57956. outputDeviceDropDown->setBounds (lx, y, w, h);
  57957. if (testButton != 0)
  57958. testButton->setBounds (proportionOfWidth (0.77f),
  57959. outputDeviceDropDown->getY(),
  57960. proportionOfWidth (0.18f),
  57961. h);
  57962. y += dh;
  57963. }
  57964. if (inputDeviceDropDown != 0)
  57965. {
  57966. inputDeviceDropDown->setBounds (lx, y, w, h);
  57967. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  57968. inputDeviceDropDown->getY(),
  57969. proportionOfWidth (0.18f),
  57970. h);
  57971. y += dh;
  57972. }
  57973. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  57974. if (outputChanList != 0)
  57975. {
  57976. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  57977. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  57978. y += bh + space;
  57979. }
  57980. if (inputChanList != 0)
  57981. {
  57982. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  57983. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  57984. y += bh + space;
  57985. }
  57986. y += space * 2;
  57987. if (showAdvancedSettingsButton != 0)
  57988. {
  57989. showAdvancedSettingsButton->changeWidthToFitText (h);
  57990. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  57991. }
  57992. if (sampleRateDropDown != 0)
  57993. {
  57994. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  57995. || ! showAdvancedSettingsButton->isVisible());
  57996. sampleRateDropDown->setBounds (lx, y, w, h);
  57997. y += dh;
  57998. }
  57999. if (bufferSizeDropDown != 0)
  58000. {
  58001. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  58002. || ! showAdvancedSettingsButton->isVisible());
  58003. bufferSizeDropDown->setBounds (lx, y, w, h);
  58004. y += dh;
  58005. }
  58006. if (showUIButton != 0)
  58007. {
  58008. showUIButton->setVisible (showAdvancedSettingsButton == 0
  58009. || ! showAdvancedSettingsButton->isVisible());
  58010. showUIButton->changeWidthToFitText (h);
  58011. showUIButton->setTopLeftPosition (lx, y);
  58012. }
  58013. }
  58014. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58015. {
  58016. if (comboBoxThatHasChanged == 0)
  58017. return;
  58018. AudioDeviceManager::AudioDeviceSetup config;
  58019. setup.manager->getAudioDeviceSetup (config);
  58020. String error;
  58021. if (comboBoxThatHasChanged == outputDeviceDropDown
  58022. || comboBoxThatHasChanged == inputDeviceDropDown)
  58023. {
  58024. if (outputDeviceDropDown != 0)
  58025. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58026. : outputDeviceDropDown->getText();
  58027. if (inputDeviceDropDown != 0)
  58028. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58029. : inputDeviceDropDown->getText();
  58030. if (! type->hasSeparateInputsAndOutputs())
  58031. config.inputDeviceName = config.outputDeviceName;
  58032. if (comboBoxThatHasChanged == inputDeviceDropDown)
  58033. config.useDefaultInputChannels = true;
  58034. else
  58035. config.useDefaultOutputChannels = true;
  58036. error = setup.manager->setAudioDeviceSetup (config, true);
  58037. showCorrectDeviceName (inputDeviceDropDown, true);
  58038. showCorrectDeviceName (outputDeviceDropDown, false);
  58039. updateControlPanelButton();
  58040. resized();
  58041. }
  58042. else if (comboBoxThatHasChanged == sampleRateDropDown)
  58043. {
  58044. if (sampleRateDropDown->getSelectedId() > 0)
  58045. {
  58046. config.sampleRate = sampleRateDropDown->getSelectedId();
  58047. error = setup.manager->setAudioDeviceSetup (config, true);
  58048. }
  58049. }
  58050. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  58051. {
  58052. if (bufferSizeDropDown->getSelectedId() > 0)
  58053. {
  58054. config.bufferSize = bufferSizeDropDown->getSelectedId();
  58055. error = setup.manager->setAudioDeviceSetup (config, true);
  58056. }
  58057. }
  58058. if (error.isNotEmpty())
  58059. {
  58060. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  58061. "Error when trying to open audio device!",
  58062. error);
  58063. }
  58064. }
  58065. void buttonClicked (Button* button)
  58066. {
  58067. if (button == showAdvancedSettingsButton)
  58068. {
  58069. showAdvancedSettingsButton->setVisible (false);
  58070. resized();
  58071. }
  58072. else if (button == showUIButton)
  58073. {
  58074. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  58075. if (device != 0 && device->showControlPanel())
  58076. {
  58077. setup.manager->closeAudioDevice();
  58078. setup.manager->restartLastAudioDevice();
  58079. getTopLevelComponent()->toFront (true);
  58080. }
  58081. }
  58082. else if (button == testButton && testButton != 0)
  58083. {
  58084. setup.manager->playTestSound();
  58085. }
  58086. }
  58087. void updateControlPanelButton()
  58088. {
  58089. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58090. deleteAndZero (showUIButton);
  58091. if (currentDevice != 0 && currentDevice->hasControlPanel())
  58092. {
  58093. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  58094. TRANS ("opens the device's own control panel")));
  58095. showUIButton->addButtonListener (this);
  58096. }
  58097. resized();
  58098. }
  58099. void changeListenerCallback (void*)
  58100. {
  58101. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58102. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  58103. {
  58104. if (outputDeviceDropDown == 0)
  58105. {
  58106. outputDeviceDropDown = new ComboBox (String::empty);
  58107. outputDeviceDropDown->addListener (this);
  58108. addAndMakeVisible (outputDeviceDropDown);
  58109. outputDeviceLabel = new Label (String::empty,
  58110. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  58111. : TRANS ("device:"));
  58112. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  58113. if (setup.maxNumOutputChannels > 0)
  58114. {
  58115. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  58116. testButton->addButtonListener (this);
  58117. }
  58118. }
  58119. addNamesToDeviceBox (*outputDeviceDropDown, false);
  58120. }
  58121. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  58122. {
  58123. if (inputDeviceDropDown == 0)
  58124. {
  58125. inputDeviceDropDown = new ComboBox (String::empty);
  58126. inputDeviceDropDown->addListener (this);
  58127. addAndMakeVisible (inputDeviceDropDown);
  58128. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  58129. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  58130. addAndMakeVisible (inputLevelMeter
  58131. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  58132. }
  58133. addNamesToDeviceBox (*inputDeviceDropDown, true);
  58134. }
  58135. updateControlPanelButton();
  58136. showCorrectDeviceName (inputDeviceDropDown, true);
  58137. showCorrectDeviceName (outputDeviceDropDown, false);
  58138. if (currentDevice != 0)
  58139. {
  58140. if (setup.maxNumOutputChannels > 0
  58141. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  58142. {
  58143. if (outputChanList == 0)
  58144. {
  58145. addAndMakeVisible (outputChanList
  58146. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  58147. TRANS ("(no audio output channels found)")));
  58148. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  58149. outputChanLabel->attachToComponent (outputChanList, true);
  58150. }
  58151. outputChanList->refresh();
  58152. }
  58153. else
  58154. {
  58155. deleteAndZero (outputChanLabel);
  58156. deleteAndZero (outputChanList);
  58157. }
  58158. if (setup.maxNumInputChannels > 0
  58159. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  58160. {
  58161. if (inputChanList == 0)
  58162. {
  58163. addAndMakeVisible (inputChanList
  58164. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  58165. TRANS ("(no audio input channels found)")));
  58166. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  58167. inputChanLabel->attachToComponent (inputChanList, true);
  58168. }
  58169. inputChanList->refresh();
  58170. }
  58171. else
  58172. {
  58173. deleteAndZero (inputChanLabel);
  58174. deleteAndZero (inputChanList);
  58175. }
  58176. // sample rate..
  58177. {
  58178. if (sampleRateDropDown == 0)
  58179. {
  58180. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  58181. sampleRateDropDown->addListener (this);
  58182. delete sampleRateLabel;
  58183. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  58184. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  58185. }
  58186. else
  58187. {
  58188. sampleRateDropDown->clear();
  58189. sampleRateDropDown->removeListener (this);
  58190. }
  58191. const int numRates = currentDevice->getNumSampleRates();
  58192. for (int i = 0; i < numRates; ++i)
  58193. {
  58194. const int rate = roundToInt (currentDevice->getSampleRate (i));
  58195. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  58196. }
  58197. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  58198. sampleRateDropDown->addListener (this);
  58199. }
  58200. // buffer size
  58201. {
  58202. if (bufferSizeDropDown == 0)
  58203. {
  58204. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  58205. bufferSizeDropDown->addListener (this);
  58206. delete bufferSizeLabel;
  58207. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  58208. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  58209. }
  58210. else
  58211. {
  58212. bufferSizeDropDown->clear();
  58213. }
  58214. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  58215. double currentRate = currentDevice->getCurrentSampleRate();
  58216. if (currentRate == 0)
  58217. currentRate = 48000.0;
  58218. for (int i = 0; i < numBufferSizes; ++i)
  58219. {
  58220. const int bs = currentDevice->getBufferSizeSamples (i);
  58221. bufferSizeDropDown->addItem (String (bs)
  58222. + " samples ("
  58223. + String (bs * 1000.0 / currentRate, 1)
  58224. + " ms)",
  58225. bs);
  58226. }
  58227. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  58228. }
  58229. }
  58230. else
  58231. {
  58232. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  58233. deleteAndZero (sampleRateLabel);
  58234. deleteAndZero (bufferSizeLabel);
  58235. deleteAndZero (sampleRateDropDown);
  58236. deleteAndZero (bufferSizeDropDown);
  58237. if (outputDeviceDropDown != 0)
  58238. outputDeviceDropDown->setSelectedId (-1, true);
  58239. if (inputDeviceDropDown != 0)
  58240. inputDeviceDropDown->setSelectedId (-1, true);
  58241. }
  58242. resized();
  58243. setSize (getWidth(), getLowestY() + 4);
  58244. }
  58245. private:
  58246. AudioIODeviceType* const type;
  58247. const AudioIODeviceType::DeviceSetupDetails setup;
  58248. ComboBox* outputDeviceDropDown;
  58249. ComboBox* inputDeviceDropDown;
  58250. ComboBox* sampleRateDropDown;
  58251. ComboBox* bufferSizeDropDown;
  58252. Label* outputDeviceLabel;
  58253. Label* inputDeviceLabel;
  58254. Label* sampleRateLabel;
  58255. Label* bufferSizeLabel;
  58256. Label* inputChanLabel;
  58257. Label* outputChanLabel;
  58258. TextButton* testButton;
  58259. Component* inputLevelMeter;
  58260. TextButton* showUIButton;
  58261. TextButton* showAdvancedSettingsButton;
  58262. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  58263. {
  58264. if (box != 0)
  58265. {
  58266. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  58267. const int index = type->getIndexOfDevice (currentDevice, isInput);
  58268. box->setSelectedId (index + 1, true);
  58269. if (testButton != 0 && ! isInput)
  58270. testButton->setEnabled (index >= 0);
  58271. }
  58272. }
  58273. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  58274. {
  58275. const StringArray devs (type->getDeviceNames (isInputs));
  58276. combo.clear (true);
  58277. for (int i = 0; i < devs.size(); ++i)
  58278. combo.addItem (devs[i], i + 1);
  58279. combo.addItem (TRANS("<< none >>"), -1);
  58280. combo.setSelectedId (-1, true);
  58281. }
  58282. int getLowestY() const
  58283. {
  58284. int y = 0;
  58285. for (int i = getNumChildComponents(); --i >= 0;)
  58286. y = jmax (y, getChildComponent (i)->getBottom());
  58287. return y;
  58288. }
  58289. public:
  58290. class ChannelSelectorListBox : public ListBox,
  58291. public ListBoxModel
  58292. {
  58293. public:
  58294. enum BoxType
  58295. {
  58296. audioInputType,
  58297. audioOutputType
  58298. };
  58299. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  58300. const BoxType type_,
  58301. const String& noItemsMessage_)
  58302. : ListBox (String::empty, 0),
  58303. setup (setup_),
  58304. type (type_),
  58305. noItemsMessage (noItemsMessage_)
  58306. {
  58307. refresh();
  58308. setModel (this);
  58309. setOutlineThickness (1);
  58310. }
  58311. ~ChannelSelectorListBox()
  58312. {
  58313. }
  58314. void refresh()
  58315. {
  58316. items.clear();
  58317. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58318. if (currentDevice != 0)
  58319. {
  58320. if (type == audioInputType)
  58321. items = currentDevice->getInputChannelNames();
  58322. else if (type == audioOutputType)
  58323. items = currentDevice->getOutputChannelNames();
  58324. if (setup.useStereoPairs)
  58325. {
  58326. StringArray pairs;
  58327. for (int i = 0; i < items.size(); i += 2)
  58328. {
  58329. const String name (items[i]);
  58330. const String name2 (items[i + 1]);
  58331. String commonBit;
  58332. for (int j = 0; j < name.length(); ++j)
  58333. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  58334. commonBit = name.substring (0, j);
  58335. // Make sure we only split the name at a space, because otherwise, things
  58336. // like "input 11" + "input 12" would become "input 11 + 2"
  58337. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  58338. commonBit = commonBit.dropLastCharacters (1);
  58339. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  58340. }
  58341. items = pairs;
  58342. }
  58343. }
  58344. updateContent();
  58345. repaint();
  58346. }
  58347. int getNumRows()
  58348. {
  58349. return items.size();
  58350. }
  58351. void paintListBoxItem (int row,
  58352. Graphics& g,
  58353. int width, int height,
  58354. bool rowIsSelected)
  58355. {
  58356. if (((unsigned int) row) < (unsigned int) items.size())
  58357. {
  58358. if (rowIsSelected)
  58359. g.fillAll (findColour (TextEditor::highlightColourId)
  58360. .withMultipliedAlpha (0.3f));
  58361. const String item (items [row]);
  58362. bool enabled = false;
  58363. AudioDeviceManager::AudioDeviceSetup config;
  58364. setup.manager->getAudioDeviceSetup (config);
  58365. if (setup.useStereoPairs)
  58366. {
  58367. if (type == audioInputType)
  58368. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  58369. else if (type == audioOutputType)
  58370. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  58371. }
  58372. else
  58373. {
  58374. if (type == audioInputType)
  58375. enabled = config.inputChannels [row];
  58376. else if (type == audioOutputType)
  58377. enabled = config.outputChannels [row];
  58378. }
  58379. const int x = getTickX();
  58380. const float tickW = height * 0.75f;
  58381. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58382. enabled, true, true, false);
  58383. g.setFont (height * 0.6f);
  58384. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58385. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58386. }
  58387. }
  58388. void listBoxItemClicked (int row, const MouseEvent& e)
  58389. {
  58390. selectRow (row);
  58391. if (e.x < getTickX())
  58392. flipEnablement (row);
  58393. }
  58394. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58395. {
  58396. flipEnablement (row);
  58397. }
  58398. void returnKeyPressed (int row)
  58399. {
  58400. flipEnablement (row);
  58401. }
  58402. void paint (Graphics& g)
  58403. {
  58404. ListBox::paint (g);
  58405. if (items.size() == 0)
  58406. {
  58407. g.setColour (Colours::grey);
  58408. g.setFont (13.0f);
  58409. g.drawText (noItemsMessage,
  58410. 0, 0, getWidth(), getHeight() / 2,
  58411. Justification::centred, true);
  58412. }
  58413. }
  58414. int getBestHeight (int maxHeight)
  58415. {
  58416. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  58417. getNumRows())
  58418. + getOutlineThickness() * 2;
  58419. }
  58420. juce_UseDebuggingNewOperator
  58421. private:
  58422. const AudioIODeviceType::DeviceSetupDetails setup;
  58423. const BoxType type;
  58424. const String noItemsMessage;
  58425. StringArray items;
  58426. void flipEnablement (const int row)
  58427. {
  58428. jassert (type == audioInputType || type == audioOutputType);
  58429. if (((unsigned int) row) < (unsigned int) items.size())
  58430. {
  58431. AudioDeviceManager::AudioDeviceSetup config;
  58432. setup.manager->getAudioDeviceSetup (config);
  58433. if (setup.useStereoPairs)
  58434. {
  58435. BigInteger bits;
  58436. BigInteger& original = (type == audioInputType ? config.inputChannels
  58437. : config.outputChannels);
  58438. int i;
  58439. for (i = 0; i < 256; i += 2)
  58440. bits.setBit (i / 2, original [i] || original [i + 1]);
  58441. if (type == audioInputType)
  58442. {
  58443. config.useDefaultInputChannels = false;
  58444. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  58445. }
  58446. else
  58447. {
  58448. config.useDefaultOutputChannels = false;
  58449. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  58450. }
  58451. for (i = 0; i < 256; ++i)
  58452. original.setBit (i, bits [i / 2]);
  58453. }
  58454. else
  58455. {
  58456. if (type == audioInputType)
  58457. {
  58458. config.useDefaultInputChannels = false;
  58459. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  58460. }
  58461. else
  58462. {
  58463. config.useDefaultOutputChannels = false;
  58464. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  58465. }
  58466. }
  58467. String error (setup.manager->setAudioDeviceSetup (config, true));
  58468. if (! error.isEmpty())
  58469. {
  58470. //xxx
  58471. }
  58472. }
  58473. }
  58474. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  58475. {
  58476. const int numActive = chans.countNumberOfSetBits();
  58477. if (chans [index])
  58478. {
  58479. if (numActive > minNumber)
  58480. chans.setBit (index, false);
  58481. }
  58482. else
  58483. {
  58484. if (numActive >= maxNumber)
  58485. {
  58486. const int firstActiveChan = chans.findNextSetBit();
  58487. chans.setBit (index > firstActiveChan
  58488. ? firstActiveChan : chans.getHighestBit(),
  58489. false);
  58490. }
  58491. chans.setBit (index, true);
  58492. }
  58493. }
  58494. int getTickX() const
  58495. {
  58496. return getRowHeight() + 5;
  58497. }
  58498. ChannelSelectorListBox (const ChannelSelectorListBox&);
  58499. ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  58500. };
  58501. private:
  58502. ChannelSelectorListBox* inputChanList;
  58503. ChannelSelectorListBox* outputChanList;
  58504. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  58505. AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  58506. };
  58507. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  58508. const int minInputChannels_,
  58509. const int maxInputChannels_,
  58510. const int minOutputChannels_,
  58511. const int maxOutputChannels_,
  58512. const bool showMidiInputOptions,
  58513. const bool showMidiOutputSelector,
  58514. const bool showChannelsAsStereoPairs_,
  58515. const bool hideAdvancedOptionsWithButton_)
  58516. : deviceManager (deviceManager_),
  58517. deviceTypeDropDown (0),
  58518. deviceTypeDropDownLabel (0),
  58519. audioDeviceSettingsComp (0),
  58520. minOutputChannels (minOutputChannels_),
  58521. maxOutputChannels (maxOutputChannels_),
  58522. minInputChannels (minInputChannels_),
  58523. maxInputChannels (maxInputChannels_),
  58524. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  58525. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  58526. {
  58527. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  58528. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  58529. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  58530. {
  58531. deviceTypeDropDown = new ComboBox (String::empty);
  58532. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  58533. {
  58534. deviceTypeDropDown
  58535. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  58536. i + 1);
  58537. }
  58538. addAndMakeVisible (deviceTypeDropDown);
  58539. deviceTypeDropDown->addListener (this);
  58540. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  58541. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  58542. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  58543. }
  58544. if (showMidiInputOptions)
  58545. {
  58546. addAndMakeVisible (midiInputsList
  58547. = new MidiInputSelectorComponentListBox (deviceManager,
  58548. TRANS("(no midi inputs available)"),
  58549. 0, 0));
  58550. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  58551. midiInputsLabel->setJustificationType (Justification::topRight);
  58552. midiInputsLabel->attachToComponent (midiInputsList, true);
  58553. }
  58554. else
  58555. {
  58556. midiInputsList = 0;
  58557. midiInputsLabel = 0;
  58558. }
  58559. if (showMidiOutputSelector)
  58560. {
  58561. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  58562. midiOutputSelector->addListener (this);
  58563. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  58564. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  58565. }
  58566. else
  58567. {
  58568. midiOutputSelector = 0;
  58569. midiOutputLabel = 0;
  58570. }
  58571. deviceManager_.addChangeListener (this);
  58572. changeListenerCallback (0);
  58573. }
  58574. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  58575. {
  58576. deviceManager.removeChangeListener (this);
  58577. deleteAllChildren();
  58578. }
  58579. void AudioDeviceSelectorComponent::resized()
  58580. {
  58581. const int lx = proportionOfWidth (0.35f);
  58582. const int w = proportionOfWidth (0.4f);
  58583. const int h = 24;
  58584. const int space = 6;
  58585. const int dh = h + space;
  58586. int y = 15;
  58587. if (deviceTypeDropDown != 0)
  58588. {
  58589. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  58590. y += dh + space * 2;
  58591. }
  58592. if (audioDeviceSettingsComp != 0)
  58593. {
  58594. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  58595. y += audioDeviceSettingsComp->getHeight() + space;
  58596. }
  58597. if (midiInputsList != 0)
  58598. {
  58599. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  58600. midiInputsList->setBounds (lx, y, w, bh);
  58601. y += bh + space;
  58602. }
  58603. if (midiOutputSelector != 0)
  58604. midiOutputSelector->setBounds (lx, y, w, h);
  58605. }
  58606. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  58607. {
  58608. if (child == audioDeviceSettingsComp)
  58609. resized();
  58610. }
  58611. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  58612. {
  58613. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  58614. if (device != 0 && device->hasControlPanel())
  58615. {
  58616. if (device->showControlPanel())
  58617. deviceManager.restartLastAudioDevice();
  58618. getTopLevelComponent()->toFront (true);
  58619. }
  58620. }
  58621. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58622. {
  58623. if (comboBoxThatHasChanged == deviceTypeDropDown)
  58624. {
  58625. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  58626. if (type != 0)
  58627. {
  58628. deleteAndZero (audioDeviceSettingsComp);
  58629. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  58630. changeListenerCallback (0); // needed in case the type hasn't actally changed
  58631. }
  58632. }
  58633. else if (comboBoxThatHasChanged == midiOutputSelector)
  58634. {
  58635. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  58636. }
  58637. }
  58638. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  58639. {
  58640. if (deviceTypeDropDown != 0)
  58641. {
  58642. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  58643. }
  58644. if (audioDeviceSettingsComp == 0
  58645. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  58646. {
  58647. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  58648. deleteAndZero (audioDeviceSettingsComp);
  58649. AudioIODeviceType* const type
  58650. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  58651. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  58652. if (type != 0)
  58653. {
  58654. AudioIODeviceType::DeviceSetupDetails details;
  58655. details.manager = &deviceManager;
  58656. details.minNumInputChannels = minInputChannels;
  58657. details.maxNumInputChannels = maxInputChannels;
  58658. details.minNumOutputChannels = minOutputChannels;
  58659. details.maxNumOutputChannels = maxOutputChannels;
  58660. details.useStereoPairs = showChannelsAsStereoPairs;
  58661. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  58662. if (audioDeviceSettingsComp != 0)
  58663. {
  58664. addAndMakeVisible (audioDeviceSettingsComp);
  58665. audioDeviceSettingsComp->resized();
  58666. }
  58667. }
  58668. }
  58669. if (midiInputsList != 0)
  58670. {
  58671. midiInputsList->updateContent();
  58672. midiInputsList->repaint();
  58673. }
  58674. if (midiOutputSelector != 0)
  58675. {
  58676. midiOutputSelector->clear();
  58677. const StringArray midiOuts (MidiOutput::getDevices());
  58678. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  58679. midiOutputSelector->addSeparator();
  58680. for (int i = 0; i < midiOuts.size(); ++i)
  58681. midiOutputSelector->addItem (midiOuts[i], i + 1);
  58682. int current = -1;
  58683. if (deviceManager.getDefaultMidiOutput() != 0)
  58684. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  58685. midiOutputSelector->setSelectedId (current, true);
  58686. }
  58687. resized();
  58688. }
  58689. END_JUCE_NAMESPACE
  58690. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58691. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  58692. BEGIN_JUCE_NAMESPACE
  58693. BubbleComponent::BubbleComponent()
  58694. : side (0),
  58695. allowablePlacements (above | below | left | right),
  58696. arrowTipX (0.0f),
  58697. arrowTipY (0.0f)
  58698. {
  58699. setInterceptsMouseClicks (false, false);
  58700. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  58701. setComponentEffect (&shadow);
  58702. }
  58703. BubbleComponent::~BubbleComponent()
  58704. {
  58705. }
  58706. void BubbleComponent::paint (Graphics& g)
  58707. {
  58708. int x = content.getX();
  58709. int y = content.getY();
  58710. int w = content.getWidth();
  58711. int h = content.getHeight();
  58712. int cw, ch;
  58713. getContentSize (cw, ch);
  58714. if (side == 3)
  58715. x += w - cw;
  58716. else if (side != 1)
  58717. x += (w - cw) / 2;
  58718. w = cw;
  58719. if (side == 2)
  58720. y += h - ch;
  58721. else if (side != 0)
  58722. y += (h - ch) / 2;
  58723. h = ch;
  58724. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  58725. (float) x, (float) y,
  58726. (float) w, (float) h);
  58727. const int cx = x + (w - cw) / 2;
  58728. const int cy = y + (h - ch) / 2;
  58729. const int indent = 3;
  58730. g.setOrigin (cx + indent, cy + indent);
  58731. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  58732. paintContent (g, cw - indent * 2, ch - indent * 2);
  58733. }
  58734. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  58735. {
  58736. allowablePlacements = newPlacement;
  58737. }
  58738. void BubbleComponent::setPosition (Component* componentToPointTo)
  58739. {
  58740. jassert (componentToPointTo->isValidComponent());
  58741. Point<int> pos;
  58742. if (getParentComponent() != 0)
  58743. pos = componentToPointTo->relativePositionToOtherComponent (getParentComponent(), pos);
  58744. else
  58745. pos = componentToPointTo->relativePositionToGlobal (pos);
  58746. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  58747. }
  58748. void BubbleComponent::setPosition (const int arrowTipX_,
  58749. const int arrowTipY_)
  58750. {
  58751. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  58752. }
  58753. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  58754. {
  58755. Rectangle<int> availableSpace;
  58756. if (getParentComponent() != 0)
  58757. {
  58758. availableSpace.setSize (getParentComponent()->getWidth(),
  58759. getParentComponent()->getHeight());
  58760. }
  58761. else
  58762. {
  58763. availableSpace = getParentMonitorArea();
  58764. }
  58765. int x = 0;
  58766. int y = 0;
  58767. int w = 150;
  58768. int h = 30;
  58769. getContentSize (w, h);
  58770. w += 30;
  58771. h += 30;
  58772. const float edgeIndent = 2.0f;
  58773. const int arrowLength = jmin (10, h / 3, w / 3);
  58774. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  58775. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  58776. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  58777. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  58778. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  58779. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  58780. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  58781. {
  58782. spaceLeft = spaceRight = 0;
  58783. }
  58784. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  58785. && (spaceLeft > w + 20 || spaceRight > w + 20))
  58786. {
  58787. spaceAbove = spaceBelow = 0;
  58788. }
  58789. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  58790. {
  58791. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  58792. arrowTipX = w * 0.5f;
  58793. content.setSize (w, h - arrowLength);
  58794. if (spaceAbove >= spaceBelow)
  58795. {
  58796. // above
  58797. y = rectangleToPointTo.getY() - h;
  58798. content.setPosition (0, 0);
  58799. arrowTipY = h - edgeIndent;
  58800. side = 2;
  58801. }
  58802. else
  58803. {
  58804. // below
  58805. y = rectangleToPointTo.getBottom();
  58806. content.setPosition (0, arrowLength);
  58807. arrowTipY = edgeIndent;
  58808. side = 0;
  58809. }
  58810. }
  58811. else
  58812. {
  58813. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  58814. arrowTipY = h * 0.5f;
  58815. content.setSize (w - arrowLength, h);
  58816. if (spaceLeft > spaceRight)
  58817. {
  58818. // on the left
  58819. x = rectangleToPointTo.getX() - w;
  58820. content.setPosition (0, 0);
  58821. arrowTipX = w - edgeIndent;
  58822. side = 3;
  58823. }
  58824. else
  58825. {
  58826. // on the right
  58827. x = rectangleToPointTo.getRight();
  58828. content.setPosition (arrowLength, 0);
  58829. arrowTipX = edgeIndent;
  58830. side = 1;
  58831. }
  58832. }
  58833. setBounds (x, y, w, h);
  58834. }
  58835. END_JUCE_NAMESPACE
  58836. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  58837. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  58838. BEGIN_JUCE_NAMESPACE
  58839. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  58840. : fadeOutLength (fadeOutLengthMs),
  58841. deleteAfterUse (false)
  58842. {
  58843. }
  58844. BubbleMessageComponent::~BubbleMessageComponent()
  58845. {
  58846. fadeOutComponent (fadeOutLength);
  58847. }
  58848. void BubbleMessageComponent::showAt (int x, int y,
  58849. const String& text,
  58850. const int numMillisecondsBeforeRemoving,
  58851. const bool removeWhenMouseClicked,
  58852. const bool deleteSelfAfterUse)
  58853. {
  58854. textLayout.clear();
  58855. textLayout.setText (text, Font (14.0f));
  58856. textLayout.layout (256, Justification::centredLeft, true);
  58857. setPosition (x, y);
  58858. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  58859. }
  58860. void BubbleMessageComponent::showAt (Component* const component,
  58861. const String& text,
  58862. const int numMillisecondsBeforeRemoving,
  58863. const bool removeWhenMouseClicked,
  58864. const bool deleteSelfAfterUse)
  58865. {
  58866. textLayout.clear();
  58867. textLayout.setText (text, Font (14.0f));
  58868. textLayout.layout (256, Justification::centredLeft, true);
  58869. setPosition (component);
  58870. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  58871. }
  58872. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  58873. const bool removeWhenMouseClicked,
  58874. const bool deleteSelfAfterUse)
  58875. {
  58876. setVisible (true);
  58877. deleteAfterUse = deleteSelfAfterUse;
  58878. if (numMillisecondsBeforeRemoving > 0)
  58879. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  58880. else
  58881. expiryTime = 0;
  58882. startTimer (77);
  58883. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  58884. if (! (removeWhenMouseClicked && isShowing()))
  58885. mouseClickCounter += 0xfffff;
  58886. repaint();
  58887. }
  58888. void BubbleMessageComponent::getContentSize (int& w, int& h)
  58889. {
  58890. w = textLayout.getWidth() + 16;
  58891. h = textLayout.getHeight() + 16;
  58892. }
  58893. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  58894. {
  58895. g.setColour (findColour (TooltipWindow::textColourId));
  58896. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  58897. }
  58898. void BubbleMessageComponent::timerCallback()
  58899. {
  58900. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  58901. {
  58902. stopTimer();
  58903. setVisible (false);
  58904. if (deleteAfterUse)
  58905. delete this;
  58906. }
  58907. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  58908. {
  58909. stopTimer();
  58910. fadeOutComponent (fadeOutLength);
  58911. if (deleteAfterUse)
  58912. delete this;
  58913. }
  58914. }
  58915. END_JUCE_NAMESPACE
  58916. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  58917. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  58918. BEGIN_JUCE_NAMESPACE
  58919. static const int swatchesPerRow = 8;
  58920. static const int swatchHeight = 22;
  58921. class ColourComponentSlider : public Slider
  58922. {
  58923. public:
  58924. ColourComponentSlider (const String& name)
  58925. : Slider (name)
  58926. {
  58927. setRange (0.0, 255.0, 1.0);
  58928. }
  58929. ~ColourComponentSlider()
  58930. {
  58931. }
  58932. const String getTextFromValue (double value)
  58933. {
  58934. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  58935. }
  58936. double getValueFromText (const String& text)
  58937. {
  58938. return (double) text.getHexValue32();
  58939. }
  58940. private:
  58941. ColourComponentSlider (const ColourComponentSlider&);
  58942. ColourComponentSlider& operator= (const ColourComponentSlider&);
  58943. };
  58944. class ColourSpaceMarker : public Component
  58945. {
  58946. public:
  58947. ColourSpaceMarker()
  58948. {
  58949. setInterceptsMouseClicks (false, false);
  58950. }
  58951. ~ColourSpaceMarker()
  58952. {
  58953. }
  58954. void paint (Graphics& g)
  58955. {
  58956. g.setColour (Colour::greyLevel (0.1f));
  58957. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  58958. g.setColour (Colour::greyLevel (0.9f));
  58959. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  58960. }
  58961. private:
  58962. ColourSpaceMarker (const ColourSpaceMarker&);
  58963. ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  58964. };
  58965. class ColourSelector::ColourSpaceView : public Component
  58966. {
  58967. public:
  58968. ColourSpaceView (ColourSelector* owner_,
  58969. float& h_, float& s_, float& v_,
  58970. const int edgeSize)
  58971. : owner (owner_),
  58972. h (h_), s (s_), v (v_),
  58973. lastHue (0.0f),
  58974. edge (edgeSize)
  58975. {
  58976. addAndMakeVisible (marker = new ColourSpaceMarker());
  58977. setMouseCursor (MouseCursor::CrosshairCursor);
  58978. }
  58979. ~ColourSpaceView()
  58980. {
  58981. deleteAllChildren();
  58982. }
  58983. void paint (Graphics& g)
  58984. {
  58985. if (colours == 0)
  58986. {
  58987. const int width = getWidth() / 2;
  58988. const int height = getHeight() / 2;
  58989. colours = new Image (Image::RGB, width, height, false);
  58990. Image::BitmapData pixels (*colours, 0, 0, width, height, true);
  58991. for (int y = 0; y < height; ++y)
  58992. {
  58993. const float val = 1.0f - y / (float) height;
  58994. for (int x = 0; x < width; ++x)
  58995. {
  58996. const float sat = x / (float) width;
  58997. const Colour col (h, sat, val, 1.0f);
  58998. PixelRGB* const pix = (PixelRGB*) pixels.getPixelPointer (x, y);
  58999. pix->set (col.getPixelARGB());
  59000. }
  59001. }
  59002. }
  59003. g.setOpacity (1.0f);
  59004. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  59005. 0, 0, colours->getWidth(), colours->getHeight());
  59006. }
  59007. void mouseDown (const MouseEvent& e)
  59008. {
  59009. mouseDrag (e);
  59010. }
  59011. void mouseDrag (const MouseEvent& e)
  59012. {
  59013. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  59014. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  59015. owner->setSV (sat, val);
  59016. }
  59017. void updateIfNeeded()
  59018. {
  59019. if (lastHue != h)
  59020. {
  59021. lastHue = h;
  59022. colours = 0;
  59023. repaint();
  59024. }
  59025. updateMarker();
  59026. }
  59027. void resized()
  59028. {
  59029. colours = 0;
  59030. updateMarker();
  59031. }
  59032. private:
  59033. ColourSelector* const owner;
  59034. float& h;
  59035. float& s;
  59036. float& v;
  59037. float lastHue;
  59038. ColourSpaceMarker* marker;
  59039. const int edge;
  59040. ScopedPointer <Image> colours;
  59041. void updateMarker() const
  59042. {
  59043. marker->setBounds (roundToInt ((getWidth() - edge * 2) * s),
  59044. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  59045. edge * 2, edge * 2);
  59046. }
  59047. ColourSpaceView (const ColourSpaceView&);
  59048. ColourSpaceView& operator= (const ColourSpaceView&);
  59049. };
  59050. class HueSelectorMarker : public Component
  59051. {
  59052. public:
  59053. HueSelectorMarker()
  59054. {
  59055. setInterceptsMouseClicks (false, false);
  59056. }
  59057. ~HueSelectorMarker()
  59058. {
  59059. }
  59060. void paint (Graphics& g)
  59061. {
  59062. Path p;
  59063. p.addTriangle (1.0f, 1.0f,
  59064. getWidth() * 0.3f, getHeight() * 0.5f,
  59065. 1.0f, getHeight() - 1.0f);
  59066. p.addTriangle (getWidth() - 1.0f, 1.0f,
  59067. getWidth() * 0.7f, getHeight() * 0.5f,
  59068. getWidth() - 1.0f, getHeight() - 1.0f);
  59069. g.setColour (Colours::white.withAlpha (0.75f));
  59070. g.fillPath (p);
  59071. g.setColour (Colours::black.withAlpha (0.75f));
  59072. g.strokePath (p, PathStrokeType (1.2f));
  59073. }
  59074. private:
  59075. HueSelectorMarker (const HueSelectorMarker&);
  59076. HueSelectorMarker& operator= (const HueSelectorMarker&);
  59077. };
  59078. class ColourSelector::HueSelectorComp : public Component
  59079. {
  59080. public:
  59081. HueSelectorComp (ColourSelector* owner_,
  59082. float& h_, float& s_, float& v_,
  59083. const int edgeSize)
  59084. : owner (owner_),
  59085. h (h_), s (s_), v (v_),
  59086. lastHue (0.0f),
  59087. edge (edgeSize)
  59088. {
  59089. addAndMakeVisible (marker = new HueSelectorMarker());
  59090. }
  59091. ~HueSelectorComp()
  59092. {
  59093. deleteAllChildren();
  59094. }
  59095. void paint (Graphics& g)
  59096. {
  59097. const float yScale = 1.0f / (getHeight() - edge * 2);
  59098. const Rectangle<int> clip (g.getClipBounds());
  59099. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  59100. {
  59101. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  59102. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  59103. }
  59104. }
  59105. void resized()
  59106. {
  59107. marker->setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  59108. getWidth(), edge * 2);
  59109. }
  59110. void mouseDown (const MouseEvent& e)
  59111. {
  59112. mouseDrag (e);
  59113. }
  59114. void mouseDrag (const MouseEvent& e)
  59115. {
  59116. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  59117. owner->setHue (hue);
  59118. }
  59119. void updateIfNeeded()
  59120. {
  59121. resized();
  59122. }
  59123. private:
  59124. ColourSelector* const owner;
  59125. float& h;
  59126. float& s;
  59127. float& v;
  59128. float lastHue;
  59129. HueSelectorMarker* marker;
  59130. const int edge;
  59131. HueSelectorComp (const HueSelectorComp&);
  59132. HueSelectorComp& operator= (const HueSelectorComp&);
  59133. };
  59134. class ColourSelector::SwatchComponent : public Component
  59135. {
  59136. public:
  59137. SwatchComponent (ColourSelector* owner_, int index_)
  59138. : owner (owner_),
  59139. index (index_)
  59140. {
  59141. }
  59142. ~SwatchComponent()
  59143. {
  59144. }
  59145. void paint (Graphics& g)
  59146. {
  59147. const Colour colour (owner->getSwatchColour (index));
  59148. g.fillCheckerBoard (0, 0, getWidth(), getHeight(),
  59149. 6, 6,
  59150. Colour (0xffdddddd).overlaidWith (colour),
  59151. Colour (0xffffffff).overlaidWith (colour));
  59152. }
  59153. void mouseDown (const MouseEvent&)
  59154. {
  59155. PopupMenu m;
  59156. m.addItem (1, TRANS("Use this swatch as the current colour"));
  59157. m.addSeparator();
  59158. m.addItem (2, TRANS("Set this swatch to the current colour"));
  59159. const int r = m.showAt (this);
  59160. if (r == 1)
  59161. {
  59162. owner->setCurrentColour (owner->getSwatchColour (index));
  59163. }
  59164. else if (r == 2)
  59165. {
  59166. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  59167. {
  59168. owner->setSwatchColour (index, owner->getCurrentColour());
  59169. repaint();
  59170. }
  59171. }
  59172. }
  59173. private:
  59174. ColourSelector* const owner;
  59175. const int index;
  59176. SwatchComponent (const SwatchComponent&);
  59177. SwatchComponent& operator= (const SwatchComponent&);
  59178. };
  59179. ColourSelector::ColourSelector (const int flags_,
  59180. const int edgeGap_,
  59181. const int gapAroundColourSpaceComponent)
  59182. : colour (Colours::white),
  59183. flags (flags_),
  59184. topSpace (0),
  59185. edgeGap (edgeGap_)
  59186. {
  59187. // not much point having a selector with no components in it!
  59188. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  59189. updateHSV();
  59190. if ((flags & showSliders) != 0)
  59191. {
  59192. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  59193. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  59194. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  59195. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  59196. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  59197. for (int i = 4; --i >= 0;)
  59198. sliders[i]->addListener (this);
  59199. }
  59200. else
  59201. {
  59202. zeromem (sliders, sizeof (sliders));
  59203. }
  59204. if ((flags & showColourspace) != 0)
  59205. {
  59206. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  59207. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  59208. }
  59209. else
  59210. {
  59211. colourSpace = 0;
  59212. hueSelector = 0;
  59213. }
  59214. update();
  59215. }
  59216. ColourSelector::~ColourSelector()
  59217. {
  59218. dispatchPendingMessages();
  59219. swatchComponents.clear();
  59220. deleteAllChildren();
  59221. }
  59222. const Colour ColourSelector::getCurrentColour() const
  59223. {
  59224. return ((flags & showAlphaChannel) != 0) ? colour
  59225. : colour.withAlpha ((uint8) 0xff);
  59226. }
  59227. void ColourSelector::setCurrentColour (const Colour& c)
  59228. {
  59229. if (c != colour)
  59230. {
  59231. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  59232. updateHSV();
  59233. update();
  59234. }
  59235. }
  59236. void ColourSelector::setHue (float newH)
  59237. {
  59238. newH = jlimit (0.0f, 1.0f, newH);
  59239. if (h != newH)
  59240. {
  59241. h = newH;
  59242. colour = Colour (h, s, v, colour.getFloatAlpha());
  59243. update();
  59244. }
  59245. }
  59246. void ColourSelector::setSV (float newS, float newV)
  59247. {
  59248. newS = jlimit (0.0f, 1.0f, newS);
  59249. newV = jlimit (0.0f, 1.0f, newV);
  59250. if (s != newS || v != newV)
  59251. {
  59252. s = newS;
  59253. v = newV;
  59254. colour = Colour (h, s, v, colour.getFloatAlpha());
  59255. update();
  59256. }
  59257. }
  59258. void ColourSelector::updateHSV()
  59259. {
  59260. colour.getHSB (h, s, v);
  59261. }
  59262. void ColourSelector::update()
  59263. {
  59264. if (sliders[0] != 0)
  59265. {
  59266. sliders[0]->setValue ((int) colour.getRed());
  59267. sliders[1]->setValue ((int) colour.getGreen());
  59268. sliders[2]->setValue ((int) colour.getBlue());
  59269. sliders[3]->setValue ((int) colour.getAlpha());
  59270. }
  59271. if (colourSpace != 0)
  59272. {
  59273. colourSpace->updateIfNeeded();
  59274. hueSelector->updateIfNeeded();
  59275. }
  59276. if ((flags & showColourAtTop) != 0)
  59277. repaint (0, edgeGap, getWidth(), topSpace - edgeGap);
  59278. sendChangeMessage (this);
  59279. }
  59280. void ColourSelector::paint (Graphics& g)
  59281. {
  59282. g.fillAll (findColour (backgroundColourId));
  59283. if ((flags & showColourAtTop) != 0)
  59284. {
  59285. const Colour currentColour (getCurrentColour());
  59286. g.fillCheckerBoard (edgeGap, edgeGap, getWidth() - edgeGap - edgeGap, topSpace - edgeGap - edgeGap,
  59287. 10, 10,
  59288. Colour (0xffdddddd).overlaidWith (currentColour),
  59289. Colour (0xffffffff).overlaidWith (currentColour));
  59290. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  59291. g.setFont (14.0f, true);
  59292. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  59293. 0, edgeGap, getWidth(), topSpace - edgeGap * 2,
  59294. Justification::centred, false);
  59295. }
  59296. if ((flags & showSliders) != 0)
  59297. {
  59298. g.setColour (findColour (labelTextColourId));
  59299. g.setFont (11.0f);
  59300. for (int i = 4; --i >= 0;)
  59301. {
  59302. if (sliders[i]->isVisible())
  59303. g.drawText (sliders[i]->getName() + ":",
  59304. 0, sliders[i]->getY(),
  59305. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  59306. Justification::centredRight, false);
  59307. }
  59308. }
  59309. }
  59310. void ColourSelector::resized()
  59311. {
  59312. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  59313. const int numSwatches = getNumSwatches();
  59314. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  59315. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  59316. topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  59317. int y = topSpace;
  59318. if ((flags & showColourspace) != 0)
  59319. {
  59320. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  59321. colourSpace->setBounds (edgeGap, y,
  59322. getWidth() - hueWidth - edgeGap - 4,
  59323. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  59324. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  59325. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  59326. colourSpace->getHeight());
  59327. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  59328. }
  59329. if ((flags & showSliders) != 0)
  59330. {
  59331. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  59332. for (int i = 0; i < numSliders; ++i)
  59333. {
  59334. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  59335. proportionOfWidth (0.72f), sliderHeight - 2);
  59336. y += sliderHeight;
  59337. }
  59338. }
  59339. if (numSwatches > 0)
  59340. {
  59341. const int startX = 8;
  59342. const int xGap = 4;
  59343. const int yGap = 4;
  59344. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  59345. y += edgeGap;
  59346. if (swatchComponents.size() != numSwatches)
  59347. {
  59348. swatchComponents.clear();
  59349. for (int i = 0; i < numSwatches; ++i)
  59350. {
  59351. SwatchComponent* const sc = new SwatchComponent (this, i);
  59352. swatchComponents.add (sc);
  59353. addAndMakeVisible (sc);
  59354. }
  59355. }
  59356. int x = startX;
  59357. for (int i = 0; i < swatchComponents.size(); ++i)
  59358. {
  59359. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  59360. sc->setBounds (x + xGap / 2,
  59361. y + yGap / 2,
  59362. swatchWidth - xGap,
  59363. swatchHeight - yGap);
  59364. if (((i + 1) % swatchesPerRow) == 0)
  59365. {
  59366. x = startX;
  59367. y += swatchHeight;
  59368. }
  59369. else
  59370. {
  59371. x += swatchWidth;
  59372. }
  59373. }
  59374. }
  59375. }
  59376. void ColourSelector::sliderValueChanged (Slider*)
  59377. {
  59378. if (sliders[0] != 0)
  59379. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  59380. (uint8) sliders[1]->getValue(),
  59381. (uint8) sliders[2]->getValue(),
  59382. (uint8) sliders[3]->getValue()));
  59383. }
  59384. int ColourSelector::getNumSwatches() const
  59385. {
  59386. return 0;
  59387. }
  59388. const Colour ColourSelector::getSwatchColour (const int) const
  59389. {
  59390. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  59391. return Colours::black;
  59392. }
  59393. void ColourSelector::setSwatchColour (const int, const Colour&) const
  59394. {
  59395. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  59396. }
  59397. END_JUCE_NAMESPACE
  59398. /*** End of inlined file: juce_ColourSelector.cpp ***/
  59399. /*** Start of inlined file: juce_DropShadower.cpp ***/
  59400. BEGIN_JUCE_NAMESPACE
  59401. class ShadowWindow : public Component
  59402. {
  59403. Component* owner;
  59404. Image** shadowImageSections;
  59405. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  59406. public:
  59407. ShadowWindow (Component* const owner_,
  59408. const int type_,
  59409. Image** const shadowImageSections_)
  59410. : owner (owner_),
  59411. shadowImageSections (shadowImageSections_),
  59412. type (type_)
  59413. {
  59414. setInterceptsMouseClicks (false, false);
  59415. if (owner_->isOnDesktop())
  59416. {
  59417. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  59418. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  59419. | ComponentPeer::windowIsTemporary
  59420. | ComponentPeer::windowIgnoresKeyPresses);
  59421. }
  59422. else if (owner_->getParentComponent() != 0)
  59423. {
  59424. owner_->getParentComponent()->addChildComponent (this);
  59425. }
  59426. }
  59427. ~ShadowWindow()
  59428. {
  59429. }
  59430. void paint (Graphics& g)
  59431. {
  59432. Image* const topLeft = shadowImageSections [type * 3];
  59433. Image* const bottomRight = shadowImageSections [type * 3 + 1];
  59434. Image* const filler = shadowImageSections [type * 3 + 2];
  59435. g.setOpacity (1.0f);
  59436. if (type < 2)
  59437. {
  59438. int imH = jmin (topLeft->getHeight(), getHeight() / 2);
  59439. g.drawImage (topLeft,
  59440. 0, 0, topLeft->getWidth(), imH,
  59441. 0, 0, topLeft->getWidth(), imH);
  59442. imH = jmin (bottomRight->getHeight(), getHeight() - getHeight() / 2);
  59443. g.drawImage (bottomRight,
  59444. 0, getHeight() - imH, bottomRight->getWidth(), imH,
  59445. 0, bottomRight->getHeight() - imH, bottomRight->getWidth(), imH);
  59446. g.setTiledImageFill (*filler, 0, 0, 1.0f);
  59447. g.fillRect (0, topLeft->getHeight(), getWidth(), getHeight() - (topLeft->getHeight() + bottomRight->getHeight()));
  59448. }
  59449. else
  59450. {
  59451. int imW = jmin (topLeft->getWidth(), getWidth() / 2);
  59452. g.drawImage (topLeft,
  59453. 0, 0, imW, topLeft->getHeight(),
  59454. 0, 0, imW, topLeft->getHeight());
  59455. imW = jmin (bottomRight->getWidth(), getWidth() - getWidth() / 2);
  59456. g.drawImage (bottomRight,
  59457. getWidth() - imW, 0, imW, bottomRight->getHeight(),
  59458. bottomRight->getWidth() - imW, 0, imW, bottomRight->getHeight());
  59459. g.setTiledImageFill (*filler, 0, 0, 1.0f);
  59460. g.fillRect (topLeft->getWidth(), 0, getWidth() - (topLeft->getWidth() + bottomRight->getWidth()), getHeight());
  59461. }
  59462. }
  59463. void resized()
  59464. {
  59465. repaint(); // (needed for correct repainting)
  59466. }
  59467. private:
  59468. ShadowWindow (const ShadowWindow&);
  59469. ShadowWindow& operator= (const ShadowWindow&);
  59470. };
  59471. DropShadower::DropShadower (const float alpha_,
  59472. const int xOffset_,
  59473. const int yOffset_,
  59474. const float blurRadius_)
  59475. : owner (0),
  59476. numShadows (0),
  59477. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  59478. xOffset (xOffset_),
  59479. yOffset (yOffset_),
  59480. alpha (alpha_),
  59481. blurRadius (blurRadius_),
  59482. inDestructor (false),
  59483. reentrant (false)
  59484. {
  59485. }
  59486. DropShadower::~DropShadower()
  59487. {
  59488. if (owner != 0)
  59489. owner->removeComponentListener (this);
  59490. inDestructor = true;
  59491. deleteShadowWindows();
  59492. }
  59493. void DropShadower::deleteShadowWindows()
  59494. {
  59495. if (numShadows > 0)
  59496. {
  59497. int i;
  59498. for (i = numShadows; --i >= 0;)
  59499. delete shadowWindows[i];
  59500. for (i = 12; --i >= 0;)
  59501. delete shadowImageSections[i];
  59502. numShadows = 0;
  59503. }
  59504. }
  59505. void DropShadower::setOwner (Component* componentToFollow)
  59506. {
  59507. if (componentToFollow != owner)
  59508. {
  59509. if (owner != 0)
  59510. owner->removeComponentListener (this);
  59511. // (the component can't be null)
  59512. jassert (componentToFollow != 0);
  59513. owner = componentToFollow;
  59514. jassert (owner != 0);
  59515. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  59516. owner->addComponentListener (this);
  59517. updateShadows();
  59518. }
  59519. }
  59520. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  59521. {
  59522. updateShadows();
  59523. }
  59524. void DropShadower::componentBroughtToFront (Component&)
  59525. {
  59526. bringShadowWindowsToFront();
  59527. }
  59528. void DropShadower::componentChildrenChanged (Component&)
  59529. {
  59530. }
  59531. void DropShadower::componentParentHierarchyChanged (Component&)
  59532. {
  59533. deleteShadowWindows();
  59534. updateShadows();
  59535. }
  59536. void DropShadower::componentVisibilityChanged (Component&)
  59537. {
  59538. updateShadows();
  59539. }
  59540. void DropShadower::updateShadows()
  59541. {
  59542. if (reentrant || inDestructor || (owner == 0))
  59543. return;
  59544. reentrant = true;
  59545. ComponentPeer* const nw = owner->getPeer();
  59546. const bool isOwnerVisible = owner->isVisible()
  59547. && (nw == 0 || ! nw->isMinimised());
  59548. const bool createShadowWindows = numShadows == 0
  59549. && owner->getWidth() > 0
  59550. && owner->getHeight() > 0
  59551. && isOwnerVisible
  59552. && (Desktop::canUseSemiTransparentWindows()
  59553. || owner->getParentComponent() != 0);
  59554. if (createShadowWindows)
  59555. {
  59556. // keep a cached version of the image to save doing the gaussian too often
  59557. String imageId;
  59558. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  59559. const int hash = imageId.hashCode();
  59560. Image* bigIm = ImageCache::getFromHashCode (hash);
  59561. if (bigIm == 0)
  59562. {
  59563. bigIm = Image::createNativeImage (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true);
  59564. Graphics bigG (*bigIm);
  59565. bigG.setColour (Colours::black.withAlpha (alpha));
  59566. bigG.fillRect (shadowEdge + xOffset,
  59567. shadowEdge + yOffset,
  59568. bigIm->getWidth() - (shadowEdge * 2),
  59569. bigIm->getHeight() - (shadowEdge * 2));
  59570. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  59571. blurKernel.createGaussianBlur (blurRadius);
  59572. blurKernel.applyToImage (*bigIm, 0,
  59573. Rectangle<int> (xOffset, yOffset,
  59574. bigIm->getWidth(), bigIm->getHeight()));
  59575. ImageCache::addImageToCache (bigIm, hash);
  59576. }
  59577. const int iw = bigIm->getWidth();
  59578. const int ih = bigIm->getHeight();
  59579. const int shadowEdge2 = shadowEdge * 2;
  59580. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  59581. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  59582. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  59583. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  59584. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  59585. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  59586. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  59587. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  59588. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  59589. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  59590. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  59591. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  59592. ImageCache::release (bigIm);
  59593. for (int i = 0; i < 4; ++i)
  59594. {
  59595. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  59596. ++numShadows;
  59597. }
  59598. }
  59599. if (numShadows > 0)
  59600. {
  59601. for (int i = numShadows; --i >= 0;)
  59602. {
  59603. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  59604. shadowWindows[i]->setVisible (isOwnerVisible);
  59605. }
  59606. const int x = owner->getX();
  59607. const int y = owner->getY() - shadowEdge;
  59608. const int w = owner->getWidth();
  59609. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  59610. shadowWindows[0]->setBounds (x - shadowEdge,
  59611. y,
  59612. shadowEdge,
  59613. h);
  59614. shadowWindows[1]->setBounds (x + w,
  59615. y,
  59616. shadowEdge,
  59617. h);
  59618. shadowWindows[2]->setBounds (x,
  59619. y,
  59620. w,
  59621. shadowEdge);
  59622. shadowWindows[3]->setBounds (x,
  59623. owner->getBottom(),
  59624. w,
  59625. shadowEdge);
  59626. }
  59627. reentrant = false;
  59628. if (createShadowWindows)
  59629. bringShadowWindowsToFront();
  59630. }
  59631. void DropShadower::setShadowImage (Image* const src, const int num, const int w, const int h,
  59632. const int sx, const int sy)
  59633. {
  59634. shadowImageSections[num] = new Image (Image::ARGB, w, h, true);
  59635. Graphics g (*shadowImageSections[num]);
  59636. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  59637. }
  59638. void DropShadower::bringShadowWindowsToFront()
  59639. {
  59640. if (! (inDestructor || reentrant))
  59641. {
  59642. updateShadows();
  59643. reentrant = true;
  59644. for (int i = numShadows; --i >= 0;)
  59645. shadowWindows[i]->toBehind (owner);
  59646. reentrant = false;
  59647. }
  59648. }
  59649. END_JUCE_NAMESPACE
  59650. /*** End of inlined file: juce_DropShadower.cpp ***/
  59651. /*** Start of inlined file: juce_MagnifierComponent.cpp ***/
  59652. BEGIN_JUCE_NAMESPACE
  59653. class MagnifyingPeer : public ComponentPeer
  59654. {
  59655. public:
  59656. MagnifyingPeer (Component* const component_,
  59657. MagnifierComponent* const magnifierComp_)
  59658. : ComponentPeer (component_, 0),
  59659. magnifierComp (magnifierComp_)
  59660. {
  59661. }
  59662. ~MagnifyingPeer()
  59663. {
  59664. }
  59665. void* getNativeHandle() const { return 0; }
  59666. void setVisible (bool) {}
  59667. void setTitle (const String&) {}
  59668. void setPosition (int, int) {}
  59669. void setSize (int, int) {}
  59670. void setBounds (int, int, int, int, bool) {}
  59671. void setMinimised (bool) {}
  59672. bool isMinimised() const { return false; }
  59673. void setFullScreen (bool) {}
  59674. bool isFullScreen() const { return false; }
  59675. const BorderSize getFrameSize() const { return BorderSize (0); }
  59676. bool setAlwaysOnTop (bool) { return true; }
  59677. void toFront (bool) {}
  59678. void toBehind (ComponentPeer*) {}
  59679. void setIcon (const Image&) {}
  59680. bool isFocused() const
  59681. {
  59682. return magnifierComp->hasKeyboardFocus (true);
  59683. }
  59684. void grabFocus()
  59685. {
  59686. ComponentPeer* peer = magnifierComp->getPeer();
  59687. if (peer != 0)
  59688. peer->grabFocus();
  59689. }
  59690. void textInputRequired (const Point<int>& position)
  59691. {
  59692. ComponentPeer* peer = magnifierComp->getPeer();
  59693. if (peer != 0)
  59694. peer->textInputRequired (position);
  59695. }
  59696. const Rectangle<int> getBounds() const
  59697. {
  59698. return Rectangle<int> (magnifierComp->getScreenX(), magnifierComp->getScreenY(),
  59699. component->getWidth(), component->getHeight());
  59700. }
  59701. const Point<int> getScreenPosition() const
  59702. {
  59703. return magnifierComp->getScreenPosition();
  59704. }
  59705. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  59706. {
  59707. const double zoom = magnifierComp->getScaleFactor();
  59708. return magnifierComp->relativePositionToGlobal (Point<int> (roundToInt (relativePosition.getX() * zoom),
  59709. roundToInt (relativePosition.getY() * zoom)));
  59710. }
  59711. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  59712. {
  59713. const Point<int> p (magnifierComp->globalPositionToRelative (screenPosition));
  59714. const double zoom = magnifierComp->getScaleFactor();
  59715. return Point<int> (roundToInt (p.getX() / zoom),
  59716. roundToInt (p.getY() / zoom));
  59717. }
  59718. bool contains (const Point<int>& position, bool) const
  59719. {
  59720. return ((unsigned int) position.getX()) < (unsigned int) magnifierComp->getWidth()
  59721. && ((unsigned int) position.getY()) < (unsigned int) magnifierComp->getHeight();
  59722. }
  59723. void repaint (int x, int y, int w, int h)
  59724. {
  59725. const double zoom = magnifierComp->getScaleFactor();
  59726. magnifierComp->repaint ((int) (x * zoom),
  59727. (int) (y * zoom),
  59728. roundToInt (w * zoom) + 1,
  59729. roundToInt (h * zoom) + 1);
  59730. }
  59731. void performAnyPendingRepaintsNow()
  59732. {
  59733. }
  59734. juce_UseDebuggingNewOperator
  59735. private:
  59736. MagnifierComponent* const magnifierComp;
  59737. MagnifyingPeer (const MagnifyingPeer&);
  59738. MagnifyingPeer& operator= (const MagnifyingPeer&);
  59739. };
  59740. class PeerHolderComp : public Component
  59741. {
  59742. public:
  59743. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  59744. : magnifierComp (magnifierComp_)
  59745. {
  59746. setVisible (true);
  59747. }
  59748. ~PeerHolderComp()
  59749. {
  59750. }
  59751. ComponentPeer* createNewPeer (int, void*)
  59752. {
  59753. return new MagnifyingPeer (this, magnifierComp);
  59754. }
  59755. void childBoundsChanged (Component* c)
  59756. {
  59757. if (c != 0)
  59758. {
  59759. setSize (c->getWidth(), c->getHeight());
  59760. magnifierComp->childBoundsChanged (this);
  59761. }
  59762. }
  59763. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  59764. {
  59765. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  59766. Component* const p = magnifierComp->getParentComponent();
  59767. if (p != 0)
  59768. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  59769. }
  59770. private:
  59771. MagnifierComponent* const magnifierComp;
  59772. PeerHolderComp (const PeerHolderComp&);
  59773. PeerHolderComp& operator= (const PeerHolderComp&);
  59774. };
  59775. MagnifierComponent::MagnifierComponent (Component* const content_,
  59776. const bool deleteContentCompWhenNoLongerNeeded)
  59777. : content (content_),
  59778. scaleFactor (0.0),
  59779. peer (0),
  59780. deleteContent (deleteContentCompWhenNoLongerNeeded),
  59781. quality (Graphics::lowResamplingQuality),
  59782. mouseSource (0, true)
  59783. {
  59784. holderComp = new PeerHolderComp (this);
  59785. setScaleFactor (1.0);
  59786. }
  59787. MagnifierComponent::~MagnifierComponent()
  59788. {
  59789. delete holderComp;
  59790. if (deleteContent)
  59791. delete content;
  59792. }
  59793. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  59794. {
  59795. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  59796. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  59797. if (scaleFactor != newScaleFactor)
  59798. {
  59799. scaleFactor = newScaleFactor;
  59800. if (scaleFactor == 1.0)
  59801. {
  59802. holderComp->removeFromDesktop();
  59803. peer = 0;
  59804. addChildComponent (content);
  59805. childBoundsChanged (content);
  59806. }
  59807. else
  59808. {
  59809. holderComp->addAndMakeVisible (content);
  59810. holderComp->childBoundsChanged (content);
  59811. childBoundsChanged (holderComp);
  59812. holderComp->addToDesktop (0);
  59813. peer = holderComp->getPeer();
  59814. }
  59815. repaint();
  59816. }
  59817. }
  59818. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  59819. {
  59820. quality = newQuality;
  59821. }
  59822. void MagnifierComponent::paint (Graphics& g)
  59823. {
  59824. const int w = holderComp->getWidth();
  59825. const int h = holderComp->getHeight();
  59826. if (w == 0 || h == 0)
  59827. return;
  59828. const Rectangle<int> r (g.getClipBounds());
  59829. const int srcX = (int) (r.getX() / scaleFactor);
  59830. const int srcY = (int) (r.getY() / scaleFactor);
  59831. int srcW = roundToInt (r.getRight() / scaleFactor) - srcX;
  59832. int srcH = roundToInt (r.getBottom() / scaleFactor) - srcY;
  59833. if (scaleFactor >= 1.0)
  59834. {
  59835. ++srcW;
  59836. ++srcH;
  59837. }
  59838. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  59839. temp.clear (Rectangle<int> (srcX, srcY, srcW, srcH));
  59840. {
  59841. Graphics g2 (temp);
  59842. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  59843. holderComp->paintEntireComponent (g2);
  59844. }
  59845. g.setImageResamplingQuality (quality);
  59846. g.drawImageTransformed (&temp, temp.getBounds(),
  59847. AffineTransform::scale ((float) scaleFactor, (float) scaleFactor),
  59848. false);
  59849. }
  59850. void MagnifierComponent::childBoundsChanged (Component* c)
  59851. {
  59852. if (c != 0)
  59853. setSize (roundToInt (c->getWidth() * scaleFactor),
  59854. roundToInt (c->getHeight() * scaleFactor));
  59855. }
  59856. void MagnifierComponent::passOnMouseEventToPeer (const MouseEvent& e)
  59857. {
  59858. if (peer != 0)
  59859. mouseSource.handleEvent (peer, Point<int> (scaleInt (e.x), scaleInt (e.y)),
  59860. e.eventTime.toMilliseconds(), ModifierKeys::getCurrentModifiers());
  59861. }
  59862. void MagnifierComponent::mouseDown (const MouseEvent& e)
  59863. {
  59864. passOnMouseEventToPeer (e);
  59865. }
  59866. void MagnifierComponent::mouseUp (const MouseEvent& e)
  59867. {
  59868. passOnMouseEventToPeer (e);
  59869. }
  59870. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  59871. {
  59872. passOnMouseEventToPeer (e);
  59873. }
  59874. void MagnifierComponent::mouseMove (const MouseEvent& e)
  59875. {
  59876. passOnMouseEventToPeer (e);
  59877. }
  59878. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  59879. {
  59880. passOnMouseEventToPeer (e);
  59881. }
  59882. void MagnifierComponent::mouseExit (const MouseEvent& e)
  59883. {
  59884. passOnMouseEventToPeer (e);
  59885. }
  59886. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  59887. {
  59888. if (peer != 0)
  59889. peer->handleMouseWheel (e.source.getIndex(),
  59890. Point<int> (scaleInt (e.x), scaleInt (e.y)), e.eventTime.toMilliseconds(),
  59891. ix * 256.0f, iy * 256.0f);
  59892. else
  59893. Component::mouseWheelMove (e, ix, iy);
  59894. }
  59895. int MagnifierComponent::scaleInt (const int n) const
  59896. {
  59897. return roundToInt (n / scaleFactor);
  59898. }
  59899. END_JUCE_NAMESPACE
  59900. /*** End of inlined file: juce_MagnifierComponent.cpp ***/
  59901. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  59902. BEGIN_JUCE_NAMESPACE
  59903. class MidiKeyboardUpDownButton : public Button
  59904. {
  59905. public:
  59906. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  59907. const int delta_)
  59908. : Button (String::empty),
  59909. owner (owner_),
  59910. delta (delta_)
  59911. {
  59912. setOpaque (true);
  59913. }
  59914. ~MidiKeyboardUpDownButton()
  59915. {
  59916. }
  59917. void clicked()
  59918. {
  59919. int note = owner->getLowestVisibleKey();
  59920. if (delta < 0)
  59921. note = (note - 1) / 12;
  59922. else
  59923. note = note / 12 + 1;
  59924. owner->setLowestVisibleKey (note * 12);
  59925. }
  59926. void paintButton (Graphics& g,
  59927. bool isMouseOverButton,
  59928. bool isButtonDown)
  59929. {
  59930. owner->drawUpDownButton (g, getWidth(), getHeight(),
  59931. isMouseOverButton, isButtonDown,
  59932. delta > 0);
  59933. }
  59934. private:
  59935. MidiKeyboardComponent* const owner;
  59936. const int delta;
  59937. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  59938. MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  59939. };
  59940. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  59941. const Orientation orientation_)
  59942. : state (state_),
  59943. xOffset (0),
  59944. blackNoteLength (1),
  59945. keyWidth (16.0f),
  59946. orientation (orientation_),
  59947. midiChannel (1),
  59948. midiInChannelMask (0xffff),
  59949. velocity (1.0f),
  59950. noteUnderMouse (-1),
  59951. mouseDownNote (-1),
  59952. rangeStart (0),
  59953. rangeEnd (127),
  59954. firstKey (12 * 4),
  59955. canScroll (true),
  59956. mouseDragging (false),
  59957. useMousePositionForVelocity (true),
  59958. keyMappingOctave (6),
  59959. octaveNumForMiddleC (3)
  59960. {
  59961. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  59962. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  59963. // initialise with a default set of querty key-mappings..
  59964. const char* const keymap = "awsedftgyhujkolp;";
  59965. for (int i = String (keymap).length(); --i >= 0;)
  59966. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  59967. setOpaque (true);
  59968. setWantsKeyboardFocus (true);
  59969. state.addListener (this);
  59970. }
  59971. MidiKeyboardComponent::~MidiKeyboardComponent()
  59972. {
  59973. state.removeListener (this);
  59974. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  59975. deleteAllChildren();
  59976. }
  59977. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  59978. {
  59979. keyWidth = widthInPixels;
  59980. resized();
  59981. }
  59982. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  59983. {
  59984. if (orientation != newOrientation)
  59985. {
  59986. orientation = newOrientation;
  59987. resized();
  59988. }
  59989. }
  59990. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  59991. const int highestNote)
  59992. {
  59993. jassert (lowestNote >= 0 && lowestNote <= 127);
  59994. jassert (highestNote >= 0 && highestNote <= 127);
  59995. jassert (lowestNote <= highestNote);
  59996. if (rangeStart != lowestNote || rangeEnd != highestNote)
  59997. {
  59998. rangeStart = jlimit (0, 127, lowestNote);
  59999. rangeEnd = jlimit (0, 127, highestNote);
  60000. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  60001. resized();
  60002. }
  60003. }
  60004. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  60005. {
  60006. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  60007. if (noteNumber != firstKey)
  60008. {
  60009. firstKey = noteNumber;
  60010. sendChangeMessage (this);
  60011. resized();
  60012. }
  60013. }
  60014. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  60015. {
  60016. if (canScroll != canScroll_)
  60017. {
  60018. canScroll = canScroll_;
  60019. resized();
  60020. }
  60021. }
  60022. void MidiKeyboardComponent::colourChanged()
  60023. {
  60024. repaint();
  60025. }
  60026. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  60027. {
  60028. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  60029. if (midiChannel != midiChannelNumber)
  60030. {
  60031. resetAnyKeysInUse();
  60032. midiChannel = jlimit (1, 16, midiChannelNumber);
  60033. }
  60034. }
  60035. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  60036. {
  60037. midiInChannelMask = midiChannelMask;
  60038. triggerAsyncUpdate();
  60039. }
  60040. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  60041. {
  60042. velocity = jlimit (0.0f, 1.0f, velocity_);
  60043. useMousePositionForVelocity = useMousePositionForVelocity_;
  60044. }
  60045. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  60046. {
  60047. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  60048. static const float blackNoteWidth = 0.7f;
  60049. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  60050. 1.0f, 2 - blackNoteWidth * 0.4f,
  60051. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  60052. 4.0f, 5 - blackNoteWidth * 0.5f,
  60053. 5.0f, 6 - blackNoteWidth * 0.3f,
  60054. 6.0f };
  60055. static const float widths[] = { 1.0f, blackNoteWidth,
  60056. 1.0f, blackNoteWidth,
  60057. 1.0f, 1.0f, blackNoteWidth,
  60058. 1.0f, blackNoteWidth,
  60059. 1.0f, blackNoteWidth,
  60060. 1.0f };
  60061. const int octave = midiNoteNumber / 12;
  60062. const int note = midiNoteNumber % 12;
  60063. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  60064. w = roundToInt (widths [note] * keyWidth_);
  60065. }
  60066. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  60067. {
  60068. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  60069. int rx, rw;
  60070. getKeyPosition (rangeStart, keyWidth, rx, rw);
  60071. x -= xOffset + rx;
  60072. }
  60073. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  60074. {
  60075. int x, y;
  60076. getKeyPos (midiNoteNumber, x, y);
  60077. return x;
  60078. }
  60079. static const uint8 whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  60080. static const uint8 blackNotes[] = { 1, 3, 6, 8, 10 };
  60081. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  60082. {
  60083. if (! reallyContains (pos.getX(), pos.getY(), false))
  60084. return -1;
  60085. Point<int> p (pos);
  60086. if (orientation != horizontalKeyboard)
  60087. {
  60088. p = Point<int> (p.getY(), p.getX());
  60089. if (orientation == verticalKeyboardFacingLeft)
  60090. p = Point<int> (p.getX(), getWidth() - p.getY());
  60091. else
  60092. p = Point<int> (getHeight() - p.getX(), p.getY());
  60093. }
  60094. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  60095. }
  60096. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  60097. {
  60098. if (pos.getY() < blackNoteLength)
  60099. {
  60100. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60101. {
  60102. for (int i = 0; i < 5; ++i)
  60103. {
  60104. const int note = octaveStart + blackNotes [i];
  60105. if (note >= rangeStart && note <= rangeEnd)
  60106. {
  60107. int kx, kw;
  60108. getKeyPos (note, kx, kw);
  60109. kx += xOffset;
  60110. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60111. {
  60112. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  60113. return note;
  60114. }
  60115. }
  60116. }
  60117. }
  60118. }
  60119. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60120. {
  60121. for (int i = 0; i < 7; ++i)
  60122. {
  60123. const int note = octaveStart + whiteNotes [i];
  60124. if (note >= rangeStart && note <= rangeEnd)
  60125. {
  60126. int kx, kw;
  60127. getKeyPos (note, kx, kw);
  60128. kx += xOffset;
  60129. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60130. {
  60131. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  60132. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  60133. return note;
  60134. }
  60135. }
  60136. }
  60137. }
  60138. mousePositionVelocity = 0;
  60139. return -1;
  60140. }
  60141. void MidiKeyboardComponent::repaintNote (const int noteNum)
  60142. {
  60143. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60144. {
  60145. int x, w;
  60146. getKeyPos (noteNum, x, w);
  60147. if (orientation == horizontalKeyboard)
  60148. repaint (x, 0, w, getHeight());
  60149. else if (orientation == verticalKeyboardFacingLeft)
  60150. repaint (0, x, getWidth(), w);
  60151. else if (orientation == verticalKeyboardFacingRight)
  60152. repaint (0, getHeight() - x - w, getWidth(), w);
  60153. }
  60154. }
  60155. void MidiKeyboardComponent::paint (Graphics& g)
  60156. {
  60157. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  60158. const Colour lineColour (findColour (keySeparatorLineColourId));
  60159. const Colour textColour (findColour (textLabelColourId));
  60160. int x, w, octave;
  60161. for (octave = 0; octave < 128; octave += 12)
  60162. {
  60163. for (int white = 0; white < 7; ++white)
  60164. {
  60165. const int noteNum = octave + whiteNotes [white];
  60166. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60167. {
  60168. getKeyPos (noteNum, x, w);
  60169. if (orientation == horizontalKeyboard)
  60170. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  60171. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60172. noteUnderMouse == noteNum,
  60173. lineColour, textColour);
  60174. else if (orientation == verticalKeyboardFacingLeft)
  60175. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  60176. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60177. noteUnderMouse == noteNum,
  60178. lineColour, textColour);
  60179. else if (orientation == verticalKeyboardFacingRight)
  60180. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  60181. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60182. noteUnderMouse == noteNum,
  60183. lineColour, textColour);
  60184. }
  60185. }
  60186. }
  60187. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  60188. if (orientation == verticalKeyboardFacingLeft)
  60189. {
  60190. x1 = getWidth() - 1.0f;
  60191. x2 = getWidth() - 5.0f;
  60192. }
  60193. else if (orientation == verticalKeyboardFacingRight)
  60194. x2 = 5.0f;
  60195. else
  60196. y2 = 5.0f;
  60197. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  60198. Colours::transparentBlack, x2, y2, false));
  60199. getKeyPos (rangeEnd, x, w);
  60200. x += w;
  60201. if (orientation == verticalKeyboardFacingLeft)
  60202. g.fillRect (getWidth() - 5, 0, 5, x);
  60203. else if (orientation == verticalKeyboardFacingRight)
  60204. g.fillRect (0, 0, 5, x);
  60205. else
  60206. g.fillRect (0, 0, x, 5);
  60207. g.setColour (lineColour);
  60208. if (orientation == verticalKeyboardFacingLeft)
  60209. g.fillRect (0, 0, 1, x);
  60210. else if (orientation == verticalKeyboardFacingRight)
  60211. g.fillRect (getWidth() - 1, 0, 1, x);
  60212. else
  60213. g.fillRect (0, getHeight() - 1, x, 1);
  60214. const Colour blackNoteColour (findColour (blackNoteColourId));
  60215. for (octave = 0; octave < 128; octave += 12)
  60216. {
  60217. for (int black = 0; black < 5; ++black)
  60218. {
  60219. const int noteNum = octave + blackNotes [black];
  60220. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60221. {
  60222. getKeyPos (noteNum, x, w);
  60223. if (orientation == horizontalKeyboard)
  60224. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  60225. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60226. noteUnderMouse == noteNum,
  60227. blackNoteColour);
  60228. else if (orientation == verticalKeyboardFacingLeft)
  60229. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  60230. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60231. noteUnderMouse == noteNum,
  60232. blackNoteColour);
  60233. else if (orientation == verticalKeyboardFacingRight)
  60234. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  60235. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60236. noteUnderMouse == noteNum,
  60237. blackNoteColour);
  60238. }
  60239. }
  60240. }
  60241. }
  60242. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  60243. Graphics& g, int x, int y, int w, int h,
  60244. bool isDown, bool isOver,
  60245. const Colour& lineColour,
  60246. const Colour& textColour)
  60247. {
  60248. Colour c (Colours::transparentWhite);
  60249. if (isDown)
  60250. c = findColour (keyDownOverlayColourId);
  60251. if (isOver)
  60252. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60253. g.setColour (c);
  60254. g.fillRect (x, y, w, h);
  60255. const String text (getWhiteNoteText (midiNoteNumber));
  60256. if (! text.isEmpty())
  60257. {
  60258. g.setColour (textColour);
  60259. Font f (jmin (12.0f, keyWidth * 0.9f));
  60260. f.setHorizontalScale (0.8f);
  60261. g.setFont (f);
  60262. Justification justification (Justification::centredBottom);
  60263. if (orientation == verticalKeyboardFacingLeft)
  60264. justification = Justification::centredLeft;
  60265. else if (orientation == verticalKeyboardFacingRight)
  60266. justification = Justification::centredRight;
  60267. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  60268. }
  60269. g.setColour (lineColour);
  60270. if (orientation == horizontalKeyboard)
  60271. g.fillRect (x, y, 1, h);
  60272. else if (orientation == verticalKeyboardFacingLeft)
  60273. g.fillRect (x, y, w, 1);
  60274. else if (orientation == verticalKeyboardFacingRight)
  60275. g.fillRect (x, y + h - 1, w, 1);
  60276. if (midiNoteNumber == rangeEnd)
  60277. {
  60278. if (orientation == horizontalKeyboard)
  60279. g.fillRect (x + w, y, 1, h);
  60280. else if (orientation == verticalKeyboardFacingLeft)
  60281. g.fillRect (x, y + h, w, 1);
  60282. else if (orientation == verticalKeyboardFacingRight)
  60283. g.fillRect (x, y - 1, w, 1);
  60284. }
  60285. }
  60286. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  60287. Graphics& g, int x, int y, int w, int h,
  60288. bool isDown, bool isOver,
  60289. const Colour& noteFillColour)
  60290. {
  60291. Colour c (noteFillColour);
  60292. if (isDown)
  60293. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  60294. if (isOver)
  60295. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60296. g.setColour (c);
  60297. g.fillRect (x, y, w, h);
  60298. if (isDown)
  60299. {
  60300. g.setColour (noteFillColour);
  60301. g.drawRect (x, y, w, h);
  60302. }
  60303. else
  60304. {
  60305. const int xIndent = jmax (1, jmin (w, h) / 8);
  60306. g.setColour (c.brighter());
  60307. if (orientation == horizontalKeyboard)
  60308. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  60309. else if (orientation == verticalKeyboardFacingLeft)
  60310. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  60311. else if (orientation == verticalKeyboardFacingRight)
  60312. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  60313. }
  60314. }
  60315. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  60316. {
  60317. octaveNumForMiddleC = octaveNumForMiddleC_;
  60318. repaint();
  60319. }
  60320. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  60321. {
  60322. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  60323. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  60324. return String::empty;
  60325. }
  60326. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  60327. const bool isMouseOver_,
  60328. const bool isButtonDown,
  60329. const bool movesOctavesUp)
  60330. {
  60331. g.fillAll (findColour (upDownButtonBackgroundColourId));
  60332. float angle;
  60333. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  60334. angle = movesOctavesUp ? 0.0f : 0.5f;
  60335. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  60336. angle = movesOctavesUp ? 0.25f : 0.75f;
  60337. else
  60338. angle = movesOctavesUp ? 0.75f : 0.25f;
  60339. Path path;
  60340. path.lineTo (0.0f, 1.0f);
  60341. path.lineTo (1.0f, 0.5f);
  60342. path.closeSubPath();
  60343. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  60344. g.setColour (findColour (upDownButtonArrowColourId)
  60345. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  60346. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  60347. w - 2.0f,
  60348. h - 2.0f,
  60349. true));
  60350. }
  60351. void MidiKeyboardComponent::resized()
  60352. {
  60353. int w = getWidth();
  60354. int h = getHeight();
  60355. if (w > 0 && h > 0)
  60356. {
  60357. if (orientation != horizontalKeyboard)
  60358. swapVariables (w, h);
  60359. blackNoteLength = roundToInt (h * 0.7f);
  60360. int kx2, kw2;
  60361. getKeyPos (rangeEnd, kx2, kw2);
  60362. kx2 += kw2;
  60363. if (firstKey != rangeStart)
  60364. {
  60365. int kx1, kw1;
  60366. getKeyPos (rangeStart, kx1, kw1);
  60367. if (kx2 - kx1 <= w)
  60368. {
  60369. firstKey = rangeStart;
  60370. sendChangeMessage (this);
  60371. repaint();
  60372. }
  60373. }
  60374. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  60375. scrollDown->setVisible (showScrollButtons);
  60376. scrollUp->setVisible (showScrollButtons);
  60377. xOffset = 0;
  60378. if (showScrollButtons)
  60379. {
  60380. const int scrollButtonW = jmin (12, w / 2);
  60381. if (orientation == horizontalKeyboard)
  60382. {
  60383. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  60384. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  60385. }
  60386. else if (orientation == verticalKeyboardFacingLeft)
  60387. {
  60388. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  60389. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60390. }
  60391. else if (orientation == verticalKeyboardFacingRight)
  60392. {
  60393. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60394. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  60395. }
  60396. int endOfLastKey, kw;
  60397. getKeyPos (rangeEnd, endOfLastKey, kw);
  60398. endOfLastKey += kw;
  60399. float mousePositionVelocity;
  60400. const int spaceAvailable = w - scrollButtonW * 2;
  60401. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  60402. if (lastStartKey >= 0 && firstKey > lastStartKey)
  60403. {
  60404. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  60405. sendChangeMessage (this);
  60406. }
  60407. int newOffset = 0;
  60408. getKeyPos (firstKey, newOffset, kw);
  60409. xOffset = newOffset - scrollButtonW;
  60410. }
  60411. else
  60412. {
  60413. firstKey = rangeStart;
  60414. }
  60415. timerCallback();
  60416. repaint();
  60417. }
  60418. }
  60419. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  60420. {
  60421. triggerAsyncUpdate();
  60422. }
  60423. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  60424. {
  60425. triggerAsyncUpdate();
  60426. }
  60427. void MidiKeyboardComponent::handleAsyncUpdate()
  60428. {
  60429. for (int i = rangeStart; i <= rangeEnd; ++i)
  60430. {
  60431. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  60432. {
  60433. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  60434. repaintNote (i);
  60435. }
  60436. }
  60437. }
  60438. void MidiKeyboardComponent::resetAnyKeysInUse()
  60439. {
  60440. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  60441. {
  60442. state.allNotesOff (midiChannel);
  60443. keysPressed.clear();
  60444. mouseDownNote = -1;
  60445. }
  60446. }
  60447. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  60448. {
  60449. float mousePositionVelocity = 0.0f;
  60450. const int newNote = (mouseDragging || isMouseOver())
  60451. ? xyToNote (pos, mousePositionVelocity) : -1;
  60452. if (noteUnderMouse != newNote)
  60453. {
  60454. if (mouseDownNote >= 0)
  60455. {
  60456. state.noteOff (midiChannel, mouseDownNote);
  60457. mouseDownNote = -1;
  60458. }
  60459. if (mouseDragging && newNote >= 0)
  60460. {
  60461. if (! useMousePositionForVelocity)
  60462. mousePositionVelocity = 1.0f;
  60463. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  60464. mouseDownNote = newNote;
  60465. }
  60466. repaintNote (noteUnderMouse);
  60467. noteUnderMouse = newNote;
  60468. repaintNote (noteUnderMouse);
  60469. }
  60470. else if (mouseDownNote >= 0 && ! mouseDragging)
  60471. {
  60472. state.noteOff (midiChannel, mouseDownNote);
  60473. mouseDownNote = -1;
  60474. }
  60475. }
  60476. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  60477. {
  60478. updateNoteUnderMouse (e.getPosition());
  60479. stopTimer();
  60480. }
  60481. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  60482. {
  60483. float mousePositionVelocity;
  60484. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60485. if (newNote >= 0)
  60486. mouseDraggedToKey (newNote, e);
  60487. updateNoteUnderMouse (e.getPosition());
  60488. }
  60489. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  60490. {
  60491. return true;
  60492. }
  60493. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  60494. {
  60495. }
  60496. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  60497. {
  60498. float mousePositionVelocity;
  60499. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60500. mouseDragging = false;
  60501. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  60502. {
  60503. repaintNote (noteUnderMouse);
  60504. noteUnderMouse = -1;
  60505. mouseDragging = true;
  60506. updateNoteUnderMouse (e.getPosition());
  60507. startTimer (500);
  60508. }
  60509. }
  60510. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  60511. {
  60512. mouseDragging = false;
  60513. updateNoteUnderMouse (e.getPosition());
  60514. stopTimer();
  60515. }
  60516. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  60517. {
  60518. updateNoteUnderMouse (e.getPosition());
  60519. }
  60520. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  60521. {
  60522. updateNoteUnderMouse (e.getPosition());
  60523. }
  60524. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  60525. {
  60526. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  60527. }
  60528. void MidiKeyboardComponent::timerCallback()
  60529. {
  60530. updateNoteUnderMouse (getMouseXYRelative());
  60531. }
  60532. void MidiKeyboardComponent::clearKeyMappings()
  60533. {
  60534. resetAnyKeysInUse();
  60535. keyPressNotes.clear();
  60536. keyPresses.clear();
  60537. }
  60538. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  60539. const int midiNoteOffsetFromC)
  60540. {
  60541. removeKeyPressForNote (midiNoteOffsetFromC);
  60542. keyPressNotes.add (midiNoteOffsetFromC);
  60543. keyPresses.add (key);
  60544. }
  60545. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  60546. {
  60547. for (int i = keyPressNotes.size(); --i >= 0;)
  60548. {
  60549. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  60550. {
  60551. keyPressNotes.remove (i);
  60552. keyPresses.remove (i);
  60553. }
  60554. }
  60555. }
  60556. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  60557. {
  60558. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  60559. keyMappingOctave = newOctaveNumber;
  60560. }
  60561. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  60562. {
  60563. bool keyPressUsed = false;
  60564. for (int i = keyPresses.size(); --i >= 0;)
  60565. {
  60566. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  60567. if (keyPresses.getReference(i).isCurrentlyDown())
  60568. {
  60569. if (! keysPressed [note])
  60570. {
  60571. keysPressed.setBit (note);
  60572. state.noteOn (midiChannel, note, velocity);
  60573. keyPressUsed = true;
  60574. }
  60575. }
  60576. else
  60577. {
  60578. if (keysPressed [note])
  60579. {
  60580. keysPressed.clearBit (note);
  60581. state.noteOff (midiChannel, note);
  60582. keyPressUsed = true;
  60583. }
  60584. }
  60585. }
  60586. return keyPressUsed;
  60587. }
  60588. void MidiKeyboardComponent::focusLost (FocusChangeType)
  60589. {
  60590. resetAnyKeysInUse();
  60591. }
  60592. END_JUCE_NAMESPACE
  60593. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60594. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  60595. #if JUCE_OPENGL
  60596. BEGIN_JUCE_NAMESPACE
  60597. extern void juce_glViewport (const int w, const int h);
  60598. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  60599. const int alphaBits_,
  60600. const int depthBufferBits_,
  60601. const int stencilBufferBits_)
  60602. : redBits (bitsPerRGBComponent),
  60603. greenBits (bitsPerRGBComponent),
  60604. blueBits (bitsPerRGBComponent),
  60605. alphaBits (alphaBits_),
  60606. depthBufferBits (depthBufferBits_),
  60607. stencilBufferBits (stencilBufferBits_),
  60608. accumulationBufferRedBits (0),
  60609. accumulationBufferGreenBits (0),
  60610. accumulationBufferBlueBits (0),
  60611. accumulationBufferAlphaBits (0),
  60612. fullSceneAntiAliasingNumSamples (0)
  60613. {
  60614. }
  60615. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  60616. : redBits (other.redBits),
  60617. greenBits (other.greenBits),
  60618. blueBits (other.blueBits),
  60619. alphaBits (other.alphaBits),
  60620. depthBufferBits (other.depthBufferBits),
  60621. stencilBufferBits (other.stencilBufferBits),
  60622. accumulationBufferRedBits (other.accumulationBufferRedBits),
  60623. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  60624. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  60625. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  60626. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  60627. {
  60628. }
  60629. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  60630. {
  60631. redBits = other.redBits;
  60632. greenBits = other.greenBits;
  60633. blueBits = other.blueBits;
  60634. alphaBits = other.alphaBits;
  60635. depthBufferBits = other.depthBufferBits;
  60636. stencilBufferBits = other.stencilBufferBits;
  60637. accumulationBufferRedBits = other.accumulationBufferRedBits;
  60638. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  60639. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  60640. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  60641. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  60642. return *this;
  60643. }
  60644. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  60645. {
  60646. return redBits == other.redBits
  60647. && greenBits == other.greenBits
  60648. && blueBits == other.blueBits
  60649. && alphaBits == other.alphaBits
  60650. && depthBufferBits == other.depthBufferBits
  60651. && stencilBufferBits == other.stencilBufferBits
  60652. && accumulationBufferRedBits == other.accumulationBufferRedBits
  60653. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  60654. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  60655. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  60656. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  60657. }
  60658. static VoidArray knownContexts;
  60659. OpenGLContext::OpenGLContext() throw()
  60660. {
  60661. knownContexts.add (this);
  60662. }
  60663. OpenGLContext::~OpenGLContext()
  60664. {
  60665. knownContexts.removeValue (this);
  60666. }
  60667. OpenGLContext* OpenGLContext::getCurrentContext()
  60668. {
  60669. for (int i = knownContexts.size(); --i >= 0;)
  60670. {
  60671. OpenGLContext* const oglc = (OpenGLContext*) knownContexts.getUnchecked(i);
  60672. if (oglc->isActive())
  60673. return oglc;
  60674. }
  60675. return 0;
  60676. }
  60677. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  60678. {
  60679. public:
  60680. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  60681. : ComponentMovementWatcher (owner_),
  60682. owner (owner_),
  60683. wasShowing (false)
  60684. {
  60685. }
  60686. ~OpenGLComponentWatcher() {}
  60687. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  60688. {
  60689. owner->updateContextPosition();
  60690. }
  60691. void componentPeerChanged()
  60692. {
  60693. const ScopedLock sl (owner->getContextLock());
  60694. owner->deleteContext();
  60695. }
  60696. void componentVisibilityChanged (Component&)
  60697. {
  60698. const bool isShowingNow = owner->isShowing();
  60699. if (wasShowing != isShowingNow)
  60700. {
  60701. wasShowing = isShowingNow;
  60702. owner->updateContextPosition();
  60703. }
  60704. }
  60705. juce_UseDebuggingNewOperator
  60706. private:
  60707. OpenGLComponent* const owner;
  60708. bool wasShowing;
  60709. };
  60710. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  60711. : type (type_),
  60712. contextToShareListsWith (0),
  60713. needToUpdateViewport (true)
  60714. {
  60715. setOpaque (true);
  60716. componentWatcher = new OpenGLComponentWatcher (this);
  60717. }
  60718. OpenGLComponent::~OpenGLComponent()
  60719. {
  60720. deleteContext();
  60721. componentWatcher = 0;
  60722. }
  60723. void OpenGLComponent::deleteContext()
  60724. {
  60725. const ScopedLock sl (contextLock);
  60726. context = 0;
  60727. }
  60728. void OpenGLComponent::updateContextPosition()
  60729. {
  60730. needToUpdateViewport = true;
  60731. if (getWidth() > 0 && getHeight() > 0)
  60732. {
  60733. Component* const topComp = getTopLevelComponent();
  60734. if (topComp->getPeer() != 0)
  60735. {
  60736. const ScopedLock sl (contextLock);
  60737. if (context != 0)
  60738. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  60739. getScreenY() - topComp->getScreenY(),
  60740. getWidth(),
  60741. getHeight(),
  60742. topComp->getHeight());
  60743. }
  60744. }
  60745. }
  60746. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  60747. {
  60748. OpenGLPixelFormat pf;
  60749. const ScopedLock sl (contextLock);
  60750. if (context != 0)
  60751. pf = context->getPixelFormat();
  60752. return pf;
  60753. }
  60754. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  60755. {
  60756. if (! (preferredPixelFormat == formatToUse))
  60757. {
  60758. const ScopedLock sl (contextLock);
  60759. deleteContext();
  60760. preferredPixelFormat = formatToUse;
  60761. }
  60762. }
  60763. void OpenGLComponent::shareWith (OpenGLContext* c)
  60764. {
  60765. if (contextToShareListsWith != c)
  60766. {
  60767. const ScopedLock sl (contextLock);
  60768. deleteContext();
  60769. contextToShareListsWith = c;
  60770. }
  60771. }
  60772. bool OpenGLComponent::makeCurrentContextActive()
  60773. {
  60774. if (context == 0)
  60775. {
  60776. const ScopedLock sl (contextLock);
  60777. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  60778. {
  60779. context = createContext();
  60780. if (context != 0)
  60781. {
  60782. updateContextPosition();
  60783. if (context->makeActive())
  60784. newOpenGLContextCreated();
  60785. }
  60786. }
  60787. }
  60788. return context != 0 && context->makeActive();
  60789. }
  60790. void OpenGLComponent::makeCurrentContextInactive()
  60791. {
  60792. if (context != 0)
  60793. context->makeInactive();
  60794. }
  60795. bool OpenGLComponent::isActiveContext() const throw()
  60796. {
  60797. return context != 0 && context->isActive();
  60798. }
  60799. void OpenGLComponent::swapBuffers()
  60800. {
  60801. if (context != 0)
  60802. context->swapBuffers();
  60803. }
  60804. void OpenGLComponent::paint (Graphics&)
  60805. {
  60806. if (renderAndSwapBuffers())
  60807. {
  60808. ComponentPeer* const peer = getPeer();
  60809. if (peer != 0)
  60810. {
  60811. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  60812. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  60813. }
  60814. }
  60815. }
  60816. bool OpenGLComponent::renderAndSwapBuffers()
  60817. {
  60818. const ScopedLock sl (contextLock);
  60819. if (! makeCurrentContextActive())
  60820. return false;
  60821. if (needToUpdateViewport)
  60822. {
  60823. needToUpdateViewport = false;
  60824. juce_glViewport (getWidth(), getHeight());
  60825. }
  60826. renderOpenGL();
  60827. swapBuffers();
  60828. return true;
  60829. }
  60830. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  60831. {
  60832. Component::internalRepaint (x, y, w, h);
  60833. if (context != 0)
  60834. context->repaint();
  60835. }
  60836. END_JUCE_NAMESPACE
  60837. #endif
  60838. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  60839. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  60840. BEGIN_JUCE_NAMESPACE
  60841. PreferencesPanel::PreferencesPanel()
  60842. : buttonSize (70)
  60843. {
  60844. }
  60845. PreferencesPanel::~PreferencesPanel()
  60846. {
  60847. currentPage = 0;
  60848. deleteAllChildren();
  60849. }
  60850. void PreferencesPanel::addSettingsPage (const String& title,
  60851. const Drawable* icon,
  60852. const Drawable* overIcon,
  60853. const Drawable* downIcon)
  60854. {
  60855. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  60856. button->setImages (icon, overIcon, downIcon);
  60857. button->setRadioGroupId (1);
  60858. button->addButtonListener (this);
  60859. button->setClickingTogglesState (true);
  60860. button->setWantsKeyboardFocus (false);
  60861. addAndMakeVisible (button);
  60862. resized();
  60863. if (currentPage == 0)
  60864. setCurrentPage (title);
  60865. }
  60866. void PreferencesPanel::addSettingsPage (const String& title,
  60867. const char* imageData,
  60868. const int imageDataSize)
  60869. {
  60870. DrawableImage icon, iconOver, iconDown;
  60871. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  60872. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  60873. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  60874. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  60875. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  60876. addSettingsPage (title, &icon, &iconOver, &iconDown);
  60877. }
  60878. class PrefsDialogWindow : public DialogWindow
  60879. {
  60880. public:
  60881. PrefsDialogWindow (const String& dialogtitle,
  60882. const Colour& backgroundColour)
  60883. : DialogWindow (dialogtitle, backgroundColour, true)
  60884. {
  60885. }
  60886. ~PrefsDialogWindow()
  60887. {
  60888. }
  60889. void closeButtonPressed()
  60890. {
  60891. exitModalState (0);
  60892. }
  60893. private:
  60894. PrefsDialogWindow (const PrefsDialogWindow&);
  60895. PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  60896. };
  60897. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  60898. int dialogWidth,
  60899. int dialogHeight,
  60900. const Colour& backgroundColour)
  60901. {
  60902. setSize (dialogWidth, dialogHeight);
  60903. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  60904. dw.setContentComponent (this, true, true);
  60905. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  60906. dw.runModalLoop();
  60907. dw.setContentComponent (0, false, false);
  60908. }
  60909. void PreferencesPanel::resized()
  60910. {
  60911. int x = 0;
  60912. for (int i = 0; i < getNumChildComponents(); ++i)
  60913. {
  60914. Component* c = getChildComponent (i);
  60915. if (dynamic_cast <DrawableButton*> (c) == 0)
  60916. {
  60917. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  60918. }
  60919. else
  60920. {
  60921. c->setBounds (x, 0, buttonSize, buttonSize);
  60922. x += buttonSize;
  60923. }
  60924. }
  60925. }
  60926. void PreferencesPanel::paint (Graphics& g)
  60927. {
  60928. g.setColour (Colours::grey);
  60929. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  60930. }
  60931. void PreferencesPanel::setCurrentPage (const String& pageName)
  60932. {
  60933. if (currentPageName != pageName)
  60934. {
  60935. currentPageName = pageName;
  60936. currentPage = 0;
  60937. currentPage = createComponentForPage (pageName);
  60938. if (currentPage != 0)
  60939. {
  60940. addAndMakeVisible (currentPage);
  60941. currentPage->toBack();
  60942. resized();
  60943. }
  60944. for (int i = 0; i < getNumChildComponents(); ++i)
  60945. {
  60946. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  60947. if (db != 0 && db->getName() == pageName)
  60948. {
  60949. db->setToggleState (true, false);
  60950. break;
  60951. }
  60952. }
  60953. }
  60954. }
  60955. void PreferencesPanel::buttonClicked (Button*)
  60956. {
  60957. for (int i = 0; i < getNumChildComponents(); ++i)
  60958. {
  60959. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  60960. if (db != 0 && db->getToggleState())
  60961. {
  60962. setCurrentPage (db->getName());
  60963. break;
  60964. }
  60965. }
  60966. }
  60967. END_JUCE_NAMESPACE
  60968. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  60969. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  60970. #if JUCE_WINDOWS || JUCE_LINUX
  60971. BEGIN_JUCE_NAMESPACE
  60972. SystemTrayIconComponent::SystemTrayIconComponent()
  60973. {
  60974. addToDesktop (0);
  60975. }
  60976. SystemTrayIconComponent::~SystemTrayIconComponent()
  60977. {
  60978. }
  60979. END_JUCE_NAMESPACE
  60980. #endif
  60981. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  60982. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  60983. BEGIN_JUCE_NAMESPACE
  60984. class AlertWindowTextEditor : public TextEditor
  60985. {
  60986. public:
  60987. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  60988. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  60989. {
  60990. setSelectAllWhenFocused (true);
  60991. }
  60992. ~AlertWindowTextEditor()
  60993. {
  60994. }
  60995. void returnPressed()
  60996. {
  60997. // pass these up the component hierarchy to be trigger the buttons
  60998. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  60999. }
  61000. void escapePressed()
  61001. {
  61002. // pass these up the component hierarchy to be trigger the buttons
  61003. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  61004. }
  61005. private:
  61006. AlertWindowTextEditor (const AlertWindowTextEditor&);
  61007. AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  61008. static juce_wchar getDefaultPasswordChar() throw()
  61009. {
  61010. #if JUCE_LINUX
  61011. return 0x2022;
  61012. #else
  61013. return 0x25cf;
  61014. #endif
  61015. }
  61016. };
  61017. AlertWindow::AlertWindow (const String& title,
  61018. const String& message,
  61019. AlertIconType iconType,
  61020. Component* associatedComponent_)
  61021. : TopLevelWindow (title, true),
  61022. alertIconType (iconType),
  61023. associatedComponent (associatedComponent_)
  61024. {
  61025. if (message.isEmpty())
  61026. text = " "; // to force an update if the message is empty
  61027. setMessage (message);
  61028. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  61029. {
  61030. Component* const c = Desktop::getInstance().getComponent (i);
  61031. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  61032. {
  61033. setAlwaysOnTop (true);
  61034. break;
  61035. }
  61036. }
  61037. if (JUCEApplication::getInstance() == 0)
  61038. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61039. lookAndFeelChanged();
  61040. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  61041. }
  61042. AlertWindow::~AlertWindow()
  61043. {
  61044. for (int i = customComps.size(); --i >= 0;)
  61045. removeChildComponent ((Component*) customComps[i]);
  61046. deleteAllChildren();
  61047. }
  61048. void AlertWindow::userTriedToCloseWindow()
  61049. {
  61050. exitModalState (0);
  61051. }
  61052. void AlertWindow::setMessage (const String& message)
  61053. {
  61054. const String newMessage (message.substring (0, 2048));
  61055. if (text != newMessage)
  61056. {
  61057. text = newMessage;
  61058. font.setHeight (15.0f);
  61059. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  61060. textLayout.setText (getName() + "\n\n", titleFont);
  61061. textLayout.appendText (text, font);
  61062. updateLayout (true);
  61063. repaint();
  61064. }
  61065. }
  61066. void AlertWindow::buttonClicked (Button* button)
  61067. {
  61068. for (int i = 0; i < buttons.size(); i++)
  61069. {
  61070. TextButton* const c = (TextButton*) buttons[i];
  61071. if (button->getName() == c->getName())
  61072. {
  61073. if (c->getParentComponent() != 0)
  61074. c->getParentComponent()->exitModalState (c->getCommandID());
  61075. break;
  61076. }
  61077. }
  61078. }
  61079. void AlertWindow::addButton (const String& name,
  61080. const int returnValue,
  61081. const KeyPress& shortcutKey1,
  61082. const KeyPress& shortcutKey2)
  61083. {
  61084. TextButton* const b = new TextButton (name, String::empty);
  61085. b->setWantsKeyboardFocus (true);
  61086. b->setMouseClickGrabsKeyboardFocus (false);
  61087. b->setCommandToTrigger (0, returnValue, false);
  61088. b->addShortcut (shortcutKey1);
  61089. b->addShortcut (shortcutKey2);
  61090. b->addButtonListener (this);
  61091. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  61092. addAndMakeVisible (b, 0);
  61093. buttons.add (b);
  61094. updateLayout (false);
  61095. }
  61096. int AlertWindow::getNumButtons() const
  61097. {
  61098. return buttons.size();
  61099. }
  61100. void AlertWindow::triggerButtonClick (const String& buttonName)
  61101. {
  61102. for (int i = buttons.size(); --i >= 0;)
  61103. {
  61104. TextButton* const b = (TextButton*) buttons[i];
  61105. if (buttonName == b->getName())
  61106. {
  61107. b->triggerClick();
  61108. break;
  61109. }
  61110. }
  61111. }
  61112. void AlertWindow::addTextEditor (const String& name,
  61113. const String& initialContents,
  61114. const String& onScreenLabel,
  61115. const bool isPasswordBox)
  61116. {
  61117. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  61118. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  61119. tc->setFont (font);
  61120. tc->setText (initialContents);
  61121. tc->setCaretPosition (initialContents.length());
  61122. addAndMakeVisible (tc);
  61123. textBoxes.add (tc);
  61124. allComps.add (tc);
  61125. textboxNames.add (onScreenLabel);
  61126. updateLayout (false);
  61127. }
  61128. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  61129. {
  61130. for (int i = textBoxes.size(); --i >= 0;)
  61131. if (((TextEditor*)textBoxes[i])->getName() == nameOfTextEditor)
  61132. return ((TextEditor*)textBoxes[i])->getText();
  61133. return String::empty;
  61134. }
  61135. void AlertWindow::addComboBox (const String& name,
  61136. const StringArray& items,
  61137. const String& onScreenLabel)
  61138. {
  61139. ComboBox* const cb = new ComboBox (name);
  61140. for (int i = 0; i < items.size(); ++i)
  61141. cb->addItem (items[i], i + 1);
  61142. addAndMakeVisible (cb);
  61143. cb->setSelectedItemIndex (0);
  61144. comboBoxes.add (cb);
  61145. allComps.add (cb);
  61146. comboBoxNames.add (onScreenLabel);
  61147. updateLayout (false);
  61148. }
  61149. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  61150. {
  61151. for (int i = comboBoxes.size(); --i >= 0;)
  61152. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  61153. return (ComboBox*) comboBoxes[i];
  61154. return 0;
  61155. }
  61156. class AlertTextComp : public TextEditor
  61157. {
  61158. public:
  61159. AlertTextComp (const String& message,
  61160. const Font& font)
  61161. {
  61162. setReadOnly (true);
  61163. setMultiLine (true, true);
  61164. setCaretVisible (false);
  61165. setScrollbarsShown (true);
  61166. lookAndFeelChanged();
  61167. setWantsKeyboardFocus (false);
  61168. setFont (font);
  61169. setText (message, false);
  61170. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  61171. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  61172. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  61173. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  61174. }
  61175. ~AlertTextComp()
  61176. {
  61177. }
  61178. int getPreferredWidth() const throw() { return bestWidth; }
  61179. void updateLayout (const int width)
  61180. {
  61181. TextLayout text;
  61182. text.appendText (getText(), getFont());
  61183. text.layout (width - 8, Justification::topLeft, true);
  61184. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  61185. }
  61186. private:
  61187. int bestWidth;
  61188. AlertTextComp (const AlertTextComp&);
  61189. AlertTextComp& operator= (const AlertTextComp&);
  61190. };
  61191. void AlertWindow::addTextBlock (const String& textBlock)
  61192. {
  61193. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  61194. textBlocks.add (c);
  61195. allComps.add (c);
  61196. addAndMakeVisible (c);
  61197. updateLayout (false);
  61198. }
  61199. void AlertWindow::addProgressBarComponent (double& progressValue)
  61200. {
  61201. ProgressBar* const pb = new ProgressBar (progressValue);
  61202. progressBars.add (pb);
  61203. allComps.add (pb);
  61204. addAndMakeVisible (pb);
  61205. updateLayout (false);
  61206. }
  61207. void AlertWindow::addCustomComponent (Component* const component)
  61208. {
  61209. customComps.add (component);
  61210. allComps.add (component);
  61211. addAndMakeVisible (component);
  61212. updateLayout (false);
  61213. }
  61214. int AlertWindow::getNumCustomComponents() const
  61215. {
  61216. return customComps.size();
  61217. }
  61218. Component* AlertWindow::getCustomComponent (const int index) const
  61219. {
  61220. return (Component*) customComps [index];
  61221. }
  61222. Component* AlertWindow::removeCustomComponent (const int index)
  61223. {
  61224. Component* const c = getCustomComponent (index);
  61225. if (c != 0)
  61226. {
  61227. customComps.removeValue (c);
  61228. allComps.removeValue (c);
  61229. removeChildComponent (c);
  61230. updateLayout (false);
  61231. }
  61232. return c;
  61233. }
  61234. void AlertWindow::paint (Graphics& g)
  61235. {
  61236. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  61237. g.setColour (findColour (textColourId));
  61238. g.setFont (getLookAndFeel().getAlertWindowFont());
  61239. int i;
  61240. for (i = textBoxes.size(); --i >= 0;)
  61241. {
  61242. const TextEditor* const te = (TextEditor*) textBoxes[i];
  61243. g.drawFittedText (textboxNames[i],
  61244. te->getX(), te->getY() - 14,
  61245. te->getWidth(), 14,
  61246. Justification::centredLeft, 1);
  61247. }
  61248. for (i = comboBoxNames.size(); --i >= 0;)
  61249. {
  61250. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  61251. g.drawFittedText (comboBoxNames[i],
  61252. cb->getX(), cb->getY() - 14,
  61253. cb->getWidth(), 14,
  61254. Justification::centredLeft, 1);
  61255. }
  61256. for (i = customComps.size(); --i >= 0;)
  61257. {
  61258. const Component* const c = (Component*) customComps[i];
  61259. g.drawFittedText (c->getName(),
  61260. c->getX(), c->getY() - 14,
  61261. c->getWidth(), 14,
  61262. Justification::centredLeft, 1);
  61263. }
  61264. }
  61265. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  61266. {
  61267. const int titleH = 24;
  61268. const int iconWidth = 80;
  61269. const int wid = jmax (font.getStringWidth (text),
  61270. font.getStringWidth (getName()));
  61271. const int sw = (int) std::sqrt (font.getHeight() * wid);
  61272. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  61273. const int edgeGap = 10;
  61274. const int labelHeight = 18;
  61275. int iconSpace;
  61276. if (alertIconType == NoIcon)
  61277. {
  61278. textLayout.layout (w, Justification::horizontallyCentred, true);
  61279. iconSpace = 0;
  61280. }
  61281. else
  61282. {
  61283. textLayout.layout (w, Justification::left, true);
  61284. iconSpace = iconWidth;
  61285. }
  61286. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  61287. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61288. const int textLayoutH = textLayout.getHeight();
  61289. const int textBottom = 16 + titleH + textLayoutH;
  61290. int h = textBottom;
  61291. int buttonW = 40;
  61292. int i;
  61293. for (i = 0; i < buttons.size(); ++i)
  61294. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  61295. w = jmax (buttonW, w);
  61296. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  61297. if (buttons.size() > 0)
  61298. h += 20 + ((TextButton*) buttons[0])->getHeight();
  61299. for (i = customComps.size(); --i >= 0;)
  61300. {
  61301. Component* c = (Component*) customComps[i];
  61302. w = jmax (w, (c->getWidth() * 100) / 80);
  61303. h += 10 + c->getHeight();
  61304. if (c->getName().isNotEmpty())
  61305. h += labelHeight;
  61306. }
  61307. for (i = textBlocks.size(); --i >= 0;)
  61308. {
  61309. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  61310. w = jmax (w, ac->getPreferredWidth());
  61311. }
  61312. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61313. for (i = textBlocks.size(); --i >= 0;)
  61314. {
  61315. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  61316. ac->updateLayout ((int) (w * 0.8f));
  61317. h += ac->getHeight() + 10;
  61318. }
  61319. h = jmin (getParentHeight() - 50, h);
  61320. if (onlyIncreaseSize)
  61321. {
  61322. w = jmax (w, getWidth());
  61323. h = jmax (h, getHeight());
  61324. }
  61325. if (! isVisible())
  61326. {
  61327. centreAroundComponent (associatedComponent, w, h);
  61328. }
  61329. else
  61330. {
  61331. const int cx = getX() + getWidth() / 2;
  61332. const int cy = getY() + getHeight() / 2;
  61333. setBounds (cx - w / 2,
  61334. cy - h / 2,
  61335. w, h);
  61336. }
  61337. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  61338. const int spacer = 16;
  61339. int totalWidth = -spacer;
  61340. for (i = buttons.size(); --i >= 0;)
  61341. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  61342. int x = (w - totalWidth) / 2;
  61343. int y = (int) (getHeight() * 0.95f);
  61344. for (i = 0; i < buttons.size(); ++i)
  61345. {
  61346. TextButton* const c = (TextButton*) buttons[i];
  61347. int ny = proportionOfHeight (0.95f) - c->getHeight();
  61348. c->setTopLeftPosition (x, ny);
  61349. if (ny < y)
  61350. y = ny;
  61351. x += c->getWidth() + spacer;
  61352. c->toFront (false);
  61353. }
  61354. y = textBottom;
  61355. for (i = 0; i < allComps.size(); ++i)
  61356. {
  61357. Component* const c = (Component*) allComps[i];
  61358. h = 22;
  61359. const int comboIndex = comboBoxes.indexOf (c);
  61360. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  61361. y += labelHeight;
  61362. const int tbIndex = textBoxes.indexOf (c);
  61363. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  61364. y += labelHeight;
  61365. if (customComps.contains (c))
  61366. {
  61367. if (c->getName().isNotEmpty())
  61368. y += labelHeight;
  61369. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  61370. h = c->getHeight();
  61371. }
  61372. else if (textBlocks.contains (c))
  61373. {
  61374. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  61375. h = c->getHeight();
  61376. }
  61377. else
  61378. {
  61379. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  61380. }
  61381. y += h + 10;
  61382. }
  61383. setWantsKeyboardFocus (getNumChildComponents() == 0);
  61384. }
  61385. bool AlertWindow::containsAnyExtraComponents() const
  61386. {
  61387. return textBoxes.size()
  61388. + comboBoxes.size()
  61389. + progressBars.size()
  61390. + customComps.size() > 0;
  61391. }
  61392. void AlertWindow::mouseDown (const MouseEvent&)
  61393. {
  61394. dragger.startDraggingComponent (this, &constrainer);
  61395. }
  61396. void AlertWindow::mouseDrag (const MouseEvent& e)
  61397. {
  61398. dragger.dragComponent (this, e);
  61399. }
  61400. bool AlertWindow::keyPressed (const KeyPress& key)
  61401. {
  61402. for (int i = buttons.size(); --i >= 0;)
  61403. {
  61404. TextButton* const b = (TextButton*) buttons[i];
  61405. if (b->isRegisteredForShortcut (key))
  61406. {
  61407. b->triggerClick();
  61408. return true;
  61409. }
  61410. }
  61411. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  61412. {
  61413. exitModalState (0);
  61414. return true;
  61415. }
  61416. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  61417. {
  61418. ((TextButton*) buttons.getFirst())->triggerClick();
  61419. return true;
  61420. }
  61421. return false;
  61422. }
  61423. void AlertWindow::lookAndFeelChanged()
  61424. {
  61425. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  61426. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  61427. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  61428. }
  61429. int AlertWindow::getDesktopWindowStyleFlags() const
  61430. {
  61431. return getLookAndFeel().getAlertBoxWindowFlags();
  61432. }
  61433. struct AlertWindowInfo
  61434. {
  61435. String title, message, button1, button2, button3;
  61436. AlertWindow::AlertIconType iconType;
  61437. int numButtons;
  61438. Component::SafePointer<Component> associatedComponent;
  61439. int run() const
  61440. {
  61441. return (int) (pointer_sized_int)
  61442. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  61443. }
  61444. private:
  61445. int show() const
  61446. {
  61447. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  61448. : LookAndFeel::getDefaultLookAndFeel();
  61449. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  61450. iconType, numButtons, associatedComponent));
  61451. jassert (alertBox != 0); // you have to return one of these!
  61452. return alertBox->runModalLoop();
  61453. }
  61454. static void* showCallback (void* userData)
  61455. {
  61456. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  61457. }
  61458. };
  61459. void AlertWindow::showMessageBox (AlertIconType iconType,
  61460. const String& title,
  61461. const String& message,
  61462. const String& buttonText,
  61463. Component* associatedComponent)
  61464. {
  61465. AlertWindowInfo info;
  61466. info.title = title;
  61467. info.message = message;
  61468. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  61469. info.iconType = iconType;
  61470. info.numButtons = 1;
  61471. info.associatedComponent = associatedComponent;
  61472. info.run();
  61473. }
  61474. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  61475. const String& title,
  61476. const String& message,
  61477. const String& button1Text,
  61478. const String& button2Text,
  61479. Component* associatedComponent)
  61480. {
  61481. AlertWindowInfo info;
  61482. info.title = title;
  61483. info.message = message;
  61484. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  61485. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  61486. info.iconType = iconType;
  61487. info.numButtons = 2;
  61488. info.associatedComponent = associatedComponent;
  61489. return info.run() != 0;
  61490. }
  61491. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  61492. const String& title,
  61493. const String& message,
  61494. const String& button1Text,
  61495. const String& button2Text,
  61496. const String& button3Text,
  61497. Component* associatedComponent)
  61498. {
  61499. AlertWindowInfo info;
  61500. info.title = title;
  61501. info.message = message;
  61502. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  61503. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  61504. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  61505. info.iconType = iconType;
  61506. info.numButtons = 3;
  61507. info.associatedComponent = associatedComponent;
  61508. return info.run();
  61509. }
  61510. END_JUCE_NAMESPACE
  61511. /*** End of inlined file: juce_AlertWindow.cpp ***/
  61512. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  61513. BEGIN_JUCE_NAMESPACE
  61514. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  61515. static VoidArray heavyweightPeers;
  61516. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  61517. : component (component_),
  61518. styleFlags (styleFlags_),
  61519. lastPaintTime (0),
  61520. constrainer (0),
  61521. lastDragAndDropCompUnderMouse (0),
  61522. fakeMouseMessageSent (false),
  61523. isWindowMinimised (false)
  61524. {
  61525. heavyweightPeers.add (this);
  61526. }
  61527. ComponentPeer::~ComponentPeer()
  61528. {
  61529. heavyweightPeers.removeValue (this);
  61530. Desktop::getInstance().triggerFocusCallback();
  61531. }
  61532. int ComponentPeer::getNumPeers() throw()
  61533. {
  61534. return heavyweightPeers.size();
  61535. }
  61536. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  61537. {
  61538. return (ComponentPeer*) heavyweightPeers [index];
  61539. }
  61540. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  61541. {
  61542. for (int i = heavyweightPeers.size(); --i >= 0;)
  61543. {
  61544. ComponentPeer* const peer = (ComponentPeer*) heavyweightPeers.getUnchecked(i);
  61545. if (peer->getComponent() == component)
  61546. return peer;
  61547. }
  61548. return 0;
  61549. }
  61550. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  61551. {
  61552. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  61553. }
  61554. void ComponentPeer::updateCurrentModifiers() throw()
  61555. {
  61556. ModifierKeys::updateCurrentModifiers();
  61557. }
  61558. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  61559. {
  61560. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61561. jassert (mouse != 0); // not enough sources!
  61562. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  61563. }
  61564. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  61565. {
  61566. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61567. jassert (mouse != 0); // not enough sources!
  61568. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  61569. }
  61570. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  61571. {
  61572. Graphics g (&contextToPaintTo);
  61573. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61574. g.saveState();
  61575. #endif
  61576. JUCE_TRY
  61577. {
  61578. component->paintEntireComponent (g);
  61579. }
  61580. JUCE_CATCH_EXCEPTION
  61581. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61582. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  61583. // clearly when things are being repainted.
  61584. {
  61585. g.restoreState();
  61586. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  61587. (uint8) Random::getSystemRandom().nextInt (255),
  61588. (uint8) Random::getSystemRandom().nextInt (255),
  61589. (uint8) 0x50));
  61590. }
  61591. #endif
  61592. }
  61593. bool ComponentPeer::handleKeyPress (const int keyCode,
  61594. const juce_wchar textCharacter)
  61595. {
  61596. updateCurrentModifiers();
  61597. Component* target = Component::getCurrentlyFocusedComponent() != 0
  61598. ? Component::getCurrentlyFocusedComponent()
  61599. : component;
  61600. if (target->isCurrentlyBlockedByAnotherModalComponent())
  61601. {
  61602. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  61603. if (currentModalComp != 0)
  61604. target = currentModalComp;
  61605. }
  61606. const KeyPress keyInfo (keyCode,
  61607. ModifierKeys::getCurrentModifiers().getRawFlags()
  61608. & ModifierKeys::allKeyboardModifiers,
  61609. textCharacter);
  61610. bool keyWasUsed = false;
  61611. while (target != 0)
  61612. {
  61613. const Component::SafePointer<Component> deletionChecker (target);
  61614. if (target->keyListeners_ != 0)
  61615. {
  61616. for (int i = target->keyListeners_->size(); --i >= 0;)
  61617. {
  61618. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyPressed (keyInfo, target);
  61619. if (keyWasUsed || deletionChecker == 0)
  61620. return keyWasUsed;
  61621. i = jmin (i, target->keyListeners_->size());
  61622. }
  61623. }
  61624. keyWasUsed = target->keyPressed (keyInfo);
  61625. if (keyWasUsed || deletionChecker == 0)
  61626. break;
  61627. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  61628. {
  61629. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  61630. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  61631. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  61632. break;
  61633. }
  61634. target = target->parentComponent_;
  61635. }
  61636. return keyWasUsed;
  61637. }
  61638. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  61639. {
  61640. updateCurrentModifiers();
  61641. Component* target = Component::getCurrentlyFocusedComponent() != 0
  61642. ? Component::getCurrentlyFocusedComponent()
  61643. : component;
  61644. if (target->isCurrentlyBlockedByAnotherModalComponent())
  61645. {
  61646. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  61647. if (currentModalComp != 0)
  61648. target = currentModalComp;
  61649. }
  61650. bool keyWasUsed = false;
  61651. while (target != 0)
  61652. {
  61653. const Component::SafePointer<Component> deletionChecker (target);
  61654. keyWasUsed = target->keyStateChanged (isKeyDown);
  61655. if (keyWasUsed || deletionChecker == 0)
  61656. break;
  61657. if (target->keyListeners_ != 0)
  61658. {
  61659. for (int i = target->keyListeners_->size(); --i >= 0;)
  61660. {
  61661. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyStateChanged (isKeyDown, target);
  61662. if (keyWasUsed || deletionChecker == 0)
  61663. return keyWasUsed;
  61664. i = jmin (i, target->keyListeners_->size());
  61665. }
  61666. }
  61667. target = target->parentComponent_;
  61668. }
  61669. return keyWasUsed;
  61670. }
  61671. void ComponentPeer::handleModifierKeysChange()
  61672. {
  61673. updateCurrentModifiers();
  61674. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  61675. if (target == 0)
  61676. target = Component::getCurrentlyFocusedComponent();
  61677. if (target == 0)
  61678. target = component;
  61679. if (target != 0)
  61680. target->internalModifierKeysChanged();
  61681. }
  61682. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  61683. {
  61684. Component* const c = Component::getCurrentlyFocusedComponent();
  61685. if (component->isParentOf (c))
  61686. {
  61687. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  61688. if (ti != 0 && ti->isTextInputActive())
  61689. return ti;
  61690. }
  61691. return 0;
  61692. }
  61693. void ComponentPeer::handleBroughtToFront()
  61694. {
  61695. updateCurrentModifiers();
  61696. if (component != 0)
  61697. component->internalBroughtToFront();
  61698. }
  61699. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  61700. {
  61701. constrainer = newConstrainer;
  61702. }
  61703. void ComponentPeer::handleMovedOrResized()
  61704. {
  61705. jassert (component->isValidComponent());
  61706. updateCurrentModifiers();
  61707. const bool nowMinimised = isMinimised();
  61708. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  61709. {
  61710. const Component::SafePointer<Component> deletionChecker (component);
  61711. const Rectangle<int> newBounds (getBounds());
  61712. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  61713. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  61714. if (wasMoved || wasResized)
  61715. {
  61716. component->bounds_ = newBounds;
  61717. if (wasResized)
  61718. component->repaint();
  61719. component->sendMovedResizedMessages (wasMoved, wasResized);
  61720. if (deletionChecker == 0)
  61721. return;
  61722. }
  61723. }
  61724. if (isWindowMinimised != nowMinimised)
  61725. {
  61726. isWindowMinimised = nowMinimised;
  61727. component->minimisationStateChanged (nowMinimised);
  61728. component->sendVisibilityChangeMessage();
  61729. }
  61730. if (! isFullScreen())
  61731. lastNonFullscreenBounds = component->getBounds();
  61732. }
  61733. void ComponentPeer::handleFocusGain()
  61734. {
  61735. updateCurrentModifiers();
  61736. if (component->isParentOf (lastFocusedComponent))
  61737. {
  61738. Component::currentlyFocusedComponent = lastFocusedComponent;
  61739. Desktop::getInstance().triggerFocusCallback();
  61740. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  61741. }
  61742. else
  61743. {
  61744. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  61745. component->grabKeyboardFocus();
  61746. else
  61747. Component::bringModalComponentToFront();
  61748. }
  61749. }
  61750. void ComponentPeer::handleFocusLoss()
  61751. {
  61752. updateCurrentModifiers();
  61753. if (component->hasKeyboardFocus (true))
  61754. {
  61755. lastFocusedComponent = Component::currentlyFocusedComponent;
  61756. if (lastFocusedComponent != 0)
  61757. {
  61758. Component::currentlyFocusedComponent = 0;
  61759. Desktop::getInstance().triggerFocusCallback();
  61760. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  61761. }
  61762. }
  61763. }
  61764. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  61765. {
  61766. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  61767. ? static_cast <Component*> (lastFocusedComponent)
  61768. : component;
  61769. }
  61770. void ComponentPeer::handleScreenSizeChange()
  61771. {
  61772. updateCurrentModifiers();
  61773. component->parentSizeChanged();
  61774. handleMovedOrResized();
  61775. }
  61776. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  61777. {
  61778. lastNonFullscreenBounds = newBounds;
  61779. }
  61780. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  61781. {
  61782. return lastNonFullscreenBounds;
  61783. }
  61784. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  61785. const StringArray& files,
  61786. FileDragAndDropTarget* const lastOne)
  61787. {
  61788. while (c != 0)
  61789. {
  61790. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  61791. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  61792. return t;
  61793. c = c->getParentComponent();
  61794. }
  61795. return 0;
  61796. }
  61797. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  61798. {
  61799. updateCurrentModifiers();
  61800. FileDragAndDropTarget* lastTarget
  61801. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  61802. FileDragAndDropTarget* newTarget = 0;
  61803. Component* const compUnderMouse = component->getComponentAt (position);
  61804. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  61805. {
  61806. lastDragAndDropCompUnderMouse = compUnderMouse;
  61807. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  61808. if (newTarget != lastTarget)
  61809. {
  61810. if (lastTarget != 0)
  61811. lastTarget->fileDragExit (files);
  61812. dragAndDropTargetComponent = 0;
  61813. if (newTarget != 0)
  61814. {
  61815. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  61816. const Point<int> pos (component->relativePositionToOtherComponent (dragAndDropTargetComponent, position));
  61817. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  61818. }
  61819. }
  61820. }
  61821. else
  61822. {
  61823. newTarget = lastTarget;
  61824. }
  61825. if (newTarget != 0)
  61826. {
  61827. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  61828. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  61829. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  61830. }
  61831. }
  61832. void ComponentPeer::handleFileDragExit (const StringArray& files)
  61833. {
  61834. handleFileDragMove (files, Point<int> (-1, -1));
  61835. jassert (dragAndDropTargetComponent == 0);
  61836. lastDragAndDropCompUnderMouse = 0;
  61837. }
  61838. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  61839. {
  61840. handleFileDragMove (files, position);
  61841. if (dragAndDropTargetComponent != 0)
  61842. {
  61843. FileDragAndDropTarget* const target
  61844. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  61845. dragAndDropTargetComponent = 0;
  61846. lastDragAndDropCompUnderMouse = 0;
  61847. if (target != 0)
  61848. {
  61849. Component* const targetComp = dynamic_cast <Component*> (target);
  61850. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  61851. {
  61852. targetComp->internalModalInputAttempt();
  61853. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  61854. return;
  61855. }
  61856. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  61857. target->filesDropped (files, pos.getX(), pos.getY());
  61858. }
  61859. }
  61860. }
  61861. void ComponentPeer::handleUserClosingWindow()
  61862. {
  61863. updateCurrentModifiers();
  61864. component->userTriedToCloseWindow();
  61865. }
  61866. void ComponentPeer::bringModalComponentToFront()
  61867. {
  61868. Component::bringModalComponentToFront();
  61869. }
  61870. void ComponentPeer::clearMaskedRegion()
  61871. {
  61872. maskedRegion.clear();
  61873. }
  61874. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  61875. {
  61876. maskedRegion.add (x, y, w, h);
  61877. }
  61878. const StringArray ComponentPeer::getAvailableRenderingEngines() throw()
  61879. {
  61880. StringArray s;
  61881. s.add ("Software Renderer");
  61882. return s;
  61883. }
  61884. int ComponentPeer::getCurrentRenderingEngine() throw()
  61885. {
  61886. return 0;
  61887. }
  61888. void ComponentPeer::setCurrentRenderingEngine (int /*index*/) throw()
  61889. {
  61890. }
  61891. END_JUCE_NAMESPACE
  61892. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  61893. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  61894. BEGIN_JUCE_NAMESPACE
  61895. DialogWindow::DialogWindow (const String& name,
  61896. const Colour& backgroundColour_,
  61897. const bool escapeKeyTriggersCloseButton_,
  61898. const bool addToDesktop_)
  61899. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  61900. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  61901. {
  61902. }
  61903. DialogWindow::~DialogWindow()
  61904. {
  61905. }
  61906. void DialogWindow::resized()
  61907. {
  61908. DocumentWindow::resized();
  61909. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  61910. if (escapeKeyTriggersCloseButton
  61911. && getCloseButton() != 0
  61912. && ! getCloseButton()->isRegisteredForShortcut (esc))
  61913. {
  61914. getCloseButton()->addShortcut (esc);
  61915. }
  61916. }
  61917. class TempDialogWindow : public DialogWindow
  61918. {
  61919. public:
  61920. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  61921. : DialogWindow (title, colour, escapeCloses, true)
  61922. {
  61923. }
  61924. ~TempDialogWindow()
  61925. {
  61926. }
  61927. void closeButtonPressed()
  61928. {
  61929. setVisible (false);
  61930. }
  61931. private:
  61932. TempDialogWindow (const TempDialogWindow&);
  61933. TempDialogWindow& operator= (const TempDialogWindow&);
  61934. };
  61935. int DialogWindow::showModalDialog (const String& dialogTitle,
  61936. Component* contentComponent,
  61937. Component* componentToCentreAround,
  61938. const Colour& colour,
  61939. const bool escapeKeyTriggersCloseButton,
  61940. const bool shouldBeResizable,
  61941. const bool useBottomRightCornerResizer)
  61942. {
  61943. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  61944. dw.setContentComponent (contentComponent, true, true);
  61945. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  61946. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  61947. const int result = dw.runModalLoop();
  61948. dw.setContentComponent (0, false);
  61949. return result;
  61950. }
  61951. END_JUCE_NAMESPACE
  61952. /*** End of inlined file: juce_DialogWindow.cpp ***/
  61953. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  61954. BEGIN_JUCE_NAMESPACE
  61955. class DocumentWindow::ButtonListenerProxy : public ButtonListener
  61956. {
  61957. public:
  61958. ButtonListenerProxy (DocumentWindow& owner_)
  61959. : owner (owner_)
  61960. {
  61961. }
  61962. void buttonClicked (Button* button)
  61963. {
  61964. if (button == owner.getMinimiseButton())
  61965. owner.minimiseButtonPressed();
  61966. else if (button == owner.getMaximiseButton())
  61967. owner.maximiseButtonPressed();
  61968. else if (button == owner.getCloseButton())
  61969. owner.closeButtonPressed();
  61970. }
  61971. juce_UseDebuggingNewOperator
  61972. private:
  61973. DocumentWindow& owner;
  61974. ButtonListenerProxy (const ButtonListenerProxy&);
  61975. ButtonListenerProxy& operator= (const ButtonListenerProxy&);
  61976. };
  61977. DocumentWindow::DocumentWindow (const String& title,
  61978. const Colour& backgroundColour,
  61979. const int requiredButtons_,
  61980. const bool addToDesktop_)
  61981. : ResizableWindow (title, backgroundColour, addToDesktop_),
  61982. titleBarHeight (26),
  61983. menuBarHeight (24),
  61984. requiredButtons (requiredButtons_),
  61985. #if JUCE_MAC
  61986. positionTitleBarButtonsOnLeft (true),
  61987. #else
  61988. positionTitleBarButtonsOnLeft (false),
  61989. #endif
  61990. drawTitleTextCentred (true),
  61991. menuBarModel (0)
  61992. {
  61993. setResizeLimits (128, 128, 32768, 32768);
  61994. lookAndFeelChanged();
  61995. }
  61996. DocumentWindow::~DocumentWindow()
  61997. {
  61998. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  61999. titleBarButtons[i] = 0;
  62000. menuBar = 0;
  62001. }
  62002. void DocumentWindow::repaintTitleBar()
  62003. {
  62004. const Rectangle<int> titleBarArea (getTitleBarArea());
  62005. repaint (titleBarArea.getX(), titleBarArea.getY(),
  62006. titleBarArea.getWidth(), titleBarArea.getHeight());
  62007. }
  62008. void DocumentWindow::setName (const String& newName)
  62009. {
  62010. if (newName != getName())
  62011. {
  62012. Component::setName (newName);
  62013. repaintTitleBar();
  62014. }
  62015. }
  62016. void DocumentWindow::setIcon (const Image* imageToUse)
  62017. {
  62018. titleBarIcon = imageToUse != 0 ? imageToUse->createCopy() : 0;
  62019. repaintTitleBar();
  62020. }
  62021. void DocumentWindow::setTitleBarHeight (const int newHeight)
  62022. {
  62023. titleBarHeight = newHeight;
  62024. resized();
  62025. repaintTitleBar();
  62026. }
  62027. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  62028. const bool positionTitleBarButtonsOnLeft_)
  62029. {
  62030. requiredButtons = requiredButtons_;
  62031. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  62032. lookAndFeelChanged();
  62033. }
  62034. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  62035. {
  62036. drawTitleTextCentred = textShouldBeCentred;
  62037. repaintTitleBar();
  62038. }
  62039. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  62040. const int menuBarHeight_)
  62041. {
  62042. if (menuBarModel != menuBarModel_)
  62043. {
  62044. menuBar = 0;
  62045. menuBarModel = menuBarModel_;
  62046. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  62047. : getLookAndFeel().getDefaultMenuBarHeight();
  62048. if (menuBarModel != 0)
  62049. {
  62050. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62051. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  62052. menuBar->setEnabled (isActiveWindow());
  62053. }
  62054. resized();
  62055. }
  62056. }
  62057. void DocumentWindow::closeButtonPressed()
  62058. {
  62059. /* If you've got a close button, you have to override this method to get
  62060. rid of your window!
  62061. If the window is just a pop-up, you should override this method and make
  62062. it delete the window in whatever way is appropriate for your app. E.g. you
  62063. might just want to call "delete this".
  62064. If your app is centred around this window such that the whole app should quit when
  62065. the window is closed, then you will probably want to use this method as an opportunity
  62066. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  62067. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  62068. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  62069. or closing it via the taskbar icon on Windows).
  62070. */
  62071. jassertfalse
  62072. }
  62073. void DocumentWindow::minimiseButtonPressed()
  62074. {
  62075. setMinimised (true);
  62076. }
  62077. void DocumentWindow::maximiseButtonPressed()
  62078. {
  62079. setFullScreen (! isFullScreen());
  62080. }
  62081. void DocumentWindow::paint (Graphics& g)
  62082. {
  62083. ResizableWindow::paint (g);
  62084. if (resizableBorder == 0)
  62085. {
  62086. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  62087. const BorderSize border (getBorderThickness());
  62088. g.fillRect (0, 0, getWidth(), border.getTop());
  62089. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  62090. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  62091. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  62092. }
  62093. const Rectangle<int> titleBarArea (getTitleBarArea());
  62094. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  62095. g.reduceClipRegion (0, 0, titleBarArea.getWidth(), titleBarArea.getHeight());
  62096. int titleSpaceX1 = 6;
  62097. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  62098. for (int i = 0; i < 3; ++i)
  62099. {
  62100. if (titleBarButtons[i] != 0)
  62101. {
  62102. if (positionTitleBarButtonsOnLeft)
  62103. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  62104. else
  62105. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  62106. }
  62107. }
  62108. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  62109. titleBarArea.getWidth(),
  62110. titleBarArea.getHeight(),
  62111. titleSpaceX1,
  62112. jmax (1, titleSpaceX2 - titleSpaceX1),
  62113. titleBarIcon,
  62114. ! drawTitleTextCentred);
  62115. }
  62116. void DocumentWindow::resized()
  62117. {
  62118. ResizableWindow::resized();
  62119. if (titleBarButtons[1] != 0)
  62120. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  62121. const Rectangle<int> titleBarArea (getTitleBarArea());
  62122. getLookAndFeel()
  62123. .positionDocumentWindowButtons (*this,
  62124. titleBarArea.getX(), titleBarArea.getY(),
  62125. titleBarArea.getWidth(), titleBarArea.getHeight(),
  62126. titleBarButtons[0],
  62127. titleBarButtons[1],
  62128. titleBarButtons[2],
  62129. positionTitleBarButtonsOnLeft);
  62130. if (menuBar != 0)
  62131. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  62132. titleBarArea.getWidth(), menuBarHeight);
  62133. }
  62134. const BorderSize DocumentWindow::getBorderThickness()
  62135. {
  62136. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  62137. ? 0 : (resizableBorder != 0 ? 4 : 1));
  62138. }
  62139. const BorderSize DocumentWindow::getContentComponentBorder()
  62140. {
  62141. BorderSize border (getBorderThickness());
  62142. border.setTop (border.getTop()
  62143. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  62144. + (menuBar != 0 ? menuBarHeight : 0));
  62145. return border;
  62146. }
  62147. int DocumentWindow::getTitleBarHeight() const
  62148. {
  62149. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  62150. }
  62151. const Rectangle<int> DocumentWindow::getTitleBarArea()
  62152. {
  62153. const BorderSize border (getBorderThickness());
  62154. return Rectangle<int> (border.getLeft(), border.getTop(),
  62155. getWidth() - border.getLeftAndRight(),
  62156. getTitleBarHeight());
  62157. }
  62158. Button* DocumentWindow::getCloseButton() const throw()
  62159. {
  62160. return titleBarButtons[2];
  62161. }
  62162. Button* DocumentWindow::getMinimiseButton() const throw()
  62163. {
  62164. return titleBarButtons[0];
  62165. }
  62166. Button* DocumentWindow::getMaximiseButton() const throw()
  62167. {
  62168. return titleBarButtons[1];
  62169. }
  62170. int DocumentWindow::getDesktopWindowStyleFlags() const
  62171. {
  62172. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  62173. if ((requiredButtons & minimiseButton) != 0)
  62174. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  62175. if ((requiredButtons & maximiseButton) != 0)
  62176. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  62177. if ((requiredButtons & closeButton) != 0)
  62178. styleFlags |= ComponentPeer::windowHasCloseButton;
  62179. return styleFlags;
  62180. }
  62181. void DocumentWindow::lookAndFeelChanged()
  62182. {
  62183. int i;
  62184. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  62185. titleBarButtons[i] = 0;
  62186. if (! isUsingNativeTitleBar())
  62187. {
  62188. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  62189. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  62190. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  62191. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  62192. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  62193. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  62194. for (i = 0; i < 3; ++i)
  62195. {
  62196. if (titleBarButtons[i] != 0)
  62197. {
  62198. if (buttonListener == 0)
  62199. buttonListener = new ButtonListenerProxy (*this);
  62200. titleBarButtons[i]->addButtonListener (buttonListener);
  62201. titleBarButtons[i]->setWantsKeyboardFocus (false);
  62202. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62203. Component::addAndMakeVisible (titleBarButtons[i]);
  62204. }
  62205. }
  62206. if (getCloseButton() != 0)
  62207. {
  62208. #if JUCE_MAC
  62209. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  62210. #else
  62211. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  62212. #endif
  62213. }
  62214. }
  62215. activeWindowStatusChanged();
  62216. ResizableWindow::lookAndFeelChanged();
  62217. }
  62218. void DocumentWindow::parentHierarchyChanged()
  62219. {
  62220. lookAndFeelChanged();
  62221. }
  62222. void DocumentWindow::activeWindowStatusChanged()
  62223. {
  62224. ResizableWindow::activeWindowStatusChanged();
  62225. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62226. if (titleBarButtons[i] != 0)
  62227. titleBarButtons[i]->setEnabled (isActiveWindow());
  62228. if (menuBar != 0)
  62229. menuBar->setEnabled (isActiveWindow());
  62230. }
  62231. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  62232. {
  62233. if (getTitleBarArea().contains (e.x, e.y)
  62234. && getMaximiseButton() != 0)
  62235. {
  62236. getMaximiseButton()->triggerClick();
  62237. }
  62238. }
  62239. void DocumentWindow::userTriedToCloseWindow()
  62240. {
  62241. closeButtonPressed();
  62242. }
  62243. END_JUCE_NAMESPACE
  62244. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  62245. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  62246. BEGIN_JUCE_NAMESPACE
  62247. ResizableWindow::ResizableWindow (const String& name,
  62248. const bool addToDesktop_)
  62249. : TopLevelWindow (name, addToDesktop_),
  62250. resizeToFitContent (false),
  62251. fullscreen (false),
  62252. lastNonFullScreenPos (50, 50, 256, 256),
  62253. constrainer (0)
  62254. #if JUCE_DEBUG
  62255. , hasBeenResized (false)
  62256. #endif
  62257. {
  62258. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62259. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  62260. if (addToDesktop_)
  62261. Component::addToDesktop (getDesktopWindowStyleFlags());
  62262. }
  62263. ResizableWindow::ResizableWindow (const String& name,
  62264. const Colour& backgroundColour_,
  62265. const bool addToDesktop_)
  62266. : TopLevelWindow (name, addToDesktop_),
  62267. resizeToFitContent (false),
  62268. fullscreen (false),
  62269. lastNonFullScreenPos (50, 50, 256, 256),
  62270. constrainer (0)
  62271. #if JUCE_DEBUG
  62272. , hasBeenResized (false)
  62273. #endif
  62274. {
  62275. setBackgroundColour (backgroundColour_);
  62276. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62277. if (addToDesktop_)
  62278. Component::addToDesktop (getDesktopWindowStyleFlags());
  62279. }
  62280. ResizableWindow::~ResizableWindow()
  62281. {
  62282. resizableCorner = 0;
  62283. resizableBorder = 0;
  62284. contentComponent = 0;
  62285. // have you been adding your own components directly to this window..? tut tut tut.
  62286. // Read the instructions for using a ResizableWindow!
  62287. jassert (getNumChildComponents() == 0);
  62288. }
  62289. int ResizableWindow::getDesktopWindowStyleFlags() const
  62290. {
  62291. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  62292. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  62293. styleFlags |= ComponentPeer::windowIsResizable;
  62294. return styleFlags;
  62295. }
  62296. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  62297. const bool deleteOldOne,
  62298. const bool resizeToFit)
  62299. {
  62300. resizeToFitContent = resizeToFit;
  62301. if (newContentComponent != static_cast <Component*> (contentComponent))
  62302. {
  62303. if (! deleteOldOne)
  62304. removeChildComponent (contentComponent.release());
  62305. contentComponent = newContentComponent;
  62306. Component::addAndMakeVisible (contentComponent);
  62307. }
  62308. if (resizeToFit)
  62309. childBoundsChanged (contentComponent);
  62310. resized(); // must always be called to position the new content comp
  62311. }
  62312. void ResizableWindow::setContentComponentSize (int width, int height)
  62313. {
  62314. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  62315. const BorderSize border (getContentComponentBorder());
  62316. setSize (width + border.getLeftAndRight(),
  62317. height + border.getTopAndBottom());
  62318. }
  62319. const BorderSize ResizableWindow::getBorderThickness()
  62320. {
  62321. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  62322. }
  62323. const BorderSize ResizableWindow::getContentComponentBorder()
  62324. {
  62325. return getBorderThickness();
  62326. }
  62327. void ResizableWindow::moved()
  62328. {
  62329. updateLastPos();
  62330. }
  62331. void ResizableWindow::visibilityChanged()
  62332. {
  62333. TopLevelWindow::visibilityChanged();
  62334. updateLastPos();
  62335. }
  62336. void ResizableWindow::resized()
  62337. {
  62338. if (resizableBorder != 0)
  62339. {
  62340. resizableBorder->setVisible (! isFullScreen());
  62341. resizableBorder->setBorderThickness (getBorderThickness());
  62342. resizableBorder->setSize (getWidth(), getHeight());
  62343. resizableBorder->toBack();
  62344. }
  62345. if (resizableCorner != 0)
  62346. {
  62347. resizableCorner->setVisible (! isFullScreen());
  62348. const int resizerSize = 18;
  62349. resizableCorner->setBounds (getWidth() - resizerSize,
  62350. getHeight() - resizerSize,
  62351. resizerSize, resizerSize);
  62352. }
  62353. if (contentComponent != 0)
  62354. contentComponent->setBoundsInset (getContentComponentBorder());
  62355. updateLastPos();
  62356. #if JUCE_DEBUG
  62357. hasBeenResized = true;
  62358. #endif
  62359. }
  62360. void ResizableWindow::childBoundsChanged (Component* child)
  62361. {
  62362. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  62363. {
  62364. // not going to look very good if this component has a zero size..
  62365. jassert (child->getWidth() > 0);
  62366. jassert (child->getHeight() > 0);
  62367. const BorderSize borders (getContentComponentBorder());
  62368. setSize (child->getWidth() + borders.getLeftAndRight(),
  62369. child->getHeight() + borders.getTopAndBottom());
  62370. }
  62371. }
  62372. void ResizableWindow::activeWindowStatusChanged()
  62373. {
  62374. const BorderSize borders (getContentComponentBorder());
  62375. repaint (0, 0, getWidth(), borders.getTop());
  62376. repaint (0, borders.getTop(), borders.getLeft(), getHeight() - borders.getBottom() - borders.getTop());
  62377. repaint (0, getHeight() - borders.getBottom(), getWidth(), borders.getBottom());
  62378. repaint (getWidth() - borders.getRight(), borders.getTop(), borders.getRight(), getHeight() - borders.getBottom() - borders.getTop());
  62379. }
  62380. void ResizableWindow::setResizable (const bool shouldBeResizable,
  62381. const bool useBottomRightCornerResizer)
  62382. {
  62383. if (shouldBeResizable)
  62384. {
  62385. if (useBottomRightCornerResizer)
  62386. {
  62387. resizableBorder = 0;
  62388. if (resizableCorner == 0)
  62389. {
  62390. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  62391. resizableCorner->setAlwaysOnTop (true);
  62392. }
  62393. }
  62394. else
  62395. {
  62396. resizableCorner = 0;
  62397. if (resizableBorder == 0)
  62398. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  62399. }
  62400. }
  62401. else
  62402. {
  62403. resizableCorner = 0;
  62404. resizableBorder = 0;
  62405. }
  62406. if (isUsingNativeTitleBar())
  62407. recreateDesktopWindow();
  62408. childBoundsChanged (contentComponent);
  62409. resized();
  62410. }
  62411. bool ResizableWindow::isResizable() const throw()
  62412. {
  62413. return resizableCorner != 0
  62414. || resizableBorder != 0;
  62415. }
  62416. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  62417. const int newMinimumHeight,
  62418. const int newMaximumWidth,
  62419. const int newMaximumHeight) throw()
  62420. {
  62421. // if you've set up a custom constrainer then these settings won't have any effect..
  62422. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  62423. if (constrainer == 0)
  62424. setConstrainer (&defaultConstrainer);
  62425. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  62426. newMaximumWidth, newMaximumHeight);
  62427. setBoundsConstrained (getBounds());
  62428. }
  62429. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  62430. {
  62431. if (constrainer != newConstrainer)
  62432. {
  62433. constrainer = newConstrainer;
  62434. const bool useBottomRightCornerResizer = resizableCorner != 0;
  62435. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  62436. resizableCorner = 0;
  62437. resizableBorder = 0;
  62438. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62439. ComponentPeer* const peer = getPeer();
  62440. if (peer != 0)
  62441. peer->setConstrainer (newConstrainer);
  62442. }
  62443. }
  62444. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  62445. {
  62446. if (constrainer != 0)
  62447. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  62448. else
  62449. setBounds (bounds);
  62450. }
  62451. void ResizableWindow::paint (Graphics& g)
  62452. {
  62453. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  62454. getBorderThickness(), *this);
  62455. if (! isFullScreen())
  62456. {
  62457. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  62458. getBorderThickness(), *this);
  62459. }
  62460. #if JUCE_DEBUG
  62461. /* If this fails, then you've probably written a subclass with a resized()
  62462. callback but forgotten to make it call its parent class's resized() method.
  62463. It's important when you override methods like resized(), moved(),
  62464. etc., that you make sure the base class methods also get called.
  62465. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  62466. because your content should all be inside the content component - and it's the
  62467. content component's resized() method that you should be using to do your
  62468. layout.
  62469. */
  62470. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  62471. #endif
  62472. }
  62473. void ResizableWindow::lookAndFeelChanged()
  62474. {
  62475. resized();
  62476. if (isOnDesktop())
  62477. {
  62478. Component::addToDesktop (getDesktopWindowStyleFlags());
  62479. ComponentPeer* const peer = getPeer();
  62480. if (peer != 0)
  62481. peer->setConstrainer (constrainer);
  62482. }
  62483. }
  62484. const Colour ResizableWindow::getBackgroundColour() const throw()
  62485. {
  62486. return findColour (backgroundColourId, false);
  62487. }
  62488. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  62489. {
  62490. Colour backgroundColour (newColour);
  62491. if (! Desktop::canUseSemiTransparentWindows())
  62492. backgroundColour = newColour.withAlpha (1.0f);
  62493. setColour (backgroundColourId, backgroundColour);
  62494. setOpaque (backgroundColour.isOpaque());
  62495. repaint();
  62496. }
  62497. bool ResizableWindow::isFullScreen() const
  62498. {
  62499. if (isOnDesktop())
  62500. {
  62501. ComponentPeer* const peer = getPeer();
  62502. return peer != 0 && peer->isFullScreen();
  62503. }
  62504. return fullscreen;
  62505. }
  62506. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  62507. {
  62508. if (shouldBeFullScreen != isFullScreen())
  62509. {
  62510. updateLastPos();
  62511. fullscreen = shouldBeFullScreen;
  62512. if (isOnDesktop())
  62513. {
  62514. ComponentPeer* const peer = getPeer();
  62515. if (peer != 0)
  62516. {
  62517. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  62518. const Rectangle<int> lastPos (lastNonFullScreenPos);
  62519. peer->setFullScreen (shouldBeFullScreen);
  62520. if (! shouldBeFullScreen)
  62521. setBounds (lastPos);
  62522. }
  62523. else
  62524. {
  62525. jassertfalse
  62526. }
  62527. }
  62528. else
  62529. {
  62530. if (shouldBeFullScreen)
  62531. setBounds (0, 0, getParentWidth(), getParentHeight());
  62532. else
  62533. setBounds (lastNonFullScreenPos);
  62534. }
  62535. resized();
  62536. }
  62537. }
  62538. bool ResizableWindow::isMinimised() const
  62539. {
  62540. ComponentPeer* const peer = getPeer();
  62541. return (peer != 0) && peer->isMinimised();
  62542. }
  62543. void ResizableWindow::setMinimised (const bool shouldMinimise)
  62544. {
  62545. if (shouldMinimise != isMinimised())
  62546. {
  62547. ComponentPeer* const peer = getPeer();
  62548. if (peer != 0)
  62549. {
  62550. updateLastPos();
  62551. peer->setMinimised (shouldMinimise);
  62552. }
  62553. else
  62554. {
  62555. jassertfalse
  62556. }
  62557. }
  62558. }
  62559. void ResizableWindow::updateLastPos()
  62560. {
  62561. if (isShowing() && ! (isFullScreen() || isMinimised()))
  62562. {
  62563. lastNonFullScreenPos = getBounds();
  62564. }
  62565. }
  62566. void ResizableWindow::parentSizeChanged()
  62567. {
  62568. if (isFullScreen() && getParentComponent() != 0)
  62569. {
  62570. setBounds (0, 0, getParentWidth(), getParentHeight());
  62571. }
  62572. }
  62573. const String ResizableWindow::getWindowStateAsString()
  62574. {
  62575. updateLastPos();
  62576. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  62577. }
  62578. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  62579. {
  62580. StringArray tokens;
  62581. tokens.addTokens (s, false);
  62582. tokens.removeEmptyStrings();
  62583. tokens.trim();
  62584. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  62585. const int firstCoord = fs ? 1 : 0;
  62586. if (tokens.size() != firstCoord + 4)
  62587. return false;
  62588. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  62589. tokens[firstCoord + 1].getIntValue(),
  62590. tokens[firstCoord + 2].getIntValue(),
  62591. tokens[firstCoord + 3].getIntValue());
  62592. if (newPos.isEmpty())
  62593. return false;
  62594. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  62595. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  62596. if (peer != 0)
  62597. peer->getFrameSize().addTo (newPos);
  62598. if (! screen.contains (newPos))
  62599. {
  62600. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  62601. jmin (newPos.getHeight(), screen.getHeight()));
  62602. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  62603. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  62604. }
  62605. if (peer != 0)
  62606. {
  62607. peer->getFrameSize().subtractFrom (newPos);
  62608. peer->setNonFullScreenBounds (newPos);
  62609. }
  62610. lastNonFullScreenPos = newPos;
  62611. setFullScreen (fs);
  62612. if (! fs)
  62613. setBoundsConstrained (newPos);
  62614. return true;
  62615. }
  62616. void ResizableWindow::mouseDown (const MouseEvent&)
  62617. {
  62618. if (! isFullScreen())
  62619. dragger.startDraggingComponent (this, constrainer);
  62620. }
  62621. void ResizableWindow::mouseDrag (const MouseEvent& e)
  62622. {
  62623. if (! isFullScreen())
  62624. dragger.dragComponent (this, e);
  62625. }
  62626. #if JUCE_DEBUG
  62627. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  62628. {
  62629. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  62630. manages its child components automatically, and if you add your own it'll cause
  62631. trouble. Instead, use setContentComponent() to give it a component which
  62632. will be automatically resized and kept in the right place - then you can add
  62633. subcomponents to the content comp. See the notes for the ResizableWindow class
  62634. for more info.
  62635. If you really know what you're doing and want to avoid this assertion, just call
  62636. Component::addChildComponent directly.
  62637. */
  62638. jassertfalse
  62639. Component::addChildComponent (child, zOrder);
  62640. }
  62641. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  62642. {
  62643. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  62644. manages its child components automatically, and if you add your own it'll cause
  62645. trouble. Instead, use setContentComponent() to give it a component which
  62646. will be automatically resized and kept in the right place - then you can add
  62647. subcomponents to the content comp. See the notes for the ResizableWindow class
  62648. for more info.
  62649. If you really know what you're doing and want to avoid this assertion, just call
  62650. Component::addAndMakeVisible directly.
  62651. */
  62652. jassertfalse
  62653. Component::addAndMakeVisible (child, zOrder);
  62654. }
  62655. #endif
  62656. END_JUCE_NAMESPACE
  62657. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  62658. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  62659. BEGIN_JUCE_NAMESPACE
  62660. SplashScreen::SplashScreen()
  62661. : backgroundImage (0)
  62662. {
  62663. setOpaque (true);
  62664. }
  62665. SplashScreen::~SplashScreen()
  62666. {
  62667. ImageCache::releaseOrDelete (backgroundImage);
  62668. }
  62669. void SplashScreen::show (const String& title,
  62670. Image* const backgroundImage_,
  62671. const int minimumTimeToDisplayFor,
  62672. const bool useDropShadow,
  62673. const bool removeOnMouseClick)
  62674. {
  62675. backgroundImage = backgroundImage_;
  62676. jassert (backgroundImage_ != 0);
  62677. if (backgroundImage_ != 0)
  62678. {
  62679. setOpaque (! backgroundImage_->hasAlphaChannel());
  62680. show (title,
  62681. backgroundImage_->getWidth(),
  62682. backgroundImage_->getHeight(),
  62683. minimumTimeToDisplayFor,
  62684. useDropShadow,
  62685. removeOnMouseClick);
  62686. }
  62687. }
  62688. void SplashScreen::show (const String& title,
  62689. const int width,
  62690. const int height,
  62691. const int minimumTimeToDisplayFor,
  62692. const bool useDropShadow,
  62693. const bool removeOnMouseClick)
  62694. {
  62695. setName (title);
  62696. setAlwaysOnTop (true);
  62697. setVisible (true);
  62698. centreWithSize (width, height);
  62699. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  62700. toFront (false);
  62701. MessageManager::getInstance()->runDispatchLoopUntil (300);
  62702. repaint();
  62703. originalClickCounter = removeOnMouseClick
  62704. ? Desktop::getMouseButtonClickCounter()
  62705. : std::numeric_limits<int>::max();
  62706. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  62707. startTimer (50);
  62708. }
  62709. void SplashScreen::paint (Graphics& g)
  62710. {
  62711. if (backgroundImage != 0)
  62712. {
  62713. g.setOpacity (1.0f);
  62714. g.drawImage (backgroundImage,
  62715. 0, 0, getWidth(), getHeight(),
  62716. 0, 0, backgroundImage->getWidth(), backgroundImage->getHeight());
  62717. }
  62718. }
  62719. void SplashScreen::timerCallback()
  62720. {
  62721. if (Time::getCurrentTime() > earliestTimeToDelete
  62722. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  62723. {
  62724. delete this;
  62725. }
  62726. }
  62727. END_JUCE_NAMESPACE
  62728. /*** End of inlined file: juce_SplashScreen.cpp ***/
  62729. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  62730. BEGIN_JUCE_NAMESPACE
  62731. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  62732. const bool hasProgressBar,
  62733. const bool hasCancelButton,
  62734. const int timeOutMsWhenCancelling_,
  62735. const String& cancelButtonText)
  62736. : Thread ("Juce Progress Window"),
  62737. progress (0.0),
  62738. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  62739. {
  62740. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  62741. .createAlertWindow (title, String::empty, cancelButtonText,
  62742. String::empty, String::empty,
  62743. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  62744. if (hasProgressBar)
  62745. alertWindow->addProgressBarComponent (progress);
  62746. }
  62747. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  62748. {
  62749. stopThread (timeOutMsWhenCancelling);
  62750. }
  62751. bool ThreadWithProgressWindow::runThread (const int priority)
  62752. {
  62753. startThread (priority);
  62754. startTimer (100);
  62755. {
  62756. const ScopedLock sl (messageLock);
  62757. alertWindow->setMessage (message);
  62758. }
  62759. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  62760. stopThread (timeOutMsWhenCancelling);
  62761. alertWindow->setVisible (false);
  62762. return finishedNaturally;
  62763. }
  62764. void ThreadWithProgressWindow::setProgress (const double newProgress)
  62765. {
  62766. progress = newProgress;
  62767. }
  62768. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  62769. {
  62770. const ScopedLock sl (messageLock);
  62771. message = newStatusMessage;
  62772. }
  62773. void ThreadWithProgressWindow::timerCallback()
  62774. {
  62775. if (! isThreadRunning())
  62776. {
  62777. // thread has finished normally..
  62778. alertWindow->exitModalState (1);
  62779. alertWindow->setVisible (false);
  62780. }
  62781. else
  62782. {
  62783. const ScopedLock sl (messageLock);
  62784. alertWindow->setMessage (message);
  62785. }
  62786. }
  62787. END_JUCE_NAMESPACE
  62788. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  62789. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  62790. BEGIN_JUCE_NAMESPACE
  62791. TooltipWindow::TooltipWindow (Component* const parentComponent,
  62792. const int millisecondsBeforeTipAppears_)
  62793. : Component ("tooltip"),
  62794. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  62795. mouseClicks (0),
  62796. lastHideTime (0),
  62797. lastComponentUnderMouse (0),
  62798. changedCompsSinceShown (true)
  62799. {
  62800. if (Desktop::getInstance().getMainMouseSource().canHover())
  62801. startTimer (123);
  62802. setAlwaysOnTop (true);
  62803. setOpaque (true);
  62804. if (parentComponent != 0)
  62805. parentComponent->addChildComponent (this);
  62806. }
  62807. TooltipWindow::~TooltipWindow()
  62808. {
  62809. hide();
  62810. }
  62811. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  62812. {
  62813. millisecondsBeforeTipAppears = newTimeMs;
  62814. }
  62815. void TooltipWindow::paint (Graphics& g)
  62816. {
  62817. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  62818. }
  62819. void TooltipWindow::mouseEnter (const MouseEvent&)
  62820. {
  62821. hide();
  62822. }
  62823. void TooltipWindow::showFor (const String& tip)
  62824. {
  62825. jassert (tip.isNotEmpty());
  62826. tipShowing = tip;
  62827. Point<int> mousePos (Desktop::getMousePosition());
  62828. if (getParentComponent() != 0)
  62829. mousePos = getParentComponent()->globalPositionToRelative (mousePos);
  62830. int x, y, w, h;
  62831. getLookAndFeel().getTooltipSize (tip, w, h);
  62832. if (mousePos.getX() > getParentWidth() / 2)
  62833. x = mousePos.getX() - (w + 12);
  62834. else
  62835. x = mousePos.getX() + 24;
  62836. if (mousePos.getY() > getParentHeight() / 2)
  62837. y = mousePos.getY() - (h + 6);
  62838. else
  62839. y = mousePos.getY() + 6;
  62840. setBounds (x, y, w, h);
  62841. setVisible (true);
  62842. if (getParentComponent() == 0)
  62843. {
  62844. addToDesktop (ComponentPeer::windowHasDropShadow
  62845. | ComponentPeer::windowIsTemporary
  62846. | ComponentPeer::windowIgnoresKeyPresses);
  62847. }
  62848. toFront (false);
  62849. }
  62850. const String TooltipWindow::getTipFor (Component* const c)
  62851. {
  62852. if (c != 0
  62853. && Process::isForegroundProcess()
  62854. && ! Component::isMouseButtonDownAnywhere())
  62855. {
  62856. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  62857. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  62858. return ttc->getTooltip();
  62859. }
  62860. return String::empty;
  62861. }
  62862. void TooltipWindow::hide()
  62863. {
  62864. tipShowing = String::empty;
  62865. removeFromDesktop();
  62866. setVisible (false);
  62867. }
  62868. void TooltipWindow::timerCallback()
  62869. {
  62870. const unsigned int now = Time::getApproximateMillisecondCounter();
  62871. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  62872. const String newTip (getTipFor (newComp));
  62873. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  62874. lastComponentUnderMouse = newComp;
  62875. lastTipUnderMouse = newTip;
  62876. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  62877. const bool mouseWasClicked = clickCount > mouseClicks;
  62878. mouseClicks = clickCount;
  62879. const Point<int> mousePos (Desktop::getMousePosition());
  62880. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  62881. lastMousePos = mousePos;
  62882. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  62883. lastCompChangeTime = now;
  62884. if (isVisible() || now < lastHideTime + 500)
  62885. {
  62886. // if a tip is currently visible (or has just disappeared), update to a new one
  62887. // immediately if needed..
  62888. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  62889. {
  62890. if (isVisible())
  62891. {
  62892. lastHideTime = now;
  62893. hide();
  62894. }
  62895. }
  62896. else if (tipChanged)
  62897. {
  62898. showFor (newTip);
  62899. }
  62900. }
  62901. else
  62902. {
  62903. // if there isn't currently a tip, but one is needed, only let it
  62904. // appear after a timeout..
  62905. if (newTip.isNotEmpty()
  62906. && newTip != tipShowing
  62907. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  62908. {
  62909. showFor (newTip);
  62910. }
  62911. }
  62912. }
  62913. END_JUCE_NAMESPACE
  62914. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  62915. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  62916. BEGIN_JUCE_NAMESPACE
  62917. /** Keeps track of the active top level window.
  62918. */
  62919. class TopLevelWindowManager : public Timer,
  62920. public DeletedAtShutdown
  62921. {
  62922. public:
  62923. TopLevelWindowManager()
  62924. : currentActive (0)
  62925. {
  62926. }
  62927. ~TopLevelWindowManager()
  62928. {
  62929. clearSingletonInstance();
  62930. }
  62931. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  62932. void timerCallback()
  62933. {
  62934. startTimer (jmin (1731, getTimerInterval() * 2));
  62935. TopLevelWindow* active = 0;
  62936. if (Process::isForegroundProcess())
  62937. {
  62938. active = currentActive;
  62939. Component* const c = Component::getCurrentlyFocusedComponent();
  62940. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  62941. if (tlw == 0 && c != 0)
  62942. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  62943. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  62944. if (tlw != 0)
  62945. active = tlw;
  62946. }
  62947. if (active != currentActive)
  62948. {
  62949. currentActive = active;
  62950. for (int i = windows.size(); --i >= 0;)
  62951. {
  62952. TopLevelWindow* const tlw = (TopLevelWindow*) windows.getUnchecked (i);
  62953. tlw->setWindowActive (isWindowActive (tlw));
  62954. i = jmin (i, windows.size() - 1);
  62955. }
  62956. Desktop::getInstance().triggerFocusCallback();
  62957. }
  62958. }
  62959. bool addWindow (TopLevelWindow* const w)
  62960. {
  62961. windows.add (w);
  62962. startTimer (10);
  62963. return isWindowActive (w);
  62964. }
  62965. void removeWindow (TopLevelWindow* const w)
  62966. {
  62967. startTimer (10);
  62968. if (currentActive == w)
  62969. currentActive = 0;
  62970. windows.removeValue (w);
  62971. if (windows.size() == 0)
  62972. deleteInstance();
  62973. }
  62974. VoidArray windows;
  62975. private:
  62976. TopLevelWindow* currentActive;
  62977. bool isWindowActive (TopLevelWindow* const tlw) const
  62978. {
  62979. return (tlw == currentActive
  62980. || tlw->isParentOf (currentActive)
  62981. || tlw->hasKeyboardFocus (true))
  62982. && tlw->isShowing();
  62983. }
  62984. TopLevelWindowManager (const TopLevelWindowManager&);
  62985. TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  62986. };
  62987. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  62988. void juce_CheckCurrentlyFocusedTopLevelWindow()
  62989. {
  62990. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  62991. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  62992. }
  62993. TopLevelWindow::TopLevelWindow (const String& name,
  62994. const bool addToDesktop_)
  62995. : Component (name),
  62996. useDropShadow (true),
  62997. useNativeTitleBar (false),
  62998. windowIsActive_ (false)
  62999. {
  63000. setOpaque (true);
  63001. if (addToDesktop_)
  63002. Component::addToDesktop (getDesktopWindowStyleFlags());
  63003. else
  63004. setDropShadowEnabled (true);
  63005. setWantsKeyboardFocus (true);
  63006. setBroughtToFrontOnMouseClick (true);
  63007. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  63008. }
  63009. TopLevelWindow::~TopLevelWindow()
  63010. {
  63011. shadower = 0;
  63012. TopLevelWindowManager::getInstance()->removeWindow (this);
  63013. }
  63014. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  63015. {
  63016. if (hasKeyboardFocus (true))
  63017. TopLevelWindowManager::getInstance()->timerCallback();
  63018. else
  63019. TopLevelWindowManager::getInstance()->startTimer (10);
  63020. }
  63021. void TopLevelWindow::setWindowActive (const bool isNowActive)
  63022. {
  63023. if (windowIsActive_ != isNowActive)
  63024. {
  63025. windowIsActive_ = isNowActive;
  63026. activeWindowStatusChanged();
  63027. }
  63028. }
  63029. void TopLevelWindow::activeWindowStatusChanged()
  63030. {
  63031. }
  63032. void TopLevelWindow::parentHierarchyChanged()
  63033. {
  63034. setDropShadowEnabled (useDropShadow);
  63035. }
  63036. void TopLevelWindow::visibilityChanged()
  63037. {
  63038. if (isShowing())
  63039. toFront (true);
  63040. }
  63041. int TopLevelWindow::getDesktopWindowStyleFlags() const
  63042. {
  63043. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  63044. if (useDropShadow)
  63045. styleFlags |= ComponentPeer::windowHasDropShadow;
  63046. if (useNativeTitleBar)
  63047. styleFlags |= ComponentPeer::windowHasTitleBar;
  63048. return styleFlags;
  63049. }
  63050. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  63051. {
  63052. useDropShadow = useShadow;
  63053. if (isOnDesktop())
  63054. {
  63055. shadower = 0;
  63056. Component::addToDesktop (getDesktopWindowStyleFlags());
  63057. }
  63058. else
  63059. {
  63060. if (useShadow && isOpaque())
  63061. {
  63062. if (shadower == 0)
  63063. {
  63064. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  63065. if (shadower != 0)
  63066. shadower->setOwner (this);
  63067. }
  63068. }
  63069. else
  63070. {
  63071. shadower = 0;
  63072. }
  63073. }
  63074. }
  63075. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  63076. {
  63077. if (useNativeTitleBar != useNativeTitleBar_)
  63078. {
  63079. useNativeTitleBar = useNativeTitleBar_;
  63080. recreateDesktopWindow();
  63081. sendLookAndFeelChange();
  63082. }
  63083. }
  63084. void TopLevelWindow::recreateDesktopWindow()
  63085. {
  63086. if (isOnDesktop())
  63087. {
  63088. Component::addToDesktop (getDesktopWindowStyleFlags());
  63089. toFront (true);
  63090. }
  63091. }
  63092. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  63093. {
  63094. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  63095. because this class needs to make sure its layout corresponds with settings like whether
  63096. it's got a native title bar or not.
  63097. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  63098. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  63099. method, then add or remove whatever flags are necessary from this value before returning it.
  63100. */
  63101. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  63102. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  63103. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  63104. if (windowStyleFlags != getDesktopWindowStyleFlags())
  63105. sendLookAndFeelChange();
  63106. }
  63107. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  63108. {
  63109. if (c == 0)
  63110. c = TopLevelWindow::getActiveTopLevelWindow();
  63111. if (c == 0)
  63112. {
  63113. centreWithSize (width, height);
  63114. }
  63115. else
  63116. {
  63117. Point<int> p (c->relativePositionToGlobal (Point<int> ((c->getWidth() - width) / 2,
  63118. (c->getHeight() - height) / 2)));
  63119. Rectangle<int> parentArea (c->getParentMonitorArea());
  63120. if (getParentComponent() != 0)
  63121. {
  63122. p = getParentComponent()->globalPositionToRelative (p);
  63123. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  63124. }
  63125. parentArea.reduce (12, 12);
  63126. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), p.getX()),
  63127. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), p.getY()),
  63128. width, height);
  63129. }
  63130. }
  63131. int TopLevelWindow::getNumTopLevelWindows() throw()
  63132. {
  63133. return TopLevelWindowManager::getInstance()->windows.size();
  63134. }
  63135. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  63136. {
  63137. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  63138. }
  63139. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  63140. {
  63141. TopLevelWindow* best = 0;
  63142. int bestNumTWLParents = -1;
  63143. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  63144. {
  63145. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  63146. if (tlw->isActiveWindow())
  63147. {
  63148. int numTWLParents = 0;
  63149. const Component* c = tlw->getParentComponent();
  63150. while (c != 0)
  63151. {
  63152. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  63153. ++numTWLParents;
  63154. c = c->getParentComponent();
  63155. }
  63156. if (bestNumTWLParents < numTWLParents)
  63157. {
  63158. best = tlw;
  63159. bestNumTWLParents = numTWLParents;
  63160. }
  63161. }
  63162. }
  63163. return best;
  63164. }
  63165. END_JUCE_NAMESPACE
  63166. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  63167. #endif
  63168. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  63169. /*** Start of inlined file: juce_Colour.cpp ***/
  63170. BEGIN_JUCE_NAMESPACE
  63171. namespace ColourHelpers
  63172. {
  63173. static uint8 floatAlphaToInt (const float alpha) throw()
  63174. {
  63175. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  63176. }
  63177. static void convertHSBtoRGB (float h, float s, float v,
  63178. uint8& r, uint8& g, uint8& b) throw()
  63179. {
  63180. v = jlimit (0.0f, 1.0f, v);
  63181. v *= 255.0f;
  63182. const uint8 intV = (uint8) roundToInt (v);
  63183. if (s <= 0)
  63184. {
  63185. r = intV;
  63186. g = intV;
  63187. b = intV;
  63188. }
  63189. else
  63190. {
  63191. s = jmin (1.0f, s);
  63192. h = jlimit (0.0f, 1.0f, h);
  63193. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  63194. const float f = h - std::floor (h);
  63195. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  63196. const float y = v * (1.0f - s * f);
  63197. const float z = v * (1.0f - (s * (1.0f - f)));
  63198. if (h < 1.0f)
  63199. {
  63200. r = intV;
  63201. g = (uint8) roundToInt (z);
  63202. b = x;
  63203. }
  63204. else if (h < 2.0f)
  63205. {
  63206. r = (uint8) roundToInt (y);
  63207. g = intV;
  63208. b = x;
  63209. }
  63210. else if (h < 3.0f)
  63211. {
  63212. r = x;
  63213. g = intV;
  63214. b = (uint8) roundToInt (z);
  63215. }
  63216. else if (h < 4.0f)
  63217. {
  63218. r = x;
  63219. g = (uint8) roundToInt (y);
  63220. b = intV;
  63221. }
  63222. else if (h < 5.0f)
  63223. {
  63224. r = (uint8) roundToInt (z);
  63225. g = x;
  63226. b = intV;
  63227. }
  63228. else if (h < 6.0f)
  63229. {
  63230. r = intV;
  63231. g = x;
  63232. b = (uint8) roundToInt (y);
  63233. }
  63234. else
  63235. {
  63236. r = 0;
  63237. g = 0;
  63238. b = 0;
  63239. }
  63240. }
  63241. }
  63242. }
  63243. Colour::Colour() throw()
  63244. : argb (0)
  63245. {
  63246. }
  63247. Colour::Colour (const Colour& other) throw()
  63248. : argb (other.argb)
  63249. {
  63250. }
  63251. Colour& Colour::operator= (const Colour& other) throw()
  63252. {
  63253. argb = other.argb;
  63254. return *this;
  63255. }
  63256. bool Colour::operator== (const Colour& other) const throw()
  63257. {
  63258. return argb.getARGB() == other.argb.getARGB();
  63259. }
  63260. bool Colour::operator!= (const Colour& other) const throw()
  63261. {
  63262. return argb.getARGB() != other.argb.getARGB();
  63263. }
  63264. Colour::Colour (const uint32 argb_) throw()
  63265. : argb (argb_)
  63266. {
  63267. }
  63268. Colour::Colour (const uint8 red,
  63269. const uint8 green,
  63270. const uint8 blue) throw()
  63271. {
  63272. argb.setARGB (0xff, red, green, blue);
  63273. }
  63274. const Colour Colour::fromRGB (const uint8 red,
  63275. const uint8 green,
  63276. const uint8 blue) throw()
  63277. {
  63278. return Colour (red, green, blue);
  63279. }
  63280. Colour::Colour (const uint8 red,
  63281. const uint8 green,
  63282. const uint8 blue,
  63283. const uint8 alpha) throw()
  63284. {
  63285. argb.setARGB (alpha, red, green, blue);
  63286. }
  63287. const Colour Colour::fromRGBA (const uint8 red,
  63288. const uint8 green,
  63289. const uint8 blue,
  63290. const uint8 alpha) throw()
  63291. {
  63292. return Colour (red, green, blue, alpha);
  63293. }
  63294. Colour::Colour (const uint8 red,
  63295. const uint8 green,
  63296. const uint8 blue,
  63297. const float alpha) throw()
  63298. {
  63299. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  63300. }
  63301. const Colour Colour::fromRGBAFloat (const uint8 red,
  63302. const uint8 green,
  63303. const uint8 blue,
  63304. const float alpha) throw()
  63305. {
  63306. return Colour (red, green, blue, alpha);
  63307. }
  63308. Colour::Colour (const float hue,
  63309. const float saturation,
  63310. const float brightness,
  63311. const float alpha) throw()
  63312. {
  63313. uint8 r = getRed(), g = getGreen(), b = getBlue();
  63314. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  63315. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  63316. }
  63317. const Colour Colour::fromHSV (const float hue,
  63318. const float saturation,
  63319. const float brightness,
  63320. const float alpha) throw()
  63321. {
  63322. return Colour (hue, saturation, brightness, alpha);
  63323. }
  63324. Colour::Colour (const float hue,
  63325. const float saturation,
  63326. const float brightness,
  63327. const uint8 alpha) throw()
  63328. {
  63329. uint8 r = getRed(), g = getGreen(), b = getBlue();
  63330. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  63331. argb.setARGB (alpha, r, g, b);
  63332. }
  63333. Colour::~Colour() throw()
  63334. {
  63335. }
  63336. const PixelARGB Colour::getPixelARGB() const throw()
  63337. {
  63338. PixelARGB p (argb);
  63339. p.premultiply();
  63340. return p;
  63341. }
  63342. uint32 Colour::getARGB() const throw()
  63343. {
  63344. return argb.getARGB();
  63345. }
  63346. bool Colour::isTransparent() const throw()
  63347. {
  63348. return getAlpha() == 0;
  63349. }
  63350. bool Colour::isOpaque() const throw()
  63351. {
  63352. return getAlpha() == 0xff;
  63353. }
  63354. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  63355. {
  63356. PixelARGB newCol (argb);
  63357. newCol.setAlpha (newAlpha);
  63358. return Colour (newCol.getARGB());
  63359. }
  63360. const Colour Colour::withAlpha (const float newAlpha) const throw()
  63361. {
  63362. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  63363. PixelARGB newCol (argb);
  63364. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  63365. return Colour (newCol.getARGB());
  63366. }
  63367. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  63368. {
  63369. jassert (alphaMultiplier >= 0);
  63370. PixelARGB newCol (argb);
  63371. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  63372. return Colour (newCol.getARGB());
  63373. }
  63374. const Colour Colour::overlaidWith (const Colour& src) const throw()
  63375. {
  63376. const int destAlpha = getAlpha();
  63377. if (destAlpha > 0)
  63378. {
  63379. const int invA = 0xff - (int) src.getAlpha();
  63380. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  63381. if (resA > 0)
  63382. {
  63383. const int da = (invA * destAlpha) / resA;
  63384. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  63385. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  63386. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  63387. (uint8) resA);
  63388. }
  63389. return *this;
  63390. }
  63391. else
  63392. {
  63393. return src;
  63394. }
  63395. }
  63396. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  63397. {
  63398. if (proportionOfOther <= 0)
  63399. return *this;
  63400. if (proportionOfOther >= 1.0f)
  63401. return other;
  63402. PixelARGB c1 (getPixelARGB());
  63403. const PixelARGB c2 (other.getPixelARGB());
  63404. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  63405. c1.unpremultiply();
  63406. return Colour (c1.getARGB());
  63407. }
  63408. float Colour::getFloatRed() const throw()
  63409. {
  63410. return getRed() / 255.0f;
  63411. }
  63412. float Colour::getFloatGreen() const throw()
  63413. {
  63414. return getGreen() / 255.0f;
  63415. }
  63416. float Colour::getFloatBlue() const throw()
  63417. {
  63418. return getBlue() / 255.0f;
  63419. }
  63420. float Colour::getFloatAlpha() const throw()
  63421. {
  63422. return getAlpha() / 255.0f;
  63423. }
  63424. void Colour::getHSB (float& h, float& s, float& v) const throw()
  63425. {
  63426. const int r = getRed();
  63427. const int g = getGreen();
  63428. const int b = getBlue();
  63429. const int hi = jmax (r, g, b);
  63430. const int lo = jmin (r, g, b);
  63431. if (hi != 0)
  63432. {
  63433. s = (hi - lo) / (float) hi;
  63434. if (s != 0)
  63435. {
  63436. const float invDiff = 1.0f / (hi - lo);
  63437. const float red = (hi - r) * invDiff;
  63438. const float green = (hi - g) * invDiff;
  63439. const float blue = (hi - b) * invDiff;
  63440. if (r == hi)
  63441. h = blue - green;
  63442. else if (g == hi)
  63443. h = 2.0f + red - blue;
  63444. else
  63445. h = 4.0f + green - red;
  63446. h *= 1.0f / 6.0f;
  63447. if (h < 0)
  63448. ++h;
  63449. }
  63450. else
  63451. {
  63452. h = 0;
  63453. }
  63454. }
  63455. else
  63456. {
  63457. s = 0;
  63458. h = 0;
  63459. }
  63460. v = hi / 255.0f;
  63461. }
  63462. float Colour::getHue() const throw()
  63463. {
  63464. float h, s, b;
  63465. getHSB (h, s, b);
  63466. return h;
  63467. }
  63468. const Colour Colour::withHue (const float hue) const throw()
  63469. {
  63470. float h, s, b;
  63471. getHSB (h, s, b);
  63472. return Colour (hue, s, b, getAlpha());
  63473. }
  63474. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  63475. {
  63476. float h, s, b;
  63477. getHSB (h, s, b);
  63478. h += amountToRotate;
  63479. h -= std::floor (h);
  63480. return Colour (h, s, b, getAlpha());
  63481. }
  63482. float Colour::getSaturation() const throw()
  63483. {
  63484. float h, s, b;
  63485. getHSB (h, s, b);
  63486. return s;
  63487. }
  63488. const Colour Colour::withSaturation (const float saturation) const throw()
  63489. {
  63490. float h, s, b;
  63491. getHSB (h, s, b);
  63492. return Colour (h, saturation, b, getAlpha());
  63493. }
  63494. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  63495. {
  63496. float h, s, b;
  63497. getHSB (h, s, b);
  63498. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  63499. }
  63500. float Colour::getBrightness() const throw()
  63501. {
  63502. float h, s, b;
  63503. getHSB (h, s, b);
  63504. return b;
  63505. }
  63506. const Colour Colour::withBrightness (const float brightness) const throw()
  63507. {
  63508. float h, s, b;
  63509. getHSB (h, s, b);
  63510. return Colour (h, s, brightness, getAlpha());
  63511. }
  63512. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  63513. {
  63514. float h, s, b;
  63515. getHSB (h, s, b);
  63516. b *= amount;
  63517. if (b > 1.0f)
  63518. b = 1.0f;
  63519. return Colour (h, s, b, getAlpha());
  63520. }
  63521. const Colour Colour::brighter (float amount) const throw()
  63522. {
  63523. amount = 1.0f / (1.0f + amount);
  63524. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  63525. (uint8) (255 - (amount * (255 - getGreen()))),
  63526. (uint8) (255 - (amount * (255 - getBlue()))),
  63527. getAlpha());
  63528. }
  63529. const Colour Colour::darker (float amount) const throw()
  63530. {
  63531. amount = 1.0f / (1.0f + amount);
  63532. return Colour ((uint8) (amount * getRed()),
  63533. (uint8) (amount * getGreen()),
  63534. (uint8) (amount * getBlue()),
  63535. getAlpha());
  63536. }
  63537. const Colour Colour::greyLevel (const float brightness) throw()
  63538. {
  63539. const uint8 level
  63540. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  63541. return Colour (level, level, level);
  63542. }
  63543. const Colour Colour::contrasting (const float amount) const throw()
  63544. {
  63545. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  63546. ? Colours::black
  63547. : Colours::white).withAlpha (amount));
  63548. }
  63549. const Colour Colour::contrasting (const Colour& colour1,
  63550. const Colour& colour2) throw()
  63551. {
  63552. const float b1 = colour1.getBrightness();
  63553. const float b2 = colour2.getBrightness();
  63554. float best = 0.0f;
  63555. float bestDist = 0.0f;
  63556. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  63557. {
  63558. const float d1 = std::abs (i - b1);
  63559. const float d2 = std::abs (i - b2);
  63560. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  63561. if (dist > bestDist)
  63562. {
  63563. best = i;
  63564. bestDist = dist;
  63565. }
  63566. }
  63567. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  63568. .withBrightness (best);
  63569. }
  63570. const String Colour::toString() const
  63571. {
  63572. return String::toHexString ((int) argb.getARGB());
  63573. }
  63574. const Colour Colour::fromString (const String& encodedColourString)
  63575. {
  63576. return Colour ((uint32) encodedColourString.getHexValue32());
  63577. }
  63578. const String Colour::toDisplayString (const bool includeAlphaValue) const
  63579. {
  63580. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  63581. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  63582. .toUpperCase();
  63583. }
  63584. END_JUCE_NAMESPACE
  63585. /*** End of inlined file: juce_Colour.cpp ***/
  63586. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  63587. BEGIN_JUCE_NAMESPACE
  63588. ColourGradient::ColourGradient() throw()
  63589. {
  63590. #if JUCE_DEBUG
  63591. x1 = 987654.0f;
  63592. #endif
  63593. }
  63594. ColourGradient::ColourGradient (const Colour& colour1,
  63595. const float x1_,
  63596. const float y1_,
  63597. const Colour& colour2,
  63598. const float x2_,
  63599. const float y2_,
  63600. const bool isRadial_)
  63601. : x1 (x1_),
  63602. y1 (y1_),
  63603. x2 (x2_),
  63604. y2 (y2_),
  63605. isRadial (isRadial_)
  63606. {
  63607. colours.add (0);
  63608. colours.add (colour1.getARGB());
  63609. colours.add (1 << 16);
  63610. colours.add (colour2.getARGB());
  63611. }
  63612. ColourGradient::~ColourGradient()
  63613. {
  63614. }
  63615. void ColourGradient::clearColours()
  63616. {
  63617. colours.clear();
  63618. }
  63619. void ColourGradient::addColour (const double proportionAlongGradient,
  63620. const Colour& colour)
  63621. {
  63622. // must be within the two end-points
  63623. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  63624. const uint32 pos = jlimit (0, 65535, roundToInt (proportionAlongGradient * 65536.0));
  63625. int i;
  63626. for (i = 0; i < colours.size(); i += 2)
  63627. if (colours.getUnchecked(i) > pos)
  63628. break;
  63629. colours.insert (i, pos);
  63630. colours.insert (i + 1, colour.getARGB());
  63631. }
  63632. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  63633. {
  63634. for (int i = 1; i < colours.size(); i += 2)
  63635. {
  63636. const Colour c (colours.getUnchecked(i));
  63637. colours.set (i, c.withMultipliedAlpha (multiplier).getARGB());
  63638. }
  63639. }
  63640. int ColourGradient::getNumColours() const throw()
  63641. {
  63642. return colours.size() >> 1;
  63643. }
  63644. double ColourGradient::getColourPosition (const int index) const throw()
  63645. {
  63646. return jlimit (0.0, 1.0, colours [index << 1] / 65535.0);
  63647. }
  63648. const Colour ColourGradient::getColour (const int index) const throw()
  63649. {
  63650. return Colour (colours [(index << 1) + 1]);
  63651. }
  63652. const Colour ColourGradient::getColourAtPosition (const float position) const throw()
  63653. {
  63654. jassert (colours.getUnchecked (0) == 0); // the first colour specified has to go at position 0
  63655. const int integerPos = jlimit (0, 65535, roundToInt (position * 65536.0f));
  63656. if (integerPos <= 0 || colours.size() <= 2)
  63657. return getColour (0);
  63658. int i = colours.size() - 2;
  63659. while (integerPos < (int) colours.getUnchecked(i))
  63660. i -= 2;
  63661. if (i >= colours.size() - 2)
  63662. return Colour (colours.getUnchecked(i));
  63663. const int pos1 = colours.getUnchecked (i);
  63664. const Colour col1 (colours.getUnchecked (i + 1));
  63665. const int pos2 = colours.getUnchecked (i + 2);
  63666. const Colour col2 (colours.getUnchecked (i + 3));
  63667. return col1.interpolatedWith (col2, (integerPos - pos1) / (float) (pos2 - pos1));
  63668. }
  63669. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  63670. {
  63671. #if JUCE_DEBUG
  63672. // trying to use the object without setting its co-ordinates? Have a careful read of
  63673. // the comments for the constructors.
  63674. jassert (x1 != 987654.0f);
  63675. #endif
  63676. const int numColours = colours.size() >> 1;
  63677. float tx1 = x1, ty1 = y1, tx2 = x2, ty2 = y2;
  63678. transform.transformPoint (tx1, ty1);
  63679. transform.transformPoint (tx2, ty2);
  63680. const double distance = juce_hypot (tx1 - tx2, ty1 - ty2);
  63681. const int numEntries = jlimit (1, (numColours - 1) << 8, 3 * (int) distance);
  63682. lookupTable.malloc (numEntries);
  63683. if (numColours >= 2)
  63684. {
  63685. jassert (colours.getUnchecked (0) == 0); // the first colour specified has to go at position 0
  63686. PixelARGB pix1 (colours.getUnchecked (1));
  63687. pix1.premultiply();
  63688. int index = 0;
  63689. for (int j = 2; j < colours.size(); j += 2)
  63690. {
  63691. const int numToDo = ((colours.getUnchecked (j) * (numEntries - 1)) >> 16) - index;
  63692. PixelARGB pix2 (colours.getUnchecked (j + 1));
  63693. pix2.premultiply();
  63694. for (int i = 0; i < numToDo; ++i)
  63695. {
  63696. jassert (index >= 0 && index < numEntries);
  63697. lookupTable[index] = pix1;
  63698. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  63699. ++index;
  63700. }
  63701. pix1 = pix2;
  63702. }
  63703. while (index < numEntries)
  63704. lookupTable [index++] = pix1;
  63705. }
  63706. else
  63707. {
  63708. jassertfalse // no colours specified!
  63709. }
  63710. return numEntries;
  63711. }
  63712. bool ColourGradient::isOpaque() const throw()
  63713. {
  63714. for (int i = 1; i < colours.size(); i += 2)
  63715. if (PixelARGB (colours.getUnchecked(i)).getAlpha() < 0xff)
  63716. return false;
  63717. return true;
  63718. }
  63719. bool ColourGradient::isInvisible() const throw()
  63720. {
  63721. for (int i = 1; i < colours.size(); i += 2)
  63722. if (PixelARGB (colours.getUnchecked(i)).getAlpha() > 0)
  63723. return false;
  63724. return true;
  63725. }
  63726. END_JUCE_NAMESPACE
  63727. /*** End of inlined file: juce_ColourGradient.cpp ***/
  63728. /*** Start of inlined file: juce_Colours.cpp ***/
  63729. BEGIN_JUCE_NAMESPACE
  63730. const Colour Colours::transparentBlack (0);
  63731. const Colour Colours::transparentWhite (0x00ffffff);
  63732. const Colour Colours::aliceblue (0xfff0f8ff);
  63733. const Colour Colours::antiquewhite (0xfffaebd7);
  63734. const Colour Colours::aqua (0xff00ffff);
  63735. const Colour Colours::aquamarine (0xff7fffd4);
  63736. const Colour Colours::azure (0xfff0ffff);
  63737. const Colour Colours::beige (0xfff5f5dc);
  63738. const Colour Colours::bisque (0xffffe4c4);
  63739. const Colour Colours::black (0xff000000);
  63740. const Colour Colours::blanchedalmond (0xffffebcd);
  63741. const Colour Colours::blue (0xff0000ff);
  63742. const Colour Colours::blueviolet (0xff8a2be2);
  63743. const Colour Colours::brown (0xffa52a2a);
  63744. const Colour Colours::burlywood (0xffdeb887);
  63745. const Colour Colours::cadetblue (0xff5f9ea0);
  63746. const Colour Colours::chartreuse (0xff7fff00);
  63747. const Colour Colours::chocolate (0xffd2691e);
  63748. const Colour Colours::coral (0xffff7f50);
  63749. const Colour Colours::cornflowerblue (0xff6495ed);
  63750. const Colour Colours::cornsilk (0xfffff8dc);
  63751. const Colour Colours::crimson (0xffdc143c);
  63752. const Colour Colours::cyan (0xff00ffff);
  63753. const Colour Colours::darkblue (0xff00008b);
  63754. const Colour Colours::darkcyan (0xff008b8b);
  63755. const Colour Colours::darkgoldenrod (0xffb8860b);
  63756. const Colour Colours::darkgrey (0xff555555);
  63757. const Colour Colours::darkgreen (0xff006400);
  63758. const Colour Colours::darkkhaki (0xffbdb76b);
  63759. const Colour Colours::darkmagenta (0xff8b008b);
  63760. const Colour Colours::darkolivegreen (0xff556b2f);
  63761. const Colour Colours::darkorange (0xffff8c00);
  63762. const Colour Colours::darkorchid (0xff9932cc);
  63763. const Colour Colours::darkred (0xff8b0000);
  63764. const Colour Colours::darksalmon (0xffe9967a);
  63765. const Colour Colours::darkseagreen (0xff8fbc8f);
  63766. const Colour Colours::darkslateblue (0xff483d8b);
  63767. const Colour Colours::darkslategrey (0xff2f4f4f);
  63768. const Colour Colours::darkturquoise (0xff00ced1);
  63769. const Colour Colours::darkviolet (0xff9400d3);
  63770. const Colour Colours::deeppink (0xffff1493);
  63771. const Colour Colours::deepskyblue (0xff00bfff);
  63772. const Colour Colours::dimgrey (0xff696969);
  63773. const Colour Colours::dodgerblue (0xff1e90ff);
  63774. const Colour Colours::firebrick (0xffb22222);
  63775. const Colour Colours::floralwhite (0xfffffaf0);
  63776. const Colour Colours::forestgreen (0xff228b22);
  63777. const Colour Colours::fuchsia (0xffff00ff);
  63778. const Colour Colours::gainsboro (0xffdcdcdc);
  63779. const Colour Colours::gold (0xffffd700);
  63780. const Colour Colours::goldenrod (0xffdaa520);
  63781. const Colour Colours::grey (0xff808080);
  63782. const Colour Colours::green (0xff008000);
  63783. const Colour Colours::greenyellow (0xffadff2f);
  63784. const Colour Colours::honeydew (0xfff0fff0);
  63785. const Colour Colours::hotpink (0xffff69b4);
  63786. const Colour Colours::indianred (0xffcd5c5c);
  63787. const Colour Colours::indigo (0xff4b0082);
  63788. const Colour Colours::ivory (0xfffffff0);
  63789. const Colour Colours::khaki (0xfff0e68c);
  63790. const Colour Colours::lavender (0xffe6e6fa);
  63791. const Colour Colours::lavenderblush (0xfffff0f5);
  63792. const Colour Colours::lemonchiffon (0xfffffacd);
  63793. const Colour Colours::lightblue (0xffadd8e6);
  63794. const Colour Colours::lightcoral (0xfff08080);
  63795. const Colour Colours::lightcyan (0xffe0ffff);
  63796. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  63797. const Colour Colours::lightgreen (0xff90ee90);
  63798. const Colour Colours::lightgrey (0xffd3d3d3);
  63799. const Colour Colours::lightpink (0xffffb6c1);
  63800. const Colour Colours::lightsalmon (0xffffa07a);
  63801. const Colour Colours::lightseagreen (0xff20b2aa);
  63802. const Colour Colours::lightskyblue (0xff87cefa);
  63803. const Colour Colours::lightslategrey (0xff778899);
  63804. const Colour Colours::lightsteelblue (0xffb0c4de);
  63805. const Colour Colours::lightyellow (0xffffffe0);
  63806. const Colour Colours::lime (0xff00ff00);
  63807. const Colour Colours::limegreen (0xff32cd32);
  63808. const Colour Colours::linen (0xfffaf0e6);
  63809. const Colour Colours::magenta (0xffff00ff);
  63810. const Colour Colours::maroon (0xff800000);
  63811. const Colour Colours::mediumaquamarine (0xff66cdaa);
  63812. const Colour Colours::mediumblue (0xff0000cd);
  63813. const Colour Colours::mediumorchid (0xffba55d3);
  63814. const Colour Colours::mediumpurple (0xff9370db);
  63815. const Colour Colours::mediumseagreen (0xff3cb371);
  63816. const Colour Colours::mediumslateblue (0xff7b68ee);
  63817. const Colour Colours::mediumspringgreen (0xff00fa9a);
  63818. const Colour Colours::mediumturquoise (0xff48d1cc);
  63819. const Colour Colours::mediumvioletred (0xffc71585);
  63820. const Colour Colours::midnightblue (0xff191970);
  63821. const Colour Colours::mintcream (0xfff5fffa);
  63822. const Colour Colours::mistyrose (0xffffe4e1);
  63823. const Colour Colours::navajowhite (0xffffdead);
  63824. const Colour Colours::navy (0xff000080);
  63825. const Colour Colours::oldlace (0xfffdf5e6);
  63826. const Colour Colours::olive (0xff808000);
  63827. const Colour Colours::olivedrab (0xff6b8e23);
  63828. const Colour Colours::orange (0xffffa500);
  63829. const Colour Colours::orangered (0xffff4500);
  63830. const Colour Colours::orchid (0xffda70d6);
  63831. const Colour Colours::palegoldenrod (0xffeee8aa);
  63832. const Colour Colours::palegreen (0xff98fb98);
  63833. const Colour Colours::paleturquoise (0xffafeeee);
  63834. const Colour Colours::palevioletred (0xffdb7093);
  63835. const Colour Colours::papayawhip (0xffffefd5);
  63836. const Colour Colours::peachpuff (0xffffdab9);
  63837. const Colour Colours::peru (0xffcd853f);
  63838. const Colour Colours::pink (0xffffc0cb);
  63839. const Colour Colours::plum (0xffdda0dd);
  63840. const Colour Colours::powderblue (0xffb0e0e6);
  63841. const Colour Colours::purple (0xff800080);
  63842. const Colour Colours::red (0xffff0000);
  63843. const Colour Colours::rosybrown (0xffbc8f8f);
  63844. const Colour Colours::royalblue (0xff4169e1);
  63845. const Colour Colours::saddlebrown (0xff8b4513);
  63846. const Colour Colours::salmon (0xfffa8072);
  63847. const Colour Colours::sandybrown (0xfff4a460);
  63848. const Colour Colours::seagreen (0xff2e8b57);
  63849. const Colour Colours::seashell (0xfffff5ee);
  63850. const Colour Colours::sienna (0xffa0522d);
  63851. const Colour Colours::silver (0xffc0c0c0);
  63852. const Colour Colours::skyblue (0xff87ceeb);
  63853. const Colour Colours::slateblue (0xff6a5acd);
  63854. const Colour Colours::slategrey (0xff708090);
  63855. const Colour Colours::snow (0xfffffafa);
  63856. const Colour Colours::springgreen (0xff00ff7f);
  63857. const Colour Colours::steelblue (0xff4682b4);
  63858. const Colour Colours::tan (0xffd2b48c);
  63859. const Colour Colours::teal (0xff008080);
  63860. const Colour Colours::thistle (0xffd8bfd8);
  63861. const Colour Colours::tomato (0xffff6347);
  63862. const Colour Colours::turquoise (0xff40e0d0);
  63863. const Colour Colours::violet (0xffee82ee);
  63864. const Colour Colours::wheat (0xfff5deb3);
  63865. const Colour Colours::white (0xffffffff);
  63866. const Colour Colours::whitesmoke (0xfff5f5f5);
  63867. const Colour Colours::yellow (0xffffff00);
  63868. const Colour Colours::yellowgreen (0xff9acd32);
  63869. const Colour Colours::findColourForName (const String& colourName,
  63870. const Colour& defaultColour)
  63871. {
  63872. static const int presets[] =
  63873. {
  63874. // (first value is the string's hashcode, second is ARGB)
  63875. 0x05978fff, 0xff000000, /* black */
  63876. 0x06bdcc29, 0xffffffff, /* white */
  63877. 0x002e305a, 0xff0000ff, /* blue */
  63878. 0x00308adf, 0xff808080, /* grey */
  63879. 0x05e0cf03, 0xff008000, /* green */
  63880. 0x0001b891, 0xffff0000, /* red */
  63881. 0xd43c6474, 0xffffff00, /* yellow */
  63882. 0x620886da, 0xfff0f8ff, /* aliceblue */
  63883. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  63884. 0x002dcebc, 0xff00ffff, /* aqua */
  63885. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  63886. 0x0590228f, 0xfff0ffff, /* azure */
  63887. 0x05947fe4, 0xfff5f5dc, /* beige */
  63888. 0xad388e35, 0xffffe4c4, /* bisque */
  63889. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  63890. 0x39129959, 0xff8a2be2, /* blueviolet */
  63891. 0x059a8136, 0xffa52a2a, /* brown */
  63892. 0x89cea8f9, 0xffdeb887, /* burlywood */
  63893. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  63894. 0x6b748956, 0xff7fff00, /* chartreuse */
  63895. 0x2903623c, 0xffd2691e, /* chocolate */
  63896. 0x05a74431, 0xffff7f50, /* coral */
  63897. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  63898. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  63899. 0x3d8c4edf, 0xffdc143c, /* crimson */
  63900. 0x002ed323, 0xff00ffff, /* cyan */
  63901. 0x67cc74d0, 0xff00008b, /* darkblue */
  63902. 0x67cd1799, 0xff008b8b, /* darkcyan */
  63903. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  63904. 0x67cecf55, 0xff555555, /* darkgrey */
  63905. 0x920b194d, 0xff006400, /* darkgreen */
  63906. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  63907. 0x5c293873, 0xff8b008b, /* darkmagenta */
  63908. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  63909. 0xbcfd2524, 0xffff8c00, /* darkorange */
  63910. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  63911. 0x55ee0d5b, 0xff8b0000, /* darkred */
  63912. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  63913. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  63914. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  63915. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  63916. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  63917. 0xc8769375, 0xff9400d3, /* darkviolet */
  63918. 0x25832862, 0xffff1493, /* deeppink */
  63919. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  63920. 0x634c8b67, 0xff696969, /* dimgrey */
  63921. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  63922. 0xef19e3cb, 0xffb22222, /* firebrick */
  63923. 0xb852b195, 0xfffffaf0, /* floralwhite */
  63924. 0xd086fd06, 0xff228b22, /* forestgreen */
  63925. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  63926. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  63927. 0x00308060, 0xffffd700, /* gold */
  63928. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  63929. 0xbab8a537, 0xffadff2f, /* greenyellow */
  63930. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  63931. 0x41892743, 0xffff69b4, /* hotpink */
  63932. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  63933. 0xb969fed2, 0xff4b0082, /* indigo */
  63934. 0x05fef6a9, 0xfffffff0, /* ivory */
  63935. 0x06149302, 0xfff0e68c, /* khaki */
  63936. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  63937. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  63938. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  63939. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  63940. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  63941. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  63942. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  63943. 0xf40157ad, 0xff90ee90, /* lightgreen */
  63944. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  63945. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  63946. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  63947. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  63948. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  63949. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  63950. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  63951. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  63952. 0x0032afd5, 0xff00ff00, /* lime */
  63953. 0x607bbc4e, 0xff32cd32, /* limegreen */
  63954. 0x06234efa, 0xfffaf0e6, /* linen */
  63955. 0x316858a9, 0xffff00ff, /* magenta */
  63956. 0xbf8ca470, 0xff800000, /* maroon */
  63957. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  63958. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  63959. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  63960. 0x07556b71, 0xff9370db, /* mediumpurple */
  63961. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  63962. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  63963. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  63964. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  63965. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  63966. 0x168eb32a, 0xff191970, /* midnightblue */
  63967. 0x4306b960, 0xfff5fffa, /* mintcream */
  63968. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  63969. 0xe97218a6, 0xffffdead, /* navajowhite */
  63970. 0x00337bb6, 0xff000080, /* navy */
  63971. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  63972. 0x064ee1db, 0xff808000, /* olive */
  63973. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  63974. 0xc3de262e, 0xffffa500, /* orange */
  63975. 0x58bebba3, 0xffff4500, /* orangered */
  63976. 0xc3def8a3, 0xffda70d6, /* orchid */
  63977. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  63978. 0x3d9dd619, 0xff98fb98, /* palegreen */
  63979. 0x74022737, 0xffafeeee, /* paleturquoise */
  63980. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  63981. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  63982. 0x93e1b776, 0xffffdab9, /* peachpuff */
  63983. 0x003472f8, 0xffcd853f, /* peru */
  63984. 0x00348176, 0xffffc0cb, /* pink */
  63985. 0x00348d94, 0xffdda0dd, /* plum */
  63986. 0xd036be93, 0xffb0e0e6, /* powderblue */
  63987. 0xc5c507bc, 0xff800080, /* purple */
  63988. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  63989. 0xbd9413e1, 0xff4169e1, /* royalblue */
  63990. 0xf456044f, 0xff8b4513, /* saddlebrown */
  63991. 0xc9c6f66e, 0xfffa8072, /* salmon */
  63992. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  63993. 0x34636c14, 0xff2e8b57, /* seagreen */
  63994. 0x3507fb41, 0xfffff5ee, /* seashell */
  63995. 0xca348772, 0xffa0522d, /* sienna */
  63996. 0xca37d30d, 0xffc0c0c0, /* silver */
  63997. 0x80da74fb, 0xff87ceeb, /* skyblue */
  63998. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  63999. 0x44ab37f8, 0xff708090, /* slategrey */
  64000. 0x0035f183, 0xfffffafa, /* snow */
  64001. 0xd5440d16, 0xff00ff7f, /* springgreen */
  64002. 0x3e1524a5, 0xff4682b4, /* steelblue */
  64003. 0x0001bfa1, 0xffd2b48c, /* tan */
  64004. 0x0036425c, 0xff008080, /* teal */
  64005. 0xafc8858f, 0xffd8bfd8, /* thistle */
  64006. 0xcc41600a, 0xffff6347, /* tomato */
  64007. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  64008. 0xcf57947f, 0xffee82ee, /* violet */
  64009. 0x06bdbae7, 0xfff5deb3, /* wheat */
  64010. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  64011. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  64012. };
  64013. const int hash = colourName.trim().toLowerCase().hashCode();
  64014. for (int i = 0; i < numElementsInArray (presets); i += 2)
  64015. if (presets [i] == hash)
  64016. return Colour (presets [i + 1]);
  64017. return defaultColour;
  64018. }
  64019. END_JUCE_NAMESPACE
  64020. /*** End of inlined file: juce_Colours.cpp ***/
  64021. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  64022. BEGIN_JUCE_NAMESPACE
  64023. const int juce_edgeTableDefaultEdgesPerLine = 32;
  64024. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  64025. const Path& path, const AffineTransform& transform)
  64026. : bounds (bounds_),
  64027. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64028. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64029. needToCheckEmptinesss (true)
  64030. {
  64031. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  64032. int* t = table;
  64033. for (int i = bounds.getHeight(); --i >= 0;)
  64034. {
  64035. *t = 0;
  64036. t += lineStrideElements;
  64037. }
  64038. const int topLimit = bounds.getY() << 8;
  64039. const int heightLimit = bounds.getHeight() << 8;
  64040. const int leftLimit = bounds.getX() << 8;
  64041. const int rightLimit = bounds.getRight() << 8;
  64042. PathFlatteningIterator iter (path, transform);
  64043. while (iter.next())
  64044. {
  64045. int y1 = roundToInt (iter.y1 * 256.0f);
  64046. int y2 = roundToInt (iter.y2 * 256.0f);
  64047. if (y1 != y2)
  64048. {
  64049. y1 -= topLimit;
  64050. y2 -= topLimit;
  64051. const int startY = y1;
  64052. int direction = -1;
  64053. if (y1 > y2)
  64054. {
  64055. swapVariables (y1, y2);
  64056. direction = 1;
  64057. }
  64058. if (y1 < 0)
  64059. y1 = 0;
  64060. if (y2 > heightLimit)
  64061. y2 = heightLimit;
  64062. if (y1 < y2)
  64063. {
  64064. const double startX = 256.0f * iter.x1;
  64065. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  64066. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  64067. do
  64068. {
  64069. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  64070. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  64071. if (x < leftLimit)
  64072. x = leftLimit;
  64073. else if (x >= rightLimit)
  64074. x = rightLimit - 1;
  64075. addEdgePoint (x, y1 >> 8, direction * step);
  64076. y1 += step;
  64077. }
  64078. while (y1 < y2);
  64079. }
  64080. }
  64081. }
  64082. sanitiseLevels (path.isUsingNonZeroWinding());
  64083. }
  64084. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  64085. : bounds (rectangleToAdd),
  64086. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64087. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64088. needToCheckEmptinesss (true)
  64089. {
  64090. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64091. table[0] = 0;
  64092. const int x1 = rectangleToAdd.getX() << 8;
  64093. const int x2 = rectangleToAdd.getRight() << 8;
  64094. int* t = table;
  64095. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  64096. {
  64097. t[0] = 2;
  64098. t[1] = x1;
  64099. t[2] = 255;
  64100. t[3] = x2;
  64101. t[4] = 0;
  64102. t += lineStrideElements;
  64103. }
  64104. }
  64105. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  64106. : bounds (rectanglesToAdd.getBounds()),
  64107. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64108. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64109. needToCheckEmptinesss (true)
  64110. {
  64111. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64112. int* t = table;
  64113. for (int i = bounds.getHeight(); --i >= 0;)
  64114. {
  64115. *t = 0;
  64116. t += lineStrideElements;
  64117. }
  64118. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  64119. {
  64120. const Rectangle<int>* const r = iter.getRectangle();
  64121. const int x1 = r->getX() << 8;
  64122. const int x2 = r->getRight() << 8;
  64123. int y = r->getY() - bounds.getY();
  64124. for (int j = r->getHeight(); --j >= 0;)
  64125. {
  64126. addEdgePoint (x1, y, 255);
  64127. addEdgePoint (x2, y, -255);
  64128. ++y;
  64129. }
  64130. }
  64131. sanitiseLevels (true);
  64132. }
  64133. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  64134. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  64135. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  64136. 2 + (int) rectangleToAdd.getWidth(),
  64137. 2 + (int) rectangleToAdd.getHeight())),
  64138. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64139. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64140. needToCheckEmptinesss (true)
  64141. {
  64142. jassert (! rectangleToAdd.isEmpty());
  64143. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64144. table[0] = 0;
  64145. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  64146. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  64147. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  64148. jassert (y1 < 256);
  64149. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  64150. if (x2 <= x1 || y2 <= y1)
  64151. {
  64152. bounds.setHeight (0);
  64153. return;
  64154. }
  64155. int lineY = 0;
  64156. int* t = table;
  64157. if ((y1 >> 8) == (y2 >> 8))
  64158. {
  64159. t[0] = 2;
  64160. t[1] = x1;
  64161. t[2] = y2 - y1;
  64162. t[3] = x2;
  64163. t[4] = 0;
  64164. ++lineY;
  64165. t += lineStrideElements;
  64166. }
  64167. else
  64168. {
  64169. t[0] = 2;
  64170. t[1] = x1;
  64171. t[2] = 255 - (y1 & 255);
  64172. t[3] = x2;
  64173. t[4] = 0;
  64174. ++lineY;
  64175. t += lineStrideElements;
  64176. while (lineY < (y2 >> 8))
  64177. {
  64178. t[0] = 2;
  64179. t[1] = x1;
  64180. t[2] = 255;
  64181. t[3] = x2;
  64182. t[4] = 0;
  64183. ++lineY;
  64184. t += lineStrideElements;
  64185. }
  64186. jassert (lineY < bounds.getHeight());
  64187. t[0] = 2;
  64188. t[1] = x1;
  64189. t[2] = y2 & 255;
  64190. t[3] = x2;
  64191. t[4] = 0;
  64192. ++lineY;
  64193. t += lineStrideElements;
  64194. }
  64195. while (lineY < bounds.getHeight())
  64196. {
  64197. t[0] = 0;
  64198. t += lineStrideElements;
  64199. ++lineY;
  64200. }
  64201. }
  64202. EdgeTable::EdgeTable (const EdgeTable& other)
  64203. {
  64204. operator= (other);
  64205. }
  64206. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  64207. {
  64208. bounds = other.bounds;
  64209. maxEdgesPerLine = other.maxEdgesPerLine;
  64210. lineStrideElements = other.lineStrideElements;
  64211. needToCheckEmptinesss = other.needToCheckEmptinesss;
  64212. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64213. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  64214. return *this;
  64215. }
  64216. EdgeTable::~EdgeTable()
  64217. {
  64218. }
  64219. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  64220. {
  64221. while (--numLines >= 0)
  64222. {
  64223. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  64224. src += srcLineStride;
  64225. dest += destLineStride;
  64226. }
  64227. }
  64228. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  64229. {
  64230. // Convert the table from relative windings to absolute levels..
  64231. int* lineStart = table;
  64232. for (int i = bounds.getHeight(); --i >= 0;)
  64233. {
  64234. int* line = lineStart;
  64235. lineStart += lineStrideElements;
  64236. int num = *line;
  64237. if (num == 0)
  64238. continue;
  64239. int level = 0;
  64240. if (useNonZeroWinding)
  64241. {
  64242. while (--num > 0)
  64243. {
  64244. line += 2;
  64245. level += *line;
  64246. int corrected = abs (level);
  64247. if (corrected >> 8)
  64248. corrected = 255;
  64249. *line = corrected;
  64250. }
  64251. }
  64252. else
  64253. {
  64254. while (--num > 0)
  64255. {
  64256. line += 2;
  64257. level += *line;
  64258. int corrected = abs (level);
  64259. if (corrected >> 8)
  64260. {
  64261. corrected &= 511;
  64262. if (corrected >> 8)
  64263. corrected = 511 - corrected;
  64264. }
  64265. *line = corrected;
  64266. }
  64267. }
  64268. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  64269. }
  64270. }
  64271. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  64272. {
  64273. if (newNumEdgesPerLine != maxEdgesPerLine)
  64274. {
  64275. maxEdgesPerLine = newNumEdgesPerLine;
  64276. jassert (bounds.getHeight() > 0);
  64277. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  64278. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  64279. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  64280. table.swapWith (newTable);
  64281. lineStrideElements = newLineStrideElements;
  64282. }
  64283. }
  64284. void EdgeTable::optimiseTable() throw()
  64285. {
  64286. int maxLineElements = 0;
  64287. for (int i = bounds.getHeight(); --i >= 0;)
  64288. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  64289. remapTableForNumEdges (maxLineElements);
  64290. }
  64291. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  64292. {
  64293. jassert (y >= 0 && y < bounds.getHeight());
  64294. int* line = table + lineStrideElements * y;
  64295. const int numPoints = line[0];
  64296. int n = numPoints << 1;
  64297. if (n > 0)
  64298. {
  64299. while (n > 0)
  64300. {
  64301. const int cx = line [n - 1];
  64302. if (cx <= x)
  64303. {
  64304. if (cx == x)
  64305. {
  64306. line [n] += winding;
  64307. return;
  64308. }
  64309. break;
  64310. }
  64311. n -= 2;
  64312. }
  64313. if (numPoints >= maxEdgesPerLine)
  64314. {
  64315. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  64316. jassert (numPoints < maxEdgesPerLine);
  64317. line = table + lineStrideElements * y;
  64318. }
  64319. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  64320. }
  64321. line [n + 1] = x;
  64322. line [n + 2] = winding;
  64323. line[0]++;
  64324. }
  64325. void EdgeTable::translate (float dx, const int dy) throw()
  64326. {
  64327. bounds.translate ((int) std::floor (dx), dy);
  64328. int* lineStart = table;
  64329. const int intDx = (int) (dx * 256.0f);
  64330. for (int i = bounds.getHeight(); --i >= 0;)
  64331. {
  64332. int* line = lineStart;
  64333. lineStart += lineStrideElements;
  64334. int num = *line++;
  64335. while (--num >= 0)
  64336. {
  64337. *line += intDx;
  64338. line += 2;
  64339. }
  64340. }
  64341. }
  64342. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine) throw()
  64343. {
  64344. jassert (y >= 0 && y < bounds.getHeight());
  64345. int* dest = table + lineStrideElements * y;
  64346. if (dest[0] == 0)
  64347. return;
  64348. int otherNumPoints = *otherLine;
  64349. if (otherNumPoints == 0)
  64350. {
  64351. *dest = 0;
  64352. return;
  64353. }
  64354. const int right = bounds.getRight() << 8;
  64355. // optimise for the common case where our line lies entirely within a
  64356. // single pair of points, as happens when clipping to a simple rect.
  64357. if (otherNumPoints == 2 && otherLine[2] >= 255)
  64358. {
  64359. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  64360. return;
  64361. }
  64362. ++otherLine;
  64363. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  64364. int* temp = (int*) alloca (lineSizeBytes);
  64365. memcpy (temp, dest, lineSizeBytes);
  64366. const int* src1 = temp;
  64367. int srcNum1 = *src1++;
  64368. int x1 = *src1++;
  64369. const int* src2 = otherLine;
  64370. int srcNum2 = otherNumPoints;
  64371. int x2 = *src2++;
  64372. int destIndex = 0, destTotal = 0;
  64373. int level1 = 0, level2 = 0;
  64374. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  64375. while (srcNum1 > 0 && srcNum2 > 0)
  64376. {
  64377. int nextX;
  64378. if (x1 < x2)
  64379. {
  64380. nextX = x1;
  64381. level1 = *src1++;
  64382. x1 = *src1++;
  64383. --srcNum1;
  64384. }
  64385. else if (x1 == x2)
  64386. {
  64387. nextX = x1;
  64388. level1 = *src1++;
  64389. level2 = *src2++;
  64390. x1 = *src1++;
  64391. x2 = *src2++;
  64392. --srcNum1;
  64393. --srcNum2;
  64394. }
  64395. else
  64396. {
  64397. nextX = x2;
  64398. level2 = *src2++;
  64399. x2 = *src2++;
  64400. --srcNum2;
  64401. }
  64402. if (nextX > lastX)
  64403. {
  64404. if (nextX >= right)
  64405. break;
  64406. lastX = nextX;
  64407. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  64408. jassert (((unsigned int) nextLevel) < (unsigned int) 256);
  64409. if (nextLevel != lastLevel)
  64410. {
  64411. if (destTotal >= maxEdgesPerLine)
  64412. {
  64413. dest[0] = destTotal;
  64414. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  64415. dest = table + lineStrideElements * y;
  64416. }
  64417. ++destTotal;
  64418. lastLevel = nextLevel;
  64419. dest[++destIndex] = nextX;
  64420. dest[++destIndex] = nextLevel;
  64421. }
  64422. }
  64423. }
  64424. if (lastLevel > 0)
  64425. {
  64426. if (destTotal >= maxEdgesPerLine)
  64427. {
  64428. dest[0] = destTotal;
  64429. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  64430. dest = table + lineStrideElements * y;
  64431. }
  64432. ++destTotal;
  64433. dest[++destIndex] = right;
  64434. dest[++destIndex] = 0;
  64435. }
  64436. dest[0] = destTotal;
  64437. #if JUCE_DEBUG
  64438. int last = std::numeric_limits<int>::min();
  64439. for (int i = 0; i < dest[0]; ++i)
  64440. {
  64441. jassert (dest[i * 2 + 1] > last);
  64442. last = dest[i * 2 + 1];
  64443. }
  64444. jassert (dest [dest[0] * 2] == 0);
  64445. #endif
  64446. }
  64447. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  64448. {
  64449. int* lastItem = dest + (dest[0] * 2 - 1);
  64450. if (x2 < lastItem[0])
  64451. {
  64452. if (x2 <= dest[1])
  64453. {
  64454. dest[0] = 0;
  64455. return;
  64456. }
  64457. while (x2 < lastItem[-2])
  64458. {
  64459. --(dest[0]);
  64460. lastItem -= 2;
  64461. }
  64462. lastItem[0] = x2;
  64463. lastItem[1] = 0;
  64464. }
  64465. if (x1 > dest[1])
  64466. {
  64467. while (lastItem[0] > x1)
  64468. lastItem -= 2;
  64469. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  64470. if (itemsRemoved > 0)
  64471. {
  64472. dest[0] -= itemsRemoved;
  64473. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  64474. }
  64475. dest[1] = x1;
  64476. }
  64477. }
  64478. void EdgeTable::clipToRectangle (const Rectangle<int>& r) throw()
  64479. {
  64480. const Rectangle<int> clipped (r.getIntersection (bounds));
  64481. if (clipped.isEmpty())
  64482. {
  64483. needToCheckEmptinesss = false;
  64484. bounds.setHeight (0);
  64485. }
  64486. else
  64487. {
  64488. const int top = clipped.getY() - bounds.getY();
  64489. const int bottom = clipped.getBottom() - bounds.getY();
  64490. if (bottom < bounds.getHeight())
  64491. bounds.setHeight (bottom);
  64492. if (clipped.getRight() < bounds.getRight())
  64493. bounds.setRight (clipped.getRight());
  64494. for (int i = top; --i >= 0;)
  64495. table [lineStrideElements * i] = 0;
  64496. if (clipped.getX() > bounds.getX())
  64497. {
  64498. const int x1 = clipped.getX() << 8;
  64499. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  64500. int* line = table + lineStrideElements * top;
  64501. for (int i = bottom - top; --i >= 0;)
  64502. {
  64503. if (line[0] != 0)
  64504. clipEdgeTableLineToRange (line, x1, x2);
  64505. line += lineStrideElements;
  64506. }
  64507. }
  64508. needToCheckEmptinesss = true;
  64509. }
  64510. }
  64511. void EdgeTable::excludeRectangle (const Rectangle<int>& r) throw()
  64512. {
  64513. const Rectangle<int> clipped (r.getIntersection (bounds));
  64514. if (! clipped.isEmpty())
  64515. {
  64516. const int top = clipped.getY() - bounds.getY();
  64517. const int bottom = clipped.getBottom() - bounds.getY();
  64518. //XXX optimise here by shortening the table if it fills top or bottom
  64519. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  64520. clipped.getX() << 8, 0,
  64521. clipped.getRight() << 8, 255,
  64522. std::numeric_limits<int>::max(), 0 };
  64523. for (int i = top; i < bottom; ++i)
  64524. intersectWithEdgeTableLine (i, rectLine);
  64525. needToCheckEmptinesss = true;
  64526. }
  64527. }
  64528. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  64529. {
  64530. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  64531. if (clipped.isEmpty())
  64532. {
  64533. needToCheckEmptinesss = false;
  64534. bounds.setHeight (0);
  64535. }
  64536. else
  64537. {
  64538. const int top = clipped.getY() - bounds.getY();
  64539. const int bottom = clipped.getBottom() - bounds.getY();
  64540. if (bottom < bounds.getHeight())
  64541. bounds.setHeight (bottom);
  64542. if (clipped.getRight() < bounds.getRight())
  64543. bounds.setRight (clipped.getRight());
  64544. int i = 0;
  64545. for (i = top; --i >= 0;)
  64546. table [lineStrideElements * i] = 0;
  64547. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  64548. for (i = top; i < bottom; ++i)
  64549. {
  64550. intersectWithEdgeTableLine (i, otherLine);
  64551. otherLine += other.lineStrideElements;
  64552. }
  64553. needToCheckEmptinesss = true;
  64554. }
  64555. }
  64556. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels) throw()
  64557. {
  64558. y -= bounds.getY();
  64559. if (y < 0 || y >= bounds.getHeight())
  64560. return;
  64561. needToCheckEmptinesss = true;
  64562. if (numPixels <= 0)
  64563. {
  64564. table [lineStrideElements * y] = 0;
  64565. return;
  64566. }
  64567. int* tempLine = (int*) alloca ((numPixels * 2 + 4) * sizeof (int));
  64568. int destIndex = 0, lastLevel = 0;
  64569. while (--numPixels >= 0)
  64570. {
  64571. const int alpha = *mask;
  64572. mask += maskStride;
  64573. if (alpha != lastLevel)
  64574. {
  64575. tempLine[++destIndex] = (x << 8);
  64576. tempLine[++destIndex] = alpha;
  64577. lastLevel = alpha;
  64578. }
  64579. ++x;
  64580. }
  64581. if (lastLevel > 0)
  64582. {
  64583. tempLine[++destIndex] = (x << 8);
  64584. tempLine[++destIndex] = 0;
  64585. }
  64586. tempLine[0] = destIndex >> 1;
  64587. intersectWithEdgeTableLine (y, tempLine);
  64588. }
  64589. bool EdgeTable::isEmpty() throw()
  64590. {
  64591. if (needToCheckEmptinesss)
  64592. {
  64593. needToCheckEmptinesss = false;
  64594. int* t = table;
  64595. for (int i = bounds.getHeight(); --i >= 0;)
  64596. {
  64597. if (t[0] > 1)
  64598. return false;
  64599. t += lineStrideElements;
  64600. }
  64601. bounds.setHeight (0);
  64602. }
  64603. return bounds.getHeight() == 0;
  64604. }
  64605. END_JUCE_NAMESPACE
  64606. /*** End of inlined file: juce_EdgeTable.cpp ***/
  64607. /*** Start of inlined file: juce_FillType.cpp ***/
  64608. BEGIN_JUCE_NAMESPACE
  64609. FillType::FillType() throw()
  64610. : colour (0xff000000), image (0)
  64611. {
  64612. }
  64613. FillType::FillType (const Colour& colour_) throw()
  64614. : colour (colour_), image (0)
  64615. {
  64616. }
  64617. FillType::FillType (const ColourGradient& gradient_)
  64618. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  64619. {
  64620. }
  64621. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  64622. : colour (0xff000000), image (&image_), transform (transform_)
  64623. {
  64624. }
  64625. FillType::FillType (const FillType& other)
  64626. : colour (other.colour),
  64627. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  64628. image (other.image), transform (other.transform)
  64629. {
  64630. }
  64631. FillType& FillType::operator= (const FillType& other)
  64632. {
  64633. if (this != &other)
  64634. {
  64635. colour = other.colour;
  64636. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  64637. image = other.image;
  64638. transform = other.transform;
  64639. }
  64640. return *this;
  64641. }
  64642. FillType::~FillType() throw()
  64643. {
  64644. }
  64645. void FillType::setColour (const Colour& newColour) throw()
  64646. {
  64647. gradient = 0;
  64648. image = 0;
  64649. colour = newColour;
  64650. }
  64651. void FillType::setGradient (const ColourGradient& newGradient)
  64652. {
  64653. if (gradient != 0)
  64654. {
  64655. *gradient = newGradient;
  64656. }
  64657. else
  64658. {
  64659. image = 0;
  64660. gradient = new ColourGradient (newGradient);
  64661. colour = Colours::black;
  64662. }
  64663. }
  64664. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  64665. {
  64666. gradient = 0;
  64667. image = &image_;
  64668. transform = transform_;
  64669. colour = Colours::black;
  64670. }
  64671. void FillType::setOpacity (const float newOpacity) throw()
  64672. {
  64673. colour = colour.withAlpha (newOpacity);
  64674. }
  64675. END_JUCE_NAMESPACE
  64676. /*** End of inlined file: juce_FillType.cpp ***/
  64677. /*** Start of inlined file: juce_Graphics.cpp ***/
  64678. BEGIN_JUCE_NAMESPACE
  64679. static const Graphics::ResamplingQuality defaultQuality = Graphics::mediumResamplingQuality;
  64680. template <typename Type>
  64681. static bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  64682. {
  64683. const int maxVal = 0x3fffffff;
  64684. return (int) x >= -maxVal && (int) x <= maxVal
  64685. && (int) y >= -maxVal && (int) y <= maxVal
  64686. && (int) w >= -maxVal && (int) w <= maxVal
  64687. && (int) h >= -maxVal && (int) h <= maxVal;
  64688. }
  64689. LowLevelGraphicsContext::LowLevelGraphicsContext()
  64690. {
  64691. }
  64692. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  64693. {
  64694. }
  64695. Graphics::Graphics (Image& imageToDrawOnto)
  64696. : context (imageToDrawOnto.createLowLevelContext()),
  64697. contextToDelete (context),
  64698. saveStatePending (false)
  64699. {
  64700. }
  64701. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  64702. : context (internalContext),
  64703. saveStatePending (false)
  64704. {
  64705. }
  64706. Graphics::~Graphics()
  64707. {
  64708. }
  64709. void Graphics::resetToDefaultState()
  64710. {
  64711. saveStateIfPending();
  64712. context->setFill (FillType());
  64713. context->setFont (Font());
  64714. context->setInterpolationQuality (defaultQuality);
  64715. }
  64716. bool Graphics::isVectorDevice() const
  64717. {
  64718. return context->isVectorDevice();
  64719. }
  64720. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  64721. {
  64722. saveStateIfPending();
  64723. return context->clipToRectangle (Rectangle<int> (x, y, w, h));
  64724. }
  64725. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  64726. {
  64727. saveStateIfPending();
  64728. return context->clipToRectangleList (clipRegion);
  64729. }
  64730. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  64731. {
  64732. saveStateIfPending();
  64733. context->clipToPath (path, transform);
  64734. return ! context->isClipEmpty();
  64735. }
  64736. bool Graphics::reduceClipRegion (const Image& image, const Rectangle<int>& sourceClipRegion, const AffineTransform& transform)
  64737. {
  64738. saveStateIfPending();
  64739. context->clipToImageAlpha (image, sourceClipRegion, transform);
  64740. return ! context->isClipEmpty();
  64741. }
  64742. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  64743. {
  64744. saveStateIfPending();
  64745. context->excludeClipRectangle (rectangleToExclude);
  64746. }
  64747. bool Graphics::isClipEmpty() const
  64748. {
  64749. return context->isClipEmpty();
  64750. }
  64751. const Rectangle<int> Graphics::getClipBounds() const
  64752. {
  64753. return context->getClipBounds();
  64754. }
  64755. void Graphics::saveState()
  64756. {
  64757. saveStateIfPending();
  64758. saveStatePending = true;
  64759. }
  64760. void Graphics::restoreState()
  64761. {
  64762. if (saveStatePending)
  64763. saveStatePending = false;
  64764. else
  64765. context->restoreState();
  64766. }
  64767. void Graphics::saveStateIfPending()
  64768. {
  64769. if (saveStatePending)
  64770. {
  64771. saveStatePending = false;
  64772. context->saveState();
  64773. }
  64774. }
  64775. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  64776. {
  64777. saveStateIfPending();
  64778. context->setOrigin (newOriginX, newOriginY);
  64779. }
  64780. bool Graphics::clipRegionIntersects (const int x, const int y, const int w, const int h) const
  64781. {
  64782. return context->clipRegionIntersects (Rectangle<int> (x, y, w, h));
  64783. }
  64784. void Graphics::setColour (const Colour& newColour)
  64785. {
  64786. saveStateIfPending();
  64787. context->setFill (newColour);
  64788. }
  64789. void Graphics::setOpacity (const float newOpacity)
  64790. {
  64791. saveStateIfPending();
  64792. context->setOpacity (newOpacity);
  64793. }
  64794. void Graphics::setGradientFill (const ColourGradient& gradient)
  64795. {
  64796. setFillType (gradient);
  64797. }
  64798. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  64799. {
  64800. saveStateIfPending();
  64801. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  64802. context->setOpacity (opacity);
  64803. }
  64804. void Graphics::setFillType (const FillType& newFill)
  64805. {
  64806. saveStateIfPending();
  64807. context->setFill (newFill);
  64808. }
  64809. void Graphics::setFont (const Font& newFont)
  64810. {
  64811. saveStateIfPending();
  64812. context->setFont (newFont);
  64813. }
  64814. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  64815. {
  64816. saveStateIfPending();
  64817. Font f (context->getFont());
  64818. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  64819. context->setFont (f);
  64820. }
  64821. const Font Graphics::getCurrentFont() const
  64822. {
  64823. return context->getFont();
  64824. }
  64825. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  64826. {
  64827. if (text.isNotEmpty()
  64828. && startX < context->getClipBounds().getRight())
  64829. {
  64830. GlyphArrangement arr;
  64831. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  64832. arr.draw (*this);
  64833. }
  64834. }
  64835. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  64836. {
  64837. if (text.isNotEmpty())
  64838. {
  64839. GlyphArrangement arr;
  64840. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  64841. arr.draw (*this, transform);
  64842. }
  64843. }
  64844. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  64845. {
  64846. if (text.isNotEmpty()
  64847. && startX < context->getClipBounds().getRight())
  64848. {
  64849. GlyphArrangement arr;
  64850. arr.addJustifiedText (context->getFont(), text,
  64851. (float) startX, (float) baselineY, (float) maximumLineWidth,
  64852. Justification::left);
  64853. arr.draw (*this);
  64854. }
  64855. }
  64856. void Graphics::drawText (const String& text,
  64857. const int x, const int y, const int width, const int height,
  64858. const Justification& justificationType,
  64859. const bool useEllipsesIfTooBig) const
  64860. {
  64861. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  64862. {
  64863. GlyphArrangement arr;
  64864. arr.addCurtailedLineOfText (context->getFont(), text,
  64865. 0.0f, 0.0f, (float) width,
  64866. useEllipsesIfTooBig);
  64867. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  64868. (float) x, (float) y, (float) width, (float) height,
  64869. justificationType);
  64870. arr.draw (*this);
  64871. }
  64872. }
  64873. void Graphics::drawFittedText (const String& text,
  64874. const int x, const int y, const int width, const int height,
  64875. const Justification& justification,
  64876. const int maximumNumberOfLines,
  64877. const float minimumHorizontalScale) const
  64878. {
  64879. if (text.isNotEmpty()
  64880. && width > 0 && height > 0
  64881. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  64882. {
  64883. GlyphArrangement arr;
  64884. arr.addFittedText (context->getFont(), text,
  64885. (float) x, (float) y, (float) width, (float) height,
  64886. justification,
  64887. maximumNumberOfLines,
  64888. minimumHorizontalScale);
  64889. arr.draw (*this);
  64890. }
  64891. }
  64892. void Graphics::fillRect (int x, int y, int width, int height) const
  64893. {
  64894. // passing in a silly number can cause maths problems in rendering!
  64895. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64896. context->fillRect (Rectangle<int> (x, y, width, height), false);
  64897. }
  64898. void Graphics::fillRect (const Rectangle<int>& r) const
  64899. {
  64900. context->fillRect (r, false);
  64901. }
  64902. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  64903. {
  64904. // passing in a silly number can cause maths problems in rendering!
  64905. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64906. Path p;
  64907. p.addRectangle (x, y, width, height);
  64908. fillPath (p);
  64909. }
  64910. void Graphics::setPixel (int x, int y) const
  64911. {
  64912. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  64913. }
  64914. void Graphics::fillAll() const
  64915. {
  64916. fillRect (context->getClipBounds());
  64917. }
  64918. void Graphics::fillAll (const Colour& colourToUse) const
  64919. {
  64920. if (! colourToUse.isTransparent())
  64921. {
  64922. const Rectangle<int> clip (context->getClipBounds());
  64923. context->saveState();
  64924. context->setFill (colourToUse);
  64925. context->fillRect (clip, false);
  64926. context->restoreState();
  64927. }
  64928. }
  64929. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  64930. {
  64931. if ((! context->isClipEmpty()) && ! path.isEmpty())
  64932. context->fillPath (path, transform);
  64933. }
  64934. void Graphics::strokePath (const Path& path,
  64935. const PathStrokeType& strokeType,
  64936. const AffineTransform& transform) const
  64937. {
  64938. Path stroke;
  64939. strokeType.createStrokedPath (stroke, path, transform);
  64940. fillPath (stroke);
  64941. }
  64942. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  64943. const int lineThickness) const
  64944. {
  64945. // passing in a silly number can cause maths problems in rendering!
  64946. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64947. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  64948. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  64949. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  64950. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  64951. }
  64952. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  64953. {
  64954. // passing in a silly number can cause maths problems in rendering!
  64955. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64956. Path p;
  64957. p.addRectangle (x, y, width, lineThickness);
  64958. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  64959. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  64960. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  64961. fillPath (p);
  64962. }
  64963. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  64964. {
  64965. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  64966. }
  64967. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  64968. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  64969. const bool useGradient, const bool sharpEdgeOnOutside) const
  64970. {
  64971. // passing in a silly number can cause maths problems in rendering!
  64972. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64973. if (clipRegionIntersects (x, y, width, height))
  64974. {
  64975. context->saveState();
  64976. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  64977. const float ramp = oldOpacity / bevelThickness;
  64978. for (int i = bevelThickness; --i >= 0;)
  64979. {
  64980. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  64981. : oldOpacity;
  64982. context->setFill (topLeftColour.withMultipliedAlpha (op));
  64983. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  64984. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  64985. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  64986. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  64987. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  64988. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  64989. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  64990. }
  64991. context->restoreState();
  64992. }
  64993. }
  64994. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  64995. {
  64996. // passing in a silly number can cause maths problems in rendering!
  64997. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64998. Path p;
  64999. p.addEllipse (x, y, width, height);
  65000. fillPath (p);
  65001. }
  65002. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  65003. const float lineThickness) const
  65004. {
  65005. // passing in a silly number can cause maths problems in rendering!
  65006. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65007. Path p;
  65008. p.addEllipse (x, y, width, height);
  65009. strokePath (p, PathStrokeType (lineThickness));
  65010. }
  65011. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  65012. {
  65013. // passing in a silly number can cause maths problems in rendering!
  65014. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65015. Path p;
  65016. p.addRoundedRectangle (x, y, width, height, cornerSize);
  65017. fillPath (p);
  65018. }
  65019. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  65020. {
  65021. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  65022. }
  65023. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  65024. const float cornerSize, const float lineThickness) const
  65025. {
  65026. // passing in a silly number can cause maths problems in rendering!
  65027. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65028. Path p;
  65029. p.addRoundedRectangle (x, y, width, height, cornerSize);
  65030. strokePath (p, PathStrokeType (lineThickness));
  65031. }
  65032. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  65033. {
  65034. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  65035. }
  65036. void Graphics::drawArrow (const float startX, const float startY, const float endX, const float endY,
  65037. const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  65038. {
  65039. Path p;
  65040. p.addArrow (startX, startY, endX, endY,
  65041. lineThickness, arrowheadWidth, arrowheadLength);
  65042. fillPath (p);
  65043. }
  65044. void Graphics::fillCheckerBoard (int x, int y, int width, int height,
  65045. const int checkWidth, const int checkHeight,
  65046. const Colour& colour1, const Colour& colour2) const
  65047. {
  65048. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  65049. if (checkWidth > 0 && checkHeight > 0)
  65050. {
  65051. context->saveState();
  65052. if (colour1 == colour2)
  65053. {
  65054. context->setFill (colour1);
  65055. context->fillRect (Rectangle<int> (x, y, width, height), false);
  65056. }
  65057. else
  65058. {
  65059. const Rectangle<int> clip (context->getClipBounds());
  65060. const int right = jmin (x + width, clip.getRight());
  65061. const int bottom = jmin (y + height, clip.getBottom());
  65062. int cy = 0;
  65063. while (y < bottom)
  65064. {
  65065. int cx = cy;
  65066. for (int xx = x; xx < right; xx += checkWidth)
  65067. {
  65068. context->setFill (((cx++ & 1) == 0) ? colour1 : colour2);
  65069. context->fillRect (Rectangle<int> (xx, y, jmin (checkWidth, right - xx), jmin (checkHeight, bottom - y)),
  65070. false);
  65071. }
  65072. ++cy;
  65073. y += checkHeight;
  65074. }
  65075. }
  65076. context->restoreState();
  65077. }
  65078. }
  65079. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  65080. {
  65081. context->drawVerticalLine (x, top, bottom);
  65082. }
  65083. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  65084. {
  65085. context->drawHorizontalLine (y, left, right);
  65086. }
  65087. void Graphics::drawLine (float x1, float y1, float x2, float y2) const
  65088. {
  65089. context->drawLine (Line<float> (x1, y1, x2, y2));
  65090. }
  65091. void Graphics::drawLine (const float startX, const float startY,
  65092. const float endX, const float endY,
  65093. const float lineThickness) const
  65094. {
  65095. Path p;
  65096. p.addLineSegment (startX, startY, endX, endY, lineThickness);
  65097. fillPath (p);
  65098. }
  65099. void Graphics::drawLine (const Line<float>& line) const
  65100. {
  65101. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  65102. }
  65103. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  65104. {
  65105. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY(), lineThickness);
  65106. }
  65107. void Graphics::drawDashedLine (const float startX, const float startY,
  65108. const float endX, const float endY,
  65109. const float* const dashLengths,
  65110. const int numDashLengths,
  65111. const float lineThickness) const
  65112. {
  65113. const double dx = endX - startX;
  65114. const double dy = endY - startY;
  65115. const double totalLen = juce_hypot (dx, dy);
  65116. if (totalLen >= 0.5)
  65117. {
  65118. const double onePixAlpha = 1.0 / totalLen;
  65119. double alpha = 0.0;
  65120. float x = startX;
  65121. float y = startY;
  65122. int n = 0;
  65123. while (alpha < 1.0f)
  65124. {
  65125. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  65126. n = n % numDashLengths;
  65127. const float oldX = x;
  65128. const float oldY = y;
  65129. x = (float) (startX + dx * alpha);
  65130. y = (float) (startY + dy * alpha);
  65131. if ((n & 1) != 0)
  65132. {
  65133. if (lineThickness != 1.0f)
  65134. drawLine (oldX, oldY, x, y, lineThickness);
  65135. else
  65136. drawLine (oldX, oldY, x, y);
  65137. }
  65138. }
  65139. }
  65140. }
  65141. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  65142. {
  65143. saveStateIfPending();
  65144. context->setInterpolationQuality (newQuality);
  65145. }
  65146. void Graphics::drawImageAt (const Image* const imageToDraw,
  65147. const int topLeftX, const int topLeftY,
  65148. const bool fillAlphaChannelWithCurrentBrush) const
  65149. {
  65150. if (imageToDraw != 0)
  65151. {
  65152. const int imageW = imageToDraw->getWidth();
  65153. const int imageH = imageToDraw->getHeight();
  65154. drawImage (imageToDraw,
  65155. topLeftX, topLeftY, imageW, imageH,
  65156. 0, 0, imageW, imageH,
  65157. fillAlphaChannelWithCurrentBrush);
  65158. }
  65159. }
  65160. void Graphics::drawImageWithin (const Image* const imageToDraw,
  65161. const int destX, const int destY,
  65162. const int destW, const int destH,
  65163. const RectanglePlacement& placementWithinTarget,
  65164. const bool fillAlphaChannelWithCurrentBrush) const
  65165. {
  65166. // passing in a silly number can cause maths problems in rendering!
  65167. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  65168. if (imageToDraw != 0)
  65169. {
  65170. const int imageW = imageToDraw->getWidth();
  65171. const int imageH = imageToDraw->getHeight();
  65172. if (imageW > 0 && imageH > 0)
  65173. {
  65174. double newX = 0.0, newY = 0.0;
  65175. double newW = imageW;
  65176. double newH = imageH;
  65177. placementWithinTarget.applyTo (newX, newY, newW, newH,
  65178. destX, destY, destW, destH);
  65179. if (newW > 0 && newH > 0)
  65180. {
  65181. drawImage (imageToDraw,
  65182. roundToInt (newX), roundToInt (newY),
  65183. roundToInt (newW), roundToInt (newH),
  65184. 0, 0, imageW, imageH,
  65185. fillAlphaChannelWithCurrentBrush);
  65186. }
  65187. }
  65188. }
  65189. }
  65190. void Graphics::drawImage (const Image* const imageToDraw,
  65191. int dx, int dy, int dw, int dh,
  65192. int sx, int sy, int sw, int sh,
  65193. const bool fillAlphaChannelWithCurrentBrush) const
  65194. {
  65195. // passing in a silly number can cause maths problems in rendering!
  65196. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  65197. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  65198. if (context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  65199. {
  65200. drawImageTransformed (imageToDraw, Rectangle<int> (sx, sy, sw, sh),
  65201. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  65202. .translated ((float) dx, (float) dy),
  65203. fillAlphaChannelWithCurrentBrush);
  65204. }
  65205. }
  65206. void Graphics::drawImageTransformed (const Image* const imageToDraw,
  65207. const Rectangle<int>& imageSubRegion,
  65208. const AffineTransform& transform,
  65209. const bool fillAlphaChannelWithCurrentBrush) const
  65210. {
  65211. if (imageToDraw != 0 && ! context->isClipEmpty())
  65212. {
  65213. const Rectangle<int> srcClip (imageSubRegion.getIntersection (imageToDraw->getBounds()));
  65214. if (fillAlphaChannelWithCurrentBrush)
  65215. {
  65216. context->saveState();
  65217. context->clipToImageAlpha (*imageToDraw, srcClip, transform);
  65218. fillAll();
  65219. context->restoreState();
  65220. }
  65221. else
  65222. {
  65223. context->drawImage (*imageToDraw, srcClip, transform, false);
  65224. }
  65225. }
  65226. }
  65227. END_JUCE_NAMESPACE
  65228. /*** End of inlined file: juce_Graphics.cpp ***/
  65229. /*** Start of inlined file: juce_Justification.cpp ***/
  65230. BEGIN_JUCE_NAMESPACE
  65231. Justification::Justification (const Justification& other) throw()
  65232. : flags (other.flags)
  65233. {
  65234. }
  65235. Justification& Justification::operator= (const Justification& other) throw()
  65236. {
  65237. flags = other.flags;
  65238. return *this;
  65239. }
  65240. int Justification::getOnlyVerticalFlags() const throw()
  65241. {
  65242. return flags & (top | bottom | verticallyCentred);
  65243. }
  65244. int Justification::getOnlyHorizontalFlags() const throw()
  65245. {
  65246. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  65247. }
  65248. void Justification::applyToRectangle (int& x, int& y,
  65249. const int w, const int h,
  65250. const int spaceX, const int spaceY,
  65251. const int spaceW, const int spaceH) const throw()
  65252. {
  65253. if ((flags & horizontallyCentred) != 0)
  65254. {
  65255. x = spaceX + ((spaceW - w) >> 1);
  65256. }
  65257. else if ((flags & right) != 0)
  65258. {
  65259. x = spaceX + spaceW - w;
  65260. }
  65261. else
  65262. {
  65263. x = spaceX;
  65264. }
  65265. if ((flags & verticallyCentred) != 0)
  65266. {
  65267. y = spaceY + ((spaceH - h) >> 1);
  65268. }
  65269. else if ((flags & bottom) != 0)
  65270. {
  65271. y = spaceY + spaceH - h;
  65272. }
  65273. else
  65274. {
  65275. y = spaceY;
  65276. }
  65277. }
  65278. END_JUCE_NAMESPACE
  65279. /*** End of inlined file: juce_Justification.cpp ***/
  65280. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  65281. BEGIN_JUCE_NAMESPACE
  65282. // this will throw an assertion if you try to draw something that's not
  65283. // possible in postscript
  65284. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  65285. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  65286. #define notPossibleInPostscriptAssert jassertfalse
  65287. #else
  65288. #define notPossibleInPostscriptAssert
  65289. #endif
  65290. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  65291. const String& documentTitle,
  65292. const int totalWidth_,
  65293. const int totalHeight_)
  65294. : out (resultingPostScript),
  65295. totalWidth (totalWidth_),
  65296. totalHeight (totalHeight_),
  65297. needToClip (true)
  65298. {
  65299. stateStack.add (new SavedState());
  65300. stateStack.getLast()->clip = Rectangle<int> (0, 0, totalWidth_, totalHeight_);
  65301. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  65302. out << "%!PS-Adobe-3.0 EPSF-3.0"
  65303. "\n%%BoundingBox: 0 0 600 824"
  65304. "\n%%Pages: 0"
  65305. "\n%%Creator: Raw Material Software JUCE"
  65306. "\n%%Title: " << documentTitle <<
  65307. "\n%%CreationDate: none"
  65308. "\n%%LanguageLevel: 2"
  65309. "\n%%EndComments"
  65310. "\n%%BeginProlog"
  65311. "\n%%BeginResource: JRes"
  65312. "\n/bd {bind def} bind def"
  65313. "\n/c {setrgbcolor} bd"
  65314. "\n/m {moveto} bd"
  65315. "\n/l {lineto} bd"
  65316. "\n/rl {rlineto} bd"
  65317. "\n/ct {curveto} bd"
  65318. "\n/cp {closepath} bd"
  65319. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  65320. "\n/doclip {initclip newpath} bd"
  65321. "\n/endclip {clip newpath} bd"
  65322. "\n%%EndResource"
  65323. "\n%%EndProlog"
  65324. "\n%%BeginSetup"
  65325. "\n%%EndSetup"
  65326. "\n%%Page: 1 1"
  65327. "\n%%BeginPageSetup"
  65328. "\n%%EndPageSetup\n\n"
  65329. << "40 800 translate\n"
  65330. << scale << ' ' << scale << " scale\n\n";
  65331. }
  65332. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  65333. {
  65334. }
  65335. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  65336. {
  65337. return true;
  65338. }
  65339. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  65340. {
  65341. if (x != 0 || y != 0)
  65342. {
  65343. stateStack.getLast()->xOffset += x;
  65344. stateStack.getLast()->yOffset += y;
  65345. needToClip = true;
  65346. }
  65347. }
  65348. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  65349. {
  65350. needToClip = true;
  65351. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65352. }
  65353. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  65354. {
  65355. needToClip = true;
  65356. return stateStack.getLast()->clip.clipTo (clipRegion);
  65357. }
  65358. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  65359. {
  65360. needToClip = true;
  65361. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65362. }
  65363. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  65364. {
  65365. writeClip();
  65366. Path p (path);
  65367. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  65368. writePath (p);
  65369. out << "clip\n";
  65370. }
  65371. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const Rectangle<int>& /*srcClip*/, const AffineTransform& /*transform*/)
  65372. {
  65373. needToClip = true;
  65374. jassertfalse // xxx
  65375. }
  65376. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  65377. {
  65378. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65379. }
  65380. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  65381. {
  65382. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  65383. -stateStack.getLast()->yOffset);
  65384. }
  65385. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  65386. {
  65387. return stateStack.getLast()->clip.isEmpty();
  65388. }
  65389. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  65390. : xOffset (0),
  65391. yOffset (0)
  65392. {
  65393. }
  65394. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  65395. {
  65396. }
  65397. void LowLevelGraphicsPostScriptRenderer::saveState()
  65398. {
  65399. stateStack.add (new SavedState (*stateStack.getLast()));
  65400. }
  65401. void LowLevelGraphicsPostScriptRenderer::restoreState()
  65402. {
  65403. jassert (stateStack.size() > 0);
  65404. if (stateStack.size() > 0)
  65405. stateStack.removeLast();
  65406. }
  65407. void LowLevelGraphicsPostScriptRenderer::writeClip()
  65408. {
  65409. if (needToClip)
  65410. {
  65411. needToClip = false;
  65412. out << "doclip ";
  65413. int itemsOnLine = 0;
  65414. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  65415. {
  65416. if (++itemsOnLine == 6)
  65417. {
  65418. itemsOnLine = 0;
  65419. out << '\n';
  65420. }
  65421. const Rectangle<int>& r = *i.getRectangle();
  65422. out << r.getX() << ' ' << -r.getY() << ' '
  65423. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  65424. }
  65425. out << "endclip\n";
  65426. }
  65427. }
  65428. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  65429. {
  65430. Colour c (Colours::white.overlaidWith (colour));
  65431. if (lastColour != c)
  65432. {
  65433. lastColour = c;
  65434. out << String (c.getFloatRed(), 3) << ' '
  65435. << String (c.getFloatGreen(), 3) << ' '
  65436. << String (c.getFloatBlue(), 3) << " c\n";
  65437. }
  65438. }
  65439. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  65440. {
  65441. out << String (x, 2) << ' '
  65442. << String (-y, 2) << ' ';
  65443. }
  65444. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  65445. {
  65446. out << "newpath ";
  65447. float lastX = 0.0f;
  65448. float lastY = 0.0f;
  65449. int itemsOnLine = 0;
  65450. Path::Iterator i (path);
  65451. while (i.next())
  65452. {
  65453. if (++itemsOnLine == 4)
  65454. {
  65455. itemsOnLine = 0;
  65456. out << '\n';
  65457. }
  65458. switch (i.elementType)
  65459. {
  65460. case Path::Iterator::startNewSubPath:
  65461. writeXY (i.x1, i.y1);
  65462. lastX = i.x1;
  65463. lastY = i.y1;
  65464. out << "m ";
  65465. break;
  65466. case Path::Iterator::lineTo:
  65467. writeXY (i.x1, i.y1);
  65468. lastX = i.x1;
  65469. lastY = i.y1;
  65470. out << "l ";
  65471. break;
  65472. case Path::Iterator::quadraticTo:
  65473. {
  65474. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  65475. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  65476. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  65477. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  65478. writeXY (cp1x, cp1y);
  65479. writeXY (cp2x, cp2y);
  65480. writeXY (i.x2, i.y2);
  65481. out << "ct ";
  65482. lastX = i.x2;
  65483. lastY = i.y2;
  65484. }
  65485. break;
  65486. case Path::Iterator::cubicTo:
  65487. writeXY (i.x1, i.y1);
  65488. writeXY (i.x2, i.y2);
  65489. writeXY (i.x3, i.y3);
  65490. out << "ct ";
  65491. lastX = i.x3;
  65492. lastY = i.y3;
  65493. break;
  65494. case Path::Iterator::closePath:
  65495. out << "cp ";
  65496. break;
  65497. default:
  65498. jassertfalse
  65499. break;
  65500. }
  65501. }
  65502. out << '\n';
  65503. }
  65504. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  65505. {
  65506. out << "[ "
  65507. << trans.mat00 << ' '
  65508. << trans.mat10 << ' '
  65509. << trans.mat01 << ' '
  65510. << trans.mat11 << ' '
  65511. << trans.mat02 << ' '
  65512. << trans.mat12 << " ] concat ";
  65513. }
  65514. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  65515. {
  65516. stateStack.getLast()->fillType = fillType;
  65517. }
  65518. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  65519. {
  65520. }
  65521. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  65522. {
  65523. }
  65524. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  65525. {
  65526. if (stateStack.getLast()->fillType.isColour())
  65527. {
  65528. writeClip();
  65529. writeColour (stateStack.getLast()->fillType.colour);
  65530. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65531. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  65532. }
  65533. else
  65534. {
  65535. Path p;
  65536. p.addRectangle (r);
  65537. fillPath (p, AffineTransform::identity);
  65538. }
  65539. }
  65540. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  65541. {
  65542. if (stateStack.getLast()->fillType.isColour())
  65543. {
  65544. writeClip();
  65545. Path p (path);
  65546. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  65547. (float) stateStack.getLast()->yOffset));
  65548. writePath (p);
  65549. writeColour (stateStack.getLast()->fillType.colour);
  65550. out << "fill\n";
  65551. }
  65552. else if (stateStack.getLast()->fillType.isGradient())
  65553. {
  65554. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  65555. // postscript can't do semi-transparent ones.
  65556. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  65557. writeClip();
  65558. out << "gsave ";
  65559. {
  65560. Path p (path);
  65561. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  65562. writePath (p);
  65563. out << "clip\n";
  65564. }
  65565. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  65566. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  65567. // time-being, this just fills it with the average colour..
  65568. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  65569. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  65570. out << "grestore\n";
  65571. }
  65572. }
  65573. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  65574. const int sx, const int sy,
  65575. const int maxW, const int maxH) const
  65576. {
  65577. out << "{<\n";
  65578. const int w = jmin (maxW, im.getWidth());
  65579. const int h = jmin (maxH, im.getHeight());
  65580. int charsOnLine = 0;
  65581. const Image::BitmapData srcData (im, 0, 0, w, h);
  65582. Colour pixel;
  65583. for (int y = h; --y >= 0;)
  65584. {
  65585. for (int x = 0; x < w; ++x)
  65586. {
  65587. const uint8* pixelData = srcData.getPixelPointer (x, y);
  65588. if (x >= sx && y >= sy)
  65589. {
  65590. if (im.isARGB())
  65591. {
  65592. PixelARGB p (*(const PixelARGB*) pixelData);
  65593. p.unpremultiply();
  65594. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  65595. }
  65596. else if (im.isRGB())
  65597. {
  65598. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  65599. }
  65600. else
  65601. {
  65602. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  65603. }
  65604. }
  65605. else
  65606. {
  65607. pixel = Colours::transparentWhite;
  65608. }
  65609. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  65610. out << String::toHexString (pixelValues, 3, 0);
  65611. charsOnLine += 3;
  65612. if (charsOnLine > 100)
  65613. {
  65614. out << '\n';
  65615. charsOnLine = 0;
  65616. }
  65617. }
  65618. }
  65619. out << "\n>}\n";
  65620. }
  65621. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  65622. const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  65623. {
  65624. const int w = jmin (sourceImage.getWidth(), srcClip.getRight());
  65625. const int h = jmin (sourceImage.getHeight(), srcClip.getBottom());
  65626. writeClip();
  65627. out << "gsave ";
  65628. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  65629. .scaled (1.0f, -1.0f));
  65630. RectangleList imageClip;
  65631. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  65632. imageClip.clipTo (srcClip);
  65633. out << "newpath ";
  65634. int itemsOnLine = 0;
  65635. for (RectangleList::Iterator i (imageClip); i.next();)
  65636. {
  65637. if (++itemsOnLine == 6)
  65638. {
  65639. out << '\n';
  65640. itemsOnLine = 0;
  65641. }
  65642. const Rectangle<int>& r = *i.getRectangle();
  65643. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  65644. }
  65645. out << " clip newpath\n";
  65646. out << w << ' ' << h << " scale\n";
  65647. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  65648. writeImage (sourceImage, srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  65649. out << "false 3 colorimage grestore\n";
  65650. needToClip = true;
  65651. }
  65652. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  65653. {
  65654. Path p;
  65655. p.addLineSegment (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY(), 1.0f);
  65656. fillPath (p, AffineTransform::identity);
  65657. }
  65658. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  65659. {
  65660. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  65661. }
  65662. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  65663. {
  65664. drawLine (Line<float> (left, (float) y, right, (float) y));
  65665. }
  65666. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  65667. {
  65668. stateStack.getLast()->font = newFont;
  65669. }
  65670. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  65671. {
  65672. return stateStack.getLast()->font;
  65673. }
  65674. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  65675. {
  65676. Path p;
  65677. Font& font = stateStack.getLast()->font;
  65678. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  65679. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  65680. }
  65681. END_JUCE_NAMESPACE
  65682. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  65683. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  65684. BEGIN_JUCE_NAMESPACE
  65685. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  65686. #define JUCE_USE_SSE_INSTRUCTIONS 1
  65687. #endif
  65688. #if JUCE_MSVC
  65689. #pragma warning (push)
  65690. #pragma warning (disable: 4127) // "expression is constant" warning
  65691. #if JUCE_DEBUG
  65692. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  65693. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  65694. #endif
  65695. #endif
  65696. namespace SoftwareRendererClasses
  65697. {
  65698. template <class PixelType, bool replaceExisting = false>
  65699. class SolidColourEdgeTableRenderer
  65700. {
  65701. public:
  65702. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  65703. : data (data_),
  65704. sourceColour (colour)
  65705. {
  65706. if (sizeof (PixelType) == 3)
  65707. {
  65708. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  65709. && sourceColour.getGreen() == sourceColour.getBlue();
  65710. filler[0].set (sourceColour);
  65711. filler[1].set (sourceColour);
  65712. filler[2].set (sourceColour);
  65713. filler[3].set (sourceColour);
  65714. }
  65715. }
  65716. forcedinline void setEdgeTableYPos (const int y) throw()
  65717. {
  65718. linePixels = (PixelType*) data.getLinePointer (y);
  65719. }
  65720. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  65721. {
  65722. if (replaceExisting)
  65723. linePixels[x].set (sourceColour);
  65724. else
  65725. linePixels[x].blend (sourceColour, alphaLevel);
  65726. }
  65727. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  65728. {
  65729. if (replaceExisting)
  65730. linePixels[x].set (sourceColour);
  65731. else
  65732. linePixels[x].blend (sourceColour);
  65733. }
  65734. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  65735. {
  65736. PixelARGB p (sourceColour);
  65737. p.multiplyAlpha (alphaLevel);
  65738. PixelType* dest = linePixels + x;
  65739. if (replaceExisting || p.getAlpha() >= 0xff)
  65740. replaceLine (dest, p, width);
  65741. else
  65742. blendLine (dest, p, width);
  65743. }
  65744. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  65745. {
  65746. PixelType* dest = linePixels + x;
  65747. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  65748. replaceLine (dest, sourceColour, width);
  65749. else
  65750. blendLine (dest, sourceColour, width);
  65751. }
  65752. private:
  65753. const Image::BitmapData& data;
  65754. PixelType* linePixels;
  65755. PixelARGB sourceColour;
  65756. PixelRGB filler [4];
  65757. bool areRGBComponentsEqual;
  65758. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  65759. {
  65760. do
  65761. {
  65762. dest->blend (colour);
  65763. ++dest;
  65764. } while (--width > 0);
  65765. }
  65766. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  65767. {
  65768. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  65769. {
  65770. memset (dest, colour.getRed(), width * 3);
  65771. }
  65772. else
  65773. {
  65774. if (width >> 5)
  65775. {
  65776. const int* const intFiller = (const int*) filler;
  65777. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  65778. {
  65779. dest->set (colour);
  65780. ++dest;
  65781. --width;
  65782. }
  65783. while (width > 4)
  65784. {
  65785. ((int*) dest) [0] = intFiller[0];
  65786. ((int*) dest) [1] = intFiller[1];
  65787. ((int*) dest) [2] = intFiller[2];
  65788. dest = (PixelRGB*) (((uint8*) dest) + 12);
  65789. width -= 4;
  65790. }
  65791. }
  65792. while (--width >= 0)
  65793. {
  65794. dest->set (colour);
  65795. ++dest;
  65796. }
  65797. }
  65798. }
  65799. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  65800. {
  65801. memset (dest, colour.getAlpha(), width);
  65802. }
  65803. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  65804. {
  65805. do
  65806. {
  65807. dest->set (colour);
  65808. ++dest;
  65809. } while (--width > 0);
  65810. }
  65811. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  65812. SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  65813. };
  65814. class LinearGradientPixelGenerator
  65815. {
  65816. public:
  65817. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  65818. : lookupTable (lookupTable_), numEntries (numEntries_)
  65819. {
  65820. jassert (numEntries_ >= 0);
  65821. Point<float> p1 (gradient.x1, gradient.y1);
  65822. Point<float> p2 (gradient.x2, gradient.y2);
  65823. if (! transform.isIdentity())
  65824. {
  65825. const Line<float> l (p2, p1);
  65826. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  65827. p1.applyTransform (transform);
  65828. p2.applyTransform (transform);
  65829. p3.applyTransform (transform);
  65830. const Line<float> l2 (p2, p3);
  65831. p2 = l2.getPointAlongLineProportionally (l2.findNearestPointTo (p1));
  65832. }
  65833. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  65834. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  65835. if (vertical)
  65836. {
  65837. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  65838. start = roundToInt (p1.getY() * scale);
  65839. }
  65840. else if (horizontal)
  65841. {
  65842. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  65843. start = roundToInt (p1.getX() * scale);
  65844. }
  65845. else
  65846. {
  65847. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  65848. yTerm = p1.getY() - p1.getX() / grad;
  65849. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  65850. grad *= scale;
  65851. }
  65852. }
  65853. forcedinline void setY (const int y) throw()
  65854. {
  65855. if (vertical)
  65856. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  65857. else if (! horizontal)
  65858. start = roundToInt ((y - yTerm) * grad);
  65859. }
  65860. inline const PixelARGB getPixel (const int x) const throw()
  65861. {
  65862. return vertical ? linePix
  65863. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  65864. }
  65865. private:
  65866. const PixelARGB* const lookupTable;
  65867. const int numEntries;
  65868. PixelARGB linePix;
  65869. int start, scale;
  65870. double grad, yTerm;
  65871. bool vertical, horizontal;
  65872. enum { numScaleBits = 12 };
  65873. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  65874. LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  65875. };
  65876. class RadialGradientPixelGenerator
  65877. {
  65878. public:
  65879. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  65880. const PixelARGB* const lookupTable_, const int numEntries_)
  65881. : lookupTable (lookupTable_),
  65882. numEntries (numEntries_),
  65883. gx1 (gradient.x1),
  65884. gy1 (gradient.y1)
  65885. {
  65886. jassert (numEntries_ >= 0);
  65887. const float gdx = gradient.x1 - gradient.x2;
  65888. const float gdy = gradient.y1 - gradient.y2;
  65889. maxDist = gdx * gdx + gdy * gdy;
  65890. invScale = numEntries / std::sqrt (maxDist);
  65891. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  65892. }
  65893. forcedinline void setY (const int y) throw()
  65894. {
  65895. dy = y - gy1;
  65896. dy *= dy;
  65897. }
  65898. inline const PixelARGB getPixel (const int px) const throw()
  65899. {
  65900. double x = px - gx1;
  65901. x *= x;
  65902. x += dy;
  65903. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  65904. }
  65905. protected:
  65906. const PixelARGB* const lookupTable;
  65907. const int numEntries;
  65908. const double gx1, gy1;
  65909. double maxDist, invScale, dy;
  65910. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  65911. RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  65912. };
  65913. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  65914. {
  65915. public:
  65916. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  65917. const PixelARGB* const lookupTable_, const int numEntries_)
  65918. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  65919. inverseTransform (transform.inverted())
  65920. {
  65921. tM10 = inverseTransform.mat10;
  65922. tM00 = inverseTransform.mat00;
  65923. }
  65924. forcedinline void setY (const int y) throw()
  65925. {
  65926. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  65927. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  65928. }
  65929. inline const PixelARGB getPixel (const int px) const throw()
  65930. {
  65931. double x = px;
  65932. const double y = tM10 * x + lineYM11;
  65933. x = tM00 * x + lineYM01;
  65934. x *= x;
  65935. x += y * y;
  65936. if (x >= maxDist)
  65937. return lookupTable [numEntries];
  65938. else
  65939. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  65940. }
  65941. private:
  65942. double tM10, tM00, lineYM01, lineYM11;
  65943. const AffineTransform inverseTransform;
  65944. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  65945. TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  65946. };
  65947. template <class PixelType, class GradientType>
  65948. class GradientEdgeTableRenderer : public GradientType
  65949. {
  65950. public:
  65951. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  65952. const PixelARGB* const lookupTable_, const int numEntries_)
  65953. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  65954. destData (destData_)
  65955. {
  65956. }
  65957. forcedinline void setEdgeTableYPos (const int y) throw()
  65958. {
  65959. linePixels = (PixelType*) destData.getLinePointer (y);
  65960. GradientType::setY (y);
  65961. }
  65962. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  65963. {
  65964. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  65965. }
  65966. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  65967. {
  65968. linePixels[x].blend (GradientType::getPixel (x));
  65969. }
  65970. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  65971. {
  65972. PixelType* dest = linePixels + x;
  65973. if (alphaLevel < 0xff)
  65974. {
  65975. do
  65976. {
  65977. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  65978. } while (--width > 0);
  65979. }
  65980. else
  65981. {
  65982. do
  65983. {
  65984. (dest++)->blend (GradientType::getPixel (x++));
  65985. } while (--width > 0);
  65986. }
  65987. }
  65988. void handleEdgeTableLineFull (int x, int width) const throw()
  65989. {
  65990. PixelType* dest = linePixels + x;
  65991. do
  65992. {
  65993. (dest++)->blend (GradientType::getPixel (x++));
  65994. } while (--width > 0);
  65995. }
  65996. private:
  65997. const Image::BitmapData& destData;
  65998. PixelType* linePixels;
  65999. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  66000. GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  66001. };
  66002. static forcedinline int safeModulo (int n, const int divisor) throw()
  66003. {
  66004. jassert (divisor > 0);
  66005. n %= divisor;
  66006. return (n < 0) ? (n + divisor) : n;
  66007. }
  66008. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  66009. class ImageFillEdgeTableRenderer
  66010. {
  66011. public:
  66012. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  66013. const Image::BitmapData& srcData_,
  66014. const int extraAlpha_,
  66015. const int x, const int y)
  66016. : destData (destData_),
  66017. srcData (srcData_),
  66018. extraAlpha (extraAlpha_ + 1),
  66019. xOffset (repeatPattern ? safeModulo (x, srcData_.width) - srcData_.width : x),
  66020. yOffset (repeatPattern ? safeModulo (y, srcData_.height) - srcData_.height : y)
  66021. {
  66022. }
  66023. forcedinline void setEdgeTableYPos (int y) throw()
  66024. {
  66025. linePixels = (DestPixelType*) destData.getLinePointer (y);
  66026. y -= yOffset;
  66027. if (repeatPattern)
  66028. {
  66029. jassert (y >= 0);
  66030. y %= srcData.height;
  66031. }
  66032. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  66033. }
  66034. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  66035. {
  66036. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  66037. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  66038. }
  66039. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  66040. {
  66041. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  66042. }
  66043. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  66044. {
  66045. DestPixelType* dest = linePixels + x;
  66046. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  66047. x -= xOffset;
  66048. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  66049. if (alphaLevel < 0xfe)
  66050. {
  66051. do
  66052. {
  66053. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  66054. } while (--width > 0);
  66055. }
  66056. else
  66057. {
  66058. if (repeatPattern)
  66059. {
  66060. do
  66061. {
  66062. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  66063. } while (--width > 0);
  66064. }
  66065. else
  66066. {
  66067. copyRow (dest, sourceLineStart + x, width);
  66068. }
  66069. }
  66070. }
  66071. void handleEdgeTableLineFull (int x, int width) const throw()
  66072. {
  66073. DestPixelType* dest = linePixels + x;
  66074. x -= xOffset;
  66075. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  66076. if (extraAlpha < 0xfe)
  66077. {
  66078. do
  66079. {
  66080. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  66081. } while (--width > 0);
  66082. }
  66083. else
  66084. {
  66085. if (repeatPattern)
  66086. {
  66087. do
  66088. {
  66089. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  66090. } while (--width > 0);
  66091. }
  66092. else
  66093. {
  66094. copyRow (dest, sourceLineStart + x, width);
  66095. }
  66096. }
  66097. }
  66098. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  66099. {
  66100. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  66101. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  66102. uint8* mask = (uint8*) (s + x - xOffset);
  66103. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  66104. mask += PixelARGB::indexA;
  66105. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  66106. }
  66107. private:
  66108. const Image::BitmapData& destData;
  66109. const Image::BitmapData& srcData;
  66110. const int extraAlpha, xOffset, yOffset;
  66111. DestPixelType* linePixels;
  66112. SrcPixelType* sourceLineStart;
  66113. template <class PixelType1, class PixelType2>
  66114. forcedinline static void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  66115. {
  66116. do
  66117. {
  66118. dest++ ->blend (*src++);
  66119. } while (--width > 0);
  66120. }
  66121. forcedinline static void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  66122. {
  66123. memcpy (dest, src, width * sizeof (PixelRGB));
  66124. }
  66125. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  66126. ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  66127. };
  66128. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  66129. class TransformedImageFillEdgeTableRenderer
  66130. {
  66131. public:
  66132. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  66133. const Image::BitmapData& srcData_,
  66134. const AffineTransform& transform,
  66135. const int extraAlpha_,
  66136. const bool betterQuality_)
  66137. : interpolator (transform),
  66138. destData (destData_),
  66139. srcData (srcData_),
  66140. extraAlpha (extraAlpha_ + 1),
  66141. betterQuality (betterQuality_),
  66142. pixelOffset (betterQuality_ ? 0.5f : 0.0f),
  66143. pixelOffsetInt (betterQuality_ ? -128 : 0),
  66144. maxX (srcData_.width - 1),
  66145. maxY (srcData_.height - 1),
  66146. scratchSize (2048)
  66147. {
  66148. scratchBuffer.malloc (scratchSize);
  66149. }
  66150. ~TransformedImageFillEdgeTableRenderer()
  66151. {
  66152. }
  66153. forcedinline void setEdgeTableYPos (const int newY) throw()
  66154. {
  66155. y = newY;
  66156. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  66157. }
  66158. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) throw()
  66159. {
  66160. alphaLevel *= extraAlpha;
  66161. alphaLevel >>= 8;
  66162. SrcPixelType p;
  66163. generate (&p, x, 1);
  66164. linePixels[x].blend (p, alphaLevel);
  66165. }
  66166. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  66167. {
  66168. SrcPixelType p;
  66169. generate (&p, x, 1);
  66170. linePixels[x].blend (p, extraAlpha);
  66171. }
  66172. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  66173. {
  66174. if (width > scratchSize)
  66175. {
  66176. scratchSize = width;
  66177. scratchBuffer.malloc (scratchSize);
  66178. }
  66179. SrcPixelType* span = scratchBuffer;
  66180. generate (span, x, width);
  66181. DestPixelType* dest = linePixels + x;
  66182. alphaLevel *= extraAlpha;
  66183. alphaLevel >>= 8;
  66184. if (alphaLevel < 0xfe)
  66185. {
  66186. do
  66187. {
  66188. dest++ ->blend (*span++, alphaLevel);
  66189. } while (--width > 0);
  66190. }
  66191. else
  66192. {
  66193. do
  66194. {
  66195. dest++ ->blend (*span++);
  66196. } while (--width > 0);
  66197. }
  66198. }
  66199. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  66200. {
  66201. handleEdgeTableLine (x, width, 255);
  66202. }
  66203. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  66204. {
  66205. if (width > scratchSize)
  66206. {
  66207. scratchSize = width;
  66208. scratchBuffer.malloc (scratchSize);
  66209. }
  66210. y = y_;
  66211. generate (scratchBuffer, x, width);
  66212. et.clipLineToMask (x, y_,
  66213. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  66214. sizeof (SrcPixelType), width);
  66215. }
  66216. private:
  66217. void generate (PixelARGB* dest, const int x, int numPixels) throw()
  66218. {
  66219. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  66220. do
  66221. {
  66222. int hiResX, hiResY;
  66223. this->interpolator.next (hiResX, hiResY);
  66224. hiResX += pixelOffsetInt;
  66225. hiResY += pixelOffsetInt;
  66226. int loResX = hiResX >> 8;
  66227. int loResY = hiResY >> 8;
  66228. if (repeatPattern)
  66229. {
  66230. loResX = safeModulo (loResX, srcData.width);
  66231. loResY = safeModulo (loResY, srcData.height);
  66232. }
  66233. if (betterQuality
  66234. && ((unsigned int) loResX) < (unsigned int) maxX
  66235. && ((unsigned int) loResY) < (unsigned int) maxY)
  66236. {
  66237. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  66238. hiResX &= 255;
  66239. hiResY &= 255;
  66240. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  66241. uint32 weight = (256 - hiResX) * (256 - hiResY);
  66242. c[0] += weight * src[0];
  66243. c[1] += weight * src[1];
  66244. c[2] += weight * src[2];
  66245. c[3] += weight * src[3];
  66246. weight = hiResX * (256 - hiResY);
  66247. c[0] += weight * src[4];
  66248. c[1] += weight * src[5];
  66249. c[2] += weight * src[6];
  66250. c[3] += weight * src[7];
  66251. src += this->srcData.lineStride;
  66252. weight = (256 - hiResX) * hiResY;
  66253. c[0] += weight * src[0];
  66254. c[1] += weight * src[1];
  66255. c[2] += weight * src[2];
  66256. c[3] += weight * src[3];
  66257. weight = hiResX * hiResY;
  66258. c[0] += weight * src[4];
  66259. c[1] += weight * src[5];
  66260. c[2] += weight * src[6];
  66261. c[3] += weight * src[7];
  66262. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  66263. (uint8) (c[PixelARGB::indexR] >> 16),
  66264. (uint8) (c[PixelARGB::indexG] >> 16),
  66265. (uint8) (c[PixelARGB::indexB] >> 16));
  66266. }
  66267. else
  66268. {
  66269. if (! repeatPattern)
  66270. {
  66271. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  66272. if (loResX < 0) loResX = 0;
  66273. if (loResY < 0) loResY = 0;
  66274. if (loResX > maxX) loResX = maxX;
  66275. if (loResY > maxY) loResY = maxY;
  66276. }
  66277. dest->set (*(const PixelARGB*) this->srcData.getPixelPointer (loResX, loResY));
  66278. }
  66279. ++dest;
  66280. } while (--numPixels > 0);
  66281. }
  66282. void generate (PixelRGB* dest, const int x, int numPixels) throw()
  66283. {
  66284. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  66285. do
  66286. {
  66287. int hiResX, hiResY;
  66288. this->interpolator.next (hiResX, hiResY);
  66289. hiResX += pixelOffsetInt;
  66290. hiResY += pixelOffsetInt;
  66291. int loResX = hiResX >> 8;
  66292. int loResY = hiResY >> 8;
  66293. if (repeatPattern)
  66294. {
  66295. loResX = safeModulo (loResX, srcData.width);
  66296. loResY = safeModulo (loResY, srcData.height);
  66297. }
  66298. if (betterQuality
  66299. && ((unsigned int) loResX) < (unsigned int) maxX
  66300. && ((unsigned int) loResY) < (unsigned int) maxY)
  66301. {
  66302. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  66303. hiResX &= 255;
  66304. hiResY &= 255;
  66305. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  66306. unsigned int weight = (256 - hiResX) * (256 - hiResY);
  66307. c[0] += weight * src[0];
  66308. c[1] += weight * src[1];
  66309. c[2] += weight * src[2];
  66310. weight = hiResX * (256 - hiResY);
  66311. c[0] += weight * src[3];
  66312. c[1] += weight * src[4];
  66313. c[2] += weight * src[5];
  66314. src += this->srcData.lineStride;
  66315. weight = (256 - hiResX) * hiResY;
  66316. c[0] += weight * src[0];
  66317. c[1] += weight * src[1];
  66318. c[2] += weight * src[2];
  66319. weight = hiResX * hiResY;
  66320. c[0] += weight * src[3];
  66321. c[1] += weight * src[4];
  66322. c[2] += weight * src[5];
  66323. dest->setARGB ((uint8) 255,
  66324. (uint8) (c[PixelRGB::indexR] >> 16),
  66325. (uint8) (c[PixelRGB::indexG] >> 16),
  66326. (uint8) (c[PixelRGB::indexB] >> 16));
  66327. }
  66328. else
  66329. {
  66330. if (! repeatPattern)
  66331. {
  66332. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  66333. if (loResX < 0) loResX = 0;
  66334. if (loResY < 0) loResY = 0;
  66335. if (loResX > maxX) loResX = maxX;
  66336. if (loResY > maxY) loResY = maxY;
  66337. }
  66338. dest->set (*(const PixelRGB*) this->srcData.getPixelPointer (loResX, loResY));
  66339. }
  66340. ++dest;
  66341. } while (--numPixels > 0);
  66342. }
  66343. void generate (PixelAlpha* dest, const int x, int numPixels) throw()
  66344. {
  66345. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  66346. do
  66347. {
  66348. int hiResX, hiResY;
  66349. this->interpolator.next (hiResX, hiResY);
  66350. hiResX += pixelOffsetInt;
  66351. hiResY += pixelOffsetInt;
  66352. int loResX = hiResX >> 8;
  66353. int loResY = hiResY >> 8;
  66354. if (repeatPattern)
  66355. {
  66356. loResX = safeModulo (loResX, srcData.width);
  66357. loResY = safeModulo (loResY, srcData.height);
  66358. }
  66359. if (betterQuality
  66360. && ((unsigned int) loResX) < (unsigned int) maxX
  66361. && ((unsigned int) loResY) < (unsigned int) maxY)
  66362. {
  66363. hiResX &= 255;
  66364. hiResY &= 255;
  66365. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  66366. uint32 c = 256 * 128;
  66367. c += src[0] * ((256 - hiResX) * (256 - hiResY));
  66368. c += src[1] * (hiResX * (256 - hiResY));
  66369. src += this->srcData.lineStride;
  66370. c += src[0] * ((256 - hiResX) * hiResY);
  66371. c += src[1] * (hiResX * hiResY);
  66372. *((uint8*) dest) = (uint8) c;
  66373. }
  66374. else
  66375. {
  66376. if (! repeatPattern)
  66377. {
  66378. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  66379. if (loResX < 0) loResX = 0;
  66380. if (loResY < 0) loResY = 0;
  66381. if (loResX > maxX) loResX = maxX;
  66382. if (loResY > maxY) loResY = maxY;
  66383. }
  66384. *((uint8*) dest) = *(this->srcData.getPixelPointer (loResX, loResY));
  66385. }
  66386. ++dest;
  66387. } while (--numPixels > 0);
  66388. }
  66389. class TransformedImageSpanInterpolator
  66390. {
  66391. public:
  66392. TransformedImageSpanInterpolator (const AffineTransform& transform) throw()
  66393. : inverseTransform (transform.inverted())
  66394. {}
  66395. void setStartOfLine (float x, float y, const int numPixels) throw()
  66396. {
  66397. float x1 = x, y1 = y;
  66398. inverseTransform.transformPoint (x1, y1);
  66399. x += numPixels;
  66400. inverseTransform.transformPoint (x, y);
  66401. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels);
  66402. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels);
  66403. }
  66404. void next (int& x, int& y) throw()
  66405. {
  66406. x = xBresenham.n;
  66407. xBresenham.stepToNext();
  66408. y = yBresenham.n;
  66409. yBresenham.stepToNext();
  66410. }
  66411. private:
  66412. class BresenhamInterpolator
  66413. {
  66414. public:
  66415. BresenhamInterpolator() throw() {}
  66416. void set (const int n1, const int n2, const int numSteps_) throw()
  66417. {
  66418. numSteps = jmax (1, numSteps_);
  66419. step = (n2 - n1) / numSteps;
  66420. remainder = modulo = (n2 - n1) % numSteps;
  66421. n = n1;
  66422. if (modulo <= 0)
  66423. {
  66424. modulo += numSteps;
  66425. remainder += numSteps;
  66426. --step;
  66427. }
  66428. modulo -= numSteps;
  66429. }
  66430. forcedinline void stepToNext() throw()
  66431. {
  66432. modulo += remainder;
  66433. n += step;
  66434. if (modulo > 0)
  66435. {
  66436. modulo -= numSteps;
  66437. ++n;
  66438. }
  66439. }
  66440. int n;
  66441. private:
  66442. int numSteps, step, modulo, remainder;
  66443. };
  66444. const AffineTransform inverseTransform;
  66445. BresenhamInterpolator xBresenham, yBresenham;
  66446. TransformedImageSpanInterpolator (const TransformedImageSpanInterpolator&);
  66447. TransformedImageSpanInterpolator& operator= (const TransformedImageSpanInterpolator&);
  66448. };
  66449. TransformedImageSpanInterpolator interpolator;
  66450. const Image::BitmapData& destData;
  66451. const Image::BitmapData& srcData;
  66452. const int extraAlpha;
  66453. const bool betterQuality;
  66454. const float pixelOffset;
  66455. const int pixelOffsetInt, maxX, maxY;
  66456. int y;
  66457. DestPixelType* linePixels;
  66458. HeapBlock <SrcPixelType> scratchBuffer;
  66459. int scratchSize;
  66460. TransformedImageFillEdgeTableRenderer (const TransformedImageFillEdgeTableRenderer&);
  66461. TransformedImageFillEdgeTableRenderer& operator= (const TransformedImageFillEdgeTableRenderer&);
  66462. };
  66463. class ClipRegionBase : public ReferenceCountedObject
  66464. {
  66465. public:
  66466. ClipRegionBase() {}
  66467. virtual ~ClipRegionBase() {}
  66468. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  66469. virtual const Ptr clone() const = 0;
  66470. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  66471. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  66472. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  66473. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  66474. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  66475. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  66476. virtual const Ptr clipToImageAlpha (const Image& image, const Rectangle<int>& srcClip, const AffineTransform& t, const bool betterQuality) = 0;
  66477. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  66478. virtual const Rectangle<int> getClipBounds() const = 0;
  66479. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  66480. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  66481. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  66482. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  66483. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  66484. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  66485. protected:
  66486. template <class Iterator>
  66487. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  66488. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  66489. {
  66490. switch (destData.pixelFormat)
  66491. {
  66492. case Image::ARGB:
  66493. switch (srcData.pixelFormat)
  66494. {
  66495. case Image::ARGB:
  66496. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66497. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66498. break;
  66499. case Image::RGB:
  66500. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66501. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66502. break;
  66503. default:
  66504. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66505. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66506. break;
  66507. }
  66508. break;
  66509. case Image::RGB:
  66510. switch (srcData.pixelFormat)
  66511. {
  66512. case Image::ARGB:
  66513. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66514. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66515. break;
  66516. case Image::RGB:
  66517. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66518. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66519. break;
  66520. default:
  66521. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66522. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66523. break;
  66524. }
  66525. break;
  66526. default:
  66527. switch (srcData.pixelFormat)
  66528. {
  66529. case Image::ARGB:
  66530. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66531. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66532. break;
  66533. case Image::RGB:
  66534. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66535. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66536. break;
  66537. default:
  66538. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66539. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66540. break;
  66541. }
  66542. break;
  66543. }
  66544. }
  66545. template <class Iterator>
  66546. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  66547. {
  66548. switch (destData.pixelFormat)
  66549. {
  66550. case Image::ARGB:
  66551. switch (srcData.pixelFormat)
  66552. {
  66553. case Image::ARGB:
  66554. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66555. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66556. break;
  66557. case Image::RGB:
  66558. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66559. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66560. break;
  66561. default:
  66562. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66563. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66564. break;
  66565. }
  66566. break;
  66567. case Image::RGB:
  66568. switch (srcData.pixelFormat)
  66569. {
  66570. case Image::ARGB:
  66571. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66572. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66573. break;
  66574. case Image::RGB:
  66575. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66576. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66577. break;
  66578. default:
  66579. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66580. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66581. break;
  66582. }
  66583. break;
  66584. default:
  66585. switch (srcData.pixelFormat)
  66586. {
  66587. case Image::ARGB:
  66588. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66589. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66590. break;
  66591. case Image::RGB:
  66592. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66593. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66594. break;
  66595. default:
  66596. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66597. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66598. break;
  66599. }
  66600. break;
  66601. }
  66602. }
  66603. template <class Iterator, class DestPixelType>
  66604. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  66605. {
  66606. jassert (destData.pixelStride == sizeof (DestPixelType));
  66607. if (replaceContents)
  66608. {
  66609. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  66610. iter.iterate (r);
  66611. }
  66612. else
  66613. {
  66614. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  66615. iter.iterate (r);
  66616. }
  66617. }
  66618. template <class Iterator, class DestPixelType>
  66619. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  66620. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  66621. {
  66622. jassert (destData.pixelStride == sizeof (DestPixelType));
  66623. if (g.isRadial)
  66624. {
  66625. if (isIdentity)
  66626. {
  66627. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  66628. iter.iterate (renderer);
  66629. }
  66630. else
  66631. {
  66632. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  66633. iter.iterate (renderer);
  66634. }
  66635. }
  66636. else
  66637. {
  66638. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  66639. iter.iterate (renderer);
  66640. }
  66641. }
  66642. };
  66643. class ClipRegion_EdgeTable : public ClipRegionBase
  66644. {
  66645. public:
  66646. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  66647. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  66648. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  66649. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  66650. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  66651. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  66652. ~ClipRegion_EdgeTable() {}
  66653. const Ptr clone() const
  66654. {
  66655. return new ClipRegion_EdgeTable (*this);
  66656. }
  66657. const Ptr applyClipTo (const Ptr& target) const
  66658. {
  66659. return target->clipToEdgeTable (edgeTable);
  66660. }
  66661. const Ptr clipToRectangle (const Rectangle<int>& r)
  66662. {
  66663. edgeTable.clipToRectangle (r);
  66664. return edgeTable.isEmpty() ? 0 : this;
  66665. }
  66666. const Ptr clipToRectangleList (const RectangleList& r)
  66667. {
  66668. edgeTable.clipToEdgeTable (EdgeTable (r));
  66669. return edgeTable.isEmpty() ? 0 : this;
  66670. }
  66671. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  66672. {
  66673. edgeTable.excludeRectangle (r);
  66674. return edgeTable.isEmpty() ? 0 : this;
  66675. }
  66676. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  66677. {
  66678. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  66679. edgeTable.clipToEdgeTable (et);
  66680. return edgeTable.isEmpty() ? 0 : this;
  66681. }
  66682. const Ptr clipToEdgeTable (const EdgeTable& et)
  66683. {
  66684. edgeTable.clipToEdgeTable (et);
  66685. return edgeTable.isEmpty() ? 0 : this;
  66686. }
  66687. const Ptr clipToImageAlpha (const Image& image, const Rectangle<int>& srcClip, const AffineTransform& transform, const bool betterQuality)
  66688. {
  66689. const Image::BitmapData srcData (image, srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  66690. if (transform.isOnlyTranslation())
  66691. {
  66692. // If our translation doesn't involve any distortion, just use a simple blit..
  66693. const int tx = (int) (transform.getTranslationX() * 256.0f);
  66694. const int ty = (int) (transform.getTranslationY() * 256.0f);
  66695. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  66696. {
  66697. const int imageX = ((tx + 128) >> 8);
  66698. const int imageY = ((ty + 128) >> 8);
  66699. if (image.getFormat() == Image::ARGB)
  66700. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  66701. else
  66702. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  66703. return edgeTable.isEmpty() ? 0 : this;
  66704. }
  66705. }
  66706. if (transform.isSingularity())
  66707. return 0;
  66708. {
  66709. Path p;
  66710. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  66711. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  66712. edgeTable.clipToEdgeTable (et2);
  66713. }
  66714. if (! edgeTable.isEmpty())
  66715. {
  66716. if (image.getFormat() == Image::ARGB)
  66717. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  66718. else
  66719. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  66720. }
  66721. return edgeTable.isEmpty() ? 0 : this;
  66722. }
  66723. bool clipRegionIntersects (const Rectangle<int>& r) const
  66724. {
  66725. return edgeTable.getMaximumBounds().intersects (r);
  66726. }
  66727. const Rectangle<int> getClipBounds() const
  66728. {
  66729. return edgeTable.getMaximumBounds();
  66730. }
  66731. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  66732. {
  66733. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  66734. const Rectangle<int> clipped (totalClip.getIntersection (area));
  66735. if (! clipped.isEmpty())
  66736. {
  66737. ClipRegion_EdgeTable et (clipped);
  66738. et.edgeTable.clipToEdgeTable (edgeTable);
  66739. et.fillAllWithColour (destData, colour, replaceContents);
  66740. }
  66741. }
  66742. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  66743. {
  66744. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  66745. const Rectangle<float> clipped (totalClip.getIntersection (area));
  66746. if (! clipped.isEmpty())
  66747. {
  66748. ClipRegion_EdgeTable et (clipped);
  66749. et.edgeTable.clipToEdgeTable (edgeTable);
  66750. et.fillAllWithColour (destData, colour, false);
  66751. }
  66752. }
  66753. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  66754. {
  66755. switch (destData.pixelFormat)
  66756. {
  66757. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  66758. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  66759. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  66760. }
  66761. }
  66762. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  66763. {
  66764. HeapBlock <PixelARGB> lookupTable;
  66765. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  66766. jassert (numLookupEntries > 0);
  66767. switch (destData.pixelFormat)
  66768. {
  66769. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  66770. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  66771. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  66772. }
  66773. }
  66774. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  66775. {
  66776. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  66777. }
  66778. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  66779. {
  66780. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  66781. }
  66782. EdgeTable edgeTable;
  66783. private:
  66784. template <class SrcPixelType>
  66785. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  66786. {
  66787. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  66788. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  66789. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  66790. edgeTable.getMaximumBounds().getWidth());
  66791. }
  66792. template <class SrcPixelType>
  66793. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  66794. {
  66795. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  66796. edgeTable.clipToRectangle (r);
  66797. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  66798. for (int y = 0; y < r.getHeight(); ++y)
  66799. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  66800. }
  66801. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  66802. };
  66803. class ClipRegion_RectangleList : public ClipRegionBase
  66804. {
  66805. public:
  66806. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  66807. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  66808. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  66809. ~ClipRegion_RectangleList() {}
  66810. const Ptr clone() const
  66811. {
  66812. return new ClipRegion_RectangleList (*this);
  66813. }
  66814. const Ptr applyClipTo (const Ptr& target) const
  66815. {
  66816. return target->clipToRectangleList (clip);
  66817. }
  66818. const Ptr clipToRectangle (const Rectangle<int>& r)
  66819. {
  66820. clip.clipTo (r);
  66821. return clip.isEmpty() ? 0 : this;
  66822. }
  66823. const Ptr clipToRectangleList (const RectangleList& r)
  66824. {
  66825. clip.clipTo (r);
  66826. return clip.isEmpty() ? 0 : this;
  66827. }
  66828. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  66829. {
  66830. clip.subtract (r);
  66831. return clip.isEmpty() ? 0 : this;
  66832. }
  66833. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  66834. {
  66835. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  66836. }
  66837. const Ptr clipToEdgeTable (const EdgeTable& et)
  66838. {
  66839. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  66840. }
  66841. const Ptr clipToImageAlpha (const Image& image, const Rectangle<int>& srcClip, const AffineTransform& transform, const bool betterQuality)
  66842. {
  66843. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, srcClip, transform, betterQuality);
  66844. }
  66845. bool clipRegionIntersects (const Rectangle<int>& r) const
  66846. {
  66847. return clip.intersects (r);
  66848. }
  66849. const Rectangle<int> getClipBounds() const
  66850. {
  66851. return clip.getBounds();
  66852. }
  66853. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  66854. {
  66855. SubRectangleIterator iter (clip, area);
  66856. switch (destData.pixelFormat)
  66857. {
  66858. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  66859. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  66860. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  66861. }
  66862. }
  66863. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  66864. {
  66865. SubRectangleIteratorFloat iter (clip, area);
  66866. switch (destData.pixelFormat)
  66867. {
  66868. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  66869. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  66870. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  66871. }
  66872. }
  66873. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  66874. {
  66875. switch (destData.pixelFormat)
  66876. {
  66877. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  66878. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  66879. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  66880. }
  66881. }
  66882. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  66883. {
  66884. HeapBlock <PixelARGB> lookupTable;
  66885. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  66886. jassert (numLookupEntries > 0);
  66887. switch (destData.pixelFormat)
  66888. {
  66889. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  66890. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  66891. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  66892. }
  66893. }
  66894. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  66895. {
  66896. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  66897. }
  66898. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  66899. {
  66900. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  66901. }
  66902. RectangleList clip;
  66903. template <class Renderer>
  66904. void iterate (Renderer& r) const throw()
  66905. {
  66906. RectangleList::Iterator iter (clip);
  66907. while (iter.next())
  66908. {
  66909. const Rectangle<int> rect (*iter.getRectangle());
  66910. const int x = rect.getX();
  66911. const int w = rect.getWidth();
  66912. jassert (w > 0);
  66913. const int bottom = rect.getBottom();
  66914. for (int y = rect.getY(); y < bottom; ++y)
  66915. {
  66916. r.setEdgeTableYPos (y);
  66917. r.handleEdgeTableLineFull (x, w);
  66918. }
  66919. }
  66920. }
  66921. private:
  66922. class SubRectangleIterator
  66923. {
  66924. public:
  66925. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  66926. : clip (clip_), area (area_)
  66927. {
  66928. }
  66929. template <class Renderer>
  66930. void iterate (Renderer& r) const throw()
  66931. {
  66932. RectangleList::Iterator iter (clip);
  66933. while (iter.next())
  66934. {
  66935. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  66936. if (! rect.isEmpty())
  66937. {
  66938. const int x = rect.getX();
  66939. const int w = rect.getWidth();
  66940. const int bottom = rect.getBottom();
  66941. for (int y = rect.getY(); y < bottom; ++y)
  66942. {
  66943. r.setEdgeTableYPos (y);
  66944. r.handleEdgeTableLineFull (x, w);
  66945. }
  66946. }
  66947. }
  66948. }
  66949. private:
  66950. const RectangleList& clip;
  66951. const Rectangle<int> area;
  66952. SubRectangleIterator (const SubRectangleIterator&);
  66953. SubRectangleIterator& operator= (const SubRectangleIterator&);
  66954. };
  66955. class SubRectangleIteratorFloat
  66956. {
  66957. public:
  66958. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  66959. : clip (clip_), area (area_)
  66960. {
  66961. }
  66962. template <class Renderer>
  66963. void iterate (Renderer& r) const throw()
  66964. {
  66965. int left = roundToInt (area.getX() * 256.0f);
  66966. int top = roundToInt (area.getY() * 256.0f);
  66967. int right = roundToInt (area.getRight() * 256.0f);
  66968. int bottom = roundToInt (area.getBottom() * 256.0f);
  66969. int totalTop, totalLeft, totalBottom, totalRight;
  66970. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  66971. if ((top >> 8) == (bottom >> 8))
  66972. {
  66973. topAlpha = bottom - top;
  66974. bottomAlpha = 0;
  66975. totalTop = top >> 8;
  66976. totalBottom = bottom = top = totalTop + 1;
  66977. }
  66978. else
  66979. {
  66980. if ((top & 255) == 0)
  66981. {
  66982. topAlpha = 0;
  66983. top = totalTop = (top >> 8);
  66984. }
  66985. else
  66986. {
  66987. topAlpha = 255 - (top & 255);
  66988. totalTop = (top >> 8);
  66989. top = totalTop + 1;
  66990. }
  66991. bottomAlpha = bottom & 255;
  66992. bottom >>= 8;
  66993. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  66994. }
  66995. if ((left >> 8) == (right >> 8))
  66996. {
  66997. leftAlpha = right - left;
  66998. rightAlpha = 0;
  66999. totalLeft = (left >> 8);
  67000. totalRight = right = left = totalLeft + 1;
  67001. }
  67002. else
  67003. {
  67004. if ((left & 255) == 0)
  67005. {
  67006. leftAlpha = 0;
  67007. left = totalLeft = (left >> 8);
  67008. }
  67009. else
  67010. {
  67011. leftAlpha = 255 - (left & 255);
  67012. totalLeft = (left >> 8);
  67013. left = totalLeft + 1;
  67014. }
  67015. rightAlpha = right & 255;
  67016. right >>= 8;
  67017. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  67018. }
  67019. RectangleList::Iterator iter (clip);
  67020. while (iter.next())
  67021. {
  67022. const int clipLeft = iter.getRectangle()->getX();
  67023. const int clipRight = iter.getRectangle()->getRight();
  67024. const int clipTop = iter.getRectangle()->getY();
  67025. const int clipBottom = iter.getRectangle()->getBottom();
  67026. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  67027. {
  67028. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  67029. {
  67030. if (topAlpha != 0 && totalTop >= clipTop)
  67031. {
  67032. r.setEdgeTableYPos (totalTop);
  67033. r.handleEdgeTablePixel (left, topAlpha);
  67034. }
  67035. const int endY = jmin (bottom, clipBottom);
  67036. for (int y = jmax (clipTop, top); y < endY; ++y)
  67037. {
  67038. r.setEdgeTableYPos (y);
  67039. r.handleEdgeTablePixelFull (left);
  67040. }
  67041. if (bottomAlpha != 0 && bottom < clipBottom)
  67042. {
  67043. r.setEdgeTableYPos (bottom);
  67044. r.handleEdgeTablePixel (left, bottomAlpha);
  67045. }
  67046. }
  67047. else
  67048. {
  67049. const int clippedLeft = jmax (left, clipLeft);
  67050. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  67051. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  67052. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  67053. if (topAlpha != 0 && totalTop >= clipTop)
  67054. {
  67055. r.setEdgeTableYPos (totalTop);
  67056. if (doLeftAlpha)
  67057. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  67058. if (clippedWidth > 0)
  67059. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  67060. if (doRightAlpha)
  67061. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  67062. }
  67063. const int endY = jmin (bottom, clipBottom);
  67064. for (int y = jmax (clipTop, top); y < endY; ++y)
  67065. {
  67066. r.setEdgeTableYPos (y);
  67067. if (doLeftAlpha)
  67068. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  67069. if (clippedWidth > 0)
  67070. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  67071. if (doRightAlpha)
  67072. r.handleEdgeTablePixel (right, rightAlpha);
  67073. }
  67074. if (bottomAlpha != 0 && bottom < clipBottom)
  67075. {
  67076. r.setEdgeTableYPos (bottom);
  67077. if (doLeftAlpha)
  67078. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  67079. if (clippedWidth > 0)
  67080. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  67081. if (doRightAlpha)
  67082. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  67083. }
  67084. }
  67085. }
  67086. }
  67087. }
  67088. private:
  67089. const RectangleList& clip;
  67090. const Rectangle<float>& area;
  67091. SubRectangleIteratorFloat (const SubRectangleIteratorFloat&);
  67092. SubRectangleIteratorFloat& operator= (const SubRectangleIteratorFloat&);
  67093. };
  67094. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  67095. };
  67096. }
  67097. class LowLevelGraphicsSoftwareRenderer::SavedState
  67098. {
  67099. public:
  67100. SavedState (const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  67101. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  67102. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  67103. {
  67104. }
  67105. SavedState (const RectangleList& clip_, const int xOffset_, const int yOffset_)
  67106. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  67107. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  67108. {
  67109. }
  67110. SavedState (const SavedState& other)
  67111. : clip (other.clip), xOffset (other.xOffset), yOffset (other.yOffset), font (other.font),
  67112. fillType (other.fillType), interpolationQuality (other.interpolationQuality)
  67113. {
  67114. }
  67115. ~SavedState()
  67116. {
  67117. }
  67118. void setOrigin (const int x, const int y) throw()
  67119. {
  67120. xOffset += x;
  67121. yOffset += y;
  67122. }
  67123. bool clipToRectangle (const Rectangle<int>& r)
  67124. {
  67125. if (clip != 0)
  67126. {
  67127. cloneClipIfMultiplyReferenced();
  67128. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  67129. }
  67130. return clip != 0;
  67131. }
  67132. bool clipToRectangleList (const RectangleList& r)
  67133. {
  67134. if (clip != 0)
  67135. {
  67136. cloneClipIfMultiplyReferenced();
  67137. RectangleList offsetList (r);
  67138. offsetList.offsetAll (xOffset, yOffset);
  67139. clip = clip->clipToRectangleList (offsetList);
  67140. }
  67141. return clip != 0;
  67142. }
  67143. bool excludeClipRectangle (const Rectangle<int>& r)
  67144. {
  67145. if (clip != 0)
  67146. {
  67147. cloneClipIfMultiplyReferenced();
  67148. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  67149. }
  67150. return clip != 0;
  67151. }
  67152. void clipToPath (const Path& p, const AffineTransform& transform)
  67153. {
  67154. if (clip != 0)
  67155. {
  67156. cloneClipIfMultiplyReferenced();
  67157. clip = clip->clipToPath (p, transform.translated ((float) xOffset, (float) yOffset));
  67158. }
  67159. }
  67160. void clipToImageAlpha (const Image& image, const Rectangle<int>& srcClip, const AffineTransform& t)
  67161. {
  67162. if (clip != 0)
  67163. {
  67164. if (image.hasAlphaChannel())
  67165. {
  67166. cloneClipIfMultiplyReferenced();
  67167. clip = clip->clipToImageAlpha (image, srcClip, t.translated ((float) xOffset, (float) yOffset),
  67168. interpolationQuality != Graphics::lowResamplingQuality);
  67169. }
  67170. else
  67171. {
  67172. Path p;
  67173. p.addRectangle (srcClip);
  67174. clipToPath (p, t);
  67175. }
  67176. }
  67177. }
  67178. bool clipRegionIntersects (const Rectangle<int>& r) const
  67179. {
  67180. return clip != 0 && clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  67181. }
  67182. const Rectangle<int> getClipBounds() const
  67183. {
  67184. return clip == 0 ? Rectangle<int>() : clip->getClipBounds().translated (-xOffset, -yOffset);
  67185. }
  67186. void fillRect (Image& image, const Rectangle<int>& r, const bool replaceContents)
  67187. {
  67188. if (clip != 0)
  67189. {
  67190. if (fillType.isColour())
  67191. {
  67192. Image::BitmapData destData (image, 0, 0, image.getWidth(), image.getHeight(), true);
  67193. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  67194. }
  67195. else
  67196. {
  67197. const Rectangle<int> totalClip (clip->getClipBounds());
  67198. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  67199. if (! clipped.isEmpty())
  67200. fillShape (image, new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  67201. }
  67202. }
  67203. }
  67204. void fillRect (Image& image, const Rectangle<float>& r)
  67205. {
  67206. if (clip != 0)
  67207. {
  67208. if (fillType.isColour())
  67209. {
  67210. Image::BitmapData destData (image, 0, 0, image.getWidth(), image.getHeight(), true);
  67211. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  67212. }
  67213. else
  67214. {
  67215. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  67216. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  67217. if (! clipped.isEmpty())
  67218. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  67219. }
  67220. }
  67221. }
  67222. void fillPath (Image& image, const Path& path, const AffineTransform& transform)
  67223. {
  67224. if (clip != 0)
  67225. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, transform.translated ((float) xOffset, (float) yOffset)), false);
  67226. }
  67227. void fillEdgeTable (Image& image, const EdgeTable& edgeTable, const float x, const int y)
  67228. {
  67229. if (clip != 0)
  67230. {
  67231. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  67232. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  67233. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  67234. fillShape (image, shapeToFill, false);
  67235. }
  67236. }
  67237. void fillShape (Image& image, SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  67238. {
  67239. jassert (clip != 0);
  67240. shapeToFill = clip->applyClipTo (shapeToFill);
  67241. if (shapeToFill != 0)
  67242. fillShapeWithoutClipping (image, shapeToFill, replaceContents);
  67243. }
  67244. void fillShapeWithoutClipping (Image& image, const SoftwareRendererClasses::ClipRegionBase::Ptr& shapeToFill, const bool replaceContents)
  67245. {
  67246. Image::BitmapData destData (image, 0, 0, image.getWidth(), image.getHeight(), true);
  67247. if (fillType.isGradient())
  67248. {
  67249. jassert (! replaceContents); // that option is just for solid colours
  67250. ColourGradient g2 (*(fillType.gradient));
  67251. g2.multiplyOpacity (fillType.getOpacity());
  67252. g2.x1 -= 0.5f; g2.y1 -= 0.5f;
  67253. g2.x2 -= 0.5f; g2.y2 -= 0.5f;
  67254. AffineTransform transform (fillType.transform.translated ((float) xOffset, (float) yOffset));
  67255. const bool isIdentity = transform.isOnlyTranslation();
  67256. if (isIdentity)
  67257. {
  67258. // If our translation doesn't involve any distortion, we can speed it up..
  67259. transform.transformPoint (g2.x1, g2.y1);
  67260. transform.transformPoint (g2.x2, g2.y2);
  67261. transform = AffineTransform::identity;
  67262. }
  67263. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  67264. }
  67265. else if (fillType.isTiledImage())
  67266. {
  67267. renderImage (image, *(fillType.image), fillType.image->getBounds(), fillType.transform, shapeToFill);
  67268. }
  67269. else
  67270. {
  67271. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  67272. }
  67273. }
  67274. void renderImage (Image& destImage, const Image& sourceImage, const Rectangle<int>& srcClip,
  67275. const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  67276. {
  67277. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  67278. const Image::BitmapData destData (destImage, 0, 0, destImage.getWidth(), destImage.getHeight(), true);
  67279. const Image::BitmapData srcData (sourceImage, srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  67280. const int alpha = fillType.colour.getAlpha();
  67281. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  67282. if (transform.isOnlyTranslation())
  67283. {
  67284. // If our translation doesn't involve any distortion, just use a simple blit..
  67285. int tx = (int) (transform.getTranslationX() * 256.0f);
  67286. int ty = (int) (transform.getTranslationY() * 256.0f);
  67287. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  67288. {
  67289. tx = ((tx + 128) >> 8);
  67290. ty = ((ty + 128) >> 8);
  67291. if (tiledFillClipRegion != 0)
  67292. {
  67293. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  67294. }
  67295. else
  67296. {
  67297. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, srcClip.getWidth(), srcClip.getHeight()).getIntersection (destImage.getBounds())));
  67298. c = clip->applyClipTo (c);
  67299. if (c != 0)
  67300. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  67301. }
  67302. return;
  67303. }
  67304. }
  67305. if (transform.isSingularity())
  67306. return;
  67307. if (tiledFillClipRegion != 0)
  67308. {
  67309. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  67310. }
  67311. else
  67312. {
  67313. Path p;
  67314. p.addRectangle (0.0f, 0.0f, (float) srcClip.getWidth(), (float) srcClip.getHeight());
  67315. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  67316. c = c->clipToPath (p, transform);
  67317. if (c != 0)
  67318. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  67319. }
  67320. }
  67321. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  67322. int xOffset, yOffset;
  67323. Font font;
  67324. FillType fillType;
  67325. Graphics::ResamplingQuality interpolationQuality;
  67326. private:
  67327. void cloneClipIfMultiplyReferenced()
  67328. {
  67329. if (clip->getReferenceCount() > 1)
  67330. clip = clip->clone();
  67331. }
  67332. SavedState& operator= (const SavedState&);
  67333. };
  67334. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (Image& image_)
  67335. : image (image_)
  67336. {
  67337. currentState = new SavedState (image_.getBounds(), 0, 0);
  67338. }
  67339. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (Image& image_, const int xOffset, const int yOffset,
  67340. const RectangleList& initialClip)
  67341. : image (image_)
  67342. {
  67343. currentState = new SavedState (initialClip, xOffset, yOffset);
  67344. }
  67345. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  67346. {
  67347. }
  67348. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  67349. {
  67350. return false;
  67351. }
  67352. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  67353. {
  67354. currentState->setOrigin (x, y);
  67355. }
  67356. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  67357. {
  67358. return currentState->clipToRectangle (r);
  67359. }
  67360. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  67361. {
  67362. return currentState->clipToRectangleList (clipRegion);
  67363. }
  67364. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  67365. {
  67366. currentState->excludeClipRectangle (r);
  67367. }
  67368. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  67369. {
  67370. currentState->clipToPath (path, transform);
  67371. }
  67372. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform)
  67373. {
  67374. currentState->clipToImageAlpha (sourceImage, srcClip, transform);
  67375. }
  67376. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  67377. {
  67378. return currentState->clipRegionIntersects (r);
  67379. }
  67380. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  67381. {
  67382. return currentState->getClipBounds();
  67383. }
  67384. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  67385. {
  67386. return currentState->clip == 0;
  67387. }
  67388. void LowLevelGraphicsSoftwareRenderer::saveState()
  67389. {
  67390. stateStack.add (new SavedState (*currentState));
  67391. }
  67392. void LowLevelGraphicsSoftwareRenderer::restoreState()
  67393. {
  67394. SavedState* const top = stateStack.getLast();
  67395. if (top != 0)
  67396. {
  67397. currentState = top;
  67398. stateStack.removeLast (1, false);
  67399. }
  67400. else
  67401. {
  67402. jassertfalse // trying to pop with an empty stack!
  67403. }
  67404. }
  67405. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  67406. {
  67407. currentState->fillType = fillType;
  67408. }
  67409. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  67410. {
  67411. currentState->fillType.setOpacity (newOpacity);
  67412. }
  67413. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  67414. {
  67415. currentState->interpolationQuality = quality;
  67416. }
  67417. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  67418. {
  67419. currentState->fillRect (image, r, replaceExistingContents);
  67420. }
  67421. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  67422. {
  67423. currentState->fillPath (image, path, transform);
  67424. }
  67425. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  67426. const AffineTransform& transform, const bool fillEntireClipAsTiles)
  67427. {
  67428. jassert (sourceImage.getBounds().contains (srcClip));
  67429. currentState->renderImage (image, sourceImage, srcClip, transform,
  67430. fillEntireClipAsTiles ? currentState->clip : 0);
  67431. }
  67432. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  67433. {
  67434. Path p;
  67435. p.addLineSegment (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY(), 1.0f);
  67436. fillPath (p, AffineTransform::identity);
  67437. }
  67438. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  67439. {
  67440. if (bottom > top)
  67441. currentState->fillRect (image, Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  67442. }
  67443. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  67444. {
  67445. if (right > left)
  67446. currentState->fillRect (image, Rectangle<float> (left, (float) y, right - left, 1.0f));
  67447. }
  67448. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  67449. {
  67450. public:
  67451. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  67452. ~CachedGlyph() {}
  67453. void draw (SavedState& state, Image& image, const float x, const float y) const
  67454. {
  67455. if (edgeTable != 0)
  67456. state.fillEdgeTable (image, *edgeTable, x, roundToInt (y));
  67457. }
  67458. void generate (const Font& newFont, const int glyphNumber)
  67459. {
  67460. font = newFont;
  67461. glyph = glyphNumber;
  67462. edgeTable = 0;
  67463. Path glyphPath;
  67464. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  67465. if (! glyphPath.isEmpty())
  67466. {
  67467. const float fontHeight = font.getHeight();
  67468. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  67469. .translated (0.0f, -0.5f));
  67470. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  67471. glyphPath, transform);
  67472. }
  67473. }
  67474. int glyph, lastAccessCount;
  67475. Font font;
  67476. juce_UseDebuggingNewOperator
  67477. private:
  67478. ScopedPointer <EdgeTable> edgeTable;
  67479. CachedGlyph (const CachedGlyph&);
  67480. CachedGlyph& operator= (const CachedGlyph&);
  67481. };
  67482. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  67483. {
  67484. public:
  67485. GlyphCache()
  67486. : accessCounter (0), hits (0), misses (0)
  67487. {
  67488. for (int i = 120; --i >= 0;)
  67489. glyphs.add (new CachedGlyph());
  67490. }
  67491. ~GlyphCache()
  67492. {
  67493. clearSingletonInstance();
  67494. }
  67495. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  67496. void drawGlyph (SavedState& state, Image& image, const Font& font, const int glyphNumber, float x, float y)
  67497. {
  67498. ++accessCounter;
  67499. int oldestCounter = std::numeric_limits<int>::max();
  67500. CachedGlyph* oldest = 0;
  67501. for (int i = glyphs.size(); --i >= 0;)
  67502. {
  67503. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  67504. if (glyph->glyph == glyphNumber && glyph->font == font)
  67505. {
  67506. ++hits;
  67507. glyph->lastAccessCount = accessCounter;
  67508. glyph->draw (state, image, x, y);
  67509. return;
  67510. }
  67511. if (glyph->lastAccessCount <= oldestCounter)
  67512. {
  67513. oldestCounter = glyph->lastAccessCount;
  67514. oldest = glyph;
  67515. }
  67516. }
  67517. if (hits + ++misses > (glyphs.size() << 4))
  67518. {
  67519. if (misses * 2 > hits)
  67520. {
  67521. for (int i = 32; --i >= 0;)
  67522. glyphs.add (new CachedGlyph());
  67523. }
  67524. hits = misses = 0;
  67525. oldest = glyphs.getLast();
  67526. }
  67527. jassert (oldest != 0);
  67528. oldest->lastAccessCount = accessCounter;
  67529. oldest->generate (font, glyphNumber);
  67530. oldest->draw (state, image, x, y);
  67531. }
  67532. juce_UseDebuggingNewOperator
  67533. private:
  67534. friend class OwnedArray <CachedGlyph>;
  67535. OwnedArray <CachedGlyph> glyphs;
  67536. int accessCounter, hits, misses;
  67537. GlyphCache (const GlyphCache&);
  67538. GlyphCache& operator= (const GlyphCache&);
  67539. };
  67540. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  67541. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  67542. {
  67543. currentState->font = newFont;
  67544. }
  67545. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  67546. {
  67547. return currentState->font;
  67548. }
  67549. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  67550. {
  67551. Font& f = currentState->font;
  67552. if (transform.isOnlyTranslation())
  67553. {
  67554. GlyphCache::getInstance()->drawGlyph (*currentState, image, f, glyphNumber,
  67555. transform.getTranslationX(),
  67556. transform.getTranslationY());
  67557. }
  67558. else
  67559. {
  67560. Path p;
  67561. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  67562. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  67563. }
  67564. }
  67565. #if JUCE_MSVC
  67566. #pragma warning (pop)
  67567. #if JUCE_DEBUG
  67568. #pragma optimize ("", on) // resets optimisations to the project defaults
  67569. #endif
  67570. #endif
  67571. END_JUCE_NAMESPACE
  67572. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  67573. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  67574. BEGIN_JUCE_NAMESPACE
  67575. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  67576. : flags (other.flags)
  67577. {
  67578. }
  67579. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  67580. {
  67581. flags = other.flags;
  67582. return *this;
  67583. }
  67584. void RectanglePlacement::applyTo (double& x, double& y,
  67585. double& w, double& h,
  67586. const double dx, const double dy,
  67587. const double dw, const double dh) const throw()
  67588. {
  67589. if (w == 0 || h == 0)
  67590. return;
  67591. if ((flags & stretchToFit) != 0)
  67592. {
  67593. x = dx;
  67594. y = dy;
  67595. w = dw;
  67596. h = dh;
  67597. }
  67598. else
  67599. {
  67600. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  67601. : jmin (dw / w, dh / h);
  67602. if ((flags & onlyReduceInSize) != 0)
  67603. scale = jmin (scale, 1.0);
  67604. if ((flags & onlyIncreaseInSize) != 0)
  67605. scale = jmax (scale, 1.0);
  67606. w *= scale;
  67607. h *= scale;
  67608. if ((flags & xLeft) != 0)
  67609. x = dx;
  67610. else if ((flags & xRight) != 0)
  67611. x = dx + dw - w;
  67612. else
  67613. x = dx + (dw - w) * 0.5;
  67614. if ((flags & yTop) != 0)
  67615. y = dy;
  67616. else if ((flags & yBottom) != 0)
  67617. y = dy + dh - h;
  67618. else
  67619. y = dy + (dh - h) * 0.5;
  67620. }
  67621. }
  67622. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  67623. float w, float h,
  67624. const float dx, const float dy,
  67625. const float dw, const float dh) const throw()
  67626. {
  67627. if (w == 0 || h == 0)
  67628. return AffineTransform::identity;
  67629. const float scaleX = dw / w;
  67630. const float scaleY = dh / h;
  67631. if ((flags & stretchToFit) != 0)
  67632. return AffineTransform::translation (-x, -y)
  67633. .scaled (scaleX, scaleY)
  67634. .translated (dx, dy);
  67635. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  67636. : jmin (scaleX, scaleY);
  67637. if ((flags & onlyReduceInSize) != 0)
  67638. scale = jmin (scale, 1.0f);
  67639. if ((flags & onlyIncreaseInSize) != 0)
  67640. scale = jmax (scale, 1.0f);
  67641. w *= scale;
  67642. h *= scale;
  67643. float newX = dx;
  67644. if ((flags & xRight) != 0)
  67645. newX += dw - w; // right
  67646. else if ((flags & xLeft) == 0)
  67647. newX += (dw - w) / 2.0f; // centre
  67648. float newY = dy;
  67649. if ((flags & yBottom) != 0)
  67650. newY += dh - h; // bottom
  67651. else if ((flags & yTop) == 0)
  67652. newY += (dh - h) / 2.0f; // centre
  67653. return AffineTransform::translation (-x, -y)
  67654. .scaled (scale, scale)
  67655. .translated (newX, newY);
  67656. }
  67657. END_JUCE_NAMESPACE
  67658. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  67659. /*** Start of inlined file: juce_Drawable.cpp ***/
  67660. BEGIN_JUCE_NAMESPACE
  67661. Drawable::RenderingContext::RenderingContext (Graphics& g_,
  67662. const AffineTransform& transform_,
  67663. const float opacity_) throw()
  67664. : g (g_),
  67665. transform (transform_),
  67666. opacity (opacity_)
  67667. {
  67668. }
  67669. Drawable::Drawable()
  67670. {
  67671. }
  67672. Drawable::~Drawable()
  67673. {
  67674. }
  67675. void Drawable::draw (Graphics& g, const float opacity,
  67676. const AffineTransform& transform) const
  67677. {
  67678. render (RenderingContext (g, transform, opacity));
  67679. }
  67680. void Drawable::drawAt (Graphics& g, const float x, const float y, const float opacity) const
  67681. {
  67682. draw (g, opacity, AffineTransform::translation (x, y));
  67683. }
  67684. void Drawable::drawWithin (Graphics& g,
  67685. const int destX,
  67686. const int destY,
  67687. const int destW,
  67688. const int destH,
  67689. const RectanglePlacement& placement,
  67690. const float opacity) const
  67691. {
  67692. if (destW > 0 && destH > 0)
  67693. {
  67694. Rectangle<float> bounds (getBounds());
  67695. draw (g, opacity,
  67696. placement.getTransformToFit (bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(),
  67697. (float) destX, (float) destY,
  67698. (float) destW, (float) destH));
  67699. }
  67700. }
  67701. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  67702. {
  67703. Drawable* result = 0;
  67704. Image* const image = ImageFileFormat::loadFrom (data, (int) numBytes);
  67705. if (image != 0)
  67706. {
  67707. DrawableImage* const di = new DrawableImage();
  67708. di->setImage (image, true);
  67709. result = di;
  67710. }
  67711. else
  67712. {
  67713. const String asString (String::createStringFromData (data, (int) numBytes));
  67714. XmlDocument doc (asString);
  67715. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  67716. if (outer != 0 && outer->hasTagName ("svg"))
  67717. {
  67718. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  67719. if (svg != 0)
  67720. result = Drawable::createFromSVG (*svg);
  67721. }
  67722. }
  67723. return result;
  67724. }
  67725. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  67726. {
  67727. MemoryBlock mb;
  67728. dataSource.readIntoMemoryBlock (mb);
  67729. return createFromImageData (mb.getData(), mb.getSize());
  67730. }
  67731. Drawable* Drawable::createFromImageFile (const File& file)
  67732. {
  67733. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  67734. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  67735. }
  67736. Drawable* Drawable::createFromValueTree (const ValueTree& tree)
  67737. {
  67738. Drawable* d = DrawablePath::createFromValueTree (tree);
  67739. if (d == 0)
  67740. {
  67741. d = DrawableComposite::createFromValueTree (tree);
  67742. if (d == 0)
  67743. {
  67744. d = DrawableImage::createFromValueTree (tree);
  67745. if (d == 0)
  67746. d = DrawableText::createFromValueTree (tree);
  67747. }
  67748. }
  67749. return d;
  67750. }
  67751. END_JUCE_NAMESPACE
  67752. /*** End of inlined file: juce_Drawable.cpp ***/
  67753. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  67754. BEGIN_JUCE_NAMESPACE
  67755. DrawableComposite::DrawableComposite()
  67756. {
  67757. }
  67758. DrawableComposite::~DrawableComposite()
  67759. {
  67760. }
  67761. void DrawableComposite::insertDrawable (Drawable* drawable,
  67762. const AffineTransform& transform,
  67763. const int index)
  67764. {
  67765. if (drawable != 0)
  67766. {
  67767. if (! drawables.contains (drawable))
  67768. {
  67769. drawables.insert (index, drawable);
  67770. if (transform.isIdentity())
  67771. transforms.insert (index, 0);
  67772. else
  67773. transforms.insert (index, new AffineTransform (transform));
  67774. }
  67775. else
  67776. {
  67777. jassertfalse // trying to add a drawable that's already in here!
  67778. }
  67779. }
  67780. }
  67781. void DrawableComposite::insertDrawable (const Drawable& drawable,
  67782. const AffineTransform& transform,
  67783. const int index)
  67784. {
  67785. insertDrawable (drawable.createCopy(), transform, index);
  67786. }
  67787. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  67788. {
  67789. drawables.remove (index, deleteDrawable);
  67790. transforms.remove (index);
  67791. }
  67792. void DrawableComposite::bringToFront (const int index)
  67793. {
  67794. if (index >= 0 && index < drawables.size() - 1)
  67795. {
  67796. drawables.move (index, -1);
  67797. transforms.move (index, -1);
  67798. }
  67799. }
  67800. void DrawableComposite::render (const Drawable::RenderingContext& context) const
  67801. {
  67802. if (drawables.size() > 0 && context.opacity > 0)
  67803. {
  67804. if (context.opacity >= 1.0f || drawables.size() == 1)
  67805. {
  67806. Drawable::RenderingContext contextCopy (context);
  67807. for (int i = 0; i < drawables.size(); ++i)
  67808. {
  67809. const AffineTransform* const t = transforms.getUnchecked(i);
  67810. contextCopy.transform = (t == 0) ? context.transform
  67811. : t->followedBy (context.transform);
  67812. drawables.getUnchecked(i)->render (contextCopy);
  67813. }
  67814. }
  67815. else
  67816. {
  67817. // To correctly render a whole composite layer with an overall transparency,
  67818. // we need to render everything opaquely into a temp buffer, then blend that
  67819. // with the target opacity...
  67820. const Rectangle<int> clipBounds (context.g.getClipBounds());
  67821. Image tempImage (Image::ARGB, clipBounds.getWidth(), clipBounds.getHeight(), true);
  67822. {
  67823. Graphics tempG (tempImage);
  67824. tempG.setOrigin (-clipBounds.getX(), -clipBounds.getY());
  67825. Drawable::RenderingContext tempContext (tempG, context.transform, 1.0f);
  67826. render (tempContext);
  67827. }
  67828. context.g.setOpacity (context.opacity);
  67829. context.g.drawImageAt (&tempImage, clipBounds.getX(), clipBounds.getY());
  67830. }
  67831. }
  67832. }
  67833. const Rectangle<float> DrawableComposite::getBounds() const
  67834. {
  67835. Rectangle<float> bounds;
  67836. for (int i = 0; i < drawables.size(); ++i)
  67837. {
  67838. const Drawable* const d = drawables.getUnchecked(i);
  67839. const AffineTransform* const t = transforms.getUnchecked(i);
  67840. const Rectangle<float> childBounds (t == 0 ? d->getBounds()
  67841. : d->getBounds().transformed (*t));
  67842. if (bounds.isEmpty())
  67843. bounds = childBounds;
  67844. else if (! childBounds.isEmpty())
  67845. bounds = bounds.getUnion (childBounds);
  67846. }
  67847. return bounds;
  67848. }
  67849. bool DrawableComposite::hitTest (float x, float y) const
  67850. {
  67851. for (int i = 0; i < drawables.size(); ++i)
  67852. {
  67853. float tx = x;
  67854. float ty = y;
  67855. const AffineTransform* const t = transforms.getUnchecked(i);
  67856. if (t != 0)
  67857. t->inverted().transformPoint (tx, ty);
  67858. if (drawables.getUnchecked(i)->hitTest (tx, ty))
  67859. return true;
  67860. }
  67861. return false;
  67862. }
  67863. Drawable* DrawableComposite::createCopy() const
  67864. {
  67865. DrawableComposite* const dc = new DrawableComposite();
  67866. for (int i = 0; i < drawables.size(); ++i)
  67867. {
  67868. dc->drawables.add (drawables.getUnchecked(i)->createCopy());
  67869. const AffineTransform* const t = transforms.getUnchecked(i);
  67870. dc->transforms.add (t != 0 ? new AffineTransform (*t) : 0);
  67871. }
  67872. return dc;
  67873. }
  67874. ValueTree DrawableComposite::createValueTree() const
  67875. {
  67876. ValueTree v ("Group");
  67877. if (getName().isNotEmpty())
  67878. v.setProperty ("id", getName(), 0);
  67879. for (int i = 0; i < drawables.size(); ++i)
  67880. {
  67881. Drawable* const d = drawables.getUnchecked(i);
  67882. ValueTree child (d->createValueTree());
  67883. AffineTransform* transform = transforms.getUnchecked(i);
  67884. if (transform != 0)
  67885. {
  67886. String t;
  67887. t << transform->mat00 << " " << transform->mat01 << " " << transform->mat02 << " "
  67888. << transform->mat10 << " " << transform->mat11 << " " << transform->mat12;
  67889. child.setProperty ("transform", t, 0);
  67890. }
  67891. v.addChild (child, -1, 0);
  67892. }
  67893. return v;
  67894. }
  67895. DrawableComposite* DrawableComposite::createFromValueTree (const ValueTree& tree)
  67896. {
  67897. if (! tree.hasType ("Group"))
  67898. return 0;
  67899. DrawableComposite* dc = new DrawableComposite();
  67900. dc->setName (tree ["id"]);
  67901. for (int i = 0; i < tree.getNumChildren(); ++i)
  67902. {
  67903. ValueTree childTree (tree.getChild (i));
  67904. Drawable* d = Drawable::createFromValueTree (childTree);
  67905. if (d != 0)
  67906. {
  67907. AffineTransform transform;
  67908. const String transformAtt (childTree ["transform"].toString());
  67909. if (transformAtt.isNotEmpty())
  67910. {
  67911. StringArray tokens;
  67912. tokens.addTokens (transformAtt.trim(), false);
  67913. tokens.removeEmptyStrings (true);
  67914. if (tokens.size() == 6)
  67915. {
  67916. float f[6];
  67917. for (int j = 0; j < 6; ++j)
  67918. f[j] = (float) tokens[j].getDoubleValue();
  67919. transform = AffineTransform (f[0], f[1], f[2], f[3], f[4], f[5]);
  67920. }
  67921. }
  67922. dc->insertDrawable (d, transform);
  67923. }
  67924. }
  67925. return dc;
  67926. }
  67927. END_JUCE_NAMESPACE
  67928. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  67929. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  67930. BEGIN_JUCE_NAMESPACE
  67931. DrawableImage::DrawableImage()
  67932. : image (0),
  67933. canDeleteImage (false),
  67934. opacity (1.0f),
  67935. overlayColour (0x00000000)
  67936. {
  67937. }
  67938. DrawableImage::~DrawableImage()
  67939. {
  67940. clearImage();
  67941. }
  67942. void DrawableImage::clearImage()
  67943. {
  67944. if (canDeleteImage && image != 0)
  67945. ImageCache::releaseOrDelete (image);
  67946. image = 0;
  67947. }
  67948. void DrawableImage::setImage (const Image& imageToCopy)
  67949. {
  67950. clearImage();
  67951. image = new Image (imageToCopy);
  67952. canDeleteImage = true;
  67953. }
  67954. void DrawableImage::setImage (Image* imageToUse,
  67955. const bool releaseWhenNotNeeded)
  67956. {
  67957. clearImage();
  67958. image = imageToUse;
  67959. canDeleteImage = releaseWhenNotNeeded;
  67960. }
  67961. void DrawableImage::setOpacity (const float newOpacity)
  67962. {
  67963. opacity = newOpacity;
  67964. }
  67965. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  67966. {
  67967. overlayColour = newOverlayColour;
  67968. }
  67969. void DrawableImage::render (const Drawable::RenderingContext& context) const
  67970. {
  67971. if (image != 0)
  67972. {
  67973. if (opacity > 0.0f && ! overlayColour.isOpaque())
  67974. {
  67975. context.g.setOpacity (context.opacity * opacity);
  67976. context.g.drawImageTransformed (image, image->getBounds(),
  67977. context.transform, false);
  67978. }
  67979. if (! overlayColour.isTransparent())
  67980. {
  67981. context.g.setColour (overlayColour.withMultipliedAlpha (context.opacity));
  67982. context.g.drawImageTransformed (image, image->getBounds(),
  67983. context.transform, true);
  67984. }
  67985. }
  67986. }
  67987. const Rectangle<float> DrawableImage::getBounds() const
  67988. {
  67989. if (image == 0)
  67990. return Rectangle<float>();
  67991. return Rectangle<float> (0, 0, (float) image->getWidth(), (float) image->getHeight());
  67992. }
  67993. bool DrawableImage::hitTest (float x, float y) const
  67994. {
  67995. return image != 0
  67996. && x >= 0.0f
  67997. && y >= 0.0f
  67998. && x < image->getWidth()
  67999. && y < image->getHeight()
  68000. && image->getPixelAt (roundToInt (x), roundToInt (y)).getAlpha() >= 127;
  68001. }
  68002. Drawable* DrawableImage::createCopy() const
  68003. {
  68004. DrawableImage* const di = new DrawableImage();
  68005. di->opacity = opacity;
  68006. di->overlayColour = overlayColour;
  68007. if (image != 0)
  68008. {
  68009. if ((! canDeleteImage) || ! ImageCache::isImageInCache (image))
  68010. {
  68011. di->setImage (*image);
  68012. }
  68013. else
  68014. {
  68015. ImageCache::incReferenceCount (image);
  68016. di->setImage (image, true);
  68017. }
  68018. }
  68019. return di;
  68020. }
  68021. ValueTree DrawableImage::createValueTree() const
  68022. {
  68023. ValueTree v ("Image");
  68024. if (getName().isNotEmpty())
  68025. v.setProperty ("id", getName(), 0);
  68026. if (opacity < 1.0f)
  68027. v.setProperty ("opacity", (double) opacity, 0);
  68028. if (! overlayColour.isTransparent())
  68029. v.setProperty ("overlay", String::toHexString ((int) overlayColour.getARGB()), 0);
  68030. if (image != 0)
  68031. {
  68032. MemoryOutputStream imageData;
  68033. PNGImageFormat pngFormat;
  68034. if (pngFormat.writeImageToStream (*image, imageData))
  68035. {
  68036. String base64 (MemoryBlock (imageData.getData(), imageData.getDataSize()).toBase64Encoding());
  68037. for (int i = (base64.length() & ~127); i >= 0; i -= 128)
  68038. base64 = base64.substring (0, i) + "\n" + base64.substring (i);
  68039. v.setProperty ("data", base64, 0);
  68040. }
  68041. }
  68042. return v;
  68043. }
  68044. DrawableImage* DrawableImage::createFromValueTree (const ValueTree& tree)
  68045. {
  68046. if (! tree.hasType ("Image"))
  68047. return 0;
  68048. DrawableImage* di = new DrawableImage();
  68049. di->setName (tree ["id"]);
  68050. di->opacity = tree.hasProperty ("opacity") ? (float) tree ["opacity"] : 1.0f;
  68051. di->overlayColour = Colour (tree ["overlay"].toString().getHexValue32());
  68052. MemoryBlock imageData;
  68053. if (imageData.fromBase64Encoding (tree ["data"]))
  68054. {
  68055. Image* const im = ImageFileFormat::loadFrom (imageData.getData(), (int) imageData.getSize());
  68056. if (im == 0)
  68057. return false;
  68058. di->setImage (im, true);
  68059. }
  68060. return di;
  68061. }
  68062. END_JUCE_NAMESPACE
  68063. /*** End of inlined file: juce_DrawableImage.cpp ***/
  68064. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  68065. BEGIN_JUCE_NAMESPACE
  68066. DrawablePath::DrawablePath()
  68067. : mainFill (Colours::black),
  68068. strokeFill (Colours::transparentBlack),
  68069. strokeType (0.0f)
  68070. {
  68071. }
  68072. DrawablePath::~DrawablePath()
  68073. {
  68074. }
  68075. void DrawablePath::setPath (const Path& newPath)
  68076. {
  68077. path = newPath;
  68078. updateOutline();
  68079. }
  68080. void DrawablePath::setFill (const FillType& newFill)
  68081. {
  68082. mainFill = newFill;
  68083. }
  68084. void DrawablePath::setStrokeFill (const FillType& newFill)
  68085. {
  68086. strokeFill = newFill;
  68087. }
  68088. void DrawablePath::setStrokeType (const PathStrokeType& newStrokeType)
  68089. {
  68090. strokeType = newStrokeType;
  68091. updateOutline();
  68092. }
  68093. void DrawablePath::setStrokeThickness (const float newThickness)
  68094. {
  68095. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  68096. }
  68097. void DrawablePath::render (const Drawable::RenderingContext& context) const
  68098. {
  68099. {
  68100. FillType f (mainFill);
  68101. if (f.isGradient())
  68102. f.gradient->multiplyOpacity (context.opacity);
  68103. f.transform = f.transform.followedBy (context.transform);
  68104. context.g.setFillType (f);
  68105. context.g.fillPath (path, context.transform);
  68106. }
  68107. if (strokeType.getStrokeThickness() > 0.0f)
  68108. {
  68109. FillType f (strokeFill);
  68110. if (f.isGradient())
  68111. f.gradient->multiplyOpacity (context.opacity);
  68112. f.transform = f.transform.followedBy (context.transform);
  68113. context.g.setFillType (f);
  68114. context.g.fillPath (stroke, context.transform);
  68115. }
  68116. }
  68117. void DrawablePath::updateOutline()
  68118. {
  68119. stroke.clear();
  68120. strokeType.createStrokedPath (stroke, path, AffineTransform::identity, 4.0f);
  68121. }
  68122. const Rectangle<float> DrawablePath::getBounds() const
  68123. {
  68124. if (strokeType.getStrokeThickness() > 0.0f)
  68125. return stroke.getBounds();
  68126. else
  68127. return path.getBounds();
  68128. }
  68129. bool DrawablePath::hitTest (float x, float y) const
  68130. {
  68131. return path.contains (x, y)
  68132. || stroke.contains (x, y);
  68133. }
  68134. Drawable* DrawablePath::createCopy() const
  68135. {
  68136. DrawablePath* const dp = new DrawablePath();
  68137. dp->path = path;
  68138. dp->stroke = stroke;
  68139. dp->mainFill = mainFill;
  68140. dp->strokeFill = strokeFill;
  68141. dp->strokeType = strokeType;
  68142. return dp;
  68143. }
  68144. static const FillType readFillTypeFromTree (const ValueTree& v)
  68145. {
  68146. const String type (v["type"].toString());
  68147. if (type.equalsIgnoreCase ("solid"))
  68148. {
  68149. const String colour (v ["colour"].toString());
  68150. return Colour (colour.isEmpty() ? (uint32) 0xff000000
  68151. : (uint32) colour.getHexValue32());
  68152. }
  68153. else if (type.equalsIgnoreCase ("gradient"))
  68154. {
  68155. ColourGradient g;
  68156. g.x1 = v["x1"];
  68157. g.y1 = v["y1"];
  68158. g.x2 = v["x2"];
  68159. g.y2 = v["y2"];
  68160. g.isRadial = v["radial"];
  68161. StringArray colours;
  68162. colours.addTokens (v["colours"].toString(), false);
  68163. for (int i = 0; i < colours.size() / 2; ++i)
  68164. g.addColour (colours[i * 2].getDoubleValue(),
  68165. Colour ((uint32) colours[i * 2 + 1].getHexValue32()));
  68166. return g;
  68167. }
  68168. jassertfalse
  68169. return FillType();
  68170. }
  68171. static ValueTree createTreeForFillType (const String& tagName, const FillType& fillType)
  68172. {
  68173. ValueTree v (tagName);
  68174. if (fillType.isColour())
  68175. {
  68176. v.setProperty ("type", "solid", 0);
  68177. v.setProperty ("colour", String::toHexString ((int) fillType.colour.getARGB()), 0);
  68178. }
  68179. else if (fillType.isGradient())
  68180. {
  68181. v.setProperty ("type", "gradient", 0);
  68182. v.setProperty ("x1", fillType.gradient->x1, 0);
  68183. v.setProperty ("y1", fillType.gradient->y1, 0);
  68184. v.setProperty ("x2", fillType.gradient->x2, 0);
  68185. v.setProperty ("y2", fillType.gradient->y2, 0);
  68186. v.setProperty ("radial", fillType.gradient->isRadial, 0);
  68187. String s;
  68188. for (int i = 0; i < fillType.gradient->getNumColours(); ++i)
  68189. s << " " << fillType.gradient->getColourPosition (i)
  68190. << " " << String::toHexString ((int) fillType.gradient->getColour(i).getARGB());
  68191. v.setProperty ("colours", s.trimStart(), 0);
  68192. }
  68193. else
  68194. {
  68195. jassertfalse //xxx
  68196. }
  68197. return v;
  68198. }
  68199. ValueTree DrawablePath::createValueTree() const
  68200. {
  68201. ValueTree v ("Path");
  68202. v.addChild (createTreeForFillType ("fill", mainFill), -1, 0);
  68203. v.addChild (createTreeForFillType ("stroke", strokeFill), -1, 0);
  68204. if (getName().isNotEmpty())
  68205. v.setProperty ("id", getName(), 0);
  68206. v.setProperty ("strokeWidth", (double) strokeType.getStrokeThickness(), 0);
  68207. v.setProperty ("jointStyle", strokeType.getJointStyle() == PathStrokeType::mitered
  68208. ? "miter" : (strokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), 0);
  68209. v.setProperty ("capStyle", strokeType.getEndStyle() == PathStrokeType::butt
  68210. ? "butt" : (strokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), 0);
  68211. v.setProperty ("path", path.toString(), 0);
  68212. return v;
  68213. }
  68214. DrawablePath* DrawablePath::createFromValueTree (const ValueTree& tree)
  68215. {
  68216. if (! tree.hasType ("Path"))
  68217. return 0;
  68218. DrawablePath* p = new DrawablePath();
  68219. p->setName (tree ["id"]);
  68220. p->mainFill = readFillTypeFromTree (tree.getChildWithName ("fill"));
  68221. p->strokeFill = readFillTypeFromTree (tree.getChildWithName ("stroke"));
  68222. const String jointStyle (tree ["jointStyle"].toString());
  68223. const String endStyle (tree ["capStyle"].toString());
  68224. p->strokeType
  68225. = PathStrokeType (tree ["strokeWidth"],
  68226. jointStyle.equalsIgnoreCase ("curved") ? PathStrokeType::curved
  68227. : (jointStyle.equalsIgnoreCase ("bevel") ? PathStrokeType::beveled
  68228. : PathStrokeType::mitered),
  68229. endStyle.equalsIgnoreCase ("square") ? PathStrokeType::square
  68230. : (endStyle.equalsIgnoreCase ("round") ? PathStrokeType::rounded
  68231. : PathStrokeType::butt));
  68232. p->path.clear();
  68233. p->path.restoreFromString (tree ["path"]);
  68234. p->updateOutline();
  68235. return p;
  68236. }
  68237. END_JUCE_NAMESPACE
  68238. /*** End of inlined file: juce_DrawablePath.cpp ***/
  68239. /*** Start of inlined file: juce_DrawableText.cpp ***/
  68240. BEGIN_JUCE_NAMESPACE
  68241. DrawableText::DrawableText()
  68242. : colour (Colours::white)
  68243. {
  68244. }
  68245. DrawableText::~DrawableText()
  68246. {
  68247. }
  68248. void DrawableText::setText (const GlyphArrangement& newText)
  68249. {
  68250. text = newText;
  68251. }
  68252. void DrawableText::setText (const String& newText, const Font& fontToUse)
  68253. {
  68254. text.clear();
  68255. text.addLineOfText (fontToUse, newText, 0.0f, 0.0f);
  68256. }
  68257. void DrawableText::setColour (const Colour& newColour)
  68258. {
  68259. colour = newColour;
  68260. }
  68261. void DrawableText::render (const Drawable::RenderingContext& context) const
  68262. {
  68263. context.g.setColour (colour.withMultipliedAlpha (context.opacity));
  68264. text.draw (context.g, context.transform);
  68265. }
  68266. const Rectangle<float> DrawableText::getBounds() const
  68267. {
  68268. return text.getBoundingBox (0, -1, false);
  68269. }
  68270. bool DrawableText::hitTest (float x, float y) const
  68271. {
  68272. return text.findGlyphIndexAt (x, y) >= 0;
  68273. }
  68274. Drawable* DrawableText::createCopy() const
  68275. {
  68276. DrawableText* const dt = new DrawableText();
  68277. dt->text = text;
  68278. dt->colour = colour;
  68279. return dt;
  68280. }
  68281. ValueTree DrawableText::createValueTree() const
  68282. {
  68283. ValueTree v ("Text");
  68284. if (getName().isNotEmpty())
  68285. v.setProperty ("id", getName(), 0);
  68286. jassertfalse // xxx not finished!
  68287. return v;
  68288. }
  68289. DrawableText* DrawableText::createFromValueTree (const ValueTree& tree)
  68290. {
  68291. if (! tree.hasType ("Text"))
  68292. return 0;
  68293. DrawableText* dt = new DrawableText();
  68294. dt->setName (tree ["id"]);
  68295. jassertfalse // xxx not finished!
  68296. return dt;
  68297. }
  68298. END_JUCE_NAMESPACE
  68299. /*** End of inlined file: juce_DrawableText.cpp ***/
  68300. /*** Start of inlined file: juce_SVGParser.cpp ***/
  68301. BEGIN_JUCE_NAMESPACE
  68302. class SVGState
  68303. {
  68304. public:
  68305. SVGState (const XmlElement* const topLevel)
  68306. : topLevelXml (topLevel),
  68307. elementX (0), elementY (0),
  68308. width (512), height (512),
  68309. viewBoxW (0), viewBoxH (0)
  68310. {
  68311. }
  68312. ~SVGState()
  68313. {
  68314. }
  68315. Drawable* parseSVGElement (const XmlElement& xml)
  68316. {
  68317. if (! xml.hasTagName ("svg"))
  68318. return 0;
  68319. DrawableComposite* const drawable = new DrawableComposite();
  68320. drawable->setName (xml.getStringAttribute ("id"));
  68321. SVGState newState (*this);
  68322. if (xml.hasAttribute ("transform"))
  68323. newState.addTransform (xml);
  68324. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  68325. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  68326. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  68327. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  68328. if (xml.hasAttribute ("viewBox"))
  68329. {
  68330. const String viewParams (xml.getStringAttribute ("viewBox"));
  68331. int i = 0;
  68332. float vx, vy, vw, vh;
  68333. if (parseCoords (viewParams, vx, vy, i, true)
  68334. && parseCoords (viewParams, vw, vh, i, true)
  68335. && vw > 0
  68336. && vh > 0)
  68337. {
  68338. newState.viewBoxW = vw;
  68339. newState.viewBoxH = vh;
  68340. int placementFlags = 0;
  68341. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  68342. if (aspect.containsIgnoreCase ("none"))
  68343. {
  68344. placementFlags = RectanglePlacement::stretchToFit;
  68345. }
  68346. else
  68347. {
  68348. if (aspect.containsIgnoreCase ("slice"))
  68349. placementFlags |= RectanglePlacement::fillDestination;
  68350. if (aspect.containsIgnoreCase ("xMin"))
  68351. placementFlags |= RectanglePlacement::xLeft;
  68352. else if (aspect.containsIgnoreCase ("xMax"))
  68353. placementFlags |= RectanglePlacement::xRight;
  68354. else
  68355. placementFlags |= RectanglePlacement::xMid;
  68356. if (aspect.containsIgnoreCase ("yMin"))
  68357. placementFlags |= RectanglePlacement::yTop;
  68358. else if (aspect.containsIgnoreCase ("yMax"))
  68359. placementFlags |= RectanglePlacement::yBottom;
  68360. else
  68361. placementFlags |= RectanglePlacement::yMid;
  68362. }
  68363. const RectanglePlacement placement (placementFlags);
  68364. newState.transform
  68365. = placement.getTransformToFit (vx, vy, vw, vh,
  68366. 0.0f, 0.0f, newState.width, newState.height)
  68367. .followedBy (newState.transform);
  68368. }
  68369. }
  68370. else
  68371. {
  68372. if (viewBoxW == 0)
  68373. newState.viewBoxW = newState.width;
  68374. if (viewBoxH == 0)
  68375. newState.viewBoxH = newState.height;
  68376. }
  68377. newState.parseSubElements (xml, drawable);
  68378. return drawable;
  68379. }
  68380. private:
  68381. const XmlElement* const topLevelXml;
  68382. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  68383. AffineTransform transform;
  68384. String cssStyleText;
  68385. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  68386. {
  68387. forEachXmlChildElement (xml, e)
  68388. {
  68389. Drawable* d = 0;
  68390. if (e->hasTagName ("g"))
  68391. d = parseGroupElement (*e);
  68392. else if (e->hasTagName ("svg"))
  68393. d = parseSVGElement (*e);
  68394. else if (e->hasTagName ("path"))
  68395. d = parsePath (*e);
  68396. else if (e->hasTagName ("rect"))
  68397. d = parseRect (*e);
  68398. else if (e->hasTagName ("circle"))
  68399. d = parseCircle (*e);
  68400. else if (e->hasTagName ("ellipse"))
  68401. d = parseEllipse (*e);
  68402. else if (e->hasTagName ("line"))
  68403. d = parseLine (*e);
  68404. else if (e->hasTagName ("polyline"))
  68405. d = parsePolygon (*e, true);
  68406. else if (e->hasTagName ("polygon"))
  68407. d = parsePolygon (*e, false);
  68408. else if (e->hasTagName ("text"))
  68409. d = parseText (*e);
  68410. else if (e->hasTagName ("switch"))
  68411. d = parseSwitch (*e);
  68412. else if (e->hasTagName ("style"))
  68413. parseCSSStyle (*e);
  68414. parentDrawable->insertDrawable (d);
  68415. }
  68416. }
  68417. DrawableComposite* parseSwitch (const XmlElement& xml)
  68418. {
  68419. const XmlElement* const group = xml.getChildByName ("g");
  68420. if (group != 0)
  68421. return parseGroupElement (*group);
  68422. return 0;
  68423. }
  68424. DrawableComposite* parseGroupElement (const XmlElement& xml)
  68425. {
  68426. DrawableComposite* const drawable = new DrawableComposite();
  68427. drawable->setName (xml.getStringAttribute ("id"));
  68428. if (xml.hasAttribute ("transform"))
  68429. {
  68430. SVGState newState (*this);
  68431. newState.addTransform (xml);
  68432. newState.parseSubElements (xml, drawable);
  68433. }
  68434. else
  68435. {
  68436. parseSubElements (xml, drawable);
  68437. }
  68438. return drawable;
  68439. }
  68440. Drawable* parsePath (const XmlElement& xml) const
  68441. {
  68442. const String d (xml.getStringAttribute ("d").trimStart());
  68443. Path path;
  68444. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  68445. path.setUsingNonZeroWinding (false);
  68446. int index = 0;
  68447. float lastX = 0, lastY = 0;
  68448. float lastX2 = 0, lastY2 = 0;
  68449. juce_wchar lastCommandChar = 0;
  68450. bool isRelative = true;
  68451. bool carryOn = true;
  68452. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  68453. while (d[index] != 0)
  68454. {
  68455. float x, y, x2, y2, x3, y3;
  68456. if (validCommandChars.containsChar (d[index]))
  68457. {
  68458. lastCommandChar = d [index++];
  68459. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  68460. }
  68461. switch (lastCommandChar)
  68462. {
  68463. case 'M':
  68464. case 'm':
  68465. case 'L':
  68466. case 'l':
  68467. if (parseCoords (d, x, y, index, false))
  68468. {
  68469. if (isRelative)
  68470. {
  68471. x += lastX;
  68472. y += lastY;
  68473. }
  68474. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  68475. {
  68476. path.startNewSubPath (x, y);
  68477. lastCommandChar = 'l';
  68478. }
  68479. else
  68480. path.lineTo (x, y);
  68481. lastX2 = lastX;
  68482. lastY2 = lastY;
  68483. lastX = x;
  68484. lastY = y;
  68485. }
  68486. else
  68487. {
  68488. ++index;
  68489. }
  68490. break;
  68491. case 'H':
  68492. case 'h':
  68493. if (parseCoord (d, x, index, false, true))
  68494. {
  68495. if (isRelative)
  68496. x += lastX;
  68497. path.lineTo (x, lastY);
  68498. lastX2 = lastX;
  68499. lastX = x;
  68500. }
  68501. else
  68502. {
  68503. ++index;
  68504. }
  68505. break;
  68506. case 'V':
  68507. case 'v':
  68508. if (parseCoord (d, y, index, false, false))
  68509. {
  68510. if (isRelative)
  68511. y += lastY;
  68512. path.lineTo (lastX, y);
  68513. lastY2 = lastY;
  68514. lastY = y;
  68515. }
  68516. else
  68517. {
  68518. ++index;
  68519. }
  68520. break;
  68521. case 'C':
  68522. case 'c':
  68523. if (parseCoords (d, x, y, index, false)
  68524. && parseCoords (d, x2, y2, index, false)
  68525. && parseCoords (d, x3, y3, index, false))
  68526. {
  68527. if (isRelative)
  68528. {
  68529. x += lastX;
  68530. y += lastY;
  68531. x2 += lastX;
  68532. y2 += lastY;
  68533. x3 += lastX;
  68534. y3 += lastY;
  68535. }
  68536. path.cubicTo (x, y, x2, y2, x3, y3);
  68537. lastX2 = x2;
  68538. lastY2 = y2;
  68539. lastX = x3;
  68540. lastY = y3;
  68541. }
  68542. else
  68543. {
  68544. ++index;
  68545. }
  68546. break;
  68547. case 'S':
  68548. case 's':
  68549. if (parseCoords (d, x, y, index, false)
  68550. && parseCoords (d, x3, y3, index, false))
  68551. {
  68552. if (isRelative)
  68553. {
  68554. x += lastX;
  68555. y += lastY;
  68556. x3 += lastX;
  68557. y3 += lastY;
  68558. }
  68559. x2 = lastX + (lastX - lastX2);
  68560. y2 = lastY + (lastY - lastY2);
  68561. path.cubicTo (x2, y2, x, y, x3, y3);
  68562. lastX2 = x;
  68563. lastY2 = y;
  68564. lastX = x3;
  68565. lastY = y3;
  68566. }
  68567. else
  68568. {
  68569. ++index;
  68570. }
  68571. break;
  68572. case 'Q':
  68573. case 'q':
  68574. if (parseCoords (d, x, y, index, false)
  68575. && parseCoords (d, x2, y2, index, false))
  68576. {
  68577. if (isRelative)
  68578. {
  68579. x += lastX;
  68580. y += lastY;
  68581. x2 += lastX;
  68582. y2 += lastY;
  68583. }
  68584. path.quadraticTo (x, y, x2, y2);
  68585. lastX2 = x;
  68586. lastY2 = y;
  68587. lastX = x2;
  68588. lastY = y2;
  68589. }
  68590. else
  68591. {
  68592. ++index;
  68593. }
  68594. break;
  68595. case 'T':
  68596. case 't':
  68597. if (parseCoords (d, x, y, index, false))
  68598. {
  68599. if (isRelative)
  68600. {
  68601. x += lastX;
  68602. y += lastY;
  68603. }
  68604. x2 = lastX + (lastX - lastX2);
  68605. y2 = lastY + (lastY - lastY2);
  68606. path.quadraticTo (x2, y2, x, y);
  68607. lastX2 = x2;
  68608. lastY2 = y2;
  68609. lastX = x;
  68610. lastY = y;
  68611. }
  68612. else
  68613. {
  68614. ++index;
  68615. }
  68616. break;
  68617. case 'A':
  68618. case 'a':
  68619. if (parseCoords (d, x, y, index, false))
  68620. {
  68621. String num;
  68622. if (parseNextNumber (d, num, index, false))
  68623. {
  68624. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  68625. if (parseNextNumber (d, num, index, false))
  68626. {
  68627. const bool largeArc = num.getIntValue() != 0;
  68628. if (parseNextNumber (d, num, index, false))
  68629. {
  68630. const bool sweep = num.getIntValue() != 0;
  68631. if (parseCoords (d, x2, y2, index, false))
  68632. {
  68633. if (isRelative)
  68634. {
  68635. x2 += lastX;
  68636. y2 += lastY;
  68637. }
  68638. if (lastX != x2 || lastY != y2)
  68639. {
  68640. double centreX, centreY, startAngle, deltaAngle;
  68641. double rx = x, ry = y;
  68642. endpointToCentreParameters (lastX, lastY, x2, y2,
  68643. angle, largeArc, sweep,
  68644. rx, ry, centreX, centreY,
  68645. startAngle, deltaAngle);
  68646. path.addCentredArc ((float) centreX, (float) centreY,
  68647. (float) rx, (float) ry,
  68648. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  68649. false);
  68650. path.lineTo (x2, y2);
  68651. }
  68652. lastX2 = lastX;
  68653. lastY2 = lastY;
  68654. lastX = x2;
  68655. lastY = y2;
  68656. }
  68657. }
  68658. }
  68659. }
  68660. }
  68661. else
  68662. {
  68663. ++index;
  68664. }
  68665. break;
  68666. case 'Z':
  68667. case 'z':
  68668. path.closeSubPath();
  68669. while (CharacterFunctions::isWhitespace (d [index]))
  68670. ++index;
  68671. break;
  68672. default:
  68673. carryOn = false;
  68674. break;
  68675. }
  68676. if (! carryOn)
  68677. break;
  68678. }
  68679. return parseShape (xml, path);
  68680. }
  68681. Drawable* parseRect (const XmlElement& xml) const
  68682. {
  68683. Path rect;
  68684. const bool hasRX = xml.hasAttribute ("rx");
  68685. const bool hasRY = xml.hasAttribute ("ry");
  68686. if (hasRX || hasRY)
  68687. {
  68688. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  68689. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  68690. if (! hasRX)
  68691. rx = ry;
  68692. else if (! hasRY)
  68693. ry = rx;
  68694. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  68695. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  68696. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  68697. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  68698. rx, ry);
  68699. }
  68700. else
  68701. {
  68702. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  68703. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  68704. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  68705. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  68706. }
  68707. return parseShape (xml, rect);
  68708. }
  68709. Drawable* parseCircle (const XmlElement& xml) const
  68710. {
  68711. Path circle;
  68712. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  68713. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  68714. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  68715. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  68716. return parseShape (xml, circle);
  68717. }
  68718. Drawable* parseEllipse (const XmlElement& xml) const
  68719. {
  68720. Path ellipse;
  68721. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  68722. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  68723. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  68724. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  68725. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  68726. return parseShape (xml, ellipse);
  68727. }
  68728. Drawable* parseLine (const XmlElement& xml) const
  68729. {
  68730. Path line;
  68731. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  68732. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  68733. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  68734. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  68735. line.startNewSubPath (x1, y1);
  68736. line.lineTo (x2, y2);
  68737. return parseShape (xml, line);
  68738. }
  68739. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  68740. {
  68741. const String points (xml.getStringAttribute ("points"));
  68742. Path path;
  68743. int index = 0;
  68744. float x, y;
  68745. if (parseCoords (points, x, y, index, true))
  68746. {
  68747. float firstX = x;
  68748. float firstY = y;
  68749. float lastX = 0, lastY = 0;
  68750. path.startNewSubPath (x, y);
  68751. while (parseCoords (points, x, y, index, true))
  68752. {
  68753. lastX = x;
  68754. lastY = y;
  68755. path.lineTo (x, y);
  68756. }
  68757. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  68758. path.closeSubPath();
  68759. }
  68760. return parseShape (xml, path);
  68761. }
  68762. Drawable* parseShape (const XmlElement& xml, Path& path,
  68763. const bool shouldParseTransform = true) const
  68764. {
  68765. if (shouldParseTransform && xml.hasAttribute ("transform"))
  68766. {
  68767. SVGState newState (*this);
  68768. newState.addTransform (xml);
  68769. return newState.parseShape (xml, path, false);
  68770. }
  68771. DrawablePath* dp = new DrawablePath();
  68772. dp->setName (xml.getStringAttribute ("id"));
  68773. dp->setFill (Colours::transparentBlack);
  68774. path.applyTransform (transform);
  68775. dp->setPath (path);
  68776. Path::Iterator iter (path);
  68777. bool containsClosedSubPath = false;
  68778. while (iter.next())
  68779. {
  68780. if (iter.elementType == Path::Iterator::closePath)
  68781. {
  68782. containsClosedSubPath = true;
  68783. break;
  68784. }
  68785. }
  68786. dp->setFill (getPathFillType (path,
  68787. getStyleAttribute (&xml, "fill"),
  68788. getStyleAttribute (&xml, "fill-opacity"),
  68789. getStyleAttribute (&xml, "opacity"),
  68790. containsClosedSubPath ? Colours::black
  68791. : Colours::transparentBlack));
  68792. const String strokeType (getStyleAttribute (&xml, "stroke"));
  68793. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  68794. {
  68795. dp->setStrokeFill (getPathFillType (path, strokeType,
  68796. getStyleAttribute (&xml, "stroke-opacity"),
  68797. getStyleAttribute (&xml, "opacity"),
  68798. Colours::transparentBlack));
  68799. dp->setStrokeType (getStrokeFor (&xml));
  68800. }
  68801. return dp;
  68802. }
  68803. const XmlElement* findLinkedElement (const XmlElement* e) const
  68804. {
  68805. const String id (e->getStringAttribute ("xlink:href"));
  68806. if (! id.startsWithChar ('#'))
  68807. return 0;
  68808. return findElementForId (topLevelXml, id.substring (1));
  68809. }
  68810. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  68811. {
  68812. if (fillXml == 0)
  68813. return;
  68814. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  68815. {
  68816. int index = 0;
  68817. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  68818. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  68819. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  68820. double offset = e->getDoubleAttribute ("offset");
  68821. if (e->getStringAttribute ("offset").containsChar ('%'))
  68822. offset *= 0.01;
  68823. cg.addColour (jlimit (0.0, 1.0, offset), col);
  68824. }
  68825. }
  68826. const FillType getPathFillType (const Path& path,
  68827. const String& fill,
  68828. const String& fillOpacity,
  68829. const String& overallOpacity,
  68830. const Colour& defaultColour) const
  68831. {
  68832. float opacity = 1.0f;
  68833. if (overallOpacity.isNotEmpty())
  68834. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  68835. if (fillOpacity.isNotEmpty())
  68836. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  68837. if (fill.startsWithIgnoreCase ("url"))
  68838. {
  68839. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  68840. .upToLastOccurrenceOf (")", false, false).trim());
  68841. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  68842. if (fillXml != 0
  68843. && (fillXml->hasTagName ("linearGradient")
  68844. || fillXml->hasTagName ("radialGradient")))
  68845. {
  68846. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  68847. ColourGradient gradient;
  68848. addGradientStopsIn (gradient, inheritedFrom);
  68849. addGradientStopsIn (gradient, fillXml);
  68850. if (gradient.getNumColours() > 0)
  68851. {
  68852. gradient.addColour (0.0, gradient.getColour (0));
  68853. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  68854. }
  68855. else
  68856. {
  68857. gradient.addColour (0.0, Colours::black);
  68858. gradient.addColour (1.0, Colours::black);
  68859. }
  68860. if (overallOpacity.isNotEmpty())
  68861. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  68862. jassert (gradient.getNumColours() > 0);
  68863. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  68864. float gradientWidth = viewBoxW;
  68865. float gradientHeight = viewBoxH;
  68866. float dx = 0.0f;
  68867. float dy = 0.0f;
  68868. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  68869. if (! userSpace)
  68870. {
  68871. const Rectangle<float> bounds (path.getBounds());
  68872. dx = bounds.getX();
  68873. dy = bounds.getY();
  68874. gradientWidth = bounds.getWidth();
  68875. gradientHeight = bounds.getHeight();
  68876. }
  68877. if (gradient.isRadial)
  68878. {
  68879. gradient.x1 = dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth);
  68880. gradient.y1 = dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight);
  68881. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  68882. gradient.x2 = gradient.x1 + radius;
  68883. gradient.y2 = gradient.y1;
  68884. //xxx (the fx, fy focal point isn't handled properly here..)
  68885. }
  68886. else
  68887. {
  68888. gradient.x1 = dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth);
  68889. gradient.y1 = dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight);
  68890. gradient.x2 = dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth);
  68891. gradient.y2 = dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight);
  68892. if (gradient.x1 == gradient.x2 && gradient.y1 == gradient.y2)
  68893. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  68894. }
  68895. FillType type (gradient);
  68896. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  68897. .followedBy (transform);
  68898. return type;
  68899. }
  68900. }
  68901. if (fill.equalsIgnoreCase ("none"))
  68902. return Colours::transparentBlack;
  68903. int i = 0;
  68904. const Colour colour (parseColour (fill, i, defaultColour));
  68905. return colour.withMultipliedAlpha (opacity);
  68906. }
  68907. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  68908. {
  68909. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  68910. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  68911. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  68912. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  68913. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  68914. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  68915. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  68916. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  68917. if (join.equalsIgnoreCase ("round"))
  68918. joinStyle = PathStrokeType::curved;
  68919. else if (join.equalsIgnoreCase ("bevel"))
  68920. joinStyle = PathStrokeType::beveled;
  68921. if (cap.equalsIgnoreCase ("round"))
  68922. capStyle = PathStrokeType::rounded;
  68923. else if (cap.equalsIgnoreCase ("square"))
  68924. capStyle = PathStrokeType::square;
  68925. float ox = 0.0f, oy = 0.0f;
  68926. transform.transformPoint (ox, oy);
  68927. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  68928. transform.transformPoint (x, y);
  68929. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  68930. joinStyle, capStyle);
  68931. }
  68932. Drawable* parseText (const XmlElement& xml)
  68933. {
  68934. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  68935. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  68936. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  68937. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  68938. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  68939. //xxx not done text yet!
  68940. forEachXmlChildElement (xml, e)
  68941. {
  68942. if (e->isTextElement())
  68943. {
  68944. const String text (e->getText());
  68945. Path path;
  68946. Drawable* s = parseShape (*e, path);
  68947. delete s;
  68948. }
  68949. else if (e->hasTagName ("tspan"))
  68950. {
  68951. Drawable* s = parseText (*e);
  68952. delete s;
  68953. }
  68954. }
  68955. return 0;
  68956. }
  68957. void addTransform (const XmlElement& xml)
  68958. {
  68959. transform = parseTransform (xml.getStringAttribute ("transform"))
  68960. .followedBy (transform);
  68961. }
  68962. bool parseCoord (const String& s, float& value, int& index,
  68963. const bool allowUnits, const bool isX) const
  68964. {
  68965. String number;
  68966. if (! parseNextNumber (s, number, index, allowUnits))
  68967. {
  68968. value = 0;
  68969. return false;
  68970. }
  68971. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  68972. return true;
  68973. }
  68974. bool parseCoords (const String& s, float& x, float& y,
  68975. int& index, const bool allowUnits) const
  68976. {
  68977. return parseCoord (s, x, index, allowUnits, true)
  68978. && parseCoord (s, y, index, allowUnits, false);
  68979. }
  68980. float getCoordLength (const String& s, const float sizeForProportions) const
  68981. {
  68982. float n = s.getFloatValue();
  68983. const int len = s.length();
  68984. if (len > 2)
  68985. {
  68986. const float dpi = 96.0f;
  68987. const juce_wchar n1 = s [len - 2];
  68988. const juce_wchar n2 = s [len - 1];
  68989. if (n1 == 'i' && n2 == 'n')
  68990. n *= dpi;
  68991. else if (n1 == 'm' && n2 == 'm')
  68992. n *= dpi / 25.4f;
  68993. else if (n1 == 'c' && n2 == 'm')
  68994. n *= dpi / 2.54f;
  68995. else if (n1 == 'p' && n2 == 'c')
  68996. n *= 15.0f;
  68997. else if (n2 == '%')
  68998. n *= 0.01f * sizeForProportions;
  68999. }
  69000. return n;
  69001. }
  69002. void getCoordList (Array <float>& coords, const String& list,
  69003. const bool allowUnits, const bool isX) const
  69004. {
  69005. int index = 0;
  69006. float value;
  69007. while (parseCoord (list, value, index, allowUnits, isX))
  69008. coords.add (value);
  69009. }
  69010. void parseCSSStyle (const XmlElement& xml)
  69011. {
  69012. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  69013. }
  69014. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  69015. const String& defaultValue = String::empty) const
  69016. {
  69017. if (xml->hasAttribute (attributeName))
  69018. return xml->getStringAttribute (attributeName, defaultValue);
  69019. const String styleAtt (xml->getStringAttribute ("style"));
  69020. if (styleAtt.isNotEmpty())
  69021. {
  69022. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  69023. if (value.isNotEmpty())
  69024. return value;
  69025. }
  69026. else if (xml->hasAttribute ("class"))
  69027. {
  69028. const String className ("." + xml->getStringAttribute ("class"));
  69029. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  69030. if (index < 0)
  69031. index = cssStyleText.indexOfIgnoreCase (className + "{");
  69032. if (index >= 0)
  69033. {
  69034. const int openBracket = cssStyleText.indexOfChar (index, '{');
  69035. if (openBracket > index)
  69036. {
  69037. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  69038. if (closeBracket > openBracket)
  69039. {
  69040. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  69041. if (value.isNotEmpty())
  69042. return value;
  69043. }
  69044. }
  69045. }
  69046. }
  69047. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  69048. if (xml != 0)
  69049. return getStyleAttribute (xml, attributeName, defaultValue);
  69050. return defaultValue;
  69051. }
  69052. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  69053. {
  69054. if (xml->hasAttribute (attributeName))
  69055. return xml->getStringAttribute (attributeName);
  69056. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  69057. if (xml != 0)
  69058. return getInheritedAttribute (xml, attributeName);
  69059. return String::empty;
  69060. }
  69061. static bool isIdentifierChar (const juce_wchar c)
  69062. {
  69063. return CharacterFunctions::isLetter (c) || c == '-';
  69064. }
  69065. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  69066. {
  69067. int i = 0;
  69068. for (;;)
  69069. {
  69070. i = list.indexOf (i, attributeName);
  69071. if (i < 0)
  69072. break;
  69073. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  69074. && ! isIdentifierChar (list [i + attributeName.length()]))
  69075. {
  69076. i = list.indexOfChar (i, ':');
  69077. if (i < 0)
  69078. break;
  69079. int end = list.indexOfChar (i, ';');
  69080. if (end < 0)
  69081. end = 0x7ffff;
  69082. return list.substring (i + 1, end).trim();
  69083. }
  69084. ++i;
  69085. }
  69086. return defaultValue;
  69087. }
  69088. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  69089. {
  69090. const juce_wchar* const s = source;
  69091. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  69092. ++index;
  69093. int start = index;
  69094. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  69095. ++index;
  69096. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  69097. ++index;
  69098. if ((s[index] == 'e' || s[index] == 'E')
  69099. && (CharacterFunctions::isDigit (s[index + 1])
  69100. || s[index + 1] == '-'
  69101. || s[index + 1] == '+'))
  69102. {
  69103. index += 2;
  69104. while (CharacterFunctions::isDigit (s[index]))
  69105. ++index;
  69106. }
  69107. if (allowUnits)
  69108. {
  69109. while (CharacterFunctions::isLetter (s[index]))
  69110. ++index;
  69111. }
  69112. if (index == start)
  69113. return false;
  69114. value = String (s + start, index - start);
  69115. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  69116. ++index;
  69117. return true;
  69118. }
  69119. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  69120. {
  69121. if (s [index] == '#')
  69122. {
  69123. uint32 hex [6];
  69124. zeromem (hex, sizeof (hex));
  69125. int numChars = 0;
  69126. for (int i = 6; --i >= 0;)
  69127. {
  69128. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  69129. if (hexValue >= 0)
  69130. hex [numChars++] = hexValue;
  69131. else
  69132. break;
  69133. }
  69134. if (numChars <= 3)
  69135. return Colour ((uint8) (hex [0] * 0x11),
  69136. (uint8) (hex [1] * 0x11),
  69137. (uint8) (hex [2] * 0x11));
  69138. else
  69139. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  69140. (uint8) ((hex [2] << 4) + hex [3]),
  69141. (uint8) ((hex [4] << 4) + hex [5]));
  69142. }
  69143. else if (s [index] == 'r'
  69144. && s [index + 1] == 'g'
  69145. && s [index + 2] == 'b')
  69146. {
  69147. const int openBracket = s.indexOfChar (index, '(');
  69148. const int closeBracket = s.indexOfChar (openBracket, ')');
  69149. if (openBracket >= 3 && closeBracket > openBracket)
  69150. {
  69151. index = closeBracket;
  69152. StringArray tokens;
  69153. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  69154. tokens.trim();
  69155. tokens.removeEmptyStrings();
  69156. if (tokens[0].containsChar ('%'))
  69157. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  69158. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  69159. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  69160. else
  69161. return Colour ((uint8) tokens[0].getIntValue(),
  69162. (uint8) tokens[1].getIntValue(),
  69163. (uint8) tokens[2].getIntValue());
  69164. }
  69165. }
  69166. return Colours::findColourForName (s, defaultColour);
  69167. }
  69168. static const AffineTransform parseTransform (String t)
  69169. {
  69170. AffineTransform result;
  69171. while (t.isNotEmpty())
  69172. {
  69173. StringArray tokens;
  69174. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  69175. .upToFirstOccurrenceOf (")", false, false),
  69176. ", ", String::empty);
  69177. tokens.removeEmptyStrings (true);
  69178. float numbers [6];
  69179. for (int i = 0; i < 6; ++i)
  69180. numbers[i] = tokens[i].getFloatValue();
  69181. AffineTransform trans;
  69182. if (t.startsWithIgnoreCase ("matrix"))
  69183. {
  69184. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  69185. numbers[1], numbers[3], numbers[5]);
  69186. }
  69187. else if (t.startsWithIgnoreCase ("translate"))
  69188. {
  69189. jassert (tokens.size() == 2);
  69190. trans = AffineTransform::translation (numbers[0], numbers[1]);
  69191. }
  69192. else if (t.startsWithIgnoreCase ("scale"))
  69193. {
  69194. if (tokens.size() == 1)
  69195. trans = AffineTransform::scale (numbers[0], numbers[0]);
  69196. else
  69197. trans = AffineTransform::scale (numbers[0], numbers[1]);
  69198. }
  69199. else if (t.startsWithIgnoreCase ("rotate"))
  69200. {
  69201. if (tokens.size() != 3)
  69202. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  69203. else
  69204. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  69205. numbers[1], numbers[2]);
  69206. }
  69207. else if (t.startsWithIgnoreCase ("skewX"))
  69208. {
  69209. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  69210. 0.0f, 1.0f, 0.0f);
  69211. }
  69212. else if (t.startsWithIgnoreCase ("skewY"))
  69213. {
  69214. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  69215. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  69216. }
  69217. result = trans.followedBy (result);
  69218. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  69219. }
  69220. return result;
  69221. }
  69222. static void endpointToCentreParameters (const double x1, const double y1,
  69223. const double x2, const double y2,
  69224. const double angle,
  69225. const bool largeArc, const bool sweep,
  69226. double& rx, double& ry,
  69227. double& centreX, double& centreY,
  69228. double& startAngle, double& deltaAngle)
  69229. {
  69230. const double midX = (x1 - x2) * 0.5;
  69231. const double midY = (y1 - y2) * 0.5;
  69232. const double cosAngle = cos (angle);
  69233. const double sinAngle = sin (angle);
  69234. const double xp = cosAngle * midX + sinAngle * midY;
  69235. const double yp = cosAngle * midY - sinAngle * midX;
  69236. const double xp2 = xp * xp;
  69237. const double yp2 = yp * yp;
  69238. double rx2 = rx * rx;
  69239. double ry2 = ry * ry;
  69240. const double s = (xp2 / rx2) + (yp2 / ry2);
  69241. double c;
  69242. if (s <= 1.0)
  69243. {
  69244. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  69245. / (( rx2 * yp2) + (ry2 * xp2))));
  69246. if (largeArc == sweep)
  69247. c = -c;
  69248. }
  69249. else
  69250. {
  69251. const double s2 = std::sqrt (s);
  69252. rx *= s2;
  69253. ry *= s2;
  69254. rx2 = rx * rx;
  69255. ry2 = ry * ry;
  69256. c = 0;
  69257. }
  69258. const double cpx = ((rx * yp) / ry) * c;
  69259. const double cpy = ((-ry * xp) / rx) * c;
  69260. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  69261. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  69262. const double ux = (xp - cpx) / rx;
  69263. const double uy = (yp - cpy) / ry;
  69264. const double vx = (-xp - cpx) / rx;
  69265. const double vy = (-yp - cpy) / ry;
  69266. const double length = juce_hypot (ux, uy);
  69267. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  69268. if (uy < 0)
  69269. startAngle = -startAngle;
  69270. startAngle += double_Pi * 0.5;
  69271. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  69272. / (length * juce_hypot (vx, vy))));
  69273. if ((ux * vy) - (uy * vx) < 0)
  69274. deltaAngle = -deltaAngle;
  69275. if (sweep)
  69276. {
  69277. if (deltaAngle < 0)
  69278. deltaAngle += double_Pi * 2.0;
  69279. }
  69280. else
  69281. {
  69282. if (deltaAngle > 0)
  69283. deltaAngle -= double_Pi * 2.0;
  69284. }
  69285. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  69286. }
  69287. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  69288. {
  69289. forEachXmlChildElement (*parent, e)
  69290. {
  69291. if (e->compareAttribute ("id", id))
  69292. return e;
  69293. const XmlElement* const found = findElementForId (e, id);
  69294. if (found != 0)
  69295. return found;
  69296. }
  69297. return 0;
  69298. }
  69299. SVGState& operator= (const SVGState&);
  69300. };
  69301. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  69302. {
  69303. SVGState state (&svgDocument);
  69304. return state.parseSVGElement (svgDocument);
  69305. }
  69306. END_JUCE_NAMESPACE
  69307. /*** End of inlined file: juce_SVGParser.cpp ***/
  69308. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  69309. BEGIN_JUCE_NAMESPACE
  69310. #if JUCE_MSVC && JUCE_DEBUG
  69311. #pragma optimize ("t", on)
  69312. #endif
  69313. DropShadowEffect::DropShadowEffect()
  69314. : offsetX (0),
  69315. offsetY (0),
  69316. radius (4),
  69317. opacity (0.6f)
  69318. {
  69319. }
  69320. DropShadowEffect::~DropShadowEffect()
  69321. {
  69322. }
  69323. void DropShadowEffect::setShadowProperties (const float newRadius,
  69324. const float newOpacity,
  69325. const int newShadowOffsetX,
  69326. const int newShadowOffsetY)
  69327. {
  69328. radius = jmax (1.1f, newRadius);
  69329. offsetX = newShadowOffsetX;
  69330. offsetY = newShadowOffsetY;
  69331. opacity = newOpacity;
  69332. }
  69333. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  69334. {
  69335. const int w = image.getWidth();
  69336. const int h = image.getHeight();
  69337. Image shadowImage (Image::SingleChannel, w, h, false);
  69338. const Image::BitmapData srcData (image, 0, 0, w, h);
  69339. const Image::BitmapData destData (shadowImage, 0, 0, w, h, true);
  69340. const int filter = roundToInt (63.0f / radius);
  69341. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  69342. for (int x = w; --x >= 0;)
  69343. {
  69344. int shadowAlpha = 0;
  69345. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  69346. uint8* shadowPix = destData.data + x;
  69347. for (int y = h; --y >= 0;)
  69348. {
  69349. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  69350. *shadowPix = (uint8) shadowAlpha;
  69351. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  69352. shadowPix += destData.lineStride;
  69353. }
  69354. }
  69355. for (int y = h; --y >= 0;)
  69356. {
  69357. int shadowAlpha = 0;
  69358. uint8* shadowPix = destData.getLinePointer (y);
  69359. for (int x = w; --x >= 0;)
  69360. {
  69361. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  69362. *shadowPix++ = (uint8) shadowAlpha;
  69363. }
  69364. }
  69365. g.setColour (Colours::black.withAlpha (opacity));
  69366. g.drawImageAt (&shadowImage, offsetX, offsetY, true);
  69367. g.setOpacity (1.0f);
  69368. g.drawImageAt (&image, 0, 0);
  69369. }
  69370. #if JUCE_MSVC && JUCE_DEBUG
  69371. #pragma optimize ("", on) // resets optimisations to the project defaults
  69372. #endif
  69373. END_JUCE_NAMESPACE
  69374. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  69375. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  69376. BEGIN_JUCE_NAMESPACE
  69377. GlowEffect::GlowEffect()
  69378. : radius (2.0f),
  69379. colour (Colours::white)
  69380. {
  69381. }
  69382. GlowEffect::~GlowEffect()
  69383. {
  69384. }
  69385. void GlowEffect::setGlowProperties (const float newRadius,
  69386. const Colour& newColour)
  69387. {
  69388. radius = newRadius;
  69389. colour = newColour;
  69390. }
  69391. void GlowEffect::applyEffect (Image& image, Graphics& g)
  69392. {
  69393. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  69394. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  69395. blurKernel.createGaussianBlur (radius);
  69396. blurKernel.rescaleAllValues (radius);
  69397. blurKernel.applyToImage (temp, &image, image.getBounds());
  69398. g.setColour (colour);
  69399. g.drawImageAt (&temp, 0, 0, true);
  69400. g.setOpacity (1.0f);
  69401. g.drawImageAt (&image, 0, 0, false);
  69402. }
  69403. END_JUCE_NAMESPACE
  69404. /*** End of inlined file: juce_GlowEffect.cpp ***/
  69405. /*** Start of inlined file: juce_ReduceOpacityEffect.cpp ***/
  69406. BEGIN_JUCE_NAMESPACE
  69407. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  69408. : opacity (opacity_)
  69409. {
  69410. }
  69411. ReduceOpacityEffect::~ReduceOpacityEffect()
  69412. {
  69413. }
  69414. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  69415. {
  69416. opacity = jlimit (0.0f, 1.0f, newOpacity);
  69417. }
  69418. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  69419. {
  69420. g.setOpacity (opacity);
  69421. g.drawImageAt (&image, 0, 0);
  69422. }
  69423. END_JUCE_NAMESPACE
  69424. /*** End of inlined file: juce_ReduceOpacityEffect.cpp ***/
  69425. /*** Start of inlined file: juce_Font.cpp ***/
  69426. BEGIN_JUCE_NAMESPACE
  69427. namespace FontValues
  69428. {
  69429. static float limitFontHeight (const float height) throw()
  69430. {
  69431. return jlimit (0.1f, 10000.0f, height);
  69432. }
  69433. static const float defaultFontHeight = 14.0f;
  69434. static String fallbackFont;
  69435. }
  69436. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const float horizontalScale_,
  69437. const float kerning_, const float ascent_, const int styleFlags_,
  69438. Typeface* const typeface_) throw()
  69439. : typefaceName (typefaceName_),
  69440. height (height_),
  69441. horizontalScale (horizontalScale_),
  69442. kerning (kerning_),
  69443. ascent (ascent_),
  69444. styleFlags (styleFlags_),
  69445. typeface (typeface_)
  69446. {
  69447. }
  69448. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  69449. : typefaceName (other.typefaceName),
  69450. height (other.height),
  69451. horizontalScale (other.horizontalScale),
  69452. kerning (other.kerning),
  69453. ascent (other.ascent),
  69454. styleFlags (other.styleFlags),
  69455. typeface (other.typeface)
  69456. {
  69457. }
  69458. Font::Font() throw()
  69459. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::defaultFontHeight,
  69460. 1.0f, 0, 0, Font::plain, 0))
  69461. {
  69462. }
  69463. Font::Font (const float fontHeight, const int styleFlags_) throw()
  69464. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::limitFontHeight (fontHeight),
  69465. 1.0f, 0, 0, styleFlags_, 0))
  69466. {
  69467. }
  69468. Font::Font (const String& typefaceName_,
  69469. const float fontHeight,
  69470. const int styleFlags_) throw()
  69471. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight),
  69472. 1.0f, 0, 0, styleFlags_, 0))
  69473. {
  69474. }
  69475. Font::Font (const Font& other) throw()
  69476. : font (other.font)
  69477. {
  69478. }
  69479. Font& Font::operator= (const Font& other) throw()
  69480. {
  69481. font = other.font;
  69482. return *this;
  69483. }
  69484. Font::~Font() throw()
  69485. {
  69486. }
  69487. Font::Font (const Typeface::Ptr& typeface) throw()
  69488. : font (new SharedFontInternal (typeface->getName(), FontValues::defaultFontHeight,
  69489. 1.0f, 0, 0, Font::plain, typeface))
  69490. {
  69491. }
  69492. bool Font::operator== (const Font& other) const throw()
  69493. {
  69494. return font == other.font
  69495. || (font->height == other.font->height
  69496. && font->styleFlags == other.font->styleFlags
  69497. && font->horizontalScale == other.font->horizontalScale
  69498. && font->kerning == other.font->kerning
  69499. && font->typefaceName == other.font->typefaceName);
  69500. }
  69501. bool Font::operator!= (const Font& other) const throw()
  69502. {
  69503. return ! operator== (other);
  69504. }
  69505. void Font::dupeInternalIfShared() throw()
  69506. {
  69507. if (font->getReferenceCount() > 1)
  69508. font = new SharedFontInternal (*font);
  69509. }
  69510. const String Font::getDefaultSansSerifFontName() throw()
  69511. {
  69512. static const String name ("<Sans-Serif>");
  69513. return name;
  69514. }
  69515. const String Font::getDefaultSerifFontName() throw()
  69516. {
  69517. static const String name ("<Serif>");
  69518. return name;
  69519. }
  69520. const String Font::getDefaultMonospacedFontName() throw()
  69521. {
  69522. static const String name ("<Monospaced>");
  69523. return name;
  69524. }
  69525. void Font::setTypefaceName (const String& faceName) throw()
  69526. {
  69527. if (faceName != font->typefaceName)
  69528. {
  69529. dupeInternalIfShared();
  69530. font->typefaceName = faceName;
  69531. font->typeface = 0;
  69532. font->ascent = 0;
  69533. }
  69534. }
  69535. const String Font::getFallbackFontName() throw()
  69536. {
  69537. return FontValues::fallbackFont;
  69538. }
  69539. void Font::setFallbackFontName (const String& name) throw()
  69540. {
  69541. FontValues::fallbackFont = name;
  69542. }
  69543. void Font::setHeight (float newHeight) throw()
  69544. {
  69545. newHeight = FontValues::limitFontHeight (newHeight);
  69546. if (font->height != newHeight)
  69547. {
  69548. dupeInternalIfShared();
  69549. font->height = newHeight;
  69550. }
  69551. }
  69552. void Font::setHeightWithoutChangingWidth (float newHeight) throw()
  69553. {
  69554. newHeight = FontValues::limitFontHeight (newHeight);
  69555. if (font->height != newHeight)
  69556. {
  69557. dupeInternalIfShared();
  69558. font->horizontalScale *= (font->height / newHeight);
  69559. font->height = newHeight;
  69560. }
  69561. }
  69562. void Font::setStyleFlags (const int newFlags) throw()
  69563. {
  69564. if (font->styleFlags != newFlags)
  69565. {
  69566. dupeInternalIfShared();
  69567. font->styleFlags = newFlags;
  69568. font->typeface = 0;
  69569. font->ascent = 0;
  69570. }
  69571. }
  69572. void Font::setSizeAndStyle (float newHeight,
  69573. const int newStyleFlags,
  69574. const float newHorizontalScale,
  69575. const float newKerningAmount) throw()
  69576. {
  69577. newHeight = FontValues::limitFontHeight (newHeight);
  69578. if (font->height != newHeight
  69579. || font->horizontalScale != newHorizontalScale
  69580. || font->kerning != newKerningAmount)
  69581. {
  69582. dupeInternalIfShared();
  69583. font->height = newHeight;
  69584. font->horizontalScale = newHorizontalScale;
  69585. font->kerning = newKerningAmount;
  69586. }
  69587. setStyleFlags (newStyleFlags);
  69588. }
  69589. void Font::setHorizontalScale (const float scaleFactor) throw()
  69590. {
  69591. dupeInternalIfShared();
  69592. font->horizontalScale = scaleFactor;
  69593. }
  69594. void Font::setExtraKerningFactor (const float extraKerning) throw()
  69595. {
  69596. dupeInternalIfShared();
  69597. font->kerning = extraKerning;
  69598. }
  69599. void Font::setBold (const bool shouldBeBold) throw()
  69600. {
  69601. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  69602. : (font->styleFlags & ~bold));
  69603. }
  69604. bool Font::isBold() const throw()
  69605. {
  69606. return (font->styleFlags & bold) != 0;
  69607. }
  69608. void Font::setItalic (const bool shouldBeItalic) throw()
  69609. {
  69610. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  69611. : (font->styleFlags & ~italic));
  69612. }
  69613. bool Font::isItalic() const throw()
  69614. {
  69615. return (font->styleFlags & italic) != 0;
  69616. }
  69617. void Font::setUnderline (const bool shouldBeUnderlined) throw()
  69618. {
  69619. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  69620. : (font->styleFlags & ~underlined));
  69621. }
  69622. bool Font::isUnderlined() const throw()
  69623. {
  69624. return (font->styleFlags & underlined) != 0;
  69625. }
  69626. float Font::getAscent() const throw()
  69627. {
  69628. if (font->ascent == 0)
  69629. font->ascent = getTypeface()->getAscent();
  69630. return font->height * font->ascent;
  69631. }
  69632. float Font::getDescent() const throw()
  69633. {
  69634. return font->height - getAscent();
  69635. }
  69636. int Font::getStringWidth (const String& text) const throw()
  69637. {
  69638. return roundToInt (getStringWidthFloat (text));
  69639. }
  69640. float Font::getStringWidthFloat (const String& text) const throw()
  69641. {
  69642. float w = getTypeface()->getStringWidth (text);
  69643. if (font->kerning != 0)
  69644. w += font->kerning * text.length();
  69645. return w * font->height * font->horizontalScale;
  69646. }
  69647. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const throw()
  69648. {
  69649. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  69650. const float scale = font->height * font->horizontalScale;
  69651. const int num = xOffsets.size();
  69652. if (num > 0)
  69653. {
  69654. float* const x = &(xOffsets.getReference(0));
  69655. if (font->kerning != 0)
  69656. {
  69657. for (int i = 0; i < num; ++i)
  69658. x[i] = (x[i] + i * font->kerning) * scale;
  69659. }
  69660. else
  69661. {
  69662. for (int i = 0; i < num; ++i)
  69663. x[i] *= scale;
  69664. }
  69665. }
  69666. }
  69667. void Font::findFonts (Array<Font>& destArray) throw()
  69668. {
  69669. const StringArray names (findAllTypefaceNames());
  69670. for (int i = 0; i < names.size(); ++i)
  69671. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  69672. }
  69673. const String Font::toString() const
  69674. {
  69675. String s (getTypefaceName());
  69676. if (s == getDefaultSansSerifFontName())
  69677. s = String::empty;
  69678. else
  69679. s += "; ";
  69680. s += String (getHeight(), 1);
  69681. if (isBold())
  69682. s += " bold";
  69683. if (isItalic())
  69684. s += " italic";
  69685. return s;
  69686. }
  69687. const Font Font::fromString (const String& fontDescription)
  69688. {
  69689. String name;
  69690. const int separator = fontDescription.indexOfChar (';');
  69691. if (separator > 0)
  69692. name = fontDescription.substring (0, separator).trim();
  69693. if (name.isEmpty())
  69694. name = getDefaultSansSerifFontName();
  69695. String sizeAndStyle (fontDescription.substring (separator + 1));
  69696. float height = sizeAndStyle.getFloatValue();
  69697. if (height <= 0)
  69698. height = 10.0f;
  69699. int flags = Font::plain;
  69700. if (sizeAndStyle.containsIgnoreCase ("bold"))
  69701. flags |= Font::bold;
  69702. if (sizeAndStyle.containsIgnoreCase ("italic"))
  69703. flags |= Font::italic;
  69704. return Font (name, height, flags);
  69705. }
  69706. class TypefaceCache : public DeletedAtShutdown
  69707. {
  69708. public:
  69709. TypefaceCache (int numToCache = 10) throw()
  69710. : counter (1)
  69711. {
  69712. while (--numToCache >= 0)
  69713. faces.add (new CachedFace());
  69714. }
  69715. ~TypefaceCache()
  69716. {
  69717. clearSingletonInstance();
  69718. }
  69719. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  69720. const Typeface::Ptr findTypefaceFor (const Font& font) throw()
  69721. {
  69722. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  69723. const String faceName (font.getTypefaceName());
  69724. int i;
  69725. for (i = faces.size(); --i >= 0;)
  69726. {
  69727. CachedFace* const face = faces.getUnchecked(i);
  69728. if (face->flags == flags
  69729. && face->typefaceName == faceName)
  69730. {
  69731. face->lastUsageCount = ++counter;
  69732. return face->typeFace;
  69733. }
  69734. }
  69735. int replaceIndex = 0;
  69736. int bestLastUsageCount = std::numeric_limits<int>::max();
  69737. for (i = faces.size(); --i >= 0;)
  69738. {
  69739. const int lu = faces.getUnchecked(i)->lastUsageCount;
  69740. if (bestLastUsageCount > lu)
  69741. {
  69742. bestLastUsageCount = lu;
  69743. replaceIndex = i;
  69744. }
  69745. }
  69746. CachedFace* const face = faces.getUnchecked (replaceIndex);
  69747. face->typefaceName = faceName;
  69748. face->flags = flags;
  69749. face->lastUsageCount = ++counter;
  69750. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  69751. jassert (face->typeFace != 0); // the look and feel must return a typeface!
  69752. return face->typeFace;
  69753. }
  69754. juce_UseDebuggingNewOperator
  69755. private:
  69756. struct CachedFace
  69757. {
  69758. CachedFace() throw()
  69759. : lastUsageCount (0), flags (-1)
  69760. {
  69761. }
  69762. String typefaceName;
  69763. int lastUsageCount;
  69764. int flags;
  69765. Typeface::Ptr typeFace;
  69766. };
  69767. int counter;
  69768. OwnedArray <CachedFace> faces;
  69769. TypefaceCache (const TypefaceCache&);
  69770. TypefaceCache& operator= (const TypefaceCache&);
  69771. };
  69772. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  69773. Typeface* Font::getTypeface() const throw()
  69774. {
  69775. if (font->typeface == 0)
  69776. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  69777. return font->typeface;
  69778. }
  69779. END_JUCE_NAMESPACE
  69780. /*** End of inlined file: juce_Font.cpp ***/
  69781. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  69782. BEGIN_JUCE_NAMESPACE
  69783. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  69784. const juce_wchar character_, const int glyph_)
  69785. : x (x_),
  69786. y (y_),
  69787. w (w_),
  69788. font (font_),
  69789. character (character_),
  69790. glyph (glyph_)
  69791. {
  69792. }
  69793. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  69794. : x (other.x),
  69795. y (other.y),
  69796. w (other.w),
  69797. font (other.font),
  69798. character (other.character),
  69799. glyph (other.glyph)
  69800. {
  69801. }
  69802. void PositionedGlyph::draw (const Graphics& g) const
  69803. {
  69804. if (! isWhitespace())
  69805. {
  69806. g.getInternalContext()->setFont (font);
  69807. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  69808. }
  69809. }
  69810. void PositionedGlyph::draw (const Graphics& g,
  69811. const AffineTransform& transform) const
  69812. {
  69813. if (! isWhitespace())
  69814. {
  69815. g.getInternalContext()->setFont (font);
  69816. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  69817. .followedBy (transform));
  69818. }
  69819. }
  69820. void PositionedGlyph::createPath (Path& path) const
  69821. {
  69822. if (! isWhitespace())
  69823. {
  69824. Typeface* const t = font.getTypeface();
  69825. if (t != 0)
  69826. {
  69827. Path p;
  69828. t->getOutlineForGlyph (glyph, p);
  69829. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  69830. .translated (x, y));
  69831. }
  69832. }
  69833. }
  69834. bool PositionedGlyph::hitTest (float px, float py) const
  69835. {
  69836. if (getBounds().contains (px, py) && ! isWhitespace())
  69837. {
  69838. Typeface* const t = font.getTypeface();
  69839. if (t != 0)
  69840. {
  69841. Path p;
  69842. t->getOutlineForGlyph (glyph, p);
  69843. AffineTransform::translation (-x, -y)
  69844. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  69845. .transformPoint (px, py);
  69846. return p.contains (px, py);
  69847. }
  69848. }
  69849. return false;
  69850. }
  69851. void PositionedGlyph::moveBy (const float deltaX,
  69852. const float deltaY)
  69853. {
  69854. x += deltaX;
  69855. y += deltaY;
  69856. }
  69857. GlyphArrangement::GlyphArrangement()
  69858. {
  69859. glyphs.ensureStorageAllocated (128);
  69860. }
  69861. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  69862. {
  69863. addGlyphArrangement (other);
  69864. }
  69865. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  69866. {
  69867. if (this != &other)
  69868. {
  69869. clear();
  69870. addGlyphArrangement (other);
  69871. }
  69872. return *this;
  69873. }
  69874. GlyphArrangement::~GlyphArrangement()
  69875. {
  69876. }
  69877. void GlyphArrangement::clear()
  69878. {
  69879. glyphs.clear();
  69880. }
  69881. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  69882. {
  69883. jassert (((unsigned int) index) < (unsigned int) glyphs.size());
  69884. return *glyphs [index];
  69885. }
  69886. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  69887. {
  69888. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  69889. for (int i = 0; i < other.glyphs.size(); ++i)
  69890. glyphs.add (new PositionedGlyph (*other.glyphs.getUnchecked (i)));
  69891. }
  69892. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  69893. {
  69894. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  69895. }
  69896. void GlyphArrangement::addLineOfText (const Font& font,
  69897. const String& text,
  69898. const float xOffset,
  69899. const float yOffset)
  69900. {
  69901. addCurtailedLineOfText (font, text,
  69902. xOffset, yOffset,
  69903. 1.0e10f, false);
  69904. }
  69905. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  69906. const String& text,
  69907. float xOffset,
  69908. const float yOffset,
  69909. const float maxWidthPixels,
  69910. const bool useEllipsis)
  69911. {
  69912. if (text.isNotEmpty())
  69913. {
  69914. Array <int> newGlyphs;
  69915. Array <float> xOffsets;
  69916. font.getGlyphPositions (text, newGlyphs, xOffsets);
  69917. const int textLen = newGlyphs.size();
  69918. const juce_wchar* const unicodeText = text;
  69919. for (int i = 0; i < textLen; ++i)
  69920. {
  69921. const float thisX = xOffsets.getUnchecked (i);
  69922. const float nextX = xOffsets.getUnchecked (i + 1);
  69923. if (nextX > maxWidthPixels + 1.0f)
  69924. {
  69925. // curtail the string if it's too wide..
  69926. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  69927. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  69928. break;
  69929. }
  69930. else
  69931. {
  69932. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  69933. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  69934. }
  69935. }
  69936. }
  69937. }
  69938. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  69939. const int startIndex, int endIndex)
  69940. {
  69941. int numDeleted = 0;
  69942. if (glyphs.size() > 0)
  69943. {
  69944. Array<int> dotGlyphs;
  69945. Array<float> dotXs;
  69946. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  69947. const float dx = dotXs[1];
  69948. float xOffset = 0.0f, yOffset = 0.0f;
  69949. while (endIndex > startIndex)
  69950. {
  69951. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  69952. xOffset = pg->x;
  69953. yOffset = pg->y;
  69954. glyphs.remove (endIndex);
  69955. ++numDeleted;
  69956. if (xOffset + dx * 3 <= maxXPos)
  69957. break;
  69958. }
  69959. for (int i = 3; --i >= 0;)
  69960. {
  69961. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  69962. font, '.', dotGlyphs.getFirst()));
  69963. --numDeleted;
  69964. xOffset += dx;
  69965. if (xOffset > maxXPos)
  69966. break;
  69967. }
  69968. }
  69969. return numDeleted;
  69970. }
  69971. void GlyphArrangement::addJustifiedText (const Font& font,
  69972. const String& text,
  69973. float x, float y,
  69974. const float maxLineWidth,
  69975. const Justification& horizontalLayout)
  69976. {
  69977. int lineStartIndex = glyphs.size();
  69978. addLineOfText (font, text, x, y);
  69979. const float originalY = y;
  69980. while (lineStartIndex < glyphs.size())
  69981. {
  69982. int i = lineStartIndex;
  69983. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  69984. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  69985. ++i;
  69986. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  69987. int lastWordBreakIndex = -1;
  69988. while (i < glyphs.size())
  69989. {
  69990. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  69991. const juce_wchar c = pg->getCharacter();
  69992. if (c == '\r' || c == '\n')
  69993. {
  69994. ++i;
  69995. if (c == '\r' && i < glyphs.size()
  69996. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  69997. ++i;
  69998. break;
  69999. }
  70000. else if (pg->isWhitespace())
  70001. {
  70002. lastWordBreakIndex = i + 1;
  70003. }
  70004. else if (pg->getRight() - 0.0001f >= lineMaxX)
  70005. {
  70006. if (lastWordBreakIndex >= 0)
  70007. i = lastWordBreakIndex;
  70008. break;
  70009. }
  70010. ++i;
  70011. }
  70012. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  70013. float currentLineEndX = currentLineStartX;
  70014. for (int j = i; --j >= lineStartIndex;)
  70015. {
  70016. if (! glyphs.getUnchecked (j)->isWhitespace())
  70017. {
  70018. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  70019. break;
  70020. }
  70021. }
  70022. float deltaX = 0.0f;
  70023. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  70024. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  70025. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  70026. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  70027. else if (horizontalLayout.testFlags (Justification::right))
  70028. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  70029. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  70030. x + deltaX - currentLineStartX, y - originalY);
  70031. lineStartIndex = i;
  70032. y += font.getHeight();
  70033. }
  70034. }
  70035. void GlyphArrangement::addFittedText (const Font& f,
  70036. const String& text,
  70037. const float x, const float y,
  70038. const float width, const float height,
  70039. const Justification& layout,
  70040. int maximumLines,
  70041. const float minimumHorizontalScale)
  70042. {
  70043. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  70044. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  70045. if (text.containsAnyOf ("\r\n"))
  70046. {
  70047. GlyphArrangement ga;
  70048. ga.addJustifiedText (f, text, x, y, width, layout);
  70049. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  70050. float dy = y - bb.getY();
  70051. if (layout.testFlags (Justification::verticallyCentred))
  70052. dy += (height - bb.getHeight()) * 0.5f;
  70053. else if (layout.testFlags (Justification::bottom))
  70054. dy += height - bb.getHeight();
  70055. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  70056. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  70057. for (int i = 0; i < ga.glyphs.size(); ++i)
  70058. glyphs.add (ga.glyphs.getUnchecked (i));
  70059. ga.glyphs.clear (false);
  70060. return;
  70061. }
  70062. int startIndex = glyphs.size();
  70063. addLineOfText (f, text.trim(), x, y);
  70064. if (glyphs.size() > startIndex)
  70065. {
  70066. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  70067. - glyphs.getUnchecked (startIndex)->getLeft();
  70068. if (lineWidth <= 0)
  70069. return;
  70070. if (lineWidth * minimumHorizontalScale < width)
  70071. {
  70072. if (lineWidth > width)
  70073. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  70074. width / lineWidth);
  70075. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  70076. x, y, width, height, layout);
  70077. }
  70078. else if (maximumLines <= 1)
  70079. {
  70080. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  70081. x, y, width, height, f, layout, minimumHorizontalScale);
  70082. }
  70083. else
  70084. {
  70085. Font font (f);
  70086. String txt (text.trim());
  70087. const int length = txt.length();
  70088. const int originalStartIndex = startIndex;
  70089. int numLines = 1;
  70090. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  70091. maximumLines = 1;
  70092. maximumLines = jmin (maximumLines, length);
  70093. while (numLines < maximumLines)
  70094. {
  70095. ++numLines;
  70096. const float newFontHeight = height / (float) numLines;
  70097. if (newFontHeight < font.getHeight())
  70098. {
  70099. font.setHeight (jmax (8.0f, newFontHeight));
  70100. removeRangeOfGlyphs (startIndex, -1);
  70101. addLineOfText (font, txt, x, y);
  70102. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  70103. - glyphs.getUnchecked (startIndex)->getLeft();
  70104. }
  70105. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  70106. break;
  70107. }
  70108. if (numLines < 1)
  70109. numLines = 1;
  70110. float lineY = y;
  70111. float widthPerLine = lineWidth / numLines;
  70112. int lastLineStartIndex = 0;
  70113. for (int line = 0; line < numLines; ++line)
  70114. {
  70115. int i = startIndex;
  70116. lastLineStartIndex = i;
  70117. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  70118. if (line == numLines - 1)
  70119. {
  70120. widthPerLine = width;
  70121. i = glyphs.size();
  70122. }
  70123. else
  70124. {
  70125. while (i < glyphs.size())
  70126. {
  70127. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  70128. if (lineWidth > widthPerLine)
  70129. {
  70130. // got to a point where the line's too long, so skip forward to find a
  70131. // good place to break it..
  70132. const int searchStartIndex = i;
  70133. while (i < glyphs.size())
  70134. {
  70135. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  70136. {
  70137. if (glyphs.getUnchecked (i)->isWhitespace()
  70138. || glyphs.getUnchecked (i)->getCharacter() == '-')
  70139. {
  70140. ++i;
  70141. break;
  70142. }
  70143. }
  70144. else
  70145. {
  70146. // can't find a suitable break, so try looking backwards..
  70147. i = searchStartIndex;
  70148. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  70149. {
  70150. if (glyphs.getUnchecked (i - back)->isWhitespace()
  70151. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  70152. {
  70153. i -= back - 1;
  70154. break;
  70155. }
  70156. }
  70157. break;
  70158. }
  70159. ++i;
  70160. }
  70161. break;
  70162. }
  70163. ++i;
  70164. }
  70165. int wsStart = i;
  70166. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  70167. --wsStart;
  70168. int wsEnd = i;
  70169. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  70170. ++wsEnd;
  70171. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  70172. i = jmax (wsStart, startIndex + 1);
  70173. }
  70174. i -= fitLineIntoSpace (startIndex, i - startIndex,
  70175. x, lineY, width, font.getHeight(), font,
  70176. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  70177. minimumHorizontalScale);
  70178. startIndex = i;
  70179. lineY += font.getHeight();
  70180. if (startIndex >= glyphs.size())
  70181. break;
  70182. }
  70183. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  70184. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  70185. }
  70186. }
  70187. }
  70188. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  70189. const float dx, const float dy)
  70190. {
  70191. jassert (startIndex >= 0);
  70192. if (dx != 0.0f || dy != 0.0f)
  70193. {
  70194. if (num < 0 || startIndex + num > glyphs.size())
  70195. num = glyphs.size() - startIndex;
  70196. while (--num >= 0)
  70197. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  70198. }
  70199. }
  70200. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  70201. const Justification& justification, float minimumHorizontalScale)
  70202. {
  70203. int numDeleted = 0;
  70204. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  70205. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  70206. if (lineWidth > w)
  70207. {
  70208. if (minimumHorizontalScale < 1.0f)
  70209. {
  70210. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  70211. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  70212. }
  70213. if (lineWidth > w)
  70214. {
  70215. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  70216. numGlyphs -= numDeleted;
  70217. }
  70218. }
  70219. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  70220. return numDeleted;
  70221. }
  70222. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  70223. const float horizontalScaleFactor)
  70224. {
  70225. jassert (startIndex >= 0);
  70226. if (num < 0 || startIndex + num > glyphs.size())
  70227. num = glyphs.size() - startIndex;
  70228. if (num > 0)
  70229. {
  70230. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  70231. while (--num >= 0)
  70232. {
  70233. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  70234. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  70235. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  70236. pg->w *= horizontalScaleFactor;
  70237. }
  70238. }
  70239. }
  70240. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  70241. {
  70242. jassert (startIndex >= 0);
  70243. if (num < 0 || startIndex + num > glyphs.size())
  70244. num = glyphs.size() - startIndex;
  70245. Rectangle<float> result;
  70246. bool isFirst = true;
  70247. while (--num >= 0)
  70248. {
  70249. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  70250. if (includeWhitespace || ! pg->isWhitespace())
  70251. {
  70252. if (isFirst)
  70253. {
  70254. isFirst = false;
  70255. result = pg->getBounds();
  70256. }
  70257. else
  70258. {
  70259. result = result.getUnion (pg->getBounds());
  70260. }
  70261. }
  70262. }
  70263. return result;
  70264. }
  70265. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  70266. const float x, const float y, const float width, const float height,
  70267. const Justification& justification)
  70268. {
  70269. jassert (num >= 0 && startIndex >= 0);
  70270. if (glyphs.size() > 0 && num > 0)
  70271. {
  70272. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  70273. | Justification::horizontallyCentred)));
  70274. float deltaX = 0.0f;
  70275. if (justification.testFlags (Justification::horizontallyJustified))
  70276. deltaX = x - bb.getX();
  70277. else if (justification.testFlags (Justification::horizontallyCentred))
  70278. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  70279. else if (justification.testFlags (Justification::right))
  70280. deltaX = (x + width) - bb.getRight();
  70281. else
  70282. deltaX = x - bb.getX();
  70283. float deltaY = 0.0f;
  70284. if (justification.testFlags (Justification::top))
  70285. deltaY = y - bb.getY();
  70286. else if (justification.testFlags (Justification::bottom))
  70287. deltaY = (y + height) - bb.getBottom();
  70288. else
  70289. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  70290. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  70291. if (justification.testFlags (Justification::horizontallyJustified))
  70292. {
  70293. int lineStart = 0;
  70294. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  70295. int i;
  70296. for (i = 0; i < num; ++i)
  70297. {
  70298. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  70299. if (glyphY != baseY)
  70300. {
  70301. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  70302. lineStart = i;
  70303. baseY = glyphY;
  70304. }
  70305. }
  70306. if (i > lineStart)
  70307. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  70308. }
  70309. }
  70310. }
  70311. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  70312. {
  70313. if (start + num < glyphs.size()
  70314. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  70315. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  70316. {
  70317. int numSpaces = 0;
  70318. int spacesAtEnd = 0;
  70319. for (int i = 0; i < num; ++i)
  70320. {
  70321. if (glyphs.getUnchecked (start + i)->isWhitespace())
  70322. {
  70323. ++spacesAtEnd;
  70324. ++numSpaces;
  70325. }
  70326. else
  70327. {
  70328. spacesAtEnd = 0;
  70329. }
  70330. }
  70331. numSpaces -= spacesAtEnd;
  70332. if (numSpaces > 0)
  70333. {
  70334. const float startX = glyphs.getUnchecked (start)->getLeft();
  70335. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  70336. const float extraPaddingBetweenWords
  70337. = (targetWidth - (endX - startX)) / (float) numSpaces;
  70338. float deltaX = 0.0f;
  70339. for (int i = 0; i < num; ++i)
  70340. {
  70341. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  70342. if (glyphs.getUnchecked (start + i)->isWhitespace())
  70343. deltaX += extraPaddingBetweenWords;
  70344. }
  70345. }
  70346. }
  70347. }
  70348. void GlyphArrangement::draw (const Graphics& g) const
  70349. {
  70350. for (int i = 0; i < glyphs.size(); ++i)
  70351. {
  70352. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  70353. if (pg->font.isUnderlined())
  70354. {
  70355. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  70356. float nextX = pg->x + pg->w;
  70357. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  70358. nextX = glyphs.getUnchecked (i + 1)->x;
  70359. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  70360. nextX - pg->x, lineThickness);
  70361. }
  70362. pg->draw (g);
  70363. }
  70364. }
  70365. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  70366. {
  70367. for (int i = 0; i < glyphs.size(); ++i)
  70368. {
  70369. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  70370. if (pg->font.isUnderlined())
  70371. {
  70372. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  70373. float nextX = pg->x + pg->w;
  70374. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  70375. nextX = glyphs.getUnchecked (i + 1)->x;
  70376. Path p;
  70377. p.addLineSegment (pg->x, pg->y + lineThickness * 2.0f,
  70378. nextX, pg->y + lineThickness * 2.0f,
  70379. lineThickness);
  70380. g.fillPath (p, transform);
  70381. }
  70382. pg->draw (g, transform);
  70383. }
  70384. }
  70385. void GlyphArrangement::createPath (Path& path) const
  70386. {
  70387. for (int i = 0; i < glyphs.size(); ++i)
  70388. glyphs.getUnchecked (i)->createPath (path);
  70389. }
  70390. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  70391. {
  70392. for (int i = 0; i < glyphs.size(); ++i)
  70393. if (glyphs.getUnchecked (i)->hitTest (x, y))
  70394. return i;
  70395. return -1;
  70396. }
  70397. END_JUCE_NAMESPACE
  70398. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  70399. /*** Start of inlined file: juce_TextLayout.cpp ***/
  70400. BEGIN_JUCE_NAMESPACE
  70401. class TextLayout::Token
  70402. {
  70403. public:
  70404. String text;
  70405. Font font;
  70406. int x, y, w, h;
  70407. int line, lineHeight;
  70408. bool isWhitespace, isNewLine;
  70409. Token (const String& t,
  70410. const Font& f,
  70411. const bool isWhitespace_)
  70412. : text (t),
  70413. font (f),
  70414. x(0),
  70415. y(0),
  70416. isWhitespace (isWhitespace_)
  70417. {
  70418. w = font.getStringWidth (t);
  70419. h = roundToInt (f.getHeight());
  70420. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  70421. }
  70422. Token (const Token& other)
  70423. : text (other.text),
  70424. font (other.font),
  70425. x (other.x),
  70426. y (other.y),
  70427. w (other.w),
  70428. h (other.h),
  70429. line (other.line),
  70430. lineHeight (other.lineHeight),
  70431. isWhitespace (other.isWhitespace),
  70432. isNewLine (other.isNewLine)
  70433. {
  70434. }
  70435. ~Token()
  70436. {
  70437. }
  70438. void draw (Graphics& g,
  70439. const int xOffset,
  70440. const int yOffset)
  70441. {
  70442. if (! isWhitespace)
  70443. {
  70444. g.setFont (font);
  70445. g.drawSingleLineText (text.trimEnd(),
  70446. xOffset + x,
  70447. yOffset + y + (lineHeight - h)
  70448. + roundToInt (font.getAscent()));
  70449. }
  70450. }
  70451. juce_UseDebuggingNewOperator
  70452. };
  70453. TextLayout::TextLayout()
  70454. : totalLines (0)
  70455. {
  70456. tokens.ensureStorageAllocated (64);
  70457. }
  70458. TextLayout::TextLayout (const String& text, const Font& font)
  70459. : totalLines (0)
  70460. {
  70461. tokens.ensureStorageAllocated (64);
  70462. appendText (text, font);
  70463. }
  70464. TextLayout::TextLayout (const TextLayout& other)
  70465. : totalLines (0)
  70466. {
  70467. *this = other;
  70468. }
  70469. TextLayout& TextLayout::operator= (const TextLayout& other)
  70470. {
  70471. if (this != &other)
  70472. {
  70473. clear();
  70474. totalLines = other.totalLines;
  70475. for (int i = 0; i < other.tokens.size(); ++i)
  70476. tokens.add (new Token (*other.tokens.getUnchecked(i)));
  70477. }
  70478. return *this;
  70479. }
  70480. TextLayout::~TextLayout()
  70481. {
  70482. clear();
  70483. }
  70484. void TextLayout::clear()
  70485. {
  70486. tokens.clear();
  70487. totalLines = 0;
  70488. }
  70489. void TextLayout::appendText (const String& text, const Font& font)
  70490. {
  70491. const juce_wchar* t = text;
  70492. String currentString;
  70493. int lastCharType = 0;
  70494. for (;;)
  70495. {
  70496. const juce_wchar c = *t++;
  70497. if (c == 0)
  70498. break;
  70499. int charType;
  70500. if (c == '\r' || c == '\n')
  70501. {
  70502. charType = 0;
  70503. }
  70504. else if (CharacterFunctions::isWhitespace (c))
  70505. {
  70506. charType = 2;
  70507. }
  70508. else
  70509. {
  70510. charType = 1;
  70511. }
  70512. if (charType == 0 || charType != lastCharType)
  70513. {
  70514. if (currentString.isNotEmpty())
  70515. {
  70516. tokens.add (new Token (currentString, font,
  70517. lastCharType == 2 || lastCharType == 0));
  70518. }
  70519. currentString = String::charToString (c);
  70520. if (c == '\r' && *t == '\n')
  70521. currentString += *t++;
  70522. }
  70523. else
  70524. {
  70525. currentString += c;
  70526. }
  70527. lastCharType = charType;
  70528. }
  70529. if (currentString.isNotEmpty())
  70530. tokens.add (new Token (currentString, font, lastCharType == 2));
  70531. }
  70532. void TextLayout::setText (const String& text, const Font& font)
  70533. {
  70534. clear();
  70535. appendText (text, font);
  70536. }
  70537. void TextLayout::layout (int maxWidth,
  70538. const Justification& justification,
  70539. const bool attemptToBalanceLineLengths)
  70540. {
  70541. if (attemptToBalanceLineLengths)
  70542. {
  70543. const int originalW = maxWidth;
  70544. int bestWidth = maxWidth;
  70545. float bestLineProportion = 0.0f;
  70546. while (maxWidth > originalW / 2)
  70547. {
  70548. layout (maxWidth, justification, false);
  70549. if (getNumLines() <= 1)
  70550. return;
  70551. const int lastLineW = getLineWidth (getNumLines() - 1);
  70552. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  70553. const float prop = lastLineW / (float) lastButOneLineW;
  70554. if (prop > 0.9f)
  70555. return;
  70556. if (prop > bestLineProportion)
  70557. {
  70558. bestLineProportion = prop;
  70559. bestWidth = maxWidth;
  70560. }
  70561. maxWidth -= 10;
  70562. }
  70563. layout (bestWidth, justification, false);
  70564. }
  70565. else
  70566. {
  70567. int x = 0;
  70568. int y = 0;
  70569. int h = 0;
  70570. totalLines = 0;
  70571. int i;
  70572. for (i = 0; i < tokens.size(); ++i)
  70573. {
  70574. Token* const t = tokens.getUnchecked(i);
  70575. t->x = x;
  70576. t->y = y;
  70577. t->line = totalLines;
  70578. x += t->w;
  70579. h = jmax (h, t->h);
  70580. const Token* nextTok = tokens [i + 1];
  70581. if (nextTok == 0)
  70582. break;
  70583. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  70584. {
  70585. // finished a line, so go back and update the heights of the things on it
  70586. for (int j = i; j >= 0; --j)
  70587. {
  70588. Token* const tok = tokens.getUnchecked(j);
  70589. if (tok->line == totalLines)
  70590. tok->lineHeight = h;
  70591. else
  70592. break;
  70593. }
  70594. x = 0;
  70595. y += h;
  70596. h = 0;
  70597. ++totalLines;
  70598. }
  70599. }
  70600. // finished a line, so go back and update the heights of the things on it
  70601. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  70602. {
  70603. Token* const t = tokens.getUnchecked(j);
  70604. if (t->line == totalLines)
  70605. t->lineHeight = h;
  70606. else
  70607. break;
  70608. }
  70609. ++totalLines;
  70610. if (! justification.testFlags (Justification::left))
  70611. {
  70612. int totalW = getWidth();
  70613. for (i = totalLines; --i >= 0;)
  70614. {
  70615. const int lineW = getLineWidth (i);
  70616. int dx = 0;
  70617. if (justification.testFlags (Justification::horizontallyCentred))
  70618. dx = (totalW - lineW) / 2;
  70619. else if (justification.testFlags (Justification::right))
  70620. dx = totalW - lineW;
  70621. for (int j = tokens.size(); --j >= 0;)
  70622. {
  70623. Token* const t = tokens.getUnchecked(j);
  70624. if (t->line == i)
  70625. t->x += dx;
  70626. }
  70627. }
  70628. }
  70629. }
  70630. }
  70631. int TextLayout::getLineWidth (const int lineNumber) const
  70632. {
  70633. int maxW = 0;
  70634. for (int i = tokens.size(); --i >= 0;)
  70635. {
  70636. const Token* const t = tokens.getUnchecked(i);
  70637. if (t->line == lineNumber && ! t->isWhitespace)
  70638. maxW = jmax (maxW, t->x + t->w);
  70639. }
  70640. return maxW;
  70641. }
  70642. int TextLayout::getWidth() const
  70643. {
  70644. int maxW = 0;
  70645. for (int i = tokens.size(); --i >= 0;)
  70646. {
  70647. const Token* const t = tokens.getUnchecked(i);
  70648. if (! t->isWhitespace)
  70649. maxW = jmax (maxW, t->x + t->w);
  70650. }
  70651. return maxW;
  70652. }
  70653. int TextLayout::getHeight() const
  70654. {
  70655. int maxH = 0;
  70656. for (int i = tokens.size(); --i >= 0;)
  70657. {
  70658. const Token* const t = tokens.getUnchecked(i);
  70659. if (! t->isWhitespace)
  70660. maxH = jmax (maxH, t->y + t->h);
  70661. }
  70662. return maxH;
  70663. }
  70664. void TextLayout::draw (Graphics& g,
  70665. const int xOffset,
  70666. const int yOffset) const
  70667. {
  70668. for (int i = tokens.size(); --i >= 0;)
  70669. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  70670. }
  70671. void TextLayout::drawWithin (Graphics& g,
  70672. int x, int y, int w, int h,
  70673. const Justification& justification) const
  70674. {
  70675. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  70676. x, y, w, h);
  70677. draw (g, x, y);
  70678. }
  70679. END_JUCE_NAMESPACE
  70680. /*** End of inlined file: juce_TextLayout.cpp ***/
  70681. /*** Start of inlined file: juce_Typeface.cpp ***/
  70682. BEGIN_JUCE_NAMESPACE
  70683. Typeface::Typeface (const String& name_) throw()
  70684. : name (name_)
  70685. {
  70686. }
  70687. Typeface::~Typeface()
  70688. {
  70689. }
  70690. class CustomTypeface::GlyphInfo
  70691. {
  70692. public:
  70693. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  70694. : character (character_), path (path_), width (width_)
  70695. {
  70696. }
  70697. ~GlyphInfo() throw()
  70698. {
  70699. }
  70700. struct KerningPair
  70701. {
  70702. juce_wchar character2;
  70703. float kerningAmount;
  70704. };
  70705. void addKerningPair (const juce_wchar subsequentCharacter,
  70706. const float extraKerningAmount) throw()
  70707. {
  70708. KerningPair kp;
  70709. kp.character2 = subsequentCharacter;
  70710. kp.kerningAmount = extraKerningAmount;
  70711. kerningPairs.add (kp);
  70712. }
  70713. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  70714. {
  70715. if (subsequentCharacter != 0)
  70716. {
  70717. for (int i = kerningPairs.size(); --i >= 0;)
  70718. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  70719. return width + kerningPairs.getReference(i).kerningAmount;
  70720. }
  70721. return width;
  70722. }
  70723. const juce_wchar character;
  70724. const Path path;
  70725. float width;
  70726. Array <KerningPair> kerningPairs;
  70727. juce_UseDebuggingNewOperator
  70728. private:
  70729. GlyphInfo (const GlyphInfo&);
  70730. GlyphInfo& operator= (const GlyphInfo&);
  70731. };
  70732. CustomTypeface::CustomTypeface()
  70733. : Typeface (String::empty)
  70734. {
  70735. clear();
  70736. }
  70737. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  70738. : Typeface (String::empty)
  70739. {
  70740. clear();
  70741. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  70742. BufferedInputStream in (&gzin, 32768, false);
  70743. name = in.readString();
  70744. isBold = in.readBool();
  70745. isItalic = in.readBool();
  70746. ascent = in.readFloat();
  70747. defaultCharacter = (juce_wchar) in.readShort();
  70748. int i, numChars = in.readInt();
  70749. for (i = 0; i < numChars; ++i)
  70750. {
  70751. const juce_wchar c = (juce_wchar) in.readShort();
  70752. const float width = in.readFloat();
  70753. Path p;
  70754. p.loadPathFromStream (in);
  70755. addGlyph (c, p, width);
  70756. }
  70757. const int numKerningPairs = in.readInt();
  70758. for (i = 0; i < numKerningPairs; ++i)
  70759. {
  70760. const juce_wchar char1 = (juce_wchar) in.readShort();
  70761. const juce_wchar char2 = (juce_wchar) in.readShort();
  70762. addKerningPair (char1, char2, in.readFloat());
  70763. }
  70764. }
  70765. CustomTypeface::~CustomTypeface()
  70766. {
  70767. }
  70768. void CustomTypeface::clear()
  70769. {
  70770. defaultCharacter = 0;
  70771. ascent = 1.0f;
  70772. isBold = isItalic = false;
  70773. zeromem (lookupTable, sizeof (lookupTable));
  70774. glyphs.clear();
  70775. }
  70776. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  70777. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  70778. {
  70779. name = name_;
  70780. defaultCharacter = defaultCharacter_;
  70781. ascent = ascent_;
  70782. isBold = isBold_;
  70783. isItalic = isItalic_;
  70784. }
  70785. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  70786. {
  70787. // Check that you're not trying to add the same character twice..
  70788. jassert (findGlyph (character, false) == 0);
  70789. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable))
  70790. lookupTable [character] = (short) glyphs.size();
  70791. glyphs.add (new GlyphInfo (character, path, width));
  70792. }
  70793. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  70794. {
  70795. if (extraAmount != 0)
  70796. {
  70797. GlyphInfo* const g = findGlyph (char1, true);
  70798. jassert (g != 0); // can only add kerning pairs for characters that exist!
  70799. if (g != 0)
  70800. g->addKerningPair (char2, extraAmount);
  70801. }
  70802. }
  70803. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  70804. {
  70805. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable) && lookupTable [character] > 0)
  70806. return glyphs [(int) lookupTable [(int) character]];
  70807. for (int i = 0; i < glyphs.size(); ++i)
  70808. {
  70809. GlyphInfo* const g = glyphs.getUnchecked(i);
  70810. if (g->character == character)
  70811. return g;
  70812. }
  70813. if (loadIfNeeded && loadGlyphIfPossible (character))
  70814. return findGlyph (character, false);
  70815. return 0;
  70816. }
  70817. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  70818. {
  70819. GlyphInfo* glyph = findGlyph (character, true);
  70820. if (glyph == 0)
  70821. {
  70822. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  70823. glyph = findGlyph (L' ', true);
  70824. if (glyph == 0)
  70825. {
  70826. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  70827. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  70828. if (fallbackTypeface != 0 && fallbackTypeface != this)
  70829. {
  70830. //xxx
  70831. }
  70832. if (glyph == 0)
  70833. glyph = findGlyph (defaultCharacter, true);
  70834. }
  70835. }
  70836. return glyph;
  70837. }
  70838. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  70839. {
  70840. return false;
  70841. }
  70842. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  70843. {
  70844. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  70845. for (int i = 0; i < numCharacters; ++i)
  70846. {
  70847. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  70848. Array <int> glyphIndexes;
  70849. Array <float> offsets;
  70850. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  70851. const int glyphIndex = glyphIndexes.getFirst();
  70852. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  70853. {
  70854. const float glyphWidth = offsets[1];
  70855. Path p;
  70856. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  70857. addGlyph (c, p, glyphWidth);
  70858. for (int j = glyphs.size() - 1; --j >= 0;)
  70859. {
  70860. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  70861. glyphIndexes.clearQuick();
  70862. offsets.clearQuick();
  70863. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  70864. if (offsets.size() > 1)
  70865. addKerningPair (c, char2, offsets[1] - glyphWidth);
  70866. }
  70867. }
  70868. }
  70869. }
  70870. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  70871. {
  70872. GZIPCompressorOutputStream out (&outputStream);
  70873. out.writeString (name);
  70874. out.writeBool (isBold);
  70875. out.writeBool (isItalic);
  70876. out.writeFloat (ascent);
  70877. out.writeShort ((short) (unsigned short) defaultCharacter);
  70878. out.writeInt (glyphs.size());
  70879. int i, numKerningPairs = 0;
  70880. for (i = 0; i < glyphs.size(); ++i)
  70881. {
  70882. const GlyphInfo* const g = glyphs.getUnchecked (i);
  70883. out.writeShort ((short) (unsigned short) g->character);
  70884. out.writeFloat (g->width);
  70885. g->path.writePathToStream (out);
  70886. numKerningPairs += g->kerningPairs.size();
  70887. }
  70888. out.writeInt (numKerningPairs);
  70889. for (i = 0; i < glyphs.size(); ++i)
  70890. {
  70891. const GlyphInfo* const g = glyphs.getUnchecked (i);
  70892. for (int j = 0; j < g->kerningPairs.size(); ++j)
  70893. {
  70894. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  70895. out.writeShort ((short) (unsigned short) g->character);
  70896. out.writeShort ((short) (unsigned short) p.character2);
  70897. out.writeFloat (p.kerningAmount);
  70898. }
  70899. }
  70900. return true;
  70901. }
  70902. float CustomTypeface::getAscent() const
  70903. {
  70904. return ascent;
  70905. }
  70906. float CustomTypeface::getDescent() const
  70907. {
  70908. return 1.0f - ascent;
  70909. }
  70910. float CustomTypeface::getStringWidth (const String& text)
  70911. {
  70912. float x = 0;
  70913. const juce_wchar* t = text;
  70914. while (*t != 0)
  70915. {
  70916. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  70917. if (glyph != 0)
  70918. x += glyph->getHorizontalSpacing (*t);
  70919. }
  70920. return x;
  70921. }
  70922. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  70923. {
  70924. xOffsets.add (0);
  70925. float x = 0;
  70926. const juce_wchar* t = text;
  70927. while (*t != 0)
  70928. {
  70929. const juce_wchar c = *t++;
  70930. const GlyphInfo* const glyph = findGlyphSubstituting (c);
  70931. if (glyph != 0)
  70932. {
  70933. x += glyph->getHorizontalSpacing (*t);
  70934. resultGlyphs.add ((int) glyph->character);
  70935. xOffsets.add (x);
  70936. }
  70937. }
  70938. }
  70939. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  70940. {
  70941. const GlyphInfo* const glyph = findGlyphSubstituting ((juce_wchar) glyphNumber);
  70942. if (glyph != 0)
  70943. {
  70944. path = glyph->path;
  70945. return true;
  70946. }
  70947. return false;
  70948. }
  70949. END_JUCE_NAMESPACE
  70950. /*** End of inlined file: juce_Typeface.cpp ***/
  70951. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  70952. BEGIN_JUCE_NAMESPACE
  70953. AffineTransform::AffineTransform() throw()
  70954. : mat00 (1.0f),
  70955. mat01 (0),
  70956. mat02 (0),
  70957. mat10 (0),
  70958. mat11 (1.0f),
  70959. mat12 (0)
  70960. {
  70961. }
  70962. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  70963. : mat00 (other.mat00),
  70964. mat01 (other.mat01),
  70965. mat02 (other.mat02),
  70966. mat10 (other.mat10),
  70967. mat11 (other.mat11),
  70968. mat12 (other.mat12)
  70969. {
  70970. }
  70971. AffineTransform::AffineTransform (const float mat00_,
  70972. const float mat01_,
  70973. const float mat02_,
  70974. const float mat10_,
  70975. const float mat11_,
  70976. const float mat12_) throw()
  70977. : mat00 (mat00_),
  70978. mat01 (mat01_),
  70979. mat02 (mat02_),
  70980. mat10 (mat10_),
  70981. mat11 (mat11_),
  70982. mat12 (mat12_)
  70983. {
  70984. }
  70985. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  70986. {
  70987. mat00 = other.mat00;
  70988. mat01 = other.mat01;
  70989. mat02 = other.mat02;
  70990. mat10 = other.mat10;
  70991. mat11 = other.mat11;
  70992. mat12 = other.mat12;
  70993. return *this;
  70994. }
  70995. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  70996. {
  70997. return mat00 == other.mat00
  70998. && mat01 == other.mat01
  70999. && mat02 == other.mat02
  71000. && mat10 == other.mat10
  71001. && mat11 == other.mat11
  71002. && mat12 == other.mat12;
  71003. }
  71004. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  71005. {
  71006. return ! operator== (other);
  71007. }
  71008. bool AffineTransform::isIdentity() const throw()
  71009. {
  71010. return (mat01 == 0)
  71011. && (mat02 == 0)
  71012. && (mat10 == 0)
  71013. && (mat12 == 0)
  71014. && (mat00 == 1.0f)
  71015. && (mat11 == 1.0f);
  71016. }
  71017. const AffineTransform AffineTransform::identity;
  71018. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  71019. {
  71020. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  71021. other.mat00 * mat01 + other.mat01 * mat11,
  71022. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  71023. other.mat10 * mat00 + other.mat11 * mat10,
  71024. other.mat10 * mat01 + other.mat11 * mat11,
  71025. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  71026. }
  71027. const AffineTransform AffineTransform::followedBy (const float omat00,
  71028. const float omat01,
  71029. const float omat02,
  71030. const float omat10,
  71031. const float omat11,
  71032. const float omat12) const throw()
  71033. {
  71034. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  71035. omat00 * mat01 + omat01 * mat11,
  71036. omat00 * mat02 + omat01 * mat12 + omat02,
  71037. omat10 * mat00 + omat11 * mat10,
  71038. omat10 * mat01 + omat11 * mat11,
  71039. omat10 * mat02 + omat11 * mat12 + omat12);
  71040. }
  71041. const AffineTransform AffineTransform::translated (const float dx,
  71042. const float dy) const throw()
  71043. {
  71044. return AffineTransform (mat00, mat01, mat02 + dx,
  71045. mat10, mat11, mat12 + dy);
  71046. }
  71047. const AffineTransform AffineTransform::translation (const float dx,
  71048. const float dy) throw()
  71049. {
  71050. return AffineTransform (1.0f, 0, dx,
  71051. 0, 1.0f, dy);
  71052. }
  71053. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  71054. {
  71055. const float cosRad = std::cos (rad);
  71056. const float sinRad = std::sin (rad);
  71057. return followedBy (cosRad, -sinRad, 0,
  71058. sinRad, cosRad, 0);
  71059. }
  71060. const AffineTransform AffineTransform::rotation (const float rad) throw()
  71061. {
  71062. const float cosRad = std::cos (rad);
  71063. const float sinRad = std::sin (rad);
  71064. return AffineTransform (cosRad, -sinRad, 0,
  71065. sinRad, cosRad, 0);
  71066. }
  71067. const AffineTransform AffineTransform::rotated (const float angle,
  71068. const float pivotX,
  71069. const float pivotY) const throw()
  71070. {
  71071. return translated (-pivotX, -pivotY)
  71072. .rotated (angle)
  71073. .translated (pivotX, pivotY);
  71074. }
  71075. const AffineTransform AffineTransform::rotation (const float angle,
  71076. const float pivotX,
  71077. const float pivotY) throw()
  71078. {
  71079. return translation (-pivotX, -pivotY)
  71080. .rotated (angle)
  71081. .translated (pivotX, pivotY);
  71082. }
  71083. const AffineTransform AffineTransform::scaled (const float factorX,
  71084. const float factorY) const throw()
  71085. {
  71086. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  71087. factorY * mat10, factorY * mat11, factorY * mat12);
  71088. }
  71089. const AffineTransform AffineTransform::scale (const float factorX,
  71090. const float factorY) throw()
  71091. {
  71092. return AffineTransform (factorX, 0, 0,
  71093. 0, factorY, 0);
  71094. }
  71095. const AffineTransform AffineTransform::sheared (const float shearX,
  71096. const float shearY) const throw()
  71097. {
  71098. return followedBy (1.0f, shearX, 0,
  71099. shearY, 1.0f, 0);
  71100. }
  71101. const AffineTransform AffineTransform::inverted() const throw()
  71102. {
  71103. double determinant = (mat00 * mat11 - mat10 * mat01);
  71104. if (determinant != 0.0)
  71105. {
  71106. determinant = 1.0 / determinant;
  71107. const float dst00 = (float) (mat11 * determinant);
  71108. const float dst10 = (float) (-mat10 * determinant);
  71109. const float dst01 = (float) (-mat01 * determinant);
  71110. const float dst11 = (float) (mat00 * determinant);
  71111. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  71112. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  71113. }
  71114. else
  71115. {
  71116. // singularity..
  71117. return *this;
  71118. }
  71119. }
  71120. bool AffineTransform::isSingularity() const throw()
  71121. {
  71122. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  71123. }
  71124. bool AffineTransform::isOnlyTranslation() const throw()
  71125. {
  71126. return (mat01 == 0)
  71127. && (mat10 == 0)
  71128. && (mat00 == 1.0f)
  71129. && (mat11 == 1.0f);
  71130. }
  71131. void AffineTransform::transformPoint (float& x,
  71132. float& y) const throw()
  71133. {
  71134. const float oldX = x;
  71135. x = mat00 * oldX + mat01 * y + mat02;
  71136. y = mat10 * oldX + mat11 * y + mat12;
  71137. }
  71138. void AffineTransform::transformPoint (double& x,
  71139. double& y) const throw()
  71140. {
  71141. const double oldX = x;
  71142. x = mat00 * oldX + mat01 * y + mat02;
  71143. y = mat10 * oldX + mat11 * y + mat12;
  71144. }
  71145. END_JUCE_NAMESPACE
  71146. /*** End of inlined file: juce_AffineTransform.cpp ***/
  71147. /*** Start of inlined file: juce_BorderSize.cpp ***/
  71148. BEGIN_JUCE_NAMESPACE
  71149. BorderSize::BorderSize() throw()
  71150. : top (0),
  71151. left (0),
  71152. bottom (0),
  71153. right (0)
  71154. {
  71155. }
  71156. BorderSize::BorderSize (const BorderSize& other) throw()
  71157. : top (other.top),
  71158. left (other.left),
  71159. bottom (other.bottom),
  71160. right (other.right)
  71161. {
  71162. }
  71163. BorderSize::BorderSize (const int topGap,
  71164. const int leftGap,
  71165. const int bottomGap,
  71166. const int rightGap) throw()
  71167. : top (topGap),
  71168. left (leftGap),
  71169. bottom (bottomGap),
  71170. right (rightGap)
  71171. {
  71172. }
  71173. BorderSize::BorderSize (const int allGaps) throw()
  71174. : top (allGaps),
  71175. left (allGaps),
  71176. bottom (allGaps),
  71177. right (allGaps)
  71178. {
  71179. }
  71180. BorderSize::~BorderSize() throw()
  71181. {
  71182. }
  71183. void BorderSize::setTop (const int newTopGap) throw()
  71184. {
  71185. top = newTopGap;
  71186. }
  71187. void BorderSize::setLeft (const int newLeftGap) throw()
  71188. {
  71189. left = newLeftGap;
  71190. }
  71191. void BorderSize::setBottom (const int newBottomGap) throw()
  71192. {
  71193. bottom = newBottomGap;
  71194. }
  71195. void BorderSize::setRight (const int newRightGap) throw()
  71196. {
  71197. right = newRightGap;
  71198. }
  71199. const Rectangle<int> BorderSize::subtractedFrom (const Rectangle<int>& r) const throw()
  71200. {
  71201. return Rectangle<int> (r.getX() + left,
  71202. r.getY() + top,
  71203. r.getWidth() - (left + right),
  71204. r.getHeight() - (top + bottom));
  71205. }
  71206. void BorderSize::subtractFrom (Rectangle<int>& r) const throw()
  71207. {
  71208. r.setBounds (r.getX() + left,
  71209. r.getY() + top,
  71210. r.getWidth() - (left + right),
  71211. r.getHeight() - (top + bottom));
  71212. }
  71213. const Rectangle<int> BorderSize::addedTo (const Rectangle<int>& r) const throw()
  71214. {
  71215. return Rectangle<int> (r.getX() - left,
  71216. r.getY() - top,
  71217. r.getWidth() + (left + right),
  71218. r.getHeight() + (top + bottom));
  71219. }
  71220. void BorderSize::addTo (Rectangle<int>& r) const throw()
  71221. {
  71222. r.setBounds (r.getX() - left,
  71223. r.getY() - top,
  71224. r.getWidth() + (left + right),
  71225. r.getHeight() + (top + bottom));
  71226. }
  71227. bool BorderSize::operator== (const BorderSize& other) const throw()
  71228. {
  71229. return top == other.top
  71230. && left == other.left
  71231. && bottom == other.bottom
  71232. && right == other.right;
  71233. }
  71234. bool BorderSize::operator!= (const BorderSize& other) const throw()
  71235. {
  71236. return ! operator== (other);
  71237. }
  71238. END_JUCE_NAMESPACE
  71239. /*** End of inlined file: juce_BorderSize.cpp ***/
  71240. /*** Start of inlined file: juce_Line.cpp ***/
  71241. BEGIN_JUCE_NAMESPACE
  71242. END_JUCE_NAMESPACE
  71243. /*** End of inlined file: juce_Line.cpp ***/
  71244. /*** Start of inlined file: juce_Path.cpp ***/
  71245. BEGIN_JUCE_NAMESPACE
  71246. // tests that some co-ords aren't NaNs
  71247. #define CHECK_COORDS_ARE_VALID(x, y) \
  71248. jassert (x == x && y == y);
  71249. namespace PathHelpers
  71250. {
  71251. static const float ellipseAngularIncrement = 0.05f;
  71252. static void perpendicularOffset (const float x1, const float y1,
  71253. const float x2, const float y2,
  71254. const float offsetX, const float offsetY,
  71255. float& resultX, float& resultY) throw()
  71256. {
  71257. const float dx = x2 - x1;
  71258. const float dy = y2 - y1;
  71259. const float len = juce_hypotf (dx, dy);
  71260. if (len == 0)
  71261. {
  71262. resultX = x1;
  71263. resultY = y1;
  71264. }
  71265. else
  71266. {
  71267. resultX = x1 + ((dx * offsetX) - (dy * offsetY)) / len;
  71268. resultY = y1 + ((dy * offsetX) + (dx * offsetY)) / len;
  71269. }
  71270. }
  71271. static const String nextToken (const juce_wchar*& t)
  71272. {
  71273. while (CharacterFunctions::isWhitespace (*t))
  71274. ++t;
  71275. const juce_wchar* const start = t;
  71276. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  71277. ++t;
  71278. const int length = (int) (t - start);
  71279. while (CharacterFunctions::isWhitespace (*t))
  71280. ++t;
  71281. return String (start, length);
  71282. }
  71283. }
  71284. const float Path::lineMarker = 100001.0f;
  71285. const float Path::moveMarker = 100002.0f;
  71286. const float Path::quadMarker = 100003.0f;
  71287. const float Path::cubicMarker = 100004.0f;
  71288. const float Path::closeSubPathMarker = 100005.0f;
  71289. Path::Path()
  71290. : numElements (0),
  71291. pathXMin (0),
  71292. pathXMax (0),
  71293. pathYMin (0),
  71294. pathYMax (0),
  71295. useNonZeroWinding (true)
  71296. {
  71297. }
  71298. Path::~Path()
  71299. {
  71300. }
  71301. Path::Path (const Path& other)
  71302. : numElements (other.numElements),
  71303. pathXMin (other.pathXMin),
  71304. pathXMax (other.pathXMax),
  71305. pathYMin (other.pathYMin),
  71306. pathYMax (other.pathYMax),
  71307. useNonZeroWinding (other.useNonZeroWinding)
  71308. {
  71309. if (numElements > 0)
  71310. {
  71311. data.setAllocatedSize ((int) numElements);
  71312. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  71313. }
  71314. }
  71315. Path& Path::operator= (const Path& other)
  71316. {
  71317. if (this != &other)
  71318. {
  71319. data.ensureAllocatedSize ((int) other.numElements);
  71320. numElements = other.numElements;
  71321. pathXMin = other.pathXMin;
  71322. pathXMax = other.pathXMax;
  71323. pathYMin = other.pathYMin;
  71324. pathYMax = other.pathYMax;
  71325. useNonZeroWinding = other.useNonZeroWinding;
  71326. if (numElements > 0)
  71327. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  71328. }
  71329. return *this;
  71330. }
  71331. void Path::clear() throw()
  71332. {
  71333. numElements = 0;
  71334. pathXMin = 0;
  71335. pathYMin = 0;
  71336. pathYMax = 0;
  71337. pathXMax = 0;
  71338. }
  71339. void Path::swapWithPath (Path& other)
  71340. {
  71341. data.swapWith (other.data);
  71342. swapVariables <size_t> (numElements, other.numElements);
  71343. swapVariables <float> (pathXMin, other.pathXMin);
  71344. swapVariables <float> (pathXMax, other.pathXMax);
  71345. swapVariables <float> (pathYMin, other.pathYMin);
  71346. swapVariables <float> (pathYMax, other.pathYMax);
  71347. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  71348. }
  71349. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  71350. {
  71351. useNonZeroWinding = isNonZero;
  71352. }
  71353. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  71354. const bool preserveProportions) throw()
  71355. {
  71356. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  71357. }
  71358. bool Path::isEmpty() const throw()
  71359. {
  71360. size_t i = 0;
  71361. while (i < numElements)
  71362. {
  71363. const float type = data.elements [i++];
  71364. if (type == moveMarker)
  71365. {
  71366. i += 2;
  71367. }
  71368. else if (type == lineMarker
  71369. || type == quadMarker
  71370. || type == cubicMarker)
  71371. {
  71372. return false;
  71373. }
  71374. }
  71375. return true;
  71376. }
  71377. const Rectangle<float> Path::getBounds() const throw()
  71378. {
  71379. return Rectangle<float> (pathXMin, pathYMin,
  71380. pathXMax - pathXMin,
  71381. pathYMax - pathYMin);
  71382. }
  71383. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  71384. {
  71385. return getBounds().transformed (transform);
  71386. }
  71387. void Path::startNewSubPath (const float x, const float y)
  71388. {
  71389. CHECK_COORDS_ARE_VALID (x, y);
  71390. if (numElements == 0)
  71391. {
  71392. pathXMin = pathXMax = x;
  71393. pathYMin = pathYMax = y;
  71394. }
  71395. else
  71396. {
  71397. pathXMin = jmin (pathXMin, x);
  71398. pathXMax = jmax (pathXMax, x);
  71399. pathYMin = jmin (pathYMin, y);
  71400. pathYMax = jmax (pathYMax, y);
  71401. }
  71402. data.ensureAllocatedSize ((int) numElements + 3);
  71403. data.elements [numElements++] = moveMarker;
  71404. data.elements [numElements++] = x;
  71405. data.elements [numElements++] = y;
  71406. }
  71407. void Path::lineTo (const float x, const float y)
  71408. {
  71409. CHECK_COORDS_ARE_VALID (x, y);
  71410. if (numElements == 0)
  71411. startNewSubPath (0, 0);
  71412. data.ensureAllocatedSize ((int) numElements + 3);
  71413. data.elements [numElements++] = lineMarker;
  71414. data.elements [numElements++] = x;
  71415. data.elements [numElements++] = y;
  71416. pathXMin = jmin (pathXMin, x);
  71417. pathXMax = jmax (pathXMax, x);
  71418. pathYMin = jmin (pathYMin, y);
  71419. pathYMax = jmax (pathYMax, y);
  71420. }
  71421. void Path::quadraticTo (const float x1, const float y1,
  71422. const float x2, const float y2)
  71423. {
  71424. CHECK_COORDS_ARE_VALID (x1, y1);
  71425. CHECK_COORDS_ARE_VALID (x2, y2);
  71426. if (numElements == 0)
  71427. startNewSubPath (0, 0);
  71428. data.ensureAllocatedSize ((int) numElements + 5);
  71429. data.elements [numElements++] = quadMarker;
  71430. data.elements [numElements++] = x1;
  71431. data.elements [numElements++] = y1;
  71432. data.elements [numElements++] = x2;
  71433. data.elements [numElements++] = y2;
  71434. pathXMin = jmin (pathXMin, x1, x2);
  71435. pathXMax = jmax (pathXMax, x1, x2);
  71436. pathYMin = jmin (pathYMin, y1, y2);
  71437. pathYMax = jmax (pathYMax, y1, y2);
  71438. }
  71439. void Path::cubicTo (const float x1, const float y1,
  71440. const float x2, const float y2,
  71441. const float x3, const float y3)
  71442. {
  71443. CHECK_COORDS_ARE_VALID (x1, y1);
  71444. CHECK_COORDS_ARE_VALID (x2, y2);
  71445. CHECK_COORDS_ARE_VALID (x3, y3);
  71446. if (numElements == 0)
  71447. startNewSubPath (0, 0);
  71448. data.ensureAllocatedSize ((int) numElements + 7);
  71449. data.elements [numElements++] = cubicMarker;
  71450. data.elements [numElements++] = x1;
  71451. data.elements [numElements++] = y1;
  71452. data.elements [numElements++] = x2;
  71453. data.elements [numElements++] = y2;
  71454. data.elements [numElements++] = x3;
  71455. data.elements [numElements++] = y3;
  71456. pathXMin = jmin (pathXMin, x1, x2, x3);
  71457. pathXMax = jmax (pathXMax, x1, x2, x3);
  71458. pathYMin = jmin (pathYMin, y1, y2, y3);
  71459. pathYMax = jmax (pathYMax, y1, y2, y3);
  71460. }
  71461. void Path::closeSubPath()
  71462. {
  71463. if (numElements > 0
  71464. && data.elements [numElements - 1] != closeSubPathMarker)
  71465. {
  71466. data.ensureAllocatedSize ((int) numElements + 1);
  71467. data.elements [numElements++] = closeSubPathMarker;
  71468. }
  71469. }
  71470. const Point<float> Path::getCurrentPosition() const
  71471. {
  71472. size_t i = numElements - 1;
  71473. if (i > 0 && data.elements[i] == closeSubPathMarker)
  71474. {
  71475. while (i >= 0)
  71476. {
  71477. if (data.elements[i] == moveMarker)
  71478. {
  71479. i += 2;
  71480. break;
  71481. }
  71482. --i;
  71483. }
  71484. }
  71485. if (i > 0)
  71486. return Point<float> (data.elements [i - 1], data.elements [i]);
  71487. return Point<float>();
  71488. }
  71489. void Path::addRectangle (const float x, const float y,
  71490. const float w, const float h)
  71491. {
  71492. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  71493. if (w < 0)
  71494. swapVariables (x1, x2);
  71495. if (h < 0)
  71496. swapVariables (y1, y2);
  71497. data.ensureAllocatedSize ((int) numElements + 13);
  71498. if (numElements == 0)
  71499. {
  71500. pathXMin = x1;
  71501. pathXMax = x2;
  71502. pathYMin = y1;
  71503. pathYMax = y2;
  71504. }
  71505. else
  71506. {
  71507. pathXMin = jmin (pathXMin, x1);
  71508. pathXMax = jmax (pathXMax, x2);
  71509. pathYMin = jmin (pathYMin, y1);
  71510. pathYMax = jmax (pathYMax, y2);
  71511. }
  71512. data.elements [numElements++] = moveMarker;
  71513. data.elements [numElements++] = x1;
  71514. data.elements [numElements++] = y2;
  71515. data.elements [numElements++] = lineMarker;
  71516. data.elements [numElements++] = x1;
  71517. data.elements [numElements++] = y1;
  71518. data.elements [numElements++] = lineMarker;
  71519. data.elements [numElements++] = x2;
  71520. data.elements [numElements++] = y1;
  71521. data.elements [numElements++] = lineMarker;
  71522. data.elements [numElements++] = x2;
  71523. data.elements [numElements++] = y2;
  71524. data.elements [numElements++] = closeSubPathMarker;
  71525. }
  71526. void Path::addRectangle (const Rectangle<int>& rectangle)
  71527. {
  71528. addRectangle ((float) rectangle.getX(), (float) rectangle.getY(),
  71529. (float) rectangle.getWidth(), (float) rectangle.getHeight());
  71530. }
  71531. void Path::addRoundedRectangle (const float x, const float y,
  71532. const float w, const float h,
  71533. float csx,
  71534. float csy)
  71535. {
  71536. csx = jmin (csx, w * 0.5f);
  71537. csy = jmin (csy, h * 0.5f);
  71538. const float cs45x = csx * 0.45f;
  71539. const float cs45y = csy * 0.45f;
  71540. const float x2 = x + w;
  71541. const float y2 = y + h;
  71542. startNewSubPath (x + csx, y);
  71543. lineTo (x2 - csx, y);
  71544. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  71545. lineTo (x2, y2 - csy);
  71546. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  71547. lineTo (x + csx, y2);
  71548. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  71549. lineTo (x, y + csy);
  71550. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  71551. closeSubPath();
  71552. }
  71553. void Path::addRoundedRectangle (const float x, const float y,
  71554. const float w, const float h,
  71555. float cs)
  71556. {
  71557. addRoundedRectangle (x, y, w, h, cs, cs);
  71558. }
  71559. void Path::addTriangle (const float x1, const float y1,
  71560. const float x2, const float y2,
  71561. const float x3, const float y3)
  71562. {
  71563. startNewSubPath (x1, y1);
  71564. lineTo (x2, y2);
  71565. lineTo (x3, y3);
  71566. closeSubPath();
  71567. }
  71568. void Path::addQuadrilateral (const float x1, const float y1,
  71569. const float x2, const float y2,
  71570. const float x3, const float y3,
  71571. const float x4, const float y4)
  71572. {
  71573. startNewSubPath (x1, y1);
  71574. lineTo (x2, y2);
  71575. lineTo (x3, y3);
  71576. lineTo (x4, y4);
  71577. closeSubPath();
  71578. }
  71579. void Path::addEllipse (const float x, const float y,
  71580. const float w, const float h)
  71581. {
  71582. const float hw = w * 0.5f;
  71583. const float hw55 = hw * 0.55f;
  71584. const float hh = h * 0.5f;
  71585. const float hh45 = hh * 0.55f;
  71586. const float cx = x + hw;
  71587. const float cy = y + hh;
  71588. startNewSubPath (cx, cy - hh);
  71589. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  71590. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  71591. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  71592. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  71593. closeSubPath();
  71594. }
  71595. void Path::addArc (const float x, const float y,
  71596. const float w, const float h,
  71597. const float fromRadians,
  71598. const float toRadians,
  71599. const bool startAsNewSubPath)
  71600. {
  71601. const float radiusX = w / 2.0f;
  71602. const float radiusY = h / 2.0f;
  71603. addCentredArc (x + radiusX,
  71604. y + radiusY,
  71605. radiusX, radiusY,
  71606. 0.0f,
  71607. fromRadians, toRadians,
  71608. startAsNewSubPath);
  71609. }
  71610. void Path::addCentredArc (const float centreX, const float centreY,
  71611. const float radiusX, const float radiusY,
  71612. const float rotationOfEllipse,
  71613. const float fromRadians,
  71614. const float toRadians,
  71615. const bool startAsNewSubPath)
  71616. {
  71617. if (radiusX > 0.0f && radiusY > 0.0f)
  71618. {
  71619. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  71620. float angle = fromRadians;
  71621. if (startAsNewSubPath)
  71622. {
  71623. float x = centreX + radiusX * std::sin (angle);
  71624. float y = centreY - radiusY * std::cos (angle);
  71625. if (rotationOfEllipse != 0)
  71626. rotation.transformPoint (x, y);
  71627. startNewSubPath (x, y);
  71628. }
  71629. if (fromRadians < toRadians)
  71630. {
  71631. if (startAsNewSubPath)
  71632. angle += PathHelpers::ellipseAngularIncrement;
  71633. while (angle < toRadians)
  71634. {
  71635. float x = centreX + radiusX * std::sin (angle);
  71636. float y = centreY - radiusY * std::cos (angle);
  71637. if (rotationOfEllipse != 0)
  71638. rotation.transformPoint (x, y);
  71639. lineTo (x, y);
  71640. angle += PathHelpers::ellipseAngularIncrement;
  71641. }
  71642. }
  71643. else
  71644. {
  71645. if (startAsNewSubPath)
  71646. angle -= PathHelpers::ellipseAngularIncrement;
  71647. while (angle > toRadians)
  71648. {
  71649. float x = centreX + radiusX * std::sin (angle);
  71650. float y = centreY - radiusY * std::cos (angle);
  71651. if (rotationOfEllipse != 0)
  71652. rotation.transformPoint (x, y);
  71653. lineTo (x, y);
  71654. angle -= PathHelpers::ellipseAngularIncrement;
  71655. }
  71656. }
  71657. float x = centreX + radiusX * std::sin (toRadians);
  71658. float y = centreY - radiusY * std::cos (toRadians);
  71659. if (rotationOfEllipse != 0)
  71660. rotation.transformPoint (x, y);
  71661. lineTo (x, y);
  71662. }
  71663. }
  71664. void Path::addPieSegment (const float x, const float y,
  71665. const float width, const float height,
  71666. const float fromRadians,
  71667. const float toRadians,
  71668. const float innerCircleProportionalSize)
  71669. {
  71670. float hw = width * 0.5f;
  71671. float hh = height * 0.5f;
  71672. const float centreX = x + hw;
  71673. const float centreY = y + hh;
  71674. startNewSubPath (centreX + hw * std::sin (fromRadians),
  71675. centreY - hh * std::cos (fromRadians));
  71676. addArc (x, y, width, height, fromRadians, toRadians);
  71677. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  71678. {
  71679. closeSubPath();
  71680. if (innerCircleProportionalSize > 0)
  71681. {
  71682. hw *= innerCircleProportionalSize;
  71683. hh *= innerCircleProportionalSize;
  71684. startNewSubPath (centreX + hw * std::sin (toRadians),
  71685. centreY - hh * std::cos (toRadians));
  71686. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  71687. toRadians, fromRadians);
  71688. }
  71689. }
  71690. else
  71691. {
  71692. if (innerCircleProportionalSize > 0)
  71693. {
  71694. hw *= innerCircleProportionalSize;
  71695. hh *= innerCircleProportionalSize;
  71696. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  71697. toRadians, fromRadians);
  71698. }
  71699. else
  71700. {
  71701. lineTo (centreX, centreY);
  71702. }
  71703. }
  71704. closeSubPath();
  71705. }
  71706. void Path::addLineSegment (const float startX, const float startY,
  71707. const float endX, const float endY,
  71708. float lineThickness)
  71709. {
  71710. lineThickness *= 0.5f;
  71711. float x, y;
  71712. PathHelpers::perpendicularOffset (startX, startY, endX, endY,
  71713. 0, lineThickness, x, y);
  71714. startNewSubPath (x, y);
  71715. PathHelpers::perpendicularOffset (startX, startY, endX, endY,
  71716. 0, -lineThickness, x, y);
  71717. lineTo (x, y);
  71718. PathHelpers::perpendicularOffset (endX, endY, startX, startY,
  71719. 0, lineThickness, x, y);
  71720. lineTo (x, y);
  71721. PathHelpers::perpendicularOffset (endX, endY, startX, startY,
  71722. 0, -lineThickness, x, y);
  71723. lineTo (x, y);
  71724. closeSubPath();
  71725. }
  71726. void Path::addArrow (const float startX, const float startY,
  71727. const float endX, const float endY,
  71728. float lineThickness,
  71729. float arrowheadWidth,
  71730. float arrowheadLength)
  71731. {
  71732. lineThickness *= 0.5f;
  71733. arrowheadWidth *= 0.5f;
  71734. arrowheadLength = jmin (arrowheadLength, 0.8f * juce_hypotf (startX - endX,
  71735. startY - endY));
  71736. float x, y;
  71737. PathHelpers::perpendicularOffset (startX, startY, endX, endY,
  71738. 0, lineThickness, x, y);
  71739. startNewSubPath (x, y);
  71740. PathHelpers::perpendicularOffset (startX, startY, endX, endY,
  71741. 0, -lineThickness, x, y);
  71742. lineTo (x, y);
  71743. PathHelpers::perpendicularOffset (endX, endY, startX, startY,
  71744. arrowheadLength, lineThickness, x, y);
  71745. lineTo (x, y);
  71746. PathHelpers::perpendicularOffset (endX, endY, startX, startY,
  71747. arrowheadLength, arrowheadWidth, x, y);
  71748. lineTo (x, y);
  71749. PathHelpers::perpendicularOffset (endX, endY, startX, startY,
  71750. 0, 0, x, y);
  71751. lineTo (x, y);
  71752. PathHelpers::perpendicularOffset (endX, endY, startX, startY,
  71753. arrowheadLength, -arrowheadWidth, x, y);
  71754. lineTo (x, y);
  71755. PathHelpers::perpendicularOffset (endX, endY, startX, startY,
  71756. arrowheadLength, -lineThickness, x, y);
  71757. lineTo (x, y);
  71758. closeSubPath();
  71759. }
  71760. void Path::addStar (const float centreX,
  71761. const float centreY,
  71762. const int numberOfPoints,
  71763. const float innerRadius,
  71764. const float outerRadius,
  71765. const float startAngle)
  71766. {
  71767. jassert (numberOfPoints > 1); // this would be silly.
  71768. if (numberOfPoints > 1)
  71769. {
  71770. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  71771. for (int i = 0; i < numberOfPoints; ++i)
  71772. {
  71773. float angle = startAngle + i * angleBetweenPoints;
  71774. const float x = centreX + outerRadius * std::sin (angle);
  71775. const float y = centreY - outerRadius * std::cos (angle);
  71776. if (i == 0)
  71777. startNewSubPath (x, y);
  71778. else
  71779. lineTo (x, y);
  71780. angle += angleBetweenPoints * 0.5f;
  71781. lineTo (centreX + innerRadius * std::sin (angle),
  71782. centreY - innerRadius * std::cos (angle));
  71783. }
  71784. closeSubPath();
  71785. }
  71786. }
  71787. void Path::addBubble (float x, float y,
  71788. float w, float h,
  71789. float cs,
  71790. float tipX,
  71791. float tipY,
  71792. int whichSide,
  71793. float arrowPos,
  71794. float arrowWidth)
  71795. {
  71796. if (w > 1.0f && h > 1.0f)
  71797. {
  71798. cs = jmin (cs, w * 0.5f, h * 0.5f);
  71799. const float cs2 = 2.0f * cs;
  71800. startNewSubPath (x + cs, y);
  71801. if (whichSide == 0)
  71802. {
  71803. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  71804. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  71805. lineTo (arrowX1, y);
  71806. lineTo (tipX, tipY);
  71807. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  71808. }
  71809. lineTo (x + w - cs, y);
  71810. if (cs > 0.0f)
  71811. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  71812. if (whichSide == 3)
  71813. {
  71814. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  71815. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  71816. lineTo (x + w, arrowY1);
  71817. lineTo (tipX, tipY);
  71818. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  71819. }
  71820. lineTo (x + w, y + h - cs);
  71821. if (cs > 0.0f)
  71822. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  71823. if (whichSide == 2)
  71824. {
  71825. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  71826. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  71827. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  71828. lineTo (tipX, tipY);
  71829. lineTo (arrowX1, y + h);
  71830. }
  71831. lineTo (x + cs, y + h);
  71832. if (cs > 0.0f)
  71833. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  71834. if (whichSide == 1)
  71835. {
  71836. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  71837. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  71838. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  71839. lineTo (tipX, tipY);
  71840. lineTo (x, arrowY1);
  71841. }
  71842. lineTo (x, y + cs);
  71843. if (cs > 0.0f)
  71844. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  71845. closeSubPath();
  71846. }
  71847. }
  71848. void Path::addPath (const Path& other)
  71849. {
  71850. size_t i = 0;
  71851. while (i < other.numElements)
  71852. {
  71853. const float type = other.data.elements [i++];
  71854. if (type == moveMarker)
  71855. {
  71856. startNewSubPath (other.data.elements [i],
  71857. other.data.elements [i + 1]);
  71858. i += 2;
  71859. }
  71860. else if (type == lineMarker)
  71861. {
  71862. lineTo (other.data.elements [i],
  71863. other.data.elements [i + 1]);
  71864. i += 2;
  71865. }
  71866. else if (type == quadMarker)
  71867. {
  71868. quadraticTo (other.data.elements [i],
  71869. other.data.elements [i + 1],
  71870. other.data.elements [i + 2],
  71871. other.data.elements [i + 3]);
  71872. i += 4;
  71873. }
  71874. else if (type == cubicMarker)
  71875. {
  71876. cubicTo (other.data.elements [i],
  71877. other.data.elements [i + 1],
  71878. other.data.elements [i + 2],
  71879. other.data.elements [i + 3],
  71880. other.data.elements [i + 4],
  71881. other.data.elements [i + 5]);
  71882. i += 6;
  71883. }
  71884. else if (type == closeSubPathMarker)
  71885. {
  71886. closeSubPath();
  71887. }
  71888. else
  71889. {
  71890. // something's gone wrong with the element list!
  71891. jassertfalse
  71892. }
  71893. }
  71894. }
  71895. void Path::addPath (const Path& other,
  71896. const AffineTransform& transformToApply)
  71897. {
  71898. size_t i = 0;
  71899. while (i < other.numElements)
  71900. {
  71901. const float type = other.data.elements [i++];
  71902. if (type == closeSubPathMarker)
  71903. {
  71904. closeSubPath();
  71905. }
  71906. else
  71907. {
  71908. float x = other.data.elements [i++];
  71909. float y = other.data.elements [i++];
  71910. transformToApply.transformPoint (x, y);
  71911. if (type == moveMarker)
  71912. {
  71913. startNewSubPath (x, y);
  71914. }
  71915. else if (type == lineMarker)
  71916. {
  71917. lineTo (x, y);
  71918. }
  71919. else if (type == quadMarker)
  71920. {
  71921. float x2 = other.data.elements [i++];
  71922. float y2 = other.data.elements [i++];
  71923. transformToApply.transformPoint (x2, y2);
  71924. quadraticTo (x, y, x2, y2);
  71925. }
  71926. else if (type == cubicMarker)
  71927. {
  71928. float x2 = other.data.elements [i++];
  71929. float y2 = other.data.elements [i++];
  71930. float x3 = other.data.elements [i++];
  71931. float y3 = other.data.elements [i++];
  71932. transformToApply.transformPoint (x2, y2);
  71933. transformToApply.transformPoint (x3, y3);
  71934. cubicTo (x, y, x2, y2, x3, y3);
  71935. }
  71936. else
  71937. {
  71938. // something's gone wrong with the element list!
  71939. jassertfalse
  71940. }
  71941. }
  71942. }
  71943. }
  71944. void Path::applyTransform (const AffineTransform& transform) throw()
  71945. {
  71946. size_t i = 0;
  71947. pathYMin = pathXMin = 0;
  71948. pathYMax = pathXMax = 0;
  71949. bool setMaxMin = false;
  71950. while (i < numElements)
  71951. {
  71952. const float type = data.elements [i++];
  71953. if (type == moveMarker)
  71954. {
  71955. transform.transformPoint (data.elements [i],
  71956. data.elements [i + 1]);
  71957. if (setMaxMin)
  71958. {
  71959. pathXMin = jmin (pathXMin, data.elements [i]);
  71960. pathXMax = jmax (pathXMax, data.elements [i]);
  71961. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  71962. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  71963. }
  71964. else
  71965. {
  71966. pathXMin = pathXMax = data.elements [i];
  71967. pathYMin = pathYMax = data.elements [i + 1];
  71968. setMaxMin = true;
  71969. }
  71970. i += 2;
  71971. }
  71972. else if (type == lineMarker)
  71973. {
  71974. transform.transformPoint (data.elements [i],
  71975. data.elements [i + 1]);
  71976. pathXMin = jmin (pathXMin, data.elements [i]);
  71977. pathXMax = jmax (pathXMax, data.elements [i]);
  71978. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  71979. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  71980. i += 2;
  71981. }
  71982. else if (type == quadMarker)
  71983. {
  71984. transform.transformPoint (data.elements [i],
  71985. data.elements [i + 1]);
  71986. transform.transformPoint (data.elements [i + 2],
  71987. data.elements [i + 3]);
  71988. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  71989. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  71990. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  71991. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  71992. i += 4;
  71993. }
  71994. else if (type == cubicMarker)
  71995. {
  71996. transform.transformPoint (data.elements [i],
  71997. data.elements [i + 1]);
  71998. transform.transformPoint (data.elements [i + 2],
  71999. data.elements [i + 3]);
  72000. transform.transformPoint (data.elements [i + 4],
  72001. data.elements [i + 5]);
  72002. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  72003. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  72004. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  72005. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  72006. i += 6;
  72007. }
  72008. }
  72009. }
  72010. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  72011. const float w, const float h,
  72012. const bool preserveProportions,
  72013. const Justification& justification) const
  72014. {
  72015. Rectangle<float> bounds (getBounds());
  72016. if (preserveProportions)
  72017. {
  72018. if (w <= 0 || h <= 0 || bounds.isEmpty())
  72019. return AffineTransform::identity;
  72020. float newW, newH;
  72021. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  72022. if (srcRatio > h / w)
  72023. {
  72024. newW = h / srcRatio;
  72025. newH = h;
  72026. }
  72027. else
  72028. {
  72029. newW = w;
  72030. newH = w * srcRatio;
  72031. }
  72032. float newXCentre = x;
  72033. float newYCentre = y;
  72034. if (justification.testFlags (Justification::left))
  72035. newXCentre += newW * 0.5f;
  72036. else if (justification.testFlags (Justification::right))
  72037. newXCentre += w - newW * 0.5f;
  72038. else
  72039. newXCentre += w * 0.5f;
  72040. if (justification.testFlags (Justification::top))
  72041. newYCentre += newH * 0.5f;
  72042. else if (justification.testFlags (Justification::bottom))
  72043. newYCentre += h - newH * 0.5f;
  72044. else
  72045. newYCentre += h * 0.5f;
  72046. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  72047. bounds.getHeight() * -0.5f - bounds.getY())
  72048. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  72049. .translated (newXCentre, newYCentre);
  72050. }
  72051. else
  72052. {
  72053. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  72054. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  72055. .translated (x, y);
  72056. }
  72057. }
  72058. bool Path::contains (const float x, const float y, const float tolerence) const
  72059. {
  72060. if (x <= pathXMin || x >= pathXMax
  72061. || y <= pathYMin || y >= pathYMax)
  72062. return false;
  72063. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  72064. int positiveCrossings = 0;
  72065. int negativeCrossings = 0;
  72066. while (i.next())
  72067. {
  72068. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  72069. {
  72070. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  72071. if (intersectX <= x)
  72072. {
  72073. if (i.y1 < i.y2)
  72074. ++positiveCrossings;
  72075. else
  72076. ++negativeCrossings;
  72077. }
  72078. }
  72079. }
  72080. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  72081. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  72082. }
  72083. bool Path::contains (const Point<float>& point, const float tolerence) const
  72084. {
  72085. return contains (point.getX(), point.getY(), tolerence);
  72086. }
  72087. bool Path::intersectsLine (const Line<float>& line, const float tolerence)
  72088. {
  72089. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  72090. Point<float> intersection;
  72091. while (i.next())
  72092. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  72093. return true;
  72094. return false;
  72095. }
  72096. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  72097. {
  72098. Line<float> result (line);
  72099. const bool startInside = contains (line.getStart());
  72100. const bool endInside = contains (line.getEnd());
  72101. if (startInside == endInside)
  72102. {
  72103. if (keepSectionOutsidePath == startInside)
  72104. result = Line<float>();
  72105. }
  72106. else
  72107. {
  72108. PathFlatteningIterator i (*this, AffineTransform::identity);
  72109. Point<float> intersection;
  72110. while (i.next())
  72111. {
  72112. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  72113. {
  72114. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  72115. result.setStart (intersection);
  72116. else
  72117. result.setEnd (intersection);
  72118. }
  72119. }
  72120. }
  72121. return result;
  72122. }
  72123. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  72124. {
  72125. if (cornerRadius <= 0.01f)
  72126. return *this;
  72127. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  72128. size_t n = 0;
  72129. bool lastWasLine = false, firstWasLine = false;
  72130. Path p;
  72131. while (n < numElements)
  72132. {
  72133. const float type = data.elements [n++];
  72134. if (type == moveMarker)
  72135. {
  72136. indexOfPathStart = p.numElements;
  72137. indexOfPathStartThis = n - 1;
  72138. const float x = data.elements [n++];
  72139. const float y = data.elements [n++];
  72140. p.startNewSubPath (x, y);
  72141. lastWasLine = false;
  72142. firstWasLine = (data.elements [n] == lineMarker);
  72143. }
  72144. else if (type == lineMarker || type == closeSubPathMarker)
  72145. {
  72146. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  72147. if (type == lineMarker)
  72148. {
  72149. endX = data.elements [n++];
  72150. endY = data.elements [n++];
  72151. if (n > 8)
  72152. {
  72153. startX = data.elements [n - 8];
  72154. startY = data.elements [n - 7];
  72155. joinX = data.elements [n - 5];
  72156. joinY = data.elements [n - 4];
  72157. }
  72158. }
  72159. else
  72160. {
  72161. endX = data.elements [indexOfPathStartThis + 1];
  72162. endY = data.elements [indexOfPathStartThis + 2];
  72163. if (n > 6)
  72164. {
  72165. startX = data.elements [n - 6];
  72166. startY = data.elements [n - 5];
  72167. joinX = data.elements [n - 3];
  72168. joinY = data.elements [n - 2];
  72169. }
  72170. }
  72171. if (lastWasLine)
  72172. {
  72173. const double len1 = juce_hypot (startX - joinX,
  72174. startY - joinY);
  72175. if (len1 > 0)
  72176. {
  72177. const double propNeeded = jmin (0.5, cornerRadius / len1);
  72178. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  72179. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  72180. }
  72181. const double len2 = juce_hypot (endX - joinX,
  72182. endY - joinY);
  72183. if (len2 > 0)
  72184. {
  72185. const double propNeeded = jmin (0.5, cornerRadius / len2);
  72186. p.quadraticTo (joinX, joinY,
  72187. (float) (joinX + (endX - joinX) * propNeeded),
  72188. (float) (joinY + (endY - joinY) * propNeeded));
  72189. }
  72190. p.lineTo (endX, endY);
  72191. }
  72192. else if (type == lineMarker)
  72193. {
  72194. p.lineTo (endX, endY);
  72195. lastWasLine = true;
  72196. }
  72197. if (type == closeSubPathMarker)
  72198. {
  72199. if (firstWasLine)
  72200. {
  72201. startX = data.elements [n - 3];
  72202. startY = data.elements [n - 2];
  72203. joinX = endX;
  72204. joinY = endY;
  72205. endX = data.elements [indexOfPathStartThis + 4];
  72206. endY = data.elements [indexOfPathStartThis + 5];
  72207. const double len1 = juce_hypot (startX - joinX,
  72208. startY - joinY);
  72209. if (len1 > 0)
  72210. {
  72211. const double propNeeded = jmin (0.5, cornerRadius / len1);
  72212. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  72213. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  72214. }
  72215. const double len2 = juce_hypot (endX - joinX,
  72216. endY - joinY);
  72217. if (len2 > 0)
  72218. {
  72219. const double propNeeded = jmin (0.5, cornerRadius / len2);
  72220. endX = (float) (joinX + (endX - joinX) * propNeeded);
  72221. endY = (float) (joinY + (endY - joinY) * propNeeded);
  72222. p.quadraticTo (joinX, joinY, endX, endY);
  72223. p.data.elements [indexOfPathStart + 1] = endX;
  72224. p.data.elements [indexOfPathStart + 2] = endY;
  72225. }
  72226. }
  72227. p.closeSubPath();
  72228. }
  72229. }
  72230. else if (type == quadMarker)
  72231. {
  72232. lastWasLine = false;
  72233. const float x1 = data.elements [n++];
  72234. const float y1 = data.elements [n++];
  72235. const float x2 = data.elements [n++];
  72236. const float y2 = data.elements [n++];
  72237. p.quadraticTo (x1, y1, x2, y2);
  72238. }
  72239. else if (type == cubicMarker)
  72240. {
  72241. lastWasLine = false;
  72242. const float x1 = data.elements [n++];
  72243. const float y1 = data.elements [n++];
  72244. const float x2 = data.elements [n++];
  72245. const float y2 = data.elements [n++];
  72246. const float x3 = data.elements [n++];
  72247. const float y3 = data.elements [n++];
  72248. p.cubicTo (x1, y1, x2, y2, x3, y3);
  72249. }
  72250. }
  72251. return p;
  72252. }
  72253. void Path::loadPathFromStream (InputStream& source)
  72254. {
  72255. while (! source.isExhausted())
  72256. {
  72257. switch (source.readByte())
  72258. {
  72259. case 'm':
  72260. {
  72261. const float x = source.readFloat();
  72262. const float y = source.readFloat();
  72263. startNewSubPath (x, y);
  72264. break;
  72265. }
  72266. case 'l':
  72267. {
  72268. const float x = source.readFloat();
  72269. const float y = source.readFloat();
  72270. lineTo (x, y);
  72271. break;
  72272. }
  72273. case 'q':
  72274. {
  72275. const float x1 = source.readFloat();
  72276. const float y1 = source.readFloat();
  72277. const float x2 = source.readFloat();
  72278. const float y2 = source.readFloat();
  72279. quadraticTo (x1, y1, x2, y2);
  72280. break;
  72281. }
  72282. case 'b':
  72283. {
  72284. const float x1 = source.readFloat();
  72285. const float y1 = source.readFloat();
  72286. const float x2 = source.readFloat();
  72287. const float y2 = source.readFloat();
  72288. const float x3 = source.readFloat();
  72289. const float y3 = source.readFloat();
  72290. cubicTo (x1, y1, x2, y2, x3, y3);
  72291. break;
  72292. }
  72293. case 'c':
  72294. closeSubPath();
  72295. break;
  72296. case 'n':
  72297. useNonZeroWinding = true;
  72298. break;
  72299. case 'z':
  72300. useNonZeroWinding = false;
  72301. break;
  72302. case 'e':
  72303. return; // end of path marker
  72304. default:
  72305. jassertfalse // illegal char in the stream
  72306. break;
  72307. }
  72308. }
  72309. }
  72310. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  72311. {
  72312. MemoryInputStream in (pathData, numberOfBytes, false);
  72313. loadPathFromStream (in);
  72314. }
  72315. void Path::writePathToStream (OutputStream& dest) const
  72316. {
  72317. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  72318. size_t i = 0;
  72319. while (i < numElements)
  72320. {
  72321. const float type = data.elements [i++];
  72322. if (type == moveMarker)
  72323. {
  72324. dest.writeByte ('m');
  72325. dest.writeFloat (data.elements [i++]);
  72326. dest.writeFloat (data.elements [i++]);
  72327. }
  72328. else if (type == lineMarker)
  72329. {
  72330. dest.writeByte ('l');
  72331. dest.writeFloat (data.elements [i++]);
  72332. dest.writeFloat (data.elements [i++]);
  72333. }
  72334. else if (type == quadMarker)
  72335. {
  72336. dest.writeByte ('q');
  72337. dest.writeFloat (data.elements [i++]);
  72338. dest.writeFloat (data.elements [i++]);
  72339. dest.writeFloat (data.elements [i++]);
  72340. dest.writeFloat (data.elements [i++]);
  72341. }
  72342. else if (type == cubicMarker)
  72343. {
  72344. dest.writeByte ('b');
  72345. dest.writeFloat (data.elements [i++]);
  72346. dest.writeFloat (data.elements [i++]);
  72347. dest.writeFloat (data.elements [i++]);
  72348. dest.writeFloat (data.elements [i++]);
  72349. dest.writeFloat (data.elements [i++]);
  72350. dest.writeFloat (data.elements [i++]);
  72351. }
  72352. else if (type == closeSubPathMarker)
  72353. {
  72354. dest.writeByte ('c');
  72355. }
  72356. }
  72357. dest.writeByte ('e'); // marks the end-of-path
  72358. }
  72359. const String Path::toString() const
  72360. {
  72361. MemoryOutputStream s (2048, 2048);
  72362. if (! useNonZeroWinding)
  72363. s << 'a';
  72364. size_t i = 0;
  72365. float lastMarker = 0.0f;
  72366. while (i < numElements)
  72367. {
  72368. const float marker = data.elements [i++];
  72369. char markerChar = 0;
  72370. int numCoords = 0;
  72371. if (marker == moveMarker)
  72372. {
  72373. markerChar = 'm';
  72374. numCoords = 2;
  72375. }
  72376. else if (marker == lineMarker)
  72377. {
  72378. markerChar = 'l';
  72379. numCoords = 2;
  72380. }
  72381. else if (marker == quadMarker)
  72382. {
  72383. markerChar = 'q';
  72384. numCoords = 4;
  72385. }
  72386. else if (marker == cubicMarker)
  72387. {
  72388. markerChar = 'c';
  72389. numCoords = 6;
  72390. }
  72391. else
  72392. {
  72393. jassert (marker == closeSubPathMarker);
  72394. markerChar = 'z';
  72395. }
  72396. if (marker != lastMarker)
  72397. {
  72398. if (s.getDataSize() != 0)
  72399. s << ' ';
  72400. s << markerChar;
  72401. lastMarker = marker;
  72402. }
  72403. while (--numCoords >= 0 && i < numElements)
  72404. {
  72405. String coord (data.elements [i++], 3);
  72406. while (coord.endsWithChar ('0') && coord != "0")
  72407. coord = coord.dropLastCharacters (1);
  72408. if (coord.endsWithChar ('.'))
  72409. coord = coord.dropLastCharacters (1);
  72410. if (s.getDataSize() != 0)
  72411. s << ' ';
  72412. s << coord;
  72413. }
  72414. }
  72415. return s.toUTF8();
  72416. }
  72417. void Path::restoreFromString (const String& stringVersion)
  72418. {
  72419. clear();
  72420. setUsingNonZeroWinding (true);
  72421. const juce_wchar* t = stringVersion;
  72422. juce_wchar marker = 'm';
  72423. int numValues = 2;
  72424. float values [6];
  72425. while (*t != 0)
  72426. {
  72427. const String token (PathHelpers::nextToken (t));
  72428. const juce_wchar firstChar = token[0];
  72429. int startNum = 0;
  72430. if (firstChar == 'm' || firstChar == 'l')
  72431. {
  72432. marker = firstChar;
  72433. numValues = 2;
  72434. }
  72435. else if (firstChar == 'q')
  72436. {
  72437. marker = firstChar;
  72438. numValues = 4;
  72439. }
  72440. else if (firstChar == 'c')
  72441. {
  72442. marker = firstChar;
  72443. numValues = 6;
  72444. }
  72445. else if (firstChar == 'z')
  72446. {
  72447. marker = firstChar;
  72448. numValues = 0;
  72449. }
  72450. else if (firstChar == 'a')
  72451. {
  72452. setUsingNonZeroWinding (false);
  72453. continue;
  72454. }
  72455. else
  72456. {
  72457. ++startNum;
  72458. values [0] = token.getFloatValue();
  72459. }
  72460. for (int i = startNum; i < numValues; ++i)
  72461. values [i] = PathHelpers::nextToken (t).getFloatValue();
  72462. switch (marker)
  72463. {
  72464. case 'm':
  72465. startNewSubPath (values[0], values[1]);
  72466. break;
  72467. case 'l':
  72468. lineTo (values[0], values[1]);
  72469. break;
  72470. case 'q':
  72471. quadraticTo (values[0], values[1],
  72472. values[2], values[3]);
  72473. break;
  72474. case 'c':
  72475. cubicTo (values[0], values[1],
  72476. values[2], values[3],
  72477. values[4], values[5]);
  72478. break;
  72479. case 'z':
  72480. closeSubPath();
  72481. break;
  72482. default:
  72483. jassertfalse // illegal string format?
  72484. break;
  72485. }
  72486. }
  72487. }
  72488. Path::Iterator::Iterator (const Path& path_)
  72489. : path (path_),
  72490. index (0)
  72491. {
  72492. }
  72493. Path::Iterator::~Iterator()
  72494. {
  72495. }
  72496. bool Path::Iterator::next()
  72497. {
  72498. const float* const elements = path.data.elements;
  72499. if (index < path.numElements)
  72500. {
  72501. const float type = elements [index++];
  72502. if (type == moveMarker)
  72503. {
  72504. elementType = startNewSubPath;
  72505. x1 = elements [index++];
  72506. y1 = elements [index++];
  72507. }
  72508. else if (type == lineMarker)
  72509. {
  72510. elementType = lineTo;
  72511. x1 = elements [index++];
  72512. y1 = elements [index++];
  72513. }
  72514. else if (type == quadMarker)
  72515. {
  72516. elementType = quadraticTo;
  72517. x1 = elements [index++];
  72518. y1 = elements [index++];
  72519. x2 = elements [index++];
  72520. y2 = elements [index++];
  72521. }
  72522. else if (type == cubicMarker)
  72523. {
  72524. elementType = cubicTo;
  72525. x1 = elements [index++];
  72526. y1 = elements [index++];
  72527. x2 = elements [index++];
  72528. y2 = elements [index++];
  72529. x3 = elements [index++];
  72530. y3 = elements [index++];
  72531. }
  72532. else if (type == closeSubPathMarker)
  72533. {
  72534. elementType = closePath;
  72535. }
  72536. return true;
  72537. }
  72538. return false;
  72539. }
  72540. END_JUCE_NAMESPACE
  72541. /*** End of inlined file: juce_Path.cpp ***/
  72542. /*** Start of inlined file: juce_PathIterator.cpp ***/
  72543. BEGIN_JUCE_NAMESPACE
  72544. #if JUCE_MSVC && JUCE_DEBUG
  72545. #pragma optimize ("t", on)
  72546. #endif
  72547. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  72548. const AffineTransform& transform_,
  72549. float tolerence_)
  72550. : x2 (0),
  72551. y2 (0),
  72552. closesSubPath (false),
  72553. subPathIndex (-1),
  72554. path (path_),
  72555. transform (transform_),
  72556. points (path_.data.elements),
  72557. tolerence (tolerence_ * tolerence_),
  72558. subPathCloseX (0),
  72559. subPathCloseY (0),
  72560. isIdentityTransform (transform_.isIdentity()),
  72561. stackBase (32),
  72562. index (0),
  72563. stackSize (32)
  72564. {
  72565. stackPos = stackBase;
  72566. }
  72567. PathFlatteningIterator::~PathFlatteningIterator()
  72568. {
  72569. }
  72570. bool PathFlatteningIterator::next()
  72571. {
  72572. x1 = x2;
  72573. y1 = y2;
  72574. float x3 = 0;
  72575. float y3 = 0;
  72576. float x4 = 0;
  72577. float y4 = 0;
  72578. float type;
  72579. for (;;)
  72580. {
  72581. if (stackPos == stackBase)
  72582. {
  72583. if (index >= path.numElements)
  72584. {
  72585. return false;
  72586. }
  72587. else
  72588. {
  72589. type = points [index++];
  72590. if (type != Path::closeSubPathMarker)
  72591. {
  72592. x2 = points [index++];
  72593. y2 = points [index++];
  72594. if (! isIdentityTransform)
  72595. transform.transformPoint (x2, y2);
  72596. if (type == Path::quadMarker)
  72597. {
  72598. x3 = points [index++];
  72599. y3 = points [index++];
  72600. if (! isIdentityTransform)
  72601. transform.transformPoint (x3, y3);
  72602. }
  72603. else if (type == Path::cubicMarker)
  72604. {
  72605. x3 = points [index++];
  72606. y3 = points [index++];
  72607. x4 = points [index++];
  72608. y4 = points [index++];
  72609. if (! isIdentityTransform)
  72610. {
  72611. transform.transformPoint (x3, y3);
  72612. transform.transformPoint (x4, y4);
  72613. }
  72614. }
  72615. }
  72616. }
  72617. }
  72618. else
  72619. {
  72620. type = *--stackPos;
  72621. if (type != Path::closeSubPathMarker)
  72622. {
  72623. x2 = *--stackPos;
  72624. y2 = *--stackPos;
  72625. if (type == Path::quadMarker)
  72626. {
  72627. x3 = *--stackPos;
  72628. y3 = *--stackPos;
  72629. }
  72630. else if (type == Path::cubicMarker)
  72631. {
  72632. x3 = *--stackPos;
  72633. y3 = *--stackPos;
  72634. x4 = *--stackPos;
  72635. y4 = *--stackPos;
  72636. }
  72637. }
  72638. }
  72639. if (type == Path::lineMarker)
  72640. {
  72641. ++subPathIndex;
  72642. closesSubPath = (stackPos == stackBase)
  72643. && (index < path.numElements)
  72644. && (points [index] == Path::closeSubPathMarker)
  72645. && x2 == subPathCloseX
  72646. && y2 == subPathCloseY;
  72647. return true;
  72648. }
  72649. else if (type == Path::quadMarker)
  72650. {
  72651. const size_t offset = (size_t) (stackPos - stackBase);
  72652. if (offset >= stackSize - 10)
  72653. {
  72654. stackSize <<= 1;
  72655. stackBase.realloc (stackSize);
  72656. stackPos = stackBase + offset;
  72657. }
  72658. const float dx1 = x1 - x2;
  72659. const float dy1 = y1 - y2;
  72660. const float dx2 = x2 - x3;
  72661. const float dy2 = y2 - y3;
  72662. const float m1x = (x1 + x2) * 0.5f;
  72663. const float m1y = (y1 + y2) * 0.5f;
  72664. const float m2x = (x2 + x3) * 0.5f;
  72665. const float m2y = (y2 + y3) * 0.5f;
  72666. const float m3x = (m1x + m2x) * 0.5f;
  72667. const float m3y = (m1y + m2y) * 0.5f;
  72668. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  72669. {
  72670. *stackPos++ = y3;
  72671. *stackPos++ = x3;
  72672. *stackPos++ = m2y;
  72673. *stackPos++ = m2x;
  72674. *stackPos++ = Path::quadMarker;
  72675. *stackPos++ = m3y;
  72676. *stackPos++ = m3x;
  72677. *stackPos++ = m1y;
  72678. *stackPos++ = m1x;
  72679. *stackPos++ = Path::quadMarker;
  72680. }
  72681. else
  72682. {
  72683. *stackPos++ = y3;
  72684. *stackPos++ = x3;
  72685. *stackPos++ = Path::lineMarker;
  72686. *stackPos++ = m3y;
  72687. *stackPos++ = m3x;
  72688. *stackPos++ = Path::lineMarker;
  72689. }
  72690. jassert (stackPos < stackBase + stackSize);
  72691. }
  72692. else if (type == Path::cubicMarker)
  72693. {
  72694. const size_t offset = (size_t) (stackPos - stackBase);
  72695. if (offset >= stackSize - 16)
  72696. {
  72697. stackSize <<= 1;
  72698. stackBase.realloc (stackSize);
  72699. stackPos = stackBase + offset;
  72700. }
  72701. const float dx1 = x1 - x2;
  72702. const float dy1 = y1 - y2;
  72703. const float dx2 = x2 - x3;
  72704. const float dy2 = y2 - y3;
  72705. const float dx3 = x3 - x4;
  72706. const float dy3 = y3 - y4;
  72707. const float m1x = (x1 + x2) * 0.5f;
  72708. const float m1y = (y1 + y2) * 0.5f;
  72709. const float m2x = (x3 + x2) * 0.5f;
  72710. const float m2y = (y3 + y2) * 0.5f;
  72711. const float m3x = (x3 + x4) * 0.5f;
  72712. const float m3y = (y3 + y4) * 0.5f;
  72713. const float m4x = (m1x + m2x) * 0.5f;
  72714. const float m4y = (m1y + m2y) * 0.5f;
  72715. const float m5x = (m3x + m2x) * 0.5f;
  72716. const float m5y = (m3y + m2y) * 0.5f;
  72717. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  72718. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  72719. {
  72720. *stackPos++ = y4;
  72721. *stackPos++ = x4;
  72722. *stackPos++ = m3y;
  72723. *stackPos++ = m3x;
  72724. *stackPos++ = m5y;
  72725. *stackPos++ = m5x;
  72726. *stackPos++ = Path::cubicMarker;
  72727. *stackPos++ = (m4y + m5y) * 0.5f;
  72728. *stackPos++ = (m4x + m5x) * 0.5f;
  72729. *stackPos++ = m4y;
  72730. *stackPos++ = m4x;
  72731. *stackPos++ = m1y;
  72732. *stackPos++ = m1x;
  72733. *stackPos++ = Path::cubicMarker;
  72734. }
  72735. else
  72736. {
  72737. *stackPos++ = y4;
  72738. *stackPos++ = x4;
  72739. *stackPos++ = Path::lineMarker;
  72740. *stackPos++ = m5y;
  72741. *stackPos++ = m5x;
  72742. *stackPos++ = Path::lineMarker;
  72743. *stackPos++ = m4y;
  72744. *stackPos++ = m4x;
  72745. *stackPos++ = Path::lineMarker;
  72746. }
  72747. }
  72748. else if (type == Path::closeSubPathMarker)
  72749. {
  72750. if (x2 != subPathCloseX || y2 != subPathCloseY)
  72751. {
  72752. x1 = x2;
  72753. y1 = y2;
  72754. x2 = subPathCloseX;
  72755. y2 = subPathCloseY;
  72756. closesSubPath = true;
  72757. return true;
  72758. }
  72759. }
  72760. else
  72761. {
  72762. jassert (type == Path::moveMarker);
  72763. subPathIndex = -1;
  72764. subPathCloseX = x1 = x2;
  72765. subPathCloseY = y1 = y2;
  72766. }
  72767. }
  72768. }
  72769. #if JUCE_MSVC && JUCE_DEBUG
  72770. #pragma optimize ("", on) // resets optimisations to the project defaults
  72771. #endif
  72772. END_JUCE_NAMESPACE
  72773. /*** End of inlined file: juce_PathIterator.cpp ***/
  72774. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  72775. BEGIN_JUCE_NAMESPACE
  72776. PathStrokeType::PathStrokeType (const float strokeThickness,
  72777. const JointStyle jointStyle_,
  72778. const EndCapStyle endStyle_) throw()
  72779. : thickness (strokeThickness),
  72780. jointStyle (jointStyle_),
  72781. endStyle (endStyle_)
  72782. {
  72783. }
  72784. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  72785. : thickness (other.thickness),
  72786. jointStyle (other.jointStyle),
  72787. endStyle (other.endStyle)
  72788. {
  72789. }
  72790. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  72791. {
  72792. thickness = other.thickness;
  72793. jointStyle = other.jointStyle;
  72794. endStyle = other.endStyle;
  72795. return *this;
  72796. }
  72797. PathStrokeType::~PathStrokeType() throw()
  72798. {
  72799. }
  72800. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  72801. {
  72802. return thickness == other.thickness
  72803. && jointStyle == other.jointStyle
  72804. && endStyle == other.endStyle;
  72805. }
  72806. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  72807. {
  72808. return ! operator== (other);
  72809. }
  72810. static bool lineIntersection (const float x1, const float y1,
  72811. const float x2, const float y2,
  72812. const float x3, const float y3,
  72813. const float x4, const float y4,
  72814. float& intersectionX,
  72815. float& intersectionY,
  72816. float& distanceBeyondLine1EndSquared) throw()
  72817. {
  72818. if (x2 != x3 || y2 != y3)
  72819. {
  72820. const float dx1 = x2 - x1;
  72821. const float dy1 = y2 - y1;
  72822. const float dx2 = x4 - x3;
  72823. const float dy2 = y4 - y3;
  72824. const float divisor = dx1 * dy2 - dx2 * dy1;
  72825. if (divisor == 0)
  72826. {
  72827. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  72828. {
  72829. if (dy1 == 0 && dy2 != 0)
  72830. {
  72831. const float along = (y1 - y3) / dy2;
  72832. intersectionX = x3 + along * dx2;
  72833. intersectionY = y1;
  72834. distanceBeyondLine1EndSquared = intersectionX - x2;
  72835. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  72836. if ((x2 > x1) == (intersectionX < x2))
  72837. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  72838. return along >= 0 && along <= 1.0f;
  72839. }
  72840. else if (dy2 == 0 && dy1 != 0)
  72841. {
  72842. const float along = (y3 - y1) / dy1;
  72843. intersectionX = x1 + along * dx1;
  72844. intersectionY = y3;
  72845. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  72846. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  72847. if (along < 1.0f)
  72848. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  72849. return along >= 0 && along <= 1.0f;
  72850. }
  72851. else if (dx1 == 0 && dx2 != 0)
  72852. {
  72853. const float along = (x1 - x3) / dx2;
  72854. intersectionX = x1;
  72855. intersectionY = y3 + along * dy2;
  72856. distanceBeyondLine1EndSquared = intersectionY - y2;
  72857. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  72858. if ((y2 > y1) == (intersectionY < y2))
  72859. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  72860. return along >= 0 && along <= 1.0f;
  72861. }
  72862. else if (dx2 == 0 && dx1 != 0)
  72863. {
  72864. const float along = (x3 - x1) / dx1;
  72865. intersectionX = x3;
  72866. intersectionY = y1 + along * dy1;
  72867. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  72868. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  72869. if (along < 1.0f)
  72870. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  72871. return along >= 0 && along <= 1.0f;
  72872. }
  72873. }
  72874. intersectionX = 0.5f * (x2 + x3);
  72875. intersectionY = 0.5f * (y2 + y3);
  72876. distanceBeyondLine1EndSquared = 0.0f;
  72877. return false;
  72878. }
  72879. else
  72880. {
  72881. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  72882. intersectionX = x1 + along1 * dx1;
  72883. intersectionY = y1 + along1 * dy1;
  72884. if (along1 >= 0 && along1 <= 1.0f)
  72885. {
  72886. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  72887. if (along2 >= 0 && along2 <= divisor)
  72888. {
  72889. distanceBeyondLine1EndSquared = 0.0f;
  72890. return true;
  72891. }
  72892. }
  72893. distanceBeyondLine1EndSquared = along1 - 1.0f;
  72894. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  72895. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  72896. if (along1 < 1.0f)
  72897. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  72898. return false;
  72899. }
  72900. }
  72901. intersectionX = x2;
  72902. intersectionY = y2;
  72903. distanceBeyondLine1EndSquared = 0.0f;
  72904. return true;
  72905. }
  72906. namespace PathFunctions
  72907. {
  72908. // part of stroke drawing stuff
  72909. static void addEdgeAndJoint (Path& destPath,
  72910. const PathStrokeType::JointStyle style,
  72911. const float maxMiterExtensionSquared, const float width,
  72912. const float x1, const float y1,
  72913. const float x2, const float y2,
  72914. const float x3, const float y3,
  72915. const float x4, const float y4,
  72916. const float midX, const float midY)
  72917. {
  72918. if (style == PathStrokeType::beveled
  72919. || (x3 == x4 && y3 == y4)
  72920. || (x1 == x2 && y1 == y2))
  72921. {
  72922. destPath.lineTo (x2, y2);
  72923. destPath.lineTo (x3, y3);
  72924. }
  72925. else
  72926. {
  72927. float jx, jy, distanceBeyondLine1EndSquared;
  72928. // if they intersect, use this point..
  72929. if (lineIntersection (x1, y1, x2, y2,
  72930. x3, y3, x4, y4,
  72931. jx, jy, distanceBeyondLine1EndSquared))
  72932. {
  72933. destPath.lineTo (jx, jy);
  72934. }
  72935. else
  72936. {
  72937. if (style == PathStrokeType::mitered)
  72938. {
  72939. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  72940. && distanceBeyondLine1EndSquared > 0.0f)
  72941. {
  72942. destPath.lineTo (jx, jy);
  72943. }
  72944. else
  72945. {
  72946. // the end sticks out too far, so just use a blunt joint
  72947. destPath.lineTo (x2, y2);
  72948. destPath.lineTo (x3, y3);
  72949. }
  72950. }
  72951. else
  72952. {
  72953. // curved joints
  72954. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  72955. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  72956. const float angleIncrement = 0.1f;
  72957. destPath.lineTo (x2, y2);
  72958. if (std::abs (angle1 - angle2) > angleIncrement)
  72959. {
  72960. if (angle2 > angle1 + float_Pi
  72961. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  72962. {
  72963. if (angle2 > angle1)
  72964. angle2 -= float_Pi * 2.0f;
  72965. jassert (angle1 <= angle2 + float_Pi);
  72966. angle1 -= angleIncrement;
  72967. while (angle1 > angle2)
  72968. {
  72969. destPath.lineTo (midX + width * std::sin (angle1),
  72970. midY + width * std::cos (angle1));
  72971. angle1 -= angleIncrement;
  72972. }
  72973. }
  72974. else
  72975. {
  72976. if (angle1 > angle2)
  72977. angle1 -= float_Pi * 2.0f;
  72978. jassert (angle1 >= angle2 - float_Pi);
  72979. angle1 += angleIncrement;
  72980. while (angle1 < angle2)
  72981. {
  72982. destPath.lineTo (midX + width * std::sin (angle1),
  72983. midY + width * std::cos (angle1));
  72984. angle1 += angleIncrement;
  72985. }
  72986. }
  72987. }
  72988. destPath.lineTo (x3, y3);
  72989. }
  72990. }
  72991. }
  72992. }
  72993. static void addLineEnd (Path& destPath,
  72994. const PathStrokeType::EndCapStyle style,
  72995. const float x1, const float y1,
  72996. const float x2, const float y2,
  72997. const float width)
  72998. {
  72999. if (style == PathStrokeType::butt)
  73000. {
  73001. destPath.lineTo (x2, y2);
  73002. }
  73003. else
  73004. {
  73005. float offx1, offy1, offx2, offy2;
  73006. float dx = x2 - x1;
  73007. float dy = y2 - y1;
  73008. const float len = juce_hypotf (dx, dy);
  73009. if (len == 0)
  73010. {
  73011. offx1 = offx2 = x1;
  73012. offy1 = offy2 = y1;
  73013. }
  73014. else
  73015. {
  73016. const float offset = width / len;
  73017. dx *= offset;
  73018. dy *= offset;
  73019. offx1 = x1 + dy;
  73020. offy1 = y1 - dx;
  73021. offx2 = x2 + dy;
  73022. offy2 = y2 - dx;
  73023. }
  73024. if (style == PathStrokeType::square)
  73025. {
  73026. // sqaure ends
  73027. destPath.lineTo (offx1, offy1);
  73028. destPath.lineTo (offx2, offy2);
  73029. destPath.lineTo (x2, y2);
  73030. }
  73031. else
  73032. {
  73033. // rounded ends
  73034. const float midx = (offx1 + offx2) * 0.5f;
  73035. const float midy = (offy1 + offy2) * 0.5f;
  73036. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  73037. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  73038. midx, midy);
  73039. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  73040. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  73041. x2, y2);
  73042. }
  73043. }
  73044. }
  73045. struct LineSection
  73046. {
  73047. LineSection() {}
  73048. LineSection (int) {}
  73049. float x1, y1, x2, y2; // original line
  73050. float lx1, ly1, lx2, ly2; // the left-hand stroke
  73051. float rx1, ry1, rx2, ry2; // the right-hand stroke
  73052. };
  73053. static void addSubPath (Path& destPath, const Array <LineSection>& subPath,
  73054. const bool isClosed,
  73055. const float width, const float maxMiterExtensionSquared,
  73056. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle)
  73057. {
  73058. jassert (subPath.size() > 0);
  73059. const LineSection& firstLine = subPath.getReference (0);
  73060. float lastX1 = firstLine.lx1;
  73061. float lastY1 = firstLine.ly1;
  73062. float lastX2 = firstLine.lx2;
  73063. float lastY2 = firstLine.ly2;
  73064. if (isClosed)
  73065. {
  73066. destPath.startNewSubPath (lastX1, lastY1);
  73067. }
  73068. else
  73069. {
  73070. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  73071. addLineEnd (destPath, endStyle,
  73072. firstLine.rx2, firstLine.ry2,
  73073. lastX1, lastY1,
  73074. width);
  73075. }
  73076. int i;
  73077. for (i = 1; i < subPath.size(); ++i)
  73078. {
  73079. const LineSection& l = subPath.getReference (i);
  73080. addEdgeAndJoint (destPath, jointStyle,
  73081. maxMiterExtensionSquared, width,
  73082. lastX1, lastY1, lastX2, lastY2,
  73083. l.lx1, l.ly1, l.lx2, l.ly2,
  73084. l.x1, l.y1);
  73085. lastX1 = l.lx1;
  73086. lastY1 = l.ly1;
  73087. lastX2 = l.lx2;
  73088. lastY2 = l.ly2;
  73089. }
  73090. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  73091. if (isClosed)
  73092. {
  73093. const LineSection& l = subPath.getReference (0);
  73094. addEdgeAndJoint (destPath, jointStyle,
  73095. maxMiterExtensionSquared, width,
  73096. lastX1, lastY1, lastX2, lastY2,
  73097. l.lx1, l.ly1, l.lx2, l.ly2,
  73098. l.x1, l.y1);
  73099. destPath.closeSubPath();
  73100. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  73101. }
  73102. else
  73103. {
  73104. destPath.lineTo (lastX2, lastY2);
  73105. addLineEnd (destPath, endStyle,
  73106. lastX2, lastY2,
  73107. lastLine.rx1, lastLine.ry1,
  73108. width);
  73109. }
  73110. lastX1 = lastLine.rx1;
  73111. lastY1 = lastLine.ry1;
  73112. lastX2 = lastLine.rx2;
  73113. lastY2 = lastLine.ry2;
  73114. for (i = subPath.size() - 1; --i >= 0;)
  73115. {
  73116. const LineSection& l = subPath.getReference (i);
  73117. addEdgeAndJoint (destPath, jointStyle,
  73118. maxMiterExtensionSquared, width,
  73119. lastX1, lastY1, lastX2, lastY2,
  73120. l.rx1, l.ry1, l.rx2, l.ry2,
  73121. l.x2, l.y2);
  73122. lastX1 = l.rx1;
  73123. lastY1 = l.ry1;
  73124. lastX2 = l.rx2;
  73125. lastY2 = l.ry2;
  73126. }
  73127. if (isClosed)
  73128. {
  73129. addEdgeAndJoint (destPath, jointStyle,
  73130. maxMiterExtensionSquared, width,
  73131. lastX1, lastY1, lastX2, lastY2,
  73132. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  73133. lastLine.x2, lastLine.y2);
  73134. }
  73135. else
  73136. {
  73137. // do the last line
  73138. destPath.lineTo (lastX2, lastY2);
  73139. }
  73140. destPath.closeSubPath();
  73141. }
  73142. }
  73143. void PathStrokeType::createStrokedPath (Path& destPath,
  73144. const Path& source,
  73145. const AffineTransform& transform,
  73146. const float extraAccuracy) const
  73147. {
  73148. if (thickness <= 0)
  73149. {
  73150. destPath.clear();
  73151. return;
  73152. }
  73153. const Path* sourcePath = &source;
  73154. Path temp;
  73155. if (sourcePath == &destPath)
  73156. {
  73157. destPath.swapWithPath (temp);
  73158. sourcePath = &temp;
  73159. }
  73160. else
  73161. {
  73162. destPath.clear();
  73163. }
  73164. destPath.setUsingNonZeroWinding (true);
  73165. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  73166. const float width = 0.5f * thickness;
  73167. // Iterate the path, creating a list of the
  73168. // left/right-hand lines along either side of it...
  73169. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  73170. using namespace PathFunctions;
  73171. Array <LineSection> subPath;
  73172. LineSection l;
  73173. l.x1 = 0;
  73174. l.y1 = 0;
  73175. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  73176. while (it.next())
  73177. {
  73178. if (it.subPathIndex == 0)
  73179. {
  73180. if (subPath.size() > 0)
  73181. {
  73182. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  73183. subPath.clearQuick();
  73184. }
  73185. l.x1 = it.x1;
  73186. l.y1 = it.y1;
  73187. }
  73188. l.x2 = it.x2;
  73189. l.y2 = it.y2;
  73190. float dx = l.x2 - l.x1;
  73191. float dy = l.y2 - l.y1;
  73192. const float hypotSquared = dx*dx + dy*dy;
  73193. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  73194. {
  73195. const float len = std::sqrt (hypotSquared);
  73196. if (len == 0)
  73197. {
  73198. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  73199. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  73200. }
  73201. else
  73202. {
  73203. const float offset = width / len;
  73204. dx *= offset;
  73205. dy *= offset;
  73206. l.rx2 = l.x1 - dy;
  73207. l.ry2 = l.y1 + dx;
  73208. l.lx1 = l.x1 + dy;
  73209. l.ly1 = l.y1 - dx;
  73210. l.lx2 = l.x2 + dy;
  73211. l.ly2 = l.y2 - dx;
  73212. l.rx1 = l.x2 - dy;
  73213. l.ry1 = l.y2 + dx;
  73214. }
  73215. subPath.add (l);
  73216. if (it.closesSubPath)
  73217. {
  73218. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle);
  73219. subPath.clearQuick();
  73220. }
  73221. else
  73222. {
  73223. l.x1 = it.x2;
  73224. l.y1 = it.y2;
  73225. }
  73226. }
  73227. }
  73228. if (subPath.size() > 0)
  73229. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  73230. }
  73231. void PathStrokeType::createDashedStroke (Path& destPath,
  73232. const Path& sourcePath,
  73233. const float* dashLengths,
  73234. int numDashLengths,
  73235. const AffineTransform& transform,
  73236. const float extraAccuracy) const
  73237. {
  73238. if (thickness <= 0)
  73239. return;
  73240. // this should really be an even number..
  73241. jassert ((numDashLengths & 1) == 0);
  73242. Path newDestPath;
  73243. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  73244. bool first = true;
  73245. int dashNum = 0;
  73246. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  73247. float dx = 0.0f, dy = 0.0f;
  73248. for (;;)
  73249. {
  73250. const bool isSolid = ((dashNum & 1) == 0);
  73251. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  73252. jassert (dashLen > 0); // must be a positive increment!
  73253. if (dashLen <= 0)
  73254. break;
  73255. pos += dashLen;
  73256. while (pos > lineEndPos)
  73257. {
  73258. if (! it.next())
  73259. {
  73260. if (isSolid && ! first)
  73261. newDestPath.lineTo (it.x2, it.y2);
  73262. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  73263. return;
  73264. }
  73265. if (isSolid && ! first)
  73266. newDestPath.lineTo (it.x1, it.y1);
  73267. else
  73268. newDestPath.startNewSubPath (it.x1, it.y1);
  73269. dx = it.x2 - it.x1;
  73270. dy = it.y2 - it.y1;
  73271. lineLen = juce_hypotf (dx, dy);
  73272. lineEndPos += lineLen;
  73273. first = it.closesSubPath;
  73274. }
  73275. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  73276. if (isSolid)
  73277. newDestPath.lineTo (it.x1 + dx * alpha,
  73278. it.y1 + dy * alpha);
  73279. else
  73280. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  73281. it.y1 + dy * alpha);
  73282. }
  73283. }
  73284. END_JUCE_NAMESPACE
  73285. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  73286. /*** Start of inlined file: juce_PositionedRectangle.cpp ***/
  73287. BEGIN_JUCE_NAMESPACE
  73288. PositionedRectangle::PositionedRectangle() throw()
  73289. : x (0.0),
  73290. y (0.0),
  73291. w (0.0),
  73292. h (0.0),
  73293. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  73294. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  73295. wMode (absoluteSize),
  73296. hMode (absoluteSize)
  73297. {
  73298. }
  73299. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  73300. : x (other.x),
  73301. y (other.y),
  73302. w (other.w),
  73303. h (other.h),
  73304. xMode (other.xMode),
  73305. yMode (other.yMode),
  73306. wMode (other.wMode),
  73307. hMode (other.hMode)
  73308. {
  73309. }
  73310. PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  73311. {
  73312. x = other.x;
  73313. y = other.y;
  73314. w = other.w;
  73315. h = other.h;
  73316. xMode = other.xMode;
  73317. yMode = other.yMode;
  73318. wMode = other.wMode;
  73319. hMode = other.hMode;
  73320. return *this;
  73321. }
  73322. PositionedRectangle::~PositionedRectangle() throw()
  73323. {
  73324. }
  73325. bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  73326. {
  73327. return x == other.x
  73328. && y == other.y
  73329. && w == other.w
  73330. && h == other.h
  73331. && xMode == other.xMode
  73332. && yMode == other.yMode
  73333. && wMode == other.wMode
  73334. && hMode == other.hMode;
  73335. }
  73336. bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  73337. {
  73338. return ! operator== (other);
  73339. }
  73340. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  73341. {
  73342. StringArray tokens;
  73343. tokens.addTokens (stringVersion, false);
  73344. decodePosString (tokens [0], xMode, x);
  73345. decodePosString (tokens [1], yMode, y);
  73346. decodeSizeString (tokens [2], wMode, w);
  73347. decodeSizeString (tokens [3], hMode, h);
  73348. }
  73349. const String PositionedRectangle::toString() const throw()
  73350. {
  73351. String s;
  73352. s.preallocateStorage (12);
  73353. addPosDescription (s, xMode, x);
  73354. s << ' ';
  73355. addPosDescription (s, yMode, y);
  73356. s << ' ';
  73357. addSizeDescription (s, wMode, w);
  73358. s << ' ';
  73359. addSizeDescription (s, hMode, h);
  73360. return s;
  73361. }
  73362. const Rectangle<int> PositionedRectangle::getRectangle (const Rectangle<int>& target) const throw()
  73363. {
  73364. jassert (! target.isEmpty());
  73365. double x_, y_, w_, h_;
  73366. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  73367. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  73368. return Rectangle<int> (roundToInt (x_), roundToInt (y_),
  73369. roundToInt (w_), roundToInt (h_));
  73370. }
  73371. void PositionedRectangle::getRectangleDouble (const Rectangle<int>& target,
  73372. double& x_, double& y_,
  73373. double& w_, double& h_) const throw()
  73374. {
  73375. jassert (! target.isEmpty());
  73376. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  73377. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  73378. }
  73379. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  73380. {
  73381. comp.setBounds (getRectangle (Rectangle<int> (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  73382. }
  73383. void PositionedRectangle::updateFrom (const Rectangle<int>& rectangle,
  73384. const Rectangle<int>& target) throw()
  73385. {
  73386. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  73387. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  73388. }
  73389. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  73390. const double newW, const double newH,
  73391. const Rectangle<int>& target) throw()
  73392. {
  73393. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  73394. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  73395. }
  73396. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  73397. {
  73398. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  73399. updateFrom (comp.getBounds(), Rectangle<int>());
  73400. else
  73401. updateFrom (comp.getBounds(), Rectangle<int> (0, 0, comp.getParentWidth(), comp.getParentHeight()));
  73402. }
  73403. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  73404. {
  73405. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  73406. }
  73407. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  73408. {
  73409. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  73410. | absoluteFromParentBottomRight
  73411. | absoluteFromParentCentre
  73412. | proportionOfParentSize));
  73413. }
  73414. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  73415. {
  73416. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  73417. }
  73418. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  73419. {
  73420. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  73421. | absoluteFromParentBottomRight
  73422. | absoluteFromParentCentre
  73423. | proportionOfParentSize));
  73424. }
  73425. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  73426. {
  73427. return (SizeMode) wMode;
  73428. }
  73429. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  73430. {
  73431. return (SizeMode) hMode;
  73432. }
  73433. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  73434. const PositionMode xMode_,
  73435. const AnchorPoint yAnchor,
  73436. const PositionMode yMode_,
  73437. const SizeMode widthMode,
  73438. const SizeMode heightMode,
  73439. const Rectangle<int>& target) throw()
  73440. {
  73441. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  73442. {
  73443. double tx, tw;
  73444. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  73445. xMode = (uint8) (xAnchor | xMode_);
  73446. wMode = (uint8) widthMode;
  73447. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  73448. }
  73449. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  73450. {
  73451. double ty, th;
  73452. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  73453. yMode = (uint8) (yAnchor | yMode_);
  73454. hMode = (uint8) heightMode;
  73455. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  73456. }
  73457. }
  73458. bool PositionedRectangle::isPositionAbsolute() const throw()
  73459. {
  73460. return xMode == absoluteFromParentTopLeft
  73461. && yMode == absoluteFromParentTopLeft
  73462. && wMode == absoluteSize
  73463. && hMode == absoluteSize;
  73464. }
  73465. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  73466. {
  73467. if ((mode & proportionOfParentSize) != 0)
  73468. {
  73469. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  73470. }
  73471. else
  73472. {
  73473. s << (roundToInt (value * 100.0) / 100.0);
  73474. if ((mode & absoluteFromParentBottomRight) != 0)
  73475. s << 'R';
  73476. else if ((mode & absoluteFromParentCentre) != 0)
  73477. s << 'C';
  73478. }
  73479. if ((mode & anchorAtRightOrBottom) != 0)
  73480. s << 'r';
  73481. else if ((mode & anchorAtCentre) != 0)
  73482. s << 'c';
  73483. }
  73484. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  73485. {
  73486. if (mode == proportionalSize)
  73487. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  73488. else if (mode == parentSizeMinusAbsolute)
  73489. s << (roundToInt (value * 100.0) / 100.0) << 'M';
  73490. else
  73491. s << (roundToInt (value * 100.0) / 100.0);
  73492. }
  73493. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  73494. {
  73495. if (s.containsChar ('r'))
  73496. mode = anchorAtRightOrBottom;
  73497. else if (s.containsChar ('c'))
  73498. mode = anchorAtCentre;
  73499. else
  73500. mode = anchorAtLeftOrTop;
  73501. if (s.containsChar ('%'))
  73502. {
  73503. mode |= proportionOfParentSize;
  73504. value = s.removeCharacters ("%rcRC").getDoubleValue() / 100.0;
  73505. }
  73506. else
  73507. {
  73508. if (s.containsChar ('R'))
  73509. mode |= absoluteFromParentBottomRight;
  73510. else if (s.containsChar ('C'))
  73511. mode |= absoluteFromParentCentre;
  73512. else
  73513. mode |= absoluteFromParentTopLeft;
  73514. value = s.removeCharacters ("rcRC").getDoubleValue();
  73515. }
  73516. }
  73517. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  73518. {
  73519. if (s.containsChar ('%'))
  73520. {
  73521. mode = proportionalSize;
  73522. value = s.upToFirstOccurrenceOf ("%", false, false).getDoubleValue() / 100.0;
  73523. }
  73524. else if (s.containsChar ('M'))
  73525. {
  73526. mode = parentSizeMinusAbsolute;
  73527. value = s.getDoubleValue();
  73528. }
  73529. else
  73530. {
  73531. mode = absoluteSize;
  73532. value = s.getDoubleValue();
  73533. }
  73534. }
  73535. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  73536. const double x_, const double w_,
  73537. const uint8 xMode_, const uint8 wMode_,
  73538. const int parentPos,
  73539. const int parentSize) const throw()
  73540. {
  73541. if (wMode_ == proportionalSize)
  73542. wOut = roundToInt (w_ * parentSize);
  73543. else if (wMode_ == parentSizeMinusAbsolute)
  73544. wOut = jmax (0, parentSize - roundToInt (w_));
  73545. else
  73546. wOut = roundToInt (w_);
  73547. if ((xMode_ & proportionOfParentSize) != 0)
  73548. xOut = parentPos + x_ * parentSize;
  73549. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  73550. xOut = (parentPos + parentSize) - x_;
  73551. else if ((xMode_ & absoluteFromParentCentre) != 0)
  73552. xOut = x_ + (parentPos + parentSize / 2);
  73553. else
  73554. xOut = x_ + parentPos;
  73555. if ((xMode_ & anchorAtRightOrBottom) != 0)
  73556. xOut -= wOut;
  73557. else if ((xMode_ & anchorAtCentre) != 0)
  73558. xOut -= wOut / 2;
  73559. }
  73560. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  73561. double x_, const double w_,
  73562. const uint8 xMode_, const uint8 wMode_,
  73563. const int parentPos,
  73564. const int parentSize) const throw()
  73565. {
  73566. if (wMode_ == proportionalSize)
  73567. {
  73568. if (parentSize > 0)
  73569. wOut = w_ / parentSize;
  73570. }
  73571. else if (wMode_ == parentSizeMinusAbsolute)
  73572. wOut = parentSize - w_;
  73573. else
  73574. wOut = w_;
  73575. if ((xMode_ & anchorAtRightOrBottom) != 0)
  73576. x_ += w_;
  73577. else if ((xMode_ & anchorAtCentre) != 0)
  73578. x_ += w_ / 2;
  73579. if ((xMode_ & proportionOfParentSize) != 0)
  73580. {
  73581. if (parentSize > 0)
  73582. xOut = (x_ - parentPos) / parentSize;
  73583. }
  73584. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  73585. xOut = (parentPos + parentSize) - x_;
  73586. else if ((xMode_ & absoluteFromParentCentre) != 0)
  73587. xOut = x_ - (parentPos + parentSize / 2);
  73588. else
  73589. xOut = x_ - parentPos;
  73590. }
  73591. END_JUCE_NAMESPACE
  73592. /*** End of inlined file: juce_PositionedRectangle.cpp ***/
  73593. /*** Start of inlined file: juce_RectangleList.cpp ***/
  73594. BEGIN_JUCE_NAMESPACE
  73595. RectangleList::RectangleList() throw()
  73596. {
  73597. }
  73598. RectangleList::RectangleList (const Rectangle<int>& rect)
  73599. {
  73600. if (! rect.isEmpty())
  73601. rects.add (rect);
  73602. }
  73603. RectangleList::RectangleList (const RectangleList& other)
  73604. : rects (other.rects)
  73605. {
  73606. }
  73607. RectangleList& RectangleList::operator= (const RectangleList& other)
  73608. {
  73609. rects = other.rects;
  73610. return *this;
  73611. }
  73612. RectangleList::~RectangleList()
  73613. {
  73614. }
  73615. void RectangleList::clear()
  73616. {
  73617. rects.clearQuick();
  73618. }
  73619. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  73620. {
  73621. if (((unsigned int) index) < (unsigned int) rects.size())
  73622. return rects.getReference (index);
  73623. return Rectangle<int>();
  73624. }
  73625. bool RectangleList::isEmpty() const throw()
  73626. {
  73627. return rects.size() == 0;
  73628. }
  73629. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  73630. : current (0),
  73631. owner (list),
  73632. index (list.rects.size())
  73633. {
  73634. }
  73635. RectangleList::Iterator::~Iterator()
  73636. {
  73637. }
  73638. bool RectangleList::Iterator::next() throw()
  73639. {
  73640. if (--index >= 0)
  73641. {
  73642. current = & (owner.rects.getReference (index));
  73643. return true;
  73644. }
  73645. return false;
  73646. }
  73647. void RectangleList::add (const Rectangle<int>& rect)
  73648. {
  73649. if (! rect.isEmpty())
  73650. {
  73651. if (rects.size() == 0)
  73652. {
  73653. rects.add (rect);
  73654. }
  73655. else
  73656. {
  73657. bool anyOverlaps = false;
  73658. int i;
  73659. for (i = rects.size(); --i >= 0;)
  73660. {
  73661. Rectangle<int>& ourRect = rects.getReference (i);
  73662. if (rect.intersects (ourRect))
  73663. {
  73664. if (rect.contains (ourRect))
  73665. rects.remove (i);
  73666. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  73667. anyOverlaps = true;
  73668. }
  73669. }
  73670. if (anyOverlaps && rects.size() > 0)
  73671. {
  73672. RectangleList r (rect);
  73673. for (i = rects.size(); --i >= 0;)
  73674. {
  73675. const Rectangle<int>& ourRect = rects.getReference (i);
  73676. if (rect.intersects (ourRect))
  73677. {
  73678. r.subtract (ourRect);
  73679. if (r.rects.size() == 0)
  73680. return;
  73681. }
  73682. }
  73683. for (i = r.getNumRectangles(); --i >= 0;)
  73684. rects.add (r.rects.getReference (i));
  73685. }
  73686. else
  73687. {
  73688. rects.add (rect);
  73689. }
  73690. }
  73691. }
  73692. }
  73693. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  73694. {
  73695. if (! rect.isEmpty())
  73696. rects.add (rect);
  73697. }
  73698. void RectangleList::add (const int x, const int y, const int w, const int h)
  73699. {
  73700. if (rects.size() == 0)
  73701. {
  73702. if (w > 0 && h > 0)
  73703. rects.add (Rectangle<int> (x, y, w, h));
  73704. }
  73705. else
  73706. {
  73707. add (Rectangle<int> (x, y, w, h));
  73708. }
  73709. }
  73710. void RectangleList::add (const RectangleList& other)
  73711. {
  73712. for (int i = 0; i < other.rects.size(); ++i)
  73713. add (other.rects.getReference (i));
  73714. }
  73715. void RectangleList::subtract (const Rectangle<int>& rect)
  73716. {
  73717. const int originalNumRects = rects.size();
  73718. if (originalNumRects > 0)
  73719. {
  73720. const int x1 = rect.x;
  73721. const int y1 = rect.y;
  73722. const int x2 = x1 + rect.w;
  73723. const int y2 = y1 + rect.h;
  73724. for (int i = getNumRectangles(); --i >= 0;)
  73725. {
  73726. Rectangle<int>& r = rects.getReference (i);
  73727. const int rx1 = r.x;
  73728. const int ry1 = r.y;
  73729. const int rx2 = rx1 + r.w;
  73730. const int ry2 = ry1 + r.h;
  73731. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  73732. {
  73733. if (x1 > rx1 && x1 < rx2)
  73734. {
  73735. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  73736. {
  73737. r.w = x1 - rx1;
  73738. }
  73739. else
  73740. {
  73741. r.x = x1;
  73742. r.w = rx2 - x1;
  73743. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  73744. i += 2;
  73745. }
  73746. }
  73747. else if (x2 > rx1 && x2 < rx2)
  73748. {
  73749. r.x = x2;
  73750. r.w = rx2 - x2;
  73751. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  73752. {
  73753. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  73754. i += 2;
  73755. }
  73756. }
  73757. else if (y1 > ry1 && y1 < ry2)
  73758. {
  73759. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  73760. {
  73761. r.h = y1 - ry1;
  73762. }
  73763. else
  73764. {
  73765. r.y = y1;
  73766. r.h = ry2 - y1;
  73767. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  73768. i += 2;
  73769. }
  73770. }
  73771. else if (y2 > ry1 && y2 < ry2)
  73772. {
  73773. r.y = y2;
  73774. r.h = ry2 - y2;
  73775. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  73776. {
  73777. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  73778. i += 2;
  73779. }
  73780. }
  73781. else
  73782. {
  73783. rects.remove (i);
  73784. }
  73785. }
  73786. }
  73787. if (rects.size() > originalNumRects + 10)
  73788. consolidate();
  73789. }
  73790. }
  73791. void RectangleList::subtract (const RectangleList& otherList)
  73792. {
  73793. for (int i = otherList.rects.size(); --i >= 0;)
  73794. subtract (otherList.rects.getReference (i));
  73795. }
  73796. bool RectangleList::clipTo (const Rectangle<int>& rect)
  73797. {
  73798. bool notEmpty = false;
  73799. if (rect.isEmpty())
  73800. {
  73801. clear();
  73802. }
  73803. else
  73804. {
  73805. for (int i = rects.size(); --i >= 0;)
  73806. {
  73807. Rectangle<int>& r = rects.getReference (i);
  73808. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  73809. rects.remove (i);
  73810. else
  73811. notEmpty = true;
  73812. }
  73813. }
  73814. return notEmpty;
  73815. }
  73816. bool RectangleList::clipTo (const RectangleList& other)
  73817. {
  73818. if (rects.size() == 0)
  73819. return false;
  73820. RectangleList result;
  73821. for (int j = 0; j < rects.size(); ++j)
  73822. {
  73823. const Rectangle<int>& rect = rects.getReference (j);
  73824. for (int i = other.rects.size(); --i >= 0;)
  73825. {
  73826. Rectangle<int> r (other.rects.getReference (i));
  73827. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  73828. result.rects.add (r);
  73829. }
  73830. }
  73831. swapWith (result);
  73832. return ! isEmpty();
  73833. }
  73834. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  73835. {
  73836. destRegion.clear();
  73837. if (! rect.isEmpty())
  73838. {
  73839. for (int i = rects.size(); --i >= 0;)
  73840. {
  73841. Rectangle<int> r (rects.getReference (i));
  73842. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  73843. destRegion.rects.add (r);
  73844. }
  73845. }
  73846. return destRegion.rects.size() > 0;
  73847. }
  73848. void RectangleList::swapWith (RectangleList& otherList) throw()
  73849. {
  73850. rects.swapWithArray (otherList.rects);
  73851. }
  73852. void RectangleList::consolidate()
  73853. {
  73854. int i;
  73855. for (i = 0; i < getNumRectangles() - 1; ++i)
  73856. {
  73857. Rectangle<int>& r = rects.getReference (i);
  73858. const int rx1 = r.x;
  73859. const int ry1 = r.y;
  73860. const int rx2 = rx1 + r.w;
  73861. const int ry2 = ry1 + r.h;
  73862. for (int j = rects.size(); --j > i;)
  73863. {
  73864. Rectangle<int>& r2 = rects.getReference (j);
  73865. const int jrx1 = r2.x;
  73866. const int jry1 = r2.y;
  73867. const int jrx2 = jrx1 + r2.w;
  73868. const int jry2 = jry1 + r2.h;
  73869. // if the vertical edges of any blocks are touching and their horizontals don't
  73870. // line up, split them horizontally..
  73871. if (jrx1 == rx2 || jrx2 == rx1)
  73872. {
  73873. if (jry1 > ry1 && jry1 < ry2)
  73874. {
  73875. r.h = jry1 - ry1;
  73876. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  73877. i = -1;
  73878. break;
  73879. }
  73880. if (jry2 > ry1 && jry2 < ry2)
  73881. {
  73882. r.h = jry2 - ry1;
  73883. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  73884. i = -1;
  73885. break;
  73886. }
  73887. else if (ry1 > jry1 && ry1 < jry2)
  73888. {
  73889. r2.h = ry1 - jry1;
  73890. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  73891. i = -1;
  73892. break;
  73893. }
  73894. else if (ry2 > jry1 && ry2 < jry2)
  73895. {
  73896. r2.h = ry2 - jry1;
  73897. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  73898. i = -1;
  73899. break;
  73900. }
  73901. }
  73902. }
  73903. }
  73904. for (i = 0; i < rects.size() - 1; ++i)
  73905. {
  73906. Rectangle<int>& r = rects.getReference (i);
  73907. for (int j = rects.size(); --j > i;)
  73908. {
  73909. if (r.enlargeIfAdjacent (rects.getReference (j)))
  73910. {
  73911. rects.remove (j);
  73912. i = -1;
  73913. break;
  73914. }
  73915. }
  73916. }
  73917. }
  73918. bool RectangleList::containsPoint (const int x, const int y) const throw()
  73919. {
  73920. for (int i = getNumRectangles(); --i >= 0;)
  73921. if (rects.getReference (i).contains (x, y))
  73922. return true;
  73923. return false;
  73924. }
  73925. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  73926. {
  73927. if (rects.size() > 1)
  73928. {
  73929. RectangleList r (rectangleToCheck);
  73930. for (int i = rects.size(); --i >= 0;)
  73931. {
  73932. r.subtract (rects.getReference (i));
  73933. if (r.rects.size() == 0)
  73934. return true;
  73935. }
  73936. }
  73937. else if (rects.size() > 0)
  73938. {
  73939. return rects.getReference (0).contains (rectangleToCheck);
  73940. }
  73941. return false;
  73942. }
  73943. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  73944. {
  73945. for (int i = rects.size(); --i >= 0;)
  73946. if (rects.getReference (i).intersects (rectangleToCheck))
  73947. return true;
  73948. return false;
  73949. }
  73950. bool RectangleList::intersects (const RectangleList& other) const throw()
  73951. {
  73952. for (int i = rects.size(); --i >= 0;)
  73953. if (other.intersectsRectangle (rects.getReference (i)))
  73954. return true;
  73955. return false;
  73956. }
  73957. const Rectangle<int> RectangleList::getBounds() const throw()
  73958. {
  73959. if (rects.size() <= 1)
  73960. {
  73961. if (rects.size() == 0)
  73962. return Rectangle<int>();
  73963. else
  73964. return rects.getReference (0);
  73965. }
  73966. else
  73967. {
  73968. const Rectangle<int>& r = rects.getReference (0);
  73969. int minX = r.x;
  73970. int minY = r.y;
  73971. int maxX = minX + r.w;
  73972. int maxY = minY + r.h;
  73973. for (int i = rects.size(); --i > 0;)
  73974. {
  73975. const Rectangle<int>& r2 = rects.getReference (i);
  73976. minX = jmin (minX, r2.x);
  73977. minY = jmin (minY, r2.y);
  73978. maxX = jmax (maxX, r2.getRight());
  73979. maxY = jmax (maxY, r2.getBottom());
  73980. }
  73981. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  73982. }
  73983. }
  73984. void RectangleList::offsetAll (const int dx, const int dy) throw()
  73985. {
  73986. for (int i = rects.size(); --i >= 0;)
  73987. {
  73988. Rectangle<int>& r = rects.getReference (i);
  73989. r.x += dx;
  73990. r.y += dy;
  73991. }
  73992. }
  73993. const Path RectangleList::toPath() const
  73994. {
  73995. Path p;
  73996. for (int i = rects.size(); --i >= 0;)
  73997. {
  73998. const Rectangle<int>& r = rects.getReference (i);
  73999. p.addRectangle ((float) r.x,
  74000. (float) r.y,
  74001. (float) r.w,
  74002. (float) r.h);
  74003. }
  74004. return p;
  74005. }
  74006. END_JUCE_NAMESPACE
  74007. /*** End of inlined file: juce_RectangleList.cpp ***/
  74008. /*** Start of inlined file: juce_Image.cpp ***/
  74009. BEGIN_JUCE_NAMESPACE
  74010. static const int fullAlphaThreshold = 253;
  74011. Image::Image (const PixelFormat format_,
  74012. const int imageWidth_,
  74013. const int imageHeight_)
  74014. : format (format_),
  74015. imageWidth (imageWidth_),
  74016. imageHeight (imageHeight_),
  74017. imageData (0)
  74018. {
  74019. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  74020. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  74021. // actual image will be at least 1x1.
  74022. }
  74023. Image::Image (const PixelFormat format_,
  74024. const int imageWidth_,
  74025. const int imageHeight_,
  74026. const bool clearImage)
  74027. : format (format_),
  74028. imageWidth (imageWidth_),
  74029. imageHeight (imageHeight_)
  74030. {
  74031. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  74032. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  74033. // actual image will be at least 1x1.
  74034. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  74035. lineStride = (pixelStride * jmax (1, imageWidth_) + 3) & ~3;
  74036. imageDataAllocated.allocate (lineStride * jmax (1, imageHeight_), clearImage);
  74037. imageData = imageDataAllocated;
  74038. }
  74039. Image::Image (const Image& other)
  74040. : format (other.format),
  74041. imageWidth (other.imageWidth),
  74042. imageHeight (other.imageHeight)
  74043. {
  74044. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  74045. lineStride = (pixelStride * jmax (1, imageWidth) + 3) & ~3;
  74046. imageDataAllocated.malloc (lineStride * jmax (1, imageHeight));
  74047. imageData = imageDataAllocated;
  74048. BitmapData srcData (other, 0, 0, imageWidth, imageHeight);
  74049. setPixelData (0, 0, imageWidth, imageHeight, srcData.data, srcData.lineStride);
  74050. }
  74051. Image::~Image()
  74052. {
  74053. }
  74054. LowLevelGraphicsContext* Image::createLowLevelContext()
  74055. {
  74056. return new LowLevelGraphicsSoftwareRenderer (*this);
  74057. }
  74058. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  74059. : data (image.imageData + image.lineStride * y + image.pixelStride * x),
  74060. pixelFormat (image.getFormat()),
  74061. lineStride (image.lineStride),
  74062. pixelStride (image.pixelStride),
  74063. width (w),
  74064. height (h)
  74065. {
  74066. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  74067. }
  74068. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  74069. : data (image.imageData + image.lineStride * y + image.pixelStride * x),
  74070. pixelFormat (image.getFormat()),
  74071. lineStride (image.lineStride),
  74072. pixelStride (image.pixelStride),
  74073. width (w),
  74074. height (h)
  74075. {
  74076. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  74077. }
  74078. Image::BitmapData::~BitmapData()
  74079. {
  74080. }
  74081. void Image::setPixelData (int x, int y, int w, int h,
  74082. const uint8* const sourcePixelData, const int sourceLineStride)
  74083. {
  74084. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  74085. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, imageWidth, imageHeight))
  74086. {
  74087. const BitmapData dest (*this, x, y, w, h, true);
  74088. for (int i = 0; i < h; ++i)
  74089. {
  74090. memcpy (dest.getLinePointer(i),
  74091. sourcePixelData + sourceLineStride * i,
  74092. w * dest.pixelStride);
  74093. }
  74094. }
  74095. }
  74096. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  74097. {
  74098. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  74099. if (! clipped.isEmpty())
  74100. {
  74101. const PixelARGB col (colourToClearTo.getPixelARGB());
  74102. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  74103. uint8* dest = destData.data;
  74104. int dh = clipped.getHeight();
  74105. while (--dh >= 0)
  74106. {
  74107. uint8* line = dest;
  74108. dest += destData.lineStride;
  74109. if (isARGB())
  74110. {
  74111. for (int x = clipped.getWidth(); --x >= 0;)
  74112. {
  74113. ((PixelARGB*) line)->set (col);
  74114. line += destData.pixelStride;
  74115. }
  74116. }
  74117. else if (isRGB())
  74118. {
  74119. for (int x = clipped.getWidth(); --x >= 0;)
  74120. {
  74121. ((PixelRGB*) line)->set (col);
  74122. line += destData.pixelStride;
  74123. }
  74124. }
  74125. else
  74126. {
  74127. for (int x = clipped.getWidth(); --x >= 0;)
  74128. {
  74129. *line = col.getAlpha();
  74130. line += destData.pixelStride;
  74131. }
  74132. }
  74133. }
  74134. }
  74135. }
  74136. Image* Image::createCopy (int newWidth, int newHeight,
  74137. const Graphics::ResamplingQuality quality) const
  74138. {
  74139. if (newWidth < 0)
  74140. newWidth = imageWidth;
  74141. if (newHeight < 0)
  74142. newHeight = imageHeight;
  74143. Image* const newImage = Image::createNativeImage (format, newWidth, newHeight, true);
  74144. Graphics g (*newImage);
  74145. g.setImageResamplingQuality (quality);
  74146. g.drawImage (this,
  74147. 0, 0, newWidth, newHeight,
  74148. 0, 0, imageWidth, imageHeight,
  74149. false);
  74150. return newImage;
  74151. }
  74152. Image* Image::createCopyOfAlphaChannel() const
  74153. {
  74154. jassert (format != SingleChannel);
  74155. Image* const newImage = Image::createNativeImage (SingleChannel, imageWidth, imageHeight, false);
  74156. if (! hasAlphaChannel())
  74157. {
  74158. newImage->clear (getBounds(), Colours::black);
  74159. }
  74160. else
  74161. {
  74162. const BitmapData destData (*newImage, 0, 0, imageWidth, imageHeight, true);
  74163. const BitmapData srcData (*this, 0, 0, imageWidth, imageHeight);
  74164. for (int y = 0; y < imageHeight; ++y)
  74165. {
  74166. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  74167. uint8* dst = destData.getLinePointer (y);
  74168. for (int x = imageWidth; --x >= 0;)
  74169. {
  74170. *dst++ = src->getAlpha();
  74171. ++src;
  74172. }
  74173. }
  74174. }
  74175. return newImage;
  74176. }
  74177. const Colour Image::getPixelAt (const int x, const int y) const
  74178. {
  74179. Colour c;
  74180. if (((unsigned int) x) < (unsigned int) imageWidth
  74181. && ((unsigned int) y) < (unsigned int) imageHeight)
  74182. {
  74183. const BitmapData srcData (*this, x, y, 1, 1);
  74184. if (isARGB())
  74185. {
  74186. PixelARGB p (*(const PixelARGB*) srcData.data);
  74187. p.unpremultiply();
  74188. c = Colour (p.getARGB());
  74189. }
  74190. else if (isRGB())
  74191. c = Colour (((const PixelRGB*) srcData.data)->getARGB());
  74192. else
  74193. c = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *(srcData.data));
  74194. }
  74195. return c;
  74196. }
  74197. void Image::setPixelAt (const int x, const int y,
  74198. const Colour& colour)
  74199. {
  74200. if (((unsigned int) x) < (unsigned int) imageWidth
  74201. && ((unsigned int) y) < (unsigned int) imageHeight)
  74202. {
  74203. const BitmapData destData (*this, x, y, 1, 1, true);
  74204. const PixelARGB col (colour.getPixelARGB());
  74205. if (isARGB())
  74206. ((PixelARGB*) destData.data)->set (col);
  74207. else if (isRGB())
  74208. ((PixelRGB*) destData.data)->set (col);
  74209. else
  74210. *(destData.data) = col.getAlpha();
  74211. }
  74212. }
  74213. void Image::multiplyAlphaAt (const int x, const int y,
  74214. const float multiplier)
  74215. {
  74216. if (((unsigned int) x) < (unsigned int) imageWidth
  74217. && ((unsigned int) y) < (unsigned int) imageHeight
  74218. && hasAlphaChannel())
  74219. {
  74220. const BitmapData destData (*this, x, y, 1, 1, true);
  74221. if (isARGB())
  74222. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  74223. else
  74224. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  74225. }
  74226. }
  74227. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  74228. {
  74229. if (hasAlphaChannel())
  74230. {
  74231. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  74232. if (isARGB())
  74233. {
  74234. for (int y = 0; y < imageHeight; ++y)
  74235. {
  74236. uint8* p = destData.getLinePointer (y);
  74237. for (int x = 0; x < imageWidth; ++x)
  74238. {
  74239. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  74240. p += destData.pixelStride;
  74241. }
  74242. }
  74243. }
  74244. else
  74245. {
  74246. for (int y = 0; y < imageHeight; ++y)
  74247. {
  74248. uint8* p = destData.getLinePointer (y);
  74249. for (int x = 0; x < imageWidth; ++x)
  74250. {
  74251. *p = (uint8) (*p * amountToMultiplyBy);
  74252. p += destData.pixelStride;
  74253. }
  74254. }
  74255. }
  74256. }
  74257. else
  74258. {
  74259. jassertfalse // can't do this without an alpha-channel!
  74260. }
  74261. }
  74262. void Image::desaturate()
  74263. {
  74264. if (isARGB() || isRGB())
  74265. {
  74266. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  74267. if (isARGB())
  74268. {
  74269. for (int y = 0; y < imageHeight; ++y)
  74270. {
  74271. uint8* p = destData.getLinePointer (y);
  74272. for (int x = 0; x < imageWidth; ++x)
  74273. {
  74274. ((PixelARGB*) p)->desaturate();
  74275. p += destData.pixelStride;
  74276. }
  74277. }
  74278. }
  74279. else
  74280. {
  74281. for (int y = 0; y < imageHeight; ++y)
  74282. {
  74283. uint8* p = destData.getLinePointer (y);
  74284. for (int x = 0; x < imageWidth; ++x)
  74285. {
  74286. ((PixelRGB*) p)->desaturate();
  74287. p += destData.pixelStride;
  74288. }
  74289. }
  74290. }
  74291. }
  74292. }
  74293. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  74294. {
  74295. if (hasAlphaChannel())
  74296. {
  74297. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  74298. SparseSet<int> pixelsOnRow;
  74299. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  74300. for (int y = 0; y < imageHeight; ++y)
  74301. {
  74302. pixelsOnRow.clear();
  74303. const uint8* lineData = srcData.getLinePointer (y);
  74304. if (isARGB())
  74305. {
  74306. for (int x = 0; x < imageWidth; ++x)
  74307. {
  74308. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  74309. pixelsOnRow.addRange (Range<int> (x, x + 1));
  74310. lineData += srcData.pixelStride;
  74311. }
  74312. }
  74313. else
  74314. {
  74315. for (int x = 0; x < imageWidth; ++x)
  74316. {
  74317. if (*lineData >= threshold)
  74318. pixelsOnRow.addRange (Range<int> (x, x + 1));
  74319. lineData += srcData.pixelStride;
  74320. }
  74321. }
  74322. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  74323. {
  74324. const Range<int> range (pixelsOnRow.getRange (i));
  74325. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  74326. }
  74327. result.consolidate();
  74328. }
  74329. }
  74330. else
  74331. {
  74332. result.add (0, 0, imageWidth, imageHeight);
  74333. }
  74334. }
  74335. void Image::moveImageSection (int dx, int dy,
  74336. int sx, int sy,
  74337. int w, int h)
  74338. {
  74339. if (dx < 0)
  74340. {
  74341. w += dx;
  74342. sx -= dx;
  74343. dx = 0;
  74344. }
  74345. if (dy < 0)
  74346. {
  74347. h += dy;
  74348. sy -= dy;
  74349. dy = 0;
  74350. }
  74351. if (sx < 0)
  74352. {
  74353. w += sx;
  74354. dx -= sx;
  74355. sx = 0;
  74356. }
  74357. if (sy < 0)
  74358. {
  74359. h += sy;
  74360. dy -= sy;
  74361. sy = 0;
  74362. }
  74363. const int minX = jmin (dx, sx);
  74364. const int minY = jmin (dy, sy);
  74365. w = jmin (w, getWidth() - jmax (sx, dx));
  74366. h = jmin (h, getHeight() - jmax (sy, dy));
  74367. if (w > 0 && h > 0)
  74368. {
  74369. const int maxX = jmax (dx, sx) + w;
  74370. const int maxY = jmax (dy, sy) + h;
  74371. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  74372. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  74373. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  74374. const int lineSize = destData.pixelStride * w;
  74375. if (dy > sy)
  74376. {
  74377. while (--h >= 0)
  74378. {
  74379. const int offset = h * destData.lineStride;
  74380. memmove (dst + offset, src + offset, lineSize);
  74381. }
  74382. }
  74383. else if (dst != src)
  74384. {
  74385. while (--h >= 0)
  74386. {
  74387. memmove (dst, src, lineSize);
  74388. dst += destData.lineStride;
  74389. src += destData.lineStride;
  74390. }
  74391. }
  74392. }
  74393. }
  74394. END_JUCE_NAMESPACE
  74395. /*** End of inlined file: juce_Image.cpp ***/
  74396. /*** Start of inlined file: juce_ImageCache.cpp ***/
  74397. BEGIN_JUCE_NAMESPACE
  74398. struct ImageCache::Item
  74399. {
  74400. ScopedPointer <Image> image;
  74401. int64 hashCode;
  74402. int refCount;
  74403. uint32 releaseTime;
  74404. juce_UseDebuggingNewOperator
  74405. };
  74406. ImageCache* ImageCache::instance = 0;
  74407. int ImageCache::cacheTimeout = 5000;
  74408. ImageCache::ImageCache()
  74409. {
  74410. }
  74411. ImageCache::~ImageCache()
  74412. {
  74413. jassert (instance == this);
  74414. instance = 0;
  74415. }
  74416. Image* ImageCache::getFromHashCode (const int64 hashCode)
  74417. {
  74418. if (instance != 0)
  74419. {
  74420. const ScopedLock sl (instance->lock);
  74421. for (int i = instance->images.size(); --i >= 0;)
  74422. {
  74423. Item* const ci = instance->images.getUnchecked(i);
  74424. if (ci->hashCode == hashCode)
  74425. {
  74426. ci->refCount++;
  74427. return ci->image;
  74428. }
  74429. }
  74430. }
  74431. return 0;
  74432. }
  74433. void ImageCache::addImageToCache (Image* const image, const int64 hashCode)
  74434. {
  74435. if (image != 0)
  74436. {
  74437. if (instance == 0)
  74438. instance = new ImageCache();
  74439. Item* const newC = new Item();
  74440. newC->hashCode = hashCode;
  74441. newC->image = image;
  74442. newC->refCount = 1;
  74443. newC->releaseTime = 0;
  74444. const ScopedLock sl (instance->lock);
  74445. instance->images.add (newC);
  74446. }
  74447. }
  74448. void ImageCache::release (Image* const imageToRelease)
  74449. {
  74450. if (imageToRelease != 0 && instance != 0)
  74451. {
  74452. const ScopedLock sl (instance->lock);
  74453. for (int i = instance->images.size(); --i >= 0;)
  74454. {
  74455. Item* const ci = instance->images.getUnchecked(i);
  74456. if (static_cast <Image*> (ci->image) == imageToRelease)
  74457. {
  74458. if (--(ci->refCount) == 0)
  74459. ci->releaseTime = Time::getApproximateMillisecondCounter();
  74460. if (! instance->isTimerRunning())
  74461. instance->startTimer (999);
  74462. break;
  74463. }
  74464. }
  74465. }
  74466. }
  74467. void ImageCache::releaseOrDelete (Image* const imageToRelease)
  74468. {
  74469. if (isImageInCache (imageToRelease))
  74470. release (imageToRelease);
  74471. else
  74472. delete imageToRelease;
  74473. }
  74474. bool ImageCache::isImageInCache (Image* const imageToLookFor)
  74475. {
  74476. if (instance != 0)
  74477. {
  74478. const ScopedLock sl (instance->lock);
  74479. for (int i = instance->images.size(); --i >= 0;)
  74480. if (static_cast <Image*> (instance->images.getUnchecked(i)->image) == imageToLookFor)
  74481. return true;
  74482. }
  74483. return false;
  74484. }
  74485. void ImageCache::incReferenceCount (Image* const image)
  74486. {
  74487. if (instance != 0)
  74488. {
  74489. const ScopedLock sl (instance->lock);
  74490. for (int i = instance->images.size(); --i >= 0;)
  74491. {
  74492. Item* const ci = instance->images.getUnchecked(i);
  74493. if (static_cast <Image*> (ci->image) == image)
  74494. {
  74495. ci->refCount++;
  74496. return;
  74497. }
  74498. }
  74499. }
  74500. jassertfalse // (trying to inc the ref count of an image that's not in the cache)
  74501. }
  74502. void ImageCache::timerCallback()
  74503. {
  74504. int numberStillNeedingReleasing = 0;
  74505. const uint32 now = Time::getApproximateMillisecondCounter();
  74506. const ScopedLock sl (lock);
  74507. for (int i = images.size(); --i >= 0;)
  74508. {
  74509. Item* const ci = images.getUnchecked(i);
  74510. if (ci->refCount <= 0)
  74511. {
  74512. if (now > ci->releaseTime + cacheTimeout
  74513. || now < ci->releaseTime - 1000)
  74514. {
  74515. images.remove (i);
  74516. }
  74517. else
  74518. {
  74519. ++numberStillNeedingReleasing;
  74520. }
  74521. }
  74522. }
  74523. if (numberStillNeedingReleasing == 0)
  74524. stopTimer();
  74525. }
  74526. Image* ImageCache::getFromFile (const File& file)
  74527. {
  74528. const int64 hashCode = file.hashCode64();
  74529. Image* image = getFromHashCode (hashCode);
  74530. if (image == 0)
  74531. {
  74532. image = ImageFileFormat::loadFrom (file);
  74533. addImageToCache (image, hashCode);
  74534. }
  74535. return image;
  74536. }
  74537. Image* ImageCache::getFromMemory (const void* imageData, const int dataSize)
  74538. {
  74539. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  74540. Image* image = getFromHashCode (hashCode);
  74541. if (image == 0)
  74542. {
  74543. image = ImageFileFormat::loadFrom (imageData, dataSize);
  74544. addImageToCache (image, hashCode);
  74545. }
  74546. return image;
  74547. }
  74548. void ImageCache::setCacheTimeout (const int millisecs)
  74549. {
  74550. cacheTimeout = millisecs;
  74551. }
  74552. END_JUCE_NAMESPACE
  74553. /*** End of inlined file: juce_ImageCache.cpp ***/
  74554. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  74555. BEGIN_JUCE_NAMESPACE
  74556. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  74557. : values (size_ * size_),
  74558. size (size_)
  74559. {
  74560. clear();
  74561. }
  74562. ImageConvolutionKernel::~ImageConvolutionKernel()
  74563. {
  74564. }
  74565. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  74566. {
  74567. if (((unsigned int) x) < (unsigned int) size
  74568. && ((unsigned int) y) < (unsigned int) size)
  74569. {
  74570. return values [x + y * size];
  74571. }
  74572. else
  74573. {
  74574. jassertfalse;
  74575. return 0;
  74576. }
  74577. }
  74578. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  74579. {
  74580. if (((unsigned int) x) < (unsigned int) size
  74581. && ((unsigned int) y) < (unsigned int) size)
  74582. {
  74583. values [x + y * size] = value;
  74584. }
  74585. else
  74586. {
  74587. jassertfalse;
  74588. }
  74589. }
  74590. void ImageConvolutionKernel::clear()
  74591. {
  74592. for (int i = size * size; --i >= 0;)
  74593. values[i] = 0;
  74594. }
  74595. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  74596. {
  74597. double currentTotal = 0.0;
  74598. for (int i = size * size; --i >= 0;)
  74599. currentTotal += values[i];
  74600. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  74601. }
  74602. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  74603. {
  74604. for (int i = size * size; --i >= 0;)
  74605. values[i] *= multiplier;
  74606. }
  74607. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  74608. {
  74609. const double radiusFactor = -1.0 / (radius * radius * 2);
  74610. const int centre = size >> 1;
  74611. for (int y = size; --y >= 0;)
  74612. {
  74613. for (int x = size; --x >= 0;)
  74614. {
  74615. const int cx = x - centre;
  74616. const int cy = y - centre;
  74617. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  74618. }
  74619. }
  74620. setOverallSum (1.0f);
  74621. }
  74622. void ImageConvolutionKernel::applyToImage (Image& destImage,
  74623. const Image* sourceImage,
  74624. const Rectangle<int>& destinationArea) const
  74625. {
  74626. ScopedPointer <Image> imageCreated;
  74627. if (sourceImage == 0)
  74628. {
  74629. sourceImage = imageCreated = destImage.createCopy();
  74630. }
  74631. else
  74632. {
  74633. jassert (sourceImage->getWidth() == destImage.getWidth()
  74634. && sourceImage->getHeight() == destImage.getHeight()
  74635. && sourceImage->getFormat() == destImage.getFormat());
  74636. if (sourceImage->getWidth() != destImage.getWidth()
  74637. || sourceImage->getHeight() != destImage.getHeight()
  74638. || sourceImage->getFormat() != destImage.getFormat())
  74639. return;
  74640. }
  74641. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  74642. if (area.isEmpty())
  74643. return;
  74644. const int right = area.getRight();
  74645. const int bottom = area.getBottom();
  74646. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  74647. uint8* line = destData.data;
  74648. const Image::BitmapData srcData (*sourceImage, 0, 0, sourceImage->getWidth(), sourceImage->getHeight());
  74649. if (destData.pixelStride == 4)
  74650. {
  74651. for (int y = area.getY(); y < bottom; ++y)
  74652. {
  74653. uint8* dest = line;
  74654. line += destData.lineStride;
  74655. for (int x = area.getX(); x < right; ++x)
  74656. {
  74657. float c1 = 0;
  74658. float c2 = 0;
  74659. float c3 = 0;
  74660. float c4 = 0;
  74661. for (int yy = 0; yy < size; ++yy)
  74662. {
  74663. const int sy = y + yy - (size >> 1);
  74664. if (sy >= srcData.height)
  74665. break;
  74666. if (sy >= 0)
  74667. {
  74668. int sx = x - (size >> 1);
  74669. const uint8* src = srcData.getPixelPointer (sx, sy);
  74670. for (int xx = 0; xx < size; ++xx)
  74671. {
  74672. if (sx >= srcData.width)
  74673. break;
  74674. if (sx >= 0)
  74675. {
  74676. const float kernelMult = values [xx + yy * size];
  74677. c1 += kernelMult * *src++;
  74678. c2 += kernelMult * *src++;
  74679. c3 += kernelMult * *src++;
  74680. c4 += kernelMult * *src++;
  74681. }
  74682. else
  74683. {
  74684. src += 4;
  74685. }
  74686. ++sx;
  74687. }
  74688. }
  74689. }
  74690. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  74691. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  74692. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  74693. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  74694. }
  74695. }
  74696. }
  74697. else if (destData.pixelStride == 3)
  74698. {
  74699. for (int y = area.getY(); y < bottom; ++y)
  74700. {
  74701. uint8* dest = line;
  74702. line += destData.lineStride;
  74703. for (int x = area.getX(); x < right; ++x)
  74704. {
  74705. float c1 = 0;
  74706. float c2 = 0;
  74707. float c3 = 0;
  74708. for (int yy = 0; yy < size; ++yy)
  74709. {
  74710. const int sy = y + yy - (size >> 1);
  74711. if (sy >= srcData.height)
  74712. break;
  74713. if (sy >= 0)
  74714. {
  74715. int sx = x - (size >> 1);
  74716. const uint8* src = srcData.getPixelPointer (sx, sy);
  74717. for (int xx = 0; xx < size; ++xx)
  74718. {
  74719. if (sx >= srcData.width)
  74720. break;
  74721. if (sx >= 0)
  74722. {
  74723. const float kernelMult = values [xx + yy * size];
  74724. c1 += kernelMult * *src++;
  74725. c2 += kernelMult * *src++;
  74726. c3 += kernelMult * *src++;
  74727. }
  74728. else
  74729. {
  74730. src += 3;
  74731. }
  74732. ++sx;
  74733. }
  74734. }
  74735. }
  74736. *dest++ = (uint8) roundToInt (c1);
  74737. *dest++ = (uint8) roundToInt (c2);
  74738. *dest++ = (uint8) roundToInt (c3);
  74739. }
  74740. }
  74741. }
  74742. }
  74743. END_JUCE_NAMESPACE
  74744. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  74745. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  74746. BEGIN_JUCE_NAMESPACE
  74747. /*** Start of inlined file: juce_GIFLoader.h ***/
  74748. #ifndef __JUCE_GIFLOADER_JUCEHEADER__
  74749. #define __JUCE_GIFLOADER_JUCEHEADER__
  74750. #ifndef DOXYGEN
  74751. /**
  74752. Used internally by ImageFileFormat - don't use this class directly in your
  74753. application.
  74754. @see ImageFileFormat
  74755. */
  74756. class GIFLoader
  74757. {
  74758. public:
  74759. GIFLoader (InputStream& in);
  74760. ~GIFLoader();
  74761. Image* getImage() const { return image; }
  74762. private:
  74763. Image* image;
  74764. InputStream& input;
  74765. uint8 buffer [300];
  74766. uint8 palette [256][4];
  74767. bool dataBlockIsZero, fresh, finished;
  74768. int currentBit, lastBit, lastByteIndex;
  74769. int codeSize, setCodeSize;
  74770. int maxCode, maxCodeSize;
  74771. int firstcode, oldcode;
  74772. int clearCode, end_code;
  74773. enum { maxGifCode = 1 << 12 };
  74774. int table [2] [maxGifCode];
  74775. int stack [2 * maxGifCode];
  74776. int *sp;
  74777. bool getSizeFromHeader (int& width, int& height);
  74778. bool readPalette (const int numCols);
  74779. int readDataBlock (unsigned char* dest);
  74780. int processExtension (int type, int& transparent);
  74781. int readLZWByte (bool initialise, int input_code_size);
  74782. int getCode (int code_size, bool initialise);
  74783. bool readImage (int width, int height, int interlace, int transparent);
  74784. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  74785. GIFLoader (const GIFLoader&);
  74786. GIFLoader& operator= (const GIFLoader&);
  74787. };
  74788. #endif // DOXYGEN
  74789. #endif // __JUCE_GIFLOADER_JUCEHEADER__
  74790. /*** End of inlined file: juce_GIFLoader.h ***/
  74791. class GIFImageFormat : public ImageFileFormat
  74792. {
  74793. public:
  74794. GIFImageFormat() {}
  74795. ~GIFImageFormat() {}
  74796. const String getFormatName()
  74797. {
  74798. return "GIF";
  74799. }
  74800. bool canUnderstand (InputStream& in)
  74801. {
  74802. const int bytesNeeded = 4;
  74803. char header [bytesNeeded];
  74804. return (in.read (header, bytesNeeded) == bytesNeeded)
  74805. && header[0] == 'G'
  74806. && header[1] == 'I'
  74807. && header[2] == 'F';
  74808. }
  74809. Image* decodeImage (InputStream& in)
  74810. {
  74811. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  74812. return loader->getImage();
  74813. }
  74814. bool writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  74815. {
  74816. return false;
  74817. }
  74818. };
  74819. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  74820. {
  74821. static PNGImageFormat png;
  74822. static JPEGImageFormat jpg;
  74823. static GIFImageFormat gif;
  74824. ImageFileFormat* formats[4];
  74825. int numFormats = 0;
  74826. formats [numFormats++] = &png;
  74827. formats [numFormats++] = &jpg;
  74828. formats [numFormats++] = &gif;
  74829. const int64 streamPos = input.getPosition();
  74830. for (int i = 0; i < numFormats; ++i)
  74831. {
  74832. const bool found = formats[i]->canUnderstand (input);
  74833. input.setPosition (streamPos);
  74834. if (found)
  74835. return formats[i];
  74836. }
  74837. return 0;
  74838. }
  74839. Image* ImageFileFormat::loadFrom (InputStream& input)
  74840. {
  74841. ImageFileFormat* const format = findImageFormatForStream (input);
  74842. if (format != 0)
  74843. return format->decodeImage (input);
  74844. return 0;
  74845. }
  74846. Image* ImageFileFormat::loadFrom (const File& file)
  74847. {
  74848. InputStream* const in = file.createInputStream();
  74849. if (in != 0)
  74850. {
  74851. BufferedInputStream b (in, 8192, true);
  74852. return loadFrom (b);
  74853. }
  74854. return 0;
  74855. }
  74856. Image* ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  74857. {
  74858. if (rawData != 0 && numBytes > 4)
  74859. {
  74860. MemoryInputStream stream (rawData, numBytes, false);
  74861. return loadFrom (stream);
  74862. }
  74863. return 0;
  74864. }
  74865. END_JUCE_NAMESPACE
  74866. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  74867. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  74868. BEGIN_JUCE_NAMESPACE
  74869. GIFLoader::GIFLoader (InputStream& in)
  74870. : image (0),
  74871. input (in),
  74872. dataBlockIsZero (false),
  74873. fresh (false),
  74874. finished (false)
  74875. {
  74876. currentBit = lastBit = lastByteIndex = 0;
  74877. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  74878. firstcode = oldcode = 0;
  74879. clearCode = end_code = 0;
  74880. int imageWidth, imageHeight;
  74881. int transparent = -1;
  74882. if (! getSizeFromHeader (imageWidth, imageHeight))
  74883. return;
  74884. if ((imageWidth <= 0) || (imageHeight <= 0))
  74885. return;
  74886. unsigned char buf [16];
  74887. if (in.read (buf, 3) != 3)
  74888. return;
  74889. int numColours = 2 << (buf[0] & 7);
  74890. if ((buf[0] & 0x80) != 0)
  74891. readPalette (numColours);
  74892. for (;;)
  74893. {
  74894. if (input.read (buf, 1) != 1)
  74895. break;
  74896. if (buf[0] == ';')
  74897. break;
  74898. if (buf[0] == '!')
  74899. {
  74900. if (input.read (buf, 1) != 1)
  74901. break;
  74902. if (processExtension (buf[0], transparent) < 0)
  74903. break;
  74904. continue;
  74905. }
  74906. if (buf[0] != ',')
  74907. continue;
  74908. if (input.read (buf, 9) != 9)
  74909. break;
  74910. imageWidth = makeWord (buf[4], buf[5]);
  74911. imageHeight = makeWord (buf[6], buf[7]);
  74912. numColours = 2 << (buf[8] & 7);
  74913. if ((buf[8] & 0x80) != 0)
  74914. if (! readPalette (numColours))
  74915. break;
  74916. image = Image::createNativeImage ((transparent >= 0) ? Image::ARGB : Image::RGB,
  74917. imageWidth, imageHeight, (transparent >= 0));
  74918. readImage (imageWidth, imageHeight,
  74919. (buf[8] & 0x40) != 0,
  74920. transparent);
  74921. break;
  74922. }
  74923. }
  74924. GIFLoader::~GIFLoader()
  74925. {
  74926. }
  74927. bool GIFLoader::getSizeFromHeader (int& w, int& h)
  74928. {
  74929. char b[8];
  74930. if (input.read (b, 6) == 6)
  74931. {
  74932. if ((strncmp ("GIF87a", b, 6) == 0)
  74933. || (strncmp ("GIF89a", b, 6) == 0))
  74934. {
  74935. if (input.read (b, 4) == 4)
  74936. {
  74937. w = makeWord (b[0], b[1]);
  74938. h = makeWord (b[2], b[3]);
  74939. return true;
  74940. }
  74941. }
  74942. }
  74943. return false;
  74944. }
  74945. bool GIFLoader::readPalette (const int numCols)
  74946. {
  74947. unsigned char rgb[4];
  74948. for (int i = 0; i < numCols; ++i)
  74949. {
  74950. input.read (rgb, 3);
  74951. palette [i][0] = rgb[0];
  74952. palette [i][1] = rgb[1];
  74953. palette [i][2] = rgb[2];
  74954. palette [i][3] = 0xff;
  74955. }
  74956. return true;
  74957. }
  74958. int GIFLoader::readDataBlock (unsigned char* const dest)
  74959. {
  74960. unsigned char n;
  74961. if (input.read (&n, 1) == 1)
  74962. {
  74963. dataBlockIsZero = (n == 0);
  74964. if (dataBlockIsZero || (input.read (dest, n) == n))
  74965. return n;
  74966. }
  74967. return -1;
  74968. }
  74969. int GIFLoader::processExtension (const int type, int& transparent)
  74970. {
  74971. unsigned char b [300];
  74972. int n = 0;
  74973. if (type == 0xf9)
  74974. {
  74975. n = readDataBlock (b);
  74976. if (n < 0)
  74977. return 1;
  74978. if ((b[0] & 0x1) != 0)
  74979. transparent = b[3];
  74980. }
  74981. do
  74982. {
  74983. n = readDataBlock (b);
  74984. }
  74985. while (n > 0);
  74986. return n;
  74987. }
  74988. int GIFLoader::getCode (const int codeSize_, const bool initialise)
  74989. {
  74990. if (initialise)
  74991. {
  74992. currentBit = 0;
  74993. lastBit = 0;
  74994. finished = false;
  74995. return 0;
  74996. }
  74997. if ((currentBit + codeSize_) >= lastBit)
  74998. {
  74999. if (finished)
  75000. return -1;
  75001. buffer[0] = buffer [lastByteIndex - 2];
  75002. buffer[1] = buffer [lastByteIndex - 1];
  75003. const int n = readDataBlock (&buffer[2]);
  75004. if (n == 0)
  75005. finished = true;
  75006. lastByteIndex = 2 + n;
  75007. currentBit = (currentBit - lastBit) + 16;
  75008. lastBit = (2 + n) * 8 ;
  75009. }
  75010. int result = 0;
  75011. int i = currentBit;
  75012. for (int j = 0; j < codeSize_; ++j)
  75013. {
  75014. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  75015. ++i;
  75016. }
  75017. currentBit += codeSize_;
  75018. return result;
  75019. }
  75020. int GIFLoader::readLZWByte (const bool initialise, const int inputCodeSize)
  75021. {
  75022. int code, incode, i;
  75023. if (initialise)
  75024. {
  75025. setCodeSize = inputCodeSize;
  75026. codeSize = setCodeSize + 1;
  75027. clearCode = 1 << setCodeSize;
  75028. end_code = clearCode + 1;
  75029. maxCodeSize = 2 * clearCode;
  75030. maxCode = clearCode + 2;
  75031. getCode (0, true);
  75032. fresh = true;
  75033. for (i = 0; i < clearCode; ++i)
  75034. {
  75035. table[0][i] = 0;
  75036. table[1][i] = i;
  75037. }
  75038. for (; i < maxGifCode; ++i)
  75039. {
  75040. table[0][i] = 0;
  75041. table[1][i] = 0;
  75042. }
  75043. sp = stack;
  75044. return 0;
  75045. }
  75046. else if (fresh)
  75047. {
  75048. fresh = false;
  75049. do
  75050. {
  75051. firstcode = oldcode
  75052. = getCode (codeSize, false);
  75053. }
  75054. while (firstcode == clearCode);
  75055. return firstcode;
  75056. }
  75057. if (sp > stack)
  75058. return *--sp;
  75059. while ((code = getCode (codeSize, false)) >= 0)
  75060. {
  75061. if (code == clearCode)
  75062. {
  75063. for (i = 0; i < clearCode; ++i)
  75064. {
  75065. table[0][i] = 0;
  75066. table[1][i] = i;
  75067. }
  75068. for (; i < maxGifCode; ++i)
  75069. {
  75070. table[0][i] = 0;
  75071. table[1][i] = 0;
  75072. }
  75073. codeSize = setCodeSize + 1;
  75074. maxCodeSize = 2 * clearCode;
  75075. maxCode = clearCode + 2;
  75076. sp = stack;
  75077. firstcode = oldcode = getCode (codeSize, false);
  75078. return firstcode;
  75079. }
  75080. else if (code == end_code)
  75081. {
  75082. if (dataBlockIsZero)
  75083. return -2;
  75084. unsigned char buf [260];
  75085. int n;
  75086. while ((n = readDataBlock (buf)) > 0)
  75087. {}
  75088. if (n != 0)
  75089. return -2;
  75090. }
  75091. incode = code;
  75092. if (code >= maxCode)
  75093. {
  75094. *sp++ = firstcode;
  75095. code = oldcode;
  75096. }
  75097. while (code >= clearCode)
  75098. {
  75099. *sp++ = table[1][code];
  75100. if (code == table[0][code])
  75101. return -2;
  75102. code = table[0][code];
  75103. }
  75104. *sp++ = firstcode = table[1][code];
  75105. if ((code = maxCode) < maxGifCode)
  75106. {
  75107. table[0][code] = oldcode;
  75108. table[1][code] = firstcode;
  75109. ++maxCode;
  75110. if ((maxCode >= maxCodeSize)
  75111. && (maxCodeSize < maxGifCode))
  75112. {
  75113. maxCodeSize <<= 1;
  75114. ++codeSize;
  75115. }
  75116. }
  75117. oldcode = incode;
  75118. if (sp > stack)
  75119. return *--sp;
  75120. }
  75121. return code;
  75122. }
  75123. bool GIFLoader::readImage (const int width, const int height,
  75124. const int interlace, const int transparent)
  75125. {
  75126. unsigned char c;
  75127. if (input.read (&c, 1) != 1
  75128. || readLZWByte (true, c) < 0)
  75129. return false;
  75130. if (transparent >= 0)
  75131. {
  75132. palette [transparent][0] = 0;
  75133. palette [transparent][1] = 0;
  75134. palette [transparent][2] = 0;
  75135. palette [transparent][3] = 0;
  75136. }
  75137. int index;
  75138. int xpos = 0, ypos = 0, pass = 0;
  75139. const Image::BitmapData destData (*image, 0, 0, width, height, true);
  75140. uint8* p = destData.data;
  75141. const bool hasAlpha = image->hasAlphaChannel();
  75142. while ((index = readLZWByte (false, c)) >= 0)
  75143. {
  75144. const uint8* const paletteEntry = palette [index];
  75145. if (hasAlpha)
  75146. {
  75147. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  75148. paletteEntry[0],
  75149. paletteEntry[1],
  75150. paletteEntry[2]);
  75151. ((PixelARGB*) p)->premultiply();
  75152. }
  75153. else
  75154. {
  75155. ((PixelRGB*) p)->setARGB (0,
  75156. paletteEntry[0],
  75157. paletteEntry[1],
  75158. paletteEntry[2]);
  75159. }
  75160. p += destData.pixelStride;
  75161. ++xpos;
  75162. if (xpos == width)
  75163. {
  75164. xpos = 0;
  75165. if (interlace)
  75166. {
  75167. switch (pass)
  75168. {
  75169. case 0:
  75170. case 1: ypos += 8; break;
  75171. case 2: ypos += 4; break;
  75172. case 3: ypos += 2; break;
  75173. }
  75174. while (ypos >= height)
  75175. {
  75176. ++pass;
  75177. switch (pass)
  75178. {
  75179. case 1: ypos = 4; break;
  75180. case 2: ypos = 2; break;
  75181. case 3: ypos = 1; break;
  75182. default: return true;
  75183. }
  75184. }
  75185. }
  75186. else
  75187. {
  75188. ++ypos;
  75189. }
  75190. p = destData.getPixelPointer (xpos, ypos);
  75191. }
  75192. if (ypos >= height)
  75193. break;
  75194. }
  75195. return true;
  75196. }
  75197. END_JUCE_NAMESPACE
  75198. /*** End of inlined file: juce_GIFLoader.cpp ***/
  75199. #endif
  75200. //==============================================================================
  75201. // some files include lots of library code, so leave them to the end to avoid cluttering
  75202. // up the build for the clean files.
  75203. #if JUCE_BUILD_CORE
  75204. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  75205. namespace zlibNamespace
  75206. {
  75207. #if JUCE_INCLUDE_ZLIB_CODE
  75208. #undef OS_CODE
  75209. #undef fdopen
  75210. /*** Start of inlined file: zlib.h ***/
  75211. #ifndef ZLIB_H
  75212. #define ZLIB_H
  75213. /*** Start of inlined file: zconf.h ***/
  75214. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  75215. #ifndef ZCONF_H
  75216. #define ZCONF_H
  75217. // *** Just a few hacks here to make it compile nicely with Juce..
  75218. #define Z_PREFIX 1
  75219. #undef __MACTYPES__
  75220. #ifdef _MSC_VER
  75221. #pragma warning (disable : 4131 4127 4244 4267)
  75222. #endif
  75223. /*
  75224. * If you *really* need a unique prefix for all types and library functions,
  75225. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  75226. */
  75227. #ifdef Z_PREFIX
  75228. # define deflateInit_ z_deflateInit_
  75229. # define deflate z_deflate
  75230. # define deflateEnd z_deflateEnd
  75231. # define inflateInit_ z_inflateInit_
  75232. # define inflate z_inflate
  75233. # define inflateEnd z_inflateEnd
  75234. # define inflatePrime z_inflatePrime
  75235. # define inflateGetHeader z_inflateGetHeader
  75236. # define adler32_combine z_adler32_combine
  75237. # define crc32_combine z_crc32_combine
  75238. # define deflateInit2_ z_deflateInit2_
  75239. # define deflateSetDictionary z_deflateSetDictionary
  75240. # define deflateCopy z_deflateCopy
  75241. # define deflateReset z_deflateReset
  75242. # define deflateParams z_deflateParams
  75243. # define deflateBound z_deflateBound
  75244. # define deflatePrime z_deflatePrime
  75245. # define inflateInit2_ z_inflateInit2_
  75246. # define inflateSetDictionary z_inflateSetDictionary
  75247. # define inflateSync z_inflateSync
  75248. # define inflateSyncPoint z_inflateSyncPoint
  75249. # define inflateCopy z_inflateCopy
  75250. # define inflateReset z_inflateReset
  75251. # define inflateBack z_inflateBack
  75252. # define inflateBackEnd z_inflateBackEnd
  75253. # define compress z_compress
  75254. # define compress2 z_compress2
  75255. # define compressBound z_compressBound
  75256. # define uncompress z_uncompress
  75257. # define adler32 z_adler32
  75258. # define crc32 z_crc32
  75259. # define get_crc_table z_get_crc_table
  75260. # define zError z_zError
  75261. # define alloc_func z_alloc_func
  75262. # define free_func z_free_func
  75263. # define in_func z_in_func
  75264. # define out_func z_out_func
  75265. # define Byte z_Byte
  75266. # define uInt z_uInt
  75267. # define uLong z_uLong
  75268. # define Bytef z_Bytef
  75269. # define charf z_charf
  75270. # define intf z_intf
  75271. # define uIntf z_uIntf
  75272. # define uLongf z_uLongf
  75273. # define voidpf z_voidpf
  75274. # define voidp z_voidp
  75275. #endif
  75276. #if defined(__MSDOS__) && !defined(MSDOS)
  75277. # define MSDOS
  75278. #endif
  75279. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  75280. # define OS2
  75281. #endif
  75282. #if defined(_WINDOWS) && !defined(WINDOWS)
  75283. # define WINDOWS
  75284. #endif
  75285. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  75286. # ifndef WIN32
  75287. # define WIN32
  75288. # endif
  75289. #endif
  75290. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  75291. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  75292. # ifndef SYS16BIT
  75293. # define SYS16BIT
  75294. # endif
  75295. # endif
  75296. #endif
  75297. /*
  75298. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  75299. * than 64k bytes at a time (needed on systems with 16-bit int).
  75300. */
  75301. #ifdef SYS16BIT
  75302. # define MAXSEG_64K
  75303. #endif
  75304. #ifdef MSDOS
  75305. # define UNALIGNED_OK
  75306. #endif
  75307. #ifdef __STDC_VERSION__
  75308. # ifndef STDC
  75309. # define STDC
  75310. # endif
  75311. # if __STDC_VERSION__ >= 199901L
  75312. # ifndef STDC99
  75313. # define STDC99
  75314. # endif
  75315. # endif
  75316. #endif
  75317. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  75318. # define STDC
  75319. #endif
  75320. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  75321. # define STDC
  75322. #endif
  75323. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  75324. # define STDC
  75325. #endif
  75326. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  75327. # define STDC
  75328. #endif
  75329. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  75330. # define STDC
  75331. #endif
  75332. #ifndef STDC
  75333. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  75334. # define const /* note: need a more gentle solution here */
  75335. # endif
  75336. #endif
  75337. /* Some Mac compilers merge all .h files incorrectly: */
  75338. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  75339. # define NO_DUMMY_DECL
  75340. #endif
  75341. /* Maximum value for memLevel in deflateInit2 */
  75342. #ifndef MAX_MEM_LEVEL
  75343. # ifdef MAXSEG_64K
  75344. # define MAX_MEM_LEVEL 8
  75345. # else
  75346. # define MAX_MEM_LEVEL 9
  75347. # endif
  75348. #endif
  75349. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  75350. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  75351. * created by gzip. (Files created by minigzip can still be extracted by
  75352. * gzip.)
  75353. */
  75354. #ifndef MAX_WBITS
  75355. # define MAX_WBITS 15 /* 32K LZ77 window */
  75356. #endif
  75357. /* The memory requirements for deflate are (in bytes):
  75358. (1 << (windowBits+2)) + (1 << (memLevel+9))
  75359. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  75360. plus a few kilobytes for small objects. For example, if you want to reduce
  75361. the default memory requirements from 256K to 128K, compile with
  75362. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  75363. Of course this will generally degrade compression (there's no free lunch).
  75364. The memory requirements for inflate are (in bytes) 1 << windowBits
  75365. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  75366. for small objects.
  75367. */
  75368. /* Type declarations */
  75369. #ifndef OF /* function prototypes */
  75370. # ifdef STDC
  75371. # define OF(args) args
  75372. # else
  75373. # define OF(args) ()
  75374. # endif
  75375. #endif
  75376. /* The following definitions for FAR are needed only for MSDOS mixed
  75377. * model programming (small or medium model with some far allocations).
  75378. * This was tested only with MSC; for other MSDOS compilers you may have
  75379. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  75380. * just define FAR to be empty.
  75381. */
  75382. #ifdef SYS16BIT
  75383. # if defined(M_I86SM) || defined(M_I86MM)
  75384. /* MSC small or medium model */
  75385. # define SMALL_MEDIUM
  75386. # ifdef _MSC_VER
  75387. # define FAR _far
  75388. # else
  75389. # define FAR far
  75390. # endif
  75391. # endif
  75392. # if (defined(__SMALL__) || defined(__MEDIUM__))
  75393. /* Turbo C small or medium model */
  75394. # define SMALL_MEDIUM
  75395. # ifdef __BORLANDC__
  75396. # define FAR _far
  75397. # else
  75398. # define FAR far
  75399. # endif
  75400. # endif
  75401. #endif
  75402. #if defined(WINDOWS) || defined(WIN32)
  75403. /* If building or using zlib as a DLL, define ZLIB_DLL.
  75404. * This is not mandatory, but it offers a little performance increase.
  75405. */
  75406. # ifdef ZLIB_DLL
  75407. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  75408. # ifdef ZLIB_INTERNAL
  75409. # define ZEXTERN extern __declspec(dllexport)
  75410. # else
  75411. # define ZEXTERN extern __declspec(dllimport)
  75412. # endif
  75413. # endif
  75414. # endif /* ZLIB_DLL */
  75415. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  75416. * define ZLIB_WINAPI.
  75417. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  75418. */
  75419. # ifdef ZLIB_WINAPI
  75420. # ifdef FAR
  75421. # undef FAR
  75422. # endif
  75423. # include <windows.h>
  75424. /* No need for _export, use ZLIB.DEF instead. */
  75425. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  75426. # define ZEXPORT WINAPI
  75427. # ifdef WIN32
  75428. # define ZEXPORTVA WINAPIV
  75429. # else
  75430. # define ZEXPORTVA FAR CDECL
  75431. # endif
  75432. # endif
  75433. #endif
  75434. #if defined (__BEOS__)
  75435. # ifdef ZLIB_DLL
  75436. # ifdef ZLIB_INTERNAL
  75437. # define ZEXPORT __declspec(dllexport)
  75438. # define ZEXPORTVA __declspec(dllexport)
  75439. # else
  75440. # define ZEXPORT __declspec(dllimport)
  75441. # define ZEXPORTVA __declspec(dllimport)
  75442. # endif
  75443. # endif
  75444. #endif
  75445. #ifndef ZEXTERN
  75446. # define ZEXTERN extern
  75447. #endif
  75448. #ifndef ZEXPORT
  75449. # define ZEXPORT
  75450. #endif
  75451. #ifndef ZEXPORTVA
  75452. # define ZEXPORTVA
  75453. #endif
  75454. #ifndef FAR
  75455. # define FAR
  75456. #endif
  75457. #if !defined(__MACTYPES__)
  75458. typedef unsigned char Byte; /* 8 bits */
  75459. #endif
  75460. typedef unsigned int uInt; /* 16 bits or more */
  75461. typedef unsigned long uLong; /* 32 bits or more */
  75462. #ifdef SMALL_MEDIUM
  75463. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  75464. # define Bytef Byte FAR
  75465. #else
  75466. typedef Byte FAR Bytef;
  75467. #endif
  75468. typedef char FAR charf;
  75469. typedef int FAR intf;
  75470. typedef uInt FAR uIntf;
  75471. typedef uLong FAR uLongf;
  75472. #ifdef STDC
  75473. typedef void const *voidpc;
  75474. typedef void FAR *voidpf;
  75475. typedef void *voidp;
  75476. #else
  75477. typedef Byte const *voidpc;
  75478. typedef Byte FAR *voidpf;
  75479. typedef Byte *voidp;
  75480. #endif
  75481. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  75482. # include <sys/types.h> /* for off_t */
  75483. # include <unistd.h> /* for SEEK_* and off_t */
  75484. # ifdef VMS
  75485. # include <unixio.h> /* for off_t */
  75486. # endif
  75487. # define z_off_t off_t
  75488. #endif
  75489. #ifndef SEEK_SET
  75490. # define SEEK_SET 0 /* Seek from beginning of file. */
  75491. # define SEEK_CUR 1 /* Seek from current position. */
  75492. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  75493. #endif
  75494. #ifndef z_off_t
  75495. # define z_off_t long
  75496. #endif
  75497. #if defined(__OS400__)
  75498. # define NO_vsnprintf
  75499. #endif
  75500. #if defined(__MVS__)
  75501. # define NO_vsnprintf
  75502. # ifdef FAR
  75503. # undef FAR
  75504. # endif
  75505. #endif
  75506. /* MVS linker does not support external names larger than 8 bytes */
  75507. #if defined(__MVS__)
  75508. # pragma map(deflateInit_,"DEIN")
  75509. # pragma map(deflateInit2_,"DEIN2")
  75510. # pragma map(deflateEnd,"DEEND")
  75511. # pragma map(deflateBound,"DEBND")
  75512. # pragma map(inflateInit_,"ININ")
  75513. # pragma map(inflateInit2_,"ININ2")
  75514. # pragma map(inflateEnd,"INEND")
  75515. # pragma map(inflateSync,"INSY")
  75516. # pragma map(inflateSetDictionary,"INSEDI")
  75517. # pragma map(compressBound,"CMBND")
  75518. # pragma map(inflate_table,"INTABL")
  75519. # pragma map(inflate_fast,"INFA")
  75520. # pragma map(inflate_copyright,"INCOPY")
  75521. #endif
  75522. #endif /* ZCONF_H */
  75523. /*** End of inlined file: zconf.h ***/
  75524. #ifdef __cplusplus
  75525. extern "C" {
  75526. #endif
  75527. #define ZLIB_VERSION "1.2.3"
  75528. #define ZLIB_VERNUM 0x1230
  75529. /*
  75530. The 'zlib' compression library provides in-memory compression and
  75531. decompression functions, including integrity checks of the uncompressed
  75532. data. This version of the library supports only one compression method
  75533. (deflation) but other algorithms will be added later and will have the same
  75534. stream interface.
  75535. Compression can be done in a single step if the buffers are large
  75536. enough (for example if an input file is mmap'ed), or can be done by
  75537. repeated calls of the compression function. In the latter case, the
  75538. application must provide more input and/or consume the output
  75539. (providing more output space) before each call.
  75540. The compressed data format used by default by the in-memory functions is
  75541. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  75542. around a deflate stream, which is itself documented in RFC 1951.
  75543. The library also supports reading and writing files in gzip (.gz) format
  75544. with an interface similar to that of stdio using the functions that start
  75545. with "gz". The gzip format is different from the zlib format. gzip is a
  75546. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  75547. This library can optionally read and write gzip streams in memory as well.
  75548. The zlib format was designed to be compact and fast for use in memory
  75549. and on communications channels. The gzip format was designed for single-
  75550. file compression on file systems, has a larger header than zlib to maintain
  75551. directory information, and uses a different, slower check method than zlib.
  75552. The library does not install any signal handler. The decoder checks
  75553. the consistency of the compressed data, so the library should never
  75554. crash even in case of corrupted input.
  75555. */
  75556. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  75557. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  75558. struct internal_state;
  75559. typedef struct z_stream_s {
  75560. Bytef *next_in; /* next input byte */
  75561. uInt avail_in; /* number of bytes available at next_in */
  75562. uLong total_in; /* total nb of input bytes read so far */
  75563. Bytef *next_out; /* next output byte should be put there */
  75564. uInt avail_out; /* remaining free space at next_out */
  75565. uLong total_out; /* total nb of bytes output so far */
  75566. char *msg; /* last error message, NULL if no error */
  75567. struct internal_state FAR *state; /* not visible by applications */
  75568. alloc_func zalloc; /* used to allocate the internal state */
  75569. free_func zfree; /* used to free the internal state */
  75570. voidpf opaque; /* private data object passed to zalloc and zfree */
  75571. int data_type; /* best guess about the data type: binary or text */
  75572. uLong adler; /* adler32 value of the uncompressed data */
  75573. uLong reserved; /* reserved for future use */
  75574. } z_stream;
  75575. typedef z_stream FAR *z_streamp;
  75576. /*
  75577. gzip header information passed to and from zlib routines. See RFC 1952
  75578. for more details on the meanings of these fields.
  75579. */
  75580. typedef struct gz_header_s {
  75581. int text; /* true if compressed data believed to be text */
  75582. uLong time; /* modification time */
  75583. int xflags; /* extra flags (not used when writing a gzip file) */
  75584. int os; /* operating system */
  75585. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  75586. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  75587. uInt extra_max; /* space at extra (only when reading header) */
  75588. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  75589. uInt name_max; /* space at name (only when reading header) */
  75590. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  75591. uInt comm_max; /* space at comment (only when reading header) */
  75592. int hcrc; /* true if there was or will be a header crc */
  75593. int done; /* true when done reading gzip header (not used
  75594. when writing a gzip file) */
  75595. } gz_header;
  75596. typedef gz_header FAR *gz_headerp;
  75597. /*
  75598. The application must update next_in and avail_in when avail_in has
  75599. dropped to zero. It must update next_out and avail_out when avail_out
  75600. has dropped to zero. The application must initialize zalloc, zfree and
  75601. opaque before calling the init function. All other fields are set by the
  75602. compression library and must not be updated by the application.
  75603. The opaque value provided by the application will be passed as the first
  75604. parameter for calls of zalloc and zfree. This can be useful for custom
  75605. memory management. The compression library attaches no meaning to the
  75606. opaque value.
  75607. zalloc must return Z_NULL if there is not enough memory for the object.
  75608. If zlib is used in a multi-threaded application, zalloc and zfree must be
  75609. thread safe.
  75610. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  75611. exactly 65536 bytes, but will not be required to allocate more than this
  75612. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  75613. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  75614. have their offset normalized to zero. The default allocation function
  75615. provided by this library ensures this (see zutil.c). To reduce memory
  75616. requirements and avoid any allocation of 64K objects, at the expense of
  75617. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  75618. The fields total_in and total_out can be used for statistics or
  75619. progress reports. After compression, total_in holds the total size of
  75620. the uncompressed data and may be saved for use in the decompressor
  75621. (particularly if the decompressor wants to decompress everything in
  75622. a single step).
  75623. */
  75624. /* constants */
  75625. #define Z_NO_FLUSH 0
  75626. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  75627. #define Z_SYNC_FLUSH 2
  75628. #define Z_FULL_FLUSH 3
  75629. #define Z_FINISH 4
  75630. #define Z_BLOCK 5
  75631. /* Allowed flush values; see deflate() and inflate() below for details */
  75632. #define Z_OK 0
  75633. #define Z_STREAM_END 1
  75634. #define Z_NEED_DICT 2
  75635. #define Z_ERRNO (-1)
  75636. #define Z_STREAM_ERROR (-2)
  75637. #define Z_DATA_ERROR (-3)
  75638. #define Z_MEM_ERROR (-4)
  75639. #define Z_BUF_ERROR (-5)
  75640. #define Z_VERSION_ERROR (-6)
  75641. /* Return codes for the compression/decompression functions. Negative
  75642. * values are errors, positive values are used for special but normal events.
  75643. */
  75644. #define Z_NO_COMPRESSION 0
  75645. #define Z_BEST_SPEED 1
  75646. #define Z_BEST_COMPRESSION 9
  75647. #define Z_DEFAULT_COMPRESSION (-1)
  75648. /* compression levels */
  75649. #define Z_FILTERED 1
  75650. #define Z_HUFFMAN_ONLY 2
  75651. #define Z_RLE 3
  75652. #define Z_FIXED 4
  75653. #define Z_DEFAULT_STRATEGY 0
  75654. /* compression strategy; see deflateInit2() below for details */
  75655. #define Z_BINARY 0
  75656. #define Z_TEXT 1
  75657. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  75658. #define Z_UNKNOWN 2
  75659. /* Possible values of the data_type field (though see inflate()) */
  75660. #define Z_DEFLATED 8
  75661. /* The deflate compression method (the only one supported in this version) */
  75662. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  75663. #define zlib_version zlibVersion()
  75664. /* for compatibility with versions < 1.0.2 */
  75665. /* basic functions */
  75666. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  75667. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  75668. If the first character differs, the library code actually used is
  75669. not compatible with the zlib.h header file used by the application.
  75670. This check is automatically made by deflateInit and inflateInit.
  75671. */
  75672. /*
  75673. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  75674. Initializes the internal stream state for compression. The fields
  75675. zalloc, zfree and opaque must be initialized before by the caller.
  75676. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  75677. use default allocation functions.
  75678. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  75679. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  75680. all (the input data is simply copied a block at a time).
  75681. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  75682. compression (currently equivalent to level 6).
  75683. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  75684. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  75685. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  75686. with the version assumed by the caller (ZLIB_VERSION).
  75687. msg is set to null if there is no error message. deflateInit does not
  75688. perform any compression: this will be done by deflate().
  75689. */
  75690. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  75691. /*
  75692. deflate compresses as much data as possible, and stops when the input
  75693. buffer becomes empty or the output buffer becomes full. It may introduce some
  75694. output latency (reading input without producing any output) except when
  75695. forced to flush.
  75696. The detailed semantics are as follows. deflate performs one or both of the
  75697. following actions:
  75698. - Compress more input starting at next_in and update next_in and avail_in
  75699. accordingly. If not all input can be processed (because there is not
  75700. enough room in the output buffer), next_in and avail_in are updated and
  75701. processing will resume at this point for the next call of deflate().
  75702. - Provide more output starting at next_out and update next_out and avail_out
  75703. accordingly. This action is forced if the parameter flush is non zero.
  75704. Forcing flush frequently degrades the compression ratio, so this parameter
  75705. should be set only when necessary (in interactive applications).
  75706. Some output may be provided even if flush is not set.
  75707. Before the call of deflate(), the application should ensure that at least
  75708. one of the actions is possible, by providing more input and/or consuming
  75709. more output, and updating avail_in or avail_out accordingly; avail_out
  75710. should never be zero before the call. The application can consume the
  75711. compressed output when it wants, for example when the output buffer is full
  75712. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  75713. and with zero avail_out, it must be called again after making room in the
  75714. output buffer because there might be more output pending.
  75715. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  75716. decide how much data to accumualte before producing output, in order to
  75717. maximize compression.
  75718. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  75719. flushed to the output buffer and the output is aligned on a byte boundary, so
  75720. that the decompressor can get all input data available so far. (In particular
  75721. avail_in is zero after the call if enough output space has been provided
  75722. before the call.) Flushing may degrade compression for some compression
  75723. algorithms and so it should be used only when necessary.
  75724. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  75725. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  75726. restart from this point if previous compressed data has been damaged or if
  75727. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  75728. compression.
  75729. If deflate returns with avail_out == 0, this function must be called again
  75730. with the same value of the flush parameter and more output space (updated
  75731. avail_out), until the flush is complete (deflate returns with non-zero
  75732. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  75733. avail_out is greater than six to avoid repeated flush markers due to
  75734. avail_out == 0 on return.
  75735. If the parameter flush is set to Z_FINISH, pending input is processed,
  75736. pending output is flushed and deflate returns with Z_STREAM_END if there
  75737. was enough output space; if deflate returns with Z_OK, this function must be
  75738. called again with Z_FINISH and more output space (updated avail_out) but no
  75739. more input data, until it returns with Z_STREAM_END or an error. After
  75740. deflate has returned Z_STREAM_END, the only possible operations on the
  75741. stream are deflateReset or deflateEnd.
  75742. Z_FINISH can be used immediately after deflateInit if all the compression
  75743. is to be done in a single step. In this case, avail_out must be at least
  75744. the value returned by deflateBound (see below). If deflate does not return
  75745. Z_STREAM_END, then it must be called again as described above.
  75746. deflate() sets strm->adler to the adler32 checksum of all input read
  75747. so far (that is, total_in bytes).
  75748. deflate() may update strm->data_type if it can make a good guess about
  75749. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  75750. binary. This field is only for information purposes and does not affect
  75751. the compression algorithm in any manner.
  75752. deflate() returns Z_OK if some progress has been made (more input
  75753. processed or more output produced), Z_STREAM_END if all input has been
  75754. consumed and all output has been produced (only when flush is set to
  75755. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  75756. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  75757. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  75758. fatal, and deflate() can be called again with more input and more output
  75759. space to continue compressing.
  75760. */
  75761. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  75762. /*
  75763. All dynamically allocated data structures for this stream are freed.
  75764. This function discards any unprocessed input and does not flush any
  75765. pending output.
  75766. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  75767. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  75768. prematurely (some input or output was discarded). In the error case,
  75769. msg may be set but then points to a static string (which must not be
  75770. deallocated).
  75771. */
  75772. /*
  75773. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  75774. Initializes the internal stream state for decompression. The fields
  75775. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  75776. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  75777. value depends on the compression method), inflateInit determines the
  75778. compression method from the zlib header and allocates all data structures
  75779. accordingly; otherwise the allocation will be deferred to the first call of
  75780. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  75781. use default allocation functions.
  75782. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  75783. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  75784. version assumed by the caller. msg is set to null if there is no error
  75785. message. inflateInit does not perform any decompression apart from reading
  75786. the zlib header if present: this will be done by inflate(). (So next_in and
  75787. avail_in may be modified, but next_out and avail_out are unchanged.)
  75788. */
  75789. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  75790. /*
  75791. inflate decompresses as much data as possible, and stops when the input
  75792. buffer becomes empty or the output buffer becomes full. It may introduce
  75793. some output latency (reading input without producing any output) except when
  75794. forced to flush.
  75795. The detailed semantics are as follows. inflate performs one or both of the
  75796. following actions:
  75797. - Decompress more input starting at next_in and update next_in and avail_in
  75798. accordingly. If not all input can be processed (because there is not
  75799. enough room in the output buffer), next_in is updated and processing
  75800. will resume at this point for the next call of inflate().
  75801. - Provide more output starting at next_out and update next_out and avail_out
  75802. accordingly. inflate() provides as much output as possible, until there
  75803. is no more input data or no more space in the output buffer (see below
  75804. about the flush parameter).
  75805. Before the call of inflate(), the application should ensure that at least
  75806. one of the actions is possible, by providing more input and/or consuming
  75807. more output, and updating the next_* and avail_* values accordingly.
  75808. The application can consume the uncompressed output when it wants, for
  75809. example when the output buffer is full (avail_out == 0), or after each
  75810. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  75811. must be called again after making room in the output buffer because there
  75812. might be more output pending.
  75813. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  75814. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  75815. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  75816. if and when it gets to the next deflate block boundary. When decoding the
  75817. zlib or gzip format, this will cause inflate() to return immediately after
  75818. the header and before the first block. When doing a raw inflate, inflate()
  75819. will go ahead and process the first block, and will return when it gets to
  75820. the end of that block, or when it runs out of data.
  75821. The Z_BLOCK option assists in appending to or combining deflate streams.
  75822. Also to assist in this, on return inflate() will set strm->data_type to the
  75823. number of unused bits in the last byte taken from strm->next_in, plus 64
  75824. if inflate() is currently decoding the last block in the deflate stream,
  75825. plus 128 if inflate() returned immediately after decoding an end-of-block
  75826. code or decoding the complete header up to just before the first byte of the
  75827. deflate stream. The end-of-block will not be indicated until all of the
  75828. uncompressed data from that block has been written to strm->next_out. The
  75829. number of unused bits may in general be greater than seven, except when
  75830. bit 7 of data_type is set, in which case the number of unused bits will be
  75831. less than eight.
  75832. inflate() should normally be called until it returns Z_STREAM_END or an
  75833. error. However if all decompression is to be performed in a single step
  75834. (a single call of inflate), the parameter flush should be set to
  75835. Z_FINISH. In this case all pending input is processed and all pending
  75836. output is flushed; avail_out must be large enough to hold all the
  75837. uncompressed data. (The size of the uncompressed data may have been saved
  75838. by the compressor for this purpose.) The next operation on this stream must
  75839. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  75840. is never required, but can be used to inform inflate that a faster approach
  75841. may be used for the single inflate() call.
  75842. In this implementation, inflate() always flushes as much output as
  75843. possible to the output buffer, and always uses the faster approach on the
  75844. first call. So the only effect of the flush parameter in this implementation
  75845. is on the return value of inflate(), as noted below, or when it returns early
  75846. because Z_BLOCK is used.
  75847. If a preset dictionary is needed after this call (see inflateSetDictionary
  75848. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  75849. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  75850. strm->adler to the adler32 checksum of all output produced so far (that is,
  75851. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  75852. below. At the end of the stream, inflate() checks that its computed adler32
  75853. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  75854. only if the checksum is correct.
  75855. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  75856. deflate data. The header type is detected automatically. Any information
  75857. contained in the gzip header is not retained, so applications that need that
  75858. information should instead use raw inflate, see inflateInit2() below, or
  75859. inflateBack() and perform their own processing of the gzip header and
  75860. trailer.
  75861. inflate() returns Z_OK if some progress has been made (more input processed
  75862. or more output produced), Z_STREAM_END if the end of the compressed data has
  75863. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  75864. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  75865. corrupted (input stream not conforming to the zlib format or incorrect check
  75866. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  75867. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  75868. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  75869. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  75870. inflate() can be called again with more input and more output space to
  75871. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  75872. call inflateSync() to look for a good compression block if a partial recovery
  75873. of the data is desired.
  75874. */
  75875. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  75876. /*
  75877. All dynamically allocated data structures for this stream are freed.
  75878. This function discards any unprocessed input and does not flush any
  75879. pending output.
  75880. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  75881. was inconsistent. In the error case, msg may be set but then points to a
  75882. static string (which must not be deallocated).
  75883. */
  75884. /* Advanced functions */
  75885. /*
  75886. The following functions are needed only in some special applications.
  75887. */
  75888. /*
  75889. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  75890. int level,
  75891. int method,
  75892. int windowBits,
  75893. int memLevel,
  75894. int strategy));
  75895. This is another version of deflateInit with more compression options. The
  75896. fields next_in, zalloc, zfree and opaque must be initialized before by
  75897. the caller.
  75898. The method parameter is the compression method. It must be Z_DEFLATED in
  75899. this version of the library.
  75900. The windowBits parameter is the base two logarithm of the window size
  75901. (the size of the history buffer). It should be in the range 8..15 for this
  75902. version of the library. Larger values of this parameter result in better
  75903. compression at the expense of memory usage. The default value is 15 if
  75904. deflateInit is used instead.
  75905. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  75906. determines the window size. deflate() will then generate raw deflate data
  75907. with no zlib header or trailer, and will not compute an adler32 check value.
  75908. windowBits can also be greater than 15 for optional gzip encoding. Add
  75909. 16 to windowBits to write a simple gzip header and trailer around the
  75910. compressed data instead of a zlib wrapper. The gzip header will have no
  75911. file name, no extra data, no comment, no modification time (set to zero),
  75912. no header crc, and the operating system will be set to 255 (unknown). If a
  75913. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  75914. The memLevel parameter specifies how much memory should be allocated
  75915. for the internal compression state. memLevel=1 uses minimum memory but
  75916. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  75917. for optimal speed. The default value is 8. See zconf.h for total memory
  75918. usage as a function of windowBits and memLevel.
  75919. The strategy parameter is used to tune the compression algorithm. Use the
  75920. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  75921. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  75922. string match), or Z_RLE to limit match distances to one (run-length
  75923. encoding). Filtered data consists mostly of small values with a somewhat
  75924. random distribution. In this case, the compression algorithm is tuned to
  75925. compress them better. The effect of Z_FILTERED is to force more Huffman
  75926. coding and less string matching; it is somewhat intermediate between
  75927. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  75928. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  75929. parameter only affects the compression ratio but not the correctness of the
  75930. compressed output even if it is not set appropriately. Z_FIXED prevents the
  75931. use of dynamic Huffman codes, allowing for a simpler decoder for special
  75932. applications.
  75933. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  75934. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  75935. method). msg is set to null if there is no error message. deflateInit2 does
  75936. not perform any compression: this will be done by deflate().
  75937. */
  75938. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  75939. const Bytef *dictionary,
  75940. uInt dictLength));
  75941. /*
  75942. Initializes the compression dictionary from the given byte sequence
  75943. without producing any compressed output. This function must be called
  75944. immediately after deflateInit, deflateInit2 or deflateReset, before any
  75945. call of deflate. The compressor and decompressor must use exactly the same
  75946. dictionary (see inflateSetDictionary).
  75947. The dictionary should consist of strings (byte sequences) that are likely
  75948. to be encountered later in the data to be compressed, with the most commonly
  75949. used strings preferably put towards the end of the dictionary. Using a
  75950. dictionary is most useful when the data to be compressed is short and can be
  75951. predicted with good accuracy; the data can then be compressed better than
  75952. with the default empty dictionary.
  75953. Depending on the size of the compression data structures selected by
  75954. deflateInit or deflateInit2, a part of the dictionary may in effect be
  75955. discarded, for example if the dictionary is larger than the window size in
  75956. deflate or deflate2. Thus the strings most likely to be useful should be
  75957. put at the end of the dictionary, not at the front. In addition, the
  75958. current implementation of deflate will use at most the window size minus
  75959. 262 bytes of the provided dictionary.
  75960. Upon return of this function, strm->adler is set to the adler32 value
  75961. of the dictionary; the decompressor may later use this value to determine
  75962. which dictionary has been used by the compressor. (The adler32 value
  75963. applies to the whole dictionary even if only a subset of the dictionary is
  75964. actually used by the compressor.) If a raw deflate was requested, then the
  75965. adler32 value is not computed and strm->adler is not set.
  75966. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  75967. parameter is invalid (such as NULL dictionary) or the stream state is
  75968. inconsistent (for example if deflate has already been called for this stream
  75969. or if the compression method is bsort). deflateSetDictionary does not
  75970. perform any compression: this will be done by deflate().
  75971. */
  75972. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  75973. z_streamp source));
  75974. /*
  75975. Sets the destination stream as a complete copy of the source stream.
  75976. This function can be useful when several compression strategies will be
  75977. tried, for example when there are several ways of pre-processing the input
  75978. data with a filter. The streams that will be discarded should then be freed
  75979. by calling deflateEnd. Note that deflateCopy duplicates the internal
  75980. compression state which can be quite large, so this strategy is slow and
  75981. can consume lots of memory.
  75982. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  75983. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  75984. (such as zalloc being NULL). msg is left unchanged in both source and
  75985. destination.
  75986. */
  75987. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  75988. /*
  75989. This function is equivalent to deflateEnd followed by deflateInit,
  75990. but does not free and reallocate all the internal compression state.
  75991. The stream will keep the same compression level and any other attributes
  75992. that may have been set by deflateInit2.
  75993. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  75994. stream state was inconsistent (such as zalloc or state being NULL).
  75995. */
  75996. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  75997. int level,
  75998. int strategy));
  75999. /*
  76000. Dynamically update the compression level and compression strategy. The
  76001. interpretation of level and strategy is as in deflateInit2. This can be
  76002. used to switch between compression and straight copy of the input data, or
  76003. to switch to a different kind of input data requiring a different
  76004. strategy. If the compression level is changed, the input available so far
  76005. is compressed with the old level (and may be flushed); the new level will
  76006. take effect only at the next call of deflate().
  76007. Before the call of deflateParams, the stream state must be set as for
  76008. a call of deflate(), since the currently available input may have to
  76009. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  76010. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  76011. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  76012. if strm->avail_out was zero.
  76013. */
  76014. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  76015. int good_length,
  76016. int max_lazy,
  76017. int nice_length,
  76018. int max_chain));
  76019. /*
  76020. Fine tune deflate's internal compression parameters. This should only be
  76021. used by someone who understands the algorithm used by zlib's deflate for
  76022. searching for the best matching string, and even then only by the most
  76023. fanatic optimizer trying to squeeze out the last compressed bit for their
  76024. specific input data. Read the deflate.c source code for the meaning of the
  76025. max_lazy, good_length, nice_length, and max_chain parameters.
  76026. deflateTune() can be called after deflateInit() or deflateInit2(), and
  76027. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  76028. */
  76029. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  76030. uLong sourceLen));
  76031. /*
  76032. deflateBound() returns an upper bound on the compressed size after
  76033. deflation of sourceLen bytes. It must be called after deflateInit()
  76034. or deflateInit2(). This would be used to allocate an output buffer
  76035. for deflation in a single pass, and so would be called before deflate().
  76036. */
  76037. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  76038. int bits,
  76039. int value));
  76040. /*
  76041. deflatePrime() inserts bits in the deflate output stream. The intent
  76042. is that this function is used to start off the deflate output with the
  76043. bits leftover from a previous deflate stream when appending to it. As such,
  76044. this function can only be used for raw deflate, and must be used before the
  76045. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  76046. less than or equal to 16, and that many of the least significant bits of
  76047. value will be inserted in the output.
  76048. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  76049. stream state was inconsistent.
  76050. */
  76051. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  76052. gz_headerp head));
  76053. /*
  76054. deflateSetHeader() provides gzip header information for when a gzip
  76055. stream is requested by deflateInit2(). deflateSetHeader() may be called
  76056. after deflateInit2() or deflateReset() and before the first call of
  76057. deflate(). The text, time, os, extra field, name, and comment information
  76058. in the provided gz_header structure are written to the gzip header (xflag is
  76059. ignored -- the extra flags are set according to the compression level). The
  76060. caller must assure that, if not Z_NULL, name and comment are terminated with
  76061. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  76062. available there. If hcrc is true, a gzip header crc is included. Note that
  76063. the current versions of the command-line version of gzip (up through version
  76064. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  76065. gzip file" and give up.
  76066. If deflateSetHeader is not used, the default gzip header has text false,
  76067. the time set to zero, and os set to 255, with no extra, name, or comment
  76068. fields. The gzip header is returned to the default state by deflateReset().
  76069. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  76070. stream state was inconsistent.
  76071. */
  76072. /*
  76073. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  76074. int windowBits));
  76075. This is another version of inflateInit with an extra parameter. The
  76076. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  76077. before by the caller.
  76078. The windowBits parameter is the base two logarithm of the maximum window
  76079. size (the size of the history buffer). It should be in the range 8..15 for
  76080. this version of the library. The default value is 15 if inflateInit is used
  76081. instead. windowBits must be greater than or equal to the windowBits value
  76082. provided to deflateInit2() while compressing, or it must be equal to 15 if
  76083. deflateInit2() was not used. If a compressed stream with a larger window
  76084. size is given as input, inflate() will return with the error code
  76085. Z_DATA_ERROR instead of trying to allocate a larger window.
  76086. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  76087. determines the window size. inflate() will then process raw deflate data,
  76088. not looking for a zlib or gzip header, not generating a check value, and not
  76089. looking for any check values for comparison at the end of the stream. This
  76090. is for use with other formats that use the deflate compressed data format
  76091. such as zip. Those formats provide their own check values. If a custom
  76092. format is developed using the raw deflate format for compressed data, it is
  76093. recommended that a check value such as an adler32 or a crc32 be applied to
  76094. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  76095. most applications, the zlib format should be used as is. Note that comments
  76096. above on the use in deflateInit2() applies to the magnitude of windowBits.
  76097. windowBits can also be greater than 15 for optional gzip decoding. Add
  76098. 32 to windowBits to enable zlib and gzip decoding with automatic header
  76099. detection, or add 16 to decode only the gzip format (the zlib format will
  76100. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  76101. a crc32 instead of an adler32.
  76102. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  76103. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  76104. is set to null if there is no error message. inflateInit2 does not perform
  76105. any decompression apart from reading the zlib header if present: this will
  76106. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  76107. and avail_out are unchanged.)
  76108. */
  76109. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  76110. const Bytef *dictionary,
  76111. uInt dictLength));
  76112. /*
  76113. Initializes the decompression dictionary from the given uncompressed byte
  76114. sequence. This function must be called immediately after a call of inflate,
  76115. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  76116. can be determined from the adler32 value returned by that call of inflate.
  76117. The compressor and decompressor must use exactly the same dictionary (see
  76118. deflateSetDictionary). For raw inflate, this function can be called
  76119. immediately after inflateInit2() or inflateReset() and before any call of
  76120. inflate() to set the dictionary. The application must insure that the
  76121. dictionary that was used for compression is provided.
  76122. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  76123. parameter is invalid (such as NULL dictionary) or the stream state is
  76124. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  76125. expected one (incorrect adler32 value). inflateSetDictionary does not
  76126. perform any decompression: this will be done by subsequent calls of
  76127. inflate().
  76128. */
  76129. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  76130. /*
  76131. Skips invalid compressed data until a full flush point (see above the
  76132. description of deflate with Z_FULL_FLUSH) can be found, or until all
  76133. available input is skipped. No output is provided.
  76134. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  76135. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  76136. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  76137. case, the application may save the current current value of total_in which
  76138. indicates where valid compressed data was found. In the error case, the
  76139. application may repeatedly call inflateSync, providing more input each time,
  76140. until success or end of the input data.
  76141. */
  76142. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  76143. z_streamp source));
  76144. /*
  76145. Sets the destination stream as a complete copy of the source stream.
  76146. This function can be useful when randomly accessing a large stream. The
  76147. first pass through the stream can periodically record the inflate state,
  76148. allowing restarting inflate at those points when randomly accessing the
  76149. stream.
  76150. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  76151. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  76152. (such as zalloc being NULL). msg is left unchanged in both source and
  76153. destination.
  76154. */
  76155. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  76156. /*
  76157. This function is equivalent to inflateEnd followed by inflateInit,
  76158. but does not free and reallocate all the internal decompression state.
  76159. The stream will keep attributes that may have been set by inflateInit2.
  76160. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  76161. stream state was inconsistent (such as zalloc or state being NULL).
  76162. */
  76163. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  76164. int bits,
  76165. int value));
  76166. /*
  76167. This function inserts bits in the inflate input stream. The intent is
  76168. that this function is used to start inflating at a bit position in the
  76169. middle of a byte. The provided bits will be used before any bytes are used
  76170. from next_in. This function should only be used with raw inflate, and
  76171. should be used before the first inflate() call after inflateInit2() or
  76172. inflateReset(). bits must be less than or equal to 16, and that many of the
  76173. least significant bits of value will be inserted in the input.
  76174. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  76175. stream state was inconsistent.
  76176. */
  76177. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  76178. gz_headerp head));
  76179. /*
  76180. inflateGetHeader() requests that gzip header information be stored in the
  76181. provided gz_header structure. inflateGetHeader() may be called after
  76182. inflateInit2() or inflateReset(), and before the first call of inflate().
  76183. As inflate() processes the gzip stream, head->done is zero until the header
  76184. is completed, at which time head->done is set to one. If a zlib stream is
  76185. being decoded, then head->done is set to -1 to indicate that there will be
  76186. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  76187. force inflate() to return immediately after header processing is complete
  76188. and before any actual data is decompressed.
  76189. The text, time, xflags, and os fields are filled in with the gzip header
  76190. contents. hcrc is set to true if there is a header CRC. (The header CRC
  76191. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  76192. contains the maximum number of bytes to write to extra. Once done is true,
  76193. extra_len contains the actual extra field length, and extra contains the
  76194. extra field, or that field truncated if extra_max is less than extra_len.
  76195. If name is not Z_NULL, then up to name_max characters are written there,
  76196. terminated with a zero unless the length is greater than name_max. If
  76197. comment is not Z_NULL, then up to comm_max characters are written there,
  76198. terminated with a zero unless the length is greater than comm_max. When
  76199. any of extra, name, or comment are not Z_NULL and the respective field is
  76200. not present in the header, then that field is set to Z_NULL to signal its
  76201. absence. This allows the use of deflateSetHeader() with the returned
  76202. structure to duplicate the header. However if those fields are set to
  76203. allocated memory, then the application will need to save those pointers
  76204. elsewhere so that they can be eventually freed.
  76205. If inflateGetHeader is not used, then the header information is simply
  76206. discarded. The header is always checked for validity, including the header
  76207. CRC if present. inflateReset() will reset the process to discard the header
  76208. information. The application would need to call inflateGetHeader() again to
  76209. retrieve the header from the next gzip stream.
  76210. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  76211. stream state was inconsistent.
  76212. */
  76213. /*
  76214. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  76215. unsigned char FAR *window));
  76216. Initialize the internal stream state for decompression using inflateBack()
  76217. calls. The fields zalloc, zfree and opaque in strm must be initialized
  76218. before the call. If zalloc and zfree are Z_NULL, then the default library-
  76219. derived memory allocation routines are used. windowBits is the base two
  76220. logarithm of the window size, in the range 8..15. window is a caller
  76221. supplied buffer of that size. Except for special applications where it is
  76222. assured that deflate was used with small window sizes, windowBits must be 15
  76223. and a 32K byte window must be supplied to be able to decompress general
  76224. deflate streams.
  76225. See inflateBack() for the usage of these routines.
  76226. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  76227. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  76228. be allocated, or Z_VERSION_ERROR if the version of the library does not
  76229. match the version of the header file.
  76230. */
  76231. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  76232. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  76233. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  76234. in_func in, void FAR *in_desc,
  76235. out_func out, void FAR *out_desc));
  76236. /*
  76237. inflateBack() does a raw inflate with a single call using a call-back
  76238. interface for input and output. This is more efficient than inflate() for
  76239. file i/o applications in that it avoids copying between the output and the
  76240. sliding window by simply making the window itself the output buffer. This
  76241. function trusts the application to not change the output buffer passed by
  76242. the output function, at least until inflateBack() returns.
  76243. inflateBackInit() must be called first to allocate the internal state
  76244. and to initialize the state with the user-provided window buffer.
  76245. inflateBack() may then be used multiple times to inflate a complete, raw
  76246. deflate stream with each call. inflateBackEnd() is then called to free
  76247. the allocated state.
  76248. A raw deflate stream is one with no zlib or gzip header or trailer.
  76249. This routine would normally be used in a utility that reads zip or gzip
  76250. files and writes out uncompressed files. The utility would decode the
  76251. header and process the trailer on its own, hence this routine expects
  76252. only the raw deflate stream to decompress. This is different from the
  76253. normal behavior of inflate(), which expects either a zlib or gzip header and
  76254. trailer around the deflate stream.
  76255. inflateBack() uses two subroutines supplied by the caller that are then
  76256. called by inflateBack() for input and output. inflateBack() calls those
  76257. routines until it reads a complete deflate stream and writes out all of the
  76258. uncompressed data, or until it encounters an error. The function's
  76259. parameters and return types are defined above in the in_func and out_func
  76260. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  76261. number of bytes of provided input, and a pointer to that input in buf. If
  76262. there is no input available, in() must return zero--buf is ignored in that
  76263. case--and inflateBack() will return a buffer error. inflateBack() will call
  76264. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  76265. should return zero on success, or non-zero on failure. If out() returns
  76266. non-zero, inflateBack() will return with an error. Neither in() nor out()
  76267. are permitted to change the contents of the window provided to
  76268. inflateBackInit(), which is also the buffer that out() uses to write from.
  76269. The length written by out() will be at most the window size. Any non-zero
  76270. amount of input may be provided by in().
  76271. For convenience, inflateBack() can be provided input on the first call by
  76272. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  76273. in() will be called. Therefore strm->next_in must be initialized before
  76274. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  76275. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  76276. must also be initialized, and then if strm->avail_in is not zero, input will
  76277. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  76278. The in_desc and out_desc parameters of inflateBack() is passed as the
  76279. first parameter of in() and out() respectively when they are called. These
  76280. descriptors can be optionally used to pass any information that the caller-
  76281. supplied in() and out() functions need to do their job.
  76282. On return, inflateBack() will set strm->next_in and strm->avail_in to
  76283. pass back any unused input that was provided by the last in() call. The
  76284. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  76285. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  76286. error in the deflate stream (in which case strm->msg is set to indicate the
  76287. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  76288. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  76289. distinguished using strm->next_in which will be Z_NULL only if in() returned
  76290. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  76291. out() returning non-zero. (in() will always be called before out(), so
  76292. strm->next_in is assured to be defined if out() returns non-zero.) Note
  76293. that inflateBack() cannot return Z_OK.
  76294. */
  76295. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  76296. /*
  76297. All memory allocated by inflateBackInit() is freed.
  76298. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  76299. state was inconsistent.
  76300. */
  76301. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  76302. /* Return flags indicating compile-time options.
  76303. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  76304. 1.0: size of uInt
  76305. 3.2: size of uLong
  76306. 5.4: size of voidpf (pointer)
  76307. 7.6: size of z_off_t
  76308. Compiler, assembler, and debug options:
  76309. 8: DEBUG
  76310. 9: ASMV or ASMINF -- use ASM code
  76311. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  76312. 11: 0 (reserved)
  76313. One-time table building (smaller code, but not thread-safe if true):
  76314. 12: BUILDFIXED -- build static block decoding tables when needed
  76315. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  76316. 14,15: 0 (reserved)
  76317. Library content (indicates missing functionality):
  76318. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  76319. deflate code when not needed)
  76320. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  76321. and decode gzip streams (to avoid linking crc code)
  76322. 18-19: 0 (reserved)
  76323. Operation variations (changes in library functionality):
  76324. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  76325. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  76326. 22,23: 0 (reserved)
  76327. The sprintf variant used by gzprintf (zero is best):
  76328. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  76329. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  76330. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  76331. Remainder:
  76332. 27-31: 0 (reserved)
  76333. */
  76334. /* utility functions */
  76335. /*
  76336. The following utility functions are implemented on top of the
  76337. basic stream-oriented functions. To simplify the interface, some
  76338. default options are assumed (compression level and memory usage,
  76339. standard memory allocation functions). The source code of these
  76340. utility functions can easily be modified if you need special options.
  76341. */
  76342. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  76343. const Bytef *source, uLong sourceLen));
  76344. /*
  76345. Compresses the source buffer into the destination buffer. sourceLen is
  76346. the byte length of the source buffer. Upon entry, destLen is the total
  76347. size of the destination buffer, which must be at least the value returned
  76348. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  76349. compressed buffer.
  76350. This function can be used to compress a whole file at once if the
  76351. input file is mmap'ed.
  76352. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  76353. enough memory, Z_BUF_ERROR if there was not enough room in the output
  76354. buffer.
  76355. */
  76356. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  76357. const Bytef *source, uLong sourceLen,
  76358. int level));
  76359. /*
  76360. Compresses the source buffer into the destination buffer. The level
  76361. parameter has the same meaning as in deflateInit. sourceLen is the byte
  76362. length of the source buffer. Upon entry, destLen is the total size of the
  76363. destination buffer, which must be at least the value returned by
  76364. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  76365. compressed buffer.
  76366. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  76367. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  76368. Z_STREAM_ERROR if the level parameter is invalid.
  76369. */
  76370. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  76371. /*
  76372. compressBound() returns an upper bound on the compressed size after
  76373. compress() or compress2() on sourceLen bytes. It would be used before
  76374. a compress() or compress2() call to allocate the destination buffer.
  76375. */
  76376. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  76377. const Bytef *source, uLong sourceLen));
  76378. /*
  76379. Decompresses the source buffer into the destination buffer. sourceLen is
  76380. the byte length of the source buffer. Upon entry, destLen is the total
  76381. size of the destination buffer, which must be large enough to hold the
  76382. entire uncompressed data. (The size of the uncompressed data must have
  76383. been saved previously by the compressor and transmitted to the decompressor
  76384. by some mechanism outside the scope of this compression library.)
  76385. Upon exit, destLen is the actual size of the compressed buffer.
  76386. This function can be used to decompress a whole file at once if the
  76387. input file is mmap'ed.
  76388. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  76389. enough memory, Z_BUF_ERROR if there was not enough room in the output
  76390. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  76391. */
  76392. typedef voidp gzFile;
  76393. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  76394. /*
  76395. Opens a gzip (.gz) file for reading or writing. The mode parameter
  76396. is as in fopen ("rb" or "wb") but can also include a compression level
  76397. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  76398. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  76399. as in "wb1R". (See the description of deflateInit2 for more information
  76400. about the strategy parameter.)
  76401. gzopen can be used to read a file which is not in gzip format; in this
  76402. case gzread will directly read from the file without decompression.
  76403. gzopen returns NULL if the file could not be opened or if there was
  76404. insufficient memory to allocate the (de)compression state; errno
  76405. can be checked to distinguish the two cases (if errno is zero, the
  76406. zlib error is Z_MEM_ERROR). */
  76407. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  76408. /*
  76409. gzdopen() associates a gzFile with the file descriptor fd. File
  76410. descriptors are obtained from calls like open, dup, creat, pipe or
  76411. fileno (in the file has been previously opened with fopen).
  76412. The mode parameter is as in gzopen.
  76413. The next call of gzclose on the returned gzFile will also close the
  76414. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  76415. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  76416. gzdopen returns NULL if there was insufficient memory to allocate
  76417. the (de)compression state.
  76418. */
  76419. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  76420. /*
  76421. Dynamically update the compression level or strategy. See the description
  76422. of deflateInit2 for the meaning of these parameters.
  76423. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  76424. opened for writing.
  76425. */
  76426. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  76427. /*
  76428. Reads the given number of uncompressed bytes from the compressed file.
  76429. If the input file was not in gzip format, gzread copies the given number
  76430. of bytes into the buffer.
  76431. gzread returns the number of uncompressed bytes actually read (0 for
  76432. end of file, -1 for error). */
  76433. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  76434. voidpc buf, unsigned len));
  76435. /*
  76436. Writes the given number of uncompressed bytes into the compressed file.
  76437. gzwrite returns the number of uncompressed bytes actually written
  76438. (0 in case of error).
  76439. */
  76440. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  76441. /*
  76442. Converts, formats, and writes the args to the compressed file under
  76443. control of the format string, as in fprintf. gzprintf returns the number of
  76444. uncompressed bytes actually written (0 in case of error). The number of
  76445. uncompressed bytes written is limited to 4095. The caller should assure that
  76446. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  76447. return an error (0) with nothing written. In this case, there may also be a
  76448. buffer overflow with unpredictable consequences, which is possible only if
  76449. zlib was compiled with the insecure functions sprintf() or vsprintf()
  76450. because the secure snprintf() or vsnprintf() functions were not available.
  76451. */
  76452. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  76453. /*
  76454. Writes the given null-terminated string to the compressed file, excluding
  76455. the terminating null character.
  76456. gzputs returns the number of characters written, or -1 in case of error.
  76457. */
  76458. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  76459. /*
  76460. Reads bytes from the compressed file until len-1 characters are read, or
  76461. a newline character is read and transferred to buf, or an end-of-file
  76462. condition is encountered. The string is then terminated with a null
  76463. character.
  76464. gzgets returns buf, or Z_NULL in case of error.
  76465. */
  76466. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  76467. /*
  76468. Writes c, converted to an unsigned char, into the compressed file.
  76469. gzputc returns the value that was written, or -1 in case of error.
  76470. */
  76471. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  76472. /*
  76473. Reads one byte from the compressed file. gzgetc returns this byte
  76474. or -1 in case of end of file or error.
  76475. */
  76476. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  76477. /*
  76478. Push one character back onto the stream to be read again later.
  76479. Only one character of push-back is allowed. gzungetc() returns the
  76480. character pushed, or -1 on failure. gzungetc() will fail if a
  76481. character has been pushed but not read yet, or if c is -1. The pushed
  76482. character will be discarded if the stream is repositioned with gzseek()
  76483. or gzrewind().
  76484. */
  76485. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  76486. /*
  76487. Flushes all pending output into the compressed file. The parameter
  76488. flush is as in the deflate() function. The return value is the zlib
  76489. error number (see function gzerror below). gzflush returns Z_OK if
  76490. the flush parameter is Z_FINISH and all output could be flushed.
  76491. gzflush should be called only when strictly necessary because it can
  76492. degrade compression.
  76493. */
  76494. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  76495. z_off_t offset, int whence));
  76496. /*
  76497. Sets the starting position for the next gzread or gzwrite on the
  76498. given compressed file. The offset represents a number of bytes in the
  76499. uncompressed data stream. The whence parameter is defined as in lseek(2);
  76500. the value SEEK_END is not supported.
  76501. If the file is opened for reading, this function is emulated but can be
  76502. extremely slow. If the file is opened for writing, only forward seeks are
  76503. supported; gzseek then compresses a sequence of zeroes up to the new
  76504. starting position.
  76505. gzseek returns the resulting offset location as measured in bytes from
  76506. the beginning of the uncompressed stream, or -1 in case of error, in
  76507. particular if the file is opened for writing and the new starting position
  76508. would be before the current position.
  76509. */
  76510. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  76511. /*
  76512. Rewinds the given file. This function is supported only for reading.
  76513. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  76514. */
  76515. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  76516. /*
  76517. Returns the starting position for the next gzread or gzwrite on the
  76518. given compressed file. This position represents a number of bytes in the
  76519. uncompressed data stream.
  76520. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  76521. */
  76522. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  76523. /*
  76524. Returns 1 when EOF has previously been detected reading the given
  76525. input stream, otherwise zero.
  76526. */
  76527. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  76528. /*
  76529. Returns 1 if file is being read directly without decompression, otherwise
  76530. zero.
  76531. */
  76532. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  76533. /*
  76534. Flushes all pending output if necessary, closes the compressed file
  76535. and deallocates all the (de)compression state. The return value is the zlib
  76536. error number (see function gzerror below).
  76537. */
  76538. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  76539. /*
  76540. Returns the error message for the last error which occurred on the
  76541. given compressed file. errnum is set to zlib error number. If an
  76542. error occurred in the file system and not in the compression library,
  76543. errnum is set to Z_ERRNO and the application may consult errno
  76544. to get the exact error code.
  76545. */
  76546. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  76547. /*
  76548. Clears the error and end-of-file flags for file. This is analogous to the
  76549. clearerr() function in stdio. This is useful for continuing to read a gzip
  76550. file that is being written concurrently.
  76551. */
  76552. /* checksum functions */
  76553. /*
  76554. These functions are not related to compression but are exported
  76555. anyway because they might be useful in applications using the
  76556. compression library.
  76557. */
  76558. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  76559. /*
  76560. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  76561. return the updated checksum. If buf is NULL, this function returns
  76562. the required initial value for the checksum.
  76563. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  76564. much faster. Usage example:
  76565. uLong adler = adler32(0L, Z_NULL, 0);
  76566. while (read_buffer(buffer, length) != EOF) {
  76567. adler = adler32(adler, buffer, length);
  76568. }
  76569. if (adler != original_adler) error();
  76570. */
  76571. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  76572. z_off_t len2));
  76573. /*
  76574. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  76575. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  76576. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  76577. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  76578. */
  76579. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  76580. /*
  76581. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  76582. updated CRC-32. If buf is NULL, this function returns the required initial
  76583. value for the for the crc. Pre- and post-conditioning (one's complement) is
  76584. performed within this function so it shouldn't be done by the application.
  76585. Usage example:
  76586. uLong crc = crc32(0L, Z_NULL, 0);
  76587. while (read_buffer(buffer, length) != EOF) {
  76588. crc = crc32(crc, buffer, length);
  76589. }
  76590. if (crc != original_crc) error();
  76591. */
  76592. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  76593. /*
  76594. Combine two CRC-32 check values into one. For two sequences of bytes,
  76595. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  76596. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  76597. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  76598. len2.
  76599. */
  76600. /* various hacks, don't look :) */
  76601. /* deflateInit and inflateInit are macros to allow checking the zlib version
  76602. * and the compiler's view of z_stream:
  76603. */
  76604. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  76605. const char *version, int stream_size));
  76606. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  76607. const char *version, int stream_size));
  76608. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  76609. int windowBits, int memLevel,
  76610. int strategy, const char *version,
  76611. int stream_size));
  76612. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  76613. const char *version, int stream_size));
  76614. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  76615. unsigned char FAR *window,
  76616. const char *version,
  76617. int stream_size));
  76618. #define deflateInit(strm, level) \
  76619. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  76620. #define inflateInit(strm) \
  76621. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  76622. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  76623. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  76624. (strategy), ZLIB_VERSION, sizeof(z_stream))
  76625. #define inflateInit2(strm, windowBits) \
  76626. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  76627. #define inflateBackInit(strm, windowBits, window) \
  76628. inflateBackInit_((strm), (windowBits), (window), \
  76629. ZLIB_VERSION, sizeof(z_stream))
  76630. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  76631. struct internal_state {int dummy;}; /* hack for buggy compilers */
  76632. #endif
  76633. ZEXTERN const char * ZEXPORT zError OF((int));
  76634. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  76635. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  76636. #ifdef __cplusplus
  76637. }
  76638. #endif
  76639. #endif /* ZLIB_H */
  76640. /*** End of inlined file: zlib.h ***/
  76641. #undef OS_CODE
  76642. #else
  76643. #include <zlib.h>
  76644. #endif
  76645. }
  76646. BEGIN_JUCE_NAMESPACE
  76647. // internal helper object that holds the zlib structures so they don't have to be
  76648. // included publicly.
  76649. class GZIPCompressorHelper
  76650. {
  76651. public:
  76652. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  76653. : data (0),
  76654. dataSize (0),
  76655. compLevel (compressionLevel),
  76656. strategy (0),
  76657. setParams (true),
  76658. streamIsValid (false),
  76659. finished (false),
  76660. shouldFinish (false)
  76661. {
  76662. using namespace zlibNamespace;
  76663. zerostruct (stream);
  76664. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  76665. nowrap ? -MAX_WBITS : MAX_WBITS,
  76666. 8, strategy) == Z_OK);
  76667. }
  76668. ~GZIPCompressorHelper()
  76669. {
  76670. using namespace zlibNamespace;
  76671. if (streamIsValid)
  76672. deflateEnd (&stream);
  76673. }
  76674. bool needsInput() const throw()
  76675. {
  76676. return dataSize <= 0;
  76677. }
  76678. void setInput (const uint8* const newData, const int size) throw()
  76679. {
  76680. data = newData;
  76681. dataSize = size;
  76682. }
  76683. int doNextBlock (uint8* const dest, const int destSize) throw()
  76684. {
  76685. using namespace zlibNamespace;
  76686. if (streamIsValid)
  76687. {
  76688. stream.next_in = const_cast <uint8*> (data);
  76689. stream.next_out = dest;
  76690. stream.avail_in = dataSize;
  76691. stream.avail_out = destSize;
  76692. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  76693. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  76694. setParams = false;
  76695. switch (result)
  76696. {
  76697. case Z_STREAM_END:
  76698. finished = true;
  76699. // Deliberate fall-through..
  76700. case Z_OK:
  76701. data += dataSize - stream.avail_in;
  76702. dataSize = stream.avail_in;
  76703. return destSize - stream.avail_out;
  76704. default:
  76705. break;
  76706. }
  76707. }
  76708. return 0;
  76709. }
  76710. private:
  76711. zlibNamespace::z_stream stream;
  76712. const uint8* data;
  76713. int dataSize, compLevel, strategy;
  76714. bool setParams, streamIsValid;
  76715. public:
  76716. bool finished, shouldFinish;
  76717. };
  76718. const int gzipCompBufferSize = 32768;
  76719. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  76720. int compressionLevel,
  76721. const bool deleteDestStream,
  76722. const bool noWrap)
  76723. : destStream (destStream_),
  76724. streamToDelete (deleteDestStream ? destStream_ : 0),
  76725. buffer (gzipCompBufferSize)
  76726. {
  76727. if (compressionLevel < 1 || compressionLevel > 9)
  76728. compressionLevel = -1;
  76729. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  76730. }
  76731. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  76732. {
  76733. flush();
  76734. }
  76735. void GZIPCompressorOutputStream::flush()
  76736. {
  76737. if (! helper->finished)
  76738. {
  76739. helper->shouldFinish = true;
  76740. while (! helper->finished)
  76741. doNextBlock();
  76742. }
  76743. destStream->flush();
  76744. }
  76745. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  76746. {
  76747. if (! helper->finished)
  76748. {
  76749. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  76750. while (! helper->needsInput())
  76751. {
  76752. if (! doNextBlock())
  76753. return false;
  76754. }
  76755. }
  76756. return true;
  76757. }
  76758. bool GZIPCompressorOutputStream::doNextBlock()
  76759. {
  76760. const int len = helper->doNextBlock (buffer, gzipCompBufferSize);
  76761. if (len > 0)
  76762. return destStream->write (buffer, len);
  76763. else
  76764. return true;
  76765. }
  76766. int64 GZIPCompressorOutputStream::getPosition()
  76767. {
  76768. return destStream->getPosition();
  76769. }
  76770. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  76771. {
  76772. jassertfalse // can't do it!
  76773. return false;
  76774. }
  76775. END_JUCE_NAMESPACE
  76776. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  76777. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  76778. #if JUCE_MSVC
  76779. #pragma warning (push)
  76780. #pragma warning (disable: 4309 4305)
  76781. #endif
  76782. namespace zlibNamespace
  76783. {
  76784. #if JUCE_INCLUDE_ZLIB_CODE
  76785. extern "C"
  76786. {
  76787. #undef OS_CODE
  76788. #undef fdopen
  76789. #define ZLIB_INTERNAL
  76790. #define NO_DUMMY_DECL
  76791. /*** Start of inlined file: adler32.c ***/
  76792. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  76793. #define ZLIB_INTERNAL
  76794. #define BASE 65521UL /* largest prime smaller than 65536 */
  76795. #define NMAX 5552
  76796. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  76797. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  76798. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  76799. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  76800. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  76801. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  76802. /* use NO_DIVIDE if your processor does not do division in hardware */
  76803. #ifdef NO_DIVIDE
  76804. # define MOD(a) \
  76805. do { \
  76806. if (a >= (BASE << 16)) a -= (BASE << 16); \
  76807. if (a >= (BASE << 15)) a -= (BASE << 15); \
  76808. if (a >= (BASE << 14)) a -= (BASE << 14); \
  76809. if (a >= (BASE << 13)) a -= (BASE << 13); \
  76810. if (a >= (BASE << 12)) a -= (BASE << 12); \
  76811. if (a >= (BASE << 11)) a -= (BASE << 11); \
  76812. if (a >= (BASE << 10)) a -= (BASE << 10); \
  76813. if (a >= (BASE << 9)) a -= (BASE << 9); \
  76814. if (a >= (BASE << 8)) a -= (BASE << 8); \
  76815. if (a >= (BASE << 7)) a -= (BASE << 7); \
  76816. if (a >= (BASE << 6)) a -= (BASE << 6); \
  76817. if (a >= (BASE << 5)) a -= (BASE << 5); \
  76818. if (a >= (BASE << 4)) a -= (BASE << 4); \
  76819. if (a >= (BASE << 3)) a -= (BASE << 3); \
  76820. if (a >= (BASE << 2)) a -= (BASE << 2); \
  76821. if (a >= (BASE << 1)) a -= (BASE << 1); \
  76822. if (a >= BASE) a -= BASE; \
  76823. } while (0)
  76824. # define MOD4(a) \
  76825. do { \
  76826. if (a >= (BASE << 4)) a -= (BASE << 4); \
  76827. if (a >= (BASE << 3)) a -= (BASE << 3); \
  76828. if (a >= (BASE << 2)) a -= (BASE << 2); \
  76829. if (a >= (BASE << 1)) a -= (BASE << 1); \
  76830. if (a >= BASE) a -= BASE; \
  76831. } while (0)
  76832. #else
  76833. # define MOD(a) a %= BASE
  76834. # define MOD4(a) a %= BASE
  76835. #endif
  76836. /* ========================================================================= */
  76837. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  76838. {
  76839. unsigned long sum2;
  76840. unsigned n;
  76841. /* split Adler-32 into component sums */
  76842. sum2 = (adler >> 16) & 0xffff;
  76843. adler &= 0xffff;
  76844. /* in case user likes doing a byte at a time, keep it fast */
  76845. if (len == 1) {
  76846. adler += buf[0];
  76847. if (adler >= BASE)
  76848. adler -= BASE;
  76849. sum2 += adler;
  76850. if (sum2 >= BASE)
  76851. sum2 -= BASE;
  76852. return adler | (sum2 << 16);
  76853. }
  76854. /* initial Adler-32 value (deferred check for len == 1 speed) */
  76855. if (buf == Z_NULL)
  76856. return 1L;
  76857. /* in case short lengths are provided, keep it somewhat fast */
  76858. if (len < 16) {
  76859. while (len--) {
  76860. adler += *buf++;
  76861. sum2 += adler;
  76862. }
  76863. if (adler >= BASE)
  76864. adler -= BASE;
  76865. MOD4(sum2); /* only added so many BASE's */
  76866. return adler | (sum2 << 16);
  76867. }
  76868. /* do length NMAX blocks -- requires just one modulo operation */
  76869. while (len >= NMAX) {
  76870. len -= NMAX;
  76871. n = NMAX / 16; /* NMAX is divisible by 16 */
  76872. do {
  76873. DO16(buf); /* 16 sums unrolled */
  76874. buf += 16;
  76875. } while (--n);
  76876. MOD(adler);
  76877. MOD(sum2);
  76878. }
  76879. /* do remaining bytes (less than NMAX, still just one modulo) */
  76880. if (len) { /* avoid modulos if none remaining */
  76881. while (len >= 16) {
  76882. len -= 16;
  76883. DO16(buf);
  76884. buf += 16;
  76885. }
  76886. while (len--) {
  76887. adler += *buf++;
  76888. sum2 += adler;
  76889. }
  76890. MOD(adler);
  76891. MOD(sum2);
  76892. }
  76893. /* return recombined sums */
  76894. return adler | (sum2 << 16);
  76895. }
  76896. /* ========================================================================= */
  76897. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  76898. {
  76899. unsigned long sum1;
  76900. unsigned long sum2;
  76901. unsigned rem;
  76902. /* the derivation of this formula is left as an exercise for the reader */
  76903. rem = (unsigned)(len2 % BASE);
  76904. sum1 = adler1 & 0xffff;
  76905. sum2 = rem * sum1;
  76906. MOD(sum2);
  76907. sum1 += (adler2 & 0xffff) + BASE - 1;
  76908. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  76909. if (sum1 > BASE) sum1 -= BASE;
  76910. if (sum1 > BASE) sum1 -= BASE;
  76911. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  76912. if (sum2 > BASE) sum2 -= BASE;
  76913. return sum1 | (sum2 << 16);
  76914. }
  76915. /*** End of inlined file: adler32.c ***/
  76916. /*** Start of inlined file: compress.c ***/
  76917. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  76918. #define ZLIB_INTERNAL
  76919. /* ===========================================================================
  76920. Compresses the source buffer into the destination buffer. The level
  76921. parameter has the same meaning as in deflateInit. sourceLen is the byte
  76922. length of the source buffer. Upon entry, destLen is the total size of the
  76923. destination buffer, which must be at least 0.1% larger than sourceLen plus
  76924. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  76925. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  76926. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  76927. Z_STREAM_ERROR if the level parameter is invalid.
  76928. */
  76929. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  76930. uLong sourceLen, int level)
  76931. {
  76932. z_stream stream;
  76933. int err;
  76934. stream.next_in = (Bytef*)source;
  76935. stream.avail_in = (uInt)sourceLen;
  76936. #ifdef MAXSEG_64K
  76937. /* Check for source > 64K on 16-bit machine: */
  76938. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  76939. #endif
  76940. stream.next_out = dest;
  76941. stream.avail_out = (uInt)*destLen;
  76942. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  76943. stream.zalloc = (alloc_func)0;
  76944. stream.zfree = (free_func)0;
  76945. stream.opaque = (voidpf)0;
  76946. err = deflateInit(&stream, level);
  76947. if (err != Z_OK) return err;
  76948. err = deflate(&stream, Z_FINISH);
  76949. if (err != Z_STREAM_END) {
  76950. deflateEnd(&stream);
  76951. return err == Z_OK ? Z_BUF_ERROR : err;
  76952. }
  76953. *destLen = stream.total_out;
  76954. err = deflateEnd(&stream);
  76955. return err;
  76956. }
  76957. /* ===========================================================================
  76958. */
  76959. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  76960. {
  76961. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  76962. }
  76963. /* ===========================================================================
  76964. If the default memLevel or windowBits for deflateInit() is changed, then
  76965. this function needs to be updated.
  76966. */
  76967. uLong ZEXPORT compressBound (uLong sourceLen)
  76968. {
  76969. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  76970. }
  76971. /*** End of inlined file: compress.c ***/
  76972. #undef DO1
  76973. #undef DO8
  76974. /*** Start of inlined file: crc32.c ***/
  76975. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  76976. /*
  76977. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  76978. protection on the static variables used to control the first-use generation
  76979. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  76980. first call get_crc_table() to initialize the tables before allowing more than
  76981. one thread to use crc32().
  76982. */
  76983. #ifdef MAKECRCH
  76984. # include <stdio.h>
  76985. # ifndef DYNAMIC_CRC_TABLE
  76986. # define DYNAMIC_CRC_TABLE
  76987. # endif /* !DYNAMIC_CRC_TABLE */
  76988. #endif /* MAKECRCH */
  76989. /*** Start of inlined file: zutil.h ***/
  76990. /* WARNING: this file should *not* be used by applications. It is
  76991. part of the implementation of the compression library and is
  76992. subject to change. Applications should only use zlib.h.
  76993. */
  76994. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  76995. #ifndef ZUTIL_H
  76996. #define ZUTIL_H
  76997. #define ZLIB_INTERNAL
  76998. #ifdef STDC
  76999. # ifndef _WIN32_WCE
  77000. # include <stddef.h>
  77001. # endif
  77002. # include <string.h>
  77003. # include <stdlib.h>
  77004. #endif
  77005. #ifdef NO_ERRNO_H
  77006. # ifdef _WIN32_WCE
  77007. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  77008. * errno. We define it as a global variable to simplify porting.
  77009. * Its value is always 0 and should not be used. We rename it to
  77010. * avoid conflict with other libraries that use the same workaround.
  77011. */
  77012. # define errno z_errno
  77013. # endif
  77014. extern int errno;
  77015. #else
  77016. # ifndef _WIN32_WCE
  77017. # include <errno.h>
  77018. # endif
  77019. #endif
  77020. #ifndef local
  77021. # define local static
  77022. #endif
  77023. /* compile with -Dlocal if your debugger can't find static symbols */
  77024. typedef unsigned char uch;
  77025. typedef uch FAR uchf;
  77026. typedef unsigned short ush;
  77027. typedef ush FAR ushf;
  77028. typedef unsigned long ulg;
  77029. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  77030. /* (size given to avoid silly warnings with Visual C++) */
  77031. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  77032. #define ERR_RETURN(strm,err) \
  77033. return (strm->msg = (char*)ERR_MSG(err), (err))
  77034. /* To be used only when the state is known to be valid */
  77035. /* common constants */
  77036. #ifndef DEF_WBITS
  77037. # define DEF_WBITS MAX_WBITS
  77038. #endif
  77039. /* default windowBits for decompression. MAX_WBITS is for compression only */
  77040. #if MAX_MEM_LEVEL >= 8
  77041. # define DEF_MEM_LEVEL 8
  77042. #else
  77043. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  77044. #endif
  77045. /* default memLevel */
  77046. #define STORED_BLOCK 0
  77047. #define STATIC_TREES 1
  77048. #define DYN_TREES 2
  77049. /* The three kinds of block type */
  77050. #define MIN_MATCH 3
  77051. #define MAX_MATCH 258
  77052. /* The minimum and maximum match lengths */
  77053. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  77054. /* target dependencies */
  77055. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  77056. # define OS_CODE 0x00
  77057. # if defined(__TURBOC__) || defined(__BORLANDC__)
  77058. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  77059. /* Allow compilation with ANSI keywords only enabled */
  77060. void _Cdecl farfree( void *block );
  77061. void *_Cdecl farmalloc( unsigned long nbytes );
  77062. # else
  77063. # include <alloc.h>
  77064. # endif
  77065. # else /* MSC or DJGPP */
  77066. # include <malloc.h>
  77067. # endif
  77068. #endif
  77069. #ifdef AMIGA
  77070. # define OS_CODE 0x01
  77071. #endif
  77072. #if defined(VAXC) || defined(VMS)
  77073. # define OS_CODE 0x02
  77074. # define F_OPEN(name, mode) \
  77075. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  77076. #endif
  77077. #if defined(ATARI) || defined(atarist)
  77078. # define OS_CODE 0x05
  77079. #endif
  77080. #ifdef OS2
  77081. # define OS_CODE 0x06
  77082. # ifdef M_I86
  77083. #include <malloc.h>
  77084. # endif
  77085. #endif
  77086. #if defined(MACOS) || TARGET_OS_MAC
  77087. # define OS_CODE 0x07
  77088. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  77089. # include <unix.h> /* for fdopen */
  77090. # else
  77091. # ifndef fdopen
  77092. # define fdopen(fd,mode) NULL /* No fdopen() */
  77093. # endif
  77094. # endif
  77095. #endif
  77096. #ifdef TOPS20
  77097. # define OS_CODE 0x0a
  77098. #endif
  77099. #ifdef WIN32
  77100. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  77101. # define OS_CODE 0x0b
  77102. # endif
  77103. #endif
  77104. #ifdef __50SERIES /* Prime/PRIMOS */
  77105. # define OS_CODE 0x0f
  77106. #endif
  77107. #if defined(_BEOS_) || defined(RISCOS)
  77108. # define fdopen(fd,mode) NULL /* No fdopen() */
  77109. #endif
  77110. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  77111. # if defined(_WIN32_WCE)
  77112. # define fdopen(fd,mode) NULL /* No fdopen() */
  77113. # ifndef _PTRDIFF_T_DEFINED
  77114. typedef int ptrdiff_t;
  77115. # define _PTRDIFF_T_DEFINED
  77116. # endif
  77117. # else
  77118. # define fdopen(fd,type) _fdopen(fd,type)
  77119. # endif
  77120. #endif
  77121. /* common defaults */
  77122. #ifndef OS_CODE
  77123. # define OS_CODE 0x03 /* assume Unix */
  77124. #endif
  77125. #ifndef F_OPEN
  77126. # define F_OPEN(name, mode) fopen((name), (mode))
  77127. #endif
  77128. /* functions */
  77129. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  77130. # ifndef HAVE_VSNPRINTF
  77131. # define HAVE_VSNPRINTF
  77132. # endif
  77133. #endif
  77134. #if defined(__CYGWIN__)
  77135. # ifndef HAVE_VSNPRINTF
  77136. # define HAVE_VSNPRINTF
  77137. # endif
  77138. #endif
  77139. #ifndef HAVE_VSNPRINTF
  77140. # ifdef MSDOS
  77141. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  77142. but for now we just assume it doesn't. */
  77143. # define NO_vsnprintf
  77144. # endif
  77145. # ifdef __TURBOC__
  77146. # define NO_vsnprintf
  77147. # endif
  77148. # ifdef WIN32
  77149. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  77150. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  77151. # define vsnprintf _vsnprintf
  77152. # endif
  77153. # endif
  77154. # ifdef __SASC
  77155. # define NO_vsnprintf
  77156. # endif
  77157. #endif
  77158. #ifdef VMS
  77159. # define NO_vsnprintf
  77160. #endif
  77161. #if defined(pyr)
  77162. # define NO_MEMCPY
  77163. #endif
  77164. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  77165. /* Use our own functions for small and medium model with MSC <= 5.0.
  77166. * You may have to use the same strategy for Borland C (untested).
  77167. * The __SC__ check is for Symantec.
  77168. */
  77169. # define NO_MEMCPY
  77170. #endif
  77171. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  77172. # define HAVE_MEMCPY
  77173. #endif
  77174. #ifdef HAVE_MEMCPY
  77175. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  77176. # define zmemcpy _fmemcpy
  77177. # define zmemcmp _fmemcmp
  77178. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  77179. # else
  77180. # define zmemcpy memcpy
  77181. # define zmemcmp memcmp
  77182. # define zmemzero(dest, len) memset(dest, 0, len)
  77183. # endif
  77184. #else
  77185. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  77186. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  77187. extern void zmemzero OF((Bytef* dest, uInt len));
  77188. #endif
  77189. /* Diagnostic functions */
  77190. #ifdef DEBUG
  77191. # include <stdio.h>
  77192. extern int z_verbose;
  77193. extern void z_error OF((const char *m));
  77194. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  77195. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  77196. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  77197. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  77198. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  77199. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  77200. #else
  77201. # define Assert(cond,msg)
  77202. # define Trace(x)
  77203. # define Tracev(x)
  77204. # define Tracevv(x)
  77205. # define Tracec(c,x)
  77206. # define Tracecv(c,x)
  77207. #endif
  77208. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  77209. void zcfree OF((voidpf opaque, voidpf ptr));
  77210. #define ZALLOC(strm, items, size) \
  77211. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  77212. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  77213. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  77214. #endif /* ZUTIL_H */
  77215. /*** End of inlined file: zutil.h ***/
  77216. /* for STDC and FAR definitions */
  77217. #define local static
  77218. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  77219. #ifndef NOBYFOUR
  77220. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  77221. # include <limits.h>
  77222. # define BYFOUR
  77223. # if (UINT_MAX == 0xffffffffUL)
  77224. typedef unsigned int u4;
  77225. # else
  77226. # if (ULONG_MAX == 0xffffffffUL)
  77227. typedef unsigned long u4;
  77228. # else
  77229. # if (USHRT_MAX == 0xffffffffUL)
  77230. typedef unsigned short u4;
  77231. # else
  77232. # undef BYFOUR /* can't find a four-byte integer type! */
  77233. # endif
  77234. # endif
  77235. # endif
  77236. # endif /* STDC */
  77237. #endif /* !NOBYFOUR */
  77238. /* Definitions for doing the crc four data bytes at a time. */
  77239. #ifdef BYFOUR
  77240. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  77241. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  77242. local unsigned long crc32_little OF((unsigned long,
  77243. const unsigned char FAR *, unsigned));
  77244. local unsigned long crc32_big OF((unsigned long,
  77245. const unsigned char FAR *, unsigned));
  77246. # define TBLS 8
  77247. #else
  77248. # define TBLS 1
  77249. #endif /* BYFOUR */
  77250. /* Local functions for crc concatenation */
  77251. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  77252. unsigned long vec));
  77253. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  77254. #ifdef DYNAMIC_CRC_TABLE
  77255. local volatile int crc_table_empty = 1;
  77256. local unsigned long FAR crc_table[TBLS][256];
  77257. local void make_crc_table OF((void));
  77258. #ifdef MAKECRCH
  77259. local void write_table OF((FILE *, const unsigned long FAR *));
  77260. #endif /* MAKECRCH */
  77261. /*
  77262. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  77263. 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.
  77264. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  77265. with the lowest powers in the most significant bit. Then adding polynomials
  77266. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  77267. one. If we call the above polynomial p, and represent a byte as the
  77268. polynomial q, also with the lowest power in the most significant bit (so the
  77269. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  77270. where a mod b means the remainder after dividing a by b.
  77271. This calculation is done using the shift-register method of multiplying and
  77272. taking the remainder. The register is initialized to zero, and for each
  77273. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  77274. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  77275. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  77276. out is a one). We start with the highest power (least significant bit) of
  77277. q and repeat for all eight bits of q.
  77278. The first table is simply the CRC of all possible eight bit values. This is
  77279. all the information needed to generate CRCs on data a byte at a time for all
  77280. combinations of CRC register values and incoming bytes. The remaining tables
  77281. allow for word-at-a-time CRC calculation for both big-endian and little-
  77282. endian machines, where a word is four bytes.
  77283. */
  77284. local void make_crc_table()
  77285. {
  77286. unsigned long c;
  77287. int n, k;
  77288. unsigned long poly; /* polynomial exclusive-or pattern */
  77289. /* terms of polynomial defining this crc (except x^32): */
  77290. static volatile int first = 1; /* flag to limit concurrent making */
  77291. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  77292. /* See if another task is already doing this (not thread-safe, but better
  77293. than nothing -- significantly reduces duration of vulnerability in
  77294. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  77295. if (first) {
  77296. first = 0;
  77297. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  77298. poly = 0UL;
  77299. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  77300. poly |= 1UL << (31 - p[n]);
  77301. /* generate a crc for every 8-bit value */
  77302. for (n = 0; n < 256; n++) {
  77303. c = (unsigned long)n;
  77304. for (k = 0; k < 8; k++)
  77305. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  77306. crc_table[0][n] = c;
  77307. }
  77308. #ifdef BYFOUR
  77309. /* generate crc for each value followed by one, two, and three zeros,
  77310. and then the byte reversal of those as well as the first table */
  77311. for (n = 0; n < 256; n++) {
  77312. c = crc_table[0][n];
  77313. crc_table[4][n] = REV(c);
  77314. for (k = 1; k < 4; k++) {
  77315. c = crc_table[0][c & 0xff] ^ (c >> 8);
  77316. crc_table[k][n] = c;
  77317. crc_table[k + 4][n] = REV(c);
  77318. }
  77319. }
  77320. #endif /* BYFOUR */
  77321. crc_table_empty = 0;
  77322. }
  77323. else { /* not first */
  77324. /* wait for the other guy to finish (not efficient, but rare) */
  77325. while (crc_table_empty)
  77326. ;
  77327. }
  77328. #ifdef MAKECRCH
  77329. /* write out CRC tables to crc32.h */
  77330. {
  77331. FILE *out;
  77332. out = fopen("crc32.h", "w");
  77333. if (out == NULL) return;
  77334. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  77335. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  77336. fprintf(out, "local const unsigned long FAR ");
  77337. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  77338. write_table(out, crc_table[0]);
  77339. # ifdef BYFOUR
  77340. fprintf(out, "#ifdef BYFOUR\n");
  77341. for (k = 1; k < 8; k++) {
  77342. fprintf(out, " },\n {\n");
  77343. write_table(out, crc_table[k]);
  77344. }
  77345. fprintf(out, "#endif\n");
  77346. # endif /* BYFOUR */
  77347. fprintf(out, " }\n};\n");
  77348. fclose(out);
  77349. }
  77350. #endif /* MAKECRCH */
  77351. }
  77352. #ifdef MAKECRCH
  77353. local void write_table(out, table)
  77354. FILE *out;
  77355. const unsigned long FAR *table;
  77356. {
  77357. int n;
  77358. for (n = 0; n < 256; n++)
  77359. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  77360. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  77361. }
  77362. #endif /* MAKECRCH */
  77363. #else /* !DYNAMIC_CRC_TABLE */
  77364. /* ========================================================================
  77365. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  77366. */
  77367. /*** Start of inlined file: crc32.h ***/
  77368. local const unsigned long FAR crc_table[TBLS][256] =
  77369. {
  77370. {
  77371. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  77372. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  77373. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  77374. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  77375. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  77376. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  77377. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  77378. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  77379. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  77380. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  77381. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  77382. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  77383. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  77384. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  77385. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  77386. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  77387. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  77388. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  77389. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  77390. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  77391. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  77392. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  77393. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  77394. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  77395. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  77396. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  77397. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  77398. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  77399. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  77400. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  77401. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  77402. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  77403. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  77404. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  77405. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  77406. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  77407. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  77408. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  77409. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  77410. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  77411. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  77412. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  77413. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  77414. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  77415. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  77416. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  77417. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  77418. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  77419. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  77420. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  77421. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  77422. 0x2d02ef8dUL
  77423. #ifdef BYFOUR
  77424. },
  77425. {
  77426. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  77427. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  77428. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  77429. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  77430. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  77431. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  77432. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  77433. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  77434. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  77435. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  77436. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  77437. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  77438. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  77439. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  77440. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  77441. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  77442. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  77443. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  77444. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  77445. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  77446. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  77447. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  77448. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  77449. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  77450. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  77451. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  77452. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  77453. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  77454. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  77455. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  77456. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  77457. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  77458. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  77459. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  77460. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  77461. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  77462. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  77463. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  77464. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  77465. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  77466. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  77467. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  77468. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  77469. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  77470. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  77471. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  77472. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  77473. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  77474. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  77475. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  77476. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  77477. 0x9324fd72UL
  77478. },
  77479. {
  77480. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  77481. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  77482. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  77483. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  77484. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  77485. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  77486. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  77487. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  77488. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  77489. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  77490. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  77491. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  77492. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  77493. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  77494. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  77495. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  77496. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  77497. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  77498. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  77499. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  77500. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  77501. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  77502. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  77503. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  77504. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  77505. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  77506. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  77507. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  77508. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  77509. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  77510. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  77511. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  77512. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  77513. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  77514. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  77515. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  77516. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  77517. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  77518. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  77519. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  77520. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  77521. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  77522. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  77523. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  77524. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  77525. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  77526. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  77527. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  77528. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  77529. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  77530. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  77531. 0xbe9834edUL
  77532. },
  77533. {
  77534. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  77535. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  77536. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  77537. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  77538. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  77539. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  77540. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  77541. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  77542. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  77543. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  77544. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  77545. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  77546. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  77547. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  77548. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  77549. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  77550. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  77551. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  77552. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  77553. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  77554. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  77555. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  77556. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  77557. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  77558. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  77559. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  77560. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  77561. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  77562. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  77563. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  77564. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  77565. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  77566. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  77567. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  77568. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  77569. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  77570. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  77571. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  77572. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  77573. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  77574. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  77575. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  77576. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  77577. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  77578. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  77579. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  77580. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  77581. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  77582. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  77583. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  77584. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  77585. 0xde0506f1UL
  77586. },
  77587. {
  77588. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  77589. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  77590. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  77591. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  77592. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  77593. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  77594. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  77595. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  77596. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  77597. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  77598. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  77599. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  77600. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  77601. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  77602. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  77603. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  77604. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  77605. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  77606. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  77607. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  77608. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  77609. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  77610. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  77611. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  77612. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  77613. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  77614. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  77615. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  77616. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  77617. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  77618. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  77619. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  77620. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  77621. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  77622. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  77623. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  77624. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  77625. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  77626. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  77627. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  77628. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  77629. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  77630. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  77631. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  77632. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  77633. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  77634. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  77635. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  77636. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  77637. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  77638. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  77639. 0x8def022dUL
  77640. },
  77641. {
  77642. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  77643. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  77644. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  77645. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  77646. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  77647. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  77648. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  77649. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  77650. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  77651. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  77652. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  77653. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  77654. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  77655. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  77656. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  77657. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  77658. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  77659. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  77660. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  77661. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  77662. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  77663. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  77664. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  77665. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  77666. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  77667. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  77668. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  77669. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  77670. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  77671. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  77672. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  77673. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  77674. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  77675. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  77676. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  77677. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  77678. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  77679. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  77680. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  77681. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  77682. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  77683. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  77684. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  77685. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  77686. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  77687. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  77688. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  77689. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  77690. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  77691. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  77692. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  77693. 0x72fd2493UL
  77694. },
  77695. {
  77696. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  77697. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  77698. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  77699. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  77700. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  77701. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  77702. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  77703. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  77704. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  77705. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  77706. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  77707. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  77708. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  77709. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  77710. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  77711. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  77712. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  77713. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  77714. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  77715. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  77716. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  77717. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  77718. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  77719. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  77720. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  77721. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  77722. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  77723. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  77724. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  77725. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  77726. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  77727. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  77728. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  77729. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  77730. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  77731. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  77732. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  77733. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  77734. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  77735. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  77736. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  77737. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  77738. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  77739. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  77740. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  77741. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  77742. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  77743. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  77744. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  77745. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  77746. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  77747. 0xed3498beUL
  77748. },
  77749. {
  77750. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  77751. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  77752. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  77753. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  77754. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  77755. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  77756. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  77757. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  77758. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  77759. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  77760. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  77761. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  77762. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  77763. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  77764. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  77765. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  77766. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  77767. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  77768. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  77769. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  77770. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  77771. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  77772. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  77773. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  77774. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  77775. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  77776. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  77777. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  77778. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  77779. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  77780. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  77781. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  77782. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  77783. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  77784. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  77785. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  77786. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  77787. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  77788. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  77789. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  77790. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  77791. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  77792. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  77793. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  77794. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  77795. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  77796. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  77797. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  77798. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  77799. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  77800. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  77801. 0xf10605deUL
  77802. #endif
  77803. }
  77804. };
  77805. /*** End of inlined file: crc32.h ***/
  77806. #endif /* DYNAMIC_CRC_TABLE */
  77807. /* =========================================================================
  77808. * This function can be used by asm versions of crc32()
  77809. */
  77810. const unsigned long FAR * ZEXPORT get_crc_table()
  77811. {
  77812. #ifdef DYNAMIC_CRC_TABLE
  77813. if (crc_table_empty)
  77814. make_crc_table();
  77815. #endif /* DYNAMIC_CRC_TABLE */
  77816. return (const unsigned long FAR *)crc_table;
  77817. }
  77818. /* ========================================================================= */
  77819. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  77820. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  77821. /* ========================================================================= */
  77822. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  77823. {
  77824. if (buf == Z_NULL) return 0UL;
  77825. #ifdef DYNAMIC_CRC_TABLE
  77826. if (crc_table_empty)
  77827. make_crc_table();
  77828. #endif /* DYNAMIC_CRC_TABLE */
  77829. #ifdef BYFOUR
  77830. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  77831. u4 endian;
  77832. endian = 1;
  77833. if (*((unsigned char *)(&endian)))
  77834. return crc32_little(crc, buf, len);
  77835. else
  77836. return crc32_big(crc, buf, len);
  77837. }
  77838. #endif /* BYFOUR */
  77839. crc = crc ^ 0xffffffffUL;
  77840. while (len >= 8) {
  77841. DO8;
  77842. len -= 8;
  77843. }
  77844. if (len) do {
  77845. DO1;
  77846. } while (--len);
  77847. return crc ^ 0xffffffffUL;
  77848. }
  77849. #ifdef BYFOUR
  77850. /* ========================================================================= */
  77851. #define DOLIT4 c ^= *buf4++; \
  77852. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  77853. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  77854. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  77855. /* ========================================================================= */
  77856. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  77857. {
  77858. register u4 c;
  77859. register const u4 FAR *buf4;
  77860. c = (u4)crc;
  77861. c = ~c;
  77862. while (len && ((ptrdiff_t)buf & 3)) {
  77863. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  77864. len--;
  77865. }
  77866. buf4 = (const u4 FAR *)(const void FAR *)buf;
  77867. while (len >= 32) {
  77868. DOLIT32;
  77869. len -= 32;
  77870. }
  77871. while (len >= 4) {
  77872. DOLIT4;
  77873. len -= 4;
  77874. }
  77875. buf = (const unsigned char FAR *)buf4;
  77876. if (len) do {
  77877. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  77878. } while (--len);
  77879. c = ~c;
  77880. return (unsigned long)c;
  77881. }
  77882. /* ========================================================================= */
  77883. #define DOBIG4 c ^= *++buf4; \
  77884. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  77885. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  77886. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  77887. /* ========================================================================= */
  77888. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  77889. {
  77890. register u4 c;
  77891. register const u4 FAR *buf4;
  77892. c = REV((u4)crc);
  77893. c = ~c;
  77894. while (len && ((ptrdiff_t)buf & 3)) {
  77895. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  77896. len--;
  77897. }
  77898. buf4 = (const u4 FAR *)(const void FAR *)buf;
  77899. buf4--;
  77900. while (len >= 32) {
  77901. DOBIG32;
  77902. len -= 32;
  77903. }
  77904. while (len >= 4) {
  77905. DOBIG4;
  77906. len -= 4;
  77907. }
  77908. buf4++;
  77909. buf = (const unsigned char FAR *)buf4;
  77910. if (len) do {
  77911. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  77912. } while (--len);
  77913. c = ~c;
  77914. return (unsigned long)(REV(c));
  77915. }
  77916. #endif /* BYFOUR */
  77917. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  77918. /* ========================================================================= */
  77919. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  77920. {
  77921. unsigned long sum;
  77922. sum = 0;
  77923. while (vec) {
  77924. if (vec & 1)
  77925. sum ^= *mat;
  77926. vec >>= 1;
  77927. mat++;
  77928. }
  77929. return sum;
  77930. }
  77931. /* ========================================================================= */
  77932. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  77933. {
  77934. int n;
  77935. for (n = 0; n < GF2_DIM; n++)
  77936. square[n] = gf2_matrix_times(mat, mat[n]);
  77937. }
  77938. /* ========================================================================= */
  77939. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  77940. {
  77941. int n;
  77942. unsigned long row;
  77943. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  77944. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  77945. /* degenerate case */
  77946. if (len2 == 0)
  77947. return crc1;
  77948. /* put operator for one zero bit in odd */
  77949. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  77950. row = 1;
  77951. for (n = 1; n < GF2_DIM; n++) {
  77952. odd[n] = row;
  77953. row <<= 1;
  77954. }
  77955. /* put operator for two zero bits in even */
  77956. gf2_matrix_square(even, odd);
  77957. /* put operator for four zero bits in odd */
  77958. gf2_matrix_square(odd, even);
  77959. /* apply len2 zeros to crc1 (first square will put the operator for one
  77960. zero byte, eight zero bits, in even) */
  77961. do {
  77962. /* apply zeros operator for this bit of len2 */
  77963. gf2_matrix_square(even, odd);
  77964. if (len2 & 1)
  77965. crc1 = gf2_matrix_times(even, crc1);
  77966. len2 >>= 1;
  77967. /* if no more bits set, then done */
  77968. if (len2 == 0)
  77969. break;
  77970. /* another iteration of the loop with odd and even swapped */
  77971. gf2_matrix_square(odd, even);
  77972. if (len2 & 1)
  77973. crc1 = gf2_matrix_times(odd, crc1);
  77974. len2 >>= 1;
  77975. /* if no more bits set, then done */
  77976. } while (len2 != 0);
  77977. /* return combined crc */
  77978. crc1 ^= crc2;
  77979. return crc1;
  77980. }
  77981. /*** End of inlined file: crc32.c ***/
  77982. /*** Start of inlined file: deflate.c ***/
  77983. /*
  77984. * ALGORITHM
  77985. *
  77986. * The "deflation" process depends on being able to identify portions
  77987. * of the input text which are identical to earlier input (within a
  77988. * sliding window trailing behind the input currently being processed).
  77989. *
  77990. * The most straightforward technique turns out to be the fastest for
  77991. * most input files: try all possible matches and select the longest.
  77992. * The key feature of this algorithm is that insertions into the string
  77993. * dictionary are very simple and thus fast, and deletions are avoided
  77994. * completely. Insertions are performed at each input character, whereas
  77995. * string matches are performed only when the previous match ends. So it
  77996. * is preferable to spend more time in matches to allow very fast string
  77997. * insertions and avoid deletions. The matching algorithm for small
  77998. * strings is inspired from that of Rabin & Karp. A brute force approach
  77999. * is used to find longer strings when a small match has been found.
  78000. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  78001. * (by Leonid Broukhis).
  78002. * A previous version of this file used a more sophisticated algorithm
  78003. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  78004. * time, but has a larger average cost, uses more memory and is patented.
  78005. * However the F&G algorithm may be faster for some highly redundant
  78006. * files if the parameter max_chain_length (described below) is too large.
  78007. *
  78008. * ACKNOWLEDGEMENTS
  78009. *
  78010. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  78011. * I found it in 'freeze' written by Leonid Broukhis.
  78012. * Thanks to many people for bug reports and testing.
  78013. *
  78014. * REFERENCES
  78015. *
  78016. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  78017. * Available in http://www.ietf.org/rfc/rfc1951.txt
  78018. *
  78019. * A description of the Rabin and Karp algorithm is given in the book
  78020. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  78021. *
  78022. * Fiala,E.R., and Greene,D.H.
  78023. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  78024. *
  78025. */
  78026. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78027. /*** Start of inlined file: deflate.h ***/
  78028. /* WARNING: this file should *not* be used by applications. It is
  78029. part of the implementation of the compression library and is
  78030. subject to change. Applications should only use zlib.h.
  78031. */
  78032. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78033. #ifndef DEFLATE_H
  78034. #define DEFLATE_H
  78035. /* define NO_GZIP when compiling if you want to disable gzip header and
  78036. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  78037. the crc code when it is not needed. For shared libraries, gzip encoding
  78038. should be left enabled. */
  78039. #ifndef NO_GZIP
  78040. # define GZIP
  78041. #endif
  78042. #define NO_DUMMY_DECL
  78043. /* ===========================================================================
  78044. * Internal compression state.
  78045. */
  78046. #define LENGTH_CODES 29
  78047. /* number of length codes, not counting the special END_BLOCK code */
  78048. #define LITERALS 256
  78049. /* number of literal bytes 0..255 */
  78050. #define L_CODES (LITERALS+1+LENGTH_CODES)
  78051. /* number of Literal or Length codes, including the END_BLOCK code */
  78052. #define D_CODES 30
  78053. /* number of distance codes */
  78054. #define BL_CODES 19
  78055. /* number of codes used to transfer the bit lengths */
  78056. #define HEAP_SIZE (2*L_CODES+1)
  78057. /* maximum heap size */
  78058. #define MAX_BITS 15
  78059. /* All codes must not exceed MAX_BITS bits */
  78060. #define INIT_STATE 42
  78061. #define EXTRA_STATE 69
  78062. #define NAME_STATE 73
  78063. #define COMMENT_STATE 91
  78064. #define HCRC_STATE 103
  78065. #define BUSY_STATE 113
  78066. #define FINISH_STATE 666
  78067. /* Stream status */
  78068. /* Data structure describing a single value and its code string. */
  78069. typedef struct ct_data_s {
  78070. union {
  78071. ush freq; /* frequency count */
  78072. ush code; /* bit string */
  78073. } fc;
  78074. union {
  78075. ush dad; /* father node in Huffman tree */
  78076. ush len; /* length of bit string */
  78077. } dl;
  78078. } FAR ct_data;
  78079. #define Freq fc.freq
  78080. #define Code fc.code
  78081. #define Dad dl.dad
  78082. #define Len dl.len
  78083. typedef struct static_tree_desc_s static_tree_desc;
  78084. typedef struct tree_desc_s {
  78085. ct_data *dyn_tree; /* the dynamic tree */
  78086. int max_code; /* largest code with non zero frequency */
  78087. static_tree_desc *stat_desc; /* the corresponding static tree */
  78088. } FAR tree_desc;
  78089. typedef ush Pos;
  78090. typedef Pos FAR Posf;
  78091. typedef unsigned IPos;
  78092. /* A Pos is an index in the character window. We use short instead of int to
  78093. * save space in the various tables. IPos is used only for parameter passing.
  78094. */
  78095. typedef struct internal_state {
  78096. z_streamp strm; /* pointer back to this zlib stream */
  78097. int status; /* as the name implies */
  78098. Bytef *pending_buf; /* output still pending */
  78099. ulg pending_buf_size; /* size of pending_buf */
  78100. Bytef *pending_out; /* next pending byte to output to the stream */
  78101. uInt pending; /* nb of bytes in the pending buffer */
  78102. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  78103. gz_headerp gzhead; /* gzip header information to write */
  78104. uInt gzindex; /* where in extra, name, or comment */
  78105. Byte method; /* STORED (for zip only) or DEFLATED */
  78106. int last_flush; /* value of flush param for previous deflate call */
  78107. /* used by deflate.c: */
  78108. uInt w_size; /* LZ77 window size (32K by default) */
  78109. uInt w_bits; /* log2(w_size) (8..16) */
  78110. uInt w_mask; /* w_size - 1 */
  78111. Bytef *window;
  78112. /* Sliding window. Input bytes are read into the second half of the window,
  78113. * and move to the first half later to keep a dictionary of at least wSize
  78114. * bytes. With this organization, matches are limited to a distance of
  78115. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  78116. * performed with a length multiple of the block size. Also, it limits
  78117. * the window size to 64K, which is quite useful on MSDOS.
  78118. * To do: use the user input buffer as sliding window.
  78119. */
  78120. ulg window_size;
  78121. /* Actual size of window: 2*wSize, except when the user input buffer
  78122. * is directly used as sliding window.
  78123. */
  78124. Posf *prev;
  78125. /* Link to older string with same hash index. To limit the size of this
  78126. * array to 64K, this link is maintained only for the last 32K strings.
  78127. * An index in this array is thus a window index modulo 32K.
  78128. */
  78129. Posf *head; /* Heads of the hash chains or NIL. */
  78130. uInt ins_h; /* hash index of string to be inserted */
  78131. uInt hash_size; /* number of elements in hash table */
  78132. uInt hash_bits; /* log2(hash_size) */
  78133. uInt hash_mask; /* hash_size-1 */
  78134. uInt hash_shift;
  78135. /* Number of bits by which ins_h must be shifted at each input
  78136. * step. It must be such that after MIN_MATCH steps, the oldest
  78137. * byte no longer takes part in the hash key, that is:
  78138. * hash_shift * MIN_MATCH >= hash_bits
  78139. */
  78140. long block_start;
  78141. /* Window position at the beginning of the current output block. Gets
  78142. * negative when the window is moved backwards.
  78143. */
  78144. uInt match_length; /* length of best match */
  78145. IPos prev_match; /* previous match */
  78146. int match_available; /* set if previous match exists */
  78147. uInt strstart; /* start of string to insert */
  78148. uInt match_start; /* start of matching string */
  78149. uInt lookahead; /* number of valid bytes ahead in window */
  78150. uInt prev_length;
  78151. /* Length of the best match at previous step. Matches not greater than this
  78152. * are discarded. This is used in the lazy match evaluation.
  78153. */
  78154. uInt max_chain_length;
  78155. /* To speed up deflation, hash chains are never searched beyond this
  78156. * length. A higher limit improves compression ratio but degrades the
  78157. * speed.
  78158. */
  78159. uInt max_lazy_match;
  78160. /* Attempt to find a better match only when the current match is strictly
  78161. * smaller than this value. This mechanism is used only for compression
  78162. * levels >= 4.
  78163. */
  78164. # define max_insert_length max_lazy_match
  78165. /* Insert new strings in the hash table only if the match length is not
  78166. * greater than this length. This saves time but degrades compression.
  78167. * max_insert_length is used only for compression levels <= 3.
  78168. */
  78169. int level; /* compression level (1..9) */
  78170. int strategy; /* favor or force Huffman coding*/
  78171. uInt good_match;
  78172. /* Use a faster search when the previous match is longer than this */
  78173. int nice_match; /* Stop searching when current match exceeds this */
  78174. /* used by trees.c: */
  78175. /* Didn't use ct_data typedef below to supress compiler warning */
  78176. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  78177. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  78178. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  78179. struct tree_desc_s l_desc; /* desc. for literal tree */
  78180. struct tree_desc_s d_desc; /* desc. for distance tree */
  78181. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  78182. ush bl_count[MAX_BITS+1];
  78183. /* number of codes at each bit length for an optimal tree */
  78184. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  78185. int heap_len; /* number of elements in the heap */
  78186. int heap_max; /* element of largest frequency */
  78187. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  78188. * The same heap array is used to build all trees.
  78189. */
  78190. uch depth[2*L_CODES+1];
  78191. /* Depth of each subtree used as tie breaker for trees of equal frequency
  78192. */
  78193. uchf *l_buf; /* buffer for literals or lengths */
  78194. uInt lit_bufsize;
  78195. /* Size of match buffer for literals/lengths. There are 4 reasons for
  78196. * limiting lit_bufsize to 64K:
  78197. * - frequencies can be kept in 16 bit counters
  78198. * - if compression is not successful for the first block, all input
  78199. * data is still in the window so we can still emit a stored block even
  78200. * when input comes from standard input. (This can also be done for
  78201. * all blocks if lit_bufsize is not greater than 32K.)
  78202. * - if compression is not successful for a file smaller than 64K, we can
  78203. * even emit a stored file instead of a stored block (saving 5 bytes).
  78204. * This is applicable only for zip (not gzip or zlib).
  78205. * - creating new Huffman trees less frequently may not provide fast
  78206. * adaptation to changes in the input data statistics. (Take for
  78207. * example a binary file with poorly compressible code followed by
  78208. * a highly compressible string table.) Smaller buffer sizes give
  78209. * fast adaptation but have of course the overhead of transmitting
  78210. * trees more frequently.
  78211. * - I can't count above 4
  78212. */
  78213. uInt last_lit; /* running index in l_buf */
  78214. ushf *d_buf;
  78215. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  78216. * the same number of elements. To use different lengths, an extra flag
  78217. * array would be necessary.
  78218. */
  78219. ulg opt_len; /* bit length of current block with optimal trees */
  78220. ulg static_len; /* bit length of current block with static trees */
  78221. uInt matches; /* number of string matches in current block */
  78222. int last_eob_len; /* bit length of EOB code for last block */
  78223. #ifdef DEBUG
  78224. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  78225. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  78226. #endif
  78227. ush bi_buf;
  78228. /* Output buffer. bits are inserted starting at the bottom (least
  78229. * significant bits).
  78230. */
  78231. int bi_valid;
  78232. /* Number of valid bits in bi_buf. All bits above the last valid bit
  78233. * are always zero.
  78234. */
  78235. } FAR deflate_state;
  78236. /* Output a byte on the stream.
  78237. * IN assertion: there is enough room in pending_buf.
  78238. */
  78239. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  78240. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  78241. /* Minimum amount of lookahead, except at the end of the input file.
  78242. * See deflate.c for comments about the MIN_MATCH+1.
  78243. */
  78244. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  78245. /* In order to simplify the code, particularly on 16 bit machines, match
  78246. * distances are limited to MAX_DIST instead of WSIZE.
  78247. */
  78248. /* in trees.c */
  78249. void _tr_init OF((deflate_state *s));
  78250. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  78251. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  78252. int eof));
  78253. void _tr_align OF((deflate_state *s));
  78254. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  78255. int eof));
  78256. #define d_code(dist) \
  78257. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  78258. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  78259. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  78260. * used.
  78261. */
  78262. #ifndef DEBUG
  78263. /* Inline versions of _tr_tally for speed: */
  78264. #if defined(GEN_TREES_H) || !defined(STDC)
  78265. extern uch _length_code[];
  78266. extern uch _dist_code[];
  78267. #else
  78268. extern const uch _length_code[];
  78269. extern const uch _dist_code[];
  78270. #endif
  78271. # define _tr_tally_lit(s, c, flush) \
  78272. { uch cc = (c); \
  78273. s->d_buf[s->last_lit] = 0; \
  78274. s->l_buf[s->last_lit++] = cc; \
  78275. s->dyn_ltree[cc].Freq++; \
  78276. flush = (s->last_lit == s->lit_bufsize-1); \
  78277. }
  78278. # define _tr_tally_dist(s, distance, length, flush) \
  78279. { uch len = (length); \
  78280. ush dist = (distance); \
  78281. s->d_buf[s->last_lit] = dist; \
  78282. s->l_buf[s->last_lit++] = len; \
  78283. dist--; \
  78284. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  78285. s->dyn_dtree[d_code(dist)].Freq++; \
  78286. flush = (s->last_lit == s->lit_bufsize-1); \
  78287. }
  78288. #else
  78289. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  78290. # define _tr_tally_dist(s, distance, length, flush) \
  78291. flush = _tr_tally(s, distance, length)
  78292. #endif
  78293. #endif /* DEFLATE_H */
  78294. /*** End of inlined file: deflate.h ***/
  78295. const char deflate_copyright[] =
  78296. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  78297. /*
  78298. If you use the zlib library in a product, an acknowledgment is welcome
  78299. in the documentation of your product. If for some reason you cannot
  78300. include such an acknowledgment, I would appreciate that you keep this
  78301. copyright string in the executable of your product.
  78302. */
  78303. /* ===========================================================================
  78304. * Function prototypes.
  78305. */
  78306. typedef enum {
  78307. need_more, /* block not completed, need more input or more output */
  78308. block_done, /* block flush performed */
  78309. finish_started, /* finish started, need only more output at next deflate */
  78310. finish_done /* finish done, accept no more input or output */
  78311. } block_state;
  78312. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  78313. /* Compression function. Returns the block state after the call. */
  78314. local void fill_window OF((deflate_state *s));
  78315. local block_state deflate_stored OF((deflate_state *s, int flush));
  78316. local block_state deflate_fast OF((deflate_state *s, int flush));
  78317. #ifndef FASTEST
  78318. local block_state deflate_slow OF((deflate_state *s, int flush));
  78319. #endif
  78320. local void lm_init OF((deflate_state *s));
  78321. local void putShortMSB OF((deflate_state *s, uInt b));
  78322. local void flush_pending OF((z_streamp strm));
  78323. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  78324. #ifndef FASTEST
  78325. #ifdef ASMV
  78326. void match_init OF((void)); /* asm code initialization */
  78327. uInt longest_match OF((deflate_state *s, IPos cur_match));
  78328. #else
  78329. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  78330. #endif
  78331. #endif
  78332. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  78333. #ifdef DEBUG
  78334. local void check_match OF((deflate_state *s, IPos start, IPos match,
  78335. int length));
  78336. #endif
  78337. /* ===========================================================================
  78338. * Local data
  78339. */
  78340. #define NIL 0
  78341. /* Tail of hash chains */
  78342. #ifndef TOO_FAR
  78343. # define TOO_FAR 4096
  78344. #endif
  78345. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  78346. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  78347. /* Minimum amount of lookahead, except at the end of the input file.
  78348. * See deflate.c for comments about the MIN_MATCH+1.
  78349. */
  78350. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  78351. * the desired pack level (0..9). The values given below have been tuned to
  78352. * exclude worst case performance for pathological files. Better values may be
  78353. * found for specific files.
  78354. */
  78355. typedef struct config_s {
  78356. ush good_length; /* reduce lazy search above this match length */
  78357. ush max_lazy; /* do not perform lazy search above this match length */
  78358. ush nice_length; /* quit search above this match length */
  78359. ush max_chain;
  78360. compress_func func;
  78361. } config;
  78362. #ifdef FASTEST
  78363. local const config configuration_table[2] = {
  78364. /* good lazy nice chain */
  78365. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  78366. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  78367. #else
  78368. local const config configuration_table[10] = {
  78369. /* good lazy nice chain */
  78370. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  78371. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  78372. /* 2 */ {4, 5, 16, 8, deflate_fast},
  78373. /* 3 */ {4, 6, 32, 32, deflate_fast},
  78374. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  78375. /* 5 */ {8, 16, 32, 32, deflate_slow},
  78376. /* 6 */ {8, 16, 128, 128, deflate_slow},
  78377. /* 7 */ {8, 32, 128, 256, deflate_slow},
  78378. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  78379. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  78380. #endif
  78381. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  78382. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  78383. * meaning.
  78384. */
  78385. #define EQUAL 0
  78386. /* result of memcmp for equal strings */
  78387. #ifndef NO_DUMMY_DECL
  78388. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  78389. #endif
  78390. /* ===========================================================================
  78391. * Update a hash value with the given input byte
  78392. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  78393. * input characters, so that a running hash key can be computed from the
  78394. * previous key instead of complete recalculation each time.
  78395. */
  78396. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  78397. /* ===========================================================================
  78398. * Insert string str in the dictionary and set match_head to the previous head
  78399. * of the hash chain (the most recent string with same hash key). Return
  78400. * the previous length of the hash chain.
  78401. * If this file is compiled with -DFASTEST, the compression level is forced
  78402. * to 1, and no hash chains are maintained.
  78403. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  78404. * input characters and the first MIN_MATCH bytes of str are valid
  78405. * (except for the last MIN_MATCH-1 bytes of the input file).
  78406. */
  78407. #ifdef FASTEST
  78408. #define INSERT_STRING(s, str, match_head) \
  78409. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  78410. match_head = s->head[s->ins_h], \
  78411. s->head[s->ins_h] = (Pos)(str))
  78412. #else
  78413. #define INSERT_STRING(s, str, match_head) \
  78414. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  78415. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  78416. s->head[s->ins_h] = (Pos)(str))
  78417. #endif
  78418. /* ===========================================================================
  78419. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  78420. * prev[] will be initialized on the fly.
  78421. */
  78422. #define CLEAR_HASH(s) \
  78423. s->head[s->hash_size-1] = NIL; \
  78424. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  78425. /* ========================================================================= */
  78426. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  78427. {
  78428. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  78429. Z_DEFAULT_STRATEGY, version, stream_size);
  78430. /* To do: ignore strm->next_in if we use it as window */
  78431. }
  78432. /* ========================================================================= */
  78433. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  78434. {
  78435. deflate_state *s;
  78436. int wrap = 1;
  78437. static const char my_version[] = ZLIB_VERSION;
  78438. ushf *overlay;
  78439. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  78440. * output size for (length,distance) codes is <= 24 bits.
  78441. */
  78442. if (version == Z_NULL || version[0] != my_version[0] ||
  78443. stream_size != sizeof(z_stream)) {
  78444. return Z_VERSION_ERROR;
  78445. }
  78446. if (strm == Z_NULL) return Z_STREAM_ERROR;
  78447. strm->msg = Z_NULL;
  78448. if (strm->zalloc == (alloc_func)0) {
  78449. strm->zalloc = zcalloc;
  78450. strm->opaque = (voidpf)0;
  78451. }
  78452. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  78453. #ifdef FASTEST
  78454. if (level != 0) level = 1;
  78455. #else
  78456. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  78457. #endif
  78458. if (windowBits < 0) { /* suppress zlib wrapper */
  78459. wrap = 0;
  78460. windowBits = -windowBits;
  78461. }
  78462. #ifdef GZIP
  78463. else if (windowBits > 15) {
  78464. wrap = 2; /* write gzip wrapper instead */
  78465. windowBits -= 16;
  78466. }
  78467. #endif
  78468. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  78469. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  78470. strategy < 0 || strategy > Z_FIXED) {
  78471. return Z_STREAM_ERROR;
  78472. }
  78473. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  78474. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  78475. if (s == Z_NULL) return Z_MEM_ERROR;
  78476. strm->state = (struct internal_state FAR *)s;
  78477. s->strm = strm;
  78478. s->wrap = wrap;
  78479. s->gzhead = Z_NULL;
  78480. s->w_bits = windowBits;
  78481. s->w_size = 1 << s->w_bits;
  78482. s->w_mask = s->w_size - 1;
  78483. s->hash_bits = memLevel + 7;
  78484. s->hash_size = 1 << s->hash_bits;
  78485. s->hash_mask = s->hash_size - 1;
  78486. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  78487. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  78488. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  78489. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  78490. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  78491. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  78492. s->pending_buf = (uchf *) overlay;
  78493. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  78494. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  78495. s->pending_buf == Z_NULL) {
  78496. s->status = FINISH_STATE;
  78497. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  78498. deflateEnd (strm);
  78499. return Z_MEM_ERROR;
  78500. }
  78501. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  78502. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  78503. s->level = level;
  78504. s->strategy = strategy;
  78505. s->method = (Byte)method;
  78506. return deflateReset(strm);
  78507. }
  78508. /* ========================================================================= */
  78509. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  78510. {
  78511. deflate_state *s;
  78512. uInt length = dictLength;
  78513. uInt n;
  78514. IPos hash_head = 0;
  78515. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  78516. strm->state->wrap == 2 ||
  78517. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  78518. return Z_STREAM_ERROR;
  78519. s = strm->state;
  78520. if (s->wrap)
  78521. strm->adler = adler32(strm->adler, dictionary, dictLength);
  78522. if (length < MIN_MATCH) return Z_OK;
  78523. if (length > MAX_DIST(s)) {
  78524. length = MAX_DIST(s);
  78525. dictionary += dictLength - length; /* use the tail of the dictionary */
  78526. }
  78527. zmemcpy(s->window, dictionary, length);
  78528. s->strstart = length;
  78529. s->block_start = (long)length;
  78530. /* Insert all strings in the hash table (except for the last two bytes).
  78531. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  78532. * call of fill_window.
  78533. */
  78534. s->ins_h = s->window[0];
  78535. UPDATE_HASH(s, s->ins_h, s->window[1]);
  78536. for (n = 0; n <= length - MIN_MATCH; n++) {
  78537. INSERT_STRING(s, n, hash_head);
  78538. }
  78539. if (hash_head) hash_head = 0; /* to make compiler happy */
  78540. return Z_OK;
  78541. }
  78542. /* ========================================================================= */
  78543. int ZEXPORT deflateReset (z_streamp strm)
  78544. {
  78545. deflate_state *s;
  78546. if (strm == Z_NULL || strm->state == Z_NULL ||
  78547. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  78548. return Z_STREAM_ERROR;
  78549. }
  78550. strm->total_in = strm->total_out = 0;
  78551. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  78552. strm->data_type = Z_UNKNOWN;
  78553. s = (deflate_state *)strm->state;
  78554. s->pending = 0;
  78555. s->pending_out = s->pending_buf;
  78556. if (s->wrap < 0) {
  78557. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  78558. }
  78559. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  78560. strm->adler =
  78561. #ifdef GZIP
  78562. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  78563. #endif
  78564. adler32(0L, Z_NULL, 0);
  78565. s->last_flush = Z_NO_FLUSH;
  78566. _tr_init(s);
  78567. lm_init(s);
  78568. return Z_OK;
  78569. }
  78570. /* ========================================================================= */
  78571. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  78572. {
  78573. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78574. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  78575. strm->state->gzhead = head;
  78576. return Z_OK;
  78577. }
  78578. /* ========================================================================= */
  78579. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  78580. {
  78581. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78582. strm->state->bi_valid = bits;
  78583. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  78584. return Z_OK;
  78585. }
  78586. /* ========================================================================= */
  78587. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  78588. {
  78589. deflate_state *s;
  78590. compress_func func;
  78591. int err = Z_OK;
  78592. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78593. s = strm->state;
  78594. #ifdef FASTEST
  78595. if (level != 0) level = 1;
  78596. #else
  78597. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  78598. #endif
  78599. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  78600. return Z_STREAM_ERROR;
  78601. }
  78602. func = configuration_table[s->level].func;
  78603. if (func != configuration_table[level].func && strm->total_in != 0) {
  78604. /* Flush the last buffer: */
  78605. err = deflate(strm, Z_PARTIAL_FLUSH);
  78606. }
  78607. if (s->level != level) {
  78608. s->level = level;
  78609. s->max_lazy_match = configuration_table[level].max_lazy;
  78610. s->good_match = configuration_table[level].good_length;
  78611. s->nice_match = configuration_table[level].nice_length;
  78612. s->max_chain_length = configuration_table[level].max_chain;
  78613. }
  78614. s->strategy = strategy;
  78615. return err;
  78616. }
  78617. /* ========================================================================= */
  78618. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  78619. {
  78620. deflate_state *s;
  78621. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78622. s = strm->state;
  78623. s->good_match = good_length;
  78624. s->max_lazy_match = max_lazy;
  78625. s->nice_match = nice_length;
  78626. s->max_chain_length = max_chain;
  78627. return Z_OK;
  78628. }
  78629. /* =========================================================================
  78630. * For the default windowBits of 15 and memLevel of 8, this function returns
  78631. * a close to exact, as well as small, upper bound on the compressed size.
  78632. * They are coded as constants here for a reason--if the #define's are
  78633. * changed, then this function needs to be changed as well. The return
  78634. * value for 15 and 8 only works for those exact settings.
  78635. *
  78636. * For any setting other than those defaults for windowBits and memLevel,
  78637. * the value returned is a conservative worst case for the maximum expansion
  78638. * resulting from using fixed blocks instead of stored blocks, which deflate
  78639. * can emit on compressed data for some combinations of the parameters.
  78640. *
  78641. * This function could be more sophisticated to provide closer upper bounds
  78642. * for every combination of windowBits and memLevel, as well as wrap.
  78643. * But even the conservative upper bound of about 14% expansion does not
  78644. * seem onerous for output buffer allocation.
  78645. */
  78646. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  78647. {
  78648. deflate_state *s;
  78649. uLong destLen;
  78650. /* conservative upper bound */
  78651. destLen = sourceLen +
  78652. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  78653. /* if can't get parameters, return conservative bound */
  78654. if (strm == Z_NULL || strm->state == Z_NULL)
  78655. return destLen;
  78656. /* if not default parameters, return conservative bound */
  78657. s = strm->state;
  78658. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  78659. return destLen;
  78660. /* default settings: return tight bound for that case */
  78661. return compressBound(sourceLen);
  78662. }
  78663. /* =========================================================================
  78664. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  78665. * IN assertion: the stream state is correct and there is enough room in
  78666. * pending_buf.
  78667. */
  78668. local void putShortMSB (deflate_state *s, uInt b)
  78669. {
  78670. put_byte(s, (Byte)(b >> 8));
  78671. put_byte(s, (Byte)(b & 0xff));
  78672. }
  78673. /* =========================================================================
  78674. * Flush as much pending output as possible. All deflate() output goes
  78675. * through this function so some applications may wish to modify it
  78676. * to avoid allocating a large strm->next_out buffer and copying into it.
  78677. * (See also read_buf()).
  78678. */
  78679. local void flush_pending (z_streamp strm)
  78680. {
  78681. unsigned len = strm->state->pending;
  78682. if (len > strm->avail_out) len = strm->avail_out;
  78683. if (len == 0) return;
  78684. zmemcpy(strm->next_out, strm->state->pending_out, len);
  78685. strm->next_out += len;
  78686. strm->state->pending_out += len;
  78687. strm->total_out += len;
  78688. strm->avail_out -= len;
  78689. strm->state->pending -= len;
  78690. if (strm->state->pending == 0) {
  78691. strm->state->pending_out = strm->state->pending_buf;
  78692. }
  78693. }
  78694. /* ========================================================================= */
  78695. int ZEXPORT deflate (z_streamp strm, int flush)
  78696. {
  78697. int old_flush; /* value of flush param for previous deflate call */
  78698. deflate_state *s;
  78699. if (strm == Z_NULL || strm->state == Z_NULL ||
  78700. flush > Z_FINISH || flush < 0) {
  78701. return Z_STREAM_ERROR;
  78702. }
  78703. s = strm->state;
  78704. if (strm->next_out == Z_NULL ||
  78705. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  78706. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  78707. ERR_RETURN(strm, Z_STREAM_ERROR);
  78708. }
  78709. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  78710. s->strm = strm; /* just in case */
  78711. old_flush = s->last_flush;
  78712. s->last_flush = flush;
  78713. /* Write the header */
  78714. if (s->status == INIT_STATE) {
  78715. #ifdef GZIP
  78716. if (s->wrap == 2) {
  78717. strm->adler = crc32(0L, Z_NULL, 0);
  78718. put_byte(s, 31);
  78719. put_byte(s, 139);
  78720. put_byte(s, 8);
  78721. if (s->gzhead == NULL) {
  78722. put_byte(s, 0);
  78723. put_byte(s, 0);
  78724. put_byte(s, 0);
  78725. put_byte(s, 0);
  78726. put_byte(s, 0);
  78727. put_byte(s, s->level == 9 ? 2 :
  78728. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  78729. 4 : 0));
  78730. put_byte(s, OS_CODE);
  78731. s->status = BUSY_STATE;
  78732. }
  78733. else {
  78734. put_byte(s, (s->gzhead->text ? 1 : 0) +
  78735. (s->gzhead->hcrc ? 2 : 0) +
  78736. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  78737. (s->gzhead->name == Z_NULL ? 0 : 8) +
  78738. (s->gzhead->comment == Z_NULL ? 0 : 16)
  78739. );
  78740. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  78741. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  78742. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  78743. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  78744. put_byte(s, s->level == 9 ? 2 :
  78745. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  78746. 4 : 0));
  78747. put_byte(s, s->gzhead->os & 0xff);
  78748. if (s->gzhead->extra != NULL) {
  78749. put_byte(s, s->gzhead->extra_len & 0xff);
  78750. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  78751. }
  78752. if (s->gzhead->hcrc)
  78753. strm->adler = crc32(strm->adler, s->pending_buf,
  78754. s->pending);
  78755. s->gzindex = 0;
  78756. s->status = EXTRA_STATE;
  78757. }
  78758. }
  78759. else
  78760. #endif
  78761. {
  78762. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  78763. uInt level_flags;
  78764. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  78765. level_flags = 0;
  78766. else if (s->level < 6)
  78767. level_flags = 1;
  78768. else if (s->level == 6)
  78769. level_flags = 2;
  78770. else
  78771. level_flags = 3;
  78772. header |= (level_flags << 6);
  78773. if (s->strstart != 0) header |= PRESET_DICT;
  78774. header += 31 - (header % 31);
  78775. s->status = BUSY_STATE;
  78776. putShortMSB(s, header);
  78777. /* Save the adler32 of the preset dictionary: */
  78778. if (s->strstart != 0) {
  78779. putShortMSB(s, (uInt)(strm->adler >> 16));
  78780. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  78781. }
  78782. strm->adler = adler32(0L, Z_NULL, 0);
  78783. }
  78784. }
  78785. #ifdef GZIP
  78786. if (s->status == EXTRA_STATE) {
  78787. if (s->gzhead->extra != NULL) {
  78788. uInt beg = s->pending; /* start of bytes to update crc */
  78789. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  78790. if (s->pending == s->pending_buf_size) {
  78791. if (s->gzhead->hcrc && s->pending > beg)
  78792. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  78793. s->pending - beg);
  78794. flush_pending(strm);
  78795. beg = s->pending;
  78796. if (s->pending == s->pending_buf_size)
  78797. break;
  78798. }
  78799. put_byte(s, s->gzhead->extra[s->gzindex]);
  78800. s->gzindex++;
  78801. }
  78802. if (s->gzhead->hcrc && s->pending > beg)
  78803. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  78804. s->pending - beg);
  78805. if (s->gzindex == s->gzhead->extra_len) {
  78806. s->gzindex = 0;
  78807. s->status = NAME_STATE;
  78808. }
  78809. }
  78810. else
  78811. s->status = NAME_STATE;
  78812. }
  78813. if (s->status == NAME_STATE) {
  78814. if (s->gzhead->name != NULL) {
  78815. uInt beg = s->pending; /* start of bytes to update crc */
  78816. int val;
  78817. do {
  78818. if (s->pending == s->pending_buf_size) {
  78819. if (s->gzhead->hcrc && s->pending > beg)
  78820. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  78821. s->pending - beg);
  78822. flush_pending(strm);
  78823. beg = s->pending;
  78824. if (s->pending == s->pending_buf_size) {
  78825. val = 1;
  78826. break;
  78827. }
  78828. }
  78829. val = s->gzhead->name[s->gzindex++];
  78830. put_byte(s, val);
  78831. } while (val != 0);
  78832. if (s->gzhead->hcrc && s->pending > beg)
  78833. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  78834. s->pending - beg);
  78835. if (val == 0) {
  78836. s->gzindex = 0;
  78837. s->status = COMMENT_STATE;
  78838. }
  78839. }
  78840. else
  78841. s->status = COMMENT_STATE;
  78842. }
  78843. if (s->status == COMMENT_STATE) {
  78844. if (s->gzhead->comment != NULL) {
  78845. uInt beg = s->pending; /* start of bytes to update crc */
  78846. int val;
  78847. do {
  78848. if (s->pending == s->pending_buf_size) {
  78849. if (s->gzhead->hcrc && s->pending > beg)
  78850. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  78851. s->pending - beg);
  78852. flush_pending(strm);
  78853. beg = s->pending;
  78854. if (s->pending == s->pending_buf_size) {
  78855. val = 1;
  78856. break;
  78857. }
  78858. }
  78859. val = s->gzhead->comment[s->gzindex++];
  78860. put_byte(s, val);
  78861. } while (val != 0);
  78862. if (s->gzhead->hcrc && s->pending > beg)
  78863. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  78864. s->pending - beg);
  78865. if (val == 0)
  78866. s->status = HCRC_STATE;
  78867. }
  78868. else
  78869. s->status = HCRC_STATE;
  78870. }
  78871. if (s->status == HCRC_STATE) {
  78872. if (s->gzhead->hcrc) {
  78873. if (s->pending + 2 > s->pending_buf_size)
  78874. flush_pending(strm);
  78875. if (s->pending + 2 <= s->pending_buf_size) {
  78876. put_byte(s, (Byte)(strm->adler & 0xff));
  78877. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  78878. strm->adler = crc32(0L, Z_NULL, 0);
  78879. s->status = BUSY_STATE;
  78880. }
  78881. }
  78882. else
  78883. s->status = BUSY_STATE;
  78884. }
  78885. #endif
  78886. /* Flush as much pending output as possible */
  78887. if (s->pending != 0) {
  78888. flush_pending(strm);
  78889. if (strm->avail_out == 0) {
  78890. /* Since avail_out is 0, deflate will be called again with
  78891. * more output space, but possibly with both pending and
  78892. * avail_in equal to zero. There won't be anything to do,
  78893. * but this is not an error situation so make sure we
  78894. * return OK instead of BUF_ERROR at next call of deflate:
  78895. */
  78896. s->last_flush = -1;
  78897. return Z_OK;
  78898. }
  78899. /* Make sure there is something to do and avoid duplicate consecutive
  78900. * flushes. For repeated and useless calls with Z_FINISH, we keep
  78901. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  78902. */
  78903. } else if (strm->avail_in == 0 && flush <= old_flush &&
  78904. flush != Z_FINISH) {
  78905. ERR_RETURN(strm, Z_BUF_ERROR);
  78906. }
  78907. /* User must not provide more input after the first FINISH: */
  78908. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  78909. ERR_RETURN(strm, Z_BUF_ERROR);
  78910. }
  78911. /* Start a new block or continue the current one.
  78912. */
  78913. if (strm->avail_in != 0 || s->lookahead != 0 ||
  78914. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  78915. block_state bstate;
  78916. bstate = (*(configuration_table[s->level].func))(s, flush);
  78917. if (bstate == finish_started || bstate == finish_done) {
  78918. s->status = FINISH_STATE;
  78919. }
  78920. if (bstate == need_more || bstate == finish_started) {
  78921. if (strm->avail_out == 0) {
  78922. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  78923. }
  78924. return Z_OK;
  78925. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  78926. * of deflate should use the same flush parameter to make sure
  78927. * that the flush is complete. So we don't have to output an
  78928. * empty block here, this will be done at next call. This also
  78929. * ensures that for a very small output buffer, we emit at most
  78930. * one empty block.
  78931. */
  78932. }
  78933. if (bstate == block_done) {
  78934. if (flush == Z_PARTIAL_FLUSH) {
  78935. _tr_align(s);
  78936. } else { /* FULL_FLUSH or SYNC_FLUSH */
  78937. _tr_stored_block(s, (char*)0, 0L, 0);
  78938. /* For a full flush, this empty block will be recognized
  78939. * as a special marker by inflate_sync().
  78940. */
  78941. if (flush == Z_FULL_FLUSH) {
  78942. CLEAR_HASH(s); /* forget history */
  78943. }
  78944. }
  78945. flush_pending(strm);
  78946. if (strm->avail_out == 0) {
  78947. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  78948. return Z_OK;
  78949. }
  78950. }
  78951. }
  78952. Assert(strm->avail_out > 0, "bug2");
  78953. if (flush != Z_FINISH) return Z_OK;
  78954. if (s->wrap <= 0) return Z_STREAM_END;
  78955. /* Write the trailer */
  78956. #ifdef GZIP
  78957. if (s->wrap == 2) {
  78958. put_byte(s, (Byte)(strm->adler & 0xff));
  78959. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  78960. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  78961. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  78962. put_byte(s, (Byte)(strm->total_in & 0xff));
  78963. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  78964. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  78965. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  78966. }
  78967. else
  78968. #endif
  78969. {
  78970. putShortMSB(s, (uInt)(strm->adler >> 16));
  78971. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  78972. }
  78973. flush_pending(strm);
  78974. /* If avail_out is zero, the application will call deflate again
  78975. * to flush the rest.
  78976. */
  78977. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  78978. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  78979. }
  78980. /* ========================================================================= */
  78981. int ZEXPORT deflateEnd (z_streamp strm)
  78982. {
  78983. int status;
  78984. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78985. status = strm->state->status;
  78986. if (status != INIT_STATE &&
  78987. status != EXTRA_STATE &&
  78988. status != NAME_STATE &&
  78989. status != COMMENT_STATE &&
  78990. status != HCRC_STATE &&
  78991. status != BUSY_STATE &&
  78992. status != FINISH_STATE) {
  78993. return Z_STREAM_ERROR;
  78994. }
  78995. /* Deallocate in reverse order of allocations: */
  78996. TRY_FREE(strm, strm->state->pending_buf);
  78997. TRY_FREE(strm, strm->state->head);
  78998. TRY_FREE(strm, strm->state->prev);
  78999. TRY_FREE(strm, strm->state->window);
  79000. ZFREE(strm, strm->state);
  79001. strm->state = Z_NULL;
  79002. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  79003. }
  79004. /* =========================================================================
  79005. * Copy the source state to the destination state.
  79006. * To simplify the source, this is not supported for 16-bit MSDOS (which
  79007. * doesn't have enough memory anyway to duplicate compression states).
  79008. */
  79009. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  79010. {
  79011. #ifdef MAXSEG_64K
  79012. return Z_STREAM_ERROR;
  79013. #else
  79014. deflate_state *ds;
  79015. deflate_state *ss;
  79016. ushf *overlay;
  79017. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  79018. return Z_STREAM_ERROR;
  79019. }
  79020. ss = source->state;
  79021. zmemcpy(dest, source, sizeof(z_stream));
  79022. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  79023. if (ds == Z_NULL) return Z_MEM_ERROR;
  79024. dest->state = (struct internal_state FAR *) ds;
  79025. zmemcpy(ds, ss, sizeof(deflate_state));
  79026. ds->strm = dest;
  79027. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  79028. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  79029. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  79030. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  79031. ds->pending_buf = (uchf *) overlay;
  79032. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  79033. ds->pending_buf == Z_NULL) {
  79034. deflateEnd (dest);
  79035. return Z_MEM_ERROR;
  79036. }
  79037. /* following zmemcpy do not work for 16-bit MSDOS */
  79038. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  79039. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  79040. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  79041. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  79042. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  79043. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  79044. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  79045. ds->l_desc.dyn_tree = ds->dyn_ltree;
  79046. ds->d_desc.dyn_tree = ds->dyn_dtree;
  79047. ds->bl_desc.dyn_tree = ds->bl_tree;
  79048. return Z_OK;
  79049. #endif /* MAXSEG_64K */
  79050. }
  79051. /* ===========================================================================
  79052. * Read a new buffer from the current input stream, update the adler32
  79053. * and total number of bytes read. All deflate() input goes through
  79054. * this function so some applications may wish to modify it to avoid
  79055. * allocating a large strm->next_in buffer and copying from it.
  79056. * (See also flush_pending()).
  79057. */
  79058. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  79059. {
  79060. unsigned len = strm->avail_in;
  79061. if (len > size) len = size;
  79062. if (len == 0) return 0;
  79063. strm->avail_in -= len;
  79064. if (strm->state->wrap == 1) {
  79065. strm->adler = adler32(strm->adler, strm->next_in, len);
  79066. }
  79067. #ifdef GZIP
  79068. else if (strm->state->wrap == 2) {
  79069. strm->adler = crc32(strm->adler, strm->next_in, len);
  79070. }
  79071. #endif
  79072. zmemcpy(buf, strm->next_in, len);
  79073. strm->next_in += len;
  79074. strm->total_in += len;
  79075. return (int)len;
  79076. }
  79077. /* ===========================================================================
  79078. * Initialize the "longest match" routines for a new zlib stream
  79079. */
  79080. local void lm_init (deflate_state *s)
  79081. {
  79082. s->window_size = (ulg)2L*s->w_size;
  79083. CLEAR_HASH(s);
  79084. /* Set the default configuration parameters:
  79085. */
  79086. s->max_lazy_match = configuration_table[s->level].max_lazy;
  79087. s->good_match = configuration_table[s->level].good_length;
  79088. s->nice_match = configuration_table[s->level].nice_length;
  79089. s->max_chain_length = configuration_table[s->level].max_chain;
  79090. s->strstart = 0;
  79091. s->block_start = 0L;
  79092. s->lookahead = 0;
  79093. s->match_length = s->prev_length = MIN_MATCH-1;
  79094. s->match_available = 0;
  79095. s->ins_h = 0;
  79096. #ifndef FASTEST
  79097. #ifdef ASMV
  79098. match_init(); /* initialize the asm code */
  79099. #endif
  79100. #endif
  79101. }
  79102. #ifndef FASTEST
  79103. /* ===========================================================================
  79104. * Set match_start to the longest match starting at the given string and
  79105. * return its length. Matches shorter or equal to prev_length are discarded,
  79106. * in which case the result is equal to prev_length and match_start is
  79107. * garbage.
  79108. * IN assertions: cur_match is the head of the hash chain for the current
  79109. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  79110. * OUT assertion: the match length is not greater than s->lookahead.
  79111. */
  79112. #ifndef ASMV
  79113. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  79114. * match.S. The code will be functionally equivalent.
  79115. */
  79116. local uInt longest_match(deflate_state *s, IPos cur_match)
  79117. {
  79118. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  79119. register Bytef *scan = s->window + s->strstart; /* current string */
  79120. register Bytef *match; /* matched string */
  79121. register int len; /* length of current match */
  79122. int best_len = s->prev_length; /* best match length so far */
  79123. int nice_match = s->nice_match; /* stop if match long enough */
  79124. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  79125. s->strstart - (IPos)MAX_DIST(s) : NIL;
  79126. /* Stop when cur_match becomes <= limit. To simplify the code,
  79127. * we prevent matches with the string of window index 0.
  79128. */
  79129. Posf *prev = s->prev;
  79130. uInt wmask = s->w_mask;
  79131. #ifdef UNALIGNED_OK
  79132. /* Compare two bytes at a time. Note: this is not always beneficial.
  79133. * Try with and without -DUNALIGNED_OK to check.
  79134. */
  79135. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  79136. register ush scan_start = *(ushf*)scan;
  79137. register ush scan_end = *(ushf*)(scan+best_len-1);
  79138. #else
  79139. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  79140. register Byte scan_end1 = scan[best_len-1];
  79141. register Byte scan_end = scan[best_len];
  79142. #endif
  79143. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  79144. * It is easy to get rid of this optimization if necessary.
  79145. */
  79146. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  79147. /* Do not waste too much time if we already have a good match: */
  79148. if (s->prev_length >= s->good_match) {
  79149. chain_length >>= 2;
  79150. }
  79151. /* Do not look for matches beyond the end of the input. This is necessary
  79152. * to make deflate deterministic.
  79153. */
  79154. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  79155. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  79156. do {
  79157. Assert(cur_match < s->strstart, "no future");
  79158. match = s->window + cur_match;
  79159. /* Skip to next match if the match length cannot increase
  79160. * or if the match length is less than 2. Note that the checks below
  79161. * for insufficient lookahead only occur occasionally for performance
  79162. * reasons. Therefore uninitialized memory will be accessed, and
  79163. * conditional jumps will be made that depend on those values.
  79164. * However the length of the match is limited to the lookahead, so
  79165. * the output of deflate is not affected by the uninitialized values.
  79166. */
  79167. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  79168. /* This code assumes sizeof(unsigned short) == 2. Do not use
  79169. * UNALIGNED_OK if your compiler uses a different size.
  79170. */
  79171. if (*(ushf*)(match+best_len-1) != scan_end ||
  79172. *(ushf*)match != scan_start) continue;
  79173. /* It is not necessary to compare scan[2] and match[2] since they are
  79174. * always equal when the other bytes match, given that the hash keys
  79175. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  79176. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  79177. * lookahead only every 4th comparison; the 128th check will be made
  79178. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  79179. * necessary to put more guard bytes at the end of the window, or
  79180. * to check more often for insufficient lookahead.
  79181. */
  79182. Assert(scan[2] == match[2], "scan[2]?");
  79183. scan++, match++;
  79184. do {
  79185. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  79186. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  79187. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  79188. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  79189. scan < strend);
  79190. /* The funny "do {}" generates better code on most compilers */
  79191. /* Here, scan <= window+strstart+257 */
  79192. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  79193. if (*scan == *match) scan++;
  79194. len = (MAX_MATCH - 1) - (int)(strend-scan);
  79195. scan = strend - (MAX_MATCH-1);
  79196. #else /* UNALIGNED_OK */
  79197. if (match[best_len] != scan_end ||
  79198. match[best_len-1] != scan_end1 ||
  79199. *match != *scan ||
  79200. *++match != scan[1]) continue;
  79201. /* The check at best_len-1 can be removed because it will be made
  79202. * again later. (This heuristic is not always a win.)
  79203. * It is not necessary to compare scan[2] and match[2] since they
  79204. * are always equal when the other bytes match, given that
  79205. * the hash keys are equal and that HASH_BITS >= 8.
  79206. */
  79207. scan += 2, match++;
  79208. Assert(*scan == *match, "match[2]?");
  79209. /* We check for insufficient lookahead only every 8th comparison;
  79210. * the 256th check will be made at strstart+258.
  79211. */
  79212. do {
  79213. } while (*++scan == *++match && *++scan == *++match &&
  79214. *++scan == *++match && *++scan == *++match &&
  79215. *++scan == *++match && *++scan == *++match &&
  79216. *++scan == *++match && *++scan == *++match &&
  79217. scan < strend);
  79218. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  79219. len = MAX_MATCH - (int)(strend - scan);
  79220. scan = strend - MAX_MATCH;
  79221. #endif /* UNALIGNED_OK */
  79222. if (len > best_len) {
  79223. s->match_start = cur_match;
  79224. best_len = len;
  79225. if (len >= nice_match) break;
  79226. #ifdef UNALIGNED_OK
  79227. scan_end = *(ushf*)(scan+best_len-1);
  79228. #else
  79229. scan_end1 = scan[best_len-1];
  79230. scan_end = scan[best_len];
  79231. #endif
  79232. }
  79233. } while ((cur_match = prev[cur_match & wmask]) > limit
  79234. && --chain_length != 0);
  79235. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  79236. return s->lookahead;
  79237. }
  79238. #endif /* ASMV */
  79239. #endif /* FASTEST */
  79240. /* ---------------------------------------------------------------------------
  79241. * Optimized version for level == 1 or strategy == Z_RLE only
  79242. */
  79243. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  79244. {
  79245. register Bytef *scan = s->window + s->strstart; /* current string */
  79246. register Bytef *match; /* matched string */
  79247. register int len; /* length of current match */
  79248. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  79249. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  79250. * It is easy to get rid of this optimization if necessary.
  79251. */
  79252. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  79253. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  79254. Assert(cur_match < s->strstart, "no future");
  79255. match = s->window + cur_match;
  79256. /* Return failure if the match length is less than 2:
  79257. */
  79258. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  79259. /* The check at best_len-1 can be removed because it will be made
  79260. * again later. (This heuristic is not always a win.)
  79261. * It is not necessary to compare scan[2] and match[2] since they
  79262. * are always equal when the other bytes match, given that
  79263. * the hash keys are equal and that HASH_BITS >= 8.
  79264. */
  79265. scan += 2, match += 2;
  79266. Assert(*scan == *match, "match[2]?");
  79267. /* We check for insufficient lookahead only every 8th comparison;
  79268. * the 256th check will be made at strstart+258.
  79269. */
  79270. do {
  79271. } while (*++scan == *++match && *++scan == *++match &&
  79272. *++scan == *++match && *++scan == *++match &&
  79273. *++scan == *++match && *++scan == *++match &&
  79274. *++scan == *++match && *++scan == *++match &&
  79275. scan < strend);
  79276. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  79277. len = MAX_MATCH - (int)(strend - scan);
  79278. if (len < MIN_MATCH) return MIN_MATCH - 1;
  79279. s->match_start = cur_match;
  79280. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  79281. }
  79282. #ifdef DEBUG
  79283. /* ===========================================================================
  79284. * Check that the match at match_start is indeed a match.
  79285. */
  79286. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  79287. {
  79288. /* check that the match is indeed a match */
  79289. if (zmemcmp(s->window + match,
  79290. s->window + start, length) != EQUAL) {
  79291. fprintf(stderr, " start %u, match %u, length %d\n",
  79292. start, match, length);
  79293. do {
  79294. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  79295. } while (--length != 0);
  79296. z_error("invalid match");
  79297. }
  79298. if (z_verbose > 1) {
  79299. fprintf(stderr,"\\[%d,%d]", start-match, length);
  79300. do { putc(s->window[start++], stderr); } while (--length != 0);
  79301. }
  79302. }
  79303. #else
  79304. # define check_match(s, start, match, length)
  79305. #endif /* DEBUG */
  79306. /* ===========================================================================
  79307. * Fill the window when the lookahead becomes insufficient.
  79308. * Updates strstart and lookahead.
  79309. *
  79310. * IN assertion: lookahead < MIN_LOOKAHEAD
  79311. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  79312. * At least one byte has been read, or avail_in == 0; reads are
  79313. * performed for at least two bytes (required for the zip translate_eol
  79314. * option -- not supported here).
  79315. */
  79316. local void fill_window (deflate_state *s)
  79317. {
  79318. register unsigned n, m;
  79319. register Posf *p;
  79320. unsigned more; /* Amount of free space at the end of the window. */
  79321. uInt wsize = s->w_size;
  79322. do {
  79323. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  79324. /* Deal with !@#$% 64K limit: */
  79325. if (sizeof(int) <= 2) {
  79326. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  79327. more = wsize;
  79328. } else if (more == (unsigned)(-1)) {
  79329. /* Very unlikely, but possible on 16 bit machine if
  79330. * strstart == 0 && lookahead == 1 (input done a byte at time)
  79331. */
  79332. more--;
  79333. }
  79334. }
  79335. /* If the window is almost full and there is insufficient lookahead,
  79336. * move the upper half to the lower one to make room in the upper half.
  79337. */
  79338. if (s->strstart >= wsize+MAX_DIST(s)) {
  79339. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  79340. s->match_start -= wsize;
  79341. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  79342. s->block_start -= (long) wsize;
  79343. /* Slide the hash table (could be avoided with 32 bit values
  79344. at the expense of memory usage). We slide even when level == 0
  79345. to keep the hash table consistent if we switch back to level > 0
  79346. later. (Using level 0 permanently is not an optimal usage of
  79347. zlib, so we don't care about this pathological case.)
  79348. */
  79349. /* %%% avoid this when Z_RLE */
  79350. n = s->hash_size;
  79351. p = &s->head[n];
  79352. do {
  79353. m = *--p;
  79354. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  79355. } while (--n);
  79356. n = wsize;
  79357. #ifndef FASTEST
  79358. p = &s->prev[n];
  79359. do {
  79360. m = *--p;
  79361. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  79362. /* If n is not on any hash chain, prev[n] is garbage but
  79363. * its value will never be used.
  79364. */
  79365. } while (--n);
  79366. #endif
  79367. more += wsize;
  79368. }
  79369. if (s->strm->avail_in == 0) return;
  79370. /* If there was no sliding:
  79371. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  79372. * more == window_size - lookahead - strstart
  79373. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  79374. * => more >= window_size - 2*WSIZE + 2
  79375. * In the BIG_MEM or MMAP case (not yet supported),
  79376. * window_size == input_size + MIN_LOOKAHEAD &&
  79377. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  79378. * Otherwise, window_size == 2*WSIZE so more >= 2.
  79379. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  79380. */
  79381. Assert(more >= 2, "more < 2");
  79382. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  79383. s->lookahead += n;
  79384. /* Initialize the hash value now that we have some input: */
  79385. if (s->lookahead >= MIN_MATCH) {
  79386. s->ins_h = s->window[s->strstart];
  79387. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  79388. #if MIN_MATCH != 3
  79389. Call UPDATE_HASH() MIN_MATCH-3 more times
  79390. #endif
  79391. }
  79392. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  79393. * but this is not important since only literal bytes will be emitted.
  79394. */
  79395. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  79396. }
  79397. /* ===========================================================================
  79398. * Flush the current block, with given end-of-file flag.
  79399. * IN assertion: strstart is set to the end of the current match.
  79400. */
  79401. #define FLUSH_BLOCK_ONLY(s, eof) { \
  79402. _tr_flush_block(s, (s->block_start >= 0L ? \
  79403. (charf *)&s->window[(unsigned)s->block_start] : \
  79404. (charf *)Z_NULL), \
  79405. (ulg)((long)s->strstart - s->block_start), \
  79406. (eof)); \
  79407. s->block_start = s->strstart; \
  79408. flush_pending(s->strm); \
  79409. Tracev((stderr,"[FLUSH]")); \
  79410. }
  79411. /* Same but force premature exit if necessary. */
  79412. #define FLUSH_BLOCK(s, eof) { \
  79413. FLUSH_BLOCK_ONLY(s, eof); \
  79414. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  79415. }
  79416. /* ===========================================================================
  79417. * Copy without compression as much as possible from the input stream, return
  79418. * the current block state.
  79419. * This function does not insert new strings in the dictionary since
  79420. * uncompressible data is probably not useful. This function is used
  79421. * only for the level=0 compression option.
  79422. * NOTE: this function should be optimized to avoid extra copying from
  79423. * window to pending_buf.
  79424. */
  79425. local block_state deflate_stored(deflate_state *s, int flush)
  79426. {
  79427. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  79428. * to pending_buf_size, and each stored block has a 5 byte header:
  79429. */
  79430. ulg max_block_size = 0xffff;
  79431. ulg max_start;
  79432. if (max_block_size > s->pending_buf_size - 5) {
  79433. max_block_size = s->pending_buf_size - 5;
  79434. }
  79435. /* Copy as much as possible from input to output: */
  79436. for (;;) {
  79437. /* Fill the window as much as possible: */
  79438. if (s->lookahead <= 1) {
  79439. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  79440. s->block_start >= (long)s->w_size, "slide too late");
  79441. fill_window(s);
  79442. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  79443. if (s->lookahead == 0) break; /* flush the current block */
  79444. }
  79445. Assert(s->block_start >= 0L, "block gone");
  79446. s->strstart += s->lookahead;
  79447. s->lookahead = 0;
  79448. /* Emit a stored block if pending_buf will be full: */
  79449. max_start = s->block_start + max_block_size;
  79450. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  79451. /* strstart == 0 is possible when wraparound on 16-bit machine */
  79452. s->lookahead = (uInt)(s->strstart - max_start);
  79453. s->strstart = (uInt)max_start;
  79454. FLUSH_BLOCK(s, 0);
  79455. }
  79456. /* Flush if we may have to slide, otherwise block_start may become
  79457. * negative and the data will be gone:
  79458. */
  79459. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  79460. FLUSH_BLOCK(s, 0);
  79461. }
  79462. }
  79463. FLUSH_BLOCK(s, flush == Z_FINISH);
  79464. return flush == Z_FINISH ? finish_done : block_done;
  79465. }
  79466. /* ===========================================================================
  79467. * Compress as much as possible from the input stream, return the current
  79468. * block state.
  79469. * This function does not perform lazy evaluation of matches and inserts
  79470. * new strings in the dictionary only for unmatched strings or for short
  79471. * matches. It is used only for the fast compression options.
  79472. */
  79473. local block_state deflate_fast(deflate_state *s, int flush)
  79474. {
  79475. IPos hash_head = NIL; /* head of the hash chain */
  79476. int bflush; /* set if current block must be flushed */
  79477. for (;;) {
  79478. /* Make sure that we always have enough lookahead, except
  79479. * at the end of the input file. We need MAX_MATCH bytes
  79480. * for the next match, plus MIN_MATCH bytes to insert the
  79481. * string following the next match.
  79482. */
  79483. if (s->lookahead < MIN_LOOKAHEAD) {
  79484. fill_window(s);
  79485. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  79486. return need_more;
  79487. }
  79488. if (s->lookahead == 0) break; /* flush the current block */
  79489. }
  79490. /* Insert the string window[strstart .. strstart+2] in the
  79491. * dictionary, and set hash_head to the head of the hash chain:
  79492. */
  79493. if (s->lookahead >= MIN_MATCH) {
  79494. INSERT_STRING(s, s->strstart, hash_head);
  79495. }
  79496. /* Find the longest match, discarding those <= prev_length.
  79497. * At this point we have always match_length < MIN_MATCH
  79498. */
  79499. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  79500. /* To simplify the code, we prevent matches with the string
  79501. * of window index 0 (in particular we have to avoid a match
  79502. * of the string with itself at the start of the input file).
  79503. */
  79504. #ifdef FASTEST
  79505. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  79506. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  79507. s->match_length = longest_match_fast (s, hash_head);
  79508. }
  79509. #else
  79510. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  79511. s->match_length = longest_match (s, hash_head);
  79512. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  79513. s->match_length = longest_match_fast (s, hash_head);
  79514. }
  79515. #endif
  79516. /* longest_match() or longest_match_fast() sets match_start */
  79517. }
  79518. if (s->match_length >= MIN_MATCH) {
  79519. check_match(s, s->strstart, s->match_start, s->match_length);
  79520. _tr_tally_dist(s, s->strstart - s->match_start,
  79521. s->match_length - MIN_MATCH, bflush);
  79522. s->lookahead -= s->match_length;
  79523. /* Insert new strings in the hash table only if the match length
  79524. * is not too large. This saves time but degrades compression.
  79525. */
  79526. #ifndef FASTEST
  79527. if (s->match_length <= s->max_insert_length &&
  79528. s->lookahead >= MIN_MATCH) {
  79529. s->match_length--; /* string at strstart already in table */
  79530. do {
  79531. s->strstart++;
  79532. INSERT_STRING(s, s->strstart, hash_head);
  79533. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  79534. * always MIN_MATCH bytes ahead.
  79535. */
  79536. } while (--s->match_length != 0);
  79537. s->strstart++;
  79538. } else
  79539. #endif
  79540. {
  79541. s->strstart += s->match_length;
  79542. s->match_length = 0;
  79543. s->ins_h = s->window[s->strstart];
  79544. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  79545. #if MIN_MATCH != 3
  79546. Call UPDATE_HASH() MIN_MATCH-3 more times
  79547. #endif
  79548. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  79549. * matter since it will be recomputed at next deflate call.
  79550. */
  79551. }
  79552. } else {
  79553. /* No match, output a literal byte */
  79554. Tracevv((stderr,"%c", s->window[s->strstart]));
  79555. _tr_tally_lit (s, s->window[s->strstart], bflush);
  79556. s->lookahead--;
  79557. s->strstart++;
  79558. }
  79559. if (bflush) FLUSH_BLOCK(s, 0);
  79560. }
  79561. FLUSH_BLOCK(s, flush == Z_FINISH);
  79562. return flush == Z_FINISH ? finish_done : block_done;
  79563. }
  79564. #ifndef FASTEST
  79565. /* ===========================================================================
  79566. * Same as above, but achieves better compression. We use a lazy
  79567. * evaluation for matches: a match is finally adopted only if there is
  79568. * no better match at the next window position.
  79569. */
  79570. local block_state deflate_slow(deflate_state *s, int flush)
  79571. {
  79572. IPos hash_head = NIL; /* head of hash chain */
  79573. int bflush; /* set if current block must be flushed */
  79574. /* Process the input block. */
  79575. for (;;) {
  79576. /* Make sure that we always have enough lookahead, except
  79577. * at the end of the input file. We need MAX_MATCH bytes
  79578. * for the next match, plus MIN_MATCH bytes to insert the
  79579. * string following the next match.
  79580. */
  79581. if (s->lookahead < MIN_LOOKAHEAD) {
  79582. fill_window(s);
  79583. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  79584. return need_more;
  79585. }
  79586. if (s->lookahead == 0) break; /* flush the current block */
  79587. }
  79588. /* Insert the string window[strstart .. strstart+2] in the
  79589. * dictionary, and set hash_head to the head of the hash chain:
  79590. */
  79591. if (s->lookahead >= MIN_MATCH) {
  79592. INSERT_STRING(s, s->strstart, hash_head);
  79593. }
  79594. /* Find the longest match, discarding those <= prev_length.
  79595. */
  79596. s->prev_length = s->match_length, s->prev_match = s->match_start;
  79597. s->match_length = MIN_MATCH-1;
  79598. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  79599. s->strstart - hash_head <= MAX_DIST(s)) {
  79600. /* To simplify the code, we prevent matches with the string
  79601. * of window index 0 (in particular we have to avoid a match
  79602. * of the string with itself at the start of the input file).
  79603. */
  79604. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  79605. s->match_length = longest_match (s, hash_head);
  79606. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  79607. s->match_length = longest_match_fast (s, hash_head);
  79608. }
  79609. /* longest_match() or longest_match_fast() sets match_start */
  79610. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  79611. #if TOO_FAR <= 32767
  79612. || (s->match_length == MIN_MATCH &&
  79613. s->strstart - s->match_start > TOO_FAR)
  79614. #endif
  79615. )) {
  79616. /* If prev_match is also MIN_MATCH, match_start is garbage
  79617. * but we will ignore the current match anyway.
  79618. */
  79619. s->match_length = MIN_MATCH-1;
  79620. }
  79621. }
  79622. /* If there was a match at the previous step and the current
  79623. * match is not better, output the previous match:
  79624. */
  79625. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  79626. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  79627. /* Do not insert strings in hash table beyond this. */
  79628. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  79629. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  79630. s->prev_length - MIN_MATCH, bflush);
  79631. /* Insert in hash table all strings up to the end of the match.
  79632. * strstart-1 and strstart are already inserted. If there is not
  79633. * enough lookahead, the last two strings are not inserted in
  79634. * the hash table.
  79635. */
  79636. s->lookahead -= s->prev_length-1;
  79637. s->prev_length -= 2;
  79638. do {
  79639. if (++s->strstart <= max_insert) {
  79640. INSERT_STRING(s, s->strstart, hash_head);
  79641. }
  79642. } while (--s->prev_length != 0);
  79643. s->match_available = 0;
  79644. s->match_length = MIN_MATCH-1;
  79645. s->strstart++;
  79646. if (bflush) FLUSH_BLOCK(s, 0);
  79647. } else if (s->match_available) {
  79648. /* If there was no match at the previous position, output a
  79649. * single literal. If there was a match but the current match
  79650. * is longer, truncate the previous match to a single literal.
  79651. */
  79652. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  79653. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  79654. if (bflush) {
  79655. FLUSH_BLOCK_ONLY(s, 0);
  79656. }
  79657. s->strstart++;
  79658. s->lookahead--;
  79659. if (s->strm->avail_out == 0) return need_more;
  79660. } else {
  79661. /* There is no previous match to compare with, wait for
  79662. * the next step to decide.
  79663. */
  79664. s->match_available = 1;
  79665. s->strstart++;
  79666. s->lookahead--;
  79667. }
  79668. }
  79669. Assert (flush != Z_NO_FLUSH, "no flush?");
  79670. if (s->match_available) {
  79671. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  79672. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  79673. s->match_available = 0;
  79674. }
  79675. FLUSH_BLOCK(s, flush == Z_FINISH);
  79676. return flush == Z_FINISH ? finish_done : block_done;
  79677. }
  79678. #endif /* FASTEST */
  79679. #if 0
  79680. /* ===========================================================================
  79681. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  79682. * one. Do not maintain a hash table. (It will be regenerated if this run of
  79683. * deflate switches away from Z_RLE.)
  79684. */
  79685. local block_state deflate_rle(s, flush)
  79686. deflate_state *s;
  79687. int flush;
  79688. {
  79689. int bflush; /* set if current block must be flushed */
  79690. uInt run; /* length of run */
  79691. uInt max; /* maximum length of run */
  79692. uInt prev; /* byte at distance one to match */
  79693. Bytef *scan; /* scan for end of run */
  79694. for (;;) {
  79695. /* Make sure that we always have enough lookahead, except
  79696. * at the end of the input file. We need MAX_MATCH bytes
  79697. * for the longest encodable run.
  79698. */
  79699. if (s->lookahead < MAX_MATCH) {
  79700. fill_window(s);
  79701. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  79702. return need_more;
  79703. }
  79704. if (s->lookahead == 0) break; /* flush the current block */
  79705. }
  79706. /* See how many times the previous byte repeats */
  79707. run = 0;
  79708. if (s->strstart > 0) { /* if there is a previous byte, that is */
  79709. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  79710. scan = s->window + s->strstart - 1;
  79711. prev = *scan++;
  79712. do {
  79713. if (*scan++ != prev)
  79714. break;
  79715. } while (++run < max);
  79716. }
  79717. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  79718. if (run >= MIN_MATCH) {
  79719. check_match(s, s->strstart, s->strstart - 1, run);
  79720. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  79721. s->lookahead -= run;
  79722. s->strstart += run;
  79723. } else {
  79724. /* No match, output a literal byte */
  79725. Tracevv((stderr,"%c", s->window[s->strstart]));
  79726. _tr_tally_lit (s, s->window[s->strstart], bflush);
  79727. s->lookahead--;
  79728. s->strstart++;
  79729. }
  79730. if (bflush) FLUSH_BLOCK(s, 0);
  79731. }
  79732. FLUSH_BLOCK(s, flush == Z_FINISH);
  79733. return flush == Z_FINISH ? finish_done : block_done;
  79734. }
  79735. #endif
  79736. /*** End of inlined file: deflate.c ***/
  79737. /*** Start of inlined file: inffast.c ***/
  79738. /*** Start of inlined file: inftrees.h ***/
  79739. /* WARNING: this file should *not* be used by applications. It is
  79740. part of the implementation of the compression library and is
  79741. subject to change. Applications should only use zlib.h.
  79742. */
  79743. #ifndef _INFTREES_H_
  79744. #define _INFTREES_H_
  79745. /* Structure for decoding tables. Each entry provides either the
  79746. information needed to do the operation requested by the code that
  79747. indexed that table entry, or it provides a pointer to another
  79748. table that indexes more bits of the code. op indicates whether
  79749. the entry is a pointer to another table, a literal, a length or
  79750. distance, an end-of-block, or an invalid code. For a table
  79751. pointer, the low four bits of op is the number of index bits of
  79752. that table. For a length or distance, the low four bits of op
  79753. is the number of extra bits to get after the code. bits is
  79754. the number of bits in this code or part of the code to drop off
  79755. of the bit buffer. val is the actual byte to output in the case
  79756. of a literal, the base length or distance, or the offset from
  79757. the current table to the next table. Each entry is four bytes. */
  79758. typedef struct {
  79759. unsigned char op; /* operation, extra bits, table bits */
  79760. unsigned char bits; /* bits in this part of the code */
  79761. unsigned short val; /* offset in table or code value */
  79762. } code;
  79763. /* op values as set by inflate_table():
  79764. 00000000 - literal
  79765. 0000tttt - table link, tttt != 0 is the number of table index bits
  79766. 0001eeee - length or distance, eeee is the number of extra bits
  79767. 01100000 - end of block
  79768. 01000000 - invalid code
  79769. */
  79770. /* Maximum size of dynamic tree. The maximum found in a long but non-
  79771. exhaustive search was 1444 code structures (852 for length/literals
  79772. and 592 for distances, the latter actually the result of an
  79773. exhaustive search). The true maximum is not known, but the value
  79774. below is more than safe. */
  79775. #define ENOUGH 2048
  79776. #define MAXD 592
  79777. /* Type of code to build for inftable() */
  79778. typedef enum {
  79779. CODES,
  79780. LENS,
  79781. DISTS
  79782. } codetype;
  79783. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  79784. unsigned codes, code FAR * FAR *table,
  79785. unsigned FAR *bits, unsigned short FAR *work));
  79786. #endif
  79787. /*** End of inlined file: inftrees.h ***/
  79788. /*** Start of inlined file: inflate.h ***/
  79789. /* WARNING: this file should *not* be used by applications. It is
  79790. part of the implementation of the compression library and is
  79791. subject to change. Applications should only use zlib.h.
  79792. */
  79793. #ifndef _INFLATE_H_
  79794. #define _INFLATE_H_
  79795. /* define NO_GZIP when compiling if you want to disable gzip header and
  79796. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  79797. the crc code when it is not needed. For shared libraries, gzip decoding
  79798. should be left enabled. */
  79799. #ifndef NO_GZIP
  79800. # define GUNZIP
  79801. #endif
  79802. /* Possible inflate modes between inflate() calls */
  79803. typedef enum {
  79804. HEAD, /* i: waiting for magic header */
  79805. FLAGS, /* i: waiting for method and flags (gzip) */
  79806. TIME, /* i: waiting for modification time (gzip) */
  79807. OS, /* i: waiting for extra flags and operating system (gzip) */
  79808. EXLEN, /* i: waiting for extra length (gzip) */
  79809. EXTRA, /* i: waiting for extra bytes (gzip) */
  79810. NAME, /* i: waiting for end of file name (gzip) */
  79811. COMMENT, /* i: waiting for end of comment (gzip) */
  79812. HCRC, /* i: waiting for header crc (gzip) */
  79813. DICTID, /* i: waiting for dictionary check value */
  79814. DICT, /* waiting for inflateSetDictionary() call */
  79815. TYPE, /* i: waiting for type bits, including last-flag bit */
  79816. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  79817. STORED, /* i: waiting for stored size (length and complement) */
  79818. COPY, /* i/o: waiting for input or output to copy stored block */
  79819. TABLE, /* i: waiting for dynamic block table lengths */
  79820. LENLENS, /* i: waiting for code length code lengths */
  79821. CODELENS, /* i: waiting for length/lit and distance code lengths */
  79822. LEN, /* i: waiting for length/lit code */
  79823. LENEXT, /* i: waiting for length extra bits */
  79824. DIST, /* i: waiting for distance code */
  79825. DISTEXT, /* i: waiting for distance extra bits */
  79826. MATCH, /* o: waiting for output space to copy string */
  79827. LIT, /* o: waiting for output space to write literal */
  79828. CHECK, /* i: waiting for 32-bit check value */
  79829. LENGTH, /* i: waiting for 32-bit length (gzip) */
  79830. DONE, /* finished check, done -- remain here until reset */
  79831. BAD, /* got a data error -- remain here until reset */
  79832. MEM, /* got an inflate() memory error -- remain here until reset */
  79833. SYNC /* looking for synchronization bytes to restart inflate() */
  79834. } inflate_mode;
  79835. /*
  79836. State transitions between above modes -
  79837. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  79838. Process header:
  79839. HEAD -> (gzip) or (zlib)
  79840. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  79841. NAME -> COMMENT -> HCRC -> TYPE
  79842. (zlib) -> DICTID or TYPE
  79843. DICTID -> DICT -> TYPE
  79844. Read deflate blocks:
  79845. TYPE -> STORED or TABLE or LEN or CHECK
  79846. STORED -> COPY -> TYPE
  79847. TABLE -> LENLENS -> CODELENS -> LEN
  79848. Read deflate codes:
  79849. LEN -> LENEXT or LIT or TYPE
  79850. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  79851. LIT -> LEN
  79852. Process trailer:
  79853. CHECK -> LENGTH -> DONE
  79854. */
  79855. /* state maintained between inflate() calls. Approximately 7K bytes. */
  79856. struct inflate_state {
  79857. inflate_mode mode; /* current inflate mode */
  79858. int last; /* true if processing last block */
  79859. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  79860. int havedict; /* true if dictionary provided */
  79861. int flags; /* gzip header method and flags (0 if zlib) */
  79862. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  79863. unsigned long check; /* protected copy of check value */
  79864. unsigned long total; /* protected copy of output count */
  79865. gz_headerp head; /* where to save gzip header information */
  79866. /* sliding window */
  79867. unsigned wbits; /* log base 2 of requested window size */
  79868. unsigned wsize; /* window size or zero if not using window */
  79869. unsigned whave; /* valid bytes in the window */
  79870. unsigned write; /* window write index */
  79871. unsigned char FAR *window; /* allocated sliding window, if needed */
  79872. /* bit accumulator */
  79873. unsigned long hold; /* input bit accumulator */
  79874. unsigned bits; /* number of bits in "in" */
  79875. /* for string and stored block copying */
  79876. unsigned length; /* literal or length of data to copy */
  79877. unsigned offset; /* distance back to copy string from */
  79878. /* for table and code decoding */
  79879. unsigned extra; /* extra bits needed */
  79880. /* fixed and dynamic code tables */
  79881. code const FAR *lencode; /* starting table for length/literal codes */
  79882. code const FAR *distcode; /* starting table for distance codes */
  79883. unsigned lenbits; /* index bits for lencode */
  79884. unsigned distbits; /* index bits for distcode */
  79885. /* dynamic table building */
  79886. unsigned ncode; /* number of code length code lengths */
  79887. unsigned nlen; /* number of length code lengths */
  79888. unsigned ndist; /* number of distance code lengths */
  79889. unsigned have; /* number of code lengths in lens[] */
  79890. code FAR *next; /* next available space in codes[] */
  79891. unsigned short lens[320]; /* temporary storage for code lengths */
  79892. unsigned short work[288]; /* work area for code table building */
  79893. code codes[ENOUGH]; /* space for code tables */
  79894. };
  79895. #endif
  79896. /*** End of inlined file: inflate.h ***/
  79897. /*** Start of inlined file: inffast.h ***/
  79898. /* WARNING: this file should *not* be used by applications. It is
  79899. part of the implementation of the compression library and is
  79900. subject to change. Applications should only use zlib.h.
  79901. */
  79902. void inflate_fast OF((z_streamp strm, unsigned start));
  79903. /*** End of inlined file: inffast.h ***/
  79904. #ifndef ASMINF
  79905. /* Allow machine dependent optimization for post-increment or pre-increment.
  79906. Based on testing to date,
  79907. Pre-increment preferred for:
  79908. - PowerPC G3 (Adler)
  79909. - MIPS R5000 (Randers-Pehrson)
  79910. Post-increment preferred for:
  79911. - none
  79912. No measurable difference:
  79913. - Pentium III (Anderson)
  79914. - M68060 (Nikl)
  79915. */
  79916. #ifdef POSTINC
  79917. # define OFF 0
  79918. # define PUP(a) *(a)++
  79919. #else
  79920. # define OFF 1
  79921. # define PUP(a) *++(a)
  79922. #endif
  79923. /*
  79924. Decode literal, length, and distance codes and write out the resulting
  79925. literal and match bytes until either not enough input or output is
  79926. available, an end-of-block is encountered, or a data error is encountered.
  79927. When large enough input and output buffers are supplied to inflate(), for
  79928. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  79929. inflate execution time is spent in this routine.
  79930. Entry assumptions:
  79931. state->mode == LEN
  79932. strm->avail_in >= 6
  79933. strm->avail_out >= 258
  79934. start >= strm->avail_out
  79935. state->bits < 8
  79936. On return, state->mode is one of:
  79937. LEN -- ran out of enough output space or enough available input
  79938. TYPE -- reached end of block code, inflate() to interpret next block
  79939. BAD -- error in block data
  79940. Notes:
  79941. - The maximum input bits used by a length/distance pair is 15 bits for the
  79942. length code, 5 bits for the length extra, 15 bits for the distance code,
  79943. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  79944. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  79945. checking for available input while decoding.
  79946. - The maximum bytes that a single length/distance pair can output is 258
  79947. bytes, which is the maximum length that can be coded. inflate_fast()
  79948. requires strm->avail_out >= 258 for each loop to avoid checking for
  79949. output space.
  79950. */
  79951. void inflate_fast (z_streamp strm, unsigned start)
  79952. {
  79953. struct inflate_state FAR *state;
  79954. unsigned char FAR *in; /* local strm->next_in */
  79955. unsigned char FAR *last; /* while in < last, enough input available */
  79956. unsigned char FAR *out; /* local strm->next_out */
  79957. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  79958. unsigned char FAR *end; /* while out < end, enough space available */
  79959. #ifdef INFLATE_STRICT
  79960. unsigned dmax; /* maximum distance from zlib header */
  79961. #endif
  79962. unsigned wsize; /* window size or zero if not using window */
  79963. unsigned whave; /* valid bytes in the window */
  79964. unsigned write; /* window write index */
  79965. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  79966. unsigned long hold; /* local strm->hold */
  79967. unsigned bits; /* local strm->bits */
  79968. code const FAR *lcode; /* local strm->lencode */
  79969. code const FAR *dcode; /* local strm->distcode */
  79970. unsigned lmask; /* mask for first level of length codes */
  79971. unsigned dmask; /* mask for first level of distance codes */
  79972. code thisx; /* retrieved table entry */
  79973. unsigned op; /* code bits, operation, extra bits, or */
  79974. /* window position, window bytes to copy */
  79975. unsigned len; /* match length, unused bytes */
  79976. unsigned dist; /* match distance */
  79977. unsigned char FAR *from; /* where to copy match from */
  79978. /* copy state to local variables */
  79979. state = (struct inflate_state FAR *)strm->state;
  79980. in = strm->next_in - OFF;
  79981. last = in + (strm->avail_in - 5);
  79982. out = strm->next_out - OFF;
  79983. beg = out - (start - strm->avail_out);
  79984. end = out + (strm->avail_out - 257);
  79985. #ifdef INFLATE_STRICT
  79986. dmax = state->dmax;
  79987. #endif
  79988. wsize = state->wsize;
  79989. whave = state->whave;
  79990. write = state->write;
  79991. window = state->window;
  79992. hold = state->hold;
  79993. bits = state->bits;
  79994. lcode = state->lencode;
  79995. dcode = state->distcode;
  79996. lmask = (1U << state->lenbits) - 1;
  79997. dmask = (1U << state->distbits) - 1;
  79998. /* decode literals and length/distances until end-of-block or not enough
  79999. input data or output space */
  80000. do {
  80001. if (bits < 15) {
  80002. hold += (unsigned long)(PUP(in)) << bits;
  80003. bits += 8;
  80004. hold += (unsigned long)(PUP(in)) << bits;
  80005. bits += 8;
  80006. }
  80007. thisx = lcode[hold & lmask];
  80008. dolen:
  80009. op = (unsigned)(thisx.bits);
  80010. hold >>= op;
  80011. bits -= op;
  80012. op = (unsigned)(thisx.op);
  80013. if (op == 0) { /* literal */
  80014. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  80015. "inflate: literal '%c'\n" :
  80016. "inflate: literal 0x%02x\n", thisx.val));
  80017. PUP(out) = (unsigned char)(thisx.val);
  80018. }
  80019. else if (op & 16) { /* length base */
  80020. len = (unsigned)(thisx.val);
  80021. op &= 15; /* number of extra bits */
  80022. if (op) {
  80023. if (bits < op) {
  80024. hold += (unsigned long)(PUP(in)) << bits;
  80025. bits += 8;
  80026. }
  80027. len += (unsigned)hold & ((1U << op) - 1);
  80028. hold >>= op;
  80029. bits -= op;
  80030. }
  80031. Tracevv((stderr, "inflate: length %u\n", len));
  80032. if (bits < 15) {
  80033. hold += (unsigned long)(PUP(in)) << bits;
  80034. bits += 8;
  80035. hold += (unsigned long)(PUP(in)) << bits;
  80036. bits += 8;
  80037. }
  80038. thisx = dcode[hold & dmask];
  80039. dodist:
  80040. op = (unsigned)(thisx.bits);
  80041. hold >>= op;
  80042. bits -= op;
  80043. op = (unsigned)(thisx.op);
  80044. if (op & 16) { /* distance base */
  80045. dist = (unsigned)(thisx.val);
  80046. op &= 15; /* number of extra bits */
  80047. if (bits < op) {
  80048. hold += (unsigned long)(PUP(in)) << bits;
  80049. bits += 8;
  80050. if (bits < op) {
  80051. hold += (unsigned long)(PUP(in)) << bits;
  80052. bits += 8;
  80053. }
  80054. }
  80055. dist += (unsigned)hold & ((1U << op) - 1);
  80056. #ifdef INFLATE_STRICT
  80057. if (dist > dmax) {
  80058. strm->msg = (char *)"invalid distance too far back";
  80059. state->mode = BAD;
  80060. break;
  80061. }
  80062. #endif
  80063. hold >>= op;
  80064. bits -= op;
  80065. Tracevv((stderr, "inflate: distance %u\n", dist));
  80066. op = (unsigned)(out - beg); /* max distance in output */
  80067. if (dist > op) { /* see if copy from window */
  80068. op = dist - op; /* distance back in window */
  80069. if (op > whave) {
  80070. strm->msg = (char *)"invalid distance too far back";
  80071. state->mode = BAD;
  80072. break;
  80073. }
  80074. from = window - OFF;
  80075. if (write == 0) { /* very common case */
  80076. from += wsize - op;
  80077. if (op < len) { /* some from window */
  80078. len -= op;
  80079. do {
  80080. PUP(out) = PUP(from);
  80081. } while (--op);
  80082. from = out - dist; /* rest from output */
  80083. }
  80084. }
  80085. else if (write < op) { /* wrap around window */
  80086. from += wsize + write - op;
  80087. op -= write;
  80088. if (op < len) { /* some from end of window */
  80089. len -= op;
  80090. do {
  80091. PUP(out) = PUP(from);
  80092. } while (--op);
  80093. from = window - OFF;
  80094. if (write < len) { /* some from start of window */
  80095. op = write;
  80096. len -= op;
  80097. do {
  80098. PUP(out) = PUP(from);
  80099. } while (--op);
  80100. from = out - dist; /* rest from output */
  80101. }
  80102. }
  80103. }
  80104. else { /* contiguous in window */
  80105. from += write - op;
  80106. if (op < len) { /* some from window */
  80107. len -= op;
  80108. do {
  80109. PUP(out) = PUP(from);
  80110. } while (--op);
  80111. from = out - dist; /* rest from output */
  80112. }
  80113. }
  80114. while (len > 2) {
  80115. PUP(out) = PUP(from);
  80116. PUP(out) = PUP(from);
  80117. PUP(out) = PUP(from);
  80118. len -= 3;
  80119. }
  80120. if (len) {
  80121. PUP(out) = PUP(from);
  80122. if (len > 1)
  80123. PUP(out) = PUP(from);
  80124. }
  80125. }
  80126. else {
  80127. from = out - dist; /* copy direct from output */
  80128. do { /* minimum length is three */
  80129. PUP(out) = PUP(from);
  80130. PUP(out) = PUP(from);
  80131. PUP(out) = PUP(from);
  80132. len -= 3;
  80133. } while (len > 2);
  80134. if (len) {
  80135. PUP(out) = PUP(from);
  80136. if (len > 1)
  80137. PUP(out) = PUP(from);
  80138. }
  80139. }
  80140. }
  80141. else if ((op & 64) == 0) { /* 2nd level distance code */
  80142. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  80143. goto dodist;
  80144. }
  80145. else {
  80146. strm->msg = (char *)"invalid distance code";
  80147. state->mode = BAD;
  80148. break;
  80149. }
  80150. }
  80151. else if ((op & 64) == 0) { /* 2nd level length code */
  80152. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  80153. goto dolen;
  80154. }
  80155. else if (op & 32) { /* end-of-block */
  80156. Tracevv((stderr, "inflate: end of block\n"));
  80157. state->mode = TYPE;
  80158. break;
  80159. }
  80160. else {
  80161. strm->msg = (char *)"invalid literal/length code";
  80162. state->mode = BAD;
  80163. break;
  80164. }
  80165. } while (in < last && out < end);
  80166. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  80167. len = bits >> 3;
  80168. in -= len;
  80169. bits -= len << 3;
  80170. hold &= (1U << bits) - 1;
  80171. /* update state and return */
  80172. strm->next_in = in + OFF;
  80173. strm->next_out = out + OFF;
  80174. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  80175. strm->avail_out = (unsigned)(out < end ?
  80176. 257 + (end - out) : 257 - (out - end));
  80177. state->hold = hold;
  80178. state->bits = bits;
  80179. return;
  80180. }
  80181. /*
  80182. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  80183. - Using bit fields for code structure
  80184. - Different op definition to avoid & for extra bits (do & for table bits)
  80185. - Three separate decoding do-loops for direct, window, and write == 0
  80186. - Special case for distance > 1 copies to do overlapped load and store copy
  80187. - Explicit branch predictions (based on measured branch probabilities)
  80188. - Deferring match copy and interspersed it with decoding subsequent codes
  80189. - Swapping literal/length else
  80190. - Swapping window/direct else
  80191. - Larger unrolled copy loops (three is about right)
  80192. - Moving len -= 3 statement into middle of loop
  80193. */
  80194. #endif /* !ASMINF */
  80195. /*** End of inlined file: inffast.c ***/
  80196. #undef PULLBYTE
  80197. #undef LOAD
  80198. #undef RESTORE
  80199. #undef INITBITS
  80200. #undef NEEDBITS
  80201. #undef DROPBITS
  80202. #undef BYTEBITS
  80203. /*** Start of inlined file: inflate.c ***/
  80204. /*
  80205. * Change history:
  80206. *
  80207. * 1.2.beta0 24 Nov 2002
  80208. * - First version -- complete rewrite of inflate to simplify code, avoid
  80209. * creation of window when not needed, minimize use of window when it is
  80210. * needed, make inffast.c even faster, implement gzip decoding, and to
  80211. * improve code readability and style over the previous zlib inflate code
  80212. *
  80213. * 1.2.beta1 25 Nov 2002
  80214. * - Use pointers for available input and output checking in inffast.c
  80215. * - Remove input and output counters in inffast.c
  80216. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  80217. * - Remove unnecessary second byte pull from length extra in inffast.c
  80218. * - Unroll direct copy to three copies per loop in inffast.c
  80219. *
  80220. * 1.2.beta2 4 Dec 2002
  80221. * - Change external routine names to reduce potential conflicts
  80222. * - Correct filename to inffixed.h for fixed tables in inflate.c
  80223. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  80224. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  80225. * to avoid negation problem on Alphas (64 bit) in inflate.c
  80226. *
  80227. * 1.2.beta3 22 Dec 2002
  80228. * - Add comments on state->bits assertion in inffast.c
  80229. * - Add comments on op field in inftrees.h
  80230. * - Fix bug in reuse of allocated window after inflateReset()
  80231. * - Remove bit fields--back to byte structure for speed
  80232. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  80233. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  80234. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  80235. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  80236. * - Use local copies of stream next and avail values, as well as local bit
  80237. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  80238. *
  80239. * 1.2.beta4 1 Jan 2003
  80240. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  80241. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  80242. * - Add comments in inffast.c to introduce the inflate_fast() routine
  80243. * - Rearrange window copies in inflate_fast() for speed and simplification
  80244. * - Unroll last copy for window match in inflate_fast()
  80245. * - Use local copies of window variables in inflate_fast() for speed
  80246. * - Pull out common write == 0 case for speed in inflate_fast()
  80247. * - Make op and len in inflate_fast() unsigned for consistency
  80248. * - Add FAR to lcode and dcode declarations in inflate_fast()
  80249. * - Simplified bad distance check in inflate_fast()
  80250. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  80251. * source file infback.c to provide a call-back interface to inflate for
  80252. * programs like gzip and unzip -- uses window as output buffer to avoid
  80253. * window copying
  80254. *
  80255. * 1.2.beta5 1 Jan 2003
  80256. * - Improved inflateBack() interface to allow the caller to provide initial
  80257. * input in strm.
  80258. * - Fixed stored blocks bug in inflateBack()
  80259. *
  80260. * 1.2.beta6 4 Jan 2003
  80261. * - Added comments in inffast.c on effectiveness of POSTINC
  80262. * - Typecasting all around to reduce compiler warnings
  80263. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  80264. * make compilers happy
  80265. * - Changed type of window in inflateBackInit() to unsigned char *
  80266. *
  80267. * 1.2.beta7 27 Jan 2003
  80268. * - Changed many types to unsigned or unsigned short to avoid warnings
  80269. * - Added inflateCopy() function
  80270. *
  80271. * 1.2.0 9 Mar 2003
  80272. * - Changed inflateBack() interface to provide separate opaque descriptors
  80273. * for the in() and out() functions
  80274. * - Changed inflateBack() argument and in_func typedef to swap the length
  80275. * and buffer address return values for the input function
  80276. * - Check next_in and next_out for Z_NULL on entry to inflate()
  80277. *
  80278. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  80279. */
  80280. /*** Start of inlined file: inffast.h ***/
  80281. /* WARNING: this file should *not* be used by applications. It is
  80282. part of the implementation of the compression library and is
  80283. subject to change. Applications should only use zlib.h.
  80284. */
  80285. void inflate_fast OF((z_streamp strm, unsigned start));
  80286. /*** End of inlined file: inffast.h ***/
  80287. #ifdef MAKEFIXED
  80288. # ifndef BUILDFIXED
  80289. # define BUILDFIXED
  80290. # endif
  80291. #endif
  80292. /* function prototypes */
  80293. local void fixedtables OF((struct inflate_state FAR *state));
  80294. local int updatewindow OF((z_streamp strm, unsigned out));
  80295. #ifdef BUILDFIXED
  80296. void makefixed OF((void));
  80297. #endif
  80298. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  80299. unsigned len));
  80300. int ZEXPORT inflateReset (z_streamp strm)
  80301. {
  80302. struct inflate_state FAR *state;
  80303. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80304. state = (struct inflate_state FAR *)strm->state;
  80305. strm->total_in = strm->total_out = state->total = 0;
  80306. strm->msg = Z_NULL;
  80307. strm->adler = 1; /* to support ill-conceived Java test suite */
  80308. state->mode = HEAD;
  80309. state->last = 0;
  80310. state->havedict = 0;
  80311. state->dmax = 32768U;
  80312. state->head = Z_NULL;
  80313. state->wsize = 0;
  80314. state->whave = 0;
  80315. state->write = 0;
  80316. state->hold = 0;
  80317. state->bits = 0;
  80318. state->lencode = state->distcode = state->next = state->codes;
  80319. Tracev((stderr, "inflate: reset\n"));
  80320. return Z_OK;
  80321. }
  80322. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  80323. {
  80324. struct inflate_state FAR *state;
  80325. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80326. state = (struct inflate_state FAR *)strm->state;
  80327. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  80328. value &= (1L << bits) - 1;
  80329. state->hold += value << state->bits;
  80330. state->bits += bits;
  80331. return Z_OK;
  80332. }
  80333. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  80334. {
  80335. struct inflate_state FAR *state;
  80336. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  80337. stream_size != (int)(sizeof(z_stream)))
  80338. return Z_VERSION_ERROR;
  80339. if (strm == Z_NULL) return Z_STREAM_ERROR;
  80340. strm->msg = Z_NULL; /* in case we return an error */
  80341. if (strm->zalloc == (alloc_func)0) {
  80342. strm->zalloc = zcalloc;
  80343. strm->opaque = (voidpf)0;
  80344. }
  80345. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  80346. state = (struct inflate_state FAR *)
  80347. ZALLOC(strm, 1, sizeof(struct inflate_state));
  80348. if (state == Z_NULL) return Z_MEM_ERROR;
  80349. Tracev((stderr, "inflate: allocated\n"));
  80350. strm->state = (struct internal_state FAR *)state;
  80351. if (windowBits < 0) {
  80352. state->wrap = 0;
  80353. windowBits = -windowBits;
  80354. }
  80355. else {
  80356. state->wrap = (windowBits >> 4) + 1;
  80357. #ifdef GUNZIP
  80358. if (windowBits < 48) windowBits &= 15;
  80359. #endif
  80360. }
  80361. if (windowBits < 8 || windowBits > 15) {
  80362. ZFREE(strm, state);
  80363. strm->state = Z_NULL;
  80364. return Z_STREAM_ERROR;
  80365. }
  80366. state->wbits = (unsigned)windowBits;
  80367. state->window = Z_NULL;
  80368. return inflateReset(strm);
  80369. }
  80370. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  80371. {
  80372. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  80373. }
  80374. /*
  80375. Return state with length and distance decoding tables and index sizes set to
  80376. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  80377. If BUILDFIXED is defined, then instead this routine builds the tables the
  80378. first time it's called, and returns those tables the first time and
  80379. thereafter. This reduces the size of the code by about 2K bytes, in
  80380. exchange for a little execution time. However, BUILDFIXED should not be
  80381. used for threaded applications, since the rewriting of the tables and virgin
  80382. may not be thread-safe.
  80383. */
  80384. local void fixedtables (struct inflate_state FAR *state)
  80385. {
  80386. #ifdef BUILDFIXED
  80387. static int virgin = 1;
  80388. static code *lenfix, *distfix;
  80389. static code fixed[544];
  80390. /* build fixed huffman tables if first call (may not be thread safe) */
  80391. if (virgin) {
  80392. unsigned sym, bits;
  80393. static code *next;
  80394. /* literal/length table */
  80395. sym = 0;
  80396. while (sym < 144) state->lens[sym++] = 8;
  80397. while (sym < 256) state->lens[sym++] = 9;
  80398. while (sym < 280) state->lens[sym++] = 7;
  80399. while (sym < 288) state->lens[sym++] = 8;
  80400. next = fixed;
  80401. lenfix = next;
  80402. bits = 9;
  80403. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  80404. /* distance table */
  80405. sym = 0;
  80406. while (sym < 32) state->lens[sym++] = 5;
  80407. distfix = next;
  80408. bits = 5;
  80409. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  80410. /* do this just once */
  80411. virgin = 0;
  80412. }
  80413. #else /* !BUILDFIXED */
  80414. /*** Start of inlined file: inffixed.h ***/
  80415. /* WARNING: this file should *not* be used by applications. It
  80416. is part of the implementation of the compression library and
  80417. is subject to change. Applications should only use zlib.h.
  80418. */
  80419. static const code lenfix[512] = {
  80420. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  80421. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  80422. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  80423. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  80424. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  80425. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  80426. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  80427. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  80428. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  80429. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  80430. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  80431. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  80432. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  80433. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  80434. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  80435. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  80436. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  80437. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  80438. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  80439. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  80440. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  80441. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  80442. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  80443. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  80444. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  80445. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  80446. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  80447. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  80448. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  80449. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  80450. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  80451. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  80452. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  80453. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  80454. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  80455. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  80456. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  80457. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  80458. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  80459. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  80460. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  80461. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  80462. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  80463. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  80464. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  80465. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  80466. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  80467. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  80468. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  80469. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  80470. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  80471. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  80472. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  80473. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  80474. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  80475. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  80476. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  80477. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  80478. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  80479. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  80480. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  80481. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  80482. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  80483. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  80484. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  80485. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  80486. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  80487. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  80488. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  80489. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  80490. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  80491. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  80492. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  80493. {0,9,255}
  80494. };
  80495. static const code distfix[32] = {
  80496. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  80497. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  80498. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  80499. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  80500. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  80501. {22,5,193},{64,5,0}
  80502. };
  80503. /*** End of inlined file: inffixed.h ***/
  80504. #endif /* BUILDFIXED */
  80505. state->lencode = lenfix;
  80506. state->lenbits = 9;
  80507. state->distcode = distfix;
  80508. state->distbits = 5;
  80509. }
  80510. #ifdef MAKEFIXED
  80511. #include <stdio.h>
  80512. /*
  80513. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  80514. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  80515. those tables to stdout, which would be piped to inffixed.h. A small program
  80516. can simply call makefixed to do this:
  80517. void makefixed(void);
  80518. int main(void)
  80519. {
  80520. makefixed();
  80521. return 0;
  80522. }
  80523. Then that can be linked with zlib built with MAKEFIXED defined and run:
  80524. a.out > inffixed.h
  80525. */
  80526. void makefixed()
  80527. {
  80528. unsigned low, size;
  80529. struct inflate_state state;
  80530. fixedtables(&state);
  80531. puts(" /* inffixed.h -- table for decoding fixed codes");
  80532. puts(" * Generated automatically by makefixed().");
  80533. puts(" */");
  80534. puts("");
  80535. puts(" /* WARNING: this file should *not* be used by applications.");
  80536. puts(" It is part of the implementation of this library and is");
  80537. puts(" subject to change. Applications should only use zlib.h.");
  80538. puts(" */");
  80539. puts("");
  80540. size = 1U << 9;
  80541. printf(" static const code lenfix[%u] = {", size);
  80542. low = 0;
  80543. for (;;) {
  80544. if ((low % 7) == 0) printf("\n ");
  80545. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  80546. state.lencode[low].val);
  80547. if (++low == size) break;
  80548. putchar(',');
  80549. }
  80550. puts("\n };");
  80551. size = 1U << 5;
  80552. printf("\n static const code distfix[%u] = {", size);
  80553. low = 0;
  80554. for (;;) {
  80555. if ((low % 6) == 0) printf("\n ");
  80556. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  80557. state.distcode[low].val);
  80558. if (++low == size) break;
  80559. putchar(',');
  80560. }
  80561. puts("\n };");
  80562. }
  80563. #endif /* MAKEFIXED */
  80564. /*
  80565. Update the window with the last wsize (normally 32K) bytes written before
  80566. returning. If window does not exist yet, create it. This is only called
  80567. when a window is already in use, or when output has been written during this
  80568. inflate call, but the end of the deflate stream has not been reached yet.
  80569. It is also called to create a window for dictionary data when a dictionary
  80570. is loaded.
  80571. Providing output buffers larger than 32K to inflate() should provide a speed
  80572. advantage, since only the last 32K of output is copied to the sliding window
  80573. upon return from inflate(), and since all distances after the first 32K of
  80574. output will fall in the output data, making match copies simpler and faster.
  80575. The advantage may be dependent on the size of the processor's data caches.
  80576. */
  80577. local int updatewindow (z_streamp strm, unsigned out)
  80578. {
  80579. struct inflate_state FAR *state;
  80580. unsigned copy, dist;
  80581. state = (struct inflate_state FAR *)strm->state;
  80582. /* if it hasn't been done already, allocate space for the window */
  80583. if (state->window == Z_NULL) {
  80584. state->window = (unsigned char FAR *)
  80585. ZALLOC(strm, 1U << state->wbits,
  80586. sizeof(unsigned char));
  80587. if (state->window == Z_NULL) return 1;
  80588. }
  80589. /* if window not in use yet, initialize */
  80590. if (state->wsize == 0) {
  80591. state->wsize = 1U << state->wbits;
  80592. state->write = 0;
  80593. state->whave = 0;
  80594. }
  80595. /* copy state->wsize or less output bytes into the circular window */
  80596. copy = out - strm->avail_out;
  80597. if (copy >= state->wsize) {
  80598. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  80599. state->write = 0;
  80600. state->whave = state->wsize;
  80601. }
  80602. else {
  80603. dist = state->wsize - state->write;
  80604. if (dist > copy) dist = copy;
  80605. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  80606. copy -= dist;
  80607. if (copy) {
  80608. zmemcpy(state->window, strm->next_out - copy, copy);
  80609. state->write = copy;
  80610. state->whave = state->wsize;
  80611. }
  80612. else {
  80613. state->write += dist;
  80614. if (state->write == state->wsize) state->write = 0;
  80615. if (state->whave < state->wsize) state->whave += dist;
  80616. }
  80617. }
  80618. return 0;
  80619. }
  80620. /* Macros for inflate(): */
  80621. /* check function to use adler32() for zlib or crc32() for gzip */
  80622. #ifdef GUNZIP
  80623. # define UPDATE(check, buf, len) \
  80624. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  80625. #else
  80626. # define UPDATE(check, buf, len) adler32(check, buf, len)
  80627. #endif
  80628. /* check macros for header crc */
  80629. #ifdef GUNZIP
  80630. # define CRC2(check, word) \
  80631. do { \
  80632. hbuf[0] = (unsigned char)(word); \
  80633. hbuf[1] = (unsigned char)((word) >> 8); \
  80634. check = crc32(check, hbuf, 2); \
  80635. } while (0)
  80636. # define CRC4(check, word) \
  80637. do { \
  80638. hbuf[0] = (unsigned char)(word); \
  80639. hbuf[1] = (unsigned char)((word) >> 8); \
  80640. hbuf[2] = (unsigned char)((word) >> 16); \
  80641. hbuf[3] = (unsigned char)((word) >> 24); \
  80642. check = crc32(check, hbuf, 4); \
  80643. } while (0)
  80644. #endif
  80645. /* Load registers with state in inflate() for speed */
  80646. #define LOAD() \
  80647. do { \
  80648. put = strm->next_out; \
  80649. left = strm->avail_out; \
  80650. next = strm->next_in; \
  80651. have = strm->avail_in; \
  80652. hold = state->hold; \
  80653. bits = state->bits; \
  80654. } while (0)
  80655. /* Restore state from registers in inflate() */
  80656. #define RESTORE() \
  80657. do { \
  80658. strm->next_out = put; \
  80659. strm->avail_out = left; \
  80660. strm->next_in = next; \
  80661. strm->avail_in = have; \
  80662. state->hold = hold; \
  80663. state->bits = bits; \
  80664. } while (0)
  80665. /* Clear the input bit accumulator */
  80666. #define INITBITS() \
  80667. do { \
  80668. hold = 0; \
  80669. bits = 0; \
  80670. } while (0)
  80671. /* Get a byte of input into the bit accumulator, or return from inflate()
  80672. if there is no input available. */
  80673. #define PULLBYTE() \
  80674. do { \
  80675. if (have == 0) goto inf_leave; \
  80676. have--; \
  80677. hold += (unsigned long)(*next++) << bits; \
  80678. bits += 8; \
  80679. } while (0)
  80680. /* Assure that there are at least n bits in the bit accumulator. If there is
  80681. not enough available input to do that, then return from inflate(). */
  80682. #define NEEDBITS(n) \
  80683. do { \
  80684. while (bits < (unsigned)(n)) \
  80685. PULLBYTE(); \
  80686. } while (0)
  80687. /* Return the low n bits of the bit accumulator (n < 16) */
  80688. #define BITS(n) \
  80689. ((unsigned)hold & ((1U << (n)) - 1))
  80690. /* Remove n bits from the bit accumulator */
  80691. #define DROPBITS(n) \
  80692. do { \
  80693. hold >>= (n); \
  80694. bits -= (unsigned)(n); \
  80695. } while (0)
  80696. /* Remove zero to seven bits as needed to go to a byte boundary */
  80697. #define BYTEBITS() \
  80698. do { \
  80699. hold >>= bits & 7; \
  80700. bits -= bits & 7; \
  80701. } while (0)
  80702. /* Reverse the bytes in a 32-bit value */
  80703. #define REVERSE(q) \
  80704. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  80705. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  80706. /*
  80707. inflate() uses a state machine to process as much input data and generate as
  80708. much output data as possible before returning. The state machine is
  80709. structured roughly as follows:
  80710. for (;;) switch (state) {
  80711. ...
  80712. case STATEn:
  80713. if (not enough input data or output space to make progress)
  80714. return;
  80715. ... make progress ...
  80716. state = STATEm;
  80717. break;
  80718. ...
  80719. }
  80720. so when inflate() is called again, the same case is attempted again, and
  80721. if the appropriate resources are provided, the machine proceeds to the
  80722. next state. The NEEDBITS() macro is usually the way the state evaluates
  80723. whether it can proceed or should return. NEEDBITS() does the return if
  80724. the requested bits are not available. The typical use of the BITS macros
  80725. is:
  80726. NEEDBITS(n);
  80727. ... do something with BITS(n) ...
  80728. DROPBITS(n);
  80729. where NEEDBITS(n) either returns from inflate() if there isn't enough
  80730. input left to load n bits into the accumulator, or it continues. BITS(n)
  80731. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  80732. the low n bits off the accumulator. INITBITS() clears the accumulator
  80733. and sets the number of available bits to zero. BYTEBITS() discards just
  80734. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  80735. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  80736. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  80737. if there is no input available. The decoding of variable length codes uses
  80738. PULLBYTE() directly in order to pull just enough bytes to decode the next
  80739. code, and no more.
  80740. Some states loop until they get enough input, making sure that enough
  80741. state information is maintained to continue the loop where it left off
  80742. if NEEDBITS() returns in the loop. For example, want, need, and keep
  80743. would all have to actually be part of the saved state in case NEEDBITS()
  80744. returns:
  80745. case STATEw:
  80746. while (want < need) {
  80747. NEEDBITS(n);
  80748. keep[want++] = BITS(n);
  80749. DROPBITS(n);
  80750. }
  80751. state = STATEx;
  80752. case STATEx:
  80753. As shown above, if the next state is also the next case, then the break
  80754. is omitted.
  80755. A state may also return if there is not enough output space available to
  80756. complete that state. Those states are copying stored data, writing a
  80757. literal byte, and copying a matching string.
  80758. When returning, a "goto inf_leave" is used to update the total counters,
  80759. update the check value, and determine whether any progress has been made
  80760. during that inflate() call in order to return the proper return code.
  80761. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  80762. When there is a window, goto inf_leave will update the window with the last
  80763. output written. If a goto inf_leave occurs in the middle of decompression
  80764. and there is no window currently, goto inf_leave will create one and copy
  80765. output to the window for the next call of inflate().
  80766. In this implementation, the flush parameter of inflate() only affects the
  80767. return code (per zlib.h). inflate() always writes as much as possible to
  80768. strm->next_out, given the space available and the provided input--the effect
  80769. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  80770. the allocation of and copying into a sliding window until necessary, which
  80771. provides the effect documented in zlib.h for Z_FINISH when the entire input
  80772. stream available. So the only thing the flush parameter actually does is:
  80773. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  80774. will return Z_BUF_ERROR if it has not reached the end of the stream.
  80775. */
  80776. int ZEXPORT inflate (z_streamp strm, int flush)
  80777. {
  80778. struct inflate_state FAR *state;
  80779. unsigned char FAR *next; /* next input */
  80780. unsigned char FAR *put; /* next output */
  80781. unsigned have, left; /* available input and output */
  80782. unsigned long hold; /* bit buffer */
  80783. unsigned bits; /* bits in bit buffer */
  80784. unsigned in, out; /* save starting available input and output */
  80785. unsigned copy; /* number of stored or match bytes to copy */
  80786. unsigned char FAR *from; /* where to copy match bytes from */
  80787. code thisx; /* current decoding table entry */
  80788. code last; /* parent table entry */
  80789. unsigned len; /* length to copy for repeats, bits to drop */
  80790. int ret; /* return code */
  80791. #ifdef GUNZIP
  80792. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  80793. #endif
  80794. static const unsigned short order[19] = /* permutation of code lengths */
  80795. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  80796. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  80797. (strm->next_in == Z_NULL && strm->avail_in != 0))
  80798. return Z_STREAM_ERROR;
  80799. state = (struct inflate_state FAR *)strm->state;
  80800. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  80801. LOAD();
  80802. in = have;
  80803. out = left;
  80804. ret = Z_OK;
  80805. for (;;)
  80806. switch (state->mode) {
  80807. case HEAD:
  80808. if (state->wrap == 0) {
  80809. state->mode = TYPEDO;
  80810. break;
  80811. }
  80812. NEEDBITS(16);
  80813. #ifdef GUNZIP
  80814. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  80815. state->check = crc32(0L, Z_NULL, 0);
  80816. CRC2(state->check, hold);
  80817. INITBITS();
  80818. state->mode = FLAGS;
  80819. break;
  80820. }
  80821. state->flags = 0; /* expect zlib header */
  80822. if (state->head != Z_NULL)
  80823. state->head->done = -1;
  80824. if (!(state->wrap & 1) || /* check if zlib header allowed */
  80825. #else
  80826. if (
  80827. #endif
  80828. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  80829. strm->msg = (char *)"incorrect header check";
  80830. state->mode = BAD;
  80831. break;
  80832. }
  80833. if (BITS(4) != Z_DEFLATED) {
  80834. strm->msg = (char *)"unknown compression method";
  80835. state->mode = BAD;
  80836. break;
  80837. }
  80838. DROPBITS(4);
  80839. len = BITS(4) + 8;
  80840. if (len > state->wbits) {
  80841. strm->msg = (char *)"invalid window size";
  80842. state->mode = BAD;
  80843. break;
  80844. }
  80845. state->dmax = 1U << len;
  80846. Tracev((stderr, "inflate: zlib header ok\n"));
  80847. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  80848. state->mode = hold & 0x200 ? DICTID : TYPE;
  80849. INITBITS();
  80850. break;
  80851. #ifdef GUNZIP
  80852. case FLAGS:
  80853. NEEDBITS(16);
  80854. state->flags = (int)(hold);
  80855. if ((state->flags & 0xff) != Z_DEFLATED) {
  80856. strm->msg = (char *)"unknown compression method";
  80857. state->mode = BAD;
  80858. break;
  80859. }
  80860. if (state->flags & 0xe000) {
  80861. strm->msg = (char *)"unknown header flags set";
  80862. state->mode = BAD;
  80863. break;
  80864. }
  80865. if (state->head != Z_NULL)
  80866. state->head->text = (int)((hold >> 8) & 1);
  80867. if (state->flags & 0x0200) CRC2(state->check, hold);
  80868. INITBITS();
  80869. state->mode = TIME;
  80870. case TIME:
  80871. NEEDBITS(32);
  80872. if (state->head != Z_NULL)
  80873. state->head->time = hold;
  80874. if (state->flags & 0x0200) CRC4(state->check, hold);
  80875. INITBITS();
  80876. state->mode = OS;
  80877. case OS:
  80878. NEEDBITS(16);
  80879. if (state->head != Z_NULL) {
  80880. state->head->xflags = (int)(hold & 0xff);
  80881. state->head->os = (int)(hold >> 8);
  80882. }
  80883. if (state->flags & 0x0200) CRC2(state->check, hold);
  80884. INITBITS();
  80885. state->mode = EXLEN;
  80886. case EXLEN:
  80887. if (state->flags & 0x0400) {
  80888. NEEDBITS(16);
  80889. state->length = (unsigned)(hold);
  80890. if (state->head != Z_NULL)
  80891. state->head->extra_len = (unsigned)hold;
  80892. if (state->flags & 0x0200) CRC2(state->check, hold);
  80893. INITBITS();
  80894. }
  80895. else if (state->head != Z_NULL)
  80896. state->head->extra = Z_NULL;
  80897. state->mode = EXTRA;
  80898. case EXTRA:
  80899. if (state->flags & 0x0400) {
  80900. copy = state->length;
  80901. if (copy > have) copy = have;
  80902. if (copy) {
  80903. if (state->head != Z_NULL &&
  80904. state->head->extra != Z_NULL) {
  80905. len = state->head->extra_len - state->length;
  80906. zmemcpy(state->head->extra + len, next,
  80907. len + copy > state->head->extra_max ?
  80908. state->head->extra_max - len : copy);
  80909. }
  80910. if (state->flags & 0x0200)
  80911. state->check = crc32(state->check, next, copy);
  80912. have -= copy;
  80913. next += copy;
  80914. state->length -= copy;
  80915. }
  80916. if (state->length) goto inf_leave;
  80917. }
  80918. state->length = 0;
  80919. state->mode = NAME;
  80920. case NAME:
  80921. if (state->flags & 0x0800) {
  80922. if (have == 0) goto inf_leave;
  80923. copy = 0;
  80924. do {
  80925. len = (unsigned)(next[copy++]);
  80926. if (state->head != Z_NULL &&
  80927. state->head->name != Z_NULL &&
  80928. state->length < state->head->name_max)
  80929. state->head->name[state->length++] = len;
  80930. } while (len && copy < have);
  80931. if (state->flags & 0x0200)
  80932. state->check = crc32(state->check, next, copy);
  80933. have -= copy;
  80934. next += copy;
  80935. if (len) goto inf_leave;
  80936. }
  80937. else if (state->head != Z_NULL)
  80938. state->head->name = Z_NULL;
  80939. state->length = 0;
  80940. state->mode = COMMENT;
  80941. case COMMENT:
  80942. if (state->flags & 0x1000) {
  80943. if (have == 0) goto inf_leave;
  80944. copy = 0;
  80945. do {
  80946. len = (unsigned)(next[copy++]);
  80947. if (state->head != Z_NULL &&
  80948. state->head->comment != Z_NULL &&
  80949. state->length < state->head->comm_max)
  80950. state->head->comment[state->length++] = len;
  80951. } while (len && copy < have);
  80952. if (state->flags & 0x0200)
  80953. state->check = crc32(state->check, next, copy);
  80954. have -= copy;
  80955. next += copy;
  80956. if (len) goto inf_leave;
  80957. }
  80958. else if (state->head != Z_NULL)
  80959. state->head->comment = Z_NULL;
  80960. state->mode = HCRC;
  80961. case HCRC:
  80962. if (state->flags & 0x0200) {
  80963. NEEDBITS(16);
  80964. if (hold != (state->check & 0xffff)) {
  80965. strm->msg = (char *)"header crc mismatch";
  80966. state->mode = BAD;
  80967. break;
  80968. }
  80969. INITBITS();
  80970. }
  80971. if (state->head != Z_NULL) {
  80972. state->head->hcrc = (int)((state->flags >> 9) & 1);
  80973. state->head->done = 1;
  80974. }
  80975. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  80976. state->mode = TYPE;
  80977. break;
  80978. #endif
  80979. case DICTID:
  80980. NEEDBITS(32);
  80981. strm->adler = state->check = REVERSE(hold);
  80982. INITBITS();
  80983. state->mode = DICT;
  80984. case DICT:
  80985. if (state->havedict == 0) {
  80986. RESTORE();
  80987. return Z_NEED_DICT;
  80988. }
  80989. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  80990. state->mode = TYPE;
  80991. case TYPE:
  80992. if (flush == Z_BLOCK) goto inf_leave;
  80993. case TYPEDO:
  80994. if (state->last) {
  80995. BYTEBITS();
  80996. state->mode = CHECK;
  80997. break;
  80998. }
  80999. NEEDBITS(3);
  81000. state->last = BITS(1);
  81001. DROPBITS(1);
  81002. switch (BITS(2)) {
  81003. case 0: /* stored block */
  81004. Tracev((stderr, "inflate: stored block%s\n",
  81005. state->last ? " (last)" : ""));
  81006. state->mode = STORED;
  81007. break;
  81008. case 1: /* fixed block */
  81009. fixedtables(state);
  81010. Tracev((stderr, "inflate: fixed codes block%s\n",
  81011. state->last ? " (last)" : ""));
  81012. state->mode = LEN; /* decode codes */
  81013. break;
  81014. case 2: /* dynamic block */
  81015. Tracev((stderr, "inflate: dynamic codes block%s\n",
  81016. state->last ? " (last)" : ""));
  81017. state->mode = TABLE;
  81018. break;
  81019. case 3:
  81020. strm->msg = (char *)"invalid block type";
  81021. state->mode = BAD;
  81022. }
  81023. DROPBITS(2);
  81024. break;
  81025. case STORED:
  81026. BYTEBITS(); /* go to byte boundary */
  81027. NEEDBITS(32);
  81028. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  81029. strm->msg = (char *)"invalid stored block lengths";
  81030. state->mode = BAD;
  81031. break;
  81032. }
  81033. state->length = (unsigned)hold & 0xffff;
  81034. Tracev((stderr, "inflate: stored length %u\n",
  81035. state->length));
  81036. INITBITS();
  81037. state->mode = COPY;
  81038. case COPY:
  81039. copy = state->length;
  81040. if (copy) {
  81041. if (copy > have) copy = have;
  81042. if (copy > left) copy = left;
  81043. if (copy == 0) goto inf_leave;
  81044. zmemcpy(put, next, copy);
  81045. have -= copy;
  81046. next += copy;
  81047. left -= copy;
  81048. put += copy;
  81049. state->length -= copy;
  81050. break;
  81051. }
  81052. Tracev((stderr, "inflate: stored end\n"));
  81053. state->mode = TYPE;
  81054. break;
  81055. case TABLE:
  81056. NEEDBITS(14);
  81057. state->nlen = BITS(5) + 257;
  81058. DROPBITS(5);
  81059. state->ndist = BITS(5) + 1;
  81060. DROPBITS(5);
  81061. state->ncode = BITS(4) + 4;
  81062. DROPBITS(4);
  81063. #ifndef PKZIP_BUG_WORKAROUND
  81064. if (state->nlen > 286 || state->ndist > 30) {
  81065. strm->msg = (char *)"too many length or distance symbols";
  81066. state->mode = BAD;
  81067. break;
  81068. }
  81069. #endif
  81070. Tracev((stderr, "inflate: table sizes ok\n"));
  81071. state->have = 0;
  81072. state->mode = LENLENS;
  81073. case LENLENS:
  81074. while (state->have < state->ncode) {
  81075. NEEDBITS(3);
  81076. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  81077. DROPBITS(3);
  81078. }
  81079. while (state->have < 19)
  81080. state->lens[order[state->have++]] = 0;
  81081. state->next = state->codes;
  81082. state->lencode = (code const FAR *)(state->next);
  81083. state->lenbits = 7;
  81084. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  81085. &(state->lenbits), state->work);
  81086. if (ret) {
  81087. strm->msg = (char *)"invalid code lengths set";
  81088. state->mode = BAD;
  81089. break;
  81090. }
  81091. Tracev((stderr, "inflate: code lengths ok\n"));
  81092. state->have = 0;
  81093. state->mode = CODELENS;
  81094. case CODELENS:
  81095. while (state->have < state->nlen + state->ndist) {
  81096. for (;;) {
  81097. thisx = state->lencode[BITS(state->lenbits)];
  81098. if ((unsigned)(thisx.bits) <= bits) break;
  81099. PULLBYTE();
  81100. }
  81101. if (thisx.val < 16) {
  81102. NEEDBITS(thisx.bits);
  81103. DROPBITS(thisx.bits);
  81104. state->lens[state->have++] = thisx.val;
  81105. }
  81106. else {
  81107. if (thisx.val == 16) {
  81108. NEEDBITS(thisx.bits + 2);
  81109. DROPBITS(thisx.bits);
  81110. if (state->have == 0) {
  81111. strm->msg = (char *)"invalid bit length repeat";
  81112. state->mode = BAD;
  81113. break;
  81114. }
  81115. len = state->lens[state->have - 1];
  81116. copy = 3 + BITS(2);
  81117. DROPBITS(2);
  81118. }
  81119. else if (thisx.val == 17) {
  81120. NEEDBITS(thisx.bits + 3);
  81121. DROPBITS(thisx.bits);
  81122. len = 0;
  81123. copy = 3 + BITS(3);
  81124. DROPBITS(3);
  81125. }
  81126. else {
  81127. NEEDBITS(thisx.bits + 7);
  81128. DROPBITS(thisx.bits);
  81129. len = 0;
  81130. copy = 11 + BITS(7);
  81131. DROPBITS(7);
  81132. }
  81133. if (state->have + copy > state->nlen + state->ndist) {
  81134. strm->msg = (char *)"invalid bit length repeat";
  81135. state->mode = BAD;
  81136. break;
  81137. }
  81138. while (copy--)
  81139. state->lens[state->have++] = (unsigned short)len;
  81140. }
  81141. }
  81142. /* handle error breaks in while */
  81143. if (state->mode == BAD) break;
  81144. /* build code tables */
  81145. state->next = state->codes;
  81146. state->lencode = (code const FAR *)(state->next);
  81147. state->lenbits = 9;
  81148. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  81149. &(state->lenbits), state->work);
  81150. if (ret) {
  81151. strm->msg = (char *)"invalid literal/lengths set";
  81152. state->mode = BAD;
  81153. break;
  81154. }
  81155. state->distcode = (code const FAR *)(state->next);
  81156. state->distbits = 6;
  81157. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  81158. &(state->next), &(state->distbits), state->work);
  81159. if (ret) {
  81160. strm->msg = (char *)"invalid distances set";
  81161. state->mode = BAD;
  81162. break;
  81163. }
  81164. Tracev((stderr, "inflate: codes ok\n"));
  81165. state->mode = LEN;
  81166. case LEN:
  81167. if (have >= 6 && left >= 258) {
  81168. RESTORE();
  81169. inflate_fast(strm, out);
  81170. LOAD();
  81171. break;
  81172. }
  81173. for (;;) {
  81174. thisx = state->lencode[BITS(state->lenbits)];
  81175. if ((unsigned)(thisx.bits) <= bits) break;
  81176. PULLBYTE();
  81177. }
  81178. if (thisx.op && (thisx.op & 0xf0) == 0) {
  81179. last = thisx;
  81180. for (;;) {
  81181. thisx = state->lencode[last.val +
  81182. (BITS(last.bits + last.op) >> last.bits)];
  81183. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  81184. PULLBYTE();
  81185. }
  81186. DROPBITS(last.bits);
  81187. }
  81188. DROPBITS(thisx.bits);
  81189. state->length = (unsigned)thisx.val;
  81190. if ((int)(thisx.op) == 0) {
  81191. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  81192. "inflate: literal '%c'\n" :
  81193. "inflate: literal 0x%02x\n", thisx.val));
  81194. state->mode = LIT;
  81195. break;
  81196. }
  81197. if (thisx.op & 32) {
  81198. Tracevv((stderr, "inflate: end of block\n"));
  81199. state->mode = TYPE;
  81200. break;
  81201. }
  81202. if (thisx.op & 64) {
  81203. strm->msg = (char *)"invalid literal/length code";
  81204. state->mode = BAD;
  81205. break;
  81206. }
  81207. state->extra = (unsigned)(thisx.op) & 15;
  81208. state->mode = LENEXT;
  81209. case LENEXT:
  81210. if (state->extra) {
  81211. NEEDBITS(state->extra);
  81212. state->length += BITS(state->extra);
  81213. DROPBITS(state->extra);
  81214. }
  81215. Tracevv((stderr, "inflate: length %u\n", state->length));
  81216. state->mode = DIST;
  81217. case DIST:
  81218. for (;;) {
  81219. thisx = state->distcode[BITS(state->distbits)];
  81220. if ((unsigned)(thisx.bits) <= bits) break;
  81221. PULLBYTE();
  81222. }
  81223. if ((thisx.op & 0xf0) == 0) {
  81224. last = thisx;
  81225. for (;;) {
  81226. thisx = state->distcode[last.val +
  81227. (BITS(last.bits + last.op) >> last.bits)];
  81228. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  81229. PULLBYTE();
  81230. }
  81231. DROPBITS(last.bits);
  81232. }
  81233. DROPBITS(thisx.bits);
  81234. if (thisx.op & 64) {
  81235. strm->msg = (char *)"invalid distance code";
  81236. state->mode = BAD;
  81237. break;
  81238. }
  81239. state->offset = (unsigned)thisx.val;
  81240. state->extra = (unsigned)(thisx.op) & 15;
  81241. state->mode = DISTEXT;
  81242. case DISTEXT:
  81243. if (state->extra) {
  81244. NEEDBITS(state->extra);
  81245. state->offset += BITS(state->extra);
  81246. DROPBITS(state->extra);
  81247. }
  81248. #ifdef INFLATE_STRICT
  81249. if (state->offset > state->dmax) {
  81250. strm->msg = (char *)"invalid distance too far back";
  81251. state->mode = BAD;
  81252. break;
  81253. }
  81254. #endif
  81255. if (state->offset > state->whave + out - left) {
  81256. strm->msg = (char *)"invalid distance too far back";
  81257. state->mode = BAD;
  81258. break;
  81259. }
  81260. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  81261. state->mode = MATCH;
  81262. case MATCH:
  81263. if (left == 0) goto inf_leave;
  81264. copy = out - left;
  81265. if (state->offset > copy) { /* copy from window */
  81266. copy = state->offset - copy;
  81267. if (copy > state->write) {
  81268. copy -= state->write;
  81269. from = state->window + (state->wsize - copy);
  81270. }
  81271. else
  81272. from = state->window + (state->write - copy);
  81273. if (copy > state->length) copy = state->length;
  81274. }
  81275. else { /* copy from output */
  81276. from = put - state->offset;
  81277. copy = state->length;
  81278. }
  81279. if (copy > left) copy = left;
  81280. left -= copy;
  81281. state->length -= copy;
  81282. do {
  81283. *put++ = *from++;
  81284. } while (--copy);
  81285. if (state->length == 0) state->mode = LEN;
  81286. break;
  81287. case LIT:
  81288. if (left == 0) goto inf_leave;
  81289. *put++ = (unsigned char)(state->length);
  81290. left--;
  81291. state->mode = LEN;
  81292. break;
  81293. case CHECK:
  81294. if (state->wrap) {
  81295. NEEDBITS(32);
  81296. out -= left;
  81297. strm->total_out += out;
  81298. state->total += out;
  81299. if (out)
  81300. strm->adler = state->check =
  81301. UPDATE(state->check, put - out, out);
  81302. out = left;
  81303. if ((
  81304. #ifdef GUNZIP
  81305. state->flags ? hold :
  81306. #endif
  81307. REVERSE(hold)) != state->check) {
  81308. strm->msg = (char *)"incorrect data check";
  81309. state->mode = BAD;
  81310. break;
  81311. }
  81312. INITBITS();
  81313. Tracev((stderr, "inflate: check matches trailer\n"));
  81314. }
  81315. #ifdef GUNZIP
  81316. state->mode = LENGTH;
  81317. case LENGTH:
  81318. if (state->wrap && state->flags) {
  81319. NEEDBITS(32);
  81320. if (hold != (state->total & 0xffffffffUL)) {
  81321. strm->msg = (char *)"incorrect length check";
  81322. state->mode = BAD;
  81323. break;
  81324. }
  81325. INITBITS();
  81326. Tracev((stderr, "inflate: length matches trailer\n"));
  81327. }
  81328. #endif
  81329. state->mode = DONE;
  81330. case DONE:
  81331. ret = Z_STREAM_END;
  81332. goto inf_leave;
  81333. case BAD:
  81334. ret = Z_DATA_ERROR;
  81335. goto inf_leave;
  81336. case MEM:
  81337. return Z_MEM_ERROR;
  81338. case SYNC:
  81339. default:
  81340. return Z_STREAM_ERROR;
  81341. }
  81342. /*
  81343. Return from inflate(), updating the total counts and the check value.
  81344. If there was no progress during the inflate() call, return a buffer
  81345. error. Call updatewindow() to create and/or update the window state.
  81346. Note: a memory error from inflate() is non-recoverable.
  81347. */
  81348. inf_leave:
  81349. RESTORE();
  81350. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  81351. if (updatewindow(strm, out)) {
  81352. state->mode = MEM;
  81353. return Z_MEM_ERROR;
  81354. }
  81355. in -= strm->avail_in;
  81356. out -= strm->avail_out;
  81357. strm->total_in += in;
  81358. strm->total_out += out;
  81359. state->total += out;
  81360. if (state->wrap && out)
  81361. strm->adler = state->check =
  81362. UPDATE(state->check, strm->next_out - out, out);
  81363. strm->data_type = state->bits + (state->last ? 64 : 0) +
  81364. (state->mode == TYPE ? 128 : 0);
  81365. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  81366. ret = Z_BUF_ERROR;
  81367. return ret;
  81368. }
  81369. int ZEXPORT inflateEnd (z_streamp strm)
  81370. {
  81371. struct inflate_state FAR *state;
  81372. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  81373. return Z_STREAM_ERROR;
  81374. state = (struct inflate_state FAR *)strm->state;
  81375. if (state->window != Z_NULL) ZFREE(strm, state->window);
  81376. ZFREE(strm, strm->state);
  81377. strm->state = Z_NULL;
  81378. Tracev((stderr, "inflate: end\n"));
  81379. return Z_OK;
  81380. }
  81381. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  81382. {
  81383. struct inflate_state FAR *state;
  81384. unsigned long id_;
  81385. /* check state */
  81386. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81387. state = (struct inflate_state FAR *)strm->state;
  81388. if (state->wrap != 0 && state->mode != DICT)
  81389. return Z_STREAM_ERROR;
  81390. /* check for correct dictionary id */
  81391. if (state->mode == DICT) {
  81392. id_ = adler32(0L, Z_NULL, 0);
  81393. id_ = adler32(id_, dictionary, dictLength);
  81394. if (id_ != state->check)
  81395. return Z_DATA_ERROR;
  81396. }
  81397. /* copy dictionary to window */
  81398. if (updatewindow(strm, strm->avail_out)) {
  81399. state->mode = MEM;
  81400. return Z_MEM_ERROR;
  81401. }
  81402. if (dictLength > state->wsize) {
  81403. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  81404. state->wsize);
  81405. state->whave = state->wsize;
  81406. }
  81407. else {
  81408. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  81409. dictLength);
  81410. state->whave = dictLength;
  81411. }
  81412. state->havedict = 1;
  81413. Tracev((stderr, "inflate: dictionary set\n"));
  81414. return Z_OK;
  81415. }
  81416. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  81417. {
  81418. struct inflate_state FAR *state;
  81419. /* check state */
  81420. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81421. state = (struct inflate_state FAR *)strm->state;
  81422. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  81423. /* save header structure */
  81424. state->head = head;
  81425. head->done = 0;
  81426. return Z_OK;
  81427. }
  81428. /*
  81429. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  81430. or when out of input. When called, *have is the number of pattern bytes
  81431. found in order so far, in 0..3. On return *have is updated to the new
  81432. state. If on return *have equals four, then the pattern was found and the
  81433. return value is how many bytes were read including the last byte of the
  81434. pattern. If *have is less than four, then the pattern has not been found
  81435. yet and the return value is len. In the latter case, syncsearch() can be
  81436. called again with more data and the *have state. *have is initialized to
  81437. zero for the first call.
  81438. */
  81439. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  81440. {
  81441. unsigned got;
  81442. unsigned next;
  81443. got = *have;
  81444. next = 0;
  81445. while (next < len && got < 4) {
  81446. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  81447. got++;
  81448. else if (buf[next])
  81449. got = 0;
  81450. else
  81451. got = 4 - got;
  81452. next++;
  81453. }
  81454. *have = got;
  81455. return next;
  81456. }
  81457. int ZEXPORT inflateSync (z_streamp strm)
  81458. {
  81459. unsigned len; /* number of bytes to look at or looked at */
  81460. unsigned long in, out; /* temporary to save total_in and total_out */
  81461. unsigned char buf[4]; /* to restore bit buffer to byte string */
  81462. struct inflate_state FAR *state;
  81463. /* check parameters */
  81464. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81465. state = (struct inflate_state FAR *)strm->state;
  81466. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  81467. /* if first time, start search in bit buffer */
  81468. if (state->mode != SYNC) {
  81469. state->mode = SYNC;
  81470. state->hold <<= state->bits & 7;
  81471. state->bits -= state->bits & 7;
  81472. len = 0;
  81473. while (state->bits >= 8) {
  81474. buf[len++] = (unsigned char)(state->hold);
  81475. state->hold >>= 8;
  81476. state->bits -= 8;
  81477. }
  81478. state->have = 0;
  81479. syncsearch(&(state->have), buf, len);
  81480. }
  81481. /* search available input */
  81482. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  81483. strm->avail_in -= len;
  81484. strm->next_in += len;
  81485. strm->total_in += len;
  81486. /* return no joy or set up to restart inflate() on a new block */
  81487. if (state->have != 4) return Z_DATA_ERROR;
  81488. in = strm->total_in; out = strm->total_out;
  81489. inflateReset(strm);
  81490. strm->total_in = in; strm->total_out = out;
  81491. state->mode = TYPE;
  81492. return Z_OK;
  81493. }
  81494. /*
  81495. Returns true if inflate is currently at the end of a block generated by
  81496. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  81497. implementation to provide an additional safety check. PPP uses
  81498. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  81499. block. When decompressing, PPP checks that at the end of input packet,
  81500. inflate is waiting for these length bytes.
  81501. */
  81502. int ZEXPORT inflateSyncPoint (z_streamp strm)
  81503. {
  81504. struct inflate_state FAR *state;
  81505. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81506. state = (struct inflate_state FAR *)strm->state;
  81507. return state->mode == STORED && state->bits == 0;
  81508. }
  81509. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  81510. {
  81511. struct inflate_state FAR *state;
  81512. struct inflate_state FAR *copy;
  81513. unsigned char FAR *window;
  81514. unsigned wsize;
  81515. /* check input */
  81516. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  81517. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  81518. return Z_STREAM_ERROR;
  81519. state = (struct inflate_state FAR *)source->state;
  81520. /* allocate space */
  81521. copy = (struct inflate_state FAR *)
  81522. ZALLOC(source, 1, sizeof(struct inflate_state));
  81523. if (copy == Z_NULL) return Z_MEM_ERROR;
  81524. window = Z_NULL;
  81525. if (state->window != Z_NULL) {
  81526. window = (unsigned char FAR *)
  81527. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  81528. if (window == Z_NULL) {
  81529. ZFREE(source, copy);
  81530. return Z_MEM_ERROR;
  81531. }
  81532. }
  81533. /* copy state */
  81534. zmemcpy(dest, source, sizeof(z_stream));
  81535. zmemcpy(copy, state, sizeof(struct inflate_state));
  81536. if (state->lencode >= state->codes &&
  81537. state->lencode <= state->codes + ENOUGH - 1) {
  81538. copy->lencode = copy->codes + (state->lencode - state->codes);
  81539. copy->distcode = copy->codes + (state->distcode - state->codes);
  81540. }
  81541. copy->next = copy->codes + (state->next - state->codes);
  81542. if (window != Z_NULL) {
  81543. wsize = 1U << state->wbits;
  81544. zmemcpy(window, state->window, wsize);
  81545. }
  81546. copy->window = window;
  81547. dest->state = (struct internal_state FAR *)copy;
  81548. return Z_OK;
  81549. }
  81550. /*** End of inlined file: inflate.c ***/
  81551. /*** Start of inlined file: inftrees.c ***/
  81552. #define MAXBITS 15
  81553. const char inflate_copyright[] =
  81554. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  81555. /*
  81556. If you use the zlib library in a product, an acknowledgment is welcome
  81557. in the documentation of your product. If for some reason you cannot
  81558. include such an acknowledgment, I would appreciate that you keep this
  81559. copyright string in the executable of your product.
  81560. */
  81561. /*
  81562. Build a set of tables to decode the provided canonical Huffman code.
  81563. The code lengths are lens[0..codes-1]. The result starts at *table,
  81564. whose indices are 0..2^bits-1. work is a writable array of at least
  81565. lens shorts, which is used as a work area. type is the type of code
  81566. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  81567. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  81568. on return points to the next available entry's address. bits is the
  81569. requested root table index bits, and on return it is the actual root
  81570. table index bits. It will differ if the request is greater than the
  81571. longest code or if it is less than the shortest code.
  81572. */
  81573. int inflate_table (codetype type,
  81574. unsigned short FAR *lens,
  81575. unsigned codes,
  81576. code FAR * FAR *table,
  81577. unsigned FAR *bits,
  81578. unsigned short FAR *work)
  81579. {
  81580. unsigned len; /* a code's length in bits */
  81581. unsigned sym; /* index of code symbols */
  81582. unsigned min, max; /* minimum and maximum code lengths */
  81583. unsigned root; /* number of index bits for root table */
  81584. unsigned curr; /* number of index bits for current table */
  81585. unsigned drop; /* code bits to drop for sub-table */
  81586. int left; /* number of prefix codes available */
  81587. unsigned used; /* code entries in table used */
  81588. unsigned huff; /* Huffman code */
  81589. unsigned incr; /* for incrementing code, index */
  81590. unsigned fill; /* index for replicating entries */
  81591. unsigned low; /* low bits for current root entry */
  81592. unsigned mask; /* mask for low root bits */
  81593. code thisx; /* table entry for duplication */
  81594. code FAR *next; /* next available space in table */
  81595. const unsigned short FAR *base; /* base value table to use */
  81596. const unsigned short FAR *extra; /* extra bits table to use */
  81597. int end; /* use base and extra for symbol > end */
  81598. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  81599. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  81600. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  81601. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  81602. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  81603. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  81604. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  81605. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  81606. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  81607. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  81608. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  81609. 8193, 12289, 16385, 24577, 0, 0};
  81610. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  81611. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  81612. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  81613. 28, 28, 29, 29, 64, 64};
  81614. /*
  81615. Process a set of code lengths to create a canonical Huffman code. The
  81616. code lengths are lens[0..codes-1]. Each length corresponds to the
  81617. symbols 0..codes-1. The Huffman code is generated by first sorting the
  81618. symbols by length from short to long, and retaining the symbol order
  81619. for codes with equal lengths. Then the code starts with all zero bits
  81620. for the first code of the shortest length, and the codes are integer
  81621. increments for the same length, and zeros are appended as the length
  81622. increases. For the deflate format, these bits are stored backwards
  81623. from their more natural integer increment ordering, and so when the
  81624. decoding tables are built in the large loop below, the integer codes
  81625. are incremented backwards.
  81626. This routine assumes, but does not check, that all of the entries in
  81627. lens[] are in the range 0..MAXBITS. The caller must assure this.
  81628. 1..MAXBITS is interpreted as that code length. zero means that that
  81629. symbol does not occur in this code.
  81630. The codes are sorted by computing a count of codes for each length,
  81631. creating from that a table of starting indices for each length in the
  81632. sorted table, and then entering the symbols in order in the sorted
  81633. table. The sorted table is work[], with that space being provided by
  81634. the caller.
  81635. The length counts are used for other purposes as well, i.e. finding
  81636. the minimum and maximum length codes, determining if there are any
  81637. codes at all, checking for a valid set of lengths, and looking ahead
  81638. at length counts to determine sub-table sizes when building the
  81639. decoding tables.
  81640. */
  81641. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  81642. for (len = 0; len <= MAXBITS; len++)
  81643. count[len] = 0;
  81644. for (sym = 0; sym < codes; sym++)
  81645. count[lens[sym]]++;
  81646. /* bound code lengths, force root to be within code lengths */
  81647. root = *bits;
  81648. for (max = MAXBITS; max >= 1; max--)
  81649. if (count[max] != 0) break;
  81650. if (root > max) root = max;
  81651. if (max == 0) { /* no symbols to code at all */
  81652. thisx.op = (unsigned char)64; /* invalid code marker */
  81653. thisx.bits = (unsigned char)1;
  81654. thisx.val = (unsigned short)0;
  81655. *(*table)++ = thisx; /* make a table to force an error */
  81656. *(*table)++ = thisx;
  81657. *bits = 1;
  81658. return 0; /* no symbols, but wait for decoding to report error */
  81659. }
  81660. for (min = 1; min <= MAXBITS; min++)
  81661. if (count[min] != 0) break;
  81662. if (root < min) root = min;
  81663. /* check for an over-subscribed or incomplete set of lengths */
  81664. left = 1;
  81665. for (len = 1; len <= MAXBITS; len++) {
  81666. left <<= 1;
  81667. left -= count[len];
  81668. if (left < 0) return -1; /* over-subscribed */
  81669. }
  81670. if (left > 0 && (type == CODES || max != 1))
  81671. return -1; /* incomplete set */
  81672. /* generate offsets into symbol table for each length for sorting */
  81673. offs[1] = 0;
  81674. for (len = 1; len < MAXBITS; len++)
  81675. offs[len + 1] = offs[len] + count[len];
  81676. /* sort symbols by length, by symbol order within each length */
  81677. for (sym = 0; sym < codes; sym++)
  81678. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  81679. /*
  81680. Create and fill in decoding tables. In this loop, the table being
  81681. filled is at next and has curr index bits. The code being used is huff
  81682. with length len. That code is converted to an index by dropping drop
  81683. bits off of the bottom. For codes where len is less than drop + curr,
  81684. those top drop + curr - len bits are incremented through all values to
  81685. fill the table with replicated entries.
  81686. root is the number of index bits for the root table. When len exceeds
  81687. root, sub-tables are created pointed to by the root entry with an index
  81688. of the low root bits of huff. This is saved in low to check for when a
  81689. new sub-table should be started. drop is zero when the root table is
  81690. being filled, and drop is root when sub-tables are being filled.
  81691. When a new sub-table is needed, it is necessary to look ahead in the
  81692. code lengths to determine what size sub-table is needed. The length
  81693. counts are used for this, and so count[] is decremented as codes are
  81694. entered in the tables.
  81695. used keeps track of how many table entries have been allocated from the
  81696. provided *table space. It is checked when a LENS table is being made
  81697. against the space in *table, ENOUGH, minus the maximum space needed by
  81698. the worst case distance code, MAXD. This should never happen, but the
  81699. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  81700. This assumes that when type == LENS, bits == 9.
  81701. sym increments through all symbols, and the loop terminates when
  81702. all codes of length max, i.e. all codes, have been processed. This
  81703. routine permits incomplete codes, so another loop after this one fills
  81704. in the rest of the decoding tables with invalid code markers.
  81705. */
  81706. /* set up for code type */
  81707. switch (type) {
  81708. case CODES:
  81709. base = extra = work; /* dummy value--not used */
  81710. end = 19;
  81711. break;
  81712. case LENS:
  81713. base = lbase;
  81714. base -= 257;
  81715. extra = lext;
  81716. extra -= 257;
  81717. end = 256;
  81718. break;
  81719. default: /* DISTS */
  81720. base = dbase;
  81721. extra = dext;
  81722. end = -1;
  81723. }
  81724. /* initialize state for loop */
  81725. huff = 0; /* starting code */
  81726. sym = 0; /* starting code symbol */
  81727. len = min; /* starting code length */
  81728. next = *table; /* current table to fill in */
  81729. curr = root; /* current table index bits */
  81730. drop = 0; /* current bits to drop from code for index */
  81731. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  81732. used = 1U << root; /* use root table entries */
  81733. mask = used - 1; /* mask for comparing low */
  81734. /* check available table space */
  81735. if (type == LENS && used >= ENOUGH - MAXD)
  81736. return 1;
  81737. /* process all codes and make table entries */
  81738. for (;;) {
  81739. /* create table entry */
  81740. thisx.bits = (unsigned char)(len - drop);
  81741. if ((int)(work[sym]) < end) {
  81742. thisx.op = (unsigned char)0;
  81743. thisx.val = work[sym];
  81744. }
  81745. else if ((int)(work[sym]) > end) {
  81746. thisx.op = (unsigned char)(extra[work[sym]]);
  81747. thisx.val = base[work[sym]];
  81748. }
  81749. else {
  81750. thisx.op = (unsigned char)(32 + 64); /* end of block */
  81751. thisx.val = 0;
  81752. }
  81753. /* replicate for those indices with low len bits equal to huff */
  81754. incr = 1U << (len - drop);
  81755. fill = 1U << curr;
  81756. min = fill; /* save offset to next table */
  81757. do {
  81758. fill -= incr;
  81759. next[(huff >> drop) + fill] = thisx;
  81760. } while (fill != 0);
  81761. /* backwards increment the len-bit code huff */
  81762. incr = 1U << (len - 1);
  81763. while (huff & incr)
  81764. incr >>= 1;
  81765. if (incr != 0) {
  81766. huff &= incr - 1;
  81767. huff += incr;
  81768. }
  81769. else
  81770. huff = 0;
  81771. /* go to next symbol, update count, len */
  81772. sym++;
  81773. if (--(count[len]) == 0) {
  81774. if (len == max) break;
  81775. len = lens[work[sym]];
  81776. }
  81777. /* create new sub-table if needed */
  81778. if (len > root && (huff & mask) != low) {
  81779. /* if first time, transition to sub-tables */
  81780. if (drop == 0)
  81781. drop = root;
  81782. /* increment past last table */
  81783. next += min; /* here min is 1 << curr */
  81784. /* determine length of next table */
  81785. curr = len - drop;
  81786. left = (int)(1 << curr);
  81787. while (curr + drop < max) {
  81788. left -= count[curr + drop];
  81789. if (left <= 0) break;
  81790. curr++;
  81791. left <<= 1;
  81792. }
  81793. /* check for enough space */
  81794. used += 1U << curr;
  81795. if (type == LENS && used >= ENOUGH - MAXD)
  81796. return 1;
  81797. /* point entry in root table to sub-table */
  81798. low = huff & mask;
  81799. (*table)[low].op = (unsigned char)curr;
  81800. (*table)[low].bits = (unsigned char)root;
  81801. (*table)[low].val = (unsigned short)(next - *table);
  81802. }
  81803. }
  81804. /*
  81805. Fill in rest of table for incomplete codes. This loop is similar to the
  81806. loop above in incrementing huff for table indices. It is assumed that
  81807. len is equal to curr + drop, so there is no loop needed to increment
  81808. through high index bits. When the current sub-table is filled, the loop
  81809. drops back to the root table to fill in any remaining entries there.
  81810. */
  81811. thisx.op = (unsigned char)64; /* invalid code marker */
  81812. thisx.bits = (unsigned char)(len - drop);
  81813. thisx.val = (unsigned short)0;
  81814. while (huff != 0) {
  81815. /* when done with sub-table, drop back to root table */
  81816. if (drop != 0 && (huff & mask) != low) {
  81817. drop = 0;
  81818. len = root;
  81819. next = *table;
  81820. thisx.bits = (unsigned char)len;
  81821. }
  81822. /* put invalid code marker in table */
  81823. next[huff >> drop] = thisx;
  81824. /* backwards increment the len-bit code huff */
  81825. incr = 1U << (len - 1);
  81826. while (huff & incr)
  81827. incr >>= 1;
  81828. if (incr != 0) {
  81829. huff &= incr - 1;
  81830. huff += incr;
  81831. }
  81832. else
  81833. huff = 0;
  81834. }
  81835. /* set return parameters */
  81836. *table += used;
  81837. *bits = root;
  81838. return 0;
  81839. }
  81840. /*** End of inlined file: inftrees.c ***/
  81841. /*** Start of inlined file: trees.c ***/
  81842. /*
  81843. * ALGORITHM
  81844. *
  81845. * The "deflation" process uses several Huffman trees. The more
  81846. * common source values are represented by shorter bit sequences.
  81847. *
  81848. * Each code tree is stored in a compressed form which is itself
  81849. * a Huffman encoding of the lengths of all the code strings (in
  81850. * ascending order by source values). The actual code strings are
  81851. * reconstructed from the lengths in the inflate process, as described
  81852. * in the deflate specification.
  81853. *
  81854. * REFERENCES
  81855. *
  81856. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  81857. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  81858. *
  81859. * Storer, James A.
  81860. * Data Compression: Methods and Theory, pp. 49-50.
  81861. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  81862. *
  81863. * Sedgewick, R.
  81864. * Algorithms, p290.
  81865. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  81866. */
  81867. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  81868. /* #define GEN_TREES_H */
  81869. #ifdef DEBUG
  81870. # include <ctype.h>
  81871. #endif
  81872. /* ===========================================================================
  81873. * Constants
  81874. */
  81875. #define MAX_BL_BITS 7
  81876. /* Bit length codes must not exceed MAX_BL_BITS bits */
  81877. #define END_BLOCK 256
  81878. /* end of block literal code */
  81879. #define REP_3_6 16
  81880. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  81881. #define REPZ_3_10 17
  81882. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  81883. #define REPZ_11_138 18
  81884. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  81885. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  81886. = {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};
  81887. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  81888. = {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};
  81889. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  81890. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  81891. local const uch bl_order[BL_CODES]
  81892. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  81893. /* The lengths of the bit length codes are sent in order of decreasing
  81894. * probability, to avoid transmitting the lengths for unused bit length codes.
  81895. */
  81896. #define Buf_size (8 * 2*sizeof(char))
  81897. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  81898. * more than 16 bits on some systems.)
  81899. */
  81900. /* ===========================================================================
  81901. * Local data. These are initialized only once.
  81902. */
  81903. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  81904. #if defined(GEN_TREES_H) || !defined(STDC)
  81905. /* non ANSI compilers may not accept trees.h */
  81906. local ct_data static_ltree[L_CODES+2];
  81907. /* The static literal tree. Since the bit lengths are imposed, there is no
  81908. * need for the L_CODES extra codes used during heap construction. However
  81909. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  81910. * below).
  81911. */
  81912. local ct_data static_dtree[D_CODES];
  81913. /* The static distance tree. (Actually a trivial tree since all codes use
  81914. * 5 bits.)
  81915. */
  81916. uch _dist_code[DIST_CODE_LEN];
  81917. /* Distance codes. The first 256 values correspond to the distances
  81918. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  81919. * the 15 bit distances.
  81920. */
  81921. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  81922. /* length code for each normalized match length (0 == MIN_MATCH) */
  81923. local int base_length[LENGTH_CODES];
  81924. /* First normalized length for each code (0 = MIN_MATCH) */
  81925. local int base_dist[D_CODES];
  81926. /* First normalized distance for each code (0 = distance of 1) */
  81927. #else
  81928. /*** Start of inlined file: trees.h ***/
  81929. local const ct_data static_ltree[L_CODES+2] = {
  81930. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  81931. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  81932. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  81933. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  81934. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  81935. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  81936. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  81937. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  81938. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  81939. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  81940. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  81941. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  81942. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  81943. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  81944. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  81945. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  81946. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  81947. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  81948. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  81949. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  81950. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  81951. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  81952. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  81953. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  81954. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  81955. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  81956. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  81957. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  81958. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  81959. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  81960. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  81961. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  81962. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  81963. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  81964. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  81965. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  81966. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  81967. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  81968. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  81969. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  81970. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  81971. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  81972. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  81973. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  81974. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  81975. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  81976. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  81977. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  81978. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  81979. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  81980. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  81981. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  81982. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  81983. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  81984. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  81985. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  81986. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  81987. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  81988. };
  81989. local const ct_data static_dtree[D_CODES] = {
  81990. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  81991. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  81992. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  81993. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  81994. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  81995. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  81996. };
  81997. const uch _dist_code[DIST_CODE_LEN] = {
  81998. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  81999. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  82000. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  82001. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  82002. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  82003. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  82004. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  82005. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  82006. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  82007. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  82008. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  82009. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  82010. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  82011. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  82012. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  82013. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  82014. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  82015. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  82016. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  82017. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  82018. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  82019. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  82020. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  82021. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  82022. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  82023. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  82024. };
  82025. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  82026. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  82027. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  82028. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  82029. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  82030. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  82031. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  82032. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  82033. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  82034. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  82035. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  82036. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  82037. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  82038. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  82039. };
  82040. local const int base_length[LENGTH_CODES] = {
  82041. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  82042. 64, 80, 96, 112, 128, 160, 192, 224, 0
  82043. };
  82044. local const int base_dist[D_CODES] = {
  82045. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  82046. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  82047. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  82048. };
  82049. /*** End of inlined file: trees.h ***/
  82050. #endif /* GEN_TREES_H */
  82051. struct static_tree_desc_s {
  82052. const ct_data *static_tree; /* static tree or NULL */
  82053. const intf *extra_bits; /* extra bits for each code or NULL */
  82054. int extra_base; /* base index for extra_bits */
  82055. int elems; /* max number of elements in the tree */
  82056. int max_length; /* max bit length for the codes */
  82057. };
  82058. local static_tree_desc static_l_desc =
  82059. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  82060. local static_tree_desc static_d_desc =
  82061. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  82062. local static_tree_desc static_bl_desc =
  82063. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  82064. /* ===========================================================================
  82065. * Local (static) routines in this file.
  82066. */
  82067. local void tr_static_init OF((void));
  82068. local void init_block OF((deflate_state *s));
  82069. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  82070. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  82071. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  82072. local void build_tree OF((deflate_state *s, tree_desc *desc));
  82073. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  82074. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  82075. local int build_bl_tree OF((deflate_state *s));
  82076. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  82077. int blcodes));
  82078. local void compress_block OF((deflate_state *s, ct_data *ltree,
  82079. ct_data *dtree));
  82080. local void set_data_type OF((deflate_state *s));
  82081. local unsigned bi_reverse OF((unsigned value, int length));
  82082. local void bi_windup OF((deflate_state *s));
  82083. local void bi_flush OF((deflate_state *s));
  82084. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  82085. int header));
  82086. #ifdef GEN_TREES_H
  82087. local void gen_trees_header OF((void));
  82088. #endif
  82089. #ifndef DEBUG
  82090. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  82091. /* Send a code of the given tree. c and tree must not have side effects */
  82092. #else /* DEBUG */
  82093. # define send_code(s, c, tree) \
  82094. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  82095. send_bits(s, tree[c].Code, tree[c].Len); }
  82096. #endif
  82097. /* ===========================================================================
  82098. * Output a short LSB first on the stream.
  82099. * IN assertion: there is enough room in pendingBuf.
  82100. */
  82101. #define put_short(s, w) { \
  82102. put_byte(s, (uch)((w) & 0xff)); \
  82103. put_byte(s, (uch)((ush)(w) >> 8)); \
  82104. }
  82105. /* ===========================================================================
  82106. * Send a value on a given number of bits.
  82107. * IN assertion: length <= 16 and value fits in length bits.
  82108. */
  82109. #ifdef DEBUG
  82110. local void send_bits OF((deflate_state *s, int value, int length));
  82111. local void send_bits (deflate_state *s, int value, int length)
  82112. {
  82113. Tracevv((stderr," l %2d v %4x ", length, value));
  82114. Assert(length > 0 && length <= 15, "invalid length");
  82115. s->bits_sent += (ulg)length;
  82116. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  82117. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  82118. * unused bits in value.
  82119. */
  82120. if (s->bi_valid > (int)Buf_size - length) {
  82121. s->bi_buf |= (value << s->bi_valid);
  82122. put_short(s, s->bi_buf);
  82123. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  82124. s->bi_valid += length - Buf_size;
  82125. } else {
  82126. s->bi_buf |= value << s->bi_valid;
  82127. s->bi_valid += length;
  82128. }
  82129. }
  82130. #else /* !DEBUG */
  82131. #define send_bits(s, value, length) \
  82132. { int len = length;\
  82133. if (s->bi_valid > (int)Buf_size - len) {\
  82134. int val = value;\
  82135. s->bi_buf |= (val << s->bi_valid);\
  82136. put_short(s, s->bi_buf);\
  82137. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  82138. s->bi_valid += len - Buf_size;\
  82139. } else {\
  82140. s->bi_buf |= (value) << s->bi_valid;\
  82141. s->bi_valid += len;\
  82142. }\
  82143. }
  82144. #endif /* DEBUG */
  82145. /* the arguments must not have side effects */
  82146. /* ===========================================================================
  82147. * Initialize the various 'constant' tables.
  82148. */
  82149. local void tr_static_init()
  82150. {
  82151. #if defined(GEN_TREES_H) || !defined(STDC)
  82152. static int static_init_done = 0;
  82153. int n; /* iterates over tree elements */
  82154. int bits; /* bit counter */
  82155. int length; /* length value */
  82156. int code; /* code value */
  82157. int dist; /* distance index */
  82158. ush bl_count[MAX_BITS+1];
  82159. /* number of codes at each bit length for an optimal tree */
  82160. if (static_init_done) return;
  82161. /* For some embedded targets, global variables are not initialized: */
  82162. static_l_desc.static_tree = static_ltree;
  82163. static_l_desc.extra_bits = extra_lbits;
  82164. static_d_desc.static_tree = static_dtree;
  82165. static_d_desc.extra_bits = extra_dbits;
  82166. static_bl_desc.extra_bits = extra_blbits;
  82167. /* Initialize the mapping length (0..255) -> length code (0..28) */
  82168. length = 0;
  82169. for (code = 0; code < LENGTH_CODES-1; code++) {
  82170. base_length[code] = length;
  82171. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  82172. _length_code[length++] = (uch)code;
  82173. }
  82174. }
  82175. Assert (length == 256, "tr_static_init: length != 256");
  82176. /* Note that the length 255 (match length 258) can be represented
  82177. * in two different ways: code 284 + 5 bits or code 285, so we
  82178. * overwrite length_code[255] to use the best encoding:
  82179. */
  82180. _length_code[length-1] = (uch)code;
  82181. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  82182. dist = 0;
  82183. for (code = 0 ; code < 16; code++) {
  82184. base_dist[code] = dist;
  82185. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  82186. _dist_code[dist++] = (uch)code;
  82187. }
  82188. }
  82189. Assert (dist == 256, "tr_static_init: dist != 256");
  82190. dist >>= 7; /* from now on, all distances are divided by 128 */
  82191. for ( ; code < D_CODES; code++) {
  82192. base_dist[code] = dist << 7;
  82193. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  82194. _dist_code[256 + dist++] = (uch)code;
  82195. }
  82196. }
  82197. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  82198. /* Construct the codes of the static literal tree */
  82199. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  82200. n = 0;
  82201. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  82202. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  82203. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  82204. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  82205. /* Codes 286 and 287 do not exist, but we must include them in the
  82206. * tree construction to get a canonical Huffman tree (longest code
  82207. * all ones)
  82208. */
  82209. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  82210. /* The static distance tree is trivial: */
  82211. for (n = 0; n < D_CODES; n++) {
  82212. static_dtree[n].Len = 5;
  82213. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  82214. }
  82215. static_init_done = 1;
  82216. # ifdef GEN_TREES_H
  82217. gen_trees_header();
  82218. # endif
  82219. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  82220. }
  82221. /* ===========================================================================
  82222. * Genererate the file trees.h describing the static trees.
  82223. */
  82224. #ifdef GEN_TREES_H
  82225. # ifndef DEBUG
  82226. # include <stdio.h>
  82227. # endif
  82228. # define SEPARATOR(i, last, width) \
  82229. ((i) == (last)? "\n};\n\n" : \
  82230. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  82231. void gen_trees_header()
  82232. {
  82233. FILE *header = fopen("trees.h", "w");
  82234. int i;
  82235. Assert (header != NULL, "Can't open trees.h");
  82236. fprintf(header,
  82237. "/* header created automatically with -DGEN_TREES_H */\n\n");
  82238. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  82239. for (i = 0; i < L_CODES+2; i++) {
  82240. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  82241. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  82242. }
  82243. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  82244. for (i = 0; i < D_CODES; i++) {
  82245. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  82246. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  82247. }
  82248. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  82249. for (i = 0; i < DIST_CODE_LEN; i++) {
  82250. fprintf(header, "%2u%s", _dist_code[i],
  82251. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  82252. }
  82253. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  82254. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  82255. fprintf(header, "%2u%s", _length_code[i],
  82256. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  82257. }
  82258. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  82259. for (i = 0; i < LENGTH_CODES; i++) {
  82260. fprintf(header, "%1u%s", base_length[i],
  82261. SEPARATOR(i, LENGTH_CODES-1, 20));
  82262. }
  82263. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  82264. for (i = 0; i < D_CODES; i++) {
  82265. fprintf(header, "%5u%s", base_dist[i],
  82266. SEPARATOR(i, D_CODES-1, 10));
  82267. }
  82268. fclose(header);
  82269. }
  82270. #endif /* GEN_TREES_H */
  82271. /* ===========================================================================
  82272. * Initialize the tree data structures for a new zlib stream.
  82273. */
  82274. void _tr_init(deflate_state *s)
  82275. {
  82276. tr_static_init();
  82277. s->l_desc.dyn_tree = s->dyn_ltree;
  82278. s->l_desc.stat_desc = &static_l_desc;
  82279. s->d_desc.dyn_tree = s->dyn_dtree;
  82280. s->d_desc.stat_desc = &static_d_desc;
  82281. s->bl_desc.dyn_tree = s->bl_tree;
  82282. s->bl_desc.stat_desc = &static_bl_desc;
  82283. s->bi_buf = 0;
  82284. s->bi_valid = 0;
  82285. s->last_eob_len = 8; /* enough lookahead for inflate */
  82286. #ifdef DEBUG
  82287. s->compressed_len = 0L;
  82288. s->bits_sent = 0L;
  82289. #endif
  82290. /* Initialize the first block of the first file: */
  82291. init_block(s);
  82292. }
  82293. /* ===========================================================================
  82294. * Initialize a new block.
  82295. */
  82296. local void init_block (deflate_state *s)
  82297. {
  82298. int n; /* iterates over tree elements */
  82299. /* Initialize the trees. */
  82300. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  82301. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  82302. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  82303. s->dyn_ltree[END_BLOCK].Freq = 1;
  82304. s->opt_len = s->static_len = 0L;
  82305. s->last_lit = s->matches = 0;
  82306. }
  82307. #define SMALLEST 1
  82308. /* Index within the heap array of least frequent node in the Huffman tree */
  82309. /* ===========================================================================
  82310. * Remove the smallest element from the heap and recreate the heap with
  82311. * one less element. Updates heap and heap_len.
  82312. */
  82313. #define pqremove(s, tree, top) \
  82314. {\
  82315. top = s->heap[SMALLEST]; \
  82316. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  82317. pqdownheap(s, tree, SMALLEST); \
  82318. }
  82319. /* ===========================================================================
  82320. * Compares to subtrees, using the tree depth as tie breaker when
  82321. * the subtrees have equal frequency. This minimizes the worst case length.
  82322. */
  82323. #define smaller(tree, n, m, depth) \
  82324. (tree[n].Freq < tree[m].Freq || \
  82325. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  82326. /* ===========================================================================
  82327. * Restore the heap property by moving down the tree starting at node k,
  82328. * exchanging a node with the smallest of its two sons if necessary, stopping
  82329. * when the heap property is re-established (each father smaller than its
  82330. * two sons).
  82331. */
  82332. local void pqdownheap (deflate_state *s,
  82333. ct_data *tree, /* the tree to restore */
  82334. int k) /* node to move down */
  82335. {
  82336. int v = s->heap[k];
  82337. int j = k << 1; /* left son of k */
  82338. while (j <= s->heap_len) {
  82339. /* Set j to the smallest of the two sons: */
  82340. if (j < s->heap_len &&
  82341. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  82342. j++;
  82343. }
  82344. /* Exit if v is smaller than both sons */
  82345. if (smaller(tree, v, s->heap[j], s->depth)) break;
  82346. /* Exchange v with the smallest son */
  82347. s->heap[k] = s->heap[j]; k = j;
  82348. /* And continue down the tree, setting j to the left son of k */
  82349. j <<= 1;
  82350. }
  82351. s->heap[k] = v;
  82352. }
  82353. /* ===========================================================================
  82354. * Compute the optimal bit lengths for a tree and update the total bit length
  82355. * for the current block.
  82356. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  82357. * above are the tree nodes sorted by increasing frequency.
  82358. * OUT assertions: the field len is set to the optimal bit length, the
  82359. * array bl_count contains the frequencies for each bit length.
  82360. * The length opt_len is updated; static_len is also updated if stree is
  82361. * not null.
  82362. */
  82363. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  82364. {
  82365. ct_data *tree = desc->dyn_tree;
  82366. int max_code = desc->max_code;
  82367. const ct_data *stree = desc->stat_desc->static_tree;
  82368. const intf *extra = desc->stat_desc->extra_bits;
  82369. int base = desc->stat_desc->extra_base;
  82370. int max_length = desc->stat_desc->max_length;
  82371. int h; /* heap index */
  82372. int n, m; /* iterate over the tree elements */
  82373. int bits; /* bit length */
  82374. int xbits; /* extra bits */
  82375. ush f; /* frequency */
  82376. int overflow = 0; /* number of elements with bit length too large */
  82377. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  82378. /* In a first pass, compute the optimal bit lengths (which may
  82379. * overflow in the case of the bit length tree).
  82380. */
  82381. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  82382. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  82383. n = s->heap[h];
  82384. bits = tree[tree[n].Dad].Len + 1;
  82385. if (bits > max_length) bits = max_length, overflow++;
  82386. tree[n].Len = (ush)bits;
  82387. /* We overwrite tree[n].Dad which is no longer needed */
  82388. if (n > max_code) continue; /* not a leaf node */
  82389. s->bl_count[bits]++;
  82390. xbits = 0;
  82391. if (n >= base) xbits = extra[n-base];
  82392. f = tree[n].Freq;
  82393. s->opt_len += (ulg)f * (bits + xbits);
  82394. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  82395. }
  82396. if (overflow == 0) return;
  82397. Trace((stderr,"\nbit length overflow\n"));
  82398. /* This happens for example on obj2 and pic of the Calgary corpus */
  82399. /* Find the first bit length which could increase: */
  82400. do {
  82401. bits = max_length-1;
  82402. while (s->bl_count[bits] == 0) bits--;
  82403. s->bl_count[bits]--; /* move one leaf down the tree */
  82404. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  82405. s->bl_count[max_length]--;
  82406. /* The brother of the overflow item also moves one step up,
  82407. * but this does not affect bl_count[max_length]
  82408. */
  82409. overflow -= 2;
  82410. } while (overflow > 0);
  82411. /* Now recompute all bit lengths, scanning in increasing frequency.
  82412. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  82413. * lengths instead of fixing only the wrong ones. This idea is taken
  82414. * from 'ar' written by Haruhiko Okumura.)
  82415. */
  82416. for (bits = max_length; bits != 0; bits--) {
  82417. n = s->bl_count[bits];
  82418. while (n != 0) {
  82419. m = s->heap[--h];
  82420. if (m > max_code) continue;
  82421. if ((unsigned) tree[m].Len != (unsigned) bits) {
  82422. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  82423. s->opt_len += ((long)bits - (long)tree[m].Len)
  82424. *(long)tree[m].Freq;
  82425. tree[m].Len = (ush)bits;
  82426. }
  82427. n--;
  82428. }
  82429. }
  82430. }
  82431. /* ===========================================================================
  82432. * Generate the codes for a given tree and bit counts (which need not be
  82433. * optimal).
  82434. * IN assertion: the array bl_count contains the bit length statistics for
  82435. * the given tree and the field len is set for all tree elements.
  82436. * OUT assertion: the field code is set for all tree elements of non
  82437. * zero code length.
  82438. */
  82439. local void gen_codes (ct_data *tree, /* the tree to decorate */
  82440. int max_code, /* largest code with non zero frequency */
  82441. ushf *bl_count) /* number of codes at each bit length */
  82442. {
  82443. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  82444. ush code = 0; /* running code value */
  82445. int bits; /* bit index */
  82446. int n; /* code index */
  82447. /* The distribution counts are first used to generate the code values
  82448. * without bit reversal.
  82449. */
  82450. for (bits = 1; bits <= MAX_BITS; bits++) {
  82451. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  82452. }
  82453. /* Check that the bit counts in bl_count are consistent. The last code
  82454. * must be all ones.
  82455. */
  82456. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  82457. "inconsistent bit counts");
  82458. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  82459. for (n = 0; n <= max_code; n++) {
  82460. int len = tree[n].Len;
  82461. if (len == 0) continue;
  82462. /* Now reverse the bits */
  82463. tree[n].Code = bi_reverse(next_code[len]++, len);
  82464. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  82465. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  82466. }
  82467. }
  82468. /* ===========================================================================
  82469. * Construct one Huffman tree and assigns the code bit strings and lengths.
  82470. * Update the total bit length for the current block.
  82471. * IN assertion: the field freq is set for all tree elements.
  82472. * OUT assertions: the fields len and code are set to the optimal bit length
  82473. * and corresponding code. The length opt_len is updated; static_len is
  82474. * also updated if stree is not null. The field max_code is set.
  82475. */
  82476. local void build_tree (deflate_state *s,
  82477. tree_desc *desc) /* the tree descriptor */
  82478. {
  82479. ct_data *tree = desc->dyn_tree;
  82480. const ct_data *stree = desc->stat_desc->static_tree;
  82481. int elems = desc->stat_desc->elems;
  82482. int n, m; /* iterate over heap elements */
  82483. int max_code = -1; /* largest code with non zero frequency */
  82484. int node; /* new node being created */
  82485. /* Construct the initial heap, with least frequent element in
  82486. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  82487. * heap[0] is not used.
  82488. */
  82489. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  82490. for (n = 0; n < elems; n++) {
  82491. if (tree[n].Freq != 0) {
  82492. s->heap[++(s->heap_len)] = max_code = n;
  82493. s->depth[n] = 0;
  82494. } else {
  82495. tree[n].Len = 0;
  82496. }
  82497. }
  82498. /* The pkzip format requires that at least one distance code exists,
  82499. * and that at least one bit should be sent even if there is only one
  82500. * possible code. So to avoid special checks later on we force at least
  82501. * two codes of non zero frequency.
  82502. */
  82503. while (s->heap_len < 2) {
  82504. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  82505. tree[node].Freq = 1;
  82506. s->depth[node] = 0;
  82507. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  82508. /* node is 0 or 1 so it does not have extra bits */
  82509. }
  82510. desc->max_code = max_code;
  82511. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  82512. * establish sub-heaps of increasing lengths:
  82513. */
  82514. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  82515. /* Construct the Huffman tree by repeatedly combining the least two
  82516. * frequent nodes.
  82517. */
  82518. node = elems; /* next internal node of the tree */
  82519. do {
  82520. pqremove(s, tree, n); /* n = node of least frequency */
  82521. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  82522. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  82523. s->heap[--(s->heap_max)] = m;
  82524. /* Create a new node father of n and m */
  82525. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  82526. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  82527. s->depth[n] : s->depth[m]) + 1);
  82528. tree[n].Dad = tree[m].Dad = (ush)node;
  82529. #ifdef DUMP_BL_TREE
  82530. if (tree == s->bl_tree) {
  82531. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  82532. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  82533. }
  82534. #endif
  82535. /* and insert the new node in the heap */
  82536. s->heap[SMALLEST] = node++;
  82537. pqdownheap(s, tree, SMALLEST);
  82538. } while (s->heap_len >= 2);
  82539. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  82540. /* At this point, the fields freq and dad are set. We can now
  82541. * generate the bit lengths.
  82542. */
  82543. gen_bitlen(s, (tree_desc *)desc);
  82544. /* The field len is now set, we can generate the bit codes */
  82545. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  82546. }
  82547. /* ===========================================================================
  82548. * Scan a literal or distance tree to determine the frequencies of the codes
  82549. * in the bit length tree.
  82550. */
  82551. local void scan_tree (deflate_state *s,
  82552. ct_data *tree, /* the tree to be scanned */
  82553. int max_code) /* and its largest code of non zero frequency */
  82554. {
  82555. int n; /* iterates over all tree elements */
  82556. int prevlen = -1; /* last emitted length */
  82557. int curlen; /* length of current code */
  82558. int nextlen = tree[0].Len; /* length of next code */
  82559. int count = 0; /* repeat count of the current code */
  82560. int max_count = 7; /* max repeat count */
  82561. int min_count = 4; /* min repeat count */
  82562. if (nextlen == 0) max_count = 138, min_count = 3;
  82563. tree[max_code+1].Len = (ush)0xffff; /* guard */
  82564. for (n = 0; n <= max_code; n++) {
  82565. curlen = nextlen; nextlen = tree[n+1].Len;
  82566. if (++count < max_count && curlen == nextlen) {
  82567. continue;
  82568. } else if (count < min_count) {
  82569. s->bl_tree[curlen].Freq += count;
  82570. } else if (curlen != 0) {
  82571. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  82572. s->bl_tree[REP_3_6].Freq++;
  82573. } else if (count <= 10) {
  82574. s->bl_tree[REPZ_3_10].Freq++;
  82575. } else {
  82576. s->bl_tree[REPZ_11_138].Freq++;
  82577. }
  82578. count = 0; prevlen = curlen;
  82579. if (nextlen == 0) {
  82580. max_count = 138, min_count = 3;
  82581. } else if (curlen == nextlen) {
  82582. max_count = 6, min_count = 3;
  82583. } else {
  82584. max_count = 7, min_count = 4;
  82585. }
  82586. }
  82587. }
  82588. /* ===========================================================================
  82589. * Send a literal or distance tree in compressed form, using the codes in
  82590. * bl_tree.
  82591. */
  82592. local void send_tree (deflate_state *s,
  82593. ct_data *tree, /* the tree to be scanned */
  82594. int max_code) /* and its largest code of non zero frequency */
  82595. {
  82596. int n; /* iterates over all tree elements */
  82597. int prevlen = -1; /* last emitted length */
  82598. int curlen; /* length of current code */
  82599. int nextlen = tree[0].Len; /* length of next code */
  82600. int count = 0; /* repeat count of the current code */
  82601. int max_count = 7; /* max repeat count */
  82602. int min_count = 4; /* min repeat count */
  82603. /* tree[max_code+1].Len = -1; */ /* guard already set */
  82604. if (nextlen == 0) max_count = 138, min_count = 3;
  82605. for (n = 0; n <= max_code; n++) {
  82606. curlen = nextlen; nextlen = tree[n+1].Len;
  82607. if (++count < max_count && curlen == nextlen) {
  82608. continue;
  82609. } else if (count < min_count) {
  82610. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  82611. } else if (curlen != 0) {
  82612. if (curlen != prevlen) {
  82613. send_code(s, curlen, s->bl_tree); count--;
  82614. }
  82615. Assert(count >= 3 && count <= 6, " 3_6?");
  82616. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  82617. } else if (count <= 10) {
  82618. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  82619. } else {
  82620. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  82621. }
  82622. count = 0; prevlen = curlen;
  82623. if (nextlen == 0) {
  82624. max_count = 138, min_count = 3;
  82625. } else if (curlen == nextlen) {
  82626. max_count = 6, min_count = 3;
  82627. } else {
  82628. max_count = 7, min_count = 4;
  82629. }
  82630. }
  82631. }
  82632. /* ===========================================================================
  82633. * Construct the Huffman tree for the bit lengths and return the index in
  82634. * bl_order of the last bit length code to send.
  82635. */
  82636. local int build_bl_tree (deflate_state *s)
  82637. {
  82638. int max_blindex; /* index of last bit length code of non zero freq */
  82639. /* Determine the bit length frequencies for literal and distance trees */
  82640. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  82641. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  82642. /* Build the bit length tree: */
  82643. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  82644. /* opt_len now includes the length of the tree representations, except
  82645. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  82646. */
  82647. /* Determine the number of bit length codes to send. The pkzip format
  82648. * requires that at least 4 bit length codes be sent. (appnote.txt says
  82649. * 3 but the actual value used is 4.)
  82650. */
  82651. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  82652. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  82653. }
  82654. /* Update opt_len to include the bit length tree and counts */
  82655. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  82656. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  82657. s->opt_len, s->static_len));
  82658. return max_blindex;
  82659. }
  82660. /* ===========================================================================
  82661. * Send the header for a block using dynamic Huffman trees: the counts, the
  82662. * lengths of the bit length codes, the literal tree and the distance tree.
  82663. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  82664. */
  82665. local void send_all_trees (deflate_state *s,
  82666. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  82667. {
  82668. int rank; /* index in bl_order */
  82669. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  82670. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  82671. "too many codes");
  82672. Tracev((stderr, "\nbl counts: "));
  82673. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  82674. send_bits(s, dcodes-1, 5);
  82675. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  82676. for (rank = 0; rank < blcodes; rank++) {
  82677. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  82678. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  82679. }
  82680. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  82681. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  82682. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  82683. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  82684. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  82685. }
  82686. /* ===========================================================================
  82687. * Send a stored block
  82688. */
  82689. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  82690. {
  82691. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  82692. #ifdef DEBUG
  82693. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  82694. s->compressed_len += (stored_len + 4) << 3;
  82695. #endif
  82696. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  82697. }
  82698. /* ===========================================================================
  82699. * Send one empty static block to give enough lookahead for inflate.
  82700. * This takes 10 bits, of which 7 may remain in the bit buffer.
  82701. * The current inflate code requires 9 bits of lookahead. If the
  82702. * last two codes for the previous block (real code plus EOB) were coded
  82703. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  82704. * the last real code. In this case we send two empty static blocks instead
  82705. * of one. (There are no problems if the previous block is stored or fixed.)
  82706. * To simplify the code, we assume the worst case of last real code encoded
  82707. * on one bit only.
  82708. */
  82709. void _tr_align (deflate_state *s)
  82710. {
  82711. send_bits(s, STATIC_TREES<<1, 3);
  82712. send_code(s, END_BLOCK, static_ltree);
  82713. #ifdef DEBUG
  82714. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  82715. #endif
  82716. bi_flush(s);
  82717. /* Of the 10 bits for the empty block, we have already sent
  82718. * (10 - bi_valid) bits. The lookahead for the last real code (before
  82719. * the EOB of the previous block) was thus at least one plus the length
  82720. * of the EOB plus what we have just sent of the empty static block.
  82721. */
  82722. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  82723. send_bits(s, STATIC_TREES<<1, 3);
  82724. send_code(s, END_BLOCK, static_ltree);
  82725. #ifdef DEBUG
  82726. s->compressed_len += 10L;
  82727. #endif
  82728. bi_flush(s);
  82729. }
  82730. s->last_eob_len = 7;
  82731. }
  82732. /* ===========================================================================
  82733. * Determine the best encoding for the current block: dynamic trees, static
  82734. * trees or store, and output the encoded block to the zip file.
  82735. */
  82736. void _tr_flush_block (deflate_state *s,
  82737. charf *buf, /* input block, or NULL if too old */
  82738. ulg stored_len, /* length of input block */
  82739. int eof) /* true if this is the last block for a file */
  82740. {
  82741. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  82742. int max_blindex = 0; /* index of last bit length code of non zero freq */
  82743. /* Build the Huffman trees unless a stored block is forced */
  82744. if (s->level > 0) {
  82745. /* Check if the file is binary or text */
  82746. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  82747. set_data_type(s);
  82748. /* Construct the literal and distance trees */
  82749. build_tree(s, (tree_desc *)(&(s->l_desc)));
  82750. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  82751. s->static_len));
  82752. build_tree(s, (tree_desc *)(&(s->d_desc)));
  82753. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  82754. s->static_len));
  82755. /* At this point, opt_len and static_len are the total bit lengths of
  82756. * the compressed block data, excluding the tree representations.
  82757. */
  82758. /* Build the bit length tree for the above two trees, and get the index
  82759. * in bl_order of the last bit length code to send.
  82760. */
  82761. max_blindex = build_bl_tree(s);
  82762. /* Determine the best encoding. Compute the block lengths in bytes. */
  82763. opt_lenb = (s->opt_len+3+7)>>3;
  82764. static_lenb = (s->static_len+3+7)>>3;
  82765. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  82766. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  82767. s->last_lit));
  82768. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  82769. } else {
  82770. Assert(buf != (char*)0, "lost buf");
  82771. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  82772. }
  82773. #ifdef FORCE_STORED
  82774. if (buf != (char*)0) { /* force stored block */
  82775. #else
  82776. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  82777. /* 4: two words for the lengths */
  82778. #endif
  82779. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  82780. * Otherwise we can't have processed more than WSIZE input bytes since
  82781. * the last block flush, because compression would have been
  82782. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  82783. * transform a block into a stored block.
  82784. */
  82785. _tr_stored_block(s, buf, stored_len, eof);
  82786. #ifdef FORCE_STATIC
  82787. } else if (static_lenb >= 0) { /* force static trees */
  82788. #else
  82789. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  82790. #endif
  82791. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  82792. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  82793. #ifdef DEBUG
  82794. s->compressed_len += 3 + s->static_len;
  82795. #endif
  82796. } else {
  82797. send_bits(s, (DYN_TREES<<1)+eof, 3);
  82798. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  82799. max_blindex+1);
  82800. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  82801. #ifdef DEBUG
  82802. s->compressed_len += 3 + s->opt_len;
  82803. #endif
  82804. }
  82805. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  82806. /* The above check is made mod 2^32, for files larger than 512 MB
  82807. * and uLong implemented on 32 bits.
  82808. */
  82809. init_block(s);
  82810. if (eof) {
  82811. bi_windup(s);
  82812. #ifdef DEBUG
  82813. s->compressed_len += 7; /* align on byte boundary */
  82814. #endif
  82815. }
  82816. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  82817. s->compressed_len-7*eof));
  82818. }
  82819. /* ===========================================================================
  82820. * Save the match info and tally the frequency counts. Return true if
  82821. * the current block must be flushed.
  82822. */
  82823. int _tr_tally (deflate_state *s,
  82824. unsigned dist, /* distance of matched string */
  82825. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  82826. {
  82827. s->d_buf[s->last_lit] = (ush)dist;
  82828. s->l_buf[s->last_lit++] = (uch)lc;
  82829. if (dist == 0) {
  82830. /* lc is the unmatched char */
  82831. s->dyn_ltree[lc].Freq++;
  82832. } else {
  82833. s->matches++;
  82834. /* Here, lc is the match length - MIN_MATCH */
  82835. dist--; /* dist = match distance - 1 */
  82836. Assert((ush)dist < (ush)MAX_DIST(s) &&
  82837. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  82838. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  82839. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  82840. s->dyn_dtree[d_code(dist)].Freq++;
  82841. }
  82842. #ifdef TRUNCATE_BLOCK
  82843. /* Try to guess if it is profitable to stop the current block here */
  82844. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  82845. /* Compute an upper bound for the compressed length */
  82846. ulg out_length = (ulg)s->last_lit*8L;
  82847. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  82848. int dcode;
  82849. for (dcode = 0; dcode < D_CODES; dcode++) {
  82850. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  82851. (5L+extra_dbits[dcode]);
  82852. }
  82853. out_length >>= 3;
  82854. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  82855. s->last_lit, in_length, out_length,
  82856. 100L - out_length*100L/in_length));
  82857. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  82858. }
  82859. #endif
  82860. return (s->last_lit == s->lit_bufsize-1);
  82861. /* We avoid equality with lit_bufsize because of wraparound at 64K
  82862. * on 16 bit machines and because stored blocks are restricted to
  82863. * 64K-1 bytes.
  82864. */
  82865. }
  82866. /* ===========================================================================
  82867. * Send the block data compressed using the given Huffman trees
  82868. */
  82869. local void compress_block (deflate_state *s,
  82870. ct_data *ltree, /* literal tree */
  82871. ct_data *dtree) /* distance tree */
  82872. {
  82873. unsigned dist; /* distance of matched string */
  82874. int lc; /* match length or unmatched char (if dist == 0) */
  82875. unsigned lx = 0; /* running index in l_buf */
  82876. unsigned code; /* the code to send */
  82877. int extra; /* number of extra bits to send */
  82878. if (s->last_lit != 0) do {
  82879. dist = s->d_buf[lx];
  82880. lc = s->l_buf[lx++];
  82881. if (dist == 0) {
  82882. send_code(s, lc, ltree); /* send a literal byte */
  82883. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  82884. } else {
  82885. /* Here, lc is the match length - MIN_MATCH */
  82886. code = _length_code[lc];
  82887. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  82888. extra = extra_lbits[code];
  82889. if (extra != 0) {
  82890. lc -= base_length[code];
  82891. send_bits(s, lc, extra); /* send the extra length bits */
  82892. }
  82893. dist--; /* dist is now the match distance - 1 */
  82894. code = d_code(dist);
  82895. Assert (code < D_CODES, "bad d_code");
  82896. send_code(s, code, dtree); /* send the distance code */
  82897. extra = extra_dbits[code];
  82898. if (extra != 0) {
  82899. dist -= base_dist[code];
  82900. send_bits(s, dist, extra); /* send the extra distance bits */
  82901. }
  82902. } /* literal or match pair ? */
  82903. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  82904. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  82905. "pendingBuf overflow");
  82906. } while (lx < s->last_lit);
  82907. send_code(s, END_BLOCK, ltree);
  82908. s->last_eob_len = ltree[END_BLOCK].Len;
  82909. }
  82910. /* ===========================================================================
  82911. * Set the data type to BINARY or TEXT, using a crude approximation:
  82912. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  82913. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  82914. * IN assertion: the fields Freq of dyn_ltree are set.
  82915. */
  82916. local void set_data_type (deflate_state *s)
  82917. {
  82918. int n;
  82919. for (n = 0; n < 9; n++)
  82920. if (s->dyn_ltree[n].Freq != 0)
  82921. break;
  82922. if (n == 9)
  82923. for (n = 14; n < 32; n++)
  82924. if (s->dyn_ltree[n].Freq != 0)
  82925. break;
  82926. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  82927. }
  82928. /* ===========================================================================
  82929. * Reverse the first len bits of a code, using straightforward code (a faster
  82930. * method would use a table)
  82931. * IN assertion: 1 <= len <= 15
  82932. */
  82933. local unsigned bi_reverse (unsigned code, int len)
  82934. {
  82935. register unsigned res = 0;
  82936. do {
  82937. res |= code & 1;
  82938. code >>= 1, res <<= 1;
  82939. } while (--len > 0);
  82940. return res >> 1;
  82941. }
  82942. /* ===========================================================================
  82943. * Flush the bit buffer, keeping at most 7 bits in it.
  82944. */
  82945. local void bi_flush (deflate_state *s)
  82946. {
  82947. if (s->bi_valid == 16) {
  82948. put_short(s, s->bi_buf);
  82949. s->bi_buf = 0;
  82950. s->bi_valid = 0;
  82951. } else if (s->bi_valid >= 8) {
  82952. put_byte(s, (Byte)s->bi_buf);
  82953. s->bi_buf >>= 8;
  82954. s->bi_valid -= 8;
  82955. }
  82956. }
  82957. /* ===========================================================================
  82958. * Flush the bit buffer and align the output on a byte boundary
  82959. */
  82960. local void bi_windup (deflate_state *s)
  82961. {
  82962. if (s->bi_valid > 8) {
  82963. put_short(s, s->bi_buf);
  82964. } else if (s->bi_valid > 0) {
  82965. put_byte(s, (Byte)s->bi_buf);
  82966. }
  82967. s->bi_buf = 0;
  82968. s->bi_valid = 0;
  82969. #ifdef DEBUG
  82970. s->bits_sent = (s->bits_sent+7) & ~7;
  82971. #endif
  82972. }
  82973. /* ===========================================================================
  82974. * Copy a stored block, storing first the length and its
  82975. * one's complement if requested.
  82976. */
  82977. local void copy_block(deflate_state *s,
  82978. charf *buf, /* the input data */
  82979. unsigned len, /* its length */
  82980. int header) /* true if block header must be written */
  82981. {
  82982. bi_windup(s); /* align on byte boundary */
  82983. s->last_eob_len = 8; /* enough lookahead for inflate */
  82984. if (header) {
  82985. put_short(s, (ush)len);
  82986. put_short(s, (ush)~len);
  82987. #ifdef DEBUG
  82988. s->bits_sent += 2*16;
  82989. #endif
  82990. }
  82991. #ifdef DEBUG
  82992. s->bits_sent += (ulg)len<<3;
  82993. #endif
  82994. while (len--) {
  82995. put_byte(s, *buf++);
  82996. }
  82997. }
  82998. /*** End of inlined file: trees.c ***/
  82999. /*** Start of inlined file: zutil.c ***/
  83000. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  83001. #ifndef NO_DUMMY_DECL
  83002. struct internal_state {int dummy;}; /* for buggy compilers */
  83003. #endif
  83004. const char * const z_errmsg[10] = {
  83005. "need dictionary", /* Z_NEED_DICT 2 */
  83006. "stream end", /* Z_STREAM_END 1 */
  83007. "", /* Z_OK 0 */
  83008. "file error", /* Z_ERRNO (-1) */
  83009. "stream error", /* Z_STREAM_ERROR (-2) */
  83010. "data error", /* Z_DATA_ERROR (-3) */
  83011. "insufficient memory", /* Z_MEM_ERROR (-4) */
  83012. "buffer error", /* Z_BUF_ERROR (-5) */
  83013. "incompatible version",/* Z_VERSION_ERROR (-6) */
  83014. ""};
  83015. /*const char * ZEXPORT zlibVersion()
  83016. {
  83017. return ZLIB_VERSION;
  83018. }
  83019. uLong ZEXPORT zlibCompileFlags()
  83020. {
  83021. uLong flags;
  83022. flags = 0;
  83023. switch (sizeof(uInt)) {
  83024. case 2: break;
  83025. case 4: flags += 1; break;
  83026. case 8: flags += 2; break;
  83027. default: flags += 3;
  83028. }
  83029. switch (sizeof(uLong)) {
  83030. case 2: break;
  83031. case 4: flags += 1 << 2; break;
  83032. case 8: flags += 2 << 2; break;
  83033. default: flags += 3 << 2;
  83034. }
  83035. switch (sizeof(voidpf)) {
  83036. case 2: break;
  83037. case 4: flags += 1 << 4; break;
  83038. case 8: flags += 2 << 4; break;
  83039. default: flags += 3 << 4;
  83040. }
  83041. switch (sizeof(z_off_t)) {
  83042. case 2: break;
  83043. case 4: flags += 1 << 6; break;
  83044. case 8: flags += 2 << 6; break;
  83045. default: flags += 3 << 6;
  83046. }
  83047. #ifdef DEBUG
  83048. flags += 1 << 8;
  83049. #endif
  83050. #if defined(ASMV) || defined(ASMINF)
  83051. flags += 1 << 9;
  83052. #endif
  83053. #ifdef ZLIB_WINAPI
  83054. flags += 1 << 10;
  83055. #endif
  83056. #ifdef BUILDFIXED
  83057. flags += 1 << 12;
  83058. #endif
  83059. #ifdef DYNAMIC_CRC_TABLE
  83060. flags += 1 << 13;
  83061. #endif
  83062. #ifdef NO_GZCOMPRESS
  83063. flags += 1L << 16;
  83064. #endif
  83065. #ifdef NO_GZIP
  83066. flags += 1L << 17;
  83067. #endif
  83068. #ifdef PKZIP_BUG_WORKAROUND
  83069. flags += 1L << 20;
  83070. #endif
  83071. #ifdef FASTEST
  83072. flags += 1L << 21;
  83073. #endif
  83074. #ifdef STDC
  83075. # ifdef NO_vsnprintf
  83076. flags += 1L << 25;
  83077. # ifdef HAS_vsprintf_void
  83078. flags += 1L << 26;
  83079. # endif
  83080. # else
  83081. # ifdef HAS_vsnprintf_void
  83082. flags += 1L << 26;
  83083. # endif
  83084. # endif
  83085. #else
  83086. flags += 1L << 24;
  83087. # ifdef NO_snprintf
  83088. flags += 1L << 25;
  83089. # ifdef HAS_sprintf_void
  83090. flags += 1L << 26;
  83091. # endif
  83092. # else
  83093. # ifdef HAS_snprintf_void
  83094. flags += 1L << 26;
  83095. # endif
  83096. # endif
  83097. #endif
  83098. return flags;
  83099. }*/
  83100. #ifdef DEBUG
  83101. # ifndef verbose
  83102. # define verbose 0
  83103. # endif
  83104. int z_verbose = verbose;
  83105. void z_error (const char *m)
  83106. {
  83107. fprintf(stderr, "%s\n", m);
  83108. exit(1);
  83109. }
  83110. #endif
  83111. /* exported to allow conversion of error code to string for compress() and
  83112. * uncompress()
  83113. */
  83114. const char * ZEXPORT zError(int err)
  83115. {
  83116. return ERR_MSG(err);
  83117. }
  83118. #if defined(_WIN32_WCE)
  83119. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  83120. * errno. We define it as a global variable to simplify porting.
  83121. * Its value is always 0 and should not be used.
  83122. */
  83123. int errno = 0;
  83124. #endif
  83125. #ifndef HAVE_MEMCPY
  83126. void zmemcpy(dest, source, len)
  83127. Bytef* dest;
  83128. const Bytef* source;
  83129. uInt len;
  83130. {
  83131. if (len == 0) return;
  83132. do {
  83133. *dest++ = *source++; /* ??? to be unrolled */
  83134. } while (--len != 0);
  83135. }
  83136. int zmemcmp(s1, s2, len)
  83137. const Bytef* s1;
  83138. const Bytef* s2;
  83139. uInt len;
  83140. {
  83141. uInt j;
  83142. for (j = 0; j < len; j++) {
  83143. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  83144. }
  83145. return 0;
  83146. }
  83147. void zmemzero(dest, len)
  83148. Bytef* dest;
  83149. uInt len;
  83150. {
  83151. if (len == 0) return;
  83152. do {
  83153. *dest++ = 0; /* ??? to be unrolled */
  83154. } while (--len != 0);
  83155. }
  83156. #endif
  83157. #ifdef SYS16BIT
  83158. #ifdef __TURBOC__
  83159. /* Turbo C in 16-bit mode */
  83160. # define MY_ZCALLOC
  83161. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  83162. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  83163. * must fix the pointer. Warning: the pointer must be put back to its
  83164. * original form in order to free it, use zcfree().
  83165. */
  83166. #define MAX_PTR 10
  83167. /* 10*64K = 640K */
  83168. local int next_ptr = 0;
  83169. typedef struct ptr_table_s {
  83170. voidpf org_ptr;
  83171. voidpf new_ptr;
  83172. } ptr_table;
  83173. local ptr_table table[MAX_PTR];
  83174. /* This table is used to remember the original form of pointers
  83175. * to large buffers (64K). Such pointers are normalized with a zero offset.
  83176. * Since MSDOS is not a preemptive multitasking OS, this table is not
  83177. * protected from concurrent access. This hack doesn't work anyway on
  83178. * a protected system like OS/2. Use Microsoft C instead.
  83179. */
  83180. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  83181. {
  83182. voidpf buf = opaque; /* just to make some compilers happy */
  83183. ulg bsize = (ulg)items*size;
  83184. /* If we allocate less than 65520 bytes, we assume that farmalloc
  83185. * will return a usable pointer which doesn't have to be normalized.
  83186. */
  83187. if (bsize < 65520L) {
  83188. buf = farmalloc(bsize);
  83189. if (*(ush*)&buf != 0) return buf;
  83190. } else {
  83191. buf = farmalloc(bsize + 16L);
  83192. }
  83193. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  83194. table[next_ptr].org_ptr = buf;
  83195. /* Normalize the pointer to seg:0 */
  83196. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  83197. *(ush*)&buf = 0;
  83198. table[next_ptr++].new_ptr = buf;
  83199. return buf;
  83200. }
  83201. void zcfree (voidpf opaque, voidpf ptr)
  83202. {
  83203. int n;
  83204. if (*(ush*)&ptr != 0) { /* object < 64K */
  83205. farfree(ptr);
  83206. return;
  83207. }
  83208. /* Find the original pointer */
  83209. for (n = 0; n < next_ptr; n++) {
  83210. if (ptr != table[n].new_ptr) continue;
  83211. farfree(table[n].org_ptr);
  83212. while (++n < next_ptr) {
  83213. table[n-1] = table[n];
  83214. }
  83215. next_ptr--;
  83216. return;
  83217. }
  83218. ptr = opaque; /* just to make some compilers happy */
  83219. Assert(0, "zcfree: ptr not found");
  83220. }
  83221. #endif /* __TURBOC__ */
  83222. #ifdef M_I86
  83223. /* Microsoft C in 16-bit mode */
  83224. # define MY_ZCALLOC
  83225. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  83226. # define _halloc halloc
  83227. # define _hfree hfree
  83228. #endif
  83229. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  83230. {
  83231. if (opaque) opaque = 0; /* to make compiler happy */
  83232. return _halloc((long)items, size);
  83233. }
  83234. void zcfree (voidpf opaque, voidpf ptr)
  83235. {
  83236. if (opaque) opaque = 0; /* to make compiler happy */
  83237. _hfree(ptr);
  83238. }
  83239. #endif /* M_I86 */
  83240. #endif /* SYS16BIT */
  83241. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  83242. #ifndef STDC
  83243. extern voidp malloc OF((uInt size));
  83244. extern voidp calloc OF((uInt items, uInt size));
  83245. extern void free OF((voidpf ptr));
  83246. #endif
  83247. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  83248. {
  83249. if (opaque) items += size - size; /* make compiler happy */
  83250. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  83251. (voidpf)calloc(items, size);
  83252. }
  83253. void zcfree (voidpf opaque, voidpf ptr)
  83254. {
  83255. free(ptr);
  83256. if (opaque) return; /* make compiler happy */
  83257. }
  83258. #endif /* MY_ZCALLOC */
  83259. /*** End of inlined file: zutil.c ***/
  83260. #undef Byte
  83261. }
  83262. #else
  83263. #include <zlib.h>
  83264. #endif
  83265. }
  83266. #if JUCE_MSVC
  83267. #pragma warning (pop)
  83268. #endif
  83269. BEGIN_JUCE_NAMESPACE
  83270. // internal helper object that holds the zlib structures so they don't have to be
  83271. // included publicly.
  83272. class GZIPDecompressHelper
  83273. {
  83274. public:
  83275. GZIPDecompressHelper (const bool noWrap)
  83276. : finished (true),
  83277. needsDictionary (false),
  83278. error (true),
  83279. streamIsValid (false),
  83280. data (0),
  83281. dataSize (0)
  83282. {
  83283. using namespace zlibNamespace;
  83284. zerostruct (stream);
  83285. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  83286. finished = error = ! streamIsValid;
  83287. }
  83288. ~GZIPDecompressHelper()
  83289. {
  83290. using namespace zlibNamespace;
  83291. if (streamIsValid)
  83292. inflateEnd (&stream);
  83293. }
  83294. bool needsInput() const throw() { return dataSize <= 0; }
  83295. void setInput (uint8* const data_, const int size) throw()
  83296. {
  83297. data = data_;
  83298. dataSize = size;
  83299. }
  83300. int doNextBlock (uint8* const dest, const int destSize)
  83301. {
  83302. using namespace zlibNamespace;
  83303. if (streamIsValid && data != 0 && ! finished)
  83304. {
  83305. stream.next_in = data;
  83306. stream.next_out = dest;
  83307. stream.avail_in = dataSize;
  83308. stream.avail_out = destSize;
  83309. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  83310. {
  83311. case Z_STREAM_END:
  83312. finished = true;
  83313. // deliberate fall-through
  83314. case Z_OK:
  83315. data += dataSize - stream.avail_in;
  83316. dataSize = stream.avail_in;
  83317. return destSize - stream.avail_out;
  83318. case Z_NEED_DICT:
  83319. needsDictionary = true;
  83320. data += dataSize - stream.avail_in;
  83321. dataSize = stream.avail_in;
  83322. break;
  83323. case Z_DATA_ERROR:
  83324. case Z_MEM_ERROR:
  83325. error = true;
  83326. default:
  83327. break;
  83328. }
  83329. }
  83330. return 0;
  83331. }
  83332. bool finished, needsDictionary, error, streamIsValid;
  83333. private:
  83334. zlibNamespace::z_stream stream;
  83335. uint8* data;
  83336. int dataSize;
  83337. GZIPDecompressHelper (const GZIPDecompressHelper&);
  83338. GZIPDecompressHelper& operator= (const GZIPDecompressHelper&);
  83339. };
  83340. const int gzipDecompBufferSize = 32768;
  83341. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  83342. const bool deleteSourceWhenDestroyed,
  83343. const bool noWrap_,
  83344. const int64 uncompressedStreamLength_)
  83345. : sourceStream (sourceStream_),
  83346. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  83347. uncompressedStreamLength (uncompressedStreamLength_),
  83348. noWrap (noWrap_),
  83349. isEof (false),
  83350. activeBufferSize (0),
  83351. originalSourcePos (sourceStream_->getPosition()),
  83352. currentPos (0),
  83353. buffer (gzipDecompBufferSize),
  83354. helper (new GZIPDecompressHelper (noWrap_))
  83355. {
  83356. }
  83357. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  83358. {
  83359. }
  83360. int64 GZIPDecompressorInputStream::getTotalLength()
  83361. {
  83362. return uncompressedStreamLength;
  83363. }
  83364. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  83365. {
  83366. if ((howMany > 0) && ! isEof)
  83367. {
  83368. jassert (destBuffer != 0);
  83369. if (destBuffer != 0)
  83370. {
  83371. int numRead = 0;
  83372. uint8* d = static_cast <uint8*> (destBuffer);
  83373. while (! helper->error)
  83374. {
  83375. const int n = helper->doNextBlock (d, howMany);
  83376. currentPos += n;
  83377. if (n == 0)
  83378. {
  83379. if (helper->finished || helper->needsDictionary)
  83380. {
  83381. isEof = true;
  83382. return numRead;
  83383. }
  83384. if (helper->needsInput())
  83385. {
  83386. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  83387. if (activeBufferSize > 0)
  83388. {
  83389. helper->setInput (buffer, activeBufferSize);
  83390. }
  83391. else
  83392. {
  83393. isEof = true;
  83394. return numRead;
  83395. }
  83396. }
  83397. }
  83398. else
  83399. {
  83400. numRead += n;
  83401. howMany -= n;
  83402. d += n;
  83403. if (howMany <= 0)
  83404. return numRead;
  83405. }
  83406. }
  83407. }
  83408. }
  83409. return 0;
  83410. }
  83411. bool GZIPDecompressorInputStream::isExhausted()
  83412. {
  83413. return helper->error || isEof;
  83414. }
  83415. int64 GZIPDecompressorInputStream::getPosition()
  83416. {
  83417. return currentPos;
  83418. }
  83419. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  83420. {
  83421. if (newPos < currentPos)
  83422. {
  83423. // to go backwards, reset the stream and start again..
  83424. isEof = false;
  83425. activeBufferSize = 0;
  83426. currentPos = 0;
  83427. helper = new GZIPDecompressHelper (noWrap);
  83428. sourceStream->setPosition (originalSourcePos);
  83429. }
  83430. skipNextBytes (newPos - currentPos);
  83431. return true;
  83432. }
  83433. END_JUCE_NAMESPACE
  83434. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  83435. #endif
  83436. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  83437. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  83438. #if JUCE_USE_FLAC
  83439. #if JUCE_WINDOWS
  83440. #include <windows.h>
  83441. #endif
  83442. namespace FlacNamespace
  83443. {
  83444. #if JUCE_INCLUDE_FLAC_CODE
  83445. #if JUCE_MSVC
  83446. #pragma warning (disable : 4505) // (unreferenced static function removal warning)
  83447. #endif
  83448. #define FLAC__NO_DLL 1
  83449. #if ! defined (SIZE_MAX)
  83450. #define SIZE_MAX 0xffffffff
  83451. #endif
  83452. #define __STDC_LIMIT_MACROS 1
  83453. /*** Start of inlined file: all.h ***/
  83454. #ifndef FLAC__ALL_H
  83455. #define FLAC__ALL_H
  83456. /*** Start of inlined file: export.h ***/
  83457. #ifndef FLAC__EXPORT_H
  83458. #define FLAC__EXPORT_H
  83459. /** \file include/FLAC/export.h
  83460. *
  83461. * \brief
  83462. * This module contains #defines and symbols for exporting function
  83463. * calls, and providing version information and compiled-in features.
  83464. *
  83465. * See the \link flac_export export \endlink module.
  83466. */
  83467. /** \defgroup flac_export FLAC/export.h: export symbols
  83468. * \ingroup flac
  83469. *
  83470. * \brief
  83471. * This module contains #defines and symbols for exporting function
  83472. * calls, and providing version information and compiled-in features.
  83473. *
  83474. * If you are compiling with MSVC and will link to the static library
  83475. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  83476. * make sure the symbols are exported properly.
  83477. *
  83478. * \{
  83479. */
  83480. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  83481. #define FLAC_API
  83482. #else
  83483. #ifdef FLAC_API_EXPORTS
  83484. #define FLAC_API _declspec(dllexport)
  83485. #else
  83486. #define FLAC_API _declspec(dllimport)
  83487. #endif
  83488. #endif
  83489. /** These #defines will mirror the libtool-based library version number, see
  83490. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  83491. */
  83492. #define FLAC_API_VERSION_CURRENT 10
  83493. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  83494. #define FLAC_API_VERSION_AGE 2 /**< see above */
  83495. #ifdef __cplusplus
  83496. extern "C" {
  83497. #endif
  83498. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  83499. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  83500. #ifdef __cplusplus
  83501. }
  83502. #endif
  83503. /* \} */
  83504. #endif
  83505. /*** End of inlined file: export.h ***/
  83506. /*** Start of inlined file: assert.h ***/
  83507. #ifndef FLAC__ASSERT_H
  83508. #define FLAC__ASSERT_H
  83509. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  83510. #ifdef DEBUG
  83511. #include <assert.h>
  83512. #define FLAC__ASSERT(x) assert(x)
  83513. #define FLAC__ASSERT_DECLARATION(x) x
  83514. #else
  83515. #define FLAC__ASSERT(x)
  83516. #define FLAC__ASSERT_DECLARATION(x)
  83517. #endif
  83518. #endif
  83519. /*** End of inlined file: assert.h ***/
  83520. /*** Start of inlined file: callback.h ***/
  83521. #ifndef FLAC__CALLBACK_H
  83522. #define FLAC__CALLBACK_H
  83523. /*** Start of inlined file: ordinals.h ***/
  83524. #ifndef FLAC__ORDINALS_H
  83525. #define FLAC__ORDINALS_H
  83526. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  83527. #include <inttypes.h>
  83528. #endif
  83529. typedef signed char FLAC__int8;
  83530. typedef unsigned char FLAC__uint8;
  83531. #if defined(_MSC_VER) || defined(__BORLANDC__)
  83532. typedef __int16 FLAC__int16;
  83533. typedef __int32 FLAC__int32;
  83534. typedef __int64 FLAC__int64;
  83535. typedef unsigned __int16 FLAC__uint16;
  83536. typedef unsigned __int32 FLAC__uint32;
  83537. typedef unsigned __int64 FLAC__uint64;
  83538. #elif defined(__EMX__)
  83539. typedef short FLAC__int16;
  83540. typedef long FLAC__int32;
  83541. typedef long long FLAC__int64;
  83542. typedef unsigned short FLAC__uint16;
  83543. typedef unsigned long FLAC__uint32;
  83544. typedef unsigned long long FLAC__uint64;
  83545. #else
  83546. typedef int16_t FLAC__int16;
  83547. typedef int32_t FLAC__int32;
  83548. typedef int64_t FLAC__int64;
  83549. typedef uint16_t FLAC__uint16;
  83550. typedef uint32_t FLAC__uint32;
  83551. typedef uint64_t FLAC__uint64;
  83552. #endif
  83553. typedef int FLAC__bool;
  83554. typedef FLAC__uint8 FLAC__byte;
  83555. #ifdef true
  83556. #undef true
  83557. #endif
  83558. #ifdef false
  83559. #undef false
  83560. #endif
  83561. #ifndef __cplusplus
  83562. #define true 1
  83563. #define false 0
  83564. #endif
  83565. #endif
  83566. /*** End of inlined file: ordinals.h ***/
  83567. #include <stdlib.h> /* for size_t */
  83568. /** \file include/FLAC/callback.h
  83569. *
  83570. * \brief
  83571. * This module defines the structures for describing I/O callbacks
  83572. * to the other FLAC interfaces.
  83573. *
  83574. * See the detailed documentation for callbacks in the
  83575. * \link flac_callbacks callbacks \endlink module.
  83576. */
  83577. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  83578. * \ingroup flac
  83579. *
  83580. * \brief
  83581. * This module defines the structures for describing I/O callbacks
  83582. * to the other FLAC interfaces.
  83583. *
  83584. * The purpose of the I/O callback functions is to create a common way
  83585. * for the metadata interfaces to handle I/O.
  83586. *
  83587. * Originally the metadata interfaces required filenames as the way of
  83588. * specifying FLAC files to operate on. This is problematic in some
  83589. * environments so there is an additional option to specify a set of
  83590. * callbacks for doing I/O on the FLAC file, instead of the filename.
  83591. *
  83592. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  83593. * opaque structure for a data source.
  83594. *
  83595. * The callback function prototypes are similar (but not identical) to the
  83596. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  83597. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  83598. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  83599. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  83600. * is required. \warning You generally CANNOT directly use fseek or ftell
  83601. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  83602. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  83603. * large files. You will have to find an equivalent function (e.g. ftello),
  83604. * or write a wrapper. The same is true for feof() since this is usually
  83605. * implemented as a macro, not as a function whose address can be taken.
  83606. *
  83607. * \{
  83608. */
  83609. #ifdef __cplusplus
  83610. extern "C" {
  83611. #endif
  83612. /** This is the opaque handle type used by the callbacks. Typically
  83613. * this is a \c FILE* or address of a file descriptor.
  83614. */
  83615. typedef void* FLAC__IOHandle;
  83616. /** Signature for the read callback.
  83617. * The signature and semantics match POSIX fread() implementations
  83618. * and can generally be used interchangeably.
  83619. *
  83620. * \param ptr The address of the read buffer.
  83621. * \param size The size of the records to be read.
  83622. * \param nmemb The number of records to be read.
  83623. * \param handle The handle to the data source.
  83624. * \retval size_t
  83625. * The number of records read.
  83626. */
  83627. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  83628. /** Signature for the write callback.
  83629. * The signature and semantics match POSIX fwrite() implementations
  83630. * and can generally be used interchangeably.
  83631. *
  83632. * \param ptr The address of the write buffer.
  83633. * \param size The size of the records to be written.
  83634. * \param nmemb The number of records to be written.
  83635. * \param handle The handle to the data source.
  83636. * \retval size_t
  83637. * The number of records written.
  83638. */
  83639. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  83640. /** Signature for the seek callback.
  83641. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  83642. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  83643. * and 32-bits wide.
  83644. *
  83645. * \param handle The handle to the data source.
  83646. * \param offset The new position, relative to \a whence
  83647. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  83648. * \retval int
  83649. * \c 0 on success, \c -1 on error.
  83650. */
  83651. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  83652. /** Signature for the tell callback.
  83653. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  83654. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  83655. * and 32-bits wide.
  83656. *
  83657. * \param handle The handle to the data source.
  83658. * \retval FLAC__int64
  83659. * The current position on success, \c -1 on error.
  83660. */
  83661. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  83662. /** Signature for the EOF callback.
  83663. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  83664. * on many systems, feof() is a macro, so in this case a wrapper function
  83665. * must be provided instead.
  83666. *
  83667. * \param handle The handle to the data source.
  83668. * \retval int
  83669. * \c 0 if not at end of file, nonzero if at end of file.
  83670. */
  83671. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  83672. /** Signature for the close callback.
  83673. * The signature and semantics match POSIX fclose() implementations
  83674. * and can generally be used interchangeably.
  83675. *
  83676. * \param handle The handle to the data source.
  83677. * \retval int
  83678. * \c 0 on success, \c EOF on error.
  83679. */
  83680. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  83681. /** A structure for holding a set of callbacks.
  83682. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  83683. * describe which of the callbacks are required. The ones that are not
  83684. * required may be set to NULL.
  83685. *
  83686. * If the seek requirement for an interface is optional, you can signify that
  83687. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  83688. */
  83689. typedef struct {
  83690. FLAC__IOCallback_Read read;
  83691. FLAC__IOCallback_Write write;
  83692. FLAC__IOCallback_Seek seek;
  83693. FLAC__IOCallback_Tell tell;
  83694. FLAC__IOCallback_Eof eof;
  83695. FLAC__IOCallback_Close close;
  83696. } FLAC__IOCallbacks;
  83697. /* \} */
  83698. #ifdef __cplusplus
  83699. }
  83700. #endif
  83701. #endif
  83702. /*** End of inlined file: callback.h ***/
  83703. /*** Start of inlined file: format.h ***/
  83704. #ifndef FLAC__FORMAT_H
  83705. #define FLAC__FORMAT_H
  83706. #ifdef __cplusplus
  83707. extern "C" {
  83708. #endif
  83709. /** \file include/FLAC/format.h
  83710. *
  83711. * \brief
  83712. * This module contains structure definitions for the representation
  83713. * of FLAC format components in memory. These are the basic
  83714. * structures used by the rest of the interfaces.
  83715. *
  83716. * See the detailed documentation in the
  83717. * \link flac_format format \endlink module.
  83718. */
  83719. /** \defgroup flac_format FLAC/format.h: format components
  83720. * \ingroup flac
  83721. *
  83722. * \brief
  83723. * This module contains structure definitions for the representation
  83724. * of FLAC format components in memory. These are the basic
  83725. * structures used by the rest of the interfaces.
  83726. *
  83727. * First, you should be familiar with the
  83728. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  83729. * follow directly from the specification. As a user of libFLAC, the
  83730. * interesting parts really are the structures that describe the frame
  83731. * header and metadata blocks.
  83732. *
  83733. * The format structures here are very primitive, designed to store
  83734. * information in an efficient way. Reading information from the
  83735. * structures is easy but creating or modifying them directly is
  83736. * more complex. For the most part, as a user of a library, editing
  83737. * is not necessary; however, for metadata blocks it is, so there are
  83738. * convenience functions provided in the \link flac_metadata metadata
  83739. * module \endlink to simplify the manipulation of metadata blocks.
  83740. *
  83741. * \note
  83742. * It's not the best convention, but symbols ending in _LEN are in bits
  83743. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  83744. * global variables because they are usually used when declaring byte
  83745. * arrays and some compilers require compile-time knowledge of array
  83746. * sizes when declared on the stack.
  83747. *
  83748. * \{
  83749. */
  83750. /*
  83751. Most of the values described in this file are defined by the FLAC
  83752. format specification. There is nothing to tune here.
  83753. */
  83754. /** The largest legal metadata type code. */
  83755. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  83756. /** The minimum block size, in samples, permitted by the format. */
  83757. #define FLAC__MIN_BLOCK_SIZE (16u)
  83758. /** The maximum block size, in samples, permitted by the format. */
  83759. #define FLAC__MAX_BLOCK_SIZE (65535u)
  83760. /** The maximum block size, in samples, permitted by the FLAC subset for
  83761. * sample rates up to 48kHz. */
  83762. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  83763. /** The maximum number of channels permitted by the format. */
  83764. #define FLAC__MAX_CHANNELS (8u)
  83765. /** The minimum sample resolution permitted by the format. */
  83766. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  83767. /** The maximum sample resolution permitted by the format. */
  83768. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  83769. /** The maximum sample resolution permitted by libFLAC.
  83770. *
  83771. * \warning
  83772. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  83773. * the reference encoder/decoder is currently limited to 24 bits because
  83774. * of prevalent 32-bit math, so make sure and use this value when
  83775. * appropriate.
  83776. */
  83777. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  83778. /** The maximum sample rate permitted by the format. The value is
  83779. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  83780. * as to why.
  83781. */
  83782. #define FLAC__MAX_SAMPLE_RATE (655350u)
  83783. /** The maximum LPC order permitted by the format. */
  83784. #define FLAC__MAX_LPC_ORDER (32u)
  83785. /** The maximum LPC order permitted by the FLAC subset for sample rates
  83786. * up to 48kHz. */
  83787. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  83788. /** The minimum quantized linear predictor coefficient precision
  83789. * permitted by the format.
  83790. */
  83791. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  83792. /** The maximum quantized linear predictor coefficient precision
  83793. * permitted by the format.
  83794. */
  83795. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  83796. /** The maximum order of the fixed predictors permitted by the format. */
  83797. #define FLAC__MAX_FIXED_ORDER (4u)
  83798. /** The maximum Rice partition order permitted by the format. */
  83799. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  83800. /** The maximum Rice partition order permitted by the FLAC Subset. */
  83801. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  83802. /** The version string of the release, stamped onto the libraries and binaries.
  83803. *
  83804. * \note
  83805. * This does not correspond to the shared library version number, which
  83806. * is used to determine binary compatibility.
  83807. */
  83808. extern FLAC_API const char *FLAC__VERSION_STRING;
  83809. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  83810. * This is a NUL-terminated ASCII string; when inserted into the
  83811. * VORBIS_COMMENT the trailing null is stripped.
  83812. */
  83813. extern FLAC_API const char *FLAC__VENDOR_STRING;
  83814. /** The byte string representation of the beginning of a FLAC stream. */
  83815. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  83816. /** The 32-bit integer big-endian representation of the beginning of
  83817. * a FLAC stream.
  83818. */
  83819. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  83820. /** The length of the FLAC signature in bits. */
  83821. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  83822. /** The length of the FLAC signature in bytes. */
  83823. #define FLAC__STREAM_SYNC_LENGTH (4u)
  83824. /*****************************************************************************
  83825. *
  83826. * Subframe structures
  83827. *
  83828. *****************************************************************************/
  83829. /*****************************************************************************/
  83830. /** An enumeration of the available entropy coding methods. */
  83831. typedef enum {
  83832. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  83833. /**< Residual is coded by partitioning into contexts, each with it's own
  83834. * 4-bit Rice parameter. */
  83835. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  83836. /**< Residual is coded by partitioning into contexts, each with it's own
  83837. * 5-bit Rice parameter. */
  83838. } FLAC__EntropyCodingMethodType;
  83839. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  83840. *
  83841. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  83842. * give the string equivalent. The contents should not be modified.
  83843. */
  83844. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  83845. /** Contents of a Rice partitioned residual
  83846. */
  83847. typedef struct {
  83848. unsigned *parameters;
  83849. /**< The Rice parameters for each context. */
  83850. unsigned *raw_bits;
  83851. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  83852. * partitions and zero for unescaped partitions.
  83853. */
  83854. unsigned capacity_by_order;
  83855. /**< The capacity of the \a parameters and \a raw_bits arrays
  83856. * specified as an order, i.e. the number of array elements
  83857. * allocated is 2 ^ \a capacity_by_order.
  83858. */
  83859. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  83860. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  83861. */
  83862. typedef struct {
  83863. unsigned order;
  83864. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  83865. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  83866. /**< The context's Rice parameters and/or raw bits. */
  83867. } FLAC__EntropyCodingMethod_PartitionedRice;
  83868. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  83869. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  83870. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  83871. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  83872. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  83873. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  83874. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  83875. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  83876. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  83877. */
  83878. typedef struct {
  83879. FLAC__EntropyCodingMethodType type;
  83880. union {
  83881. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  83882. } data;
  83883. } FLAC__EntropyCodingMethod;
  83884. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  83885. /*****************************************************************************/
  83886. /** An enumeration of the available subframe types. */
  83887. typedef enum {
  83888. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  83889. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  83890. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  83891. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  83892. } FLAC__SubframeType;
  83893. /** Maps a FLAC__SubframeType to a C string.
  83894. *
  83895. * Using a FLAC__SubframeType as the index to this array will
  83896. * give the string equivalent. The contents should not be modified.
  83897. */
  83898. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  83899. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  83900. */
  83901. typedef struct {
  83902. FLAC__int32 value; /**< The constant signal value. */
  83903. } FLAC__Subframe_Constant;
  83904. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  83905. */
  83906. typedef struct {
  83907. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  83908. } FLAC__Subframe_Verbatim;
  83909. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  83910. */
  83911. typedef struct {
  83912. FLAC__EntropyCodingMethod entropy_coding_method;
  83913. /**< The residual coding method. */
  83914. unsigned order;
  83915. /**< The polynomial order. */
  83916. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  83917. /**< Warmup samples to prime the predictor, length == order. */
  83918. const FLAC__int32 *residual;
  83919. /**< The residual signal, length == (blocksize minus order) samples. */
  83920. } FLAC__Subframe_Fixed;
  83921. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  83922. */
  83923. typedef struct {
  83924. FLAC__EntropyCodingMethod entropy_coding_method;
  83925. /**< The residual coding method. */
  83926. unsigned order;
  83927. /**< The FIR order. */
  83928. unsigned qlp_coeff_precision;
  83929. /**< Quantized FIR filter coefficient precision in bits. */
  83930. int quantization_level;
  83931. /**< The qlp coeff shift needed. */
  83932. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  83933. /**< FIR filter coefficients. */
  83934. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  83935. /**< Warmup samples to prime the predictor, length == order. */
  83936. const FLAC__int32 *residual;
  83937. /**< The residual signal, length == (blocksize minus order) samples. */
  83938. } FLAC__Subframe_LPC;
  83939. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  83940. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  83941. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  83942. */
  83943. typedef struct {
  83944. FLAC__SubframeType type;
  83945. union {
  83946. FLAC__Subframe_Constant constant;
  83947. FLAC__Subframe_Fixed fixed;
  83948. FLAC__Subframe_LPC lpc;
  83949. FLAC__Subframe_Verbatim verbatim;
  83950. } data;
  83951. unsigned wasted_bits;
  83952. } FLAC__Subframe;
  83953. /** == 1 (bit)
  83954. *
  83955. * This used to be a zero-padding bit (hence the name
  83956. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  83957. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  83958. * to mean something else.
  83959. */
  83960. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  83961. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  83962. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  83963. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  83964. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  83965. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  83966. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  83967. /*****************************************************************************/
  83968. /*****************************************************************************
  83969. *
  83970. * Frame structures
  83971. *
  83972. *****************************************************************************/
  83973. /** An enumeration of the available channel assignments. */
  83974. typedef enum {
  83975. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  83976. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  83977. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  83978. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  83979. } FLAC__ChannelAssignment;
  83980. /** Maps a FLAC__ChannelAssignment to a C string.
  83981. *
  83982. * Using a FLAC__ChannelAssignment as the index to this array will
  83983. * give the string equivalent. The contents should not be modified.
  83984. */
  83985. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  83986. /** An enumeration of the possible frame numbering methods. */
  83987. typedef enum {
  83988. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  83989. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  83990. } FLAC__FrameNumberType;
  83991. /** Maps a FLAC__FrameNumberType to a C string.
  83992. *
  83993. * Using a FLAC__FrameNumberType as the index to this array will
  83994. * give the string equivalent. The contents should not be modified.
  83995. */
  83996. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  83997. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  83998. */
  83999. typedef struct {
  84000. unsigned blocksize;
  84001. /**< The number of samples per subframe. */
  84002. unsigned sample_rate;
  84003. /**< The sample rate in Hz. */
  84004. unsigned channels;
  84005. /**< The number of channels (== number of subframes). */
  84006. FLAC__ChannelAssignment channel_assignment;
  84007. /**< The channel assignment for the frame. */
  84008. unsigned bits_per_sample;
  84009. /**< The sample resolution. */
  84010. FLAC__FrameNumberType number_type;
  84011. /**< The numbering scheme used for the frame. As a convenience, the
  84012. * decoder will always convert a frame number to a sample number because
  84013. * the rules are complex. */
  84014. union {
  84015. FLAC__uint32 frame_number;
  84016. FLAC__uint64 sample_number;
  84017. } number;
  84018. /**< The frame number or sample number of first sample in frame;
  84019. * use the \a number_type value to determine which to use. */
  84020. FLAC__uint8 crc;
  84021. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  84022. * of the raw frame header bytes, meaning everything before the CRC byte
  84023. * including the sync code.
  84024. */
  84025. } FLAC__FrameHeader;
  84026. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  84027. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  84028. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  84029. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  84030. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  84031. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  84032. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  84033. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  84034. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  84035. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  84036. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  84037. */
  84038. typedef struct {
  84039. FLAC__uint16 crc;
  84040. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  84041. * 0) of the bytes before the crc, back to and including the frame header
  84042. * sync code.
  84043. */
  84044. } FLAC__FrameFooter;
  84045. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  84046. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  84047. */
  84048. typedef struct {
  84049. FLAC__FrameHeader header;
  84050. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  84051. FLAC__FrameFooter footer;
  84052. } FLAC__Frame;
  84053. /*****************************************************************************/
  84054. /*****************************************************************************
  84055. *
  84056. * Meta-data structures
  84057. *
  84058. *****************************************************************************/
  84059. /** An enumeration of the available metadata block types. */
  84060. typedef enum {
  84061. FLAC__METADATA_TYPE_STREAMINFO = 0,
  84062. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  84063. FLAC__METADATA_TYPE_PADDING = 1,
  84064. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  84065. FLAC__METADATA_TYPE_APPLICATION = 2,
  84066. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  84067. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  84068. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  84069. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  84070. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  84071. FLAC__METADATA_TYPE_CUESHEET = 5,
  84072. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  84073. FLAC__METADATA_TYPE_PICTURE = 6,
  84074. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  84075. FLAC__METADATA_TYPE_UNDEFINED = 7
  84076. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  84077. } FLAC__MetadataType;
  84078. /** Maps a FLAC__MetadataType to a C string.
  84079. *
  84080. * Using a FLAC__MetadataType as the index to this array will
  84081. * give the string equivalent. The contents should not be modified.
  84082. */
  84083. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  84084. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  84085. */
  84086. typedef struct {
  84087. unsigned min_blocksize, max_blocksize;
  84088. unsigned min_framesize, max_framesize;
  84089. unsigned sample_rate;
  84090. unsigned channels;
  84091. unsigned bits_per_sample;
  84092. FLAC__uint64 total_samples;
  84093. FLAC__byte md5sum[16];
  84094. } FLAC__StreamMetadata_StreamInfo;
  84095. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  84096. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  84097. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  84098. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  84099. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  84100. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  84101. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  84102. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  84103. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  84104. /** The total stream length of the STREAMINFO block in bytes. */
  84105. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  84106. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  84107. */
  84108. typedef struct {
  84109. int dummy;
  84110. /**< Conceptually this is an empty struct since we don't store the
  84111. * padding bytes. Empty structs are not allowed by some C compilers,
  84112. * hence the dummy.
  84113. */
  84114. } FLAC__StreamMetadata_Padding;
  84115. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  84116. */
  84117. typedef struct {
  84118. FLAC__byte id[4];
  84119. FLAC__byte *data;
  84120. } FLAC__StreamMetadata_Application;
  84121. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  84122. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  84123. */
  84124. typedef struct {
  84125. FLAC__uint64 sample_number;
  84126. /**< The sample number of the target frame. */
  84127. FLAC__uint64 stream_offset;
  84128. /**< The offset, in bytes, of the target frame with respect to
  84129. * beginning of the first frame. */
  84130. unsigned frame_samples;
  84131. /**< The number of samples in the target frame. */
  84132. } FLAC__StreamMetadata_SeekPoint;
  84133. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  84134. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  84135. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  84136. /** The total stream length of a seek point in bytes. */
  84137. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  84138. /** The value used in the \a sample_number field of
  84139. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  84140. * point (== 0xffffffffffffffff).
  84141. */
  84142. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  84143. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  84144. *
  84145. * \note From the format specification:
  84146. * - The seek points must be sorted by ascending sample number.
  84147. * - Each seek point's sample number must be the first sample of the
  84148. * target frame.
  84149. * - Each seek point's sample number must be unique within the table.
  84150. * - Existence of a SEEKTABLE block implies a correct setting of
  84151. * total_samples in the stream_info block.
  84152. * - Behavior is undefined when more than one SEEKTABLE block is
  84153. * present in a stream.
  84154. */
  84155. typedef struct {
  84156. unsigned num_points;
  84157. FLAC__StreamMetadata_SeekPoint *points;
  84158. } FLAC__StreamMetadata_SeekTable;
  84159. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  84160. *
  84161. * For convenience, the APIs maintain a trailing NUL character at the end of
  84162. * \a entry which is not counted toward \a length, i.e.
  84163. * \code strlen(entry) == length \endcode
  84164. */
  84165. typedef struct {
  84166. FLAC__uint32 length;
  84167. FLAC__byte *entry;
  84168. } FLAC__StreamMetadata_VorbisComment_Entry;
  84169. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  84170. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  84171. */
  84172. typedef struct {
  84173. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  84174. FLAC__uint32 num_comments;
  84175. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  84176. } FLAC__StreamMetadata_VorbisComment;
  84177. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  84178. /** FLAC CUESHEET track index structure. (See the
  84179. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  84180. * the full description of each field.)
  84181. */
  84182. typedef struct {
  84183. FLAC__uint64 offset;
  84184. /**< Offset in samples, relative to the track offset, of the index
  84185. * point.
  84186. */
  84187. FLAC__byte number;
  84188. /**< The index point number. */
  84189. } FLAC__StreamMetadata_CueSheet_Index;
  84190. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  84191. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  84192. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  84193. /** FLAC CUESHEET track structure. (See the
  84194. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  84195. * the full description of each field.)
  84196. */
  84197. typedef struct {
  84198. FLAC__uint64 offset;
  84199. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  84200. FLAC__byte number;
  84201. /**< The track number. */
  84202. char isrc[13];
  84203. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  84204. unsigned type:1;
  84205. /**< The track type: 0 for audio, 1 for non-audio. */
  84206. unsigned pre_emphasis:1;
  84207. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  84208. FLAC__byte num_indices;
  84209. /**< The number of track index points. */
  84210. FLAC__StreamMetadata_CueSheet_Index *indices;
  84211. /**< NULL if num_indices == 0, else pointer to array of index points. */
  84212. } FLAC__StreamMetadata_CueSheet_Track;
  84213. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  84214. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  84215. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  84216. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  84217. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  84218. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  84219. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  84220. /** FLAC CUESHEET structure. (See the
  84221. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  84222. * for the full description of each field.)
  84223. */
  84224. typedef struct {
  84225. char media_catalog_number[129];
  84226. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  84227. * general, the media catalog number may be 0 to 128 bytes long; any
  84228. * unused characters should be right-padded with NUL characters.
  84229. */
  84230. FLAC__uint64 lead_in;
  84231. /**< The number of lead-in samples. */
  84232. FLAC__bool is_cd;
  84233. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  84234. unsigned num_tracks;
  84235. /**< The number of tracks. */
  84236. FLAC__StreamMetadata_CueSheet_Track *tracks;
  84237. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  84238. } FLAC__StreamMetadata_CueSheet;
  84239. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  84240. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  84241. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  84242. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  84243. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  84244. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  84245. typedef enum {
  84246. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  84247. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  84248. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  84249. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  84250. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  84251. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  84252. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  84253. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  84254. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  84255. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  84256. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  84257. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  84258. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  84259. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  84260. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  84261. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  84262. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  84263. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  84264. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  84265. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  84266. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  84267. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  84268. } FLAC__StreamMetadata_Picture_Type;
  84269. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  84270. *
  84271. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  84272. * will give the string equivalent. The contents should not be
  84273. * modified.
  84274. */
  84275. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  84276. /** FLAC PICTURE structure. (See the
  84277. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  84278. * for the full description of each field.)
  84279. */
  84280. typedef struct {
  84281. FLAC__StreamMetadata_Picture_Type type;
  84282. /**< The kind of picture stored. */
  84283. char *mime_type;
  84284. /**< Picture data's MIME type, in ASCII printable characters
  84285. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  84286. * use picture data of MIME type \c image/jpeg or \c image/png. A
  84287. * MIME type of '-->' is also allowed, in which case the picture
  84288. * data should be a complete URL. In file storage, the MIME type is
  84289. * stored as a 32-bit length followed by the ASCII string with no NUL
  84290. * terminator, but is converted to a plain C string in this structure
  84291. * for convenience.
  84292. */
  84293. FLAC__byte *description;
  84294. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  84295. * the description is stored as a 32-bit length followed by the UTF-8
  84296. * string with no NUL terminator, but is converted to a plain C string
  84297. * in this structure for convenience.
  84298. */
  84299. FLAC__uint32 width;
  84300. /**< Picture's width in pixels. */
  84301. FLAC__uint32 height;
  84302. /**< Picture's height in pixels. */
  84303. FLAC__uint32 depth;
  84304. /**< Picture's color depth in bits-per-pixel. */
  84305. FLAC__uint32 colors;
  84306. /**< For indexed palettes (like GIF), picture's number of colors (the
  84307. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  84308. */
  84309. FLAC__uint32 data_length;
  84310. /**< Length of binary picture data in bytes. */
  84311. FLAC__byte *data;
  84312. /**< Binary picture data. */
  84313. } FLAC__StreamMetadata_Picture;
  84314. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  84315. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  84316. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  84317. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  84318. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  84319. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  84320. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  84321. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  84322. /** Structure that is used when a metadata block of unknown type is loaded.
  84323. * The contents are opaque. The structure is used only internally to
  84324. * correctly handle unknown metadata.
  84325. */
  84326. typedef struct {
  84327. FLAC__byte *data;
  84328. } FLAC__StreamMetadata_Unknown;
  84329. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  84330. */
  84331. typedef struct {
  84332. FLAC__MetadataType type;
  84333. /**< The type of the metadata block; used determine which member of the
  84334. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  84335. * then \a data.unknown must be used. */
  84336. FLAC__bool is_last;
  84337. /**< \c true if this metadata block is the last, else \a false */
  84338. unsigned length;
  84339. /**< Length, in bytes, of the block data as it appears in the stream. */
  84340. union {
  84341. FLAC__StreamMetadata_StreamInfo stream_info;
  84342. FLAC__StreamMetadata_Padding padding;
  84343. FLAC__StreamMetadata_Application application;
  84344. FLAC__StreamMetadata_SeekTable seek_table;
  84345. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  84346. FLAC__StreamMetadata_CueSheet cue_sheet;
  84347. FLAC__StreamMetadata_Picture picture;
  84348. FLAC__StreamMetadata_Unknown unknown;
  84349. } data;
  84350. /**< Polymorphic block data; use the \a type value to determine which
  84351. * to use. */
  84352. } FLAC__StreamMetadata;
  84353. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  84354. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  84355. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  84356. /** The total stream length of a metadata block header in bytes. */
  84357. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  84358. /*****************************************************************************/
  84359. /*****************************************************************************
  84360. *
  84361. * Utility functions
  84362. *
  84363. *****************************************************************************/
  84364. /** Tests that a sample rate is valid for FLAC.
  84365. *
  84366. * \param sample_rate The sample rate to test for compliance.
  84367. * \retval FLAC__bool
  84368. * \c true if the given sample rate conforms to the specification, else
  84369. * \c false.
  84370. */
  84371. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  84372. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  84373. * for valid sample rates are slightly more complex since the rate has to
  84374. * be expressible completely in the frame header.
  84375. *
  84376. * \param sample_rate The sample rate to test for compliance.
  84377. * \retval FLAC__bool
  84378. * \c true if the given sample rate conforms to the specification for the
  84379. * subset, else \c false.
  84380. */
  84381. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  84382. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  84383. * comment specification.
  84384. *
  84385. * Vorbis comment names must be composed only of characters from
  84386. * [0x20-0x3C,0x3E-0x7D].
  84387. *
  84388. * \param name A NUL-terminated string to be checked.
  84389. * \assert
  84390. * \code name != NULL \endcode
  84391. * \retval FLAC__bool
  84392. * \c false if entry name is illegal, else \c true.
  84393. */
  84394. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  84395. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  84396. * comment specification.
  84397. *
  84398. * Vorbis comment values must be valid UTF-8 sequences.
  84399. *
  84400. * \param value A string to be checked.
  84401. * \param length A the length of \a value in bytes. May be
  84402. * \c (unsigned)(-1) to indicate that \a value is a plain
  84403. * UTF-8 NUL-terminated string.
  84404. * \assert
  84405. * \code value != NULL \endcode
  84406. * \retval FLAC__bool
  84407. * \c false if entry name is illegal, else \c true.
  84408. */
  84409. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  84410. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  84411. * comment specification.
  84412. *
  84413. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  84414. * 'value' must be legal according to
  84415. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  84416. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  84417. *
  84418. * \param entry An entry to be checked.
  84419. * \param length The length of \a entry in bytes.
  84420. * \assert
  84421. * \code value != NULL \endcode
  84422. * \retval FLAC__bool
  84423. * \c false if entry name is illegal, else \c true.
  84424. */
  84425. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  84426. /** Check a seek table to see if it conforms to the FLAC specification.
  84427. * See the format specification for limits on the contents of the
  84428. * seek table.
  84429. *
  84430. * \param seek_table A pointer to a seek table to be checked.
  84431. * \assert
  84432. * \code seek_table != NULL \endcode
  84433. * \retval FLAC__bool
  84434. * \c false if seek table is illegal, else \c true.
  84435. */
  84436. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  84437. /** Sort a seek table's seek points according to the format specification.
  84438. * This includes a "unique-ification" step to remove duplicates, i.e.
  84439. * seek points with identical \a sample_number values. Duplicate seek
  84440. * points are converted into placeholder points and sorted to the end of
  84441. * the table.
  84442. *
  84443. * \param seek_table A pointer to a seek table to be sorted.
  84444. * \assert
  84445. * \code seek_table != NULL \endcode
  84446. * \retval unsigned
  84447. * The number of duplicate seek points converted into placeholders.
  84448. */
  84449. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  84450. /** Check a cue sheet to see if it conforms to the FLAC specification.
  84451. * See the format specification for limits on the contents of the
  84452. * cue sheet.
  84453. *
  84454. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  84455. * \param check_cd_da_subset If \c true, check CUESHEET against more
  84456. * stringent requirements for a CD-DA (audio) disc.
  84457. * \param violation Address of a pointer to a string. If there is a
  84458. * violation, a pointer to a string explanation of the
  84459. * violation will be returned here. \a violation may be
  84460. * \c NULL if you don't need the returned string. Do not
  84461. * free the returned string; it will always point to static
  84462. * data.
  84463. * \assert
  84464. * \code cue_sheet != NULL \endcode
  84465. * \retval FLAC__bool
  84466. * \c false if cue sheet is illegal, else \c true.
  84467. */
  84468. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  84469. /** Check picture data to see if it conforms to the FLAC specification.
  84470. * See the format specification for limits on the contents of the
  84471. * PICTURE block.
  84472. *
  84473. * \param picture A pointer to existing picture data to be checked.
  84474. * \param violation Address of a pointer to a string. If there is a
  84475. * violation, a pointer to a string explanation of the
  84476. * violation will be returned here. \a violation may be
  84477. * \c NULL if you don't need the returned string. Do not
  84478. * free the returned string; it will always point to static
  84479. * data.
  84480. * \assert
  84481. * \code picture != NULL \endcode
  84482. * \retval FLAC__bool
  84483. * \c false if picture data is illegal, else \c true.
  84484. */
  84485. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  84486. /* \} */
  84487. #ifdef __cplusplus
  84488. }
  84489. #endif
  84490. #endif
  84491. /*** End of inlined file: format.h ***/
  84492. /*** Start of inlined file: metadata.h ***/
  84493. #ifndef FLAC__METADATA_H
  84494. #define FLAC__METADATA_H
  84495. #include <sys/types.h> /* for off_t */
  84496. /* --------------------------------------------------------------------
  84497. (For an example of how all these routines are used, see the source
  84498. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  84499. metaflac in src/metaflac/)
  84500. ------------------------------------------------------------------*/
  84501. /** \file include/FLAC/metadata.h
  84502. *
  84503. * \brief
  84504. * This module provides functions for creating and manipulating FLAC
  84505. * metadata blocks in memory, and three progressively more powerful
  84506. * interfaces for traversing and editing metadata in FLAC files.
  84507. *
  84508. * See the detailed documentation for each interface in the
  84509. * \link flac_metadata metadata \endlink module.
  84510. */
  84511. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  84512. * \ingroup flac
  84513. *
  84514. * \brief
  84515. * This module provides functions for creating and manipulating FLAC
  84516. * metadata blocks in memory, and three progressively more powerful
  84517. * interfaces for traversing and editing metadata in native FLAC files.
  84518. * Note that currently only the Chain interface (level 2) supports Ogg
  84519. * FLAC files, and it is read-only i.e. no writing back changed
  84520. * metadata to file.
  84521. *
  84522. * There are three metadata interfaces of increasing complexity:
  84523. *
  84524. * Level 0:
  84525. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  84526. * PICTURE blocks.
  84527. *
  84528. * Level 1:
  84529. * Read-write access to all metadata blocks. This level is write-
  84530. * efficient in most cases (more on this below), and uses less memory
  84531. * than level 2.
  84532. *
  84533. * Level 2:
  84534. * Read-write access to all metadata blocks. This level is write-
  84535. * efficient in all cases, but uses more memory since all metadata for
  84536. * the whole file is read into memory and manipulated before writing
  84537. * out again.
  84538. *
  84539. * What do we mean by efficient? Since FLAC metadata appears at the
  84540. * beginning of the file, when writing metadata back to a FLAC file
  84541. * it is possible to grow or shrink the metadata such that the entire
  84542. * file must be rewritten. However, if the size remains the same during
  84543. * changes or PADDING blocks are utilized, only the metadata needs to be
  84544. * overwritten, which is much faster.
  84545. *
  84546. * Efficient means the whole file is rewritten at most one time, and only
  84547. * when necessary. Level 1 is not efficient only in the case that you
  84548. * cause more than one metadata block to grow or shrink beyond what can
  84549. * be accomodated by padding. In this case you should probably use level
  84550. * 2, which allows you to edit all the metadata for a file in memory and
  84551. * write it out all at once.
  84552. *
  84553. * All levels know how to skip over and not disturb an ID3v2 tag at the
  84554. * front of the file.
  84555. *
  84556. * All levels access files via their filenames. In addition, level 2
  84557. * has additional alternative read and write functions that take an I/O
  84558. * handle and callbacks, for situations where access by filename is not
  84559. * possible.
  84560. *
  84561. * In addition to the three interfaces, this module defines functions for
  84562. * creating and manipulating various metadata objects in memory. As we see
  84563. * from the Format module, FLAC metadata blocks in memory are very primitive
  84564. * structures for storing information in an efficient way. Reading
  84565. * information from the structures is easy but creating or modifying them
  84566. * directly is more complex. The metadata object routines here facilitate
  84567. * this by taking care of the consistency and memory management drudgery.
  84568. *
  84569. * Unless you will be using the level 1 or 2 interfaces to modify existing
  84570. * metadata however, you will not probably not need these.
  84571. *
  84572. * From a dependency standpoint, none of the encoders or decoders require
  84573. * the metadata module. This is so that embedded users can strip out the
  84574. * metadata module from libFLAC to reduce the size and complexity.
  84575. */
  84576. #ifdef __cplusplus
  84577. extern "C" {
  84578. #endif
  84579. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  84580. * \ingroup flac_metadata
  84581. *
  84582. * \brief
  84583. * The level 0 interface consists of individual routines to read the
  84584. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  84585. * only a filename.
  84586. *
  84587. * They try to skip any ID3v2 tag at the head of the file.
  84588. *
  84589. * \{
  84590. */
  84591. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  84592. * will try to skip any ID3v2 tag at the head of the file.
  84593. *
  84594. * \param filename The path to the FLAC file to read.
  84595. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  84596. * FLAC__StreamMetadata is a simple structure with no
  84597. * memory allocation involved, you pass the address of
  84598. * an existing structure. It need not be initialized.
  84599. * \assert
  84600. * \code filename != NULL \endcode
  84601. * \code streaminfo != NULL \endcode
  84602. * \retval FLAC__bool
  84603. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  84604. * \c false if there was a memory allocation error, a file decoder error,
  84605. * or the file contained no STREAMINFO block. (A memory allocation error
  84606. * is possible because this function must set up a file decoder.)
  84607. */
  84608. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  84609. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  84610. * function will try to skip any ID3v2 tag at the head of the file.
  84611. *
  84612. * \param filename The path to the FLAC file to read.
  84613. * \param tags The address where the returned pointer will be
  84614. * stored. The \a tags object must be deleted by
  84615. * the caller using FLAC__metadata_object_delete().
  84616. * \assert
  84617. * \code filename != NULL \endcode
  84618. * \code tags != NULL \endcode
  84619. * \retval FLAC__bool
  84620. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  84621. * and \a *tags will be set to the address of the metadata structure.
  84622. * Returns \c false if there was a memory allocation error, a file
  84623. * decoder error, or the file contained no VORBIS_COMMENT block, and
  84624. * \a *tags will be set to \c NULL.
  84625. */
  84626. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  84627. /** Read the CUESHEET metadata block of the given FLAC file. This
  84628. * function will try to skip any ID3v2 tag at the head of the file.
  84629. *
  84630. * \param filename The path to the FLAC file to read.
  84631. * \param cuesheet The address where the returned pointer will be
  84632. * stored. The \a cuesheet object must be deleted by
  84633. * the caller using FLAC__metadata_object_delete().
  84634. * \assert
  84635. * \code filename != NULL \endcode
  84636. * \code cuesheet != NULL \endcode
  84637. * \retval FLAC__bool
  84638. * \c true if a valid CUESHEET block was read from \a filename,
  84639. * and \a *cuesheet will be set to the address of the metadata
  84640. * structure. Returns \c false if there was a memory allocation
  84641. * error, a file decoder error, or the file contained no CUESHEET
  84642. * block, and \a *cuesheet will be set to \c NULL.
  84643. */
  84644. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  84645. /** Read a PICTURE metadata block of the given FLAC file. This
  84646. * function will try to skip any ID3v2 tag at the head of the file.
  84647. * Since there can be more than one PICTURE block in a file, this
  84648. * function takes a number of parameters that act as constraints to
  84649. * the search. The PICTURE block with the largest area matching all
  84650. * the constraints will be returned, or \a *picture will be set to
  84651. * \c NULL if there was no such block.
  84652. *
  84653. * \param filename The path to the FLAC file to read.
  84654. * \param picture The address where the returned pointer will be
  84655. * stored. The \a picture object must be deleted by
  84656. * the caller using FLAC__metadata_object_delete().
  84657. * \param type The desired picture type. Use \c -1 to mean
  84658. * "any type".
  84659. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  84660. * string will be matched exactly. Use \c NULL to
  84661. * mean "any MIME type".
  84662. * \param description The desired description. The string will be
  84663. * matched exactly. Use \c NULL to mean "any
  84664. * description".
  84665. * \param max_width The maximum width in pixels desired. Use
  84666. * \c (unsigned)(-1) to mean "any width".
  84667. * \param max_height The maximum height in pixels desired. Use
  84668. * \c (unsigned)(-1) to mean "any height".
  84669. * \param max_depth The maximum color depth in bits-per-pixel desired.
  84670. * Use \c (unsigned)(-1) to mean "any depth".
  84671. * \param max_colors The maximum number of colors desired. Use
  84672. * \c (unsigned)(-1) to mean "any number of colors".
  84673. * \assert
  84674. * \code filename != NULL \endcode
  84675. * \code picture != NULL \endcode
  84676. * \retval FLAC__bool
  84677. * \c true if a valid PICTURE block was read from \a filename,
  84678. * and \a *picture will be set to the address of the metadata
  84679. * structure. Returns \c false if there was a memory allocation
  84680. * error, a file decoder error, or the file contained no PICTURE
  84681. * block, and \a *picture will be set to \c NULL.
  84682. */
  84683. 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);
  84684. /* \} */
  84685. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  84686. * \ingroup flac_metadata
  84687. *
  84688. * \brief
  84689. * The level 1 interface provides read-write access to FLAC file metadata and
  84690. * operates directly on the FLAC file.
  84691. *
  84692. * The general usage of this interface is:
  84693. *
  84694. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  84695. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  84696. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  84697. * see if the file is writable, or only read access is allowed.
  84698. * - Use FLAC__metadata_simple_iterator_next() and
  84699. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  84700. * This is does not read the actual blocks themselves.
  84701. * FLAC__metadata_simple_iterator_next() is relatively fast.
  84702. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  84703. * forward from the front of the file.
  84704. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  84705. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  84706. * the current iterator position. The returned object is yours to modify
  84707. * and free.
  84708. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  84709. * back. You must have write permission to the original file. Make sure to
  84710. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  84711. * below.
  84712. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  84713. * Use the object creation functions from
  84714. * \link flac_metadata_object here \endlink to generate new objects.
  84715. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  84716. * currently referred to by the iterator, or replace it with padding.
  84717. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  84718. * finished.
  84719. *
  84720. * \note
  84721. * The FLAC file remains open the whole time between
  84722. * FLAC__metadata_simple_iterator_init() and
  84723. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  84724. * the file during this time.
  84725. *
  84726. * \note
  84727. * Do not modify the \a is_last, \a length, or \a type fields of returned
  84728. * FLAC__StreamMetadata objects. These are managed automatically.
  84729. *
  84730. * \note
  84731. * If any of the modification functions
  84732. * (FLAC__metadata_simple_iterator_set_block(),
  84733. * FLAC__metadata_simple_iterator_delete_block(),
  84734. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  84735. * you should delete the iterator as it may no longer be valid.
  84736. *
  84737. * \{
  84738. */
  84739. struct FLAC__Metadata_SimpleIterator;
  84740. /** The opaque structure definition for the level 1 iterator type.
  84741. * See the
  84742. * \link flac_metadata_level1 metadata level 1 module \endlink
  84743. * for a detailed description.
  84744. */
  84745. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  84746. /** Status type for FLAC__Metadata_SimpleIterator.
  84747. *
  84748. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  84749. */
  84750. typedef enum {
  84751. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  84752. /**< The iterator is in the normal OK state */
  84753. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  84754. /**< The data passed into a function violated the function's usage criteria */
  84755. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  84756. /**< The iterator could not open the target file */
  84757. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  84758. /**< The iterator could not find the FLAC signature at the start of the file */
  84759. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  84760. /**< The iterator tried to write to a file that was not writable */
  84761. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  84762. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  84763. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  84764. /**< The iterator encountered an error while reading the FLAC file */
  84765. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  84766. /**< The iterator encountered an error while seeking in the FLAC file */
  84767. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  84768. /**< The iterator encountered an error while writing the FLAC file */
  84769. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  84770. /**< The iterator encountered an error renaming the FLAC file */
  84771. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  84772. /**< The iterator encountered an error removing the temporary file */
  84773. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  84774. /**< Memory allocation failed */
  84775. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  84776. /**< The caller violated an assertion or an unexpected error occurred */
  84777. } FLAC__Metadata_SimpleIteratorStatus;
  84778. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  84779. *
  84780. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  84781. * will give the string equivalent. The contents should not be modified.
  84782. */
  84783. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  84784. /** Create a new iterator instance.
  84785. *
  84786. * \retval FLAC__Metadata_SimpleIterator*
  84787. * \c NULL if there was an error allocating memory, else the new instance.
  84788. */
  84789. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  84790. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  84791. *
  84792. * \param iterator A pointer to an existing iterator.
  84793. * \assert
  84794. * \code iterator != NULL \endcode
  84795. */
  84796. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  84797. /** Get the current status of the iterator. Call this after a function
  84798. * returns \c false to get the reason for the error. Also resets the status
  84799. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  84800. *
  84801. * \param iterator A pointer to an existing iterator.
  84802. * \assert
  84803. * \code iterator != NULL \endcode
  84804. * \retval FLAC__Metadata_SimpleIteratorStatus
  84805. * The current status of the iterator.
  84806. */
  84807. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  84808. /** Initialize the iterator to point to the first metadata block in the
  84809. * given FLAC file.
  84810. *
  84811. * \param iterator A pointer to an existing iterator.
  84812. * \param filename The path to the FLAC file.
  84813. * \param read_only If \c true, the FLAC file will be opened
  84814. * in read-only mode; if \c false, the FLAC
  84815. * file will be opened for edit even if no
  84816. * edits are performed.
  84817. * \param preserve_file_stats If \c true, the owner and modification
  84818. * time will be preserved even if the FLAC
  84819. * file is written to.
  84820. * \assert
  84821. * \code iterator != NULL \endcode
  84822. * \code filename != NULL \endcode
  84823. * \retval FLAC__bool
  84824. * \c false if a memory allocation error occurs, the file can't be
  84825. * opened, or another error occurs, else \c true.
  84826. */
  84827. 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);
  84828. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  84829. * FLAC__metadata_simple_iterator_set_block() and
  84830. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  84831. *
  84832. * \param iterator A pointer to an existing iterator.
  84833. * \assert
  84834. * \code iterator != NULL \endcode
  84835. * \retval FLAC__bool
  84836. * See above.
  84837. */
  84838. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  84839. /** Moves the iterator forward one metadata block, returning \c false if
  84840. * already at the end.
  84841. *
  84842. * \param iterator A pointer to an existing initialized iterator.
  84843. * \assert
  84844. * \code iterator != NULL \endcode
  84845. * \a iterator has been successfully initialized with
  84846. * FLAC__metadata_simple_iterator_init()
  84847. * \retval FLAC__bool
  84848. * \c false if already at the last metadata block of the chain, else
  84849. * \c true.
  84850. */
  84851. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  84852. /** Moves the iterator backward one metadata block, returning \c false if
  84853. * already at the beginning.
  84854. *
  84855. * \param iterator A pointer to an existing initialized iterator.
  84856. * \assert
  84857. * \code iterator != NULL \endcode
  84858. * \a iterator has been successfully initialized with
  84859. * FLAC__metadata_simple_iterator_init()
  84860. * \retval FLAC__bool
  84861. * \c false if already at the first metadata block of the chain, else
  84862. * \c true.
  84863. */
  84864. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  84865. /** Returns a flag telling if the current metadata block is the last.
  84866. *
  84867. * \param iterator A pointer to an existing initialized iterator.
  84868. * \assert
  84869. * \code iterator != NULL \endcode
  84870. * \a iterator has been successfully initialized with
  84871. * FLAC__metadata_simple_iterator_init()
  84872. * \retval FLAC__bool
  84873. * \c true if the current metadata block is the last in the file,
  84874. * else \c false.
  84875. */
  84876. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  84877. /** Get the offset of the metadata block at the current position. This
  84878. * avoids reading the actual block data which can save time for large
  84879. * blocks.
  84880. *
  84881. * \param iterator A pointer to an existing initialized iterator.
  84882. * \assert
  84883. * \code iterator != NULL \endcode
  84884. * \a iterator has been successfully initialized with
  84885. * FLAC__metadata_simple_iterator_init()
  84886. * \retval off_t
  84887. * The offset of the metadata block at the current iterator position.
  84888. * This is the byte offset relative to the beginning of the file of
  84889. * the current metadata block's header.
  84890. */
  84891. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  84892. /** Get the type of the metadata block at the current position. This
  84893. * avoids reading the actual block data which can save time for large
  84894. * blocks.
  84895. *
  84896. * \param iterator A pointer to an existing initialized iterator.
  84897. * \assert
  84898. * \code iterator != NULL \endcode
  84899. * \a iterator has been successfully initialized with
  84900. * FLAC__metadata_simple_iterator_init()
  84901. * \retval FLAC__MetadataType
  84902. * The type of the metadata block at the current iterator position.
  84903. */
  84904. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  84905. /** Get the length of the metadata block at the current position. This
  84906. * avoids reading the actual block data which can save time for large
  84907. * blocks.
  84908. *
  84909. * \param iterator A pointer to an existing initialized iterator.
  84910. * \assert
  84911. * \code iterator != NULL \endcode
  84912. * \a iterator has been successfully initialized with
  84913. * FLAC__metadata_simple_iterator_init()
  84914. * \retval unsigned
  84915. * The length of the metadata block at the current iterator position.
  84916. * The is same length as that in the
  84917. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  84918. * i.e. the length of the metadata body that follows the header.
  84919. */
  84920. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  84921. /** Get the application ID of the \c APPLICATION block at the current
  84922. * position. This avoids reading the actual block data which can save
  84923. * time for large blocks.
  84924. *
  84925. * \param iterator A pointer to an existing initialized iterator.
  84926. * \param id A pointer to a buffer of at least \c 4 bytes where
  84927. * the ID will be stored.
  84928. * \assert
  84929. * \code iterator != NULL \endcode
  84930. * \code id != NULL \endcode
  84931. * \a iterator has been successfully initialized with
  84932. * FLAC__metadata_simple_iterator_init()
  84933. * \retval FLAC__bool
  84934. * \c true if the ID was successfully read, else \c false, in which
  84935. * case you should check FLAC__metadata_simple_iterator_status() to
  84936. * find out why. If the status is
  84937. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  84938. * current metadata block is not an \c APPLICATION block. Otherwise
  84939. * if the status is
  84940. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  84941. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  84942. * occurred and the iterator can no longer be used.
  84943. */
  84944. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  84945. /** Get the metadata block at the current position. You can modify the
  84946. * block but must use FLAC__metadata_simple_iterator_set_block() to
  84947. * write it back to the FLAC file.
  84948. *
  84949. * You must call FLAC__metadata_object_delete() on the returned object
  84950. * when you are finished with it.
  84951. *
  84952. * \param iterator A pointer to an existing initialized iterator.
  84953. * \assert
  84954. * \code iterator != NULL \endcode
  84955. * \a iterator has been successfully initialized with
  84956. * FLAC__metadata_simple_iterator_init()
  84957. * \retval FLAC__StreamMetadata*
  84958. * The current metadata block, or \c NULL if there was a memory
  84959. * allocation error.
  84960. */
  84961. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  84962. /** Write a block back to the FLAC file. This function tries to be
  84963. * as efficient as possible; how the block is actually written is
  84964. * shown by the following:
  84965. *
  84966. * Existing block is a STREAMINFO block and the new block is a
  84967. * STREAMINFO block: the new block is written in place. Make sure
  84968. * you know what you're doing when changing the values of a
  84969. * STREAMINFO block.
  84970. *
  84971. * Existing block is a STREAMINFO block and the new block is a
  84972. * not a STREAMINFO block: this is an error since the first block
  84973. * must be a STREAMINFO block. Returns \c false without altering the
  84974. * file.
  84975. *
  84976. * Existing block is not a STREAMINFO block and the new block is a
  84977. * STREAMINFO block: this is an error since there may be only one
  84978. * STREAMINFO block. Returns \c false without altering the file.
  84979. *
  84980. * Existing block and new block are the same length: the existing
  84981. * block will be replaced by the new block, written in place.
  84982. *
  84983. * Existing block is longer than new block: if use_padding is \c true,
  84984. * the existing block will be overwritten in place with the new
  84985. * block followed by a PADDING block, if possible, to make the total
  84986. * size the same as the existing block. Remember that a padding
  84987. * block requires at least four bytes so if the difference in size
  84988. * between the new block and existing block is less than that, the
  84989. * entire file will have to be rewritten, using the new block's
  84990. * exact size. If use_padding is \c false, the entire file will be
  84991. * rewritten, replacing the existing block by the new block.
  84992. *
  84993. * Existing block is shorter than new block: if use_padding is \c true,
  84994. * the function will try and expand the new block into the following
  84995. * PADDING block, if it exists and doing so won't shrink the PADDING
  84996. * block to less than 4 bytes. If there is no following PADDING
  84997. * block, or it will shrink to less than 4 bytes, or use_padding is
  84998. * \c false, the entire file is rewritten, replacing the existing block
  84999. * with the new block. Note that in this case any following PADDING
  85000. * block is preserved as is.
  85001. *
  85002. * After writing the block, the iterator will remain in the same
  85003. * place, i.e. pointing to the new block.
  85004. *
  85005. * \param iterator A pointer to an existing initialized iterator.
  85006. * \param block The block to set.
  85007. * \param use_padding See above.
  85008. * \assert
  85009. * \code iterator != NULL \endcode
  85010. * \a iterator has been successfully initialized with
  85011. * FLAC__metadata_simple_iterator_init()
  85012. * \code block != NULL \endcode
  85013. * \retval FLAC__bool
  85014. * \c true if successful, else \c false.
  85015. */
  85016. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  85017. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  85018. * except that instead of writing over an existing block, it appends
  85019. * a block after the existing block. \a use_padding is again used to
  85020. * tell the function to try an expand into following padding in an
  85021. * attempt to avoid rewriting the entire file.
  85022. *
  85023. * This function will fail and return \c false if given a STREAMINFO
  85024. * block.
  85025. *
  85026. * After writing the block, the iterator will be pointing to the
  85027. * new block.
  85028. *
  85029. * \param iterator A pointer to an existing initialized iterator.
  85030. * \param block The block to set.
  85031. * \param use_padding See above.
  85032. * \assert
  85033. * \code iterator != NULL \endcode
  85034. * \a iterator has been successfully initialized with
  85035. * FLAC__metadata_simple_iterator_init()
  85036. * \code block != NULL \endcode
  85037. * \retval FLAC__bool
  85038. * \c true if successful, else \c false.
  85039. */
  85040. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  85041. /** Deletes the block at the current position. This will cause the
  85042. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  85043. * in which case the block will be replaced by an equal-sized PADDING
  85044. * block. The iterator will be left pointing to the block before the
  85045. * one just deleted.
  85046. *
  85047. * You may not delete the STREAMINFO block.
  85048. *
  85049. * \param iterator A pointer to an existing initialized iterator.
  85050. * \param use_padding See above.
  85051. * \assert
  85052. * \code iterator != NULL \endcode
  85053. * \a iterator has been successfully initialized with
  85054. * FLAC__metadata_simple_iterator_init()
  85055. * \retval FLAC__bool
  85056. * \c true if successful, else \c false.
  85057. */
  85058. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  85059. /* \} */
  85060. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  85061. * \ingroup flac_metadata
  85062. *
  85063. * \brief
  85064. * The level 2 interface provides read-write access to FLAC file metadata;
  85065. * all metadata is read into memory, operated on in memory, and then written
  85066. * to file, which is more efficient than level 1 when editing multiple blocks.
  85067. *
  85068. * Currently Ogg FLAC is supported for read only, via
  85069. * FLAC__metadata_chain_read_ogg() but a subsequent
  85070. * FLAC__metadata_chain_write() will fail.
  85071. *
  85072. * The general usage of this interface is:
  85073. *
  85074. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  85075. * linked list of FLAC metadata blocks.
  85076. * - Read all metadata into the the chain from a FLAC file using
  85077. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  85078. * check the status.
  85079. * - Optionally, consolidate the padding using
  85080. * FLAC__metadata_chain_merge_padding() or
  85081. * FLAC__metadata_chain_sort_padding().
  85082. * - Create a new iterator using FLAC__metadata_iterator_new()
  85083. * - Initialize the iterator to point to the first element in the chain
  85084. * using FLAC__metadata_iterator_init()
  85085. * - Traverse the chain using FLAC__metadata_iterator_next and
  85086. * FLAC__metadata_iterator_prev().
  85087. * - Get a block for reading or modification using
  85088. * FLAC__metadata_iterator_get_block(). The pointer to the object
  85089. * inside the chain is returned, so the block is yours to modify.
  85090. * Changes will be reflected in the FLAC file when you write the
  85091. * chain. You can also add and delete blocks (see functions below).
  85092. * - When done, write out the chain using FLAC__metadata_chain_write().
  85093. * Make sure to read the whole comment to the function below.
  85094. * - Delete the chain using FLAC__metadata_chain_delete().
  85095. *
  85096. * \note
  85097. * Even though the FLAC file is not open while the chain is being
  85098. * manipulated, you must not alter the file externally during
  85099. * this time. The chain assumes the FLAC file will not change
  85100. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  85101. * and FLAC__metadata_chain_write().
  85102. *
  85103. * \note
  85104. * Do not modify the is_last, length, or type fields of returned
  85105. * FLAC__StreamMetadata objects. These are managed automatically.
  85106. *
  85107. * \note
  85108. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  85109. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  85110. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  85111. * become owned by the chain and they will be deleted when the chain is
  85112. * deleted.
  85113. *
  85114. * \{
  85115. */
  85116. struct FLAC__Metadata_Chain;
  85117. /** The opaque structure definition for the level 2 chain type.
  85118. */
  85119. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  85120. struct FLAC__Metadata_Iterator;
  85121. /** The opaque structure definition for the level 2 iterator type.
  85122. */
  85123. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  85124. typedef enum {
  85125. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  85126. /**< The chain is in the normal OK state */
  85127. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  85128. /**< The data passed into a function violated the function's usage criteria */
  85129. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  85130. /**< The chain could not open the target file */
  85131. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  85132. /**< The chain could not find the FLAC signature at the start of the file */
  85133. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  85134. /**< The chain tried to write to a file that was not writable */
  85135. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  85136. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  85137. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  85138. /**< The chain encountered an error while reading the FLAC file */
  85139. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  85140. /**< The chain encountered an error while seeking in the FLAC file */
  85141. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  85142. /**< The chain encountered an error while writing the FLAC file */
  85143. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  85144. /**< The chain encountered an error renaming the FLAC file */
  85145. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  85146. /**< The chain encountered an error removing the temporary file */
  85147. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  85148. /**< Memory allocation failed */
  85149. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  85150. /**< The caller violated an assertion or an unexpected error occurred */
  85151. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  85152. /**< One or more of the required callbacks was NULL */
  85153. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  85154. /**< FLAC__metadata_chain_write() was called on a chain read by
  85155. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  85156. * or
  85157. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  85158. * was called on a chain read by
  85159. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  85160. * Matching read/write methods must always be used. */
  85161. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  85162. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  85163. * chain write requires a tempfile; use
  85164. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  85165. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  85166. * called when the chain write does not require a tempfile; use
  85167. * FLAC__metadata_chain_write_with_callbacks() instead.
  85168. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  85169. * before writing via callbacks. */
  85170. } FLAC__Metadata_ChainStatus;
  85171. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  85172. *
  85173. * Using a FLAC__Metadata_ChainStatus as the index to this array
  85174. * will give the string equivalent. The contents should not be modified.
  85175. */
  85176. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  85177. /*********** FLAC__Metadata_Chain ***********/
  85178. /** Create a new chain instance.
  85179. *
  85180. * \retval FLAC__Metadata_Chain*
  85181. * \c NULL if there was an error allocating memory, else the new instance.
  85182. */
  85183. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  85184. /** Free a chain instance. Deletes the object pointed to by \a chain.
  85185. *
  85186. * \param chain A pointer to an existing chain.
  85187. * \assert
  85188. * \code chain != NULL \endcode
  85189. */
  85190. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  85191. /** Get the current status of the chain. Call this after a function
  85192. * returns \c false to get the reason for the error. Also resets the
  85193. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  85194. *
  85195. * \param chain A pointer to an existing chain.
  85196. * \assert
  85197. * \code chain != NULL \endcode
  85198. * \retval FLAC__Metadata_ChainStatus
  85199. * The current status of the chain.
  85200. */
  85201. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  85202. /** Read all metadata from a FLAC file into the chain.
  85203. *
  85204. * \param chain A pointer to an existing chain.
  85205. * \param filename The path to the FLAC file to read.
  85206. * \assert
  85207. * \code chain != NULL \endcode
  85208. * \code filename != NULL \endcode
  85209. * \retval FLAC__bool
  85210. * \c true if a valid list of metadata blocks was read from
  85211. * \a filename, else \c false. On failure, check the status with
  85212. * FLAC__metadata_chain_status().
  85213. */
  85214. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  85215. /** Read all metadata from an Ogg FLAC file into the chain.
  85216. *
  85217. * \note Ogg FLAC metadata data writing is not supported yet and
  85218. * FLAC__metadata_chain_write() will fail.
  85219. *
  85220. * \param chain A pointer to an existing chain.
  85221. * \param filename The path to the Ogg FLAC file to read.
  85222. * \assert
  85223. * \code chain != NULL \endcode
  85224. * \code filename != NULL \endcode
  85225. * \retval FLAC__bool
  85226. * \c true if a valid list of metadata blocks was read from
  85227. * \a filename, else \c false. On failure, check the status with
  85228. * FLAC__metadata_chain_status().
  85229. */
  85230. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  85231. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  85232. *
  85233. * The \a handle need only be open for reading, but must be seekable.
  85234. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  85235. * for Windows).
  85236. *
  85237. * \param chain A pointer to an existing chain.
  85238. * \param handle The I/O handle of the FLAC stream to read. The
  85239. * handle will NOT be closed after the metadata is read;
  85240. * that is the duty of the caller.
  85241. * \param callbacks
  85242. * A set of callbacks to use for I/O. The mandatory
  85243. * callbacks are \a read, \a seek, and \a tell.
  85244. * \assert
  85245. * \code chain != NULL \endcode
  85246. * \retval FLAC__bool
  85247. * \c true if a valid list of metadata blocks was read from
  85248. * \a handle, else \c false. On failure, check the status with
  85249. * FLAC__metadata_chain_status().
  85250. */
  85251. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  85252. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  85253. *
  85254. * The \a handle need only be open for reading, but must be seekable.
  85255. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  85256. * for Windows).
  85257. *
  85258. * \note Ogg FLAC metadata data writing is not supported yet and
  85259. * FLAC__metadata_chain_write() will fail.
  85260. *
  85261. * \param chain A pointer to an existing chain.
  85262. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  85263. * handle will NOT be closed after the metadata is read;
  85264. * that is the duty of the caller.
  85265. * \param callbacks
  85266. * A set of callbacks to use for I/O. The mandatory
  85267. * callbacks are \a read, \a seek, and \a tell.
  85268. * \assert
  85269. * \code chain != NULL \endcode
  85270. * \retval FLAC__bool
  85271. * \c true if a valid list of metadata blocks was read from
  85272. * \a handle, else \c false. On failure, check the status with
  85273. * FLAC__metadata_chain_status().
  85274. */
  85275. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  85276. /** Checks if writing the given chain would require the use of a
  85277. * temporary file, or if it could be written in place.
  85278. *
  85279. * Under certain conditions, padding can be utilized so that writing
  85280. * edited metadata back to the FLAC file does not require rewriting the
  85281. * entire file. If rewriting is required, then a temporary workfile is
  85282. * required. When writing metadata using callbacks, you must check
  85283. * this function to know whether to call
  85284. * FLAC__metadata_chain_write_with_callbacks() or
  85285. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  85286. * writing with FLAC__metadata_chain_write(), the temporary file is
  85287. * handled internally.
  85288. *
  85289. * \param chain A pointer to an existing chain.
  85290. * \param use_padding
  85291. * Whether or not padding will be allowed to be used
  85292. * during the write. The value of \a use_padding given
  85293. * here must match the value later passed to
  85294. * FLAC__metadata_chain_write_with_callbacks() or
  85295. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  85296. * \assert
  85297. * \code chain != NULL \endcode
  85298. * \retval FLAC__bool
  85299. * \c true if writing the current chain would require a tempfile, or
  85300. * \c false if metadata can be written in place.
  85301. */
  85302. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  85303. /** Write all metadata out to the FLAC file. This function tries to be as
  85304. * efficient as possible; how the metadata is actually written is shown by
  85305. * the following:
  85306. *
  85307. * If the current chain is the same size as the existing metadata, the new
  85308. * data is written in place.
  85309. *
  85310. * If the current chain is longer than the existing metadata, and
  85311. * \a use_padding is \c true, and the last block is a PADDING block of
  85312. * sufficient length, the function will truncate the final padding block
  85313. * so that the overall size of the metadata is the same as the existing
  85314. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  85315. * the above conditions are met, the entire FLAC file must be rewritten.
  85316. * If you want to use padding this way it is a good idea to call
  85317. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  85318. * amount of padding to work with, unless you need to preserve ordering
  85319. * of the PADDING blocks for some reason.
  85320. *
  85321. * If the current chain is shorter than the existing metadata, and
  85322. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  85323. * is extended to make the overall size the same as the existing data. If
  85324. * \a use_padding is \c true and the last block is not a PADDING block, a new
  85325. * PADDING block is added to the end of the new data to make it the same
  85326. * size as the existing data (if possible, see the note to
  85327. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  85328. * and the new data is written in place. If none of the above apply or
  85329. * \a use_padding is \c false, the entire FLAC file is rewritten.
  85330. *
  85331. * If \a preserve_file_stats is \c true, the owner and modification time will
  85332. * be preserved even if the FLAC file is written.
  85333. *
  85334. * For this write function to be used, the chain must have been read with
  85335. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  85336. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  85337. *
  85338. * \param chain A pointer to an existing chain.
  85339. * \param use_padding See above.
  85340. * \param preserve_file_stats See above.
  85341. * \assert
  85342. * \code chain != NULL \endcode
  85343. * \retval FLAC__bool
  85344. * \c true if the write succeeded, else \c false. On failure,
  85345. * check the status with FLAC__metadata_chain_status().
  85346. */
  85347. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  85348. /** Write all metadata out to a FLAC stream via callbacks.
  85349. *
  85350. * (See FLAC__metadata_chain_write() for the details on how padding is
  85351. * used to write metadata in place if possible.)
  85352. *
  85353. * The \a handle must be open for updating and be seekable. The
  85354. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  85355. * for Windows).
  85356. *
  85357. * For this write function to be used, the chain must have been read with
  85358. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  85359. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  85360. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  85361. * \c false.
  85362. *
  85363. * \param chain A pointer to an existing chain.
  85364. * \param use_padding See FLAC__metadata_chain_write()
  85365. * \param handle The I/O handle of the FLAC stream to write. The
  85366. * handle will NOT be closed after the metadata is
  85367. * written; that is the duty of the caller.
  85368. * \param callbacks A set of callbacks to use for I/O. The mandatory
  85369. * callbacks are \a write and \a seek.
  85370. * \assert
  85371. * \code chain != NULL \endcode
  85372. * \retval FLAC__bool
  85373. * \c true if the write succeeded, else \c false. On failure,
  85374. * check the status with FLAC__metadata_chain_status().
  85375. */
  85376. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  85377. /** Write all metadata out to a FLAC stream via callbacks.
  85378. *
  85379. * (See FLAC__metadata_chain_write() for the details on how padding is
  85380. * used to write metadata in place if possible.)
  85381. *
  85382. * This version of the write-with-callbacks function must be used when
  85383. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  85384. * this function, you must supply an I/O handle corresponding to the
  85385. * FLAC file to edit, and a temporary handle to which the new FLAC
  85386. * file will be written. It is the caller's job to move this temporary
  85387. * FLAC file on top of the original FLAC file to complete the metadata
  85388. * edit.
  85389. *
  85390. * The \a handle must be open for reading and be seekable. The
  85391. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  85392. * for Windows).
  85393. *
  85394. * The \a temp_handle must be open for writing. The
  85395. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  85396. * for Windows). It should be an empty stream, or at least positioned
  85397. * at the start-of-file (in which case it is the caller's duty to
  85398. * truncate it on return).
  85399. *
  85400. * For this write function to be used, the chain must have been read with
  85401. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  85402. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  85403. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  85404. * \c true.
  85405. *
  85406. * \param chain A pointer to an existing chain.
  85407. * \param use_padding See FLAC__metadata_chain_write()
  85408. * \param handle The I/O handle of the original FLAC stream to read.
  85409. * The handle will NOT be closed after the metadata is
  85410. * written; that is the duty of the caller.
  85411. * \param callbacks A set of callbacks to use for I/O on \a handle.
  85412. * The mandatory callbacks are \a read, \a seek, and
  85413. * \a eof.
  85414. * \param temp_handle The I/O handle of the FLAC stream to write. The
  85415. * handle will NOT be closed after the metadata is
  85416. * written; that is the duty of the caller.
  85417. * \param temp_callbacks
  85418. * A set of callbacks to use for I/O on temp_handle.
  85419. * The only mandatory callback is \a write.
  85420. * \assert
  85421. * \code chain != NULL \endcode
  85422. * \retval FLAC__bool
  85423. * \c true if the write succeeded, else \c false. On failure,
  85424. * check the status with FLAC__metadata_chain_status().
  85425. */
  85426. 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);
  85427. /** Merge adjacent PADDING blocks into a single block.
  85428. *
  85429. * \note This function does not write to the FLAC file, it only
  85430. * modifies the chain.
  85431. *
  85432. * \warning Any iterator on the current chain will become invalid after this
  85433. * call. You should delete the iterator and get a new one.
  85434. *
  85435. * \param chain A pointer to an existing chain.
  85436. * \assert
  85437. * \code chain != NULL \endcode
  85438. */
  85439. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  85440. /** This function will move all PADDING blocks to the end on the metadata,
  85441. * then merge them into a single block.
  85442. *
  85443. * \note This function does not write to the FLAC file, it only
  85444. * modifies the chain.
  85445. *
  85446. * \warning Any iterator on the current chain will become invalid after this
  85447. * call. You should delete the iterator and get a new one.
  85448. *
  85449. * \param chain A pointer to an existing chain.
  85450. * \assert
  85451. * \code chain != NULL \endcode
  85452. */
  85453. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  85454. /*********** FLAC__Metadata_Iterator ***********/
  85455. /** Create a new iterator instance.
  85456. *
  85457. * \retval FLAC__Metadata_Iterator*
  85458. * \c NULL if there was an error allocating memory, else the new instance.
  85459. */
  85460. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  85461. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  85462. *
  85463. * \param iterator A pointer to an existing iterator.
  85464. * \assert
  85465. * \code iterator != NULL \endcode
  85466. */
  85467. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  85468. /** Initialize the iterator to point to the first metadata block in the
  85469. * given chain.
  85470. *
  85471. * \param iterator A pointer to an existing iterator.
  85472. * \param chain A pointer to an existing and initialized (read) chain.
  85473. * \assert
  85474. * \code iterator != NULL \endcode
  85475. * \code chain != NULL \endcode
  85476. */
  85477. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  85478. /** Moves the iterator forward one metadata block, returning \c false if
  85479. * already at the end.
  85480. *
  85481. * \param iterator A pointer to an existing initialized iterator.
  85482. * \assert
  85483. * \code iterator != NULL \endcode
  85484. * \a iterator has been successfully initialized with
  85485. * FLAC__metadata_iterator_init()
  85486. * \retval FLAC__bool
  85487. * \c false if already at the last metadata block of the chain, else
  85488. * \c true.
  85489. */
  85490. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  85491. /** Moves the iterator backward one metadata block, returning \c false if
  85492. * already at the beginning.
  85493. *
  85494. * \param iterator A pointer to an existing initialized iterator.
  85495. * \assert
  85496. * \code iterator != NULL \endcode
  85497. * \a iterator has been successfully initialized with
  85498. * FLAC__metadata_iterator_init()
  85499. * \retval FLAC__bool
  85500. * \c false if already at the first metadata block of the chain, else
  85501. * \c true.
  85502. */
  85503. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  85504. /** Get the type of the metadata block at the current position.
  85505. *
  85506. * \param iterator A pointer to an existing initialized iterator.
  85507. * \assert
  85508. * \code iterator != NULL \endcode
  85509. * \a iterator has been successfully initialized with
  85510. * FLAC__metadata_iterator_init()
  85511. * \retval FLAC__MetadataType
  85512. * The type of the metadata block at the current iterator position.
  85513. */
  85514. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  85515. /** Get the metadata block at the current position. You can modify
  85516. * the block in place but must write the chain before the changes
  85517. * are reflected to the FLAC file. You do not need to call
  85518. * FLAC__metadata_iterator_set_block() to reflect the changes;
  85519. * the pointer returned by FLAC__metadata_iterator_get_block()
  85520. * points directly into the chain.
  85521. *
  85522. * \warning
  85523. * Do not call FLAC__metadata_object_delete() on the returned object;
  85524. * to delete a block use FLAC__metadata_iterator_delete_block().
  85525. *
  85526. * \param iterator A pointer to an existing initialized iterator.
  85527. * \assert
  85528. * \code iterator != NULL \endcode
  85529. * \a iterator has been successfully initialized with
  85530. * FLAC__metadata_iterator_init()
  85531. * \retval FLAC__StreamMetadata*
  85532. * The current metadata block.
  85533. */
  85534. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  85535. /** Set the metadata block at the current position, replacing the existing
  85536. * block. The new block passed in becomes owned by the chain and it will be
  85537. * deleted when the chain is deleted.
  85538. *
  85539. * \param iterator A pointer to an existing initialized iterator.
  85540. * \param block A pointer to a metadata block.
  85541. * \assert
  85542. * \code iterator != NULL \endcode
  85543. * \a iterator has been successfully initialized with
  85544. * FLAC__metadata_iterator_init()
  85545. * \code block != NULL \endcode
  85546. * \retval FLAC__bool
  85547. * \c false if the conditions in the above description are not met, or
  85548. * a memory allocation error occurs, otherwise \c true.
  85549. */
  85550. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  85551. /** Removes the current block from the chain. If \a replace_with_padding is
  85552. * \c true, the block will instead be replaced with a padding block of equal
  85553. * size. You can not delete the STREAMINFO block. The iterator will be
  85554. * left pointing to the block before the one just "deleted", even if
  85555. * \a replace_with_padding is \c true.
  85556. *
  85557. * \param iterator A pointer to an existing initialized iterator.
  85558. * \param replace_with_padding See above.
  85559. * \assert
  85560. * \code iterator != NULL \endcode
  85561. * \a iterator has been successfully initialized with
  85562. * FLAC__metadata_iterator_init()
  85563. * \retval FLAC__bool
  85564. * \c false if the conditions in the above description are not met,
  85565. * otherwise \c true.
  85566. */
  85567. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  85568. /** Insert a new block before the current block. You cannot insert a block
  85569. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  85570. * as there can be only one, the one that already exists at the head when you
  85571. * read in a chain. The chain takes ownership of the new block and it will be
  85572. * deleted when the chain is deleted. The iterator will be left pointing to
  85573. * the new block.
  85574. *
  85575. * \param iterator A pointer to an existing initialized iterator.
  85576. * \param block A pointer to a metadata block to insert.
  85577. * \assert
  85578. * \code iterator != NULL \endcode
  85579. * \a iterator has been successfully initialized with
  85580. * FLAC__metadata_iterator_init()
  85581. * \retval FLAC__bool
  85582. * \c false if the conditions in the above description are not met, or
  85583. * a memory allocation error occurs, otherwise \c true.
  85584. */
  85585. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  85586. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  85587. * block as there can be only one, the one that already exists at the head when
  85588. * you read in a chain. The chain takes ownership of the new block and it will
  85589. * be deleted when the chain is deleted. The iterator will be left pointing to
  85590. * the new block.
  85591. *
  85592. * \param iterator A pointer to an existing initialized iterator.
  85593. * \param block A pointer to a metadata block to insert.
  85594. * \assert
  85595. * \code iterator != NULL \endcode
  85596. * \a iterator has been successfully initialized with
  85597. * FLAC__metadata_iterator_init()
  85598. * \retval FLAC__bool
  85599. * \c false if the conditions in the above description are not met, or
  85600. * a memory allocation error occurs, otherwise \c true.
  85601. */
  85602. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  85603. /* \} */
  85604. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  85605. * \ingroup flac_metadata
  85606. *
  85607. * \brief
  85608. * This module contains methods for manipulating FLAC metadata objects.
  85609. *
  85610. * Since many are variable length we have to be careful about the memory
  85611. * management. We decree that all pointers to data in the object are
  85612. * owned by the object and memory-managed by the object.
  85613. *
  85614. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  85615. * functions to create all instances. When using the
  85616. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  85617. * \a copy to \c true to have the function make it's own copy of the data, or
  85618. * to \c false to give the object ownership of your data. In the latter case
  85619. * your pointer must be freeable by free() and will be free()d when the object
  85620. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  85621. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  85622. * the length argument is 0 and the \a copy argument is \c false.
  85623. *
  85624. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  85625. * will return \c NULL in the case of a memory allocation error, otherwise a new
  85626. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  85627. * case of a memory allocation error.
  85628. *
  85629. * We don't have the convenience of C++ here, so note that the library relies
  85630. * on you to keep the types straight. In other words, if you pass, for
  85631. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  85632. * FLAC__metadata_object_application_set_data(), you will get an assertion
  85633. * failure.
  85634. *
  85635. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  85636. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  85637. * toward the length or stored in the stream, but it can make working with plain
  85638. * comments (those that don't contain embedded-NULs in the value) easier.
  85639. * Entries passed into these functions have trailing NULs added if missing, and
  85640. * returned entries are guaranteed to have a trailing NUL.
  85641. *
  85642. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  85643. * comment entry/name/value will first validate that it complies with the Vorbis
  85644. * comment specification and return false if it does not.
  85645. *
  85646. * There is no need to recalculate the length field on metadata blocks you
  85647. * have modified. They will be calculated automatically before they are
  85648. * written back to a file.
  85649. *
  85650. * \{
  85651. */
  85652. /** Create a new metadata object instance of the given type.
  85653. *
  85654. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  85655. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  85656. * the vendor string set (but zero comments).
  85657. *
  85658. * Do not pass in a value greater than or equal to
  85659. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  85660. * doing.
  85661. *
  85662. * \param type Type of object to create
  85663. * \retval FLAC__StreamMetadata*
  85664. * \c NULL if there was an error allocating memory or the type code is
  85665. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  85666. */
  85667. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  85668. /** Create a copy of an existing metadata object.
  85669. *
  85670. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  85671. * object is also copied. The caller takes ownership of the new block and
  85672. * is responsible for freeing it with FLAC__metadata_object_delete().
  85673. *
  85674. * \param object Pointer to object to copy.
  85675. * \assert
  85676. * \code object != NULL \endcode
  85677. * \retval FLAC__StreamMetadata*
  85678. * \c NULL if there was an error allocating memory, else the new instance.
  85679. */
  85680. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  85681. /** Free a metadata object. Deletes the object pointed to by \a object.
  85682. *
  85683. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  85684. * object is also deleted.
  85685. *
  85686. * \param object A pointer to an existing object.
  85687. * \assert
  85688. * \code object != NULL \endcode
  85689. */
  85690. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  85691. /** Compares two metadata objects.
  85692. *
  85693. * The compare is "deep", i.e. dynamically allocated data within the
  85694. * object is also compared.
  85695. *
  85696. * \param block1 A pointer to an existing object.
  85697. * \param block2 A pointer to an existing object.
  85698. * \assert
  85699. * \code block1 != NULL \endcode
  85700. * \code block2 != NULL \endcode
  85701. * \retval FLAC__bool
  85702. * \c true if objects are identical, else \c false.
  85703. */
  85704. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  85705. /** Sets the application data of an APPLICATION block.
  85706. *
  85707. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  85708. * takes ownership of the pointer. The existing data will be freed if this
  85709. * function is successful, otherwise the original data will remain if \a copy
  85710. * is \c true and malloc() fails.
  85711. *
  85712. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  85713. *
  85714. * \param object A pointer to an existing APPLICATION object.
  85715. * \param data A pointer to the data to set.
  85716. * \param length The length of \a data in bytes.
  85717. * \param copy See above.
  85718. * \assert
  85719. * \code object != NULL \endcode
  85720. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  85721. * \code (data != NULL && length > 0) ||
  85722. * (data == NULL && length == 0 && copy == false) \endcode
  85723. * \retval FLAC__bool
  85724. * \c false if \a copy is \c true and malloc() fails, else \c true.
  85725. */
  85726. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  85727. /** Resize the seekpoint array.
  85728. *
  85729. * If the size shrinks, elements will truncated; if it grows, new placeholder
  85730. * points will be added to the end.
  85731. *
  85732. * \param object A pointer to an existing SEEKTABLE object.
  85733. * \param new_num_points The desired length of the array; may be \c 0.
  85734. * \assert
  85735. * \code object != NULL \endcode
  85736. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85737. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  85738. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  85739. * \retval FLAC__bool
  85740. * \c false if memory allocation error, else \c true.
  85741. */
  85742. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  85743. /** Set a seekpoint in a seektable.
  85744. *
  85745. * \param object A pointer to an existing SEEKTABLE object.
  85746. * \param point_num Index into seekpoint array to set.
  85747. * \param point The point to set.
  85748. * \assert
  85749. * \code object != NULL \endcode
  85750. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85751. * \code object->data.seek_table.num_points > point_num \endcode
  85752. */
  85753. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  85754. /** Insert a seekpoint into a seektable.
  85755. *
  85756. * \param object A pointer to an existing SEEKTABLE object.
  85757. * \param point_num Index into seekpoint array to set.
  85758. * \param point The point to set.
  85759. * \assert
  85760. * \code object != NULL \endcode
  85761. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85762. * \code object->data.seek_table.num_points >= point_num \endcode
  85763. * \retval FLAC__bool
  85764. * \c false if memory allocation error, else \c true.
  85765. */
  85766. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  85767. /** Delete a seekpoint from a seektable.
  85768. *
  85769. * \param object A pointer to an existing SEEKTABLE object.
  85770. * \param point_num Index into seekpoint array to set.
  85771. * \assert
  85772. * \code object != NULL \endcode
  85773. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85774. * \code object->data.seek_table.num_points > point_num \endcode
  85775. * \retval FLAC__bool
  85776. * \c false if memory allocation error, else \c true.
  85777. */
  85778. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  85779. /** Check a seektable to see if it conforms to the FLAC specification.
  85780. * See the format specification for limits on the contents of the
  85781. * seektable.
  85782. *
  85783. * \param object A pointer to an existing SEEKTABLE object.
  85784. * \assert
  85785. * \code object != NULL \endcode
  85786. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85787. * \retval FLAC__bool
  85788. * \c false if seek table is illegal, else \c true.
  85789. */
  85790. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  85791. /** Append a number of placeholder points to the end of a seek table.
  85792. *
  85793. * \note
  85794. * As with the other ..._seektable_template_... functions, you should
  85795. * call FLAC__metadata_object_seektable_template_sort() when finished
  85796. * to make the seek table legal.
  85797. *
  85798. * \param object A pointer to an existing SEEKTABLE object.
  85799. * \param num The number of placeholder points to append.
  85800. * \assert
  85801. * \code object != NULL \endcode
  85802. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85803. * \retval FLAC__bool
  85804. * \c false if memory allocation fails, else \c true.
  85805. */
  85806. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  85807. /** Append a specific seek point template to the end of a seek table.
  85808. *
  85809. * \note
  85810. * As with the other ..._seektable_template_... functions, you should
  85811. * call FLAC__metadata_object_seektable_template_sort() when finished
  85812. * to make the seek table legal.
  85813. *
  85814. * \param object A pointer to an existing SEEKTABLE object.
  85815. * \param sample_number The sample number of the seek point template.
  85816. * \assert
  85817. * \code object != NULL \endcode
  85818. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85819. * \retval FLAC__bool
  85820. * \c false if memory allocation fails, else \c true.
  85821. */
  85822. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  85823. /** Append specific seek point templates to the end of a seek table.
  85824. *
  85825. * \note
  85826. * As with the other ..._seektable_template_... functions, you should
  85827. * call FLAC__metadata_object_seektable_template_sort() when finished
  85828. * to make the seek table legal.
  85829. *
  85830. * \param object A pointer to an existing SEEKTABLE object.
  85831. * \param sample_numbers An array of sample numbers for the seek points.
  85832. * \param num The number of seek point templates to append.
  85833. * \assert
  85834. * \code object != NULL \endcode
  85835. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85836. * \retval FLAC__bool
  85837. * \c false if memory allocation fails, else \c true.
  85838. */
  85839. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  85840. /** Append a set of evenly-spaced seek point templates to the end of a
  85841. * seek table.
  85842. *
  85843. * \note
  85844. * As with the other ..._seektable_template_... functions, you should
  85845. * call FLAC__metadata_object_seektable_template_sort() when finished
  85846. * to make the seek table legal.
  85847. *
  85848. * \param object A pointer to an existing SEEKTABLE object.
  85849. * \param num The number of placeholder points to append.
  85850. * \param total_samples The total number of samples to be encoded;
  85851. * the seekpoints will be spaced approximately
  85852. * \a total_samples / \a num samples apart.
  85853. * \assert
  85854. * \code object != NULL \endcode
  85855. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85856. * \code total_samples > 0 \endcode
  85857. * \retval FLAC__bool
  85858. * \c false if memory allocation fails, else \c true.
  85859. */
  85860. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  85861. /** Append a set of evenly-spaced seek point templates to the end of a
  85862. * seek table.
  85863. *
  85864. * \note
  85865. * As with the other ..._seektable_template_... functions, you should
  85866. * call FLAC__metadata_object_seektable_template_sort() when finished
  85867. * to make the seek table legal.
  85868. *
  85869. * \param object A pointer to an existing SEEKTABLE object.
  85870. * \param samples The number of samples apart to space the placeholder
  85871. * points. The first point will be at sample \c 0, the
  85872. * second at sample \a samples, then 2*\a samples, and
  85873. * so on. As long as \a samples and \a total_samples
  85874. * are greater than \c 0, there will always be at least
  85875. * one seekpoint at sample \c 0.
  85876. * \param total_samples The total number of samples to be encoded;
  85877. * the seekpoints will be spaced
  85878. * \a samples samples apart.
  85879. * \assert
  85880. * \code object != NULL \endcode
  85881. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85882. * \code samples > 0 \endcode
  85883. * \code total_samples > 0 \endcode
  85884. * \retval FLAC__bool
  85885. * \c false if memory allocation fails, else \c true.
  85886. */
  85887. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  85888. /** Sort a seek table's seek points according to the format specification,
  85889. * removing duplicates.
  85890. *
  85891. * \param object A pointer to a seek table to be sorted.
  85892. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  85893. * If \c true, duplicates are deleted and the seek table is
  85894. * shrunk appropriately; the number of placeholder points
  85895. * present in the seek table will be the same after the call
  85896. * as before.
  85897. * \assert
  85898. * \code object != NULL \endcode
  85899. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85900. * \retval FLAC__bool
  85901. * \c false if realloc() fails, else \c true.
  85902. */
  85903. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  85904. /** Sets the vendor string in a VORBIS_COMMENT block.
  85905. *
  85906. * For convenience, a trailing NUL is added to the entry if it doesn't have
  85907. * one already.
  85908. *
  85909. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  85910. * takes ownership of the \c entry.entry pointer.
  85911. *
  85912. * \note If this function returns \c false, the caller still owns the
  85913. * pointer.
  85914. *
  85915. * \param object A pointer to an existing VORBIS_COMMENT object.
  85916. * \param entry The entry to set the vendor string to.
  85917. * \param copy See above.
  85918. * \assert
  85919. * \code object != NULL \endcode
  85920. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85921. * \code (entry.entry != NULL && entry.length > 0) ||
  85922. * (entry.entry == NULL && entry.length == 0) \endcode
  85923. * \retval FLAC__bool
  85924. * \c false if memory allocation fails or \a entry does not comply with the
  85925. * Vorbis comment specification, else \c true.
  85926. */
  85927. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  85928. /** Resize the comment array.
  85929. *
  85930. * If the size shrinks, elements will truncated; if it grows, new empty
  85931. * fields will be added to the end.
  85932. *
  85933. * \param object A pointer to an existing VORBIS_COMMENT object.
  85934. * \param new_num_comments The desired length of the array; may be \c 0.
  85935. * \assert
  85936. * \code object != NULL \endcode
  85937. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85938. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  85939. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  85940. * \retval FLAC__bool
  85941. * \c false if memory allocation fails, else \c true.
  85942. */
  85943. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  85944. /** Sets a comment in a VORBIS_COMMENT block.
  85945. *
  85946. * For convenience, a trailing NUL is added to the entry if it doesn't have
  85947. * one already.
  85948. *
  85949. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  85950. * takes ownership of the \c entry.entry pointer.
  85951. *
  85952. * \note If this function returns \c false, the caller still owns the
  85953. * pointer.
  85954. *
  85955. * \param object A pointer to an existing VORBIS_COMMENT object.
  85956. * \param comment_num Index into comment array to set.
  85957. * \param entry The entry to set the comment to.
  85958. * \param copy See above.
  85959. * \assert
  85960. * \code object != NULL \endcode
  85961. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85962. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  85963. * \code (entry.entry != NULL && entry.length > 0) ||
  85964. * (entry.entry == NULL && entry.length == 0) \endcode
  85965. * \retval FLAC__bool
  85966. * \c false if memory allocation fails or \a entry does not comply with the
  85967. * Vorbis comment specification, else \c true.
  85968. */
  85969. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  85970. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  85971. *
  85972. * For convenience, a trailing NUL is added to the entry if it doesn't have
  85973. * one already.
  85974. *
  85975. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  85976. * takes ownership of the \c entry.entry pointer.
  85977. *
  85978. * \note If this function returns \c false, the caller still owns the
  85979. * pointer.
  85980. *
  85981. * \param object A pointer to an existing VORBIS_COMMENT object.
  85982. * \param comment_num The index at which to insert the comment. The comments
  85983. * at and after \a comment_num move right one position.
  85984. * To append a comment to the end, set \a comment_num to
  85985. * \c object->data.vorbis_comment.num_comments .
  85986. * \param entry The comment to insert.
  85987. * \param copy See above.
  85988. * \assert
  85989. * \code object != NULL \endcode
  85990. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85991. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  85992. * \code (entry.entry != NULL && entry.length > 0) ||
  85993. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  85994. * \retval FLAC__bool
  85995. * \c false if memory allocation fails or \a entry does not comply with the
  85996. * Vorbis comment specification, else \c true.
  85997. */
  85998. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  85999. /** Appends a comment to a VORBIS_COMMENT block.
  86000. *
  86001. * For convenience, a trailing NUL is added to the entry if it doesn't have
  86002. * one already.
  86003. *
  86004. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  86005. * takes ownership of the \c entry.entry pointer.
  86006. *
  86007. * \note If this function returns \c false, the caller still owns the
  86008. * pointer.
  86009. *
  86010. * \param object A pointer to an existing VORBIS_COMMENT object.
  86011. * \param entry The comment to insert.
  86012. * \param copy See above.
  86013. * \assert
  86014. * \code object != NULL \endcode
  86015. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  86016. * \code (entry.entry != NULL && entry.length > 0) ||
  86017. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  86018. * \retval FLAC__bool
  86019. * \c false if memory allocation fails or \a entry does not comply with the
  86020. * Vorbis comment specification, else \c true.
  86021. */
  86022. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  86023. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  86024. *
  86025. * For convenience, a trailing NUL is added to the entry if it doesn't have
  86026. * one already.
  86027. *
  86028. * Depending on the the value of \a all, either all or just the first comment
  86029. * whose field name(s) match the given entry's name will be replaced by the
  86030. * given entry. If no comments match, \a entry will simply be appended.
  86031. *
  86032. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  86033. * takes ownership of the \c entry.entry pointer.
  86034. *
  86035. * \note If this function returns \c false, the caller still owns the
  86036. * pointer.
  86037. *
  86038. * \param object A pointer to an existing VORBIS_COMMENT object.
  86039. * \param entry The comment to insert.
  86040. * \param all If \c true, all comments whose field name matches
  86041. * \a entry's field name will be removed, and \a entry will
  86042. * be inserted at the position of the first matching
  86043. * comment. If \c false, only the first comment whose
  86044. * field name matches \a entry's field name will be
  86045. * replaced with \a entry.
  86046. * \param copy See above.
  86047. * \assert
  86048. * \code object != NULL \endcode
  86049. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  86050. * \code (entry.entry != NULL && entry.length > 0) ||
  86051. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  86052. * \retval FLAC__bool
  86053. * \c false if memory allocation fails or \a entry does not comply with the
  86054. * Vorbis comment specification, else \c true.
  86055. */
  86056. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  86057. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  86058. *
  86059. * \param object A pointer to an existing VORBIS_COMMENT object.
  86060. * \param comment_num The index of the comment to delete.
  86061. * \assert
  86062. * \code object != NULL \endcode
  86063. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  86064. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  86065. * \retval FLAC__bool
  86066. * \c false if realloc() fails, else \c true.
  86067. */
  86068. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  86069. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  86070. *
  86071. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  86072. * memory and shall be owned by the caller. For convenience the entry will
  86073. * have a terminating NUL.
  86074. *
  86075. * \param entry A pointer to a Vorbis comment entry. The entry's
  86076. * \c entry pointer should not point to allocated
  86077. * memory as it will be overwritten.
  86078. * \param field_name The field name in ASCII, \c NUL terminated.
  86079. * \param field_value The field value in UTF-8, \c NUL terminated.
  86080. * \assert
  86081. * \code entry != NULL \endcode
  86082. * \code field_name != NULL \endcode
  86083. * \code field_value != NULL \endcode
  86084. * \retval FLAC__bool
  86085. * \c false if malloc() fails, or if \a field_name or \a field_value does
  86086. * not comply with the Vorbis comment specification, else \c true.
  86087. */
  86088. 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);
  86089. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  86090. *
  86091. * The returned pointers to name and value will be allocated by malloc()
  86092. * and shall be owned by the caller.
  86093. *
  86094. * \param entry An existing Vorbis comment entry.
  86095. * \param field_name The address of where the returned pointer to the
  86096. * field name will be stored.
  86097. * \param field_value The address of where the returned pointer to the
  86098. * field value will be stored.
  86099. * \assert
  86100. * \code (entry.entry != NULL && entry.length > 0) \endcode
  86101. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  86102. * \code field_name != NULL \endcode
  86103. * \code field_value != NULL \endcode
  86104. * \retval FLAC__bool
  86105. * \c false if memory allocation fails or \a entry does not comply with the
  86106. * Vorbis comment specification, else \c true.
  86107. */
  86108. 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);
  86109. /** Check if the given Vorbis comment entry's field name matches the given
  86110. * field name.
  86111. *
  86112. * \param entry An existing Vorbis comment entry.
  86113. * \param field_name The field name to check.
  86114. * \param field_name_length The length of \a field_name, not including the
  86115. * terminating \c NUL.
  86116. * \assert
  86117. * \code (entry.entry != NULL && entry.length > 0) \endcode
  86118. * \retval FLAC__bool
  86119. * \c true if the field names match, else \c false
  86120. */
  86121. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  86122. /** Find a Vorbis comment with the given field name.
  86123. *
  86124. * The search begins at entry number \a offset; use an offset of 0 to
  86125. * search from the beginning of the comment array.
  86126. *
  86127. * \param object A pointer to an existing VORBIS_COMMENT object.
  86128. * \param offset The offset into the comment array from where to start
  86129. * the search.
  86130. * \param field_name The field name of the comment to find.
  86131. * \assert
  86132. * \code object != NULL \endcode
  86133. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  86134. * \code field_name != NULL \endcode
  86135. * \retval int
  86136. * The offset in the comment array of the first comment whose field
  86137. * name matches \a field_name, or \c -1 if no match was found.
  86138. */
  86139. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  86140. /** Remove first Vorbis comment matching the given field name.
  86141. *
  86142. * \param object A pointer to an existing VORBIS_COMMENT object.
  86143. * \param field_name The field name of comment to delete.
  86144. * \assert
  86145. * \code object != NULL \endcode
  86146. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  86147. * \retval int
  86148. * \c -1 for memory allocation error, \c 0 for no matching entries,
  86149. * \c 1 for one matching entry deleted.
  86150. */
  86151. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  86152. /** Remove all Vorbis comments matching the given field name.
  86153. *
  86154. * \param object A pointer to an existing VORBIS_COMMENT object.
  86155. * \param field_name The field name of comments to delete.
  86156. * \assert
  86157. * \code object != NULL \endcode
  86158. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  86159. * \retval int
  86160. * \c -1 for memory allocation error, \c 0 for no matching entries,
  86161. * else the number of matching entries deleted.
  86162. */
  86163. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  86164. /** Create a new CUESHEET track instance.
  86165. *
  86166. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  86167. *
  86168. * \retval FLAC__StreamMetadata_CueSheet_Track*
  86169. * \c NULL if there was an error allocating memory, else the new instance.
  86170. */
  86171. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  86172. /** Create a copy of an existing CUESHEET track object.
  86173. *
  86174. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  86175. * object is also copied. The caller takes ownership of the new object and
  86176. * is responsible for freeing it with
  86177. * FLAC__metadata_object_cuesheet_track_delete().
  86178. *
  86179. * \param object Pointer to object to copy.
  86180. * \assert
  86181. * \code object != NULL \endcode
  86182. * \retval FLAC__StreamMetadata_CueSheet_Track*
  86183. * \c NULL if there was an error allocating memory, else the new instance.
  86184. */
  86185. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  86186. /** Delete a CUESHEET track object
  86187. *
  86188. * \param object A pointer to an existing CUESHEET track object.
  86189. * \assert
  86190. * \code object != NULL \endcode
  86191. */
  86192. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  86193. /** Resize a track's index point array.
  86194. *
  86195. * If the size shrinks, elements will truncated; if it grows, new blank
  86196. * indices will be added to the end.
  86197. *
  86198. * \param object A pointer to an existing CUESHEET object.
  86199. * \param track_num The index of the track to modify. NOTE: this is not
  86200. * necessarily the same as the track's \a number field.
  86201. * \param new_num_indices The desired length of the array; may be \c 0.
  86202. * \assert
  86203. * \code object != NULL \endcode
  86204. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  86205. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  86206. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  86207. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  86208. * \retval FLAC__bool
  86209. * \c false if memory allocation error, else \c true.
  86210. */
  86211. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  86212. /** Insert an index point in a CUESHEET track at the given index.
  86213. *
  86214. * \param object A pointer to an existing CUESHEET object.
  86215. * \param track_num The index of the track to modify. NOTE: this is not
  86216. * necessarily the same as the track's \a number field.
  86217. * \param index_num The index into the track's index array at which to
  86218. * insert the index point. NOTE: this is not necessarily
  86219. * the same as the index point's \a number field. The
  86220. * indices at and after \a index_num move right one
  86221. * position. To append an index point to the end, set
  86222. * \a index_num to
  86223. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  86224. * \param index The index point to insert.
  86225. * \assert
  86226. * \code object != NULL \endcode
  86227. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  86228. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  86229. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  86230. * \retval FLAC__bool
  86231. * \c false if realloc() fails, else \c true.
  86232. */
  86233. 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);
  86234. /** Insert a blank index point in a CUESHEET track at the given index.
  86235. *
  86236. * A blank index point is one in which all field values are zero.
  86237. *
  86238. * \param object A pointer to an existing CUESHEET object.
  86239. * \param track_num The index of the track to modify. NOTE: this is not
  86240. * necessarily the same as the track's \a number field.
  86241. * \param index_num The index into the track's index array at which to
  86242. * insert the index point. NOTE: this is not necessarily
  86243. * the same as the index point's \a number field. The
  86244. * indices at and after \a index_num move right one
  86245. * position. To append an index point to the end, set
  86246. * \a index_num to
  86247. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  86248. * \assert
  86249. * \code object != NULL \endcode
  86250. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  86251. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  86252. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  86253. * \retval FLAC__bool
  86254. * \c false if realloc() fails, else \c true.
  86255. */
  86256. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  86257. /** Delete an index point in a CUESHEET track at the given index.
  86258. *
  86259. * \param object A pointer to an existing CUESHEET object.
  86260. * \param track_num The index into the track array of the track to
  86261. * modify. NOTE: this is not necessarily the same
  86262. * as the track's \a number field.
  86263. * \param index_num The index into the track's index array of the index
  86264. * to delete. NOTE: this is not necessarily the same
  86265. * as the index's \a number field.
  86266. * \assert
  86267. * \code object != NULL \endcode
  86268. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  86269. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  86270. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  86271. * \retval FLAC__bool
  86272. * \c false if realloc() fails, else \c true.
  86273. */
  86274. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  86275. /** Resize the track array.
  86276. *
  86277. * If the size shrinks, elements will truncated; if it grows, new blank
  86278. * tracks will be added to the end.
  86279. *
  86280. * \param object A pointer to an existing CUESHEET object.
  86281. * \param new_num_tracks The desired length of the array; may be \c 0.
  86282. * \assert
  86283. * \code object != NULL \endcode
  86284. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  86285. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  86286. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  86287. * \retval FLAC__bool
  86288. * \c false if memory allocation error, else \c true.
  86289. */
  86290. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  86291. /** Sets a track in a CUESHEET block.
  86292. *
  86293. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  86294. * takes ownership of the \a track pointer.
  86295. *
  86296. * \param object A pointer to an existing CUESHEET object.
  86297. * \param track_num Index into track array to set. NOTE: this is not
  86298. * necessarily the same as the track's \a number field.
  86299. * \param track The track to set the track to. You may safely pass in
  86300. * a const pointer if \a copy is \c true.
  86301. * \param copy See above.
  86302. * \assert
  86303. * \code object != NULL \endcode
  86304. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  86305. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  86306. * \code (track->indices != NULL && track->num_indices > 0) ||
  86307. * (track->indices == NULL && track->num_indices == 0)
  86308. * \retval FLAC__bool
  86309. * \c false if \a copy is \c true and malloc() fails, else \c true.
  86310. */
  86311. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  86312. /** Insert a track in a CUESHEET block at the given index.
  86313. *
  86314. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  86315. * takes ownership of the \a track pointer.
  86316. *
  86317. * \param object A pointer to an existing CUESHEET object.
  86318. * \param track_num The index at which to insert the track. NOTE: this
  86319. * is not necessarily the same as the track's \a number
  86320. * field. The tracks at and after \a track_num move right
  86321. * one position. To append a track to the end, set
  86322. * \a track_num to \c object->data.cue_sheet.num_tracks .
  86323. * \param track The track to insert. You may safely pass in a const
  86324. * pointer if \a copy is \c true.
  86325. * \param copy See above.
  86326. * \assert
  86327. * \code object != NULL \endcode
  86328. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  86329. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  86330. * \retval FLAC__bool
  86331. * \c false if \a copy is \c true and malloc() fails, else \c true.
  86332. */
  86333. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  86334. /** Insert a blank track in a CUESHEET block at the given index.
  86335. *
  86336. * A blank track is one in which all field values are zero.
  86337. *
  86338. * \param object A pointer to an existing CUESHEET object.
  86339. * \param track_num The index at which to insert the track. NOTE: this
  86340. * is not necessarily the same as the track's \a number
  86341. * field. The tracks at and after \a track_num move right
  86342. * one position. To append a track to the end, set
  86343. * \a track_num to \c object->data.cue_sheet.num_tracks .
  86344. * \assert
  86345. * \code object != NULL \endcode
  86346. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  86347. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  86348. * \retval FLAC__bool
  86349. * \c false if \a copy is \c true and malloc() fails, else \c true.
  86350. */
  86351. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  86352. /** Delete a track in a CUESHEET block at the given index.
  86353. *
  86354. * \param object A pointer to an existing CUESHEET object.
  86355. * \param track_num The index into the track array of the track to
  86356. * delete. NOTE: this is not necessarily the same
  86357. * as the track's \a number field.
  86358. * \assert
  86359. * \code object != NULL \endcode
  86360. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  86361. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  86362. * \retval FLAC__bool
  86363. * \c false if realloc() fails, else \c true.
  86364. */
  86365. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  86366. /** Check a cue sheet to see if it conforms to the FLAC specification.
  86367. * See the format specification for limits on the contents of the
  86368. * cue sheet.
  86369. *
  86370. * \param object A pointer to an existing CUESHEET object.
  86371. * \param check_cd_da_subset If \c true, check CUESHEET against more
  86372. * stringent requirements for a CD-DA (audio) disc.
  86373. * \param violation Address of a pointer to a string. If there is a
  86374. * violation, a pointer to a string explanation of the
  86375. * violation will be returned here. \a violation may be
  86376. * \c NULL if you don't need the returned string. Do not
  86377. * free the returned string; it will always point to static
  86378. * data.
  86379. * \assert
  86380. * \code object != NULL \endcode
  86381. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  86382. * \retval FLAC__bool
  86383. * \c false if cue sheet is illegal, else \c true.
  86384. */
  86385. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  86386. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  86387. * assumes the cue sheet corresponds to a CD; the result is undefined
  86388. * if the cuesheet's is_cd bit is not set.
  86389. *
  86390. * \param object A pointer to an existing CUESHEET object.
  86391. * \assert
  86392. * \code object != NULL \endcode
  86393. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  86394. * \retval FLAC__uint32
  86395. * The unsigned integer representation of the CDDB/freedb ID
  86396. */
  86397. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  86398. /** Sets the MIME type of a PICTURE block.
  86399. *
  86400. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  86401. * takes ownership of the pointer. The existing string will be freed if this
  86402. * function is successful, otherwise the original string will remain if \a copy
  86403. * is \c true and malloc() fails.
  86404. *
  86405. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  86406. *
  86407. * \param object A pointer to an existing PICTURE object.
  86408. * \param mime_type A pointer to the MIME type string. The string must be
  86409. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  86410. * is done.
  86411. * \param copy See above.
  86412. * \assert
  86413. * \code object != NULL \endcode
  86414. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  86415. * \code (mime_type != NULL) \endcode
  86416. * \retval FLAC__bool
  86417. * \c false if \a copy is \c true and malloc() fails, else \c true.
  86418. */
  86419. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  86420. /** Sets the description of a PICTURE block.
  86421. *
  86422. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  86423. * takes ownership of the pointer. The existing string will be freed if this
  86424. * function is successful, otherwise the original string will remain if \a copy
  86425. * is \c true and malloc() fails.
  86426. *
  86427. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  86428. *
  86429. * \param object A pointer to an existing PICTURE object.
  86430. * \param description A pointer to the description string. The string must be
  86431. * valid UTF-8, NUL-terminated. No validation is done.
  86432. * \param copy See above.
  86433. * \assert
  86434. * \code object != NULL \endcode
  86435. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  86436. * \code (description != NULL) \endcode
  86437. * \retval FLAC__bool
  86438. * \c false if \a copy is \c true and malloc() fails, else \c true.
  86439. */
  86440. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  86441. /** Sets the picture data of a PICTURE block.
  86442. *
  86443. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  86444. * takes ownership of the pointer. Also sets the \a data_length field of the
  86445. * metadata object to what is passed in as the \a length parameter. The
  86446. * existing data will be freed if this function is successful, otherwise the
  86447. * original data and data_length will remain if \a copy is \c true and
  86448. * malloc() fails.
  86449. *
  86450. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  86451. *
  86452. * \param object A pointer to an existing PICTURE object.
  86453. * \param data A pointer to the data to set.
  86454. * \param length The length of \a data in bytes.
  86455. * \param copy See above.
  86456. * \assert
  86457. * \code object != NULL \endcode
  86458. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  86459. * \code (data != NULL && length > 0) ||
  86460. * (data == NULL && length == 0 && copy == false) \endcode
  86461. * \retval FLAC__bool
  86462. * \c false if \a copy is \c true and malloc() fails, else \c true.
  86463. */
  86464. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  86465. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  86466. * See the format specification for limits on the contents of the
  86467. * PICTURE block.
  86468. *
  86469. * \param object A pointer to existing PICTURE block to be checked.
  86470. * \param violation Address of a pointer to a string. If there is a
  86471. * violation, a pointer to a string explanation of the
  86472. * violation will be returned here. \a violation may be
  86473. * \c NULL if you don't need the returned string. Do not
  86474. * free the returned string; it will always point to static
  86475. * data.
  86476. * \assert
  86477. * \code object != NULL \endcode
  86478. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  86479. * \retval FLAC__bool
  86480. * \c false if PICTURE block is illegal, else \c true.
  86481. */
  86482. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  86483. /* \} */
  86484. #ifdef __cplusplus
  86485. }
  86486. #endif
  86487. #endif
  86488. /*** End of inlined file: metadata.h ***/
  86489. /*** Start of inlined file: stream_decoder.h ***/
  86490. #ifndef FLAC__STREAM_DECODER_H
  86491. #define FLAC__STREAM_DECODER_H
  86492. #include <stdio.h> /* for FILE */
  86493. #ifdef __cplusplus
  86494. extern "C" {
  86495. #endif
  86496. /** \file include/FLAC/stream_decoder.h
  86497. *
  86498. * \brief
  86499. * This module contains the functions which implement the stream
  86500. * decoder.
  86501. *
  86502. * See the detailed documentation in the
  86503. * \link flac_stream_decoder stream decoder \endlink module.
  86504. */
  86505. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  86506. * \ingroup flac
  86507. *
  86508. * \brief
  86509. * This module describes the decoder layers provided by libFLAC.
  86510. *
  86511. * The stream decoder can be used to decode complete streams either from
  86512. * the client via callbacks, or directly from a file, depending on how
  86513. * it is initialized. When decoding via callbacks, the client provides
  86514. * callbacks for reading FLAC data and writing decoded samples, and
  86515. * handling metadata and errors. If the client also supplies seek-related
  86516. * callback, the decoder function for sample-accurate seeking within the
  86517. * FLAC input is also available. When decoding from a file, the client
  86518. * needs only supply a filename or open \c FILE* and write/metadata/error
  86519. * callbacks; the rest of the callbacks are supplied internally. For more
  86520. * info see the \link flac_stream_decoder stream decoder \endlink module.
  86521. */
  86522. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  86523. * \ingroup flac_decoder
  86524. *
  86525. * \brief
  86526. * This module contains the functions which implement the stream
  86527. * decoder.
  86528. *
  86529. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  86530. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  86531. *
  86532. * The basic usage of this decoder is as follows:
  86533. * - The program creates an instance of a decoder using
  86534. * FLAC__stream_decoder_new().
  86535. * - The program overrides the default settings using
  86536. * FLAC__stream_decoder_set_*() functions.
  86537. * - The program initializes the instance to validate the settings and
  86538. * prepare for decoding using
  86539. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  86540. * or FLAC__stream_decoder_init_file() for native FLAC,
  86541. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  86542. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  86543. * - The program calls the FLAC__stream_decoder_process_*() functions
  86544. * to decode data, which subsequently calls the callbacks.
  86545. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  86546. * which flushes the input and output and resets the decoder to the
  86547. * uninitialized state.
  86548. * - The instance may be used again or deleted with
  86549. * FLAC__stream_decoder_delete().
  86550. *
  86551. * In more detail, the program will create a new instance by calling
  86552. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  86553. * functions to override the default decoder options, and call
  86554. * one of the FLAC__stream_decoder_init_*() functions.
  86555. *
  86556. * There are three initialization functions for native FLAC, one for
  86557. * setting up the decoder to decode FLAC data from the client via
  86558. * callbacks, and two for decoding directly from a FLAC file.
  86559. *
  86560. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  86561. * You must also supply several callbacks for handling I/O. Some (like
  86562. * seeking) are optional, depending on the capabilities of the input.
  86563. *
  86564. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  86565. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  86566. * \c FILE* or filename and fewer callbacks; the decoder will handle
  86567. * the other callbacks internally.
  86568. *
  86569. * There are three similarly-named init functions for decoding from Ogg
  86570. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  86571. * library has been built with Ogg support.
  86572. *
  86573. * Once the decoder is initialized, your program will call one of several
  86574. * functions to start the decoding process:
  86575. *
  86576. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  86577. * most one metadata block or audio frame and return, calling either the
  86578. * metadata callback or write callback, respectively, once. If the decoder
  86579. * loses sync it will return with only the error callback being called.
  86580. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  86581. * to process the stream from the current location and stop upon reaching
  86582. * the first audio frame. The client will get one metadata, write, or error
  86583. * callback per metadata block, audio frame, or sync error, respectively.
  86584. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  86585. * to process the stream from the current location until the read callback
  86586. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  86587. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  86588. * write, or error callback per metadata block, audio frame, or sync error,
  86589. * respectively.
  86590. *
  86591. * When the decoder has finished decoding (normally or through an abort),
  86592. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  86593. * ensures the decoder is in the correct state and frees memory. Then the
  86594. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  86595. * again to decode another stream.
  86596. *
  86597. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  86598. * At any point after the stream decoder has been initialized, the client can
  86599. * call this function to seek to an exact sample within the stream.
  86600. * Subsequently, the first time the write callback is called it will be
  86601. * passed a (possibly partial) block starting at that sample.
  86602. *
  86603. * If the client cannot seek via the callback interface provided, but still
  86604. * has another way of seeking, it can flush the decoder using
  86605. * FLAC__stream_decoder_flush() and start feeding data from the new position
  86606. * through the read callback.
  86607. *
  86608. * The stream decoder also provides MD5 signature checking. If this is
  86609. * turned on before initialization, FLAC__stream_decoder_finish() will
  86610. * report when the decoded MD5 signature does not match the one stored
  86611. * in the STREAMINFO block. MD5 checking is automatically turned off
  86612. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  86613. * in the STREAMINFO block or when a seek is attempted.
  86614. *
  86615. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  86616. * attention. By default, the decoder only calls the metadata_callback for
  86617. * the STREAMINFO block. These functions allow you to tell the decoder
  86618. * explicitly which blocks to parse and return via the metadata_callback
  86619. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  86620. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  86621. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  86622. * which blocks to return. Remember that metadata blocks can potentially
  86623. * be big (for example, cover art) so filtering out the ones you don't
  86624. * use can reduce the memory requirements of the decoder. Also note the
  86625. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  86626. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  86627. * filtering APPLICATION blocks based on the application ID.
  86628. *
  86629. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  86630. * they still can legally be filtered from the metadata_callback.
  86631. *
  86632. * \note
  86633. * The "set" functions may only be called when the decoder is in the
  86634. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  86635. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  86636. * before FLAC__stream_decoder_init_*(). If this is the case they will
  86637. * return \c true, otherwise \c false.
  86638. *
  86639. * \note
  86640. * FLAC__stream_decoder_finish() resets all settings to the constructor
  86641. * defaults, including the callbacks.
  86642. *
  86643. * \{
  86644. */
  86645. /** State values for a FLAC__StreamDecoder
  86646. *
  86647. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  86648. */
  86649. typedef enum {
  86650. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  86651. /**< The decoder is ready to search for metadata. */
  86652. FLAC__STREAM_DECODER_READ_METADATA,
  86653. /**< The decoder is ready to or is in the process of reading metadata. */
  86654. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  86655. /**< The decoder is ready to or is in the process of searching for the
  86656. * frame sync code.
  86657. */
  86658. FLAC__STREAM_DECODER_READ_FRAME,
  86659. /**< The decoder is ready to or is in the process of reading a frame. */
  86660. FLAC__STREAM_DECODER_END_OF_STREAM,
  86661. /**< The decoder has reached the end of the stream. */
  86662. FLAC__STREAM_DECODER_OGG_ERROR,
  86663. /**< An error occurred in the underlying Ogg layer. */
  86664. FLAC__STREAM_DECODER_SEEK_ERROR,
  86665. /**< An error occurred while seeking. The decoder must be flushed
  86666. * with FLAC__stream_decoder_flush() or reset with
  86667. * FLAC__stream_decoder_reset() before decoding can continue.
  86668. */
  86669. FLAC__STREAM_DECODER_ABORTED,
  86670. /**< The decoder was aborted by the read callback. */
  86671. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  86672. /**< An error occurred allocating memory. The decoder is in an invalid
  86673. * state and can no longer be used.
  86674. */
  86675. FLAC__STREAM_DECODER_UNINITIALIZED
  86676. /**< The decoder is in the uninitialized state; one of the
  86677. * FLAC__stream_decoder_init_*() functions must be called before samples
  86678. * can be processed.
  86679. */
  86680. } FLAC__StreamDecoderState;
  86681. /** Maps a FLAC__StreamDecoderState to a C string.
  86682. *
  86683. * Using a FLAC__StreamDecoderState as the index to this array
  86684. * will give the string equivalent. The contents should not be modified.
  86685. */
  86686. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  86687. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  86688. */
  86689. typedef enum {
  86690. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  86691. /**< Initialization was successful. */
  86692. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  86693. /**< The library was not compiled with support for the given container
  86694. * format.
  86695. */
  86696. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  86697. /**< A required callback was not supplied. */
  86698. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  86699. /**< An error occurred allocating memory. */
  86700. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  86701. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  86702. * FLAC__stream_decoder_init_ogg_file(). */
  86703. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  86704. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  86705. * already initialized, usually because
  86706. * FLAC__stream_decoder_finish() was not called.
  86707. */
  86708. } FLAC__StreamDecoderInitStatus;
  86709. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  86710. *
  86711. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  86712. * will give the string equivalent. The contents should not be modified.
  86713. */
  86714. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  86715. /** Return values for the FLAC__StreamDecoder read callback.
  86716. */
  86717. typedef enum {
  86718. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  86719. /**< The read was OK and decoding can continue. */
  86720. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  86721. /**< The read was attempted while at the end of the stream. Note that
  86722. * the client must only return this value when the read callback was
  86723. * called when already at the end of the stream. Otherwise, if the read
  86724. * itself moves to the end of the stream, the client should still return
  86725. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  86726. * the next read callback it should return
  86727. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  86728. * of \c 0.
  86729. */
  86730. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  86731. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  86732. } FLAC__StreamDecoderReadStatus;
  86733. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  86734. *
  86735. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  86736. * will give the string equivalent. The contents should not be modified.
  86737. */
  86738. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  86739. /** Return values for the FLAC__StreamDecoder seek callback.
  86740. */
  86741. typedef enum {
  86742. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  86743. /**< The seek was OK and decoding can continue. */
  86744. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  86745. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  86746. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  86747. /**< Client does not support seeking. */
  86748. } FLAC__StreamDecoderSeekStatus;
  86749. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  86750. *
  86751. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  86752. * will give the string equivalent. The contents should not be modified.
  86753. */
  86754. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  86755. /** Return values for the FLAC__StreamDecoder tell callback.
  86756. */
  86757. typedef enum {
  86758. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  86759. /**< The tell was OK and decoding can continue. */
  86760. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  86761. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  86762. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  86763. /**< Client does not support telling the position. */
  86764. } FLAC__StreamDecoderTellStatus;
  86765. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  86766. *
  86767. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  86768. * will give the string equivalent. The contents should not be modified.
  86769. */
  86770. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  86771. /** Return values for the FLAC__StreamDecoder length callback.
  86772. */
  86773. typedef enum {
  86774. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  86775. /**< The length call was OK and decoding can continue. */
  86776. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  86777. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  86778. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  86779. /**< Client does not support reporting the length. */
  86780. } FLAC__StreamDecoderLengthStatus;
  86781. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  86782. *
  86783. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  86784. * will give the string equivalent. The contents should not be modified.
  86785. */
  86786. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  86787. /** Return values for the FLAC__StreamDecoder write callback.
  86788. */
  86789. typedef enum {
  86790. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  86791. /**< The write was OK and decoding can continue. */
  86792. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  86793. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  86794. } FLAC__StreamDecoderWriteStatus;
  86795. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  86796. *
  86797. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  86798. * will give the string equivalent. The contents should not be modified.
  86799. */
  86800. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  86801. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  86802. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  86803. * all. The rest could be caused by bad sync (false synchronization on
  86804. * data that is not the start of a frame) or corrupted data. The error
  86805. * itself is the decoder's best guess at what happened assuming a correct
  86806. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  86807. * could be caused by a correct sync on the start of a frame, but some
  86808. * data in the frame header was corrupted. Or it could be the result of
  86809. * syncing on a point the stream that looked like the starting of a frame
  86810. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  86811. * could be because the decoder encountered a valid frame made by a future
  86812. * version of the encoder which it cannot parse, or because of a false
  86813. * sync making it appear as though an encountered frame was generated by
  86814. * a future encoder.
  86815. */
  86816. typedef enum {
  86817. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  86818. /**< An error in the stream caused the decoder to lose synchronization. */
  86819. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  86820. /**< The decoder encountered a corrupted frame header. */
  86821. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  86822. /**< The frame's data did not match the CRC in the footer. */
  86823. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  86824. /**< The decoder encountered reserved fields in use in the stream. */
  86825. } FLAC__StreamDecoderErrorStatus;
  86826. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  86827. *
  86828. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  86829. * will give the string equivalent. The contents should not be modified.
  86830. */
  86831. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  86832. /***********************************************************************
  86833. *
  86834. * class FLAC__StreamDecoder
  86835. *
  86836. ***********************************************************************/
  86837. struct FLAC__StreamDecoderProtected;
  86838. struct FLAC__StreamDecoderPrivate;
  86839. /** The opaque structure definition for the stream decoder type.
  86840. * See the \link flac_stream_decoder stream decoder module \endlink
  86841. * for a detailed description.
  86842. */
  86843. typedef struct {
  86844. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  86845. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  86846. } FLAC__StreamDecoder;
  86847. /** Signature for the read callback.
  86848. *
  86849. * A function pointer matching this signature must be passed to
  86850. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  86851. * called when the decoder needs more input data. The address of the
  86852. * buffer to be filled is supplied, along with the number of bytes the
  86853. * buffer can hold. The callback may choose to supply less data and
  86854. * modify the byte count but must be careful not to overflow the buffer.
  86855. * The callback then returns a status code chosen from
  86856. * FLAC__StreamDecoderReadStatus.
  86857. *
  86858. * Here is an example of a read callback for stdio streams:
  86859. * \code
  86860. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  86861. * {
  86862. * FILE *file = ((MyClientData*)client_data)->file;
  86863. * if(*bytes > 0) {
  86864. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  86865. * if(ferror(file))
  86866. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  86867. * else if(*bytes == 0)
  86868. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  86869. * else
  86870. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  86871. * }
  86872. * else
  86873. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  86874. * }
  86875. * \endcode
  86876. *
  86877. * \note In general, FLAC__StreamDecoder functions which change the
  86878. * state should not be called on the \a decoder while in the callback.
  86879. *
  86880. * \param decoder The decoder instance calling the callback.
  86881. * \param buffer A pointer to a location for the callee to store
  86882. * data to be decoded.
  86883. * \param bytes A pointer to the size of the buffer. On entry
  86884. * to the callback, it contains the maximum number
  86885. * of bytes that may be stored in \a buffer. The
  86886. * callee must set it to the actual number of bytes
  86887. * stored (0 in case of error or end-of-stream) before
  86888. * returning.
  86889. * \param client_data The callee's client data set through
  86890. * FLAC__stream_decoder_init_*().
  86891. * \retval FLAC__StreamDecoderReadStatus
  86892. * The callee's return status. Note that the callback should return
  86893. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  86894. * zero bytes were read and there is no more data to be read.
  86895. */
  86896. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  86897. /** Signature for the seek callback.
  86898. *
  86899. * A function pointer matching this signature may be passed to
  86900. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  86901. * called when the decoder needs to seek the input stream. The decoder
  86902. * will pass the absolute byte offset to seek to, 0 meaning the
  86903. * beginning of the stream.
  86904. *
  86905. * Here is an example of a seek callback for stdio streams:
  86906. * \code
  86907. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  86908. * {
  86909. * FILE *file = ((MyClientData*)client_data)->file;
  86910. * if(file == stdin)
  86911. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  86912. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  86913. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  86914. * else
  86915. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  86916. * }
  86917. * \endcode
  86918. *
  86919. * \note In general, FLAC__StreamDecoder functions which change the
  86920. * state should not be called on the \a decoder while in the callback.
  86921. *
  86922. * \param decoder The decoder instance calling the callback.
  86923. * \param absolute_byte_offset The offset from the beginning of the stream
  86924. * to seek to.
  86925. * \param client_data The callee's client data set through
  86926. * FLAC__stream_decoder_init_*().
  86927. * \retval FLAC__StreamDecoderSeekStatus
  86928. * The callee's return status.
  86929. */
  86930. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  86931. /** Signature for the tell callback.
  86932. *
  86933. * A function pointer matching this signature may be passed to
  86934. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  86935. * called when the decoder wants to know the current position of the
  86936. * stream. The callback should return the byte offset from the
  86937. * beginning of the stream.
  86938. *
  86939. * Here is an example of a tell callback for stdio streams:
  86940. * \code
  86941. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  86942. * {
  86943. * FILE *file = ((MyClientData*)client_data)->file;
  86944. * off_t pos;
  86945. * if(file == stdin)
  86946. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  86947. * else if((pos = ftello(file)) < 0)
  86948. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  86949. * else {
  86950. * *absolute_byte_offset = (FLAC__uint64)pos;
  86951. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  86952. * }
  86953. * }
  86954. * \endcode
  86955. *
  86956. * \note In general, FLAC__StreamDecoder functions which change the
  86957. * state should not be called on the \a decoder while in the callback.
  86958. *
  86959. * \param decoder The decoder instance calling the callback.
  86960. * \param absolute_byte_offset A pointer to storage for the current offset
  86961. * from the beginning of the stream.
  86962. * \param client_data The callee's client data set through
  86963. * FLAC__stream_decoder_init_*().
  86964. * \retval FLAC__StreamDecoderTellStatus
  86965. * The callee's return status.
  86966. */
  86967. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  86968. /** Signature for the length callback.
  86969. *
  86970. * A function pointer matching this signature may be passed to
  86971. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  86972. * called when the decoder wants to know the total length of the stream
  86973. * in bytes.
  86974. *
  86975. * Here is an example of a length callback for stdio streams:
  86976. * \code
  86977. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  86978. * {
  86979. * FILE *file = ((MyClientData*)client_data)->file;
  86980. * struct stat filestats;
  86981. *
  86982. * if(file == stdin)
  86983. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  86984. * else if(fstat(fileno(file), &filestats) != 0)
  86985. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  86986. * else {
  86987. * *stream_length = (FLAC__uint64)filestats.st_size;
  86988. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  86989. * }
  86990. * }
  86991. * \endcode
  86992. *
  86993. * \note In general, FLAC__StreamDecoder functions which change the
  86994. * state should not be called on the \a decoder while in the callback.
  86995. *
  86996. * \param decoder The decoder instance calling the callback.
  86997. * \param stream_length A pointer to storage for the length of the stream
  86998. * in bytes.
  86999. * \param client_data The callee's client data set through
  87000. * FLAC__stream_decoder_init_*().
  87001. * \retval FLAC__StreamDecoderLengthStatus
  87002. * The callee's return status.
  87003. */
  87004. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  87005. /** Signature for the EOF callback.
  87006. *
  87007. * A function pointer matching this signature may be passed to
  87008. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  87009. * called when the decoder needs to know if the end of the stream has
  87010. * been reached.
  87011. *
  87012. * Here is an example of a EOF callback for stdio streams:
  87013. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  87014. * \code
  87015. * {
  87016. * FILE *file = ((MyClientData*)client_data)->file;
  87017. * return feof(file)? true : false;
  87018. * }
  87019. * \endcode
  87020. *
  87021. * \note In general, FLAC__StreamDecoder functions which change the
  87022. * state should not be called on the \a decoder while in the callback.
  87023. *
  87024. * \param decoder The decoder instance calling the callback.
  87025. * \param client_data The callee's client data set through
  87026. * FLAC__stream_decoder_init_*().
  87027. * \retval FLAC__bool
  87028. * \c true if the currently at the end of the stream, else \c false.
  87029. */
  87030. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  87031. /** Signature for the write callback.
  87032. *
  87033. * A function pointer matching this signature must be passed to one of
  87034. * the FLAC__stream_decoder_init_*() functions.
  87035. * The supplied function will be called when the decoder has decoded a
  87036. * single audio frame. The decoder will pass the frame metadata as well
  87037. * as an array of pointers (one for each channel) pointing to the
  87038. * decoded audio.
  87039. *
  87040. * \note In general, FLAC__StreamDecoder functions which change the
  87041. * state should not be called on the \a decoder while in the callback.
  87042. *
  87043. * \param decoder The decoder instance calling the callback.
  87044. * \param frame The description of the decoded frame. See
  87045. * FLAC__Frame.
  87046. * \param buffer An array of pointers to decoded channels of data.
  87047. * Each pointer will point to an array of signed
  87048. * samples of length \a frame->header.blocksize.
  87049. * Channels will be ordered according to the FLAC
  87050. * specification; see the documentation for the
  87051. * <A HREF="../format.html#frame_header">frame header</A>.
  87052. * \param client_data The callee's client data set through
  87053. * FLAC__stream_decoder_init_*().
  87054. * \retval FLAC__StreamDecoderWriteStatus
  87055. * The callee's return status.
  87056. */
  87057. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  87058. /** Signature for the metadata callback.
  87059. *
  87060. * A function pointer matching this signature must be passed to one of
  87061. * the FLAC__stream_decoder_init_*() functions.
  87062. * The supplied function will be called when the decoder has decoded a
  87063. * metadata block. In a valid FLAC file there will always be one
  87064. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  87065. * These will be supplied by the decoder in the same order as they
  87066. * appear in the stream and always before the first audio frame (i.e.
  87067. * write callback). The metadata block that is passed in must not be
  87068. * modified, and it doesn't live beyond the callback, so you should make
  87069. * a copy of it with FLAC__metadata_object_clone() if you will need it
  87070. * elsewhere. Since metadata blocks can potentially be large, by
  87071. * default the decoder only calls the metadata callback for the
  87072. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  87073. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  87074. *
  87075. * \note In general, FLAC__StreamDecoder functions which change the
  87076. * state should not be called on the \a decoder while in the callback.
  87077. *
  87078. * \param decoder The decoder instance calling the callback.
  87079. * \param metadata The decoded metadata block.
  87080. * \param client_data The callee's client data set through
  87081. * FLAC__stream_decoder_init_*().
  87082. */
  87083. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  87084. /** Signature for the error callback.
  87085. *
  87086. * A function pointer matching this signature must be passed to one of
  87087. * the FLAC__stream_decoder_init_*() functions.
  87088. * The supplied function will be called whenever an error occurs during
  87089. * decoding.
  87090. *
  87091. * \note In general, FLAC__StreamDecoder functions which change the
  87092. * state should not be called on the \a decoder while in the callback.
  87093. *
  87094. * \param decoder The decoder instance calling the callback.
  87095. * \param status The error encountered by the decoder.
  87096. * \param client_data The callee's client data set through
  87097. * FLAC__stream_decoder_init_*().
  87098. */
  87099. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  87100. /***********************************************************************
  87101. *
  87102. * Class constructor/destructor
  87103. *
  87104. ***********************************************************************/
  87105. /** Create a new stream decoder instance. The instance is created with
  87106. * default settings; see the individual FLAC__stream_decoder_set_*()
  87107. * functions for each setting's default.
  87108. *
  87109. * \retval FLAC__StreamDecoder*
  87110. * \c NULL if there was an error allocating memory, else the new instance.
  87111. */
  87112. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  87113. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  87114. *
  87115. * \param decoder A pointer to an existing decoder.
  87116. * \assert
  87117. * \code decoder != NULL \endcode
  87118. */
  87119. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  87120. /***********************************************************************
  87121. *
  87122. * Public class method prototypes
  87123. *
  87124. ***********************************************************************/
  87125. /** Set the serial number for the FLAC stream within the Ogg container.
  87126. * The default behavior is to use the serial number of the first Ogg
  87127. * page. Setting a serial number here will explicitly specify which
  87128. * stream is to be decoded.
  87129. *
  87130. * \note
  87131. * This does not need to be set for native FLAC decoding.
  87132. *
  87133. * \default \c use serial number of first page
  87134. * \param decoder A decoder instance to set.
  87135. * \param serial_number See above.
  87136. * \assert
  87137. * \code decoder != NULL \endcode
  87138. * \retval FLAC__bool
  87139. * \c false if the decoder is already initialized, else \c true.
  87140. */
  87141. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  87142. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  87143. * compute the MD5 signature of the unencoded audio data while decoding
  87144. * and compare it to the signature from the STREAMINFO block, if it
  87145. * exists, during FLAC__stream_decoder_finish().
  87146. *
  87147. * MD5 signature checking will be turned off (until the next
  87148. * FLAC__stream_decoder_reset()) if there is no signature in the
  87149. * STREAMINFO block or when a seek is attempted.
  87150. *
  87151. * Clients that do not use the MD5 check should leave this off to speed
  87152. * up decoding.
  87153. *
  87154. * \default \c false
  87155. * \param decoder A decoder instance to set.
  87156. * \param value Flag value (see above).
  87157. * \assert
  87158. * \code decoder != NULL \endcode
  87159. * \retval FLAC__bool
  87160. * \c false if the decoder is already initialized, else \c true.
  87161. */
  87162. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  87163. /** Direct the decoder to pass on all metadata blocks of type \a type.
  87164. *
  87165. * \default By default, only the \c STREAMINFO block is returned via the
  87166. * metadata callback.
  87167. * \param decoder A decoder instance to set.
  87168. * \param type See above.
  87169. * \assert
  87170. * \code decoder != NULL \endcode
  87171. * \a type is valid
  87172. * \retval FLAC__bool
  87173. * \c false if the decoder is already initialized, else \c true.
  87174. */
  87175. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  87176. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  87177. * given \a id.
  87178. *
  87179. * \default By default, only the \c STREAMINFO block is returned via the
  87180. * metadata callback.
  87181. * \param decoder A decoder instance to set.
  87182. * \param id See above.
  87183. * \assert
  87184. * \code decoder != NULL \endcode
  87185. * \code id != NULL \endcode
  87186. * \retval FLAC__bool
  87187. * \c false if the decoder is already initialized, else \c true.
  87188. */
  87189. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  87190. /** Direct the decoder to pass on all metadata blocks of any type.
  87191. *
  87192. * \default By default, only the \c STREAMINFO block is returned via the
  87193. * metadata callback.
  87194. * \param decoder A decoder instance to set.
  87195. * \assert
  87196. * \code decoder != NULL \endcode
  87197. * \retval FLAC__bool
  87198. * \c false if the decoder is already initialized, else \c true.
  87199. */
  87200. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  87201. /** Direct the decoder to filter out all metadata blocks of type \a type.
  87202. *
  87203. * \default By default, only the \c STREAMINFO block is returned via the
  87204. * metadata callback.
  87205. * \param decoder A decoder instance to set.
  87206. * \param type See above.
  87207. * \assert
  87208. * \code decoder != NULL \endcode
  87209. * \a type is valid
  87210. * \retval FLAC__bool
  87211. * \c false if the decoder is already initialized, else \c true.
  87212. */
  87213. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  87214. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  87215. * the given \a id.
  87216. *
  87217. * \default By default, only the \c STREAMINFO block is returned via the
  87218. * metadata callback.
  87219. * \param decoder A decoder instance to set.
  87220. * \param id See above.
  87221. * \assert
  87222. * \code decoder != NULL \endcode
  87223. * \code id != NULL \endcode
  87224. * \retval FLAC__bool
  87225. * \c false if the decoder is already initialized, else \c true.
  87226. */
  87227. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  87228. /** Direct the decoder to filter out all metadata blocks of any type.
  87229. *
  87230. * \default By default, only the \c STREAMINFO block is returned via the
  87231. * metadata callback.
  87232. * \param decoder A decoder instance to set.
  87233. * \assert
  87234. * \code decoder != NULL \endcode
  87235. * \retval FLAC__bool
  87236. * \c false if the decoder is already initialized, else \c true.
  87237. */
  87238. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  87239. /** Get the current decoder state.
  87240. *
  87241. * \param decoder A decoder instance to query.
  87242. * \assert
  87243. * \code decoder != NULL \endcode
  87244. * \retval FLAC__StreamDecoderState
  87245. * The current decoder state.
  87246. */
  87247. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  87248. /** Get the current decoder state as a C string.
  87249. *
  87250. * \param decoder A decoder instance to query.
  87251. * \assert
  87252. * \code decoder != NULL \endcode
  87253. * \retval const char *
  87254. * The decoder state as a C string. Do not modify the contents.
  87255. */
  87256. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  87257. /** Get the "MD5 signature checking" flag.
  87258. * This is the value of the setting, not whether or not the decoder is
  87259. * currently checking the MD5 (remember, it can be turned off automatically
  87260. * by a seek). When the decoder is reset the flag will be restored to the
  87261. * value returned by this function.
  87262. *
  87263. * \param decoder A decoder instance to query.
  87264. * \assert
  87265. * \code decoder != NULL \endcode
  87266. * \retval FLAC__bool
  87267. * See above.
  87268. */
  87269. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  87270. /** Get the total number of samples in the stream being decoded.
  87271. * Will only be valid after decoding has started and will contain the
  87272. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  87273. *
  87274. * \param decoder A decoder instance to query.
  87275. * \assert
  87276. * \code decoder != NULL \endcode
  87277. * \retval unsigned
  87278. * See above.
  87279. */
  87280. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  87281. /** Get the current number of channels in the stream being decoded.
  87282. * Will only be valid after decoding has started and will contain the
  87283. * value from the most recently decoded frame header.
  87284. *
  87285. * \param decoder A decoder instance to query.
  87286. * \assert
  87287. * \code decoder != NULL \endcode
  87288. * \retval unsigned
  87289. * See above.
  87290. */
  87291. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  87292. /** Get the current channel assignment in the stream being decoded.
  87293. * Will only be valid after decoding has started and will contain the
  87294. * value from the most recently decoded frame header.
  87295. *
  87296. * \param decoder A decoder instance to query.
  87297. * \assert
  87298. * \code decoder != NULL \endcode
  87299. * \retval FLAC__ChannelAssignment
  87300. * See above.
  87301. */
  87302. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  87303. /** Get the current sample resolution in the stream being decoded.
  87304. * Will only be valid after decoding has started and will contain the
  87305. * value from the most recently decoded frame header.
  87306. *
  87307. * \param decoder A decoder instance to query.
  87308. * \assert
  87309. * \code decoder != NULL \endcode
  87310. * \retval unsigned
  87311. * See above.
  87312. */
  87313. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  87314. /** Get the current sample rate in Hz of the stream being decoded.
  87315. * Will only be valid after decoding has started and will contain the
  87316. * value from the most recently decoded frame header.
  87317. *
  87318. * \param decoder A decoder instance to query.
  87319. * \assert
  87320. * \code decoder != NULL \endcode
  87321. * \retval unsigned
  87322. * See above.
  87323. */
  87324. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  87325. /** Get the current blocksize of the stream being decoded.
  87326. * Will only be valid after decoding has started and will contain the
  87327. * value from the most recently decoded frame header.
  87328. *
  87329. * \param decoder A decoder instance to query.
  87330. * \assert
  87331. * \code decoder != NULL \endcode
  87332. * \retval unsigned
  87333. * See above.
  87334. */
  87335. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  87336. /** Returns the decoder's current read position within the stream.
  87337. * The position is the byte offset from the start of the stream.
  87338. * Bytes before this position have been fully decoded. Note that
  87339. * there may still be undecoded bytes in the decoder's read FIFO.
  87340. * The returned position is correct even after a seek.
  87341. *
  87342. * \warning This function currently only works for native FLAC,
  87343. * not Ogg FLAC streams.
  87344. *
  87345. * \param decoder A decoder instance to query.
  87346. * \param position Address at which to return the desired position.
  87347. * \assert
  87348. * \code decoder != NULL \endcode
  87349. * \code position != NULL \endcode
  87350. * \retval FLAC__bool
  87351. * \c true if successful, \c false if the stream is not native FLAC,
  87352. * or there was an error from the 'tell' callback or it returned
  87353. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  87354. */
  87355. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  87356. /** Initialize the decoder instance to decode native FLAC streams.
  87357. *
  87358. * This flavor of initialization sets up the decoder to decode from a
  87359. * native FLAC stream. I/O is performed via callbacks to the client.
  87360. * For decoding from a plain file via filename or open FILE*,
  87361. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  87362. * provide a simpler interface.
  87363. *
  87364. * This function should be called after FLAC__stream_decoder_new() and
  87365. * FLAC__stream_decoder_set_*() but before any of the
  87366. * FLAC__stream_decoder_process_*() functions. Will set and return the
  87367. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  87368. * if initialization succeeded.
  87369. *
  87370. * \param decoder An uninitialized decoder instance.
  87371. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  87372. * pointer must not be \c NULL.
  87373. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  87374. * pointer may be \c NULL if seeking is not
  87375. * supported. If \a seek_callback is not \c NULL then a
  87376. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  87377. * Alternatively, a dummy seek callback that just
  87378. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  87379. * may also be supplied, all though this is slightly
  87380. * less efficient for the decoder.
  87381. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  87382. * pointer may be \c NULL if not supported by the client. If
  87383. * \a seek_callback is not \c NULL then a
  87384. * \a tell_callback must also be supplied.
  87385. * Alternatively, a dummy tell callback that just
  87386. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  87387. * may also be supplied, all though this is slightly
  87388. * less efficient for the decoder.
  87389. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  87390. * pointer may be \c NULL if not supported by the client. If
  87391. * \a seek_callback is not \c NULL then a
  87392. * \a length_callback must also be supplied.
  87393. * Alternatively, a dummy length callback that just
  87394. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  87395. * may also be supplied, all though this is slightly
  87396. * less efficient for the decoder.
  87397. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  87398. * pointer may be \c NULL if not supported by the client. If
  87399. * \a seek_callback is not \c NULL then a
  87400. * \a eof_callback must also be supplied.
  87401. * Alternatively, a dummy length callback that just
  87402. * returns \c false
  87403. * may also be supplied, all though this is slightly
  87404. * less efficient for the decoder.
  87405. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  87406. * pointer must not be \c NULL.
  87407. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  87408. * pointer may be \c NULL if the callback is not
  87409. * desired.
  87410. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  87411. * pointer must not be \c NULL.
  87412. * \param client_data This value will be supplied to callbacks in their
  87413. * \a client_data argument.
  87414. * \assert
  87415. * \code decoder != NULL \endcode
  87416. * \retval FLAC__StreamDecoderInitStatus
  87417. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  87418. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  87419. */
  87420. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  87421. FLAC__StreamDecoder *decoder,
  87422. FLAC__StreamDecoderReadCallback read_callback,
  87423. FLAC__StreamDecoderSeekCallback seek_callback,
  87424. FLAC__StreamDecoderTellCallback tell_callback,
  87425. FLAC__StreamDecoderLengthCallback length_callback,
  87426. FLAC__StreamDecoderEofCallback eof_callback,
  87427. FLAC__StreamDecoderWriteCallback write_callback,
  87428. FLAC__StreamDecoderMetadataCallback metadata_callback,
  87429. FLAC__StreamDecoderErrorCallback error_callback,
  87430. void *client_data
  87431. );
  87432. /** Initialize the decoder instance to decode Ogg FLAC streams.
  87433. *
  87434. * This flavor of initialization sets up the decoder to decode from a
  87435. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  87436. * client. For decoding from a plain file via filename or open FILE*,
  87437. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  87438. * provide a simpler interface.
  87439. *
  87440. * This function should be called after FLAC__stream_decoder_new() and
  87441. * FLAC__stream_decoder_set_*() but before any of the
  87442. * FLAC__stream_decoder_process_*() functions. Will set and return the
  87443. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  87444. * if initialization succeeded.
  87445. *
  87446. * \note Support for Ogg FLAC in the library is optional. If this
  87447. * library has been built without support for Ogg FLAC, this function
  87448. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  87449. *
  87450. * \param decoder An uninitialized decoder instance.
  87451. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  87452. * pointer must not be \c NULL.
  87453. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  87454. * pointer may be \c NULL if seeking is not
  87455. * supported. If \a seek_callback is not \c NULL then a
  87456. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  87457. * Alternatively, a dummy seek callback that just
  87458. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  87459. * may also be supplied, all though this is slightly
  87460. * less efficient for the decoder.
  87461. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  87462. * pointer may be \c NULL if not supported by the client. If
  87463. * \a seek_callback is not \c NULL then a
  87464. * \a tell_callback must also be supplied.
  87465. * Alternatively, a dummy tell callback that just
  87466. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  87467. * may also be supplied, all though this is slightly
  87468. * less efficient for the decoder.
  87469. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  87470. * pointer may be \c NULL if not supported by the client. If
  87471. * \a seek_callback is not \c NULL then a
  87472. * \a length_callback must also be supplied.
  87473. * Alternatively, a dummy length callback that just
  87474. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  87475. * may also be supplied, all though this is slightly
  87476. * less efficient for the decoder.
  87477. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  87478. * pointer may be \c NULL if not supported by the client. If
  87479. * \a seek_callback is not \c NULL then a
  87480. * \a eof_callback must also be supplied.
  87481. * Alternatively, a dummy length callback that just
  87482. * returns \c false
  87483. * may also be supplied, all though this is slightly
  87484. * less efficient for the decoder.
  87485. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  87486. * pointer must not be \c NULL.
  87487. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  87488. * pointer may be \c NULL if the callback is not
  87489. * desired.
  87490. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  87491. * pointer must not be \c NULL.
  87492. * \param client_data This value will be supplied to callbacks in their
  87493. * \a client_data argument.
  87494. * \assert
  87495. * \code decoder != NULL \endcode
  87496. * \retval FLAC__StreamDecoderInitStatus
  87497. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  87498. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  87499. */
  87500. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  87501. FLAC__StreamDecoder *decoder,
  87502. FLAC__StreamDecoderReadCallback read_callback,
  87503. FLAC__StreamDecoderSeekCallback seek_callback,
  87504. FLAC__StreamDecoderTellCallback tell_callback,
  87505. FLAC__StreamDecoderLengthCallback length_callback,
  87506. FLAC__StreamDecoderEofCallback eof_callback,
  87507. FLAC__StreamDecoderWriteCallback write_callback,
  87508. FLAC__StreamDecoderMetadataCallback metadata_callback,
  87509. FLAC__StreamDecoderErrorCallback error_callback,
  87510. void *client_data
  87511. );
  87512. /** Initialize the decoder instance to decode native FLAC files.
  87513. *
  87514. * This flavor of initialization sets up the decoder to decode from a
  87515. * plain native FLAC file. For non-stdio streams, you must use
  87516. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  87517. *
  87518. * This function should be called after FLAC__stream_decoder_new() and
  87519. * FLAC__stream_decoder_set_*() but before any of the
  87520. * FLAC__stream_decoder_process_*() functions. Will set and return the
  87521. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  87522. * if initialization succeeded.
  87523. *
  87524. * \param decoder An uninitialized decoder instance.
  87525. * \param file An open FLAC file. The file should have been
  87526. * opened with mode \c "rb" and rewound. The file
  87527. * becomes owned by the decoder and should not be
  87528. * manipulated by the client while decoding.
  87529. * Unless \a file is \c stdin, it will be closed
  87530. * when FLAC__stream_decoder_finish() is called.
  87531. * Note however that seeking will not work when
  87532. * decoding from \c stdout since it is not seekable.
  87533. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  87534. * pointer must not be \c NULL.
  87535. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  87536. * pointer may be \c NULL if the callback is not
  87537. * desired.
  87538. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  87539. * pointer must not be \c NULL.
  87540. * \param client_data This value will be supplied to callbacks in their
  87541. * \a client_data argument.
  87542. * \assert
  87543. * \code decoder != NULL \endcode
  87544. * \code file != NULL \endcode
  87545. * \retval FLAC__StreamDecoderInitStatus
  87546. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  87547. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  87548. */
  87549. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  87550. FLAC__StreamDecoder *decoder,
  87551. FILE *file,
  87552. FLAC__StreamDecoderWriteCallback write_callback,
  87553. FLAC__StreamDecoderMetadataCallback metadata_callback,
  87554. FLAC__StreamDecoderErrorCallback error_callback,
  87555. void *client_data
  87556. );
  87557. /** Initialize the decoder instance to decode Ogg FLAC files.
  87558. *
  87559. * This flavor of initialization sets up the decoder to decode from a
  87560. * plain Ogg FLAC file. For non-stdio streams, you must use
  87561. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  87562. *
  87563. * This function should be called after FLAC__stream_decoder_new() and
  87564. * FLAC__stream_decoder_set_*() but before any of the
  87565. * FLAC__stream_decoder_process_*() functions. Will set and return the
  87566. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  87567. * if initialization succeeded.
  87568. *
  87569. * \note Support for Ogg FLAC in the library is optional. If this
  87570. * library has been built without support for Ogg FLAC, this function
  87571. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  87572. *
  87573. * \param decoder An uninitialized decoder instance.
  87574. * \param file An open FLAC file. The file should have been
  87575. * opened with mode \c "rb" and rewound. The file
  87576. * becomes owned by the decoder and should not be
  87577. * manipulated by the client while decoding.
  87578. * Unless \a file is \c stdin, it will be closed
  87579. * when FLAC__stream_decoder_finish() is called.
  87580. * Note however that seeking will not work when
  87581. * decoding from \c stdout since it is not seekable.
  87582. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  87583. * pointer must not be \c NULL.
  87584. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  87585. * pointer may be \c NULL if the callback is not
  87586. * desired.
  87587. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  87588. * pointer must not be \c NULL.
  87589. * \param client_data This value will be supplied to callbacks in their
  87590. * \a client_data argument.
  87591. * \assert
  87592. * \code decoder != NULL \endcode
  87593. * \code file != NULL \endcode
  87594. * \retval FLAC__StreamDecoderInitStatus
  87595. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  87596. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  87597. */
  87598. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  87599. FLAC__StreamDecoder *decoder,
  87600. FILE *file,
  87601. FLAC__StreamDecoderWriteCallback write_callback,
  87602. FLAC__StreamDecoderMetadataCallback metadata_callback,
  87603. FLAC__StreamDecoderErrorCallback error_callback,
  87604. void *client_data
  87605. );
  87606. /** Initialize the decoder instance to decode native FLAC files.
  87607. *
  87608. * This flavor of initialization sets up the decoder to decode from a plain
  87609. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  87610. * example, with Unicode filenames on Windows), you must use
  87611. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  87612. * and provide callbacks for the I/O.
  87613. *
  87614. * This function should be called after FLAC__stream_decoder_new() and
  87615. * FLAC__stream_decoder_set_*() but before any of the
  87616. * FLAC__stream_decoder_process_*() functions. Will set and return the
  87617. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  87618. * if initialization succeeded.
  87619. *
  87620. * \param decoder An uninitialized decoder instance.
  87621. * \param filename The name of the file to decode from. The file will
  87622. * be opened with fopen(). Use \c NULL to decode from
  87623. * \c stdin. Note that \c stdin is not seekable.
  87624. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  87625. * pointer must not be \c NULL.
  87626. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  87627. * pointer may be \c NULL if the callback is not
  87628. * desired.
  87629. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  87630. * pointer must not be \c NULL.
  87631. * \param client_data This value will be supplied to callbacks in their
  87632. * \a client_data argument.
  87633. * \assert
  87634. * \code decoder != NULL \endcode
  87635. * \retval FLAC__StreamDecoderInitStatus
  87636. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  87637. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  87638. */
  87639. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  87640. FLAC__StreamDecoder *decoder,
  87641. const char *filename,
  87642. FLAC__StreamDecoderWriteCallback write_callback,
  87643. FLAC__StreamDecoderMetadataCallback metadata_callback,
  87644. FLAC__StreamDecoderErrorCallback error_callback,
  87645. void *client_data
  87646. );
  87647. /** Initialize the decoder instance to decode Ogg FLAC files.
  87648. *
  87649. * This flavor of initialization sets up the decoder to decode from a plain
  87650. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  87651. * example, with Unicode filenames on Windows), you must use
  87652. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  87653. * and provide callbacks for the I/O.
  87654. *
  87655. * This function should be called after FLAC__stream_decoder_new() and
  87656. * FLAC__stream_decoder_set_*() but before any of the
  87657. * FLAC__stream_decoder_process_*() functions. Will set and return the
  87658. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  87659. * if initialization succeeded.
  87660. *
  87661. * \note Support for Ogg FLAC in the library is optional. If this
  87662. * library has been built without support for Ogg FLAC, this function
  87663. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  87664. *
  87665. * \param decoder An uninitialized decoder instance.
  87666. * \param filename The name of the file to decode from. The file will
  87667. * be opened with fopen(). Use \c NULL to decode from
  87668. * \c stdin. Note that \c stdin is not seekable.
  87669. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  87670. * pointer must not be \c NULL.
  87671. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  87672. * pointer may be \c NULL if the callback is not
  87673. * desired.
  87674. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  87675. * pointer must not be \c NULL.
  87676. * \param client_data This value will be supplied to callbacks in their
  87677. * \a client_data argument.
  87678. * \assert
  87679. * \code decoder != NULL \endcode
  87680. * \retval FLAC__StreamDecoderInitStatus
  87681. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  87682. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  87683. */
  87684. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  87685. FLAC__StreamDecoder *decoder,
  87686. const char *filename,
  87687. FLAC__StreamDecoderWriteCallback write_callback,
  87688. FLAC__StreamDecoderMetadataCallback metadata_callback,
  87689. FLAC__StreamDecoderErrorCallback error_callback,
  87690. void *client_data
  87691. );
  87692. /** Finish the decoding process.
  87693. * Flushes the decoding buffer, releases resources, resets the decoder
  87694. * settings to their defaults, and returns the decoder state to
  87695. * FLAC__STREAM_DECODER_UNINITIALIZED.
  87696. *
  87697. * In the event of a prematurely-terminated decode, it is not strictly
  87698. * necessary to call this immediately before FLAC__stream_decoder_delete()
  87699. * but it is good practice to match every FLAC__stream_decoder_init_*()
  87700. * with a FLAC__stream_decoder_finish().
  87701. *
  87702. * \param decoder An uninitialized decoder instance.
  87703. * \assert
  87704. * \code decoder != NULL \endcode
  87705. * \retval FLAC__bool
  87706. * \c false if MD5 checking is on AND a STREAMINFO block was available
  87707. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  87708. * signature does not match the one computed by the decoder; else
  87709. * \c true.
  87710. */
  87711. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  87712. /** Flush the stream input.
  87713. * The decoder's input buffer will be cleared and the state set to
  87714. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  87715. * off MD5 checking.
  87716. *
  87717. * \param decoder A decoder instance.
  87718. * \assert
  87719. * \code decoder != NULL \endcode
  87720. * \retval FLAC__bool
  87721. * \c true if successful, else \c false if a memory allocation
  87722. * error occurs (in which case the state will be set to
  87723. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  87724. */
  87725. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  87726. /** Reset the decoding process.
  87727. * The decoder's input buffer will be cleared and the state set to
  87728. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  87729. * FLAC__stream_decoder_finish() except that the settings are
  87730. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  87731. * before decoding again. MD5 checking will be restored to its original
  87732. * setting.
  87733. *
  87734. * If the decoder is seekable, or was initialized with
  87735. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  87736. * the decoder will also attempt to seek to the beginning of the file.
  87737. * If this rewind fails, this function will return \c false. It follows
  87738. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  87739. * \c stdin.
  87740. *
  87741. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  87742. * and is not seekable (i.e. no seek callback was provided or the seek
  87743. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  87744. * is the duty of the client to start feeding data from the beginning of
  87745. * the stream on the next FLAC__stream_decoder_process() or
  87746. * FLAC__stream_decoder_process_interleaved() call.
  87747. *
  87748. * \param decoder A decoder instance.
  87749. * \assert
  87750. * \code decoder != NULL \endcode
  87751. * \retval FLAC__bool
  87752. * \c true if successful, else \c false if a memory allocation occurs
  87753. * (in which case the state will be set to
  87754. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  87755. * occurs (the state will be unchanged).
  87756. */
  87757. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  87758. /** Decode one metadata block or audio frame.
  87759. * This version instructs the decoder to decode a either a single metadata
  87760. * block or a single frame and stop, unless the callbacks return a fatal
  87761. * error or the read callback returns
  87762. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  87763. *
  87764. * As the decoder needs more input it will call the read callback.
  87765. * Depending on what was decoded, the metadata or write callback will be
  87766. * called with the decoded metadata block or audio frame.
  87767. *
  87768. * Unless there is a fatal read error or end of stream, this function
  87769. * will return once one whole frame is decoded. In other words, if the
  87770. * stream is not synchronized or points to a corrupt frame header, the
  87771. * decoder will continue to try and resync until it gets to a valid
  87772. * frame, then decode one frame, then return. If the decoder points to
  87773. * a frame whose frame CRC in the frame footer does not match the
  87774. * computed frame CRC, this function will issue a
  87775. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  87776. * error callback, and return, having decoded one complete, although
  87777. * corrupt, frame. (Such corrupted frames are sent as silence of the
  87778. * correct length to the write callback.)
  87779. *
  87780. * \param decoder An initialized decoder instance.
  87781. * \assert
  87782. * \code decoder != NULL \endcode
  87783. * \retval FLAC__bool
  87784. * \c false if any fatal read, write, or memory allocation error
  87785. * occurred (meaning decoding must stop), else \c true; for more
  87786. * information about the decoder, check the decoder state with
  87787. * FLAC__stream_decoder_get_state().
  87788. */
  87789. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  87790. /** Decode until the end of the metadata.
  87791. * This version instructs the decoder to decode from the current position
  87792. * and continue until all the metadata has been read, or until the
  87793. * callbacks return a fatal error or the read callback returns
  87794. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  87795. *
  87796. * As the decoder needs more input it will call the read callback.
  87797. * As each metadata block is decoded, the metadata callback will be called
  87798. * with the decoded metadata.
  87799. *
  87800. * \param decoder An initialized decoder instance.
  87801. * \assert
  87802. * \code decoder != NULL \endcode
  87803. * \retval FLAC__bool
  87804. * \c false if any fatal read, write, or memory allocation error
  87805. * occurred (meaning decoding must stop), else \c true; for more
  87806. * information about the decoder, check the decoder state with
  87807. * FLAC__stream_decoder_get_state().
  87808. */
  87809. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  87810. /** Decode until the end of the stream.
  87811. * This version instructs the decoder to decode from the current position
  87812. * and continue until the end of stream (the read callback returns
  87813. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  87814. * callbacks return a fatal error.
  87815. *
  87816. * As the decoder needs more input it will call the read callback.
  87817. * As each metadata block and frame is decoded, the metadata or write
  87818. * callback will be called with the decoded metadata or frame.
  87819. *
  87820. * \param decoder An initialized decoder instance.
  87821. * \assert
  87822. * \code decoder != NULL \endcode
  87823. * \retval FLAC__bool
  87824. * \c false if any fatal read, write, or memory allocation error
  87825. * occurred (meaning decoding must stop), else \c true; for more
  87826. * information about the decoder, check the decoder state with
  87827. * FLAC__stream_decoder_get_state().
  87828. */
  87829. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  87830. /** Skip one audio frame.
  87831. * This version instructs the decoder to 'skip' a single frame and stop,
  87832. * unless the callbacks return a fatal error or the read callback returns
  87833. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  87834. *
  87835. * The decoding flow is the same as what occurs when
  87836. * FLAC__stream_decoder_process_single() is called to process an audio
  87837. * frame, except that this function does not decode the parsed data into
  87838. * PCM or call the write callback. The integrity of the frame is still
  87839. * checked the same way as in the other process functions.
  87840. *
  87841. * This function will return once one whole frame is skipped, in the
  87842. * same way that FLAC__stream_decoder_process_single() will return once
  87843. * one whole frame is decoded.
  87844. *
  87845. * This function can be used in more quickly determining FLAC frame
  87846. * boundaries when decoding of the actual data is not needed, for
  87847. * example when an application is separating a FLAC stream into frames
  87848. * for editing or storing in a container. To do this, the application
  87849. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  87850. * to the next frame, then use
  87851. * FLAC__stream_decoder_get_decode_position() to find the new frame
  87852. * boundary.
  87853. *
  87854. * This function should only be called when the stream has advanced
  87855. * past all the metadata, otherwise it will return \c false.
  87856. *
  87857. * \param decoder An initialized decoder instance not in a metadata
  87858. * state.
  87859. * \assert
  87860. * \code decoder != NULL \endcode
  87861. * \retval FLAC__bool
  87862. * \c false if any fatal read, write, or memory allocation error
  87863. * occurred (meaning decoding must stop), or if the decoder
  87864. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  87865. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  87866. * information about the decoder, check the decoder state with
  87867. * FLAC__stream_decoder_get_state().
  87868. */
  87869. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  87870. /** Flush the input and seek to an absolute sample.
  87871. * Decoding will resume at the given sample. Note that because of
  87872. * this, the next write callback may contain a partial block. The
  87873. * client must support seeking the input or this function will fail
  87874. * and return \c false. Furthermore, if the decoder state is
  87875. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  87876. * with FLAC__stream_decoder_flush() or reset with
  87877. * FLAC__stream_decoder_reset() before decoding can continue.
  87878. *
  87879. * \param decoder A decoder instance.
  87880. * \param sample The target sample number to seek to.
  87881. * \assert
  87882. * \code decoder != NULL \endcode
  87883. * \retval FLAC__bool
  87884. * \c true if successful, else \c false.
  87885. */
  87886. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  87887. /* \} */
  87888. #ifdef __cplusplus
  87889. }
  87890. #endif
  87891. #endif
  87892. /*** End of inlined file: stream_decoder.h ***/
  87893. /*** Start of inlined file: stream_encoder.h ***/
  87894. #ifndef FLAC__STREAM_ENCODER_H
  87895. #define FLAC__STREAM_ENCODER_H
  87896. #include <stdio.h> /* for FILE */
  87897. #ifdef __cplusplus
  87898. extern "C" {
  87899. #endif
  87900. /** \file include/FLAC/stream_encoder.h
  87901. *
  87902. * \brief
  87903. * This module contains the functions which implement the stream
  87904. * encoder.
  87905. *
  87906. * See the detailed documentation in the
  87907. * \link flac_stream_encoder stream encoder \endlink module.
  87908. */
  87909. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  87910. * \ingroup flac
  87911. *
  87912. * \brief
  87913. * This module describes the encoder layers provided by libFLAC.
  87914. *
  87915. * The stream encoder can be used to encode complete streams either to the
  87916. * client via callbacks, or directly to a file, depending on how it is
  87917. * initialized. When encoding via callbacks, the client provides a write
  87918. * callback which will be called whenever FLAC data is ready to be written.
  87919. * If the client also supplies a seek callback, the encoder will also
  87920. * automatically handle the writing back of metadata discovered while
  87921. * encoding, like stream info, seek points offsets, etc. When encoding to
  87922. * a file, the client needs only supply a filename or open \c FILE* and an
  87923. * optional progress callback for periodic notification of progress; the
  87924. * write and seek callbacks are supplied internally. For more info see the
  87925. * \link flac_stream_encoder stream encoder \endlink module.
  87926. */
  87927. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  87928. * \ingroup flac_encoder
  87929. *
  87930. * \brief
  87931. * This module contains the functions which implement the stream
  87932. * encoder.
  87933. *
  87934. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  87935. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  87936. *
  87937. * The basic usage of this encoder is as follows:
  87938. * - The program creates an instance of an encoder using
  87939. * FLAC__stream_encoder_new().
  87940. * - The program overrides the default settings using
  87941. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  87942. * functions should be called:
  87943. * - FLAC__stream_encoder_set_channels()
  87944. * - FLAC__stream_encoder_set_bits_per_sample()
  87945. * - FLAC__stream_encoder_set_sample_rate()
  87946. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  87947. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  87948. * - If the application wants to control the compression level or set its own
  87949. * metadata, then the following should also be called:
  87950. * - FLAC__stream_encoder_set_compression_level()
  87951. * - FLAC__stream_encoder_set_verify()
  87952. * - FLAC__stream_encoder_set_metadata()
  87953. * - The rest of the set functions should only be called if the client needs
  87954. * exact control over how the audio is compressed; thorough understanding
  87955. * of the FLAC format is necessary to achieve good results.
  87956. * - The program initializes the instance to validate the settings and
  87957. * prepare for encoding using
  87958. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  87959. * or FLAC__stream_encoder_init_file() for native FLAC
  87960. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  87961. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  87962. * - The program calls FLAC__stream_encoder_process() or
  87963. * FLAC__stream_encoder_process_interleaved() to encode data, which
  87964. * subsequently calls the callbacks when there is encoder data ready
  87965. * to be written.
  87966. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  87967. * which causes the encoder to encode any data still in its input pipe,
  87968. * update the metadata with the final encoding statistics if output
  87969. * seeking is possible, and finally reset the encoder to the
  87970. * uninitialized state.
  87971. * - The instance may be used again or deleted with
  87972. * FLAC__stream_encoder_delete().
  87973. *
  87974. * In more detail, the stream encoder functions similarly to the
  87975. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  87976. * callbacks and more options. Typically the client will create a new
  87977. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  87978. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  87979. * calling one of the FLAC__stream_encoder_init_*() functions.
  87980. *
  87981. * Unlike the decoders, the stream encoder has many options that can
  87982. * affect the speed and compression ratio. When setting these parameters
  87983. * you should have some basic knowledge of the format (see the
  87984. * <A HREF="../documentation.html#format">user-level documentation</A>
  87985. * or the <A HREF="../format.html">formal description</A>). The
  87986. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  87987. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  87988. * functions will do this, so make sure to pay attention to the state
  87989. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  87990. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  87991. * before FLAC__stream_encoder_init_*() will take on the defaults from
  87992. * the constructor.
  87993. *
  87994. * There are three initialization functions for native FLAC, one for
  87995. * setting up the encoder to encode FLAC data to the client via
  87996. * callbacks, and two for encoding directly to a file.
  87997. *
  87998. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  87999. * You must also supply a write callback which will be called anytime
  88000. * there is raw encoded data to write. If the client can seek the output
  88001. * it is best to also supply seek and tell callbacks, as this allows the
  88002. * encoder to go back after encoding is finished to write back
  88003. * information that was collected while encoding, like seek point offsets,
  88004. * frame sizes, etc.
  88005. *
  88006. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  88007. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  88008. * filename or open \c FILE*; the encoder will handle all the callbacks
  88009. * internally. You may also supply a progress callback for periodic
  88010. * notification of the encoding progress.
  88011. *
  88012. * There are three similarly-named init functions for encoding to Ogg
  88013. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  88014. * library has been built with Ogg support.
  88015. *
  88016. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  88017. * call the write callback several times, once with the \c fLaC signature,
  88018. * and once for each encoded metadata block. Note that for Ogg FLAC
  88019. * encoding you will usually get at least twice the number of callbacks than
  88020. * with native FLAC, one for the Ogg page header and one for the page body.
  88021. *
  88022. * After initializing the instance, the client may feed audio data to the
  88023. * encoder in one of two ways:
  88024. *
  88025. * - Channel separate, through FLAC__stream_encoder_process() - The client
  88026. * will pass an array of pointers to buffers, one for each channel, to
  88027. * the encoder, each of the same length. The samples need not be
  88028. * block-aligned, but each channel should have the same number of samples.
  88029. * - Channel interleaved, through
  88030. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  88031. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  88032. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  88033. * Again, the samples need not be block-aligned but they must be
  88034. * sample-aligned, i.e. the first value should be channel0_sample0 and
  88035. * the last value channelN_sampleM.
  88036. *
  88037. * Note that for either process call, each sample in the buffers should be a
  88038. * signed integer, right-justified to the resolution set by
  88039. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  88040. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  88041. *
  88042. * When the client is finished encoding data, it calls
  88043. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  88044. * data still in its input pipe, and call the metadata callback with the
  88045. * final encoding statistics. Then the instance may be deleted with
  88046. * FLAC__stream_encoder_delete() or initialized again to encode another
  88047. * stream.
  88048. *
  88049. * For programs that write their own metadata, but that do not know the
  88050. * actual metadata until after encoding, it is advantageous to instruct
  88051. * the encoder to write a PADDING block of the correct size, so that
  88052. * instead of rewriting the whole stream after encoding, the program can
  88053. * just overwrite the PADDING block. If only the maximum size of the
  88054. * metadata is known, the program can write a slightly larger padding
  88055. * block, then split it after encoding.
  88056. *
  88057. * Make sure you understand how lengths are calculated. All FLAC metadata
  88058. * blocks have a 4 byte header which contains the type and length. This
  88059. * length does not include the 4 bytes of the header. See the format page
  88060. * for the specification of metadata blocks and their lengths.
  88061. *
  88062. * \note
  88063. * If you are writing the FLAC data to a file via callbacks, make sure it
  88064. * is open for update (e.g. mode "w+" for stdio streams). This is because
  88065. * after the first encoding pass, the encoder will try to seek back to the
  88066. * beginning of the stream, to the STREAMINFO block, to write some data
  88067. * there. (If using FLAC__stream_encoder_init*_file() or
  88068. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  88069. *
  88070. * \note
  88071. * The "set" functions may only be called when the encoder is in the
  88072. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  88073. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  88074. * before FLAC__stream_encoder_init_*(). If this is the case they will
  88075. * return \c true, otherwise \c false.
  88076. *
  88077. * \note
  88078. * FLAC__stream_encoder_finish() resets all settings to the constructor
  88079. * defaults.
  88080. *
  88081. * \{
  88082. */
  88083. /** State values for a FLAC__StreamEncoder.
  88084. *
  88085. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  88086. *
  88087. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  88088. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  88089. * must be deleted with FLAC__stream_encoder_delete().
  88090. */
  88091. typedef enum {
  88092. FLAC__STREAM_ENCODER_OK = 0,
  88093. /**< The encoder is in the normal OK state and samples can be processed. */
  88094. FLAC__STREAM_ENCODER_UNINITIALIZED,
  88095. /**< The encoder is in the uninitialized state; one of the
  88096. * FLAC__stream_encoder_init_*() functions must be called before samples
  88097. * can be processed.
  88098. */
  88099. FLAC__STREAM_ENCODER_OGG_ERROR,
  88100. /**< An error occurred in the underlying Ogg layer. */
  88101. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  88102. /**< An error occurred in the underlying verify stream decoder;
  88103. * check FLAC__stream_encoder_get_verify_decoder_state().
  88104. */
  88105. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  88106. /**< The verify decoder detected a mismatch between the original
  88107. * audio signal and the decoded audio signal.
  88108. */
  88109. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  88110. /**< One of the callbacks returned a fatal error. */
  88111. FLAC__STREAM_ENCODER_IO_ERROR,
  88112. /**< An I/O error occurred while opening/reading/writing a file.
  88113. * Check \c errno.
  88114. */
  88115. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  88116. /**< An error occurred while writing the stream; usually, the
  88117. * write_callback returned an error.
  88118. */
  88119. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  88120. /**< Memory allocation failed. */
  88121. } FLAC__StreamEncoderState;
  88122. /** Maps a FLAC__StreamEncoderState to a C string.
  88123. *
  88124. * Using a FLAC__StreamEncoderState as the index to this array
  88125. * will give the string equivalent. The contents should not be modified.
  88126. */
  88127. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  88128. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  88129. */
  88130. typedef enum {
  88131. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  88132. /**< Initialization was successful. */
  88133. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  88134. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  88135. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  88136. /**< The library was not compiled with support for the given container
  88137. * format.
  88138. */
  88139. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  88140. /**< A required callback was not supplied. */
  88141. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  88142. /**< The encoder has an invalid setting for number of channels. */
  88143. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  88144. /**< The encoder has an invalid setting for bits-per-sample.
  88145. * FLAC supports 4-32 bps but the reference encoder currently supports
  88146. * only up to 24 bps.
  88147. */
  88148. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  88149. /**< The encoder has an invalid setting for the input sample rate. */
  88150. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  88151. /**< The encoder has an invalid setting for the block size. */
  88152. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  88153. /**< The encoder has an invalid setting for the maximum LPC order. */
  88154. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  88155. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  88156. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  88157. /**< The specified block size is less than the maximum LPC order. */
  88158. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  88159. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  88160. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  88161. /**< The metadata input to the encoder is invalid, in one of the following ways:
  88162. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  88163. * - One of the metadata blocks contains an undefined type
  88164. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  88165. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  88166. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  88167. */
  88168. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  88169. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  88170. * already initialized, usually because
  88171. * FLAC__stream_encoder_finish() was not called.
  88172. */
  88173. } FLAC__StreamEncoderInitStatus;
  88174. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  88175. *
  88176. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  88177. * will give the string equivalent. The contents should not be modified.
  88178. */
  88179. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  88180. /** Return values for the FLAC__StreamEncoder read callback.
  88181. */
  88182. typedef enum {
  88183. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  88184. /**< The read was OK and decoding can continue. */
  88185. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  88186. /**< The read was attempted at the end of the stream. */
  88187. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  88188. /**< An unrecoverable error occurred. */
  88189. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  88190. /**< Client does not support reading back from the output. */
  88191. } FLAC__StreamEncoderReadStatus;
  88192. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  88193. *
  88194. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  88195. * will give the string equivalent. The contents should not be modified.
  88196. */
  88197. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  88198. /** Return values for the FLAC__StreamEncoder write callback.
  88199. */
  88200. typedef enum {
  88201. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  88202. /**< The write was OK and encoding can continue. */
  88203. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  88204. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  88205. } FLAC__StreamEncoderWriteStatus;
  88206. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  88207. *
  88208. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  88209. * will give the string equivalent. The contents should not be modified.
  88210. */
  88211. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  88212. /** Return values for the FLAC__StreamEncoder seek callback.
  88213. */
  88214. typedef enum {
  88215. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  88216. /**< The seek was OK and encoding can continue. */
  88217. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  88218. /**< An unrecoverable error occurred. */
  88219. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  88220. /**< Client does not support seeking. */
  88221. } FLAC__StreamEncoderSeekStatus;
  88222. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  88223. *
  88224. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  88225. * will give the string equivalent. The contents should not be modified.
  88226. */
  88227. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  88228. /** Return values for the FLAC__StreamEncoder tell callback.
  88229. */
  88230. typedef enum {
  88231. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  88232. /**< The tell was OK and encoding can continue. */
  88233. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  88234. /**< An unrecoverable error occurred. */
  88235. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  88236. /**< Client does not support seeking. */
  88237. } FLAC__StreamEncoderTellStatus;
  88238. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  88239. *
  88240. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  88241. * will give the string equivalent. The contents should not be modified.
  88242. */
  88243. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  88244. /***********************************************************************
  88245. *
  88246. * class FLAC__StreamEncoder
  88247. *
  88248. ***********************************************************************/
  88249. struct FLAC__StreamEncoderProtected;
  88250. struct FLAC__StreamEncoderPrivate;
  88251. /** The opaque structure definition for the stream encoder type.
  88252. * See the \link flac_stream_encoder stream encoder module \endlink
  88253. * for a detailed description.
  88254. */
  88255. typedef struct {
  88256. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  88257. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  88258. } FLAC__StreamEncoder;
  88259. /** Signature for the read callback.
  88260. *
  88261. * A function pointer matching this signature must be passed to
  88262. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  88263. * The supplied function will be called when the encoder needs to read back
  88264. * encoded data. This happens during the metadata callback, when the encoder
  88265. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  88266. * while encoding. The address of the buffer to be filled is supplied, along
  88267. * with the number of bytes the buffer can hold. The callback may choose to
  88268. * supply less data and modify the byte count but must be careful not to
  88269. * overflow the buffer. The callback then returns a status code chosen from
  88270. * FLAC__StreamEncoderReadStatus.
  88271. *
  88272. * Here is an example of a read callback for stdio streams:
  88273. * \code
  88274. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  88275. * {
  88276. * FILE *file = ((MyClientData*)client_data)->file;
  88277. * if(*bytes > 0) {
  88278. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  88279. * if(ferror(file))
  88280. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  88281. * else if(*bytes == 0)
  88282. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  88283. * else
  88284. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  88285. * }
  88286. * else
  88287. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  88288. * }
  88289. * \endcode
  88290. *
  88291. * \note In general, FLAC__StreamEncoder functions which change the
  88292. * state should not be called on the \a encoder while in the callback.
  88293. *
  88294. * \param encoder The encoder instance calling the callback.
  88295. * \param buffer A pointer to a location for the callee to store
  88296. * data to be encoded.
  88297. * \param bytes A pointer to the size of the buffer. On entry
  88298. * to the callback, it contains the maximum number
  88299. * of bytes that may be stored in \a buffer. The
  88300. * callee must set it to the actual number of bytes
  88301. * stored (0 in case of error or end-of-stream) before
  88302. * returning.
  88303. * \param client_data The callee's client data set through
  88304. * FLAC__stream_encoder_set_client_data().
  88305. * \retval FLAC__StreamEncoderReadStatus
  88306. * The callee's return status.
  88307. */
  88308. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  88309. /** Signature for the write callback.
  88310. *
  88311. * A function pointer matching this signature must be passed to
  88312. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  88313. * by the encoder anytime there is raw encoded data ready to write. It may
  88314. * include metadata mixed with encoded audio frames and the data is not
  88315. * guaranteed to be aligned on frame or metadata block boundaries.
  88316. *
  88317. * The only duty of the callback is to write out the \a bytes worth of data
  88318. * in \a buffer to the current position in the output stream. The arguments
  88319. * \a samples and \a current_frame are purely informational. If \a samples
  88320. * is greater than \c 0, then \a current_frame will hold the current frame
  88321. * number that is being written; otherwise it indicates that the write
  88322. * callback is being called to write metadata.
  88323. *
  88324. * \note
  88325. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  88326. * write callback will be called twice when writing each audio
  88327. * frame; once for the page header, and once for the page body.
  88328. * When writing the page header, the \a samples argument to the
  88329. * write callback will be \c 0.
  88330. *
  88331. * \note In general, FLAC__StreamEncoder functions which change the
  88332. * state should not be called on the \a encoder while in the callback.
  88333. *
  88334. * \param encoder The encoder instance calling the callback.
  88335. * \param buffer An array of encoded data of length \a bytes.
  88336. * \param bytes The byte length of \a buffer.
  88337. * \param samples The number of samples encoded by \a buffer.
  88338. * \c 0 has a special meaning; see above.
  88339. * \param current_frame The number of the current frame being encoded.
  88340. * \param client_data The callee's client data set through
  88341. * FLAC__stream_encoder_init_*().
  88342. * \retval FLAC__StreamEncoderWriteStatus
  88343. * The callee's return status.
  88344. */
  88345. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  88346. /** Signature for the seek callback.
  88347. *
  88348. * A function pointer matching this signature may be passed to
  88349. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  88350. * when the encoder needs to seek the output stream. The encoder will pass
  88351. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  88352. *
  88353. * Here is an example of a seek callback for stdio streams:
  88354. * \code
  88355. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  88356. * {
  88357. * FILE *file = ((MyClientData*)client_data)->file;
  88358. * if(file == stdin)
  88359. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  88360. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  88361. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  88362. * else
  88363. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  88364. * }
  88365. * \endcode
  88366. *
  88367. * \note In general, FLAC__StreamEncoder functions which change the
  88368. * state should not be called on the \a encoder while in the callback.
  88369. *
  88370. * \param encoder The encoder instance calling the callback.
  88371. * \param absolute_byte_offset The offset from the beginning of the stream
  88372. * to seek to.
  88373. * \param client_data The callee's client data set through
  88374. * FLAC__stream_encoder_init_*().
  88375. * \retval FLAC__StreamEncoderSeekStatus
  88376. * The callee's return status.
  88377. */
  88378. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  88379. /** Signature for the tell callback.
  88380. *
  88381. * A function pointer matching this signature may be passed to
  88382. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  88383. * when the encoder needs to know the current position of the output stream.
  88384. *
  88385. * \warning
  88386. * The callback must return the true current byte offset of the output to
  88387. * which the encoder is writing. If you are buffering the output, make
  88388. * sure and take this into account. If you are writing directly to a
  88389. * FILE* from your write callback, ftell() is sufficient. If you are
  88390. * writing directly to a file descriptor from your write callback, you
  88391. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  88392. * these points to rewrite metadata after encoding.
  88393. *
  88394. * Here is an example of a tell callback for stdio streams:
  88395. * \code
  88396. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  88397. * {
  88398. * FILE *file = ((MyClientData*)client_data)->file;
  88399. * off_t pos;
  88400. * if(file == stdin)
  88401. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  88402. * else if((pos = ftello(file)) < 0)
  88403. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  88404. * else {
  88405. * *absolute_byte_offset = (FLAC__uint64)pos;
  88406. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  88407. * }
  88408. * }
  88409. * \endcode
  88410. *
  88411. * \note In general, FLAC__StreamEncoder functions which change the
  88412. * state should not be called on the \a encoder while in the callback.
  88413. *
  88414. * \param encoder The encoder instance calling the callback.
  88415. * \param absolute_byte_offset The address at which to store the current
  88416. * position of the output.
  88417. * \param client_data The callee's client data set through
  88418. * FLAC__stream_encoder_init_*().
  88419. * \retval FLAC__StreamEncoderTellStatus
  88420. * The callee's return status.
  88421. */
  88422. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  88423. /** Signature for the metadata callback.
  88424. *
  88425. * A function pointer matching this signature may be passed to
  88426. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  88427. * once at the end of encoding with the populated STREAMINFO structure. This
  88428. * is so the client can seek back to the beginning of the file and write the
  88429. * STREAMINFO block with the correct statistics after encoding (like
  88430. * minimum/maximum frame size and total samples).
  88431. *
  88432. * \note In general, FLAC__StreamEncoder functions which change the
  88433. * state should not be called on the \a encoder while in the callback.
  88434. *
  88435. * \param encoder The encoder instance calling the callback.
  88436. * \param metadata The final populated STREAMINFO block.
  88437. * \param client_data The callee's client data set through
  88438. * FLAC__stream_encoder_init_*().
  88439. */
  88440. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  88441. /** Signature for the progress callback.
  88442. *
  88443. * A function pointer matching this signature may be passed to
  88444. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  88445. * The supplied function will be called when the encoder has finished
  88446. * writing a frame. The \c total_frames_estimate argument to the
  88447. * callback will be based on the value from
  88448. * FLAC__stream_encoder_set_total_samples_estimate().
  88449. *
  88450. * \note In general, FLAC__StreamEncoder functions which change the
  88451. * state should not be called on the \a encoder while in the callback.
  88452. *
  88453. * \param encoder The encoder instance calling the callback.
  88454. * \param bytes_written Bytes written so far.
  88455. * \param samples_written Samples written so far.
  88456. * \param frames_written Frames written so far.
  88457. * \param total_frames_estimate The estimate of the total number of
  88458. * frames to be written.
  88459. * \param client_data The callee's client data set through
  88460. * FLAC__stream_encoder_init_*().
  88461. */
  88462. 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);
  88463. /***********************************************************************
  88464. *
  88465. * Class constructor/destructor
  88466. *
  88467. ***********************************************************************/
  88468. /** Create a new stream encoder instance. The instance is created with
  88469. * default settings; see the individual FLAC__stream_encoder_set_*()
  88470. * functions for each setting's default.
  88471. *
  88472. * \retval FLAC__StreamEncoder*
  88473. * \c NULL if there was an error allocating memory, else the new instance.
  88474. */
  88475. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  88476. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  88477. *
  88478. * \param encoder A pointer to an existing encoder.
  88479. * \assert
  88480. * \code encoder != NULL \endcode
  88481. */
  88482. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  88483. /***********************************************************************
  88484. *
  88485. * Public class method prototypes
  88486. *
  88487. ***********************************************************************/
  88488. /** Set the serial number for the FLAC stream to use in the Ogg container.
  88489. *
  88490. * \note
  88491. * This does not need to be set for native FLAC encoding.
  88492. *
  88493. * \note
  88494. * It is recommended to set a serial number explicitly as the default of '0'
  88495. * may collide with other streams.
  88496. *
  88497. * \default \c 0
  88498. * \param encoder An encoder instance to set.
  88499. * \param serial_number See above.
  88500. * \assert
  88501. * \code encoder != NULL \endcode
  88502. * \retval FLAC__bool
  88503. * \c false if the encoder is already initialized, else \c true.
  88504. */
  88505. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  88506. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  88507. * encoded output by feeding it through an internal decoder and comparing
  88508. * the original signal against the decoded signal. If a mismatch occurs,
  88509. * the process call will return \c false. Note that this will slow the
  88510. * encoding process by the extra time required for decoding and comparison.
  88511. *
  88512. * \default \c false
  88513. * \param encoder An encoder instance to set.
  88514. * \param value Flag value (see above).
  88515. * \assert
  88516. * \code encoder != NULL \endcode
  88517. * \retval FLAC__bool
  88518. * \c false if the encoder is already initialized, else \c true.
  88519. */
  88520. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  88521. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  88522. * the encoder will comply with the Subset and will check the
  88523. * settings during FLAC__stream_encoder_init_*() to see if all settings
  88524. * comply. If \c false, the settings may take advantage of the full
  88525. * range that the format allows.
  88526. *
  88527. * Make sure you know what it entails before setting this to \c false.
  88528. *
  88529. * \default \c true
  88530. * \param encoder An encoder instance to set.
  88531. * \param value Flag value (see above).
  88532. * \assert
  88533. * \code encoder != NULL \endcode
  88534. * \retval FLAC__bool
  88535. * \c false if the encoder is already initialized, else \c true.
  88536. */
  88537. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  88538. /** Set the number of channels to be encoded.
  88539. *
  88540. * \default \c 2
  88541. * \param encoder An encoder instance to set.
  88542. * \param value See above.
  88543. * \assert
  88544. * \code encoder != NULL \endcode
  88545. * \retval FLAC__bool
  88546. * \c false if the encoder is already initialized, else \c true.
  88547. */
  88548. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  88549. /** Set the sample resolution of the input to be encoded.
  88550. *
  88551. * \warning
  88552. * Do not feed the encoder data that is wider than the value you
  88553. * set here or you will generate an invalid stream.
  88554. *
  88555. * \default \c 16
  88556. * \param encoder An encoder instance to set.
  88557. * \param value See above.
  88558. * \assert
  88559. * \code encoder != NULL \endcode
  88560. * \retval FLAC__bool
  88561. * \c false if the encoder is already initialized, else \c true.
  88562. */
  88563. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  88564. /** Set the sample rate (in Hz) of the input to be encoded.
  88565. *
  88566. * \default \c 44100
  88567. * \param encoder An encoder instance to set.
  88568. * \param value See above.
  88569. * \assert
  88570. * \code encoder != NULL \endcode
  88571. * \retval FLAC__bool
  88572. * \c false if the encoder is already initialized, else \c true.
  88573. */
  88574. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  88575. /** Set the compression level
  88576. *
  88577. * The compression level is roughly proportional to the amount of effort
  88578. * the encoder expends to compress the file. A higher level usually
  88579. * means more computation but higher compression. The default level is
  88580. * suitable for most applications.
  88581. *
  88582. * Currently the levels range from \c 0 (fastest, least compression) to
  88583. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  88584. * treated as \c 8.
  88585. *
  88586. * This function automatically calls the following other \c _set_
  88587. * functions with appropriate values, so the client does not need to
  88588. * unless it specifically wants to override them:
  88589. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  88590. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  88591. * - FLAC__stream_encoder_set_apodization()
  88592. * - FLAC__stream_encoder_set_max_lpc_order()
  88593. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  88594. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  88595. * - FLAC__stream_encoder_set_do_escape_coding()
  88596. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  88597. * - FLAC__stream_encoder_set_min_residual_partition_order()
  88598. * - FLAC__stream_encoder_set_max_residual_partition_order()
  88599. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  88600. *
  88601. * The actual values set for each level are:
  88602. * <table>
  88603. * <tr>
  88604. * <td><b>level</b><td>
  88605. * <td>do mid-side stereo<td>
  88606. * <td>loose mid-side stereo<td>
  88607. * <td>apodization<td>
  88608. * <td>max lpc order<td>
  88609. * <td>qlp coeff precision<td>
  88610. * <td>qlp coeff prec search<td>
  88611. * <td>escape coding<td>
  88612. * <td>exhaustive model search<td>
  88613. * <td>min residual partition order<td>
  88614. * <td>max residual partition order<td>
  88615. * <td>rice parameter search dist<td>
  88616. * </tr>
  88617. * <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>
  88618. * <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>
  88619. * <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>
  88620. * <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>
  88621. * <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>
  88622. * <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>
  88623. * <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>
  88624. * <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>
  88625. * <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>
  88626. * </table>
  88627. *
  88628. * \default \c 5
  88629. * \param encoder An encoder instance to set.
  88630. * \param value See above.
  88631. * \assert
  88632. * \code encoder != NULL \endcode
  88633. * \retval FLAC__bool
  88634. * \c false if the encoder is already initialized, else \c true.
  88635. */
  88636. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  88637. /** Set the blocksize to use while encoding.
  88638. *
  88639. * The number of samples to use per frame. Use \c 0 to let the encoder
  88640. * estimate a blocksize; this is usually best.
  88641. *
  88642. * \default \c 0
  88643. * \param encoder An encoder instance to set.
  88644. * \param value See above.
  88645. * \assert
  88646. * \code encoder != NULL \endcode
  88647. * \retval FLAC__bool
  88648. * \c false if the encoder is already initialized, else \c true.
  88649. */
  88650. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  88651. /** Set to \c true to enable mid-side encoding on stereo input. The
  88652. * number of channels must be 2 for this to have any effect. Set to
  88653. * \c false to use only independent channel coding.
  88654. *
  88655. * \default \c false
  88656. * \param encoder An encoder instance to set.
  88657. * \param value Flag value (see above).
  88658. * \assert
  88659. * \code encoder != NULL \endcode
  88660. * \retval FLAC__bool
  88661. * \c false if the encoder is already initialized, else \c true.
  88662. */
  88663. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  88664. /** Set to \c true to enable adaptive switching between mid-side and
  88665. * left-right encoding on stereo input. Set to \c false to use
  88666. * exhaustive searching. Setting this to \c true requires
  88667. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  88668. * \c true in order to have any effect.
  88669. *
  88670. * \default \c false
  88671. * \param encoder An encoder instance to set.
  88672. * \param value Flag value (see above).
  88673. * \assert
  88674. * \code encoder != NULL \endcode
  88675. * \retval FLAC__bool
  88676. * \c false if the encoder is already initialized, else \c true.
  88677. */
  88678. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  88679. /** Sets the apodization function(s) the encoder will use when windowing
  88680. * audio data for LPC analysis.
  88681. *
  88682. * The \a specification is a plain ASCII string which specifies exactly
  88683. * which functions to use. There may be more than one (up to 32),
  88684. * separated by \c ';' characters. Some functions take one or more
  88685. * comma-separated arguments in parentheses.
  88686. *
  88687. * The available functions are \c bartlett, \c bartlett_hann,
  88688. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  88689. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  88690. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  88691. *
  88692. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  88693. * (0<STDDEV<=0.5).
  88694. *
  88695. * For \c tukey(P), P specifies the fraction of the window that is
  88696. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  88697. * corresponds to \c hann.
  88698. *
  88699. * Example specifications are \c "blackman" or
  88700. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  88701. *
  88702. * Any function that is specified erroneously is silently dropped. Up
  88703. * to 32 functions are kept, the rest are dropped. If the specification
  88704. * is empty the encoder defaults to \c "tukey(0.5)".
  88705. *
  88706. * When more than one function is specified, then for every subframe the
  88707. * encoder will try each of them separately and choose the window that
  88708. * results in the smallest compressed subframe.
  88709. *
  88710. * Note that each function specified causes the encoder to occupy a
  88711. * floating point array in which to store the window.
  88712. *
  88713. * \default \c "tukey(0.5)"
  88714. * \param encoder An encoder instance to set.
  88715. * \param specification See above.
  88716. * \assert
  88717. * \code encoder != NULL \endcode
  88718. * \code specification != NULL \endcode
  88719. * \retval FLAC__bool
  88720. * \c false if the encoder is already initialized, else \c true.
  88721. */
  88722. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  88723. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  88724. *
  88725. * \default \c 0
  88726. * \param encoder An encoder instance to set.
  88727. * \param value See above.
  88728. * \assert
  88729. * \code encoder != NULL \endcode
  88730. * \retval FLAC__bool
  88731. * \c false if the encoder is already initialized, else \c true.
  88732. */
  88733. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  88734. /** Set the precision, in bits, of the quantized linear predictor
  88735. * coefficients, or \c 0 to let the encoder select it based on the
  88736. * blocksize.
  88737. *
  88738. * \note
  88739. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  88740. * be less than 32.
  88741. *
  88742. * \default \c 0
  88743. * \param encoder An encoder instance to set.
  88744. * \param value See above.
  88745. * \assert
  88746. * \code encoder != NULL \endcode
  88747. * \retval FLAC__bool
  88748. * \c false if the encoder is already initialized, else \c true.
  88749. */
  88750. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  88751. /** Set to \c false to use only the specified quantized linear predictor
  88752. * coefficient precision, or \c true to search neighboring precision
  88753. * values and use the best one.
  88754. *
  88755. * \default \c false
  88756. * \param encoder An encoder instance to set.
  88757. * \param value See above.
  88758. * \assert
  88759. * \code encoder != NULL \endcode
  88760. * \retval FLAC__bool
  88761. * \c false if the encoder is already initialized, else \c true.
  88762. */
  88763. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  88764. /** Deprecated. Setting this value has no effect.
  88765. *
  88766. * \default \c false
  88767. * \param encoder An encoder instance to set.
  88768. * \param value See above.
  88769. * \assert
  88770. * \code encoder != NULL \endcode
  88771. * \retval FLAC__bool
  88772. * \c false if the encoder is already initialized, else \c true.
  88773. */
  88774. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  88775. /** Set to \c false to let the encoder estimate the best model order
  88776. * based on the residual signal energy, or \c true to force the
  88777. * encoder to evaluate all order models and select the best.
  88778. *
  88779. * \default \c false
  88780. * \param encoder An encoder instance to set.
  88781. * \param value See above.
  88782. * \assert
  88783. * \code encoder != NULL \endcode
  88784. * \retval FLAC__bool
  88785. * \c false if the encoder is already initialized, else \c true.
  88786. */
  88787. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  88788. /** Set the minimum partition order to search when coding the residual.
  88789. * This is used in tandem with
  88790. * FLAC__stream_encoder_set_max_residual_partition_order().
  88791. *
  88792. * The partition order determines the context size in the residual.
  88793. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  88794. *
  88795. * Set both min and max values to \c 0 to force a single context,
  88796. * whose Rice parameter is based on the residual signal variance.
  88797. * Otherwise, set a min and max order, and the encoder will search
  88798. * all orders, using the mean of each context for its Rice parameter,
  88799. * and use the best.
  88800. *
  88801. * \default \c 0
  88802. * \param encoder An encoder instance to set.
  88803. * \param value See above.
  88804. * \assert
  88805. * \code encoder != NULL \endcode
  88806. * \retval FLAC__bool
  88807. * \c false if the encoder is already initialized, else \c true.
  88808. */
  88809. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  88810. /** Set the maximum partition order to search when coding the residual.
  88811. * This is used in tandem with
  88812. * FLAC__stream_encoder_set_min_residual_partition_order().
  88813. *
  88814. * The partition order determines the context size in the residual.
  88815. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  88816. *
  88817. * Set both min and max values to \c 0 to force a single context,
  88818. * whose Rice parameter is based on the residual signal variance.
  88819. * Otherwise, set a min and max order, and the encoder will search
  88820. * all orders, using the mean of each context for its Rice parameter,
  88821. * and use the best.
  88822. *
  88823. * \default \c 0
  88824. * \param encoder An encoder instance to set.
  88825. * \param value See above.
  88826. * \assert
  88827. * \code encoder != NULL \endcode
  88828. * \retval FLAC__bool
  88829. * \c false if the encoder is already initialized, else \c true.
  88830. */
  88831. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  88832. /** Deprecated. Setting this value has no effect.
  88833. *
  88834. * \default \c 0
  88835. * \param encoder An encoder instance to set.
  88836. * \param value See above.
  88837. * \assert
  88838. * \code encoder != NULL \endcode
  88839. * \retval FLAC__bool
  88840. * \c false if the encoder is already initialized, else \c true.
  88841. */
  88842. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  88843. /** Set an estimate of the total samples that will be encoded.
  88844. * This is merely an estimate and may be set to \c 0 if unknown.
  88845. * This value will be written to the STREAMINFO block before encoding,
  88846. * and can remove the need for the caller to rewrite the value later
  88847. * if the value is known before encoding.
  88848. *
  88849. * \default \c 0
  88850. * \param encoder An encoder instance to set.
  88851. * \param value See above.
  88852. * \assert
  88853. * \code encoder != NULL \endcode
  88854. * \retval FLAC__bool
  88855. * \c false if the encoder is already initialized, else \c true.
  88856. */
  88857. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  88858. /** Set the metadata blocks to be emitted to the stream before encoding.
  88859. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  88860. * array of pointers to metadata blocks. The array is non-const since
  88861. * the encoder may need to change the \a is_last flag inside them, and
  88862. * in some cases update seek point offsets. Otherwise, the encoder will
  88863. * not modify or free the blocks. It is up to the caller to free the
  88864. * metadata blocks after encoding finishes.
  88865. *
  88866. * \note
  88867. * The encoder stores only copies of the pointers in the \a metadata array;
  88868. * the metadata blocks themselves must survive at least until after
  88869. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  88870. *
  88871. * \note
  88872. * The STREAMINFO block is always written and no STREAMINFO block may
  88873. * occur in the supplied array.
  88874. *
  88875. * \note
  88876. * By default the encoder does not create a SEEKTABLE. If one is supplied
  88877. * in the \a metadata array, but the client has specified that it does not
  88878. * support seeking, then the SEEKTABLE will be written verbatim. However
  88879. * by itself this is not very useful as the client will not know the stream
  88880. * offsets for the seekpoints ahead of time. In order to get a proper
  88881. * seektable the client must support seeking. See next note.
  88882. *
  88883. * \note
  88884. * SEEKTABLE blocks are handled specially. Since you will not know
  88885. * the values for the seek point stream offsets, you should pass in
  88886. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  88887. * required sample numbers (or placeholder points), with \c 0 for the
  88888. * \a frame_samples and \a stream_offset fields for each point. If the
  88889. * client has specified that it supports seeking by providing a seek
  88890. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  88891. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  88892. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  88893. * then while it is encoding the encoder will fill the stream offsets in
  88894. * for you and when encoding is finished, it will seek back and write the
  88895. * real values into the SEEKTABLE block in the stream. There are helper
  88896. * routines for manipulating seektable template blocks; see metadata.h:
  88897. * FLAC__metadata_object_seektable_template_*(). If the client does
  88898. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  88899. * will slow down or remove the ability to seek in the FLAC stream.
  88900. *
  88901. * \note
  88902. * The encoder instance \b will modify the first \c SEEKTABLE block
  88903. * as it transforms the template to a valid seektable while encoding,
  88904. * but it is still up to the caller to free all metadata blocks after
  88905. * encoding.
  88906. *
  88907. * \note
  88908. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  88909. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  88910. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  88911. * will simply write it's own into the stream. If no VORBIS_COMMENT
  88912. * block is present in the \a metadata array, libFLAC will write an
  88913. * empty one, containing only the vendor string.
  88914. *
  88915. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  88916. * the second metadata block of the stream. The encoder already supplies
  88917. * the STREAMINFO block automatically. If \a metadata does not contain a
  88918. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  88919. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  88920. * first, the init function will reorder \a metadata by moving the
  88921. * VORBIS_COMMENT block to the front; the relative ordering of the other
  88922. * blocks will remain as they were.
  88923. *
  88924. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  88925. * stream to \c 65535. If \a num_blocks exceeds this the function will
  88926. * return \c false.
  88927. *
  88928. * \default \c NULL, 0
  88929. * \param encoder An encoder instance to set.
  88930. * \param metadata See above.
  88931. * \param num_blocks See above.
  88932. * \assert
  88933. * \code encoder != NULL \endcode
  88934. * \retval FLAC__bool
  88935. * \c false if the encoder is already initialized, else \c true.
  88936. * \c false if the encoder is already initialized, or if
  88937. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  88938. */
  88939. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  88940. /** Get the current encoder state.
  88941. *
  88942. * \param encoder An encoder instance to query.
  88943. * \assert
  88944. * \code encoder != NULL \endcode
  88945. * \retval FLAC__StreamEncoderState
  88946. * The current encoder state.
  88947. */
  88948. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  88949. /** Get the state of the verify stream decoder.
  88950. * Useful when the stream encoder state is
  88951. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  88952. *
  88953. * \param encoder An encoder instance to query.
  88954. * \assert
  88955. * \code encoder != NULL \endcode
  88956. * \retval FLAC__StreamDecoderState
  88957. * The verify stream decoder state.
  88958. */
  88959. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  88960. /** Get the current encoder state as a C string.
  88961. * This version automatically resolves
  88962. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  88963. * verify decoder's state.
  88964. *
  88965. * \param encoder A encoder instance to query.
  88966. * \assert
  88967. * \code encoder != NULL \endcode
  88968. * \retval const char *
  88969. * The encoder state as a C string. Do not modify the contents.
  88970. */
  88971. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  88972. /** Get relevant values about the nature of a verify decoder error.
  88973. * Useful when the stream encoder state is
  88974. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  88975. * be addresses in which the stats will be returned, or NULL if value
  88976. * is not desired.
  88977. *
  88978. * \param encoder An encoder instance to query.
  88979. * \param absolute_sample The absolute sample number of the mismatch.
  88980. * \param frame_number The number of the frame in which the mismatch occurred.
  88981. * \param channel The channel in which the mismatch occurred.
  88982. * \param sample The number of the sample (relative to the frame) in
  88983. * which the mismatch occurred.
  88984. * \param expected The expected value for the sample in question.
  88985. * \param got The actual value returned by the decoder.
  88986. * \assert
  88987. * \code encoder != NULL \endcode
  88988. */
  88989. 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);
  88990. /** Get the "verify" flag.
  88991. *
  88992. * \param encoder An encoder instance to query.
  88993. * \assert
  88994. * \code encoder != NULL \endcode
  88995. * \retval FLAC__bool
  88996. * See FLAC__stream_encoder_set_verify().
  88997. */
  88998. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  88999. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  89000. *
  89001. * \param encoder An encoder instance to query.
  89002. * \assert
  89003. * \code encoder != NULL \endcode
  89004. * \retval FLAC__bool
  89005. * See FLAC__stream_encoder_set_streamable_subset().
  89006. */
  89007. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  89008. /** Get the number of input channels being processed.
  89009. *
  89010. * \param encoder An encoder instance to query.
  89011. * \assert
  89012. * \code encoder != NULL \endcode
  89013. * \retval unsigned
  89014. * See FLAC__stream_encoder_set_channels().
  89015. */
  89016. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  89017. /** Get the input sample resolution setting.
  89018. *
  89019. * \param encoder An encoder instance to query.
  89020. * \assert
  89021. * \code encoder != NULL \endcode
  89022. * \retval unsigned
  89023. * See FLAC__stream_encoder_set_bits_per_sample().
  89024. */
  89025. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  89026. /** Get the input sample rate setting.
  89027. *
  89028. * \param encoder An encoder instance to query.
  89029. * \assert
  89030. * \code encoder != NULL \endcode
  89031. * \retval unsigned
  89032. * See FLAC__stream_encoder_set_sample_rate().
  89033. */
  89034. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  89035. /** Get the blocksize setting.
  89036. *
  89037. * \param encoder An encoder instance to query.
  89038. * \assert
  89039. * \code encoder != NULL \endcode
  89040. * \retval unsigned
  89041. * See FLAC__stream_encoder_set_blocksize().
  89042. */
  89043. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  89044. /** Get the "mid/side stereo coding" flag.
  89045. *
  89046. * \param encoder An encoder instance to query.
  89047. * \assert
  89048. * \code encoder != NULL \endcode
  89049. * \retval FLAC__bool
  89050. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  89051. */
  89052. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  89053. /** Get the "adaptive mid/side switching" flag.
  89054. *
  89055. * \param encoder An encoder instance to query.
  89056. * \assert
  89057. * \code encoder != NULL \endcode
  89058. * \retval FLAC__bool
  89059. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  89060. */
  89061. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  89062. /** Get the maximum LPC order setting.
  89063. *
  89064. * \param encoder An encoder instance to query.
  89065. * \assert
  89066. * \code encoder != NULL \endcode
  89067. * \retval unsigned
  89068. * See FLAC__stream_encoder_set_max_lpc_order().
  89069. */
  89070. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  89071. /** Get the quantized linear predictor coefficient precision setting.
  89072. *
  89073. * \param encoder An encoder instance to query.
  89074. * \assert
  89075. * \code encoder != NULL \endcode
  89076. * \retval unsigned
  89077. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  89078. */
  89079. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  89080. /** Get the qlp coefficient precision search flag.
  89081. *
  89082. * \param encoder An encoder instance to query.
  89083. * \assert
  89084. * \code encoder != NULL \endcode
  89085. * \retval FLAC__bool
  89086. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  89087. */
  89088. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  89089. /** Get the "escape coding" flag.
  89090. *
  89091. * \param encoder An encoder instance to query.
  89092. * \assert
  89093. * \code encoder != NULL \endcode
  89094. * \retval FLAC__bool
  89095. * See FLAC__stream_encoder_set_do_escape_coding().
  89096. */
  89097. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  89098. /** Get the exhaustive model search flag.
  89099. *
  89100. * \param encoder An encoder instance to query.
  89101. * \assert
  89102. * \code encoder != NULL \endcode
  89103. * \retval FLAC__bool
  89104. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  89105. */
  89106. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  89107. /** Get the minimum residual partition order setting.
  89108. *
  89109. * \param encoder An encoder instance to query.
  89110. * \assert
  89111. * \code encoder != NULL \endcode
  89112. * \retval unsigned
  89113. * See FLAC__stream_encoder_set_min_residual_partition_order().
  89114. */
  89115. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  89116. /** Get maximum residual partition order setting.
  89117. *
  89118. * \param encoder An encoder instance to query.
  89119. * \assert
  89120. * \code encoder != NULL \endcode
  89121. * \retval unsigned
  89122. * See FLAC__stream_encoder_set_max_residual_partition_order().
  89123. */
  89124. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  89125. /** Get the Rice parameter search distance setting.
  89126. *
  89127. * \param encoder An encoder instance to query.
  89128. * \assert
  89129. * \code encoder != NULL \endcode
  89130. * \retval unsigned
  89131. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  89132. */
  89133. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  89134. /** Get the previously set estimate of the total samples to be encoded.
  89135. * The encoder merely mimics back the value given to
  89136. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  89137. * other way of knowing how many samples the client will encode.
  89138. *
  89139. * \param encoder An encoder instance to set.
  89140. * \assert
  89141. * \code encoder != NULL \endcode
  89142. * \retval FLAC__uint64
  89143. * See FLAC__stream_encoder_get_total_samples_estimate().
  89144. */
  89145. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  89146. /** Initialize the encoder instance to encode native FLAC streams.
  89147. *
  89148. * This flavor of initialization sets up the encoder to encode to a
  89149. * native FLAC stream. I/O is performed via callbacks to the client.
  89150. * For encoding to a plain file via filename or open \c FILE*,
  89151. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  89152. * provide a simpler interface.
  89153. *
  89154. * This function should be called after FLAC__stream_encoder_new() and
  89155. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  89156. * or FLAC__stream_encoder_process_interleaved().
  89157. * initialization succeeded.
  89158. *
  89159. * The call to FLAC__stream_encoder_init_stream() currently will also
  89160. * immediately call the write callback several times, once with the \c fLaC
  89161. * signature, and once for each encoded metadata block.
  89162. *
  89163. * \param encoder An uninitialized encoder instance.
  89164. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  89165. * pointer must not be \c NULL.
  89166. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  89167. * pointer may be \c NULL if seeking is not
  89168. * supported. The encoder uses seeking to go back
  89169. * and write some some stream statistics to the
  89170. * STREAMINFO block; this is recommended but not
  89171. * necessary to create a valid FLAC stream. If
  89172. * \a seek_callback is not \c NULL then a
  89173. * \a tell_callback must also be supplied.
  89174. * Alternatively, a dummy seek callback that just
  89175. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  89176. * may also be supplied, all though this is slightly
  89177. * less efficient for the encoder.
  89178. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  89179. * pointer may be \c NULL if seeking is not
  89180. * supported. If \a seek_callback is \c NULL then
  89181. * this argument will be ignored. If
  89182. * \a seek_callback is not \c NULL then a
  89183. * \a tell_callback must also be supplied.
  89184. * Alternatively, a dummy tell callback that just
  89185. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  89186. * may also be supplied, all though this is slightly
  89187. * less efficient for the encoder.
  89188. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  89189. * pointer may be \c NULL if the callback is not
  89190. * desired. If the client provides a seek callback,
  89191. * this function is not necessary as the encoder
  89192. * will automatically seek back and update the
  89193. * STREAMINFO block. It may also be \c NULL if the
  89194. * client does not support seeking, since it will
  89195. * have no way of going back to update the
  89196. * STREAMINFO. However the client can still supply
  89197. * a callback if it would like to know the details
  89198. * from the STREAMINFO.
  89199. * \param client_data This value will be supplied to callbacks in their
  89200. * \a client_data argument.
  89201. * \assert
  89202. * \code encoder != NULL \endcode
  89203. * \retval FLAC__StreamEncoderInitStatus
  89204. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  89205. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  89206. */
  89207. 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);
  89208. /** Initialize the encoder instance to encode Ogg FLAC streams.
  89209. *
  89210. * This flavor of initialization sets up the encoder to encode to a FLAC
  89211. * stream in an Ogg container. I/O is performed via callbacks to the
  89212. * client. For encoding to a plain file via filename or open \c FILE*,
  89213. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  89214. * provide a simpler interface.
  89215. *
  89216. * This function should be called after FLAC__stream_encoder_new() and
  89217. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  89218. * or FLAC__stream_encoder_process_interleaved().
  89219. * initialization succeeded.
  89220. *
  89221. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  89222. * immediately call the write callback several times to write the metadata
  89223. * packets.
  89224. *
  89225. * \param encoder An uninitialized encoder instance.
  89226. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  89227. * pointer must not be \c NULL if \a seek_callback
  89228. * is non-NULL since they are both needed to be
  89229. * able to write data back to the Ogg FLAC stream
  89230. * in the post-encode phase.
  89231. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  89232. * pointer must not be \c NULL.
  89233. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  89234. * pointer may be \c NULL if seeking is not
  89235. * supported. The encoder uses seeking to go back
  89236. * and write some some stream statistics to the
  89237. * STREAMINFO block; this is recommended but not
  89238. * necessary to create a valid FLAC stream. If
  89239. * \a seek_callback is not \c NULL then a
  89240. * \a tell_callback must also be supplied.
  89241. * Alternatively, a dummy seek callback that just
  89242. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  89243. * may also be supplied, all though this is slightly
  89244. * less efficient for the encoder.
  89245. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  89246. * pointer may be \c NULL if seeking is not
  89247. * supported. If \a seek_callback is \c NULL then
  89248. * this argument will be ignored. If
  89249. * \a seek_callback is not \c NULL then a
  89250. * \a tell_callback must also be supplied.
  89251. * Alternatively, a dummy tell callback that just
  89252. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  89253. * may also be supplied, all though this is slightly
  89254. * less efficient for the encoder.
  89255. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  89256. * pointer may be \c NULL if the callback is not
  89257. * desired. If the client provides a seek callback,
  89258. * this function is not necessary as the encoder
  89259. * will automatically seek back and update the
  89260. * STREAMINFO block. It may also be \c NULL if the
  89261. * client does not support seeking, since it will
  89262. * have no way of going back to update the
  89263. * STREAMINFO. However the client can still supply
  89264. * a callback if it would like to know the details
  89265. * from the STREAMINFO.
  89266. * \param client_data This value will be supplied to callbacks in their
  89267. * \a client_data argument.
  89268. * \assert
  89269. * \code encoder != NULL \endcode
  89270. * \retval FLAC__StreamEncoderInitStatus
  89271. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  89272. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  89273. */
  89274. 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);
  89275. /** Initialize the encoder instance to encode native FLAC files.
  89276. *
  89277. * This flavor of initialization sets up the encoder to encode to a
  89278. * plain native FLAC file. For non-stdio streams, you must use
  89279. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  89280. *
  89281. * This function should be called after FLAC__stream_encoder_new() and
  89282. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  89283. * or FLAC__stream_encoder_process_interleaved().
  89284. * initialization succeeded.
  89285. *
  89286. * \param encoder An uninitialized encoder instance.
  89287. * \param file An open file. The file should have been opened
  89288. * with mode \c "w+b" and rewound. The file
  89289. * becomes owned by the encoder and should not be
  89290. * manipulated by the client while encoding.
  89291. * Unless \a file is \c stdout, it will be closed
  89292. * when FLAC__stream_encoder_finish() is called.
  89293. * Note however that a proper SEEKTABLE cannot be
  89294. * created when encoding to \c stdout since it is
  89295. * not seekable.
  89296. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  89297. * pointer may be \c NULL if the callback is not
  89298. * desired.
  89299. * \param client_data This value will be supplied to callbacks in their
  89300. * \a client_data argument.
  89301. * \assert
  89302. * \code encoder != NULL \endcode
  89303. * \code file != NULL \endcode
  89304. * \retval FLAC__StreamEncoderInitStatus
  89305. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  89306. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  89307. */
  89308. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  89309. /** Initialize the encoder instance to encode Ogg FLAC files.
  89310. *
  89311. * This flavor of initialization sets up the encoder to encode to a
  89312. * plain Ogg FLAC file. For non-stdio streams, you must use
  89313. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  89314. *
  89315. * This function should be called after FLAC__stream_encoder_new() and
  89316. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  89317. * or FLAC__stream_encoder_process_interleaved().
  89318. * initialization succeeded.
  89319. *
  89320. * \param encoder An uninitialized encoder instance.
  89321. * \param file An open file. The file should have been opened
  89322. * with mode \c "w+b" and rewound. The file
  89323. * becomes owned by the encoder and should not be
  89324. * manipulated by the client while encoding.
  89325. * Unless \a file is \c stdout, it will be closed
  89326. * when FLAC__stream_encoder_finish() is called.
  89327. * Note however that a proper SEEKTABLE cannot be
  89328. * created when encoding to \c stdout since it is
  89329. * not seekable.
  89330. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  89331. * pointer may be \c NULL if the callback is not
  89332. * desired.
  89333. * \param client_data This value will be supplied to callbacks in their
  89334. * \a client_data argument.
  89335. * \assert
  89336. * \code encoder != NULL \endcode
  89337. * \code file != NULL \endcode
  89338. * \retval FLAC__StreamEncoderInitStatus
  89339. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  89340. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  89341. */
  89342. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  89343. /** Initialize the encoder instance to encode native FLAC files.
  89344. *
  89345. * This flavor of initialization sets up the encoder to encode to a plain
  89346. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  89347. * with Unicode filenames on Windows), you must use
  89348. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  89349. * and provide callbacks for the I/O.
  89350. *
  89351. * This function should be called after FLAC__stream_encoder_new() and
  89352. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  89353. * or FLAC__stream_encoder_process_interleaved().
  89354. * initialization succeeded.
  89355. *
  89356. * \param encoder An uninitialized encoder instance.
  89357. * \param filename The name of the file to encode to. The file will
  89358. * be opened with fopen(). Use \c NULL to encode to
  89359. * \c stdout. Note however that a proper SEEKTABLE
  89360. * cannot be created when encoding to \c stdout since
  89361. * it is not seekable.
  89362. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  89363. * pointer may be \c NULL if the callback is not
  89364. * desired.
  89365. * \param client_data This value will be supplied to callbacks in their
  89366. * \a client_data argument.
  89367. * \assert
  89368. * \code encoder != NULL \endcode
  89369. * \retval FLAC__StreamEncoderInitStatus
  89370. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  89371. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  89372. */
  89373. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  89374. /** Initialize the encoder instance to encode Ogg FLAC files.
  89375. *
  89376. * This flavor of initialization sets up the encoder to encode to a plain
  89377. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  89378. * with Unicode filenames on Windows), you must use
  89379. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  89380. * and provide callbacks for the I/O.
  89381. *
  89382. * This function should be called after FLAC__stream_encoder_new() and
  89383. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  89384. * or FLAC__stream_encoder_process_interleaved().
  89385. * initialization succeeded.
  89386. *
  89387. * \param encoder An uninitialized encoder instance.
  89388. * \param filename The name of the file to encode to. The file will
  89389. * be opened with fopen(). Use \c NULL to encode to
  89390. * \c stdout. Note however that a proper SEEKTABLE
  89391. * cannot be created when encoding to \c stdout since
  89392. * it is not seekable.
  89393. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  89394. * pointer may be \c NULL if the callback is not
  89395. * desired.
  89396. * \param client_data This value will be supplied to callbacks in their
  89397. * \a client_data argument.
  89398. * \assert
  89399. * \code encoder != NULL \endcode
  89400. * \retval FLAC__StreamEncoderInitStatus
  89401. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  89402. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  89403. */
  89404. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  89405. /** Finish the encoding process.
  89406. * Flushes the encoding buffer, releases resources, resets the encoder
  89407. * settings to their defaults, and returns the encoder state to
  89408. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  89409. * one or more write callbacks before returning, and will generate
  89410. * a metadata callback.
  89411. *
  89412. * Note that in the course of processing the last frame, errors can
  89413. * occur, so the caller should be sure to check the return value to
  89414. * ensure the file was encoded properly.
  89415. *
  89416. * In the event of a prematurely-terminated encode, it is not strictly
  89417. * necessary to call this immediately before FLAC__stream_encoder_delete()
  89418. * but it is good practice to match every FLAC__stream_encoder_init_*()
  89419. * with a FLAC__stream_encoder_finish().
  89420. *
  89421. * \param encoder An uninitialized encoder instance.
  89422. * \assert
  89423. * \code encoder != NULL \endcode
  89424. * \retval FLAC__bool
  89425. * \c false if an error occurred processing the last frame; or if verify
  89426. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  89427. * verify mismatch; else \c true. If \c false, caller should check the
  89428. * state with FLAC__stream_encoder_get_state() for more information
  89429. * about the error.
  89430. */
  89431. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  89432. /** Submit data for encoding.
  89433. * This version allows you to supply the input data via an array of
  89434. * pointers, each pointer pointing to an array of \a samples samples
  89435. * representing one channel. The samples need not be block-aligned,
  89436. * but each channel should have the same number of samples. Each sample
  89437. * should be a signed integer, right-justified to the resolution set by
  89438. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  89439. * resolution is 16 bits per sample, the samples should all be in the
  89440. * range [-32768,32767].
  89441. *
  89442. * For applications where channel order is important, channels must
  89443. * follow the order as described in the
  89444. * <A HREF="../format.html#frame_header">frame header</A>.
  89445. *
  89446. * \param encoder An initialized encoder instance in the OK state.
  89447. * \param buffer An array of pointers to each channel's signal.
  89448. * \param samples The number of samples in one channel.
  89449. * \assert
  89450. * \code encoder != NULL \endcode
  89451. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  89452. * \retval FLAC__bool
  89453. * \c true if successful, else \c false; in this case, check the
  89454. * encoder state with FLAC__stream_encoder_get_state() to see what
  89455. * went wrong.
  89456. */
  89457. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  89458. /** Submit data for encoding.
  89459. * This version allows you to supply the input data where the channels
  89460. * are interleaved into a single array (i.e. channel0_sample0,
  89461. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  89462. * The samples need not be block-aligned but they must be
  89463. * sample-aligned, i.e. the first value should be channel0_sample0
  89464. * and the last value channelN_sampleM. Each sample should be a signed
  89465. * integer, right-justified to the resolution set by
  89466. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  89467. * resolution is 16 bits per sample, the samples should all be in the
  89468. * range [-32768,32767].
  89469. *
  89470. * For applications where channel order is important, channels must
  89471. * follow the order as described in the
  89472. * <A HREF="../format.html#frame_header">frame header</A>.
  89473. *
  89474. * \param encoder An initialized encoder instance in the OK state.
  89475. * \param buffer An array of channel-interleaved data (see above).
  89476. * \param samples The number of samples in one channel, the same as for
  89477. * FLAC__stream_encoder_process(). For example, if
  89478. * encoding two channels, \c 1000 \a samples corresponds
  89479. * to a \a buffer of 2000 values.
  89480. * \assert
  89481. * \code encoder != NULL \endcode
  89482. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  89483. * \retval FLAC__bool
  89484. * \c true if successful, else \c false; in this case, check the
  89485. * encoder state with FLAC__stream_encoder_get_state() to see what
  89486. * went wrong.
  89487. */
  89488. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  89489. /* \} */
  89490. #ifdef __cplusplus
  89491. }
  89492. #endif
  89493. #endif
  89494. /*** End of inlined file: stream_encoder.h ***/
  89495. #ifdef _MSC_VER
  89496. /* OPT: an MSVC built-in would be better */
  89497. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  89498. {
  89499. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  89500. return (x>>16) | (x<<16);
  89501. }
  89502. #endif
  89503. #if defined(_MSC_VER) && defined(_X86_)
  89504. /* OPT: an MSVC built-in would be better */
  89505. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  89506. {
  89507. __asm {
  89508. mov edx, start
  89509. mov ecx, len
  89510. test ecx, ecx
  89511. loop1:
  89512. jz done1
  89513. mov eax, [edx]
  89514. bswap eax
  89515. mov [edx], eax
  89516. add edx, 4
  89517. dec ecx
  89518. jmp short loop1
  89519. done1:
  89520. }
  89521. }
  89522. #endif
  89523. /** \mainpage
  89524. *
  89525. * \section intro Introduction
  89526. *
  89527. * This is the documentation for the FLAC C and C++ APIs. It is
  89528. * highly interconnected; this introduction should give you a top
  89529. * level idea of the structure and how to find the information you
  89530. * need. As a prerequisite you should have at least a basic
  89531. * knowledge of the FLAC format, documented
  89532. * <A HREF="../format.html">here</A>.
  89533. *
  89534. * \section c_api FLAC C API
  89535. *
  89536. * The FLAC C API is the interface to libFLAC, a set of structures
  89537. * describing the components of FLAC streams, and functions for
  89538. * encoding and decoding streams, as well as manipulating FLAC
  89539. * metadata in files. The public include files will be installed
  89540. * in your include area (for example /usr/include/FLAC/...).
  89541. *
  89542. * By writing a little code and linking against libFLAC, it is
  89543. * relatively easy to add FLAC support to another program. The
  89544. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  89545. * Complete source code of libFLAC as well as the command-line
  89546. * encoder and plugins is available and is a useful source of
  89547. * examples.
  89548. *
  89549. * Aside from encoders and decoders, libFLAC provides a powerful
  89550. * metadata interface for manipulating metadata in FLAC files. It
  89551. * allows the user to add, delete, and modify FLAC metadata blocks
  89552. * and it can automatically take advantage of PADDING blocks to avoid
  89553. * rewriting the entire FLAC file when changing the size of the
  89554. * metadata.
  89555. *
  89556. * libFLAC usually only requires the standard C library and C math
  89557. * library. In particular, threading is not used so there is no
  89558. * dependency on a thread library. However, libFLAC does not use
  89559. * global variables and should be thread-safe.
  89560. *
  89561. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  89562. * However the metadata editing interfaces currently have limited
  89563. * read-only support for Ogg FLAC files.
  89564. *
  89565. * \section cpp_api FLAC C++ API
  89566. *
  89567. * The FLAC C++ API is a set of classes that encapsulate the
  89568. * structures and functions in libFLAC. They provide slightly more
  89569. * functionality with respect to metadata but are otherwise
  89570. * equivalent. For the most part, they share the same usage as
  89571. * their counterparts in libFLAC, and the FLAC C API documentation
  89572. * can be used as a supplement. The public include files
  89573. * for the C++ API will be installed in your include area (for
  89574. * example /usr/include/FLAC++/...).
  89575. *
  89576. * libFLAC++ is also licensed under
  89577. * <A HREF="../license.html">Xiph's BSD license</A>.
  89578. *
  89579. * \section getting_started Getting Started
  89580. *
  89581. * A good starting point for learning the API is to browse through
  89582. * the <A HREF="modules.html">modules</A>. Modules are logical
  89583. * groupings of related functions or classes, which correspond roughly
  89584. * to header files or sections of header files. Each module includes a
  89585. * detailed description of the general usage of its functions or
  89586. * classes.
  89587. *
  89588. * From there you can go on to look at the documentation of
  89589. * individual functions. You can see different views of the individual
  89590. * functions through the links in top bar across this page.
  89591. *
  89592. * If you prefer a more hands-on approach, you can jump right to some
  89593. * <A HREF="../documentation_example_code.html">example code</A>.
  89594. *
  89595. * \section porting_guide Porting Guide
  89596. *
  89597. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  89598. * has been introduced which gives detailed instructions on how to
  89599. * port your code to newer versions of FLAC.
  89600. *
  89601. * \section embedded_developers Embedded Developers
  89602. *
  89603. * libFLAC has grown larger over time as more functionality has been
  89604. * included, but much of it may be unnecessary for a particular embedded
  89605. * implementation. Unused parts may be pruned by some simple editing of
  89606. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  89607. * metadata interface are all independent from each other.
  89608. *
  89609. * It is easiest to just describe the dependencies:
  89610. *
  89611. * - All modules depend on the \link flac_format Format \endlink module.
  89612. * - The decoders and encoders depend on the bitbuffer.
  89613. * - The decoder is independent of the encoder. The encoder uses the
  89614. * decoder because of the verify feature, but this can be removed if
  89615. * not needed.
  89616. * - Parts of the metadata interface require the stream decoder (but not
  89617. * the encoder).
  89618. * - Ogg support is selectable through the compile time macro
  89619. * \c FLAC__HAS_OGG.
  89620. *
  89621. * For example, if your application only requires the stream decoder, no
  89622. * encoder, and no metadata interface, you can remove the stream encoder
  89623. * and the metadata interface, which will greatly reduce the size of the
  89624. * library.
  89625. *
  89626. * Also, there are several places in the libFLAC code with comments marked
  89627. * with "OPT:" where a #define can be changed to enable code that might be
  89628. * faster on a specific platform. Experimenting with these can yield faster
  89629. * binaries.
  89630. */
  89631. /** \defgroup porting Porting Guide for New Versions
  89632. *
  89633. * This module describes differences in the library interfaces from
  89634. * version to version. It assists in the porting of code that uses
  89635. * the libraries to newer versions of FLAC.
  89636. *
  89637. * One simple facility for making porting easier that has been added
  89638. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  89639. * library's includes (e.g. \c include/FLAC/export.h). The
  89640. * \c #defines mirror the libraries'
  89641. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  89642. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  89643. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  89644. * These can be used to support multiple versions of an API during the
  89645. * transition phase, e.g.
  89646. *
  89647. * \code
  89648. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  89649. * legacy code
  89650. * #else
  89651. * new code
  89652. * #endif
  89653. * \endcode
  89654. *
  89655. * The the source will work for multiple versions and the legacy code can
  89656. * easily be removed when the transition is complete.
  89657. *
  89658. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  89659. * include/FLAC/export.h), which can be used to determine whether or not
  89660. * the library has been compiled with support for Ogg FLAC. This is
  89661. * simpler than trying to call an Ogg init function and catching the
  89662. * error.
  89663. */
  89664. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  89665. * \ingroup porting
  89666. *
  89667. * \brief
  89668. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  89669. *
  89670. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  89671. * been simplified. First, libOggFLAC has been merged into libFLAC and
  89672. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  89673. * decoding layers and three encoding layers have been merged into a
  89674. * single stream decoder and stream encoder. That is, the functionality
  89675. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  89676. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  89677. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  89678. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  89679. * is there is now a single API that can be used to encode or decode
  89680. * streams to/from native FLAC or Ogg FLAC and the single API can work
  89681. * on both seekable and non-seekable streams.
  89682. *
  89683. * Instead of creating an encoder or decoder of a certain layer, now the
  89684. * client will always create a FLAC__StreamEncoder or
  89685. * FLAC__StreamDecoder. The old layers are now differentiated by the
  89686. * initialization function. For example, for the decoder,
  89687. * FLAC__stream_decoder_init() has been replaced by
  89688. * FLAC__stream_decoder_init_stream(). This init function takes
  89689. * callbacks for the I/O, and the seeking callbacks are optional. This
  89690. * allows the client to use the same object for seekable and
  89691. * non-seekable streams. For decoding a FLAC file directly, the client
  89692. * can use FLAC__stream_decoder_init_file() and pass just a filename
  89693. * and fewer callbacks; most of the other callbacks are supplied
  89694. * internally. For situations where fopen()ing by filename is not
  89695. * possible (e.g. Unicode filenames on Windows) the client can instead
  89696. * open the file itself and supply the FILE* to
  89697. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  89698. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  89699. * Since the callbacks and client data are now passed to the init
  89700. * function, the FLAC__stream_decoder_set_*_callback() functions and
  89701. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  89702. * rest of the calls to the decoder are the same as before.
  89703. *
  89704. * There are counterpart init functions for Ogg FLAC, e.g.
  89705. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  89706. * and callbacks are the same as for native FLAC.
  89707. *
  89708. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  89709. * been set up like so:
  89710. *
  89711. * \code
  89712. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  89713. * if(decoder == NULL) do_something;
  89714. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  89715. * [... other settings ...]
  89716. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  89717. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  89718. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  89719. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  89720. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  89721. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  89722. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  89723. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  89724. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  89725. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  89726. * \endcode
  89727. *
  89728. * In FLAC 1.1.3 it is like this:
  89729. *
  89730. * \code
  89731. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  89732. * if(decoder == NULL) do_something;
  89733. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  89734. * [... other settings ...]
  89735. * if(FLAC__stream_decoder_init_stream(
  89736. * decoder,
  89737. * my_read_callback,
  89738. * my_seek_callback, // or NULL
  89739. * my_tell_callback, // or NULL
  89740. * my_length_callback, // or NULL
  89741. * my_eof_callback, // or NULL
  89742. * my_write_callback,
  89743. * my_metadata_callback, // or NULL
  89744. * my_error_callback,
  89745. * my_client_data
  89746. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  89747. * \endcode
  89748. *
  89749. * or you could do;
  89750. *
  89751. * \code
  89752. * [...]
  89753. * FILE *file = fopen("somefile.flac","rb");
  89754. * if(file == NULL) do_somthing;
  89755. * if(FLAC__stream_decoder_init_FILE(
  89756. * decoder,
  89757. * file,
  89758. * my_write_callback,
  89759. * my_metadata_callback, // or NULL
  89760. * my_error_callback,
  89761. * my_client_data
  89762. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  89763. * \endcode
  89764. *
  89765. * or just:
  89766. *
  89767. * \code
  89768. * [...]
  89769. * if(FLAC__stream_decoder_init_file(
  89770. * decoder,
  89771. * "somefile.flac",
  89772. * my_write_callback,
  89773. * my_metadata_callback, // or NULL
  89774. * my_error_callback,
  89775. * my_client_data
  89776. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  89777. * \endcode
  89778. *
  89779. * Another small change to the decoder is in how it handles unparseable
  89780. * streams. Before, when the decoder found an unparseable stream
  89781. * (reserved for when the decoder encounters a stream from a future
  89782. * encoder that it can't parse), it changed the state to
  89783. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  89784. * drops sync and calls the error callback with a new error code
  89785. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  89786. * more robust. If your error callback does not discriminate on the the
  89787. * error state, your code does not need to be changed.
  89788. *
  89789. * The encoder now has a new setting:
  89790. * FLAC__stream_encoder_set_apodization(). This is for setting the
  89791. * method used to window the data before LPC analysis. You only need to
  89792. * add a call to this function if the default is not suitable. There
  89793. * are also two new convenience functions that may be useful:
  89794. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  89795. * FLAC__metadata_get_cuesheet().
  89796. *
  89797. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  89798. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  89799. * is now \c size_t instead of \c unsigned.
  89800. */
  89801. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  89802. * \ingroup porting
  89803. *
  89804. * \brief
  89805. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  89806. *
  89807. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  89808. * There was a slight change in the implementation of
  89809. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  89810. * of the \a metadata array of pointers so the client no longer needs
  89811. * to maintain it after the call. The objects themselves that are
  89812. * pointed to by the array are still not copied though and must be
  89813. * maintained until the call to FLAC__stream_encoder_finish().
  89814. */
  89815. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  89816. * \ingroup porting
  89817. *
  89818. * \brief
  89819. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  89820. *
  89821. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  89822. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  89823. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  89824. *
  89825. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  89826. * has changed to reflect the conversion of one of the reserved bits
  89827. * into active use. It used to be \c 2 and now is \c 1. However the
  89828. * FLAC frame header length has not changed, so to skip the proper
  89829. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  89830. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  89831. */
  89832. /** \defgroup flac FLAC C API
  89833. *
  89834. * The FLAC C API is the interface to libFLAC, a set of structures
  89835. * describing the components of FLAC streams, and functions for
  89836. * encoding and decoding streams, as well as manipulating FLAC
  89837. * metadata in files.
  89838. *
  89839. * You should start with the format components as all other modules
  89840. * are dependent on it.
  89841. */
  89842. #endif
  89843. /*** End of inlined file: all.h ***/
  89844. /*** Start of inlined file: bitmath.c ***/
  89845. /*** Start of inlined file: juce_FlacHeader.h ***/
  89846. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  89847. // tasks..
  89848. #define VERSION "1.2.1"
  89849. #define FLAC__NO_DLL 1
  89850. #if JUCE_MSVC
  89851. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  89852. #endif
  89853. #if JUCE_MAC
  89854. #define FLAC__SYS_DARWIN 1
  89855. #endif
  89856. /*** End of inlined file: juce_FlacHeader.h ***/
  89857. #if JUCE_USE_FLAC
  89858. #if HAVE_CONFIG_H
  89859. # include <config.h>
  89860. #endif
  89861. /*** Start of inlined file: bitmath.h ***/
  89862. #ifndef FLAC__PRIVATE__BITMATH_H
  89863. #define FLAC__PRIVATE__BITMATH_H
  89864. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  89865. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  89866. unsigned FLAC__bitmath_silog2(int v);
  89867. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  89868. #endif
  89869. /*** End of inlined file: bitmath.h ***/
  89870. /* An example of what FLAC__bitmath_ilog2() computes:
  89871. *
  89872. * ilog2( 0) = assertion failure
  89873. * ilog2( 1) = 0
  89874. * ilog2( 2) = 1
  89875. * ilog2( 3) = 1
  89876. * ilog2( 4) = 2
  89877. * ilog2( 5) = 2
  89878. * ilog2( 6) = 2
  89879. * ilog2( 7) = 2
  89880. * ilog2( 8) = 3
  89881. * ilog2( 9) = 3
  89882. * ilog2(10) = 3
  89883. * ilog2(11) = 3
  89884. * ilog2(12) = 3
  89885. * ilog2(13) = 3
  89886. * ilog2(14) = 3
  89887. * ilog2(15) = 3
  89888. * ilog2(16) = 4
  89889. * ilog2(17) = 4
  89890. * ilog2(18) = 4
  89891. */
  89892. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  89893. {
  89894. unsigned l = 0;
  89895. FLAC__ASSERT(v > 0);
  89896. while(v >>= 1)
  89897. l++;
  89898. return l;
  89899. }
  89900. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  89901. {
  89902. unsigned l = 0;
  89903. FLAC__ASSERT(v > 0);
  89904. while(v >>= 1)
  89905. l++;
  89906. return l;
  89907. }
  89908. /* An example of what FLAC__bitmath_silog2() computes:
  89909. *
  89910. * silog2(-10) = 5
  89911. * silog2(- 9) = 5
  89912. * silog2(- 8) = 4
  89913. * silog2(- 7) = 4
  89914. * silog2(- 6) = 4
  89915. * silog2(- 5) = 4
  89916. * silog2(- 4) = 3
  89917. * silog2(- 3) = 3
  89918. * silog2(- 2) = 2
  89919. * silog2(- 1) = 2
  89920. * silog2( 0) = 0
  89921. * silog2( 1) = 2
  89922. * silog2( 2) = 3
  89923. * silog2( 3) = 3
  89924. * silog2( 4) = 4
  89925. * silog2( 5) = 4
  89926. * silog2( 6) = 4
  89927. * silog2( 7) = 4
  89928. * silog2( 8) = 5
  89929. * silog2( 9) = 5
  89930. * silog2( 10) = 5
  89931. */
  89932. unsigned FLAC__bitmath_silog2(int v)
  89933. {
  89934. while(1) {
  89935. if(v == 0) {
  89936. return 0;
  89937. }
  89938. else if(v > 0) {
  89939. unsigned l = 0;
  89940. while(v) {
  89941. l++;
  89942. v >>= 1;
  89943. }
  89944. return l+1;
  89945. }
  89946. else if(v == -1) {
  89947. return 2;
  89948. }
  89949. else {
  89950. v++;
  89951. v = -v;
  89952. }
  89953. }
  89954. }
  89955. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  89956. {
  89957. while(1) {
  89958. if(v == 0) {
  89959. return 0;
  89960. }
  89961. else if(v > 0) {
  89962. unsigned l = 0;
  89963. while(v) {
  89964. l++;
  89965. v >>= 1;
  89966. }
  89967. return l+1;
  89968. }
  89969. else if(v == -1) {
  89970. return 2;
  89971. }
  89972. else {
  89973. v++;
  89974. v = -v;
  89975. }
  89976. }
  89977. }
  89978. #endif
  89979. /*** End of inlined file: bitmath.c ***/
  89980. /*** Start of inlined file: bitreader.c ***/
  89981. /*** Start of inlined file: juce_FlacHeader.h ***/
  89982. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  89983. // tasks..
  89984. #define VERSION "1.2.1"
  89985. #define FLAC__NO_DLL 1
  89986. #if JUCE_MSVC
  89987. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  89988. #endif
  89989. #if JUCE_MAC
  89990. #define FLAC__SYS_DARWIN 1
  89991. #endif
  89992. /*** End of inlined file: juce_FlacHeader.h ***/
  89993. #if JUCE_USE_FLAC
  89994. #if HAVE_CONFIG_H
  89995. # include <config.h>
  89996. #endif
  89997. #include <stdlib.h> /* for malloc() */
  89998. #include <string.h> /* for memcpy(), memset() */
  89999. #ifdef _MSC_VER
  90000. #include <winsock.h> /* for ntohl() */
  90001. #elif defined FLAC__SYS_DARWIN
  90002. #include <machine/endian.h> /* for ntohl() */
  90003. #elif defined __MINGW32__
  90004. #include <winsock.h> /* for ntohl() */
  90005. #else
  90006. #include <netinet/in.h> /* for ntohl() */
  90007. #endif
  90008. /*** Start of inlined file: bitreader.h ***/
  90009. #ifndef FLAC__PRIVATE__BITREADER_H
  90010. #define FLAC__PRIVATE__BITREADER_H
  90011. #include <stdio.h> /* for FILE */
  90012. /*** Start of inlined file: cpu.h ***/
  90013. #ifndef FLAC__PRIVATE__CPU_H
  90014. #define FLAC__PRIVATE__CPU_H
  90015. #ifdef HAVE_CONFIG_H
  90016. #include <config.h>
  90017. #endif
  90018. typedef enum {
  90019. FLAC__CPUINFO_TYPE_IA32,
  90020. FLAC__CPUINFO_TYPE_PPC,
  90021. FLAC__CPUINFO_TYPE_UNKNOWN
  90022. } FLAC__CPUInfo_Type;
  90023. typedef struct {
  90024. FLAC__bool cpuid;
  90025. FLAC__bool bswap;
  90026. FLAC__bool cmov;
  90027. FLAC__bool mmx;
  90028. FLAC__bool fxsr;
  90029. FLAC__bool sse;
  90030. FLAC__bool sse2;
  90031. FLAC__bool sse3;
  90032. FLAC__bool ssse3;
  90033. FLAC__bool _3dnow;
  90034. FLAC__bool ext3dnow;
  90035. FLAC__bool extmmx;
  90036. } FLAC__CPUInfo_IA32;
  90037. typedef struct {
  90038. FLAC__bool altivec;
  90039. FLAC__bool ppc64;
  90040. } FLAC__CPUInfo_PPC;
  90041. typedef struct {
  90042. FLAC__bool use_asm;
  90043. FLAC__CPUInfo_Type type;
  90044. union {
  90045. FLAC__CPUInfo_IA32 ia32;
  90046. FLAC__CPUInfo_PPC ppc;
  90047. } data;
  90048. } FLAC__CPUInfo;
  90049. void FLAC__cpu_info(FLAC__CPUInfo *info);
  90050. #ifndef FLAC__NO_ASM
  90051. #ifdef FLAC__CPU_IA32
  90052. #ifdef FLAC__HAS_NASM
  90053. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  90054. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  90055. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  90056. #endif
  90057. #endif
  90058. #endif
  90059. #endif
  90060. /*** End of inlined file: cpu.h ***/
  90061. /*
  90062. * opaque structure definition
  90063. */
  90064. struct FLAC__BitReader;
  90065. typedef struct FLAC__BitReader FLAC__BitReader;
  90066. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  90067. /*
  90068. * construction, deletion, initialization, etc functions
  90069. */
  90070. FLAC__BitReader *FLAC__bitreader_new(void);
  90071. void FLAC__bitreader_delete(FLAC__BitReader *br);
  90072. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  90073. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  90074. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  90075. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  90076. /*
  90077. * CRC functions
  90078. */
  90079. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  90080. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  90081. /*
  90082. * info functions
  90083. */
  90084. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  90085. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  90086. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  90087. /*
  90088. * read functions
  90089. */
  90090. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  90091. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  90092. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  90093. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  90094. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  90095. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  90096. 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! */
  90097. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  90098. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  90099. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  90100. #ifndef FLAC__NO_ASM
  90101. # ifdef FLAC__CPU_IA32
  90102. # ifdef FLAC__HAS_NASM
  90103. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  90104. # endif
  90105. # endif
  90106. #endif
  90107. #if 0 /* UNUSED */
  90108. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  90109. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  90110. #endif
  90111. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  90112. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  90113. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  90114. #endif
  90115. /*** End of inlined file: bitreader.h ***/
  90116. /*** Start of inlined file: crc.h ***/
  90117. #ifndef FLAC__PRIVATE__CRC_H
  90118. #define FLAC__PRIVATE__CRC_H
  90119. /* 8 bit CRC generator, MSB shifted first
  90120. ** polynomial = x^8 + x^2 + x^1 + x^0
  90121. ** init = 0
  90122. */
  90123. extern FLAC__byte const FLAC__crc8_table[256];
  90124. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  90125. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  90126. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  90127. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  90128. /* 16 bit CRC generator, MSB shifted first
  90129. ** polynomial = x^16 + x^15 + x^2 + x^0
  90130. ** init = 0
  90131. */
  90132. extern unsigned FLAC__crc16_table[256];
  90133. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  90134. /* this alternate may be faster on some systems/compilers */
  90135. #if 0
  90136. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  90137. #endif
  90138. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  90139. #endif
  90140. /*** End of inlined file: crc.h ***/
  90141. /* Things should be fastest when this matches the machine word size */
  90142. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  90143. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  90144. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  90145. typedef FLAC__uint32 brword;
  90146. #define FLAC__BYTES_PER_WORD 4
  90147. #define FLAC__BITS_PER_WORD 32
  90148. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  90149. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  90150. #if WORDS_BIGENDIAN
  90151. #define SWAP_BE_WORD_TO_HOST(x) (x)
  90152. #else
  90153. #if defined (_MSC_VER) && defined (_X86_)
  90154. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  90155. #else
  90156. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  90157. #endif
  90158. #endif
  90159. /* counts the # of zero MSBs in a word */
  90160. #define COUNT_ZERO_MSBS(word) ( \
  90161. (word) <= 0xffff ? \
  90162. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  90163. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  90164. )
  90165. /* this alternate might be slightly faster on some systems/compilers: */
  90166. #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])) )
  90167. /*
  90168. * This should be at least twice as large as the largest number of words
  90169. * required to represent any 'number' (in any encoding) you are going to
  90170. * read. With FLAC this is on the order of maybe a few hundred bits.
  90171. * If the buffer is smaller than that, the decoder won't be able to read
  90172. * in a whole number that is in a variable length encoding (e.g. Rice).
  90173. * But to be practical it should be at least 1K bytes.
  90174. *
  90175. * Increase this number to decrease the number of read callbacks, at the
  90176. * expense of using more memory. Or decrease for the reverse effect,
  90177. * keeping in mind the limit from the first paragraph. The optimal size
  90178. * also depends on the CPU cache size and other factors; some twiddling
  90179. * may be necessary to squeeze out the best performance.
  90180. */
  90181. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  90182. static const unsigned char byte_to_unary_table[] = {
  90183. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  90184. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  90185. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  90186. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  90187. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  90188. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  90189. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  90190. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  90191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  90192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  90193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  90194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  90195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  90196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  90197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  90198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  90199. };
  90200. #ifdef min
  90201. #undef min
  90202. #endif
  90203. #define min(x,y) ((x)<(y)?(x):(y))
  90204. #ifdef max
  90205. #undef max
  90206. #endif
  90207. #define max(x,y) ((x)>(y)?(x):(y))
  90208. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  90209. #ifdef _MSC_VER
  90210. #define FLAC__U64L(x) x
  90211. #else
  90212. #define FLAC__U64L(x) x##LLU
  90213. #endif
  90214. #ifndef FLaC__INLINE
  90215. #define FLaC__INLINE
  90216. #endif
  90217. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  90218. struct FLAC__BitReader {
  90219. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  90220. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  90221. brword *buffer;
  90222. unsigned capacity; /* in words */
  90223. unsigned words; /* # of completed words in buffer */
  90224. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  90225. unsigned consumed_words; /* #words ... */
  90226. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  90227. unsigned read_crc16; /* the running frame CRC */
  90228. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  90229. FLAC__BitReaderReadCallback read_callback;
  90230. void *client_data;
  90231. FLAC__CPUInfo cpu_info;
  90232. };
  90233. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  90234. {
  90235. register unsigned crc = br->read_crc16;
  90236. #if FLAC__BYTES_PER_WORD == 4
  90237. switch(br->crc16_align) {
  90238. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  90239. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  90240. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  90241. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  90242. }
  90243. #elif FLAC__BYTES_PER_WORD == 8
  90244. switch(br->crc16_align) {
  90245. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  90246. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  90247. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  90248. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  90249. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  90250. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  90251. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  90252. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  90253. }
  90254. #else
  90255. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  90256. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  90257. br->read_crc16 = crc;
  90258. #endif
  90259. br->crc16_align = 0;
  90260. }
  90261. /* would be static except it needs to be called by asm routines */
  90262. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  90263. {
  90264. unsigned start, end;
  90265. size_t bytes;
  90266. FLAC__byte *target;
  90267. /* first shift the unconsumed buffer data toward the front as much as possible */
  90268. if(br->consumed_words > 0) {
  90269. start = br->consumed_words;
  90270. end = br->words + (br->bytes? 1:0);
  90271. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  90272. br->words -= start;
  90273. br->consumed_words = 0;
  90274. }
  90275. /*
  90276. * set the target for reading, taking into account word alignment and endianness
  90277. */
  90278. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  90279. if(bytes == 0)
  90280. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  90281. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  90282. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  90283. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  90284. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  90285. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  90286. * ^^-------target, bytes=3
  90287. * on LE machines, have to byteswap the odd tail word so nothing is
  90288. * overwritten:
  90289. */
  90290. #if WORDS_BIGENDIAN
  90291. #else
  90292. if(br->bytes)
  90293. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  90294. #endif
  90295. /* now it looks like:
  90296. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  90297. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  90298. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  90299. * ^^-------target, bytes=3
  90300. */
  90301. /* read in the data; note that the callback may return a smaller number of bytes */
  90302. if(!br->read_callback(target, &bytes, br->client_data))
  90303. return false;
  90304. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  90305. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  90306. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  90307. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  90308. * now have to byteswap on LE machines:
  90309. */
  90310. #if WORDS_BIGENDIAN
  90311. #else
  90312. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  90313. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  90314. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  90315. start = br->words;
  90316. local_swap32_block_(br->buffer + start, end - start);
  90317. }
  90318. else
  90319. # endif
  90320. for(start = br->words; start < end; start++)
  90321. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  90322. #endif
  90323. /* now it looks like:
  90324. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  90325. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  90326. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  90327. * finally we'll update the reader values:
  90328. */
  90329. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  90330. br->words = end / FLAC__BYTES_PER_WORD;
  90331. br->bytes = end % FLAC__BYTES_PER_WORD;
  90332. return true;
  90333. }
  90334. /***********************************************************************
  90335. *
  90336. * Class constructor/destructor
  90337. *
  90338. ***********************************************************************/
  90339. FLAC__BitReader *FLAC__bitreader_new(void)
  90340. {
  90341. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  90342. /* calloc() implies:
  90343. memset(br, 0, sizeof(FLAC__BitReader));
  90344. br->buffer = 0;
  90345. br->capacity = 0;
  90346. br->words = br->bytes = 0;
  90347. br->consumed_words = br->consumed_bits = 0;
  90348. br->read_callback = 0;
  90349. br->client_data = 0;
  90350. */
  90351. return br;
  90352. }
  90353. void FLAC__bitreader_delete(FLAC__BitReader *br)
  90354. {
  90355. FLAC__ASSERT(0 != br);
  90356. FLAC__bitreader_free(br);
  90357. free(br);
  90358. }
  90359. /***********************************************************************
  90360. *
  90361. * Public class methods
  90362. *
  90363. ***********************************************************************/
  90364. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  90365. {
  90366. FLAC__ASSERT(0 != br);
  90367. br->words = br->bytes = 0;
  90368. br->consumed_words = br->consumed_bits = 0;
  90369. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  90370. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  90371. if(br->buffer == 0)
  90372. return false;
  90373. br->read_callback = rcb;
  90374. br->client_data = cd;
  90375. br->cpu_info = cpu;
  90376. return true;
  90377. }
  90378. void FLAC__bitreader_free(FLAC__BitReader *br)
  90379. {
  90380. FLAC__ASSERT(0 != br);
  90381. if(0 != br->buffer)
  90382. free(br->buffer);
  90383. br->buffer = 0;
  90384. br->capacity = 0;
  90385. br->words = br->bytes = 0;
  90386. br->consumed_words = br->consumed_bits = 0;
  90387. br->read_callback = 0;
  90388. br->client_data = 0;
  90389. }
  90390. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  90391. {
  90392. br->words = br->bytes = 0;
  90393. br->consumed_words = br->consumed_bits = 0;
  90394. return true;
  90395. }
  90396. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  90397. {
  90398. unsigned i, j;
  90399. if(br == 0) {
  90400. fprintf(out, "bitreader is NULL\n");
  90401. }
  90402. else {
  90403. 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);
  90404. for(i = 0; i < br->words; i++) {
  90405. fprintf(out, "%08X: ", i);
  90406. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  90407. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  90408. fprintf(out, ".");
  90409. else
  90410. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  90411. fprintf(out, "\n");
  90412. }
  90413. if(br->bytes > 0) {
  90414. fprintf(out, "%08X: ", i);
  90415. for(j = 0; j < br->bytes*8; j++)
  90416. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  90417. fprintf(out, ".");
  90418. else
  90419. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  90420. fprintf(out, "\n");
  90421. }
  90422. }
  90423. }
  90424. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  90425. {
  90426. FLAC__ASSERT(0 != br);
  90427. FLAC__ASSERT(0 != br->buffer);
  90428. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  90429. br->read_crc16 = (unsigned)seed;
  90430. br->crc16_align = br->consumed_bits;
  90431. }
  90432. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  90433. {
  90434. FLAC__ASSERT(0 != br);
  90435. FLAC__ASSERT(0 != br->buffer);
  90436. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  90437. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  90438. /* CRC any tail bytes in a partially-consumed word */
  90439. if(br->consumed_bits) {
  90440. const brword tail = br->buffer[br->consumed_words];
  90441. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  90442. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  90443. }
  90444. return br->read_crc16;
  90445. }
  90446. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  90447. {
  90448. return ((br->consumed_bits & 7) == 0);
  90449. }
  90450. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  90451. {
  90452. return 8 - (br->consumed_bits & 7);
  90453. }
  90454. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  90455. {
  90456. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  90457. }
  90458. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  90459. {
  90460. FLAC__ASSERT(0 != br);
  90461. FLAC__ASSERT(0 != br->buffer);
  90462. FLAC__ASSERT(bits <= 32);
  90463. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  90464. FLAC__ASSERT(br->consumed_words <= br->words);
  90465. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  90466. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  90467. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  90468. *val = 0;
  90469. return true;
  90470. }
  90471. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  90472. if(!bitreader_read_from_client_(br))
  90473. return false;
  90474. }
  90475. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  90476. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  90477. if(br->consumed_bits) {
  90478. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  90479. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  90480. const brword word = br->buffer[br->consumed_words];
  90481. if(bits < n) {
  90482. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  90483. br->consumed_bits += bits;
  90484. return true;
  90485. }
  90486. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  90487. bits -= n;
  90488. crc16_update_word_(br, word);
  90489. br->consumed_words++;
  90490. br->consumed_bits = 0;
  90491. 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 */
  90492. *val <<= bits;
  90493. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  90494. br->consumed_bits = bits;
  90495. }
  90496. return true;
  90497. }
  90498. else {
  90499. const brword word = br->buffer[br->consumed_words];
  90500. if(bits < FLAC__BITS_PER_WORD) {
  90501. *val = word >> (FLAC__BITS_PER_WORD-bits);
  90502. br->consumed_bits = bits;
  90503. return true;
  90504. }
  90505. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  90506. *val = word;
  90507. crc16_update_word_(br, word);
  90508. br->consumed_words++;
  90509. return true;
  90510. }
  90511. }
  90512. else {
  90513. /* in this case we're starting our read at a partial tail word;
  90514. * the reader has guaranteed that we have at least 'bits' bits
  90515. * available to read, which makes this case simpler.
  90516. */
  90517. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  90518. if(br->consumed_bits) {
  90519. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  90520. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  90521. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  90522. br->consumed_bits += bits;
  90523. return true;
  90524. }
  90525. else {
  90526. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  90527. br->consumed_bits += bits;
  90528. return true;
  90529. }
  90530. }
  90531. }
  90532. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  90533. {
  90534. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  90535. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  90536. return false;
  90537. /* sign-extend: */
  90538. *val <<= (32-bits);
  90539. *val >>= (32-bits);
  90540. return true;
  90541. }
  90542. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  90543. {
  90544. FLAC__uint32 hi, lo;
  90545. if(bits > 32) {
  90546. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  90547. return false;
  90548. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  90549. return false;
  90550. *val = hi;
  90551. *val <<= 32;
  90552. *val |= lo;
  90553. }
  90554. else {
  90555. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  90556. return false;
  90557. *val = lo;
  90558. }
  90559. return true;
  90560. }
  90561. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  90562. {
  90563. FLAC__uint32 x8, x32 = 0;
  90564. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  90565. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  90566. return false;
  90567. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  90568. return false;
  90569. x32 |= (x8 << 8);
  90570. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  90571. return false;
  90572. x32 |= (x8 << 16);
  90573. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  90574. return false;
  90575. x32 |= (x8 << 24);
  90576. *val = x32;
  90577. return true;
  90578. }
  90579. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  90580. {
  90581. /*
  90582. * OPT: a faster implementation is possible but probably not that useful
  90583. * since this is only called a couple of times in the metadata readers.
  90584. */
  90585. FLAC__ASSERT(0 != br);
  90586. FLAC__ASSERT(0 != br->buffer);
  90587. if(bits > 0) {
  90588. const unsigned n = br->consumed_bits & 7;
  90589. unsigned m;
  90590. FLAC__uint32 x;
  90591. if(n != 0) {
  90592. m = min(8-n, bits);
  90593. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  90594. return false;
  90595. bits -= m;
  90596. }
  90597. m = bits / 8;
  90598. if(m > 0) {
  90599. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  90600. return false;
  90601. bits %= 8;
  90602. }
  90603. if(bits > 0) {
  90604. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  90605. return false;
  90606. }
  90607. }
  90608. return true;
  90609. }
  90610. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  90611. {
  90612. FLAC__uint32 x;
  90613. FLAC__ASSERT(0 != br);
  90614. FLAC__ASSERT(0 != br->buffer);
  90615. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  90616. /* step 1: skip over partial head word to get word aligned */
  90617. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  90618. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  90619. return false;
  90620. nvals--;
  90621. }
  90622. if(0 == nvals)
  90623. return true;
  90624. /* step 2: skip whole words in chunks */
  90625. while(nvals >= FLAC__BYTES_PER_WORD) {
  90626. if(br->consumed_words < br->words) {
  90627. br->consumed_words++;
  90628. nvals -= FLAC__BYTES_PER_WORD;
  90629. }
  90630. else if(!bitreader_read_from_client_(br))
  90631. return false;
  90632. }
  90633. /* step 3: skip any remainder from partial tail bytes */
  90634. while(nvals) {
  90635. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  90636. return false;
  90637. nvals--;
  90638. }
  90639. return true;
  90640. }
  90641. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  90642. {
  90643. FLAC__uint32 x;
  90644. FLAC__ASSERT(0 != br);
  90645. FLAC__ASSERT(0 != br->buffer);
  90646. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  90647. /* step 1: read from partial head word to get word aligned */
  90648. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  90649. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  90650. return false;
  90651. *val++ = (FLAC__byte)x;
  90652. nvals--;
  90653. }
  90654. if(0 == nvals)
  90655. return true;
  90656. /* step 2: read whole words in chunks */
  90657. while(nvals >= FLAC__BYTES_PER_WORD) {
  90658. if(br->consumed_words < br->words) {
  90659. const brword word = br->buffer[br->consumed_words++];
  90660. #if FLAC__BYTES_PER_WORD == 4
  90661. val[0] = (FLAC__byte)(word >> 24);
  90662. val[1] = (FLAC__byte)(word >> 16);
  90663. val[2] = (FLAC__byte)(word >> 8);
  90664. val[3] = (FLAC__byte)word;
  90665. #elif FLAC__BYTES_PER_WORD == 8
  90666. val[0] = (FLAC__byte)(word >> 56);
  90667. val[1] = (FLAC__byte)(word >> 48);
  90668. val[2] = (FLAC__byte)(word >> 40);
  90669. val[3] = (FLAC__byte)(word >> 32);
  90670. val[4] = (FLAC__byte)(word >> 24);
  90671. val[5] = (FLAC__byte)(word >> 16);
  90672. val[6] = (FLAC__byte)(word >> 8);
  90673. val[7] = (FLAC__byte)word;
  90674. #else
  90675. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  90676. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  90677. #endif
  90678. val += FLAC__BYTES_PER_WORD;
  90679. nvals -= FLAC__BYTES_PER_WORD;
  90680. }
  90681. else if(!bitreader_read_from_client_(br))
  90682. return false;
  90683. }
  90684. /* step 3: read any remainder from partial tail bytes */
  90685. while(nvals) {
  90686. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  90687. return false;
  90688. *val++ = (FLAC__byte)x;
  90689. nvals--;
  90690. }
  90691. return true;
  90692. }
  90693. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  90694. #if 0 /* slow but readable version */
  90695. {
  90696. unsigned bit;
  90697. FLAC__ASSERT(0 != br);
  90698. FLAC__ASSERT(0 != br->buffer);
  90699. *val = 0;
  90700. while(1) {
  90701. if(!FLAC__bitreader_read_bit(br, &bit))
  90702. return false;
  90703. if(bit)
  90704. break;
  90705. else
  90706. *val++;
  90707. }
  90708. return true;
  90709. }
  90710. #else
  90711. {
  90712. unsigned i;
  90713. FLAC__ASSERT(0 != br);
  90714. FLAC__ASSERT(0 != br->buffer);
  90715. *val = 0;
  90716. while(1) {
  90717. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  90718. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  90719. if(b) {
  90720. i = COUNT_ZERO_MSBS(b);
  90721. *val += i;
  90722. i++;
  90723. br->consumed_bits += i;
  90724. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  90725. crc16_update_word_(br, br->buffer[br->consumed_words]);
  90726. br->consumed_words++;
  90727. br->consumed_bits = 0;
  90728. }
  90729. return true;
  90730. }
  90731. else {
  90732. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  90733. crc16_update_word_(br, br->buffer[br->consumed_words]);
  90734. br->consumed_words++;
  90735. br->consumed_bits = 0;
  90736. /* didn't find stop bit yet, have to keep going... */
  90737. }
  90738. }
  90739. /* at this point we've eaten up all the whole words; have to try
  90740. * reading through any tail bytes before calling the read callback.
  90741. * this is a repeat of the above logic adjusted for the fact we
  90742. * don't have a whole word. note though if the client is feeding
  90743. * us data a byte at a time (unlikely), br->consumed_bits may not
  90744. * be zero.
  90745. */
  90746. if(br->bytes) {
  90747. const unsigned end = br->bytes * 8;
  90748. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  90749. if(b) {
  90750. i = COUNT_ZERO_MSBS(b);
  90751. *val += i;
  90752. i++;
  90753. br->consumed_bits += i;
  90754. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  90755. return true;
  90756. }
  90757. else {
  90758. *val += end - br->consumed_bits;
  90759. br->consumed_bits += end;
  90760. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  90761. /* didn't find stop bit yet, have to keep going... */
  90762. }
  90763. }
  90764. if(!bitreader_read_from_client_(br))
  90765. return false;
  90766. }
  90767. }
  90768. #endif
  90769. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  90770. {
  90771. FLAC__uint32 lsbs = 0, msbs = 0;
  90772. unsigned uval;
  90773. FLAC__ASSERT(0 != br);
  90774. FLAC__ASSERT(0 != br->buffer);
  90775. FLAC__ASSERT(parameter <= 31);
  90776. /* read the unary MSBs and end bit */
  90777. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  90778. return false;
  90779. /* read the binary LSBs */
  90780. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  90781. return false;
  90782. /* compose the value */
  90783. uval = (msbs << parameter) | lsbs;
  90784. if(uval & 1)
  90785. *val = -((int)(uval >> 1)) - 1;
  90786. else
  90787. *val = (int)(uval >> 1);
  90788. return true;
  90789. }
  90790. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  90791. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  90792. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  90793. /* OPT: possibly faster version for use with MSVC */
  90794. #ifdef _MSC_VER
  90795. {
  90796. unsigned i;
  90797. unsigned uval = 0;
  90798. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  90799. /* try and get br->consumed_words and br->consumed_bits into register;
  90800. * must remember to flush them back to *br before calling other
  90801. * bitwriter functions that use them, and before returning */
  90802. register unsigned cwords;
  90803. register unsigned cbits;
  90804. FLAC__ASSERT(0 != br);
  90805. FLAC__ASSERT(0 != br->buffer);
  90806. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  90807. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  90808. FLAC__ASSERT(parameter < 32);
  90809. /* 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 */
  90810. if(nvals == 0)
  90811. return true;
  90812. cbits = br->consumed_bits;
  90813. cwords = br->consumed_words;
  90814. while(1) {
  90815. /* read unary part */
  90816. while(1) {
  90817. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  90818. brword b = br->buffer[cwords] << cbits;
  90819. if(b) {
  90820. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  90821. __asm {
  90822. bsr eax, b
  90823. not eax
  90824. and eax, 31
  90825. mov i, eax
  90826. }
  90827. #else
  90828. i = COUNT_ZERO_MSBS(b);
  90829. #endif
  90830. uval += i;
  90831. bits = parameter;
  90832. i++;
  90833. cbits += i;
  90834. if(cbits == FLAC__BITS_PER_WORD) {
  90835. crc16_update_word_(br, br->buffer[cwords]);
  90836. cwords++;
  90837. cbits = 0;
  90838. }
  90839. goto break1;
  90840. }
  90841. else {
  90842. uval += FLAC__BITS_PER_WORD - cbits;
  90843. crc16_update_word_(br, br->buffer[cwords]);
  90844. cwords++;
  90845. cbits = 0;
  90846. /* didn't find stop bit yet, have to keep going... */
  90847. }
  90848. }
  90849. /* at this point we've eaten up all the whole words; have to try
  90850. * reading through any tail bytes before calling the read callback.
  90851. * this is a repeat of the above logic adjusted for the fact we
  90852. * don't have a whole word. note though if the client is feeding
  90853. * us data a byte at a time (unlikely), br->consumed_bits may not
  90854. * be zero.
  90855. */
  90856. if(br->bytes) {
  90857. const unsigned end = br->bytes * 8;
  90858. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  90859. if(b) {
  90860. i = COUNT_ZERO_MSBS(b);
  90861. uval += i;
  90862. bits = parameter;
  90863. i++;
  90864. cbits += i;
  90865. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  90866. goto break1;
  90867. }
  90868. else {
  90869. uval += end - cbits;
  90870. cbits += end;
  90871. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  90872. /* didn't find stop bit yet, have to keep going... */
  90873. }
  90874. }
  90875. /* flush registers and read; bitreader_read_from_client_() does
  90876. * not touch br->consumed_bits at all but we still need to set
  90877. * it in case it fails and we have to return false.
  90878. */
  90879. br->consumed_bits = cbits;
  90880. br->consumed_words = cwords;
  90881. if(!bitreader_read_from_client_(br))
  90882. return false;
  90883. cwords = br->consumed_words;
  90884. }
  90885. break1:
  90886. /* read binary part */
  90887. FLAC__ASSERT(cwords <= br->words);
  90888. if(bits) {
  90889. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  90890. /* flush registers and read; bitreader_read_from_client_() does
  90891. * not touch br->consumed_bits at all but we still need to set
  90892. * it in case it fails and we have to return false.
  90893. */
  90894. br->consumed_bits = cbits;
  90895. br->consumed_words = cwords;
  90896. if(!bitreader_read_from_client_(br))
  90897. return false;
  90898. cwords = br->consumed_words;
  90899. }
  90900. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  90901. if(cbits) {
  90902. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  90903. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  90904. const brword word = br->buffer[cwords];
  90905. if(bits < n) {
  90906. uval <<= bits;
  90907. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  90908. cbits += bits;
  90909. goto break2;
  90910. }
  90911. uval <<= n;
  90912. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  90913. bits -= n;
  90914. crc16_update_word_(br, word);
  90915. cwords++;
  90916. cbits = 0;
  90917. 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 */
  90918. uval <<= bits;
  90919. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  90920. cbits = bits;
  90921. }
  90922. goto break2;
  90923. }
  90924. else {
  90925. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  90926. uval <<= bits;
  90927. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  90928. cbits = bits;
  90929. goto break2;
  90930. }
  90931. }
  90932. else {
  90933. /* in this case we're starting our read at a partial tail word;
  90934. * the reader has guaranteed that we have at least 'bits' bits
  90935. * available to read, which makes this case simpler.
  90936. */
  90937. uval <<= bits;
  90938. if(cbits) {
  90939. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  90940. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  90941. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  90942. cbits += bits;
  90943. goto break2;
  90944. }
  90945. else {
  90946. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  90947. cbits += bits;
  90948. goto break2;
  90949. }
  90950. }
  90951. }
  90952. break2:
  90953. /* compose the value */
  90954. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  90955. /* are we done? */
  90956. --nvals;
  90957. if(nvals == 0) {
  90958. br->consumed_bits = cbits;
  90959. br->consumed_words = cwords;
  90960. return true;
  90961. }
  90962. uval = 0;
  90963. ++vals;
  90964. }
  90965. }
  90966. #else
  90967. {
  90968. unsigned i;
  90969. unsigned uval = 0;
  90970. /* try and get br->consumed_words and br->consumed_bits into register;
  90971. * must remember to flush them back to *br before calling other
  90972. * bitwriter functions that use them, and before returning */
  90973. register unsigned cwords;
  90974. register unsigned cbits;
  90975. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  90976. FLAC__ASSERT(0 != br);
  90977. FLAC__ASSERT(0 != br->buffer);
  90978. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  90979. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  90980. FLAC__ASSERT(parameter < 32);
  90981. /* 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 */
  90982. if(nvals == 0)
  90983. return true;
  90984. cbits = br->consumed_bits;
  90985. cwords = br->consumed_words;
  90986. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  90987. while(1) {
  90988. /* read unary part */
  90989. while(1) {
  90990. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  90991. brword b = br->buffer[cwords] << cbits;
  90992. if(b) {
  90993. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  90994. asm volatile (
  90995. "bsrl %1, %0;"
  90996. "notl %0;"
  90997. "andl $31, %0;"
  90998. : "=r"(i)
  90999. : "r"(b)
  91000. );
  91001. #else
  91002. i = COUNT_ZERO_MSBS(b);
  91003. #endif
  91004. uval += i;
  91005. cbits += i;
  91006. cbits++; /* skip over stop bit */
  91007. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  91008. crc16_update_word_(br, br->buffer[cwords]);
  91009. cwords++;
  91010. cbits = 0;
  91011. }
  91012. goto break1;
  91013. }
  91014. else {
  91015. uval += FLAC__BITS_PER_WORD - cbits;
  91016. crc16_update_word_(br, br->buffer[cwords]);
  91017. cwords++;
  91018. cbits = 0;
  91019. /* didn't find stop bit yet, have to keep going... */
  91020. }
  91021. }
  91022. /* at this point we've eaten up all the whole words; have to try
  91023. * reading through any tail bytes before calling the read callback.
  91024. * this is a repeat of the above logic adjusted for the fact we
  91025. * don't have a whole word. note though if the client is feeding
  91026. * us data a byte at a time (unlikely), br->consumed_bits may not
  91027. * be zero.
  91028. */
  91029. if(br->bytes) {
  91030. const unsigned end = br->bytes * 8;
  91031. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  91032. if(b) {
  91033. i = COUNT_ZERO_MSBS(b);
  91034. uval += i;
  91035. cbits += i;
  91036. cbits++; /* skip over stop bit */
  91037. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  91038. goto break1;
  91039. }
  91040. else {
  91041. uval += end - cbits;
  91042. cbits += end;
  91043. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  91044. /* didn't find stop bit yet, have to keep going... */
  91045. }
  91046. }
  91047. /* flush registers and read; bitreader_read_from_client_() does
  91048. * not touch br->consumed_bits at all but we still need to set
  91049. * it in case it fails and we have to return false.
  91050. */
  91051. br->consumed_bits = cbits;
  91052. br->consumed_words = cwords;
  91053. if(!bitreader_read_from_client_(br))
  91054. return false;
  91055. cwords = br->consumed_words;
  91056. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  91057. /* + uval to offset our count by the # of unary bits already
  91058. * consumed before the read, because we will add these back
  91059. * in all at once at break1
  91060. */
  91061. }
  91062. break1:
  91063. ucbits -= uval;
  91064. ucbits--; /* account for stop bit */
  91065. /* read binary part */
  91066. FLAC__ASSERT(cwords <= br->words);
  91067. if(parameter) {
  91068. while(ucbits < parameter) {
  91069. /* flush registers and read; bitreader_read_from_client_() does
  91070. * not touch br->consumed_bits at all but we still need to set
  91071. * it in case it fails and we have to return false.
  91072. */
  91073. br->consumed_bits = cbits;
  91074. br->consumed_words = cwords;
  91075. if(!bitreader_read_from_client_(br))
  91076. return false;
  91077. cwords = br->consumed_words;
  91078. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  91079. }
  91080. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  91081. if(cbits) {
  91082. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  91083. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  91084. const brword word = br->buffer[cwords];
  91085. if(parameter < n) {
  91086. uval <<= parameter;
  91087. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  91088. cbits += parameter;
  91089. }
  91090. else {
  91091. uval <<= n;
  91092. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  91093. crc16_update_word_(br, word);
  91094. cwords++;
  91095. cbits = parameter - n;
  91096. 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 */
  91097. uval <<= cbits;
  91098. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  91099. }
  91100. }
  91101. }
  91102. else {
  91103. cbits = parameter;
  91104. uval <<= parameter;
  91105. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  91106. }
  91107. }
  91108. else {
  91109. /* in this case we're starting our read at a partial tail word;
  91110. * the reader has guaranteed that we have at least 'parameter'
  91111. * bits available to read, which makes this case simpler.
  91112. */
  91113. uval <<= parameter;
  91114. if(cbits) {
  91115. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  91116. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  91117. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  91118. cbits += parameter;
  91119. }
  91120. else {
  91121. cbits = parameter;
  91122. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  91123. }
  91124. }
  91125. }
  91126. ucbits -= parameter;
  91127. /* compose the value */
  91128. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  91129. /* are we done? */
  91130. --nvals;
  91131. if(nvals == 0) {
  91132. br->consumed_bits = cbits;
  91133. br->consumed_words = cwords;
  91134. return true;
  91135. }
  91136. uval = 0;
  91137. ++vals;
  91138. }
  91139. }
  91140. #endif
  91141. #if 0 /* UNUSED */
  91142. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  91143. {
  91144. FLAC__uint32 lsbs = 0, msbs = 0;
  91145. unsigned bit, uval, k;
  91146. FLAC__ASSERT(0 != br);
  91147. FLAC__ASSERT(0 != br->buffer);
  91148. k = FLAC__bitmath_ilog2(parameter);
  91149. /* read the unary MSBs and end bit */
  91150. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  91151. return false;
  91152. /* read the binary LSBs */
  91153. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  91154. return false;
  91155. if(parameter == 1u<<k) {
  91156. /* compose the value */
  91157. uval = (msbs << k) | lsbs;
  91158. }
  91159. else {
  91160. unsigned d = (1 << (k+1)) - parameter;
  91161. if(lsbs >= d) {
  91162. if(!FLAC__bitreader_read_bit(br, &bit))
  91163. return false;
  91164. lsbs <<= 1;
  91165. lsbs |= bit;
  91166. lsbs -= d;
  91167. }
  91168. /* compose the value */
  91169. uval = msbs * parameter + lsbs;
  91170. }
  91171. /* unfold unsigned to signed */
  91172. if(uval & 1)
  91173. *val = -((int)(uval >> 1)) - 1;
  91174. else
  91175. *val = (int)(uval >> 1);
  91176. return true;
  91177. }
  91178. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  91179. {
  91180. FLAC__uint32 lsbs, msbs = 0;
  91181. unsigned bit, k;
  91182. FLAC__ASSERT(0 != br);
  91183. FLAC__ASSERT(0 != br->buffer);
  91184. k = FLAC__bitmath_ilog2(parameter);
  91185. /* read the unary MSBs and end bit */
  91186. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  91187. return false;
  91188. /* read the binary LSBs */
  91189. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  91190. return false;
  91191. if(parameter == 1u<<k) {
  91192. /* compose the value */
  91193. *val = (msbs << k) | lsbs;
  91194. }
  91195. else {
  91196. unsigned d = (1 << (k+1)) - parameter;
  91197. if(lsbs >= d) {
  91198. if(!FLAC__bitreader_read_bit(br, &bit))
  91199. return false;
  91200. lsbs <<= 1;
  91201. lsbs |= bit;
  91202. lsbs -= d;
  91203. }
  91204. /* compose the value */
  91205. *val = msbs * parameter + lsbs;
  91206. }
  91207. return true;
  91208. }
  91209. #endif /* UNUSED */
  91210. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  91211. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  91212. {
  91213. FLAC__uint32 v = 0;
  91214. FLAC__uint32 x;
  91215. unsigned i;
  91216. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  91217. return false;
  91218. if(raw)
  91219. raw[(*rawlen)++] = (FLAC__byte)x;
  91220. if(!(x & 0x80)) { /* 0xxxxxxx */
  91221. v = x;
  91222. i = 0;
  91223. }
  91224. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  91225. v = x & 0x1F;
  91226. i = 1;
  91227. }
  91228. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  91229. v = x & 0x0F;
  91230. i = 2;
  91231. }
  91232. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  91233. v = x & 0x07;
  91234. i = 3;
  91235. }
  91236. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  91237. v = x & 0x03;
  91238. i = 4;
  91239. }
  91240. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  91241. v = x & 0x01;
  91242. i = 5;
  91243. }
  91244. else {
  91245. *val = 0xffffffff;
  91246. return true;
  91247. }
  91248. for( ; i; i--) {
  91249. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  91250. return false;
  91251. if(raw)
  91252. raw[(*rawlen)++] = (FLAC__byte)x;
  91253. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  91254. *val = 0xffffffff;
  91255. return true;
  91256. }
  91257. v <<= 6;
  91258. v |= (x & 0x3F);
  91259. }
  91260. *val = v;
  91261. return true;
  91262. }
  91263. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  91264. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  91265. {
  91266. FLAC__uint64 v = 0;
  91267. FLAC__uint32 x;
  91268. unsigned i;
  91269. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  91270. return false;
  91271. if(raw)
  91272. raw[(*rawlen)++] = (FLAC__byte)x;
  91273. if(!(x & 0x80)) { /* 0xxxxxxx */
  91274. v = x;
  91275. i = 0;
  91276. }
  91277. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  91278. v = x & 0x1F;
  91279. i = 1;
  91280. }
  91281. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  91282. v = x & 0x0F;
  91283. i = 2;
  91284. }
  91285. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  91286. v = x & 0x07;
  91287. i = 3;
  91288. }
  91289. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  91290. v = x & 0x03;
  91291. i = 4;
  91292. }
  91293. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  91294. v = x & 0x01;
  91295. i = 5;
  91296. }
  91297. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  91298. v = 0;
  91299. i = 6;
  91300. }
  91301. else {
  91302. *val = FLAC__U64L(0xffffffffffffffff);
  91303. return true;
  91304. }
  91305. for( ; i; i--) {
  91306. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  91307. return false;
  91308. if(raw)
  91309. raw[(*rawlen)++] = (FLAC__byte)x;
  91310. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  91311. *val = FLAC__U64L(0xffffffffffffffff);
  91312. return true;
  91313. }
  91314. v <<= 6;
  91315. v |= (x & 0x3F);
  91316. }
  91317. *val = v;
  91318. return true;
  91319. }
  91320. #endif
  91321. /*** End of inlined file: bitreader.c ***/
  91322. /*** Start of inlined file: bitwriter.c ***/
  91323. /*** Start of inlined file: juce_FlacHeader.h ***/
  91324. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91325. // tasks..
  91326. #define VERSION "1.2.1"
  91327. #define FLAC__NO_DLL 1
  91328. #if JUCE_MSVC
  91329. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91330. #endif
  91331. #if JUCE_MAC
  91332. #define FLAC__SYS_DARWIN 1
  91333. #endif
  91334. /*** End of inlined file: juce_FlacHeader.h ***/
  91335. #if JUCE_USE_FLAC
  91336. #if HAVE_CONFIG_H
  91337. # include <config.h>
  91338. #endif
  91339. #include <stdlib.h> /* for malloc() */
  91340. #include <string.h> /* for memcpy(), memset() */
  91341. #ifdef _MSC_VER
  91342. #include <winsock.h> /* for ntohl() */
  91343. #elif defined FLAC__SYS_DARWIN
  91344. #include <machine/endian.h> /* for ntohl() */
  91345. #elif defined __MINGW32__
  91346. #include <winsock.h> /* for ntohl() */
  91347. #else
  91348. #include <netinet/in.h> /* for ntohl() */
  91349. #endif
  91350. #if 0 /* UNUSED */
  91351. #endif
  91352. /*** Start of inlined file: bitwriter.h ***/
  91353. #ifndef FLAC__PRIVATE__BITWRITER_H
  91354. #define FLAC__PRIVATE__BITWRITER_H
  91355. #include <stdio.h> /* for FILE */
  91356. /*
  91357. * opaque structure definition
  91358. */
  91359. struct FLAC__BitWriter;
  91360. typedef struct FLAC__BitWriter FLAC__BitWriter;
  91361. /*
  91362. * construction, deletion, initialization, etc functions
  91363. */
  91364. FLAC__BitWriter *FLAC__bitwriter_new(void);
  91365. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  91366. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  91367. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  91368. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  91369. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  91370. /*
  91371. * CRC functions
  91372. *
  91373. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  91374. */
  91375. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  91376. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  91377. /*
  91378. * info functions
  91379. */
  91380. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  91381. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  91382. /*
  91383. * direct buffer access
  91384. *
  91385. * there may be no calls on the bitwriter between get and release.
  91386. * the bitwriter continues to own the returned buffer.
  91387. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  91388. */
  91389. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  91390. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  91391. /*
  91392. * write functions
  91393. */
  91394. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  91395. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  91396. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  91397. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  91398. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  91399. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  91400. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  91401. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  91402. #if 0 /* UNUSED */
  91403. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  91404. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  91405. #endif
  91406. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  91407. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  91408. #if 0 /* UNUSED */
  91409. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  91410. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  91411. #endif
  91412. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  91413. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  91414. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  91415. #endif
  91416. /*** End of inlined file: bitwriter.h ***/
  91417. /*** Start of inlined file: alloc.h ***/
  91418. #ifndef FLAC__SHARE__ALLOC_H
  91419. #define FLAC__SHARE__ALLOC_H
  91420. #if HAVE_CONFIG_H
  91421. # include <config.h>
  91422. #endif
  91423. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  91424. * before #including this file, otherwise SIZE_MAX might not be defined
  91425. */
  91426. #include <limits.h> /* for SIZE_MAX */
  91427. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  91428. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  91429. #endif
  91430. #include <stdlib.h> /* for size_t, malloc(), etc */
  91431. #ifndef SIZE_MAX
  91432. # ifndef SIZE_T_MAX
  91433. # ifdef _MSC_VER
  91434. # define SIZE_T_MAX UINT_MAX
  91435. # else
  91436. # error
  91437. # endif
  91438. # endif
  91439. # define SIZE_MAX SIZE_T_MAX
  91440. #endif
  91441. #ifndef FLaC__INLINE
  91442. #define FLaC__INLINE
  91443. #endif
  91444. /* avoid malloc()ing 0 bytes, see:
  91445. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  91446. */
  91447. static FLaC__INLINE void *safe_malloc_(size_t size)
  91448. {
  91449. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  91450. if(!size)
  91451. size++;
  91452. return malloc(size);
  91453. }
  91454. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  91455. {
  91456. if(!nmemb || !size)
  91457. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  91458. return calloc(nmemb, size);
  91459. }
  91460. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  91461. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  91462. {
  91463. size2 += size1;
  91464. if(size2 < size1)
  91465. return 0;
  91466. return safe_malloc_(size2);
  91467. }
  91468. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  91469. {
  91470. size2 += size1;
  91471. if(size2 < size1)
  91472. return 0;
  91473. size3 += size2;
  91474. if(size3 < size2)
  91475. return 0;
  91476. return safe_malloc_(size3);
  91477. }
  91478. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  91479. {
  91480. size2 += size1;
  91481. if(size2 < size1)
  91482. return 0;
  91483. size3 += size2;
  91484. if(size3 < size2)
  91485. return 0;
  91486. size4 += size3;
  91487. if(size4 < size3)
  91488. return 0;
  91489. return safe_malloc_(size4);
  91490. }
  91491. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  91492. #if 0
  91493. needs support for cases where sizeof(size_t) != 4
  91494. {
  91495. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  91496. if(sizeof(size_t) == 4) {
  91497. if ((double)size1 * (double)size2 < 4294967296.0)
  91498. return malloc(size1*size2);
  91499. }
  91500. return 0;
  91501. }
  91502. #else
  91503. /* better? */
  91504. {
  91505. if(!size1 || !size2)
  91506. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  91507. if(size1 > SIZE_MAX / size2)
  91508. return 0;
  91509. return malloc(size1*size2);
  91510. }
  91511. #endif
  91512. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  91513. {
  91514. if(!size1 || !size2 || !size3)
  91515. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  91516. if(size1 > SIZE_MAX / size2)
  91517. return 0;
  91518. size1 *= size2;
  91519. if(size1 > SIZE_MAX / size3)
  91520. return 0;
  91521. return malloc(size1*size3);
  91522. }
  91523. /* size1*size2 + size3 */
  91524. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  91525. {
  91526. if(!size1 || !size2)
  91527. return safe_malloc_(size3);
  91528. if(size1 > SIZE_MAX / size2)
  91529. return 0;
  91530. return safe_malloc_add_2op_(size1*size2, size3);
  91531. }
  91532. /* size1 * (size2 + size3) */
  91533. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  91534. {
  91535. if(!size1 || (!size2 && !size3))
  91536. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  91537. size2 += size3;
  91538. if(size2 < size3)
  91539. return 0;
  91540. return safe_malloc_mul_2op_(size1, size2);
  91541. }
  91542. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  91543. {
  91544. size2 += size1;
  91545. if(size2 < size1)
  91546. return 0;
  91547. return realloc(ptr, size2);
  91548. }
  91549. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  91550. {
  91551. size2 += size1;
  91552. if(size2 < size1)
  91553. return 0;
  91554. size3 += size2;
  91555. if(size3 < size2)
  91556. return 0;
  91557. return realloc(ptr, size3);
  91558. }
  91559. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  91560. {
  91561. size2 += size1;
  91562. if(size2 < size1)
  91563. return 0;
  91564. size3 += size2;
  91565. if(size3 < size2)
  91566. return 0;
  91567. size4 += size3;
  91568. if(size4 < size3)
  91569. return 0;
  91570. return realloc(ptr, size4);
  91571. }
  91572. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  91573. {
  91574. if(!size1 || !size2)
  91575. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  91576. if(size1 > SIZE_MAX / size2)
  91577. return 0;
  91578. return realloc(ptr, size1*size2);
  91579. }
  91580. /* size1 * (size2 + size3) */
  91581. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  91582. {
  91583. if(!size1 || (!size2 && !size3))
  91584. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  91585. size2 += size3;
  91586. if(size2 < size3)
  91587. return 0;
  91588. return safe_realloc_mul_2op_(ptr, size1, size2);
  91589. }
  91590. #endif
  91591. /*** End of inlined file: alloc.h ***/
  91592. /* Things should be fastest when this matches the machine word size */
  91593. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  91594. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  91595. typedef FLAC__uint32 bwword;
  91596. #define FLAC__BYTES_PER_WORD 4
  91597. #define FLAC__BITS_PER_WORD 32
  91598. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  91599. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  91600. #if WORDS_BIGENDIAN
  91601. #define SWAP_BE_WORD_TO_HOST(x) (x)
  91602. #else
  91603. #ifdef _MSC_VER
  91604. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  91605. #else
  91606. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  91607. #endif
  91608. #endif
  91609. /*
  91610. * The default capacity here doesn't matter too much. The buffer always grows
  91611. * to hold whatever is written to it. Usually the encoder will stop adding at
  91612. * a frame or metadata block, then write that out and clear the buffer for the
  91613. * next one.
  91614. */
  91615. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  91616. /* When growing, increment 4K at a time */
  91617. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  91618. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  91619. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  91620. #ifdef min
  91621. #undef min
  91622. #endif
  91623. #define min(x,y) ((x)<(y)?(x):(y))
  91624. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  91625. #ifdef _MSC_VER
  91626. #define FLAC__U64L(x) x
  91627. #else
  91628. #define FLAC__U64L(x) x##LLU
  91629. #endif
  91630. #ifndef FLaC__INLINE
  91631. #define FLaC__INLINE
  91632. #endif
  91633. struct FLAC__BitWriter {
  91634. bwword *buffer;
  91635. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  91636. unsigned capacity; /* capacity of buffer in words */
  91637. unsigned words; /* # of complete words in buffer */
  91638. unsigned bits; /* # of used bits in accum */
  91639. };
  91640. /* * WATCHOUT: The current implementation only grows the buffer. */
  91641. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  91642. {
  91643. unsigned new_capacity;
  91644. bwword *new_buffer;
  91645. FLAC__ASSERT(0 != bw);
  91646. FLAC__ASSERT(0 != bw->buffer);
  91647. /* calculate total words needed to store 'bits_to_add' additional bits */
  91648. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  91649. /* it's possible (due to pessimism in the growth estimation that
  91650. * leads to this call) that we don't actually need to grow
  91651. */
  91652. if(bw->capacity >= new_capacity)
  91653. return true;
  91654. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  91655. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  91656. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  91657. /* make sure we got everything right */
  91658. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  91659. FLAC__ASSERT(new_capacity > bw->capacity);
  91660. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  91661. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  91662. if(new_buffer == 0)
  91663. return false;
  91664. bw->buffer = new_buffer;
  91665. bw->capacity = new_capacity;
  91666. return true;
  91667. }
  91668. /***********************************************************************
  91669. *
  91670. * Class constructor/destructor
  91671. *
  91672. ***********************************************************************/
  91673. FLAC__BitWriter *FLAC__bitwriter_new(void)
  91674. {
  91675. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  91676. /* note that calloc() sets all members to 0 for us */
  91677. return bw;
  91678. }
  91679. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  91680. {
  91681. FLAC__ASSERT(0 != bw);
  91682. FLAC__bitwriter_free(bw);
  91683. free(bw);
  91684. }
  91685. /***********************************************************************
  91686. *
  91687. * Public class methods
  91688. *
  91689. ***********************************************************************/
  91690. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  91691. {
  91692. FLAC__ASSERT(0 != bw);
  91693. bw->words = bw->bits = 0;
  91694. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  91695. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  91696. if(bw->buffer == 0)
  91697. return false;
  91698. return true;
  91699. }
  91700. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  91701. {
  91702. FLAC__ASSERT(0 != bw);
  91703. if(0 != bw->buffer)
  91704. free(bw->buffer);
  91705. bw->buffer = 0;
  91706. bw->capacity = 0;
  91707. bw->words = bw->bits = 0;
  91708. }
  91709. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  91710. {
  91711. bw->words = bw->bits = 0;
  91712. }
  91713. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  91714. {
  91715. unsigned i, j;
  91716. if(bw == 0) {
  91717. fprintf(out, "bitwriter is NULL\n");
  91718. }
  91719. else {
  91720. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  91721. for(i = 0; i < bw->words; i++) {
  91722. fprintf(out, "%08X: ", i);
  91723. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  91724. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  91725. fprintf(out, "\n");
  91726. }
  91727. if(bw->bits > 0) {
  91728. fprintf(out, "%08X: ", i);
  91729. for(j = 0; j < bw->bits; j++)
  91730. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  91731. fprintf(out, "\n");
  91732. }
  91733. }
  91734. }
  91735. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  91736. {
  91737. const FLAC__byte *buffer;
  91738. size_t bytes;
  91739. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  91740. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  91741. return false;
  91742. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  91743. FLAC__bitwriter_release_buffer(bw);
  91744. return true;
  91745. }
  91746. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  91747. {
  91748. const FLAC__byte *buffer;
  91749. size_t bytes;
  91750. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  91751. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  91752. return false;
  91753. *crc = FLAC__crc8(buffer, bytes);
  91754. FLAC__bitwriter_release_buffer(bw);
  91755. return true;
  91756. }
  91757. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  91758. {
  91759. return ((bw->bits & 7) == 0);
  91760. }
  91761. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  91762. {
  91763. return FLAC__TOTAL_BITS(bw);
  91764. }
  91765. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  91766. {
  91767. FLAC__ASSERT((bw->bits & 7) == 0);
  91768. /* double protection */
  91769. if(bw->bits & 7)
  91770. return false;
  91771. /* if we have bits in the accumulator we have to flush those to the buffer first */
  91772. if(bw->bits) {
  91773. FLAC__ASSERT(bw->words <= bw->capacity);
  91774. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  91775. return false;
  91776. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  91777. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  91778. }
  91779. /* now we can just return what we have */
  91780. *buffer = (FLAC__byte*)bw->buffer;
  91781. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  91782. return true;
  91783. }
  91784. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  91785. {
  91786. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  91787. * get-mode' flag could be added everywhere and then cleared here
  91788. */
  91789. (void)bw;
  91790. }
  91791. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  91792. {
  91793. unsigned n;
  91794. FLAC__ASSERT(0 != bw);
  91795. FLAC__ASSERT(0 != bw->buffer);
  91796. if(bits == 0)
  91797. return true;
  91798. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  91799. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  91800. return false;
  91801. /* first part gets to word alignment */
  91802. if(bw->bits) {
  91803. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  91804. bw->accum <<= n;
  91805. bits -= n;
  91806. bw->bits += n;
  91807. if(bw->bits == FLAC__BITS_PER_WORD) {
  91808. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  91809. bw->bits = 0;
  91810. }
  91811. else
  91812. return true;
  91813. }
  91814. /* do whole words */
  91815. while(bits >= FLAC__BITS_PER_WORD) {
  91816. bw->buffer[bw->words++] = 0;
  91817. bits -= FLAC__BITS_PER_WORD;
  91818. }
  91819. /* do any leftovers */
  91820. if(bits > 0) {
  91821. bw->accum = 0;
  91822. bw->bits = bits;
  91823. }
  91824. return true;
  91825. }
  91826. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  91827. {
  91828. register unsigned left;
  91829. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  91830. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  91831. FLAC__ASSERT(0 != bw);
  91832. FLAC__ASSERT(0 != bw->buffer);
  91833. FLAC__ASSERT(bits <= 32);
  91834. if(bits == 0)
  91835. return true;
  91836. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  91837. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  91838. return false;
  91839. left = FLAC__BITS_PER_WORD - bw->bits;
  91840. if(bits < left) {
  91841. bw->accum <<= bits;
  91842. bw->accum |= val;
  91843. bw->bits += bits;
  91844. }
  91845. 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 */
  91846. bw->accum <<= left;
  91847. bw->accum |= val >> (bw->bits = bits - left);
  91848. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  91849. bw->accum = val;
  91850. }
  91851. else {
  91852. bw->accum = val;
  91853. bw->bits = 0;
  91854. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  91855. }
  91856. return true;
  91857. }
  91858. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  91859. {
  91860. /* zero-out unused bits */
  91861. if(bits < 32)
  91862. val &= (~(0xffffffff << bits));
  91863. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  91864. }
  91865. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  91866. {
  91867. /* this could be a little faster but it's not used for much */
  91868. if(bits > 32) {
  91869. return
  91870. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  91871. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  91872. }
  91873. else
  91874. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  91875. }
  91876. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  91877. {
  91878. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  91879. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  91880. return false;
  91881. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  91882. return false;
  91883. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  91884. return false;
  91885. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  91886. return false;
  91887. return true;
  91888. }
  91889. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  91890. {
  91891. unsigned i;
  91892. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  91893. for(i = 0; i < nvals; i++) {
  91894. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  91895. return false;
  91896. }
  91897. return true;
  91898. }
  91899. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  91900. {
  91901. if(val < 32)
  91902. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  91903. else
  91904. return
  91905. FLAC__bitwriter_write_zeroes(bw, val) &&
  91906. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  91907. }
  91908. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  91909. {
  91910. FLAC__uint32 uval;
  91911. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  91912. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  91913. uval = (val<<1) ^ (val>>31);
  91914. return 1 + parameter + (uval >> parameter);
  91915. }
  91916. #if 0 /* UNUSED */
  91917. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  91918. {
  91919. unsigned bits, msbs, uval;
  91920. unsigned k;
  91921. FLAC__ASSERT(parameter > 0);
  91922. /* fold signed to unsigned */
  91923. if(val < 0)
  91924. uval = (unsigned)(((-(++val)) << 1) + 1);
  91925. else
  91926. uval = (unsigned)(val << 1);
  91927. k = FLAC__bitmath_ilog2(parameter);
  91928. if(parameter == 1u<<k) {
  91929. FLAC__ASSERT(k <= 30);
  91930. msbs = uval >> k;
  91931. bits = 1 + k + msbs;
  91932. }
  91933. else {
  91934. unsigned q, r, d;
  91935. d = (1 << (k+1)) - parameter;
  91936. q = uval / parameter;
  91937. r = uval - (q * parameter);
  91938. bits = 1 + q + k;
  91939. if(r >= d)
  91940. bits++;
  91941. }
  91942. return bits;
  91943. }
  91944. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  91945. {
  91946. unsigned bits, msbs;
  91947. unsigned k;
  91948. FLAC__ASSERT(parameter > 0);
  91949. k = FLAC__bitmath_ilog2(parameter);
  91950. if(parameter == 1u<<k) {
  91951. FLAC__ASSERT(k <= 30);
  91952. msbs = uval >> k;
  91953. bits = 1 + k + msbs;
  91954. }
  91955. else {
  91956. unsigned q, r, d;
  91957. d = (1 << (k+1)) - parameter;
  91958. q = uval / parameter;
  91959. r = uval - (q * parameter);
  91960. bits = 1 + q + k;
  91961. if(r >= d)
  91962. bits++;
  91963. }
  91964. return bits;
  91965. }
  91966. #endif /* UNUSED */
  91967. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  91968. {
  91969. unsigned total_bits, interesting_bits, msbs;
  91970. FLAC__uint32 uval, pattern;
  91971. FLAC__ASSERT(0 != bw);
  91972. FLAC__ASSERT(0 != bw->buffer);
  91973. FLAC__ASSERT(parameter < 8*sizeof(uval));
  91974. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  91975. uval = (val<<1) ^ (val>>31);
  91976. msbs = uval >> parameter;
  91977. interesting_bits = 1 + parameter;
  91978. total_bits = interesting_bits + msbs;
  91979. pattern = 1 << parameter; /* the unary end bit */
  91980. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  91981. if(total_bits <= 32)
  91982. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  91983. else
  91984. return
  91985. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  91986. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  91987. }
  91988. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  91989. {
  91990. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  91991. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  91992. FLAC__uint32 uval;
  91993. unsigned left;
  91994. const unsigned lsbits = 1 + parameter;
  91995. unsigned msbits;
  91996. FLAC__ASSERT(0 != bw);
  91997. FLAC__ASSERT(0 != bw->buffer);
  91998. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  91999. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  92000. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  92001. while(nvals) {
  92002. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  92003. uval = (*vals<<1) ^ (*vals>>31);
  92004. msbits = uval >> parameter;
  92005. #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) */
  92006. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  92007. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  92008. bw->bits = bw->bits + msbits + lsbits;
  92009. uval |= mask1; /* set stop bit */
  92010. uval &= mask2; /* mask off unused top bits */
  92011. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  92012. bw->accum <<= msbits;
  92013. bw->accum <<= lsbits;
  92014. bw->accum |= uval;
  92015. if(bw->bits == FLAC__BITS_PER_WORD) {
  92016. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  92017. bw->bits = 0;
  92018. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  92019. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  92020. FLAC__ASSERT(bw->capacity == bw->words);
  92021. return false;
  92022. }
  92023. }
  92024. }
  92025. else {
  92026. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  92027. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  92028. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  92029. bw->bits = bw->bits + msbits + lsbits;
  92030. uval |= mask1; /* set stop bit */
  92031. uval &= mask2; /* mask off unused top bits */
  92032. bw->accum <<= msbits + lsbits;
  92033. bw->accum |= uval;
  92034. }
  92035. else {
  92036. #endif
  92037. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  92038. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  92039. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  92040. return false;
  92041. if(msbits) {
  92042. /* first part gets to word alignment */
  92043. if(bw->bits) {
  92044. left = FLAC__BITS_PER_WORD - bw->bits;
  92045. if(msbits < left) {
  92046. bw->accum <<= msbits;
  92047. bw->bits += msbits;
  92048. goto break1;
  92049. }
  92050. else {
  92051. bw->accum <<= left;
  92052. msbits -= left;
  92053. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  92054. bw->bits = 0;
  92055. }
  92056. }
  92057. /* do whole words */
  92058. while(msbits >= FLAC__BITS_PER_WORD) {
  92059. bw->buffer[bw->words++] = 0;
  92060. msbits -= FLAC__BITS_PER_WORD;
  92061. }
  92062. /* do any leftovers */
  92063. if(msbits > 0) {
  92064. bw->accum = 0;
  92065. bw->bits = msbits;
  92066. }
  92067. }
  92068. break1:
  92069. uval |= mask1; /* set stop bit */
  92070. uval &= mask2; /* mask off unused top bits */
  92071. left = FLAC__BITS_PER_WORD - bw->bits;
  92072. if(lsbits < left) {
  92073. bw->accum <<= lsbits;
  92074. bw->accum |= uval;
  92075. bw->bits += lsbits;
  92076. }
  92077. else {
  92078. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  92079. * be > lsbits (because of previous assertions) so it would have
  92080. * triggered the (lsbits<left) case above.
  92081. */
  92082. FLAC__ASSERT(bw->bits);
  92083. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  92084. bw->accum <<= left;
  92085. bw->accum |= uval >> (bw->bits = lsbits - left);
  92086. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  92087. bw->accum = uval;
  92088. }
  92089. #if 1
  92090. }
  92091. #endif
  92092. vals++;
  92093. nvals--;
  92094. }
  92095. return true;
  92096. }
  92097. #if 0 /* UNUSED */
  92098. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  92099. {
  92100. unsigned total_bits, msbs, uval;
  92101. unsigned k;
  92102. FLAC__ASSERT(0 != bw);
  92103. FLAC__ASSERT(0 != bw->buffer);
  92104. FLAC__ASSERT(parameter > 0);
  92105. /* fold signed to unsigned */
  92106. if(val < 0)
  92107. uval = (unsigned)(((-(++val)) << 1) + 1);
  92108. else
  92109. uval = (unsigned)(val << 1);
  92110. k = FLAC__bitmath_ilog2(parameter);
  92111. if(parameter == 1u<<k) {
  92112. unsigned pattern;
  92113. FLAC__ASSERT(k <= 30);
  92114. msbs = uval >> k;
  92115. total_bits = 1 + k + msbs;
  92116. pattern = 1 << k; /* the unary end bit */
  92117. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  92118. if(total_bits <= 32) {
  92119. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  92120. return false;
  92121. }
  92122. else {
  92123. /* write the unary MSBs */
  92124. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  92125. return false;
  92126. /* write the unary end bit and binary LSBs */
  92127. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  92128. return false;
  92129. }
  92130. }
  92131. else {
  92132. unsigned q, r, d;
  92133. d = (1 << (k+1)) - parameter;
  92134. q = uval / parameter;
  92135. r = uval - (q * parameter);
  92136. /* write the unary MSBs */
  92137. if(!FLAC__bitwriter_write_zeroes(bw, q))
  92138. return false;
  92139. /* write the unary end bit */
  92140. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  92141. return false;
  92142. /* write the binary LSBs */
  92143. if(r >= d) {
  92144. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  92145. return false;
  92146. }
  92147. else {
  92148. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  92149. return false;
  92150. }
  92151. }
  92152. return true;
  92153. }
  92154. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  92155. {
  92156. unsigned total_bits, msbs;
  92157. unsigned k;
  92158. FLAC__ASSERT(0 != bw);
  92159. FLAC__ASSERT(0 != bw->buffer);
  92160. FLAC__ASSERT(parameter > 0);
  92161. k = FLAC__bitmath_ilog2(parameter);
  92162. if(parameter == 1u<<k) {
  92163. unsigned pattern;
  92164. FLAC__ASSERT(k <= 30);
  92165. msbs = uval >> k;
  92166. total_bits = 1 + k + msbs;
  92167. pattern = 1 << k; /* the unary end bit */
  92168. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  92169. if(total_bits <= 32) {
  92170. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  92171. return false;
  92172. }
  92173. else {
  92174. /* write the unary MSBs */
  92175. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  92176. return false;
  92177. /* write the unary end bit and binary LSBs */
  92178. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  92179. return false;
  92180. }
  92181. }
  92182. else {
  92183. unsigned q, r, d;
  92184. d = (1 << (k+1)) - parameter;
  92185. q = uval / parameter;
  92186. r = uval - (q * parameter);
  92187. /* write the unary MSBs */
  92188. if(!FLAC__bitwriter_write_zeroes(bw, q))
  92189. return false;
  92190. /* write the unary end bit */
  92191. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  92192. return false;
  92193. /* write the binary LSBs */
  92194. if(r >= d) {
  92195. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  92196. return false;
  92197. }
  92198. else {
  92199. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  92200. return false;
  92201. }
  92202. }
  92203. return true;
  92204. }
  92205. #endif /* UNUSED */
  92206. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  92207. {
  92208. FLAC__bool ok = 1;
  92209. FLAC__ASSERT(0 != bw);
  92210. FLAC__ASSERT(0 != bw->buffer);
  92211. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  92212. if(val < 0x80) {
  92213. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  92214. }
  92215. else if(val < 0x800) {
  92216. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  92217. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  92218. }
  92219. else if(val < 0x10000) {
  92220. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  92221. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  92222. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  92223. }
  92224. else if(val < 0x200000) {
  92225. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  92226. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  92227. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  92228. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  92229. }
  92230. else if(val < 0x4000000) {
  92231. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  92232. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  92233. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  92234. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  92235. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  92236. }
  92237. else {
  92238. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  92239. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  92240. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  92241. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  92242. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  92243. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  92244. }
  92245. return ok;
  92246. }
  92247. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  92248. {
  92249. FLAC__bool ok = 1;
  92250. FLAC__ASSERT(0 != bw);
  92251. FLAC__ASSERT(0 != bw->buffer);
  92252. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  92253. if(val < 0x80) {
  92254. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  92255. }
  92256. else if(val < 0x800) {
  92257. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  92258. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  92259. }
  92260. else if(val < 0x10000) {
  92261. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  92262. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  92263. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  92264. }
  92265. else if(val < 0x200000) {
  92266. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  92267. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  92268. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  92269. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  92270. }
  92271. else if(val < 0x4000000) {
  92272. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  92273. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  92274. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  92275. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  92276. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  92277. }
  92278. else if(val < 0x80000000) {
  92279. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  92280. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  92281. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  92282. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  92283. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  92284. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  92285. }
  92286. else {
  92287. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  92288. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  92289. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  92290. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  92291. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  92292. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  92293. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  92294. }
  92295. return ok;
  92296. }
  92297. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  92298. {
  92299. /* 0-pad to byte boundary */
  92300. if(bw->bits & 7u)
  92301. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  92302. else
  92303. return true;
  92304. }
  92305. #endif
  92306. /*** End of inlined file: bitwriter.c ***/
  92307. /*** Start of inlined file: cpu.c ***/
  92308. /*** Start of inlined file: juce_FlacHeader.h ***/
  92309. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92310. // tasks..
  92311. #define VERSION "1.2.1"
  92312. #define FLAC__NO_DLL 1
  92313. #if JUCE_MSVC
  92314. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92315. #endif
  92316. #if JUCE_MAC
  92317. #define FLAC__SYS_DARWIN 1
  92318. #endif
  92319. /*** End of inlined file: juce_FlacHeader.h ***/
  92320. #if JUCE_USE_FLAC
  92321. #if HAVE_CONFIG_H
  92322. # include <config.h>
  92323. #endif
  92324. #include <stdlib.h>
  92325. #include <stdio.h>
  92326. #if defined FLAC__CPU_IA32
  92327. # include <signal.h>
  92328. #elif defined FLAC__CPU_PPC
  92329. # if !defined FLAC__NO_ASM
  92330. # if defined FLAC__SYS_DARWIN
  92331. # include <sys/sysctl.h>
  92332. # include <mach/mach.h>
  92333. # include <mach/mach_host.h>
  92334. # include <mach/host_info.h>
  92335. # include <mach/machine.h>
  92336. # ifndef CPU_SUBTYPE_POWERPC_970
  92337. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  92338. # endif
  92339. # else /* FLAC__SYS_DARWIN */
  92340. # include <signal.h>
  92341. # include <setjmp.h>
  92342. static sigjmp_buf jmpbuf;
  92343. static volatile sig_atomic_t canjump = 0;
  92344. static void sigill_handler (int sig)
  92345. {
  92346. if (!canjump) {
  92347. signal (sig, SIG_DFL);
  92348. raise (sig);
  92349. }
  92350. canjump = 0;
  92351. siglongjmp (jmpbuf, 1);
  92352. }
  92353. # endif /* FLAC__SYS_DARWIN */
  92354. # endif /* FLAC__NO_ASM */
  92355. #endif /* FLAC__CPU_PPC */
  92356. #if defined (__NetBSD__) || defined(__OpenBSD__)
  92357. #include <sys/param.h>
  92358. #include <sys/sysctl.h>
  92359. #include <machine/cpu.h>
  92360. #endif
  92361. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  92362. #include <sys/types.h>
  92363. #include <sys/sysctl.h>
  92364. #endif
  92365. #if defined(__APPLE__)
  92366. /* how to get sysctlbyname()? */
  92367. #endif
  92368. /* these are flags in EDX of CPUID AX=00000001 */
  92369. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  92370. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  92371. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  92372. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  92373. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  92374. /* these are flags in ECX of CPUID AX=00000001 */
  92375. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  92376. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  92377. /* these are flags in EDX of CPUID AX=80000001 */
  92378. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  92379. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  92380. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  92381. /*
  92382. * Extra stuff needed for detection of OS support for SSE on IA-32
  92383. */
  92384. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  92385. # if defined(__linux__)
  92386. /*
  92387. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  92388. * modify the return address to jump over the offending SSE instruction
  92389. * and also the operation following it that indicates the instruction
  92390. * executed successfully. In this way we use no global variables and
  92391. * stay thread-safe.
  92392. *
  92393. * 3 + 3 + 6:
  92394. * 3 bytes for "xorps xmm0,xmm0"
  92395. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  92396. * 6 bytes extra in case our estimate is wrong
  92397. * 12 bytes puts us in the NOP "landing zone"
  92398. */
  92399. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  92400. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  92401. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  92402. {
  92403. (void)signal;
  92404. sc.eip += 3 + 3 + 6;
  92405. }
  92406. # else
  92407. # include <sys/ucontext.h>
  92408. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  92409. {
  92410. (void)signal, (void)si;
  92411. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  92412. }
  92413. # endif
  92414. # elif defined(_MSC_VER)
  92415. # include <windows.h>
  92416. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  92417. # ifdef USE_TRY_CATCH_FLAVOR
  92418. # else
  92419. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  92420. {
  92421. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  92422. ep->ContextRecord->Eip += 3 + 3 + 6;
  92423. return EXCEPTION_CONTINUE_EXECUTION;
  92424. }
  92425. return EXCEPTION_CONTINUE_SEARCH;
  92426. }
  92427. # endif
  92428. # endif
  92429. #endif
  92430. void FLAC__cpu_info(FLAC__CPUInfo *info)
  92431. {
  92432. /*
  92433. * IA32-specific
  92434. */
  92435. #ifdef FLAC__CPU_IA32
  92436. info->type = FLAC__CPUINFO_TYPE_IA32;
  92437. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  92438. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  92439. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  92440. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  92441. info->data.ia32.cmov = false;
  92442. info->data.ia32.mmx = false;
  92443. info->data.ia32.fxsr = false;
  92444. info->data.ia32.sse = false;
  92445. info->data.ia32.sse2 = false;
  92446. info->data.ia32.sse3 = false;
  92447. info->data.ia32.ssse3 = false;
  92448. info->data.ia32._3dnow = false;
  92449. info->data.ia32.ext3dnow = false;
  92450. info->data.ia32.extmmx = false;
  92451. if(info->data.ia32.cpuid) {
  92452. /* http://www.sandpile.org/ia32/cpuid.htm */
  92453. FLAC__uint32 flags_edx, flags_ecx;
  92454. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  92455. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  92456. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  92457. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  92458. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  92459. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  92460. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  92461. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  92462. #ifdef FLAC__USE_3DNOW
  92463. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  92464. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  92465. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  92466. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  92467. #else
  92468. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  92469. #endif
  92470. #ifdef DEBUG
  92471. fprintf(stderr, "CPU info (IA-32):\n");
  92472. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  92473. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  92474. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  92475. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  92476. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  92477. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  92478. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  92479. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  92480. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  92481. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  92482. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  92483. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  92484. #endif
  92485. /*
  92486. * now have to check for OS support of SSE/SSE2
  92487. */
  92488. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  92489. #if defined FLAC__NO_SSE_OS
  92490. /* assume user knows better than us; turn it off */
  92491. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  92492. #elif defined FLAC__SSE_OS
  92493. /* assume user knows better than us; leave as detected above */
  92494. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  92495. int sse = 0;
  92496. size_t len;
  92497. /* at least one of these must work: */
  92498. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  92499. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  92500. if(!sse)
  92501. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  92502. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  92503. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  92504. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  92505. size_t len = sizeof(val);
  92506. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  92507. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  92508. else { /* double-check SSE2 */
  92509. mib[1] = CPU_SSE2;
  92510. len = sizeof(val);
  92511. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  92512. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  92513. }
  92514. # else
  92515. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  92516. # endif
  92517. #elif defined(__linux__)
  92518. int sse = 0;
  92519. struct sigaction sigill_save;
  92520. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  92521. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  92522. #else
  92523. struct sigaction sigill_sse;
  92524. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  92525. __sigemptyset(&sigill_sse.sa_mask);
  92526. 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 */
  92527. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  92528. #endif
  92529. {
  92530. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  92531. /* see sigill_handler_sse_os() for an explanation of the following: */
  92532. asm volatile (
  92533. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  92534. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  92535. "incl %0\n\t" /* SIGILL handler will jump over this */
  92536. /* landing zone */
  92537. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  92538. "nop\n\t"
  92539. "nop\n\t"
  92540. "nop\n\t"
  92541. "nop\n\t"
  92542. "nop\n\t"
  92543. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  92544. "nop\n\t"
  92545. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  92546. : "=r"(sse)
  92547. : "r"(sse)
  92548. );
  92549. sigaction(SIGILL, &sigill_save, NULL);
  92550. }
  92551. if(!sse)
  92552. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  92553. #elif defined(_MSC_VER)
  92554. # ifdef USE_TRY_CATCH_FLAVOR
  92555. _try {
  92556. __asm {
  92557. # if _MSC_VER <= 1200
  92558. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  92559. _emit 0x0F
  92560. _emit 0x57
  92561. _emit 0xC0
  92562. # else
  92563. xorps xmm0,xmm0
  92564. # endif
  92565. }
  92566. }
  92567. _except(EXCEPTION_EXECUTE_HANDLER) {
  92568. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  92569. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  92570. }
  92571. # else
  92572. int sse = 0;
  92573. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  92574. /* see GCC version above for explanation */
  92575. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  92576. /* http://www.codeproject.com/cpp/gccasm.asp */
  92577. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  92578. __asm {
  92579. # if _MSC_VER <= 1200
  92580. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  92581. _emit 0x0F
  92582. _emit 0x57
  92583. _emit 0xC0
  92584. # else
  92585. xorps xmm0,xmm0
  92586. # endif
  92587. inc sse
  92588. nop
  92589. nop
  92590. nop
  92591. nop
  92592. nop
  92593. nop
  92594. nop
  92595. nop
  92596. nop
  92597. }
  92598. SetUnhandledExceptionFilter(save);
  92599. if(!sse)
  92600. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  92601. # endif
  92602. #else
  92603. /* no way to test, disable to be safe */
  92604. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  92605. #endif
  92606. #ifdef DEBUG
  92607. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  92608. #endif
  92609. }
  92610. }
  92611. #else
  92612. info->use_asm = false;
  92613. #endif
  92614. /*
  92615. * PPC-specific
  92616. */
  92617. #elif defined FLAC__CPU_PPC
  92618. info->type = FLAC__CPUINFO_TYPE_PPC;
  92619. # if !defined FLAC__NO_ASM
  92620. info->use_asm = true;
  92621. # ifdef FLAC__USE_ALTIVEC
  92622. # if defined FLAC__SYS_DARWIN
  92623. {
  92624. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  92625. size_t len = sizeof(val);
  92626. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  92627. }
  92628. {
  92629. host_basic_info_data_t hostInfo;
  92630. mach_msg_type_number_t infoCount;
  92631. infoCount = HOST_BASIC_INFO_COUNT;
  92632. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  92633. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  92634. }
  92635. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  92636. {
  92637. /* no Darwin, do it the brute-force way */
  92638. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  92639. info->data.ppc.altivec = 0;
  92640. info->data.ppc.ppc64 = 0;
  92641. signal (SIGILL, sigill_handler);
  92642. canjump = 0;
  92643. if (!sigsetjmp (jmpbuf, 1)) {
  92644. canjump = 1;
  92645. asm volatile (
  92646. "mtspr 256, %0\n\t"
  92647. "vand %%v0, %%v0, %%v0"
  92648. :
  92649. : "r" (-1)
  92650. );
  92651. info->data.ppc.altivec = 1;
  92652. }
  92653. canjump = 0;
  92654. if (!sigsetjmp (jmpbuf, 1)) {
  92655. int x = 0;
  92656. canjump = 1;
  92657. /* PPC64 hardware implements the cntlzd instruction */
  92658. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  92659. info->data.ppc.ppc64 = 1;
  92660. }
  92661. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  92662. }
  92663. # endif
  92664. # else /* !FLAC__USE_ALTIVEC */
  92665. info->data.ppc.altivec = 0;
  92666. info->data.ppc.ppc64 = 0;
  92667. # endif
  92668. # else
  92669. info->use_asm = false;
  92670. # endif
  92671. /*
  92672. * unknown CPI
  92673. */
  92674. #else
  92675. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  92676. info->use_asm = false;
  92677. #endif
  92678. }
  92679. #endif
  92680. /*** End of inlined file: cpu.c ***/
  92681. /*** Start of inlined file: crc.c ***/
  92682. /*** Start of inlined file: juce_FlacHeader.h ***/
  92683. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92684. // tasks..
  92685. #define VERSION "1.2.1"
  92686. #define FLAC__NO_DLL 1
  92687. #if JUCE_MSVC
  92688. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92689. #endif
  92690. #if JUCE_MAC
  92691. #define FLAC__SYS_DARWIN 1
  92692. #endif
  92693. /*** End of inlined file: juce_FlacHeader.h ***/
  92694. #if JUCE_USE_FLAC
  92695. #if HAVE_CONFIG_H
  92696. # include <config.h>
  92697. #endif
  92698. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  92699. FLAC__byte const FLAC__crc8_table[256] = {
  92700. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  92701. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  92702. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  92703. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  92704. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  92705. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  92706. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  92707. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  92708. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  92709. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  92710. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  92711. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  92712. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  92713. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  92714. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  92715. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  92716. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  92717. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  92718. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  92719. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  92720. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  92721. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  92722. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  92723. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  92724. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  92725. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  92726. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  92727. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  92728. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  92729. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  92730. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  92731. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  92732. };
  92733. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  92734. unsigned FLAC__crc16_table[256] = {
  92735. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  92736. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  92737. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  92738. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  92739. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  92740. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  92741. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  92742. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  92743. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  92744. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  92745. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  92746. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  92747. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  92748. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  92749. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  92750. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  92751. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  92752. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  92753. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  92754. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  92755. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  92756. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  92757. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  92758. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  92759. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  92760. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  92761. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  92762. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  92763. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  92764. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  92765. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  92766. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  92767. };
  92768. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  92769. {
  92770. *crc = FLAC__crc8_table[*crc ^ data];
  92771. }
  92772. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  92773. {
  92774. while(len--)
  92775. *crc = FLAC__crc8_table[*crc ^ *data++];
  92776. }
  92777. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  92778. {
  92779. FLAC__uint8 crc = 0;
  92780. while(len--)
  92781. crc = FLAC__crc8_table[crc ^ *data++];
  92782. return crc;
  92783. }
  92784. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  92785. {
  92786. unsigned crc = 0;
  92787. while(len--)
  92788. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  92789. return crc;
  92790. }
  92791. #endif
  92792. /*** End of inlined file: crc.c ***/
  92793. /*** Start of inlined file: fixed.c ***/
  92794. /*** Start of inlined file: juce_FlacHeader.h ***/
  92795. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92796. // tasks..
  92797. #define VERSION "1.2.1"
  92798. #define FLAC__NO_DLL 1
  92799. #if JUCE_MSVC
  92800. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92801. #endif
  92802. #if JUCE_MAC
  92803. #define FLAC__SYS_DARWIN 1
  92804. #endif
  92805. /*** End of inlined file: juce_FlacHeader.h ***/
  92806. #if JUCE_USE_FLAC
  92807. #if HAVE_CONFIG_H
  92808. # include <config.h>
  92809. #endif
  92810. #include <math.h>
  92811. #include <string.h>
  92812. /*** Start of inlined file: fixed.h ***/
  92813. #ifndef FLAC__PRIVATE__FIXED_H
  92814. #define FLAC__PRIVATE__FIXED_H
  92815. #ifdef HAVE_CONFIG_H
  92816. #include <config.h>
  92817. #endif
  92818. /*** Start of inlined file: float.h ***/
  92819. #ifndef FLAC__PRIVATE__FLOAT_H
  92820. #define FLAC__PRIVATE__FLOAT_H
  92821. #ifdef HAVE_CONFIG_H
  92822. #include <config.h>
  92823. #endif
  92824. /*
  92825. * These typedefs make it easier to ensure that integer versions of
  92826. * the library really only contain integer operations. All the code
  92827. * in libFLAC should use FLAC__float and FLAC__double in place of
  92828. * float and double, and be protected by checks of the macro
  92829. * FLAC__INTEGER_ONLY_LIBRARY.
  92830. *
  92831. * FLAC__real is the basic floating point type used in LPC analysis.
  92832. */
  92833. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92834. typedef double FLAC__double;
  92835. typedef float FLAC__float;
  92836. /*
  92837. * WATCHOUT: changing FLAC__real will change the signatures of many
  92838. * functions that have assembly language equivalents and break them.
  92839. */
  92840. typedef float FLAC__real;
  92841. #else
  92842. /*
  92843. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  92844. * for the integer part and lower 16 bits for the fractional part.
  92845. */
  92846. typedef FLAC__int32 FLAC__fixedpoint;
  92847. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  92848. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  92849. extern const FLAC__fixedpoint FLAC__FP_ONE;
  92850. extern const FLAC__fixedpoint FLAC__FP_LN2;
  92851. extern const FLAC__fixedpoint FLAC__FP_E;
  92852. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  92853. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  92854. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  92855. /*
  92856. * FLAC__fixedpoint_log2()
  92857. * --------------------------------------------------------------------
  92858. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  92859. * algorithm by Knuth for x >= 1.0
  92860. *
  92861. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  92862. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  92863. *
  92864. * 'precision' roughly limits the number of iterations that are done;
  92865. * use (unsigned)(-1) for maximum precision.
  92866. *
  92867. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  92868. * function will punt and return 0.
  92869. *
  92870. * The return value will also have 'fracbits' fractional bits.
  92871. */
  92872. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  92873. #endif
  92874. #endif
  92875. /*** End of inlined file: float.h ***/
  92876. /*** Start of inlined file: format.h ***/
  92877. #ifndef FLAC__PRIVATE__FORMAT_H
  92878. #define FLAC__PRIVATE__FORMAT_H
  92879. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  92880. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  92881. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  92882. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  92883. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  92884. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  92885. #endif
  92886. /*** End of inlined file: format.h ***/
  92887. /*
  92888. * FLAC__fixed_compute_best_predictor()
  92889. * --------------------------------------------------------------------
  92890. * Compute the best fixed predictor and the expected bits-per-sample
  92891. * of the residual signal for each order. The _wide() version uses
  92892. * 64-bit integers which is statistically necessary when bits-per-
  92893. * sample + log2(blocksize) > 30
  92894. *
  92895. * IN data[0,data_len-1]
  92896. * IN data_len
  92897. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  92898. */
  92899. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92900. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  92901. # ifndef FLAC__NO_ASM
  92902. # ifdef FLAC__CPU_IA32
  92903. # ifdef FLAC__HAS_NASM
  92904. 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]);
  92905. # endif
  92906. # endif
  92907. # endif
  92908. 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]);
  92909. #else
  92910. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  92911. 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]);
  92912. #endif
  92913. /*
  92914. * FLAC__fixed_compute_residual()
  92915. * --------------------------------------------------------------------
  92916. * Compute the residual signal obtained from sutracting the predicted
  92917. * signal from the original.
  92918. *
  92919. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  92920. * IN data_len length of original signal
  92921. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  92922. * OUT residual[0,data_len-1] residual signal
  92923. */
  92924. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  92925. /*
  92926. * FLAC__fixed_restore_signal()
  92927. * --------------------------------------------------------------------
  92928. * Restore the original signal by summing the residual and the
  92929. * predictor.
  92930. *
  92931. * IN residual[0,data_len-1] residual signal
  92932. * IN data_len length of original signal
  92933. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  92934. * *** IMPORTANT: the caller must pass in the historical samples:
  92935. * IN data[-order,-1] previously-reconstructed historical samples
  92936. * OUT data[0,data_len-1] original signal
  92937. */
  92938. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  92939. #endif
  92940. /*** End of inlined file: fixed.h ***/
  92941. #ifndef M_LN2
  92942. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  92943. #define M_LN2 0.69314718055994530942
  92944. #endif
  92945. #ifdef min
  92946. #undef min
  92947. #endif
  92948. #define min(x,y) ((x) < (y)? (x) : (y))
  92949. #ifdef local_abs
  92950. #undef local_abs
  92951. #endif
  92952. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  92953. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  92954. /* rbps stands for residual bits per sample
  92955. *
  92956. * (ln(2) * err)
  92957. * rbps = log (-----------)
  92958. * 2 ( n )
  92959. */
  92960. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  92961. {
  92962. FLAC__uint32 rbps;
  92963. unsigned bits; /* the number of bits required to represent a number */
  92964. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  92965. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  92966. FLAC__ASSERT(err > 0);
  92967. FLAC__ASSERT(n > 0);
  92968. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  92969. if(err <= n)
  92970. return 0;
  92971. /*
  92972. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  92973. * These allow us later to know we won't lose too much precision in the
  92974. * fixed-point division (err<<fracbits)/n.
  92975. */
  92976. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  92977. err <<= fracbits;
  92978. err /= n;
  92979. /* err now holds err/n with fracbits fractional bits */
  92980. /*
  92981. * Whittle err down to 16 bits max. 16 significant bits is enough for
  92982. * our purposes.
  92983. */
  92984. FLAC__ASSERT(err > 0);
  92985. bits = FLAC__bitmath_ilog2(err)+1;
  92986. if(bits > 16) {
  92987. err >>= (bits-16);
  92988. fracbits -= (bits-16);
  92989. }
  92990. rbps = (FLAC__uint32)err;
  92991. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  92992. rbps *= FLAC__FP_LN2;
  92993. fracbits += 16;
  92994. FLAC__ASSERT(fracbits >= 0);
  92995. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  92996. {
  92997. const int f = fracbits & 3;
  92998. if(f) {
  92999. rbps >>= f;
  93000. fracbits -= f;
  93001. }
  93002. }
  93003. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  93004. if(rbps == 0)
  93005. return 0;
  93006. /*
  93007. * The return value must have 16 fractional bits. Since the whole part
  93008. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  93009. * must be >= -3, these assertion allows us to be able to shift rbps
  93010. * left if necessary to get 16 fracbits without losing any bits of the
  93011. * whole part of rbps.
  93012. *
  93013. * There is a slight chance due to accumulated error that the whole part
  93014. * will require 6 bits, so we use 6 in the assertion. Really though as
  93015. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  93016. */
  93017. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  93018. FLAC__ASSERT(fracbits >= -3);
  93019. /* now shift the decimal point into place */
  93020. if(fracbits < 16)
  93021. return rbps << (16-fracbits);
  93022. else if(fracbits > 16)
  93023. return rbps >> (fracbits-16);
  93024. else
  93025. return rbps;
  93026. }
  93027. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  93028. {
  93029. FLAC__uint32 rbps;
  93030. unsigned bits; /* the number of bits required to represent a number */
  93031. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  93032. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  93033. FLAC__ASSERT(err > 0);
  93034. FLAC__ASSERT(n > 0);
  93035. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  93036. if(err <= n)
  93037. return 0;
  93038. /*
  93039. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  93040. * These allow us later to know we won't lose too much precision in the
  93041. * fixed-point division (err<<fracbits)/n.
  93042. */
  93043. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  93044. err <<= fracbits;
  93045. err /= n;
  93046. /* err now holds err/n with fracbits fractional bits */
  93047. /*
  93048. * Whittle err down to 16 bits max. 16 significant bits is enough for
  93049. * our purposes.
  93050. */
  93051. FLAC__ASSERT(err > 0);
  93052. bits = FLAC__bitmath_ilog2_wide(err)+1;
  93053. if(bits > 16) {
  93054. err >>= (bits-16);
  93055. fracbits -= (bits-16);
  93056. }
  93057. rbps = (FLAC__uint32)err;
  93058. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  93059. rbps *= FLAC__FP_LN2;
  93060. fracbits += 16;
  93061. FLAC__ASSERT(fracbits >= 0);
  93062. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  93063. {
  93064. const int f = fracbits & 3;
  93065. if(f) {
  93066. rbps >>= f;
  93067. fracbits -= f;
  93068. }
  93069. }
  93070. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  93071. if(rbps == 0)
  93072. return 0;
  93073. /*
  93074. * The return value must have 16 fractional bits. Since the whole part
  93075. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  93076. * must be >= -3, these assertion allows us to be able to shift rbps
  93077. * left if necessary to get 16 fracbits without losing any bits of the
  93078. * whole part of rbps.
  93079. *
  93080. * There is a slight chance due to accumulated error that the whole part
  93081. * will require 6 bits, so we use 6 in the assertion. Really though as
  93082. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  93083. */
  93084. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  93085. FLAC__ASSERT(fracbits >= -3);
  93086. /* now shift the decimal point into place */
  93087. if(fracbits < 16)
  93088. return rbps << (16-fracbits);
  93089. else if(fracbits > 16)
  93090. return rbps >> (fracbits-16);
  93091. else
  93092. return rbps;
  93093. }
  93094. #endif
  93095. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  93096. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  93097. #else
  93098. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  93099. #endif
  93100. {
  93101. FLAC__int32 last_error_0 = data[-1];
  93102. FLAC__int32 last_error_1 = data[-1] - data[-2];
  93103. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  93104. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  93105. FLAC__int32 error, save;
  93106. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  93107. unsigned i, order;
  93108. for(i = 0; i < data_len; i++) {
  93109. error = data[i] ; total_error_0 += local_abs(error); save = error;
  93110. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  93111. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  93112. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  93113. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  93114. }
  93115. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  93116. order = 0;
  93117. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  93118. order = 1;
  93119. else if(total_error_2 < min(total_error_3, total_error_4))
  93120. order = 2;
  93121. else if(total_error_3 < total_error_4)
  93122. order = 3;
  93123. else
  93124. order = 4;
  93125. /* Estimate the expected number of bits per residual signal sample. */
  93126. /* 'total_error*' is linearly related to the variance of the residual */
  93127. /* signal, so we use it directly to compute E(|x|) */
  93128. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  93129. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  93130. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  93131. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  93132. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  93133. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  93134. 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);
  93135. 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);
  93136. 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);
  93137. 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);
  93138. 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);
  93139. #else
  93140. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  93141. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  93142. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  93143. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  93144. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  93145. #endif
  93146. return order;
  93147. }
  93148. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  93149. 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])
  93150. #else
  93151. 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])
  93152. #endif
  93153. {
  93154. FLAC__int32 last_error_0 = data[-1];
  93155. FLAC__int32 last_error_1 = data[-1] - data[-2];
  93156. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  93157. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  93158. FLAC__int32 error, save;
  93159. /* total_error_* are 64-bits to avoid overflow when encoding
  93160. * erratic signals when the bits-per-sample and blocksize are
  93161. * large.
  93162. */
  93163. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  93164. unsigned i, order;
  93165. for(i = 0; i < data_len; i++) {
  93166. error = data[i] ; total_error_0 += local_abs(error); save = error;
  93167. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  93168. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  93169. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  93170. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  93171. }
  93172. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  93173. order = 0;
  93174. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  93175. order = 1;
  93176. else if(total_error_2 < min(total_error_3, total_error_4))
  93177. order = 2;
  93178. else if(total_error_3 < total_error_4)
  93179. order = 3;
  93180. else
  93181. order = 4;
  93182. /* Estimate the expected number of bits per residual signal sample. */
  93183. /* 'total_error*' is linearly related to the variance of the residual */
  93184. /* signal, so we use it directly to compute E(|x|) */
  93185. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  93186. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  93187. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  93188. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  93189. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  93190. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  93191. #if defined _MSC_VER || defined __MINGW32__
  93192. /* with MSVC you have to spoon feed it the casting */
  93193. 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);
  93194. 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);
  93195. 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);
  93196. 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);
  93197. 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);
  93198. #else
  93199. 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);
  93200. 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);
  93201. 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);
  93202. 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);
  93203. 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);
  93204. #endif
  93205. #else
  93206. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  93207. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  93208. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  93209. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  93210. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  93211. #endif
  93212. return order;
  93213. }
  93214. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  93215. {
  93216. const int idata_len = (int)data_len;
  93217. int i;
  93218. switch(order) {
  93219. case 0:
  93220. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  93221. memcpy(residual, data, sizeof(residual[0])*data_len);
  93222. break;
  93223. case 1:
  93224. for(i = 0; i < idata_len; i++)
  93225. residual[i] = data[i] - data[i-1];
  93226. break;
  93227. case 2:
  93228. for(i = 0; i < idata_len; i++)
  93229. #if 1 /* OPT: may be faster with some compilers on some systems */
  93230. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  93231. #else
  93232. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  93233. #endif
  93234. break;
  93235. case 3:
  93236. for(i = 0; i < idata_len; i++)
  93237. #if 1 /* OPT: may be faster with some compilers on some systems */
  93238. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  93239. #else
  93240. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  93241. #endif
  93242. break;
  93243. case 4:
  93244. for(i = 0; i < idata_len; i++)
  93245. #if 1 /* OPT: may be faster with some compilers on some systems */
  93246. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  93247. #else
  93248. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  93249. #endif
  93250. break;
  93251. default:
  93252. FLAC__ASSERT(0);
  93253. }
  93254. }
  93255. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  93256. {
  93257. int i, idata_len = (int)data_len;
  93258. switch(order) {
  93259. case 0:
  93260. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  93261. memcpy(data, residual, sizeof(residual[0])*data_len);
  93262. break;
  93263. case 1:
  93264. for(i = 0; i < idata_len; i++)
  93265. data[i] = residual[i] + data[i-1];
  93266. break;
  93267. case 2:
  93268. for(i = 0; i < idata_len; i++)
  93269. #if 1 /* OPT: may be faster with some compilers on some systems */
  93270. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  93271. #else
  93272. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  93273. #endif
  93274. break;
  93275. case 3:
  93276. for(i = 0; i < idata_len; i++)
  93277. #if 1 /* OPT: may be faster with some compilers on some systems */
  93278. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  93279. #else
  93280. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  93281. #endif
  93282. break;
  93283. case 4:
  93284. for(i = 0; i < idata_len; i++)
  93285. #if 1 /* OPT: may be faster with some compilers on some systems */
  93286. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  93287. #else
  93288. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  93289. #endif
  93290. break;
  93291. default:
  93292. FLAC__ASSERT(0);
  93293. }
  93294. }
  93295. #endif
  93296. /*** End of inlined file: fixed.c ***/
  93297. /*** Start of inlined file: float.c ***/
  93298. /*** Start of inlined file: juce_FlacHeader.h ***/
  93299. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93300. // tasks..
  93301. #define VERSION "1.2.1"
  93302. #define FLAC__NO_DLL 1
  93303. #if JUCE_MSVC
  93304. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93305. #endif
  93306. #if JUCE_MAC
  93307. #define FLAC__SYS_DARWIN 1
  93308. #endif
  93309. /*** End of inlined file: juce_FlacHeader.h ***/
  93310. #if JUCE_USE_FLAC
  93311. #if HAVE_CONFIG_H
  93312. # include <config.h>
  93313. #endif
  93314. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  93315. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93316. #ifdef _MSC_VER
  93317. #define FLAC__U64L(x) x
  93318. #else
  93319. #define FLAC__U64L(x) x##LLU
  93320. #endif
  93321. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  93322. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  93323. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  93324. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  93325. const FLAC__fixedpoint FLAC__FP_E = 178145;
  93326. /* Lookup tables for Knuth's logarithm algorithm */
  93327. #define LOG2_LOOKUP_PRECISION 16
  93328. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  93329. {
  93330. /*
  93331. * 0 fraction bits
  93332. */
  93333. /* undefined */ 0x00000000,
  93334. /* lg(2/1) = */ 0x00000001,
  93335. /* lg(4/3) = */ 0x00000000,
  93336. /* lg(8/7) = */ 0x00000000,
  93337. /* lg(16/15) = */ 0x00000000,
  93338. /* lg(32/31) = */ 0x00000000,
  93339. /* lg(64/63) = */ 0x00000000,
  93340. /* lg(128/127) = */ 0x00000000,
  93341. /* lg(256/255) = */ 0x00000000,
  93342. /* lg(512/511) = */ 0x00000000,
  93343. /* lg(1024/1023) = */ 0x00000000,
  93344. /* lg(2048/2047) = */ 0x00000000,
  93345. /* lg(4096/4095) = */ 0x00000000,
  93346. /* lg(8192/8191) = */ 0x00000000,
  93347. /* lg(16384/16383) = */ 0x00000000,
  93348. /* lg(32768/32767) = */ 0x00000000
  93349. },
  93350. {
  93351. /*
  93352. * 4 fraction bits
  93353. */
  93354. /* undefined */ 0x00000000,
  93355. /* lg(2/1) = */ 0x00000010,
  93356. /* lg(4/3) = */ 0x00000007,
  93357. /* lg(8/7) = */ 0x00000003,
  93358. /* lg(16/15) = */ 0x00000001,
  93359. /* lg(32/31) = */ 0x00000001,
  93360. /* lg(64/63) = */ 0x00000000,
  93361. /* lg(128/127) = */ 0x00000000,
  93362. /* lg(256/255) = */ 0x00000000,
  93363. /* lg(512/511) = */ 0x00000000,
  93364. /* lg(1024/1023) = */ 0x00000000,
  93365. /* lg(2048/2047) = */ 0x00000000,
  93366. /* lg(4096/4095) = */ 0x00000000,
  93367. /* lg(8192/8191) = */ 0x00000000,
  93368. /* lg(16384/16383) = */ 0x00000000,
  93369. /* lg(32768/32767) = */ 0x00000000
  93370. },
  93371. {
  93372. /*
  93373. * 8 fraction bits
  93374. */
  93375. /* undefined */ 0x00000000,
  93376. /* lg(2/1) = */ 0x00000100,
  93377. /* lg(4/3) = */ 0x0000006a,
  93378. /* lg(8/7) = */ 0x00000031,
  93379. /* lg(16/15) = */ 0x00000018,
  93380. /* lg(32/31) = */ 0x0000000c,
  93381. /* lg(64/63) = */ 0x00000006,
  93382. /* lg(128/127) = */ 0x00000003,
  93383. /* lg(256/255) = */ 0x00000001,
  93384. /* lg(512/511) = */ 0x00000001,
  93385. /* lg(1024/1023) = */ 0x00000000,
  93386. /* lg(2048/2047) = */ 0x00000000,
  93387. /* lg(4096/4095) = */ 0x00000000,
  93388. /* lg(8192/8191) = */ 0x00000000,
  93389. /* lg(16384/16383) = */ 0x00000000,
  93390. /* lg(32768/32767) = */ 0x00000000
  93391. },
  93392. {
  93393. /*
  93394. * 12 fraction bits
  93395. */
  93396. /* undefined */ 0x00000000,
  93397. /* lg(2/1) = */ 0x00001000,
  93398. /* lg(4/3) = */ 0x000006a4,
  93399. /* lg(8/7) = */ 0x00000315,
  93400. /* lg(16/15) = */ 0x0000017d,
  93401. /* lg(32/31) = */ 0x000000bc,
  93402. /* lg(64/63) = */ 0x0000005d,
  93403. /* lg(128/127) = */ 0x0000002e,
  93404. /* lg(256/255) = */ 0x00000017,
  93405. /* lg(512/511) = */ 0x0000000c,
  93406. /* lg(1024/1023) = */ 0x00000006,
  93407. /* lg(2048/2047) = */ 0x00000003,
  93408. /* lg(4096/4095) = */ 0x00000001,
  93409. /* lg(8192/8191) = */ 0x00000001,
  93410. /* lg(16384/16383) = */ 0x00000000,
  93411. /* lg(32768/32767) = */ 0x00000000
  93412. },
  93413. {
  93414. /*
  93415. * 16 fraction bits
  93416. */
  93417. /* undefined */ 0x00000000,
  93418. /* lg(2/1) = */ 0x00010000,
  93419. /* lg(4/3) = */ 0x00006a40,
  93420. /* lg(8/7) = */ 0x00003151,
  93421. /* lg(16/15) = */ 0x000017d6,
  93422. /* lg(32/31) = */ 0x00000bba,
  93423. /* lg(64/63) = */ 0x000005d1,
  93424. /* lg(128/127) = */ 0x000002e6,
  93425. /* lg(256/255) = */ 0x00000172,
  93426. /* lg(512/511) = */ 0x000000b9,
  93427. /* lg(1024/1023) = */ 0x0000005c,
  93428. /* lg(2048/2047) = */ 0x0000002e,
  93429. /* lg(4096/4095) = */ 0x00000017,
  93430. /* lg(8192/8191) = */ 0x0000000c,
  93431. /* lg(16384/16383) = */ 0x00000006,
  93432. /* lg(32768/32767) = */ 0x00000003
  93433. },
  93434. {
  93435. /*
  93436. * 20 fraction bits
  93437. */
  93438. /* undefined */ 0x00000000,
  93439. /* lg(2/1) = */ 0x00100000,
  93440. /* lg(4/3) = */ 0x0006a3fe,
  93441. /* lg(8/7) = */ 0x00031513,
  93442. /* lg(16/15) = */ 0x00017d60,
  93443. /* lg(32/31) = */ 0x0000bb9d,
  93444. /* lg(64/63) = */ 0x00005d10,
  93445. /* lg(128/127) = */ 0x00002e59,
  93446. /* lg(256/255) = */ 0x00001721,
  93447. /* lg(512/511) = */ 0x00000b8e,
  93448. /* lg(1024/1023) = */ 0x000005c6,
  93449. /* lg(2048/2047) = */ 0x000002e3,
  93450. /* lg(4096/4095) = */ 0x00000171,
  93451. /* lg(8192/8191) = */ 0x000000b9,
  93452. /* lg(16384/16383) = */ 0x0000005c,
  93453. /* lg(32768/32767) = */ 0x0000002e
  93454. },
  93455. {
  93456. /*
  93457. * 24 fraction bits
  93458. */
  93459. /* undefined */ 0x00000000,
  93460. /* lg(2/1) = */ 0x01000000,
  93461. /* lg(4/3) = */ 0x006a3fe6,
  93462. /* lg(8/7) = */ 0x00315130,
  93463. /* lg(16/15) = */ 0x0017d605,
  93464. /* lg(32/31) = */ 0x000bb9ca,
  93465. /* lg(64/63) = */ 0x0005d0fc,
  93466. /* lg(128/127) = */ 0x0002e58f,
  93467. /* lg(256/255) = */ 0x0001720e,
  93468. /* lg(512/511) = */ 0x0000b8d8,
  93469. /* lg(1024/1023) = */ 0x00005c61,
  93470. /* lg(2048/2047) = */ 0x00002e2d,
  93471. /* lg(4096/4095) = */ 0x00001716,
  93472. /* lg(8192/8191) = */ 0x00000b8b,
  93473. /* lg(16384/16383) = */ 0x000005c5,
  93474. /* lg(32768/32767) = */ 0x000002e3
  93475. },
  93476. {
  93477. /*
  93478. * 28 fraction bits
  93479. */
  93480. /* undefined */ 0x00000000,
  93481. /* lg(2/1) = */ 0x10000000,
  93482. /* lg(4/3) = */ 0x06a3fe5c,
  93483. /* lg(8/7) = */ 0x03151301,
  93484. /* lg(16/15) = */ 0x017d6049,
  93485. /* lg(32/31) = */ 0x00bb9ca6,
  93486. /* lg(64/63) = */ 0x005d0fba,
  93487. /* lg(128/127) = */ 0x002e58f7,
  93488. /* lg(256/255) = */ 0x001720da,
  93489. /* lg(512/511) = */ 0x000b8d87,
  93490. /* lg(1024/1023) = */ 0x0005c60b,
  93491. /* lg(2048/2047) = */ 0x0002e2d7,
  93492. /* lg(4096/4095) = */ 0x00017160,
  93493. /* lg(8192/8191) = */ 0x0000b8ad,
  93494. /* lg(16384/16383) = */ 0x00005c56,
  93495. /* lg(32768/32767) = */ 0x00002e2b
  93496. }
  93497. };
  93498. #if 0
  93499. static const FLAC__uint64 log2_lookup_wide[] = {
  93500. {
  93501. /*
  93502. * 32 fraction bits
  93503. */
  93504. /* undefined */ 0x00000000,
  93505. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  93506. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  93507. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  93508. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  93509. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  93510. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  93511. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  93512. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  93513. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  93514. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  93515. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  93516. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  93517. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  93518. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  93519. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  93520. },
  93521. {
  93522. /*
  93523. * 48 fraction bits
  93524. */
  93525. /* undefined */ 0x00000000,
  93526. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  93527. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  93528. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  93529. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  93530. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  93531. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  93532. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  93533. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  93534. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  93535. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  93536. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  93537. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  93538. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  93539. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  93540. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  93541. }
  93542. };
  93543. #endif
  93544. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  93545. {
  93546. const FLAC__uint32 ONE = (1u << fracbits);
  93547. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  93548. FLAC__ASSERT(fracbits < 32);
  93549. FLAC__ASSERT((fracbits & 0x3) == 0);
  93550. if(x < ONE)
  93551. return 0;
  93552. if(precision > LOG2_LOOKUP_PRECISION)
  93553. precision = LOG2_LOOKUP_PRECISION;
  93554. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  93555. {
  93556. FLAC__uint32 y = 0;
  93557. FLAC__uint32 z = x >> 1, k = 1;
  93558. while (x > ONE && k < precision) {
  93559. if (x - z >= ONE) {
  93560. x -= z;
  93561. z = x >> k;
  93562. y += table[k];
  93563. }
  93564. else {
  93565. z >>= 1;
  93566. k++;
  93567. }
  93568. }
  93569. return y;
  93570. }
  93571. }
  93572. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  93573. #endif
  93574. /*** End of inlined file: float.c ***/
  93575. /*** Start of inlined file: format.c ***/
  93576. /*** Start of inlined file: juce_FlacHeader.h ***/
  93577. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93578. // tasks..
  93579. #define VERSION "1.2.1"
  93580. #define FLAC__NO_DLL 1
  93581. #if JUCE_MSVC
  93582. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93583. #endif
  93584. #if JUCE_MAC
  93585. #define FLAC__SYS_DARWIN 1
  93586. #endif
  93587. /*** End of inlined file: juce_FlacHeader.h ***/
  93588. #if JUCE_USE_FLAC
  93589. #if HAVE_CONFIG_H
  93590. # include <config.h>
  93591. #endif
  93592. #include <stdio.h>
  93593. #include <stdlib.h> /* for qsort() */
  93594. #include <string.h> /* for memset() */
  93595. #ifndef FLaC__INLINE
  93596. #define FLaC__INLINE
  93597. #endif
  93598. #ifdef min
  93599. #undef min
  93600. #endif
  93601. #define min(a,b) ((a)<(b)?(a):(b))
  93602. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93603. #ifdef _MSC_VER
  93604. #define FLAC__U64L(x) x
  93605. #else
  93606. #define FLAC__U64L(x) x##LLU
  93607. #endif
  93608. /* VERSION should come from configure */
  93609. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  93610. ;
  93611. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  93612. /* yet one more hack because of MSVC6: */
  93613. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  93614. #else
  93615. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  93616. #endif
  93617. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  93618. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  93619. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  93620. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  93621. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  93622. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  93623. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  93624. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  93625. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  93626. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  93627. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  93628. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  93629. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  93630. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  93631. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  93632. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  93633. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  93634. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  93635. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  93636. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  93637. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  93638. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  93639. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  93640. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  93641. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  93642. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  93643. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  93644. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  93645. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  93646. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  93647. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  93648. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  93649. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  93650. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  93651. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  93652. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  93653. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  93654. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  93655. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  93656. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  93657. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  93658. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  93659. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  93660. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  93661. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  93662. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  93663. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  93664. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  93665. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  93666. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  93667. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  93668. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  93669. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  93670. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  93671. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  93672. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  93673. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  93674. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  93675. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  93676. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  93677. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  93678. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  93679. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  93680. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  93681. "PARTITIONED_RICE",
  93682. "PARTITIONED_RICE2"
  93683. };
  93684. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  93685. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  93686. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  93687. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  93688. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  93689. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  93690. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  93691. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  93692. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  93693. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  93694. "CONSTANT",
  93695. "VERBATIM",
  93696. "FIXED",
  93697. "LPC"
  93698. };
  93699. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  93700. "INDEPENDENT",
  93701. "LEFT_SIDE",
  93702. "RIGHT_SIDE",
  93703. "MID_SIDE"
  93704. };
  93705. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  93706. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  93707. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  93708. };
  93709. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  93710. "STREAMINFO",
  93711. "PADDING",
  93712. "APPLICATION",
  93713. "SEEKTABLE",
  93714. "VORBIS_COMMENT",
  93715. "CUESHEET",
  93716. "PICTURE"
  93717. };
  93718. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  93719. "Other",
  93720. "32x32 pixels 'file icon' (PNG only)",
  93721. "Other file icon",
  93722. "Cover (front)",
  93723. "Cover (back)",
  93724. "Leaflet page",
  93725. "Media (e.g. label side of CD)",
  93726. "Lead artist/lead performer/soloist",
  93727. "Artist/performer",
  93728. "Conductor",
  93729. "Band/Orchestra",
  93730. "Composer",
  93731. "Lyricist/text writer",
  93732. "Recording Location",
  93733. "During recording",
  93734. "During performance",
  93735. "Movie/video screen capture",
  93736. "A bright coloured fish",
  93737. "Illustration",
  93738. "Band/artist logotype",
  93739. "Publisher/Studio logotype"
  93740. };
  93741. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  93742. {
  93743. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  93744. return false;
  93745. }
  93746. else
  93747. return true;
  93748. }
  93749. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  93750. {
  93751. if(
  93752. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  93753. (
  93754. sample_rate >= (1u << 16) &&
  93755. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  93756. )
  93757. ) {
  93758. return false;
  93759. }
  93760. else
  93761. return true;
  93762. }
  93763. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  93764. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  93765. {
  93766. unsigned i;
  93767. FLAC__uint64 prev_sample_number = 0;
  93768. FLAC__bool got_prev = false;
  93769. FLAC__ASSERT(0 != seek_table);
  93770. for(i = 0; i < seek_table->num_points; i++) {
  93771. if(got_prev) {
  93772. if(
  93773. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  93774. seek_table->points[i].sample_number <= prev_sample_number
  93775. )
  93776. return false;
  93777. }
  93778. prev_sample_number = seek_table->points[i].sample_number;
  93779. got_prev = true;
  93780. }
  93781. return true;
  93782. }
  93783. /* used as the sort predicate for qsort() */
  93784. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  93785. {
  93786. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  93787. if(l->sample_number == r->sample_number)
  93788. return 0;
  93789. else if(l->sample_number < r->sample_number)
  93790. return -1;
  93791. else
  93792. return 1;
  93793. }
  93794. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  93795. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  93796. {
  93797. unsigned i, j;
  93798. FLAC__bool first;
  93799. FLAC__ASSERT(0 != seek_table);
  93800. /* sort the seekpoints */
  93801. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  93802. /* uniquify the seekpoints */
  93803. first = true;
  93804. for(i = j = 0; i < seek_table->num_points; i++) {
  93805. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  93806. if(!first) {
  93807. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  93808. continue;
  93809. }
  93810. }
  93811. first = false;
  93812. seek_table->points[j++] = seek_table->points[i];
  93813. }
  93814. for(i = j; i < seek_table->num_points; i++) {
  93815. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  93816. seek_table->points[i].stream_offset = 0;
  93817. seek_table->points[i].frame_samples = 0;
  93818. }
  93819. return j;
  93820. }
  93821. /*
  93822. * also disallows non-shortest-form encodings, c.f.
  93823. * http://www.unicode.org/versions/corrigendum1.html
  93824. * and a more clear explanation at the end of this section:
  93825. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  93826. */
  93827. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  93828. {
  93829. FLAC__ASSERT(0 != utf8);
  93830. if ((utf8[0] & 0x80) == 0) {
  93831. return 1;
  93832. }
  93833. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  93834. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  93835. return 0;
  93836. return 2;
  93837. }
  93838. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  93839. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  93840. return 0;
  93841. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  93842. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  93843. return 0;
  93844. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  93845. return 0;
  93846. return 3;
  93847. }
  93848. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  93849. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  93850. return 0;
  93851. return 4;
  93852. }
  93853. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  93854. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  93855. return 0;
  93856. return 5;
  93857. }
  93858. 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) {
  93859. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  93860. return 0;
  93861. return 6;
  93862. }
  93863. else {
  93864. return 0;
  93865. }
  93866. }
  93867. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  93868. {
  93869. char c;
  93870. for(c = *name; c; c = *(++name))
  93871. if(c < 0x20 || c == 0x3d || c > 0x7d)
  93872. return false;
  93873. return true;
  93874. }
  93875. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  93876. {
  93877. if(length == (unsigned)(-1)) {
  93878. while(*value) {
  93879. unsigned n = utf8len_(value);
  93880. if(n == 0)
  93881. return false;
  93882. value += n;
  93883. }
  93884. }
  93885. else {
  93886. const FLAC__byte *end = value + length;
  93887. while(value < end) {
  93888. unsigned n = utf8len_(value);
  93889. if(n == 0)
  93890. return false;
  93891. value += n;
  93892. }
  93893. if(value != end)
  93894. return false;
  93895. }
  93896. return true;
  93897. }
  93898. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  93899. {
  93900. const FLAC__byte *s, *end;
  93901. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  93902. if(*s < 0x20 || *s > 0x7D)
  93903. return false;
  93904. }
  93905. if(s == end)
  93906. return false;
  93907. s++; /* skip '=' */
  93908. while(s < end) {
  93909. unsigned n = utf8len_(s);
  93910. if(n == 0)
  93911. return false;
  93912. s += n;
  93913. }
  93914. if(s != end)
  93915. return false;
  93916. return true;
  93917. }
  93918. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  93919. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  93920. {
  93921. unsigned i, j;
  93922. if(check_cd_da_subset) {
  93923. if(cue_sheet->lead_in < 2 * 44100) {
  93924. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  93925. return false;
  93926. }
  93927. if(cue_sheet->lead_in % 588 != 0) {
  93928. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  93929. return false;
  93930. }
  93931. }
  93932. if(cue_sheet->num_tracks == 0) {
  93933. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  93934. return false;
  93935. }
  93936. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  93937. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  93938. return false;
  93939. }
  93940. for(i = 0; i < cue_sheet->num_tracks; i++) {
  93941. if(cue_sheet->tracks[i].number == 0) {
  93942. if(violation) *violation = "cue sheet may not have a track number 0";
  93943. return false;
  93944. }
  93945. if(check_cd_da_subset) {
  93946. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  93947. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  93948. return false;
  93949. }
  93950. }
  93951. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  93952. if(violation) {
  93953. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  93954. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  93955. else
  93956. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  93957. }
  93958. return false;
  93959. }
  93960. if(i < cue_sheet->num_tracks - 1) {
  93961. if(cue_sheet->tracks[i].num_indices == 0) {
  93962. if(violation) *violation = "cue sheet track must have at least one index point";
  93963. return false;
  93964. }
  93965. if(cue_sheet->tracks[i].indices[0].number > 1) {
  93966. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  93967. return false;
  93968. }
  93969. }
  93970. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  93971. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  93972. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  93973. return false;
  93974. }
  93975. if(j > 0) {
  93976. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  93977. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  93978. return false;
  93979. }
  93980. }
  93981. }
  93982. }
  93983. return true;
  93984. }
  93985. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  93986. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  93987. {
  93988. char *p;
  93989. FLAC__byte *b;
  93990. for(p = picture->mime_type; *p; p++) {
  93991. if(*p < 0x20 || *p > 0x7e) {
  93992. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  93993. return false;
  93994. }
  93995. }
  93996. for(b = picture->description; *b; ) {
  93997. unsigned n = utf8len_(b);
  93998. if(n == 0) {
  93999. if(violation) *violation = "description string must be valid UTF-8";
  94000. return false;
  94001. }
  94002. b += n;
  94003. }
  94004. return true;
  94005. }
  94006. /*
  94007. * These routines are private to libFLAC
  94008. */
  94009. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  94010. {
  94011. return
  94012. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  94013. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  94014. blocksize,
  94015. predictor_order
  94016. );
  94017. }
  94018. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  94019. {
  94020. unsigned max_rice_partition_order = 0;
  94021. while(!(blocksize & 1)) {
  94022. max_rice_partition_order++;
  94023. blocksize >>= 1;
  94024. }
  94025. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  94026. }
  94027. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  94028. {
  94029. unsigned max_rice_partition_order = limit;
  94030. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  94031. max_rice_partition_order--;
  94032. FLAC__ASSERT(
  94033. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  94034. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  94035. );
  94036. return max_rice_partition_order;
  94037. }
  94038. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  94039. {
  94040. FLAC__ASSERT(0 != object);
  94041. object->parameters = 0;
  94042. object->raw_bits = 0;
  94043. object->capacity_by_order = 0;
  94044. }
  94045. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  94046. {
  94047. FLAC__ASSERT(0 != object);
  94048. if(0 != object->parameters)
  94049. free(object->parameters);
  94050. if(0 != object->raw_bits)
  94051. free(object->raw_bits);
  94052. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  94053. }
  94054. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  94055. {
  94056. FLAC__ASSERT(0 != object);
  94057. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  94058. if(object->capacity_by_order < max_partition_order) {
  94059. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  94060. return false;
  94061. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  94062. return false;
  94063. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  94064. object->capacity_by_order = max_partition_order;
  94065. }
  94066. return true;
  94067. }
  94068. #endif
  94069. /*** End of inlined file: format.c ***/
  94070. /*** Start of inlined file: lpc_flac.c ***/
  94071. /*** Start of inlined file: juce_FlacHeader.h ***/
  94072. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94073. // tasks..
  94074. #define VERSION "1.2.1"
  94075. #define FLAC__NO_DLL 1
  94076. #if JUCE_MSVC
  94077. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94078. #endif
  94079. #if JUCE_MAC
  94080. #define FLAC__SYS_DARWIN 1
  94081. #endif
  94082. /*** End of inlined file: juce_FlacHeader.h ***/
  94083. #if JUCE_USE_FLAC
  94084. #if HAVE_CONFIG_H
  94085. # include <config.h>
  94086. #endif
  94087. #include <math.h>
  94088. /*** Start of inlined file: lpc.h ***/
  94089. #ifndef FLAC__PRIVATE__LPC_H
  94090. #define FLAC__PRIVATE__LPC_H
  94091. #ifdef HAVE_CONFIG_H
  94092. #include <config.h>
  94093. #endif
  94094. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94095. /*
  94096. * FLAC__lpc_window_data()
  94097. * --------------------------------------------------------------------
  94098. * Applies the given window to the data.
  94099. * OPT: asm implementation
  94100. *
  94101. * IN in[0,data_len-1]
  94102. * IN window[0,data_len-1]
  94103. * OUT out[0,lag-1]
  94104. * IN data_len
  94105. */
  94106. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  94107. /*
  94108. * FLAC__lpc_compute_autocorrelation()
  94109. * --------------------------------------------------------------------
  94110. * Compute the autocorrelation for lags between 0 and lag-1.
  94111. * Assumes data[] outside of [0,data_len-1] == 0.
  94112. * Asserts that lag > 0.
  94113. *
  94114. * IN data[0,data_len-1]
  94115. * IN data_len
  94116. * IN 0 < lag <= data_len
  94117. * OUT autoc[0,lag-1]
  94118. */
  94119. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  94120. #ifndef FLAC__NO_ASM
  94121. # ifdef FLAC__CPU_IA32
  94122. # ifdef FLAC__HAS_NASM
  94123. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  94124. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  94125. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  94126. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  94127. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  94128. # endif
  94129. # endif
  94130. #endif
  94131. /*
  94132. * FLAC__lpc_compute_lp_coefficients()
  94133. * --------------------------------------------------------------------
  94134. * Computes LP coefficients for orders 1..max_order.
  94135. * Do not call if autoc[0] == 0.0. This means the signal is zero
  94136. * and there is no point in calculating a predictor.
  94137. *
  94138. * IN autoc[0,max_order] autocorrelation values
  94139. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  94140. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  94141. * *** IMPORTANT:
  94142. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  94143. * OUT error[0,max_order-1] error for each order (more
  94144. * specifically, the variance of
  94145. * the error signal times # of
  94146. * samples in the signal)
  94147. *
  94148. * Example: if max_order is 9, the LP coefficients for order 9 will be
  94149. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  94150. * in lp_coeff[7][0,7], etc.
  94151. */
  94152. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  94153. /*
  94154. * FLAC__lpc_quantize_coefficients()
  94155. * --------------------------------------------------------------------
  94156. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  94157. * must be less than 32 (sizeof(FLAC__int32)*8).
  94158. *
  94159. * IN lp_coeff[0,order-1] LP coefficients
  94160. * IN order LP order
  94161. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  94162. * desired precision (in bits, including sign
  94163. * bit) of largest coefficient
  94164. * OUT qlp_coeff[0,order-1] quantized coefficients
  94165. * OUT shift # of bits to shift right to get approximated
  94166. * LP coefficients. NOTE: could be negative.
  94167. * RETURN 0 => quantization OK
  94168. * 1 => coefficients require too much shifting for *shift to
  94169. * fit in the LPC subframe header. 'shift' is unset.
  94170. * 2 => coefficients are all zero, which is bad. 'shift' is
  94171. * unset.
  94172. */
  94173. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  94174. /*
  94175. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  94176. * --------------------------------------------------------------------
  94177. * Compute the residual signal obtained from sutracting the predicted
  94178. * signal from the original.
  94179. *
  94180. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  94181. * IN data_len length of original signal
  94182. * IN qlp_coeff[0,order-1] quantized LP coefficients
  94183. * IN order > 0 LP order
  94184. * IN lp_quantization quantization of LP coefficients in bits
  94185. * OUT residual[0,data_len-1] residual signal
  94186. */
  94187. 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[]);
  94188. 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[]);
  94189. #ifndef FLAC__NO_ASM
  94190. # ifdef FLAC__CPU_IA32
  94191. # ifdef FLAC__HAS_NASM
  94192. 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[]);
  94193. 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[]);
  94194. # endif
  94195. # endif
  94196. #endif
  94197. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  94198. /*
  94199. * FLAC__lpc_restore_signal()
  94200. * --------------------------------------------------------------------
  94201. * Restore the original signal by summing the residual and the
  94202. * predictor.
  94203. *
  94204. * IN residual[0,data_len-1] residual signal
  94205. * IN data_len length of original signal
  94206. * IN qlp_coeff[0,order-1] quantized LP coefficients
  94207. * IN order > 0 LP order
  94208. * IN lp_quantization quantization of LP coefficients in bits
  94209. * *** IMPORTANT: the caller must pass in the historical samples:
  94210. * IN data[-order,-1] previously-reconstructed historical samples
  94211. * OUT data[0,data_len-1] original signal
  94212. */
  94213. 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[]);
  94214. 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[]);
  94215. #ifndef FLAC__NO_ASM
  94216. # ifdef FLAC__CPU_IA32
  94217. # ifdef FLAC__HAS_NASM
  94218. 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[]);
  94219. 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[]);
  94220. # endif /* FLAC__HAS_NASM */
  94221. # elif defined FLAC__CPU_PPC
  94222. 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[]);
  94223. 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[]);
  94224. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  94225. #endif /* FLAC__NO_ASM */
  94226. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94227. /*
  94228. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  94229. * --------------------------------------------------------------------
  94230. * Compute the expected number of bits per residual signal sample
  94231. * based on the LP error (which is related to the residual variance).
  94232. *
  94233. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  94234. * IN total_samples > 0 # of samples in residual signal
  94235. * RETURN expected bits per sample
  94236. */
  94237. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  94238. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  94239. /*
  94240. * FLAC__lpc_compute_best_order()
  94241. * --------------------------------------------------------------------
  94242. * Compute the best order from the array of signal errors returned
  94243. * during coefficient computation.
  94244. *
  94245. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  94246. * IN max_order > 0 max LP order
  94247. * IN total_samples > 0 # of samples in residual signal
  94248. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  94249. * (includes warmup sample size and quantized LP coefficient)
  94250. * RETURN [1,max_order] best order
  94251. */
  94252. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  94253. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  94254. #endif
  94255. /*** End of inlined file: lpc.h ***/
  94256. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  94257. #include <stdio.h>
  94258. #endif
  94259. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94260. #ifndef M_LN2
  94261. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  94262. #define M_LN2 0.69314718055994530942
  94263. #endif
  94264. /* OPT: #undef'ing this may improve the speed on some architectures */
  94265. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  94266. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  94267. {
  94268. unsigned i;
  94269. for(i = 0; i < data_len; i++)
  94270. out[i] = in[i] * window[i];
  94271. }
  94272. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  94273. {
  94274. /* a readable, but slower, version */
  94275. #if 0
  94276. FLAC__real d;
  94277. unsigned i;
  94278. FLAC__ASSERT(lag > 0);
  94279. FLAC__ASSERT(lag <= data_len);
  94280. /*
  94281. * Technically we should subtract the mean first like so:
  94282. * for(i = 0; i < data_len; i++)
  94283. * data[i] -= mean;
  94284. * but it appears not to make enough of a difference to matter, and
  94285. * most signals are already closely centered around zero
  94286. */
  94287. while(lag--) {
  94288. for(i = lag, d = 0.0; i < data_len; i++)
  94289. d += data[i] * data[i - lag];
  94290. autoc[lag] = d;
  94291. }
  94292. #endif
  94293. /*
  94294. * this version tends to run faster because of better data locality
  94295. * ('data_len' is usually much larger than 'lag')
  94296. */
  94297. FLAC__real d;
  94298. unsigned sample, coeff;
  94299. const unsigned limit = data_len - lag;
  94300. FLAC__ASSERT(lag > 0);
  94301. FLAC__ASSERT(lag <= data_len);
  94302. for(coeff = 0; coeff < lag; coeff++)
  94303. autoc[coeff] = 0.0;
  94304. for(sample = 0; sample <= limit; sample++) {
  94305. d = data[sample];
  94306. for(coeff = 0; coeff < lag; coeff++)
  94307. autoc[coeff] += d * data[sample+coeff];
  94308. }
  94309. for(; sample < data_len; sample++) {
  94310. d = data[sample];
  94311. for(coeff = 0; coeff < data_len - sample; coeff++)
  94312. autoc[coeff] += d * data[sample+coeff];
  94313. }
  94314. }
  94315. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  94316. {
  94317. unsigned i, j;
  94318. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  94319. FLAC__ASSERT(0 != max_order);
  94320. FLAC__ASSERT(0 < *max_order);
  94321. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  94322. FLAC__ASSERT(autoc[0] != 0.0);
  94323. err = autoc[0];
  94324. for(i = 0; i < *max_order; i++) {
  94325. /* Sum up this iteration's reflection coefficient. */
  94326. r = -autoc[i+1];
  94327. for(j = 0; j < i; j++)
  94328. r -= lpc[j] * autoc[i-j];
  94329. ref[i] = (r/=err);
  94330. /* Update LPC coefficients and total error. */
  94331. lpc[i]=r;
  94332. for(j = 0; j < (i>>1); j++) {
  94333. FLAC__double tmp = lpc[j];
  94334. lpc[j] += r * lpc[i-1-j];
  94335. lpc[i-1-j] += r * tmp;
  94336. }
  94337. if(i & 1)
  94338. lpc[j] += lpc[j] * r;
  94339. err *= (1.0 - r * r);
  94340. /* save this order */
  94341. for(j = 0; j <= i; j++)
  94342. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  94343. error[i] = err;
  94344. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  94345. if(err == 0.0) {
  94346. *max_order = i+1;
  94347. return;
  94348. }
  94349. }
  94350. }
  94351. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  94352. {
  94353. unsigned i;
  94354. FLAC__double cmax;
  94355. FLAC__int32 qmax, qmin;
  94356. FLAC__ASSERT(precision > 0);
  94357. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  94358. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  94359. precision--;
  94360. qmax = 1 << precision;
  94361. qmin = -qmax;
  94362. qmax--;
  94363. /* calc cmax = max( |lp_coeff[i]| ) */
  94364. cmax = 0.0;
  94365. for(i = 0; i < order; i++) {
  94366. const FLAC__double d = fabs(lp_coeff[i]);
  94367. if(d > cmax)
  94368. cmax = d;
  94369. }
  94370. if(cmax <= 0.0) {
  94371. /* => coefficients are all 0, which means our constant-detect didn't work */
  94372. return 2;
  94373. }
  94374. else {
  94375. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  94376. const int min_shiftlimit = -max_shiftlimit - 1;
  94377. int log2cmax;
  94378. (void)frexp(cmax, &log2cmax);
  94379. log2cmax--;
  94380. *shift = (int)precision - log2cmax - 1;
  94381. if(*shift > max_shiftlimit)
  94382. *shift = max_shiftlimit;
  94383. else if(*shift < min_shiftlimit)
  94384. return 1;
  94385. }
  94386. if(*shift >= 0) {
  94387. FLAC__double error = 0.0;
  94388. FLAC__int32 q;
  94389. for(i = 0; i < order; i++) {
  94390. error += lp_coeff[i] * (1 << *shift);
  94391. #if 1 /* unfortunately lround() is C99 */
  94392. if(error >= 0.0)
  94393. q = (FLAC__int32)(error + 0.5);
  94394. else
  94395. q = (FLAC__int32)(error - 0.5);
  94396. #else
  94397. q = lround(error);
  94398. #endif
  94399. #ifdef FLAC__OVERFLOW_DETECT
  94400. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  94401. 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]);
  94402. else if(q < qmin)
  94403. 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]);
  94404. #endif
  94405. if(q > qmax)
  94406. q = qmax;
  94407. else if(q < qmin)
  94408. q = qmin;
  94409. error -= q;
  94410. qlp_coeff[i] = q;
  94411. }
  94412. }
  94413. /* negative shift is very rare but due to design flaw, negative shift is
  94414. * a NOP in the decoder, so it must be handled specially by scaling down
  94415. * coeffs
  94416. */
  94417. else {
  94418. const int nshift = -(*shift);
  94419. FLAC__double error = 0.0;
  94420. FLAC__int32 q;
  94421. #ifdef DEBUG
  94422. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  94423. #endif
  94424. for(i = 0; i < order; i++) {
  94425. error += lp_coeff[i] / (1 << nshift);
  94426. #if 1 /* unfortunately lround() is C99 */
  94427. if(error >= 0.0)
  94428. q = (FLAC__int32)(error + 0.5);
  94429. else
  94430. q = (FLAC__int32)(error - 0.5);
  94431. #else
  94432. q = lround(error);
  94433. #endif
  94434. #ifdef FLAC__OVERFLOW_DETECT
  94435. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  94436. 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]);
  94437. else if(q < qmin)
  94438. 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]);
  94439. #endif
  94440. if(q > qmax)
  94441. q = qmax;
  94442. else if(q < qmin)
  94443. q = qmin;
  94444. error -= q;
  94445. qlp_coeff[i] = q;
  94446. }
  94447. *shift = 0;
  94448. }
  94449. return 0;
  94450. }
  94451. 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[])
  94452. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  94453. {
  94454. FLAC__int64 sumo;
  94455. unsigned i, j;
  94456. FLAC__int32 sum;
  94457. const FLAC__int32 *history;
  94458. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  94459. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  94460. for(i=0;i<order;i++)
  94461. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  94462. fprintf(stderr,"\n");
  94463. #endif
  94464. FLAC__ASSERT(order > 0);
  94465. for(i = 0; i < data_len; i++) {
  94466. sumo = 0;
  94467. sum = 0;
  94468. history = data;
  94469. for(j = 0; j < order; j++) {
  94470. sum += qlp_coeff[j] * (*(--history));
  94471. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  94472. #if defined _MSC_VER
  94473. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  94474. 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);
  94475. #else
  94476. if(sumo > 2147483647ll || sumo < -2147483648ll)
  94477. 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);
  94478. #endif
  94479. }
  94480. *(residual++) = *(data++) - (sum >> lp_quantization);
  94481. }
  94482. /* Here's a slower but clearer version:
  94483. for(i = 0; i < data_len; i++) {
  94484. sum = 0;
  94485. for(j = 0; j < order; j++)
  94486. sum += qlp_coeff[j] * data[i-j-1];
  94487. residual[i] = data[i] - (sum >> lp_quantization);
  94488. }
  94489. */
  94490. }
  94491. #else /* fully unrolled version for normal use */
  94492. {
  94493. int i;
  94494. FLAC__int32 sum;
  94495. FLAC__ASSERT(order > 0);
  94496. FLAC__ASSERT(order <= 32);
  94497. /*
  94498. * We do unique versions up to 12th order since that's the subset limit.
  94499. * Also they are roughly ordered to match frequency of occurrence to
  94500. * minimize branching.
  94501. */
  94502. if(order <= 12) {
  94503. if(order > 8) {
  94504. if(order > 10) {
  94505. if(order == 12) {
  94506. for(i = 0; i < (int)data_len; i++) {
  94507. sum = 0;
  94508. sum += qlp_coeff[11] * data[i-12];
  94509. sum += qlp_coeff[10] * data[i-11];
  94510. sum += qlp_coeff[9] * data[i-10];
  94511. sum += qlp_coeff[8] * data[i-9];
  94512. sum += qlp_coeff[7] * data[i-8];
  94513. sum += qlp_coeff[6] * data[i-7];
  94514. sum += qlp_coeff[5] * data[i-6];
  94515. sum += qlp_coeff[4] * data[i-5];
  94516. sum += qlp_coeff[3] * data[i-4];
  94517. sum += qlp_coeff[2] * data[i-3];
  94518. sum += qlp_coeff[1] * data[i-2];
  94519. sum += qlp_coeff[0] * data[i-1];
  94520. residual[i] = data[i] - (sum >> lp_quantization);
  94521. }
  94522. }
  94523. else { /* order == 11 */
  94524. for(i = 0; i < (int)data_len; i++) {
  94525. sum = 0;
  94526. sum += qlp_coeff[10] * data[i-11];
  94527. sum += qlp_coeff[9] * data[i-10];
  94528. sum += qlp_coeff[8] * data[i-9];
  94529. sum += qlp_coeff[7] * data[i-8];
  94530. sum += qlp_coeff[6] * data[i-7];
  94531. sum += qlp_coeff[5] * data[i-6];
  94532. sum += qlp_coeff[4] * data[i-5];
  94533. sum += qlp_coeff[3] * data[i-4];
  94534. sum += qlp_coeff[2] * data[i-3];
  94535. sum += qlp_coeff[1] * data[i-2];
  94536. sum += qlp_coeff[0] * data[i-1];
  94537. residual[i] = data[i] - (sum >> lp_quantization);
  94538. }
  94539. }
  94540. }
  94541. else {
  94542. if(order == 10) {
  94543. for(i = 0; i < (int)data_len; i++) {
  94544. sum = 0;
  94545. sum += qlp_coeff[9] * data[i-10];
  94546. sum += qlp_coeff[8] * data[i-9];
  94547. sum += qlp_coeff[7] * data[i-8];
  94548. sum += qlp_coeff[6] * data[i-7];
  94549. sum += qlp_coeff[5] * data[i-6];
  94550. sum += qlp_coeff[4] * data[i-5];
  94551. sum += qlp_coeff[3] * data[i-4];
  94552. sum += qlp_coeff[2] * data[i-3];
  94553. sum += qlp_coeff[1] * data[i-2];
  94554. sum += qlp_coeff[0] * data[i-1];
  94555. residual[i] = data[i] - (sum >> lp_quantization);
  94556. }
  94557. }
  94558. else { /* order == 9 */
  94559. for(i = 0; i < (int)data_len; i++) {
  94560. sum = 0;
  94561. sum += qlp_coeff[8] * data[i-9];
  94562. sum += qlp_coeff[7] * data[i-8];
  94563. sum += qlp_coeff[6] * data[i-7];
  94564. sum += qlp_coeff[5] * data[i-6];
  94565. sum += qlp_coeff[4] * data[i-5];
  94566. sum += qlp_coeff[3] * data[i-4];
  94567. sum += qlp_coeff[2] * data[i-3];
  94568. sum += qlp_coeff[1] * data[i-2];
  94569. sum += qlp_coeff[0] * data[i-1];
  94570. residual[i] = data[i] - (sum >> lp_quantization);
  94571. }
  94572. }
  94573. }
  94574. }
  94575. else if(order > 4) {
  94576. if(order > 6) {
  94577. if(order == 8) {
  94578. for(i = 0; i < (int)data_len; i++) {
  94579. sum = 0;
  94580. sum += qlp_coeff[7] * data[i-8];
  94581. sum += qlp_coeff[6] * data[i-7];
  94582. sum += qlp_coeff[5] * data[i-6];
  94583. sum += qlp_coeff[4] * data[i-5];
  94584. sum += qlp_coeff[3] * data[i-4];
  94585. sum += qlp_coeff[2] * data[i-3];
  94586. sum += qlp_coeff[1] * data[i-2];
  94587. sum += qlp_coeff[0] * data[i-1];
  94588. residual[i] = data[i] - (sum >> lp_quantization);
  94589. }
  94590. }
  94591. else { /* order == 7 */
  94592. for(i = 0; i < (int)data_len; i++) {
  94593. sum = 0;
  94594. sum += qlp_coeff[6] * data[i-7];
  94595. sum += qlp_coeff[5] * data[i-6];
  94596. sum += qlp_coeff[4] * data[i-5];
  94597. sum += qlp_coeff[3] * data[i-4];
  94598. sum += qlp_coeff[2] * data[i-3];
  94599. sum += qlp_coeff[1] * data[i-2];
  94600. sum += qlp_coeff[0] * data[i-1];
  94601. residual[i] = data[i] - (sum >> lp_quantization);
  94602. }
  94603. }
  94604. }
  94605. else {
  94606. if(order == 6) {
  94607. for(i = 0; i < (int)data_len; i++) {
  94608. sum = 0;
  94609. sum += qlp_coeff[5] * data[i-6];
  94610. sum += qlp_coeff[4] * data[i-5];
  94611. sum += qlp_coeff[3] * data[i-4];
  94612. sum += qlp_coeff[2] * data[i-3];
  94613. sum += qlp_coeff[1] * data[i-2];
  94614. sum += qlp_coeff[0] * data[i-1];
  94615. residual[i] = data[i] - (sum >> lp_quantization);
  94616. }
  94617. }
  94618. else { /* order == 5 */
  94619. for(i = 0; i < (int)data_len; i++) {
  94620. sum = 0;
  94621. sum += qlp_coeff[4] * data[i-5];
  94622. sum += qlp_coeff[3] * data[i-4];
  94623. sum += qlp_coeff[2] * data[i-3];
  94624. sum += qlp_coeff[1] * data[i-2];
  94625. sum += qlp_coeff[0] * data[i-1];
  94626. residual[i] = data[i] - (sum >> lp_quantization);
  94627. }
  94628. }
  94629. }
  94630. }
  94631. else {
  94632. if(order > 2) {
  94633. if(order == 4) {
  94634. for(i = 0; i < (int)data_len; i++) {
  94635. sum = 0;
  94636. sum += qlp_coeff[3] * data[i-4];
  94637. sum += qlp_coeff[2] * data[i-3];
  94638. sum += qlp_coeff[1] * data[i-2];
  94639. sum += qlp_coeff[0] * data[i-1];
  94640. residual[i] = data[i] - (sum >> lp_quantization);
  94641. }
  94642. }
  94643. else { /* order == 3 */
  94644. for(i = 0; i < (int)data_len; i++) {
  94645. sum = 0;
  94646. sum += qlp_coeff[2] * data[i-3];
  94647. sum += qlp_coeff[1] * data[i-2];
  94648. sum += qlp_coeff[0] * data[i-1];
  94649. residual[i] = data[i] - (sum >> lp_quantization);
  94650. }
  94651. }
  94652. }
  94653. else {
  94654. if(order == 2) {
  94655. for(i = 0; i < (int)data_len; i++) {
  94656. sum = 0;
  94657. sum += qlp_coeff[1] * data[i-2];
  94658. sum += qlp_coeff[0] * data[i-1];
  94659. residual[i] = data[i] - (sum >> lp_quantization);
  94660. }
  94661. }
  94662. else { /* order == 1 */
  94663. for(i = 0; i < (int)data_len; i++)
  94664. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  94665. }
  94666. }
  94667. }
  94668. }
  94669. else { /* order > 12 */
  94670. for(i = 0; i < (int)data_len; i++) {
  94671. sum = 0;
  94672. switch(order) {
  94673. case 32: sum += qlp_coeff[31] * data[i-32];
  94674. case 31: sum += qlp_coeff[30] * data[i-31];
  94675. case 30: sum += qlp_coeff[29] * data[i-30];
  94676. case 29: sum += qlp_coeff[28] * data[i-29];
  94677. case 28: sum += qlp_coeff[27] * data[i-28];
  94678. case 27: sum += qlp_coeff[26] * data[i-27];
  94679. case 26: sum += qlp_coeff[25] * data[i-26];
  94680. case 25: sum += qlp_coeff[24] * data[i-25];
  94681. case 24: sum += qlp_coeff[23] * data[i-24];
  94682. case 23: sum += qlp_coeff[22] * data[i-23];
  94683. case 22: sum += qlp_coeff[21] * data[i-22];
  94684. case 21: sum += qlp_coeff[20] * data[i-21];
  94685. case 20: sum += qlp_coeff[19] * data[i-20];
  94686. case 19: sum += qlp_coeff[18] * data[i-19];
  94687. case 18: sum += qlp_coeff[17] * data[i-18];
  94688. case 17: sum += qlp_coeff[16] * data[i-17];
  94689. case 16: sum += qlp_coeff[15] * data[i-16];
  94690. case 15: sum += qlp_coeff[14] * data[i-15];
  94691. case 14: sum += qlp_coeff[13] * data[i-14];
  94692. case 13: sum += qlp_coeff[12] * data[i-13];
  94693. sum += qlp_coeff[11] * data[i-12];
  94694. sum += qlp_coeff[10] * data[i-11];
  94695. sum += qlp_coeff[ 9] * data[i-10];
  94696. sum += qlp_coeff[ 8] * data[i- 9];
  94697. sum += qlp_coeff[ 7] * data[i- 8];
  94698. sum += qlp_coeff[ 6] * data[i- 7];
  94699. sum += qlp_coeff[ 5] * data[i- 6];
  94700. sum += qlp_coeff[ 4] * data[i- 5];
  94701. sum += qlp_coeff[ 3] * data[i- 4];
  94702. sum += qlp_coeff[ 2] * data[i- 3];
  94703. sum += qlp_coeff[ 1] * data[i- 2];
  94704. sum += qlp_coeff[ 0] * data[i- 1];
  94705. }
  94706. residual[i] = data[i] - (sum >> lp_quantization);
  94707. }
  94708. }
  94709. }
  94710. #endif
  94711. 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[])
  94712. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  94713. {
  94714. unsigned i, j;
  94715. FLAC__int64 sum;
  94716. const FLAC__int32 *history;
  94717. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  94718. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  94719. for(i=0;i<order;i++)
  94720. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  94721. fprintf(stderr,"\n");
  94722. #endif
  94723. FLAC__ASSERT(order > 0);
  94724. for(i = 0; i < data_len; i++) {
  94725. sum = 0;
  94726. history = data;
  94727. for(j = 0; j < order; j++)
  94728. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  94729. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  94730. #if defined _MSC_VER
  94731. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  94732. #else
  94733. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  94734. #endif
  94735. break;
  94736. }
  94737. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  94738. #if defined _MSC_VER
  94739. 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));
  94740. #else
  94741. 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)));
  94742. #endif
  94743. break;
  94744. }
  94745. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  94746. }
  94747. }
  94748. #else /* fully unrolled version for normal use */
  94749. {
  94750. int i;
  94751. FLAC__int64 sum;
  94752. FLAC__ASSERT(order > 0);
  94753. FLAC__ASSERT(order <= 32);
  94754. /*
  94755. * We do unique versions up to 12th order since that's the subset limit.
  94756. * Also they are roughly ordered to match frequency of occurrence to
  94757. * minimize branching.
  94758. */
  94759. if(order <= 12) {
  94760. if(order > 8) {
  94761. if(order > 10) {
  94762. if(order == 12) {
  94763. for(i = 0; i < (int)data_len; i++) {
  94764. sum = 0;
  94765. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  94766. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  94767. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  94768. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  94769. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94770. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94771. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94772. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94773. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94774. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94775. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94776. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94777. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94778. }
  94779. }
  94780. else { /* order == 11 */
  94781. for(i = 0; i < (int)data_len; i++) {
  94782. sum = 0;
  94783. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  94784. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  94785. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  94786. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94787. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94788. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94789. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94790. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94791. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94792. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94793. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94794. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94795. }
  94796. }
  94797. }
  94798. else {
  94799. if(order == 10) {
  94800. for(i = 0; i < (int)data_len; i++) {
  94801. sum = 0;
  94802. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  94803. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  94804. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94805. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94806. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94807. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94808. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94809. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94810. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94811. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94812. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94813. }
  94814. }
  94815. else { /* order == 9 */
  94816. for(i = 0; i < (int)data_len; i++) {
  94817. sum = 0;
  94818. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  94819. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94820. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94821. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94822. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94823. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94824. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94825. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94826. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94827. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94828. }
  94829. }
  94830. }
  94831. }
  94832. else if(order > 4) {
  94833. if(order > 6) {
  94834. if(order == 8) {
  94835. for(i = 0; i < (int)data_len; i++) {
  94836. sum = 0;
  94837. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94838. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94839. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94840. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94841. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94842. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94843. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94844. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94845. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94846. }
  94847. }
  94848. else { /* order == 7 */
  94849. for(i = 0; i < (int)data_len; i++) {
  94850. sum = 0;
  94851. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94852. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94853. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94854. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94855. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94856. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94857. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94858. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94859. }
  94860. }
  94861. }
  94862. else {
  94863. if(order == 6) {
  94864. for(i = 0; i < (int)data_len; i++) {
  94865. sum = 0;
  94866. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94867. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94868. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94869. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94870. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94871. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94872. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94873. }
  94874. }
  94875. else { /* order == 5 */
  94876. for(i = 0; i < (int)data_len; i++) {
  94877. sum = 0;
  94878. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94879. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94880. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94881. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94882. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94883. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94884. }
  94885. }
  94886. }
  94887. }
  94888. else {
  94889. if(order > 2) {
  94890. if(order == 4) {
  94891. for(i = 0; i < (int)data_len; i++) {
  94892. sum = 0;
  94893. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94894. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94895. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94896. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94897. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94898. }
  94899. }
  94900. else { /* order == 3 */
  94901. for(i = 0; i < (int)data_len; i++) {
  94902. sum = 0;
  94903. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94904. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94905. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94906. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94907. }
  94908. }
  94909. }
  94910. else {
  94911. if(order == 2) {
  94912. for(i = 0; i < (int)data_len; i++) {
  94913. sum = 0;
  94914. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94915. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94916. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94917. }
  94918. }
  94919. else { /* order == 1 */
  94920. for(i = 0; i < (int)data_len; i++)
  94921. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  94922. }
  94923. }
  94924. }
  94925. }
  94926. else { /* order > 12 */
  94927. for(i = 0; i < (int)data_len; i++) {
  94928. sum = 0;
  94929. switch(order) {
  94930. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  94931. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  94932. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  94933. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  94934. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  94935. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  94936. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  94937. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  94938. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  94939. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  94940. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  94941. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  94942. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  94943. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  94944. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  94945. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  94946. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  94947. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  94948. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  94949. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  94950. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  94951. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  94952. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  94953. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  94954. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  94955. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  94956. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  94957. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  94958. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  94959. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  94960. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  94961. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  94962. }
  94963. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94964. }
  94965. }
  94966. }
  94967. #endif
  94968. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  94969. 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[])
  94970. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  94971. {
  94972. FLAC__int64 sumo;
  94973. unsigned i, j;
  94974. FLAC__int32 sum;
  94975. const FLAC__int32 *r = residual, *history;
  94976. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  94977. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  94978. for(i=0;i<order;i++)
  94979. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  94980. fprintf(stderr,"\n");
  94981. #endif
  94982. FLAC__ASSERT(order > 0);
  94983. for(i = 0; i < data_len; i++) {
  94984. sumo = 0;
  94985. sum = 0;
  94986. history = data;
  94987. for(j = 0; j < order; j++) {
  94988. sum += qlp_coeff[j] * (*(--history));
  94989. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  94990. #if defined _MSC_VER
  94991. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  94992. 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);
  94993. #else
  94994. if(sumo > 2147483647ll || sumo < -2147483648ll)
  94995. 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);
  94996. #endif
  94997. }
  94998. *(data++) = *(r++) + (sum >> lp_quantization);
  94999. }
  95000. /* Here's a slower but clearer version:
  95001. for(i = 0; i < data_len; i++) {
  95002. sum = 0;
  95003. for(j = 0; j < order; j++)
  95004. sum += qlp_coeff[j] * data[i-j-1];
  95005. data[i] = residual[i] + (sum >> lp_quantization);
  95006. }
  95007. */
  95008. }
  95009. #else /* fully unrolled version for normal use */
  95010. {
  95011. int i;
  95012. FLAC__int32 sum;
  95013. FLAC__ASSERT(order > 0);
  95014. FLAC__ASSERT(order <= 32);
  95015. /*
  95016. * We do unique versions up to 12th order since that's the subset limit.
  95017. * Also they are roughly ordered to match frequency of occurrence to
  95018. * minimize branching.
  95019. */
  95020. if(order <= 12) {
  95021. if(order > 8) {
  95022. if(order > 10) {
  95023. if(order == 12) {
  95024. for(i = 0; i < (int)data_len; i++) {
  95025. sum = 0;
  95026. sum += qlp_coeff[11] * data[i-12];
  95027. sum += qlp_coeff[10] * data[i-11];
  95028. sum += qlp_coeff[9] * data[i-10];
  95029. sum += qlp_coeff[8] * data[i-9];
  95030. sum += qlp_coeff[7] * data[i-8];
  95031. sum += qlp_coeff[6] * data[i-7];
  95032. sum += qlp_coeff[5] * data[i-6];
  95033. sum += qlp_coeff[4] * data[i-5];
  95034. sum += qlp_coeff[3] * data[i-4];
  95035. sum += qlp_coeff[2] * data[i-3];
  95036. sum += qlp_coeff[1] * data[i-2];
  95037. sum += qlp_coeff[0] * data[i-1];
  95038. data[i] = residual[i] + (sum >> lp_quantization);
  95039. }
  95040. }
  95041. else { /* order == 11 */
  95042. for(i = 0; i < (int)data_len; i++) {
  95043. sum = 0;
  95044. sum += qlp_coeff[10] * data[i-11];
  95045. sum += qlp_coeff[9] * data[i-10];
  95046. sum += qlp_coeff[8] * data[i-9];
  95047. sum += qlp_coeff[7] * data[i-8];
  95048. sum += qlp_coeff[6] * data[i-7];
  95049. sum += qlp_coeff[5] * data[i-6];
  95050. sum += qlp_coeff[4] * data[i-5];
  95051. sum += qlp_coeff[3] * data[i-4];
  95052. sum += qlp_coeff[2] * data[i-3];
  95053. sum += qlp_coeff[1] * data[i-2];
  95054. sum += qlp_coeff[0] * data[i-1];
  95055. data[i] = residual[i] + (sum >> lp_quantization);
  95056. }
  95057. }
  95058. }
  95059. else {
  95060. if(order == 10) {
  95061. for(i = 0; i < (int)data_len; i++) {
  95062. sum = 0;
  95063. sum += qlp_coeff[9] * data[i-10];
  95064. sum += qlp_coeff[8] * data[i-9];
  95065. sum += qlp_coeff[7] * data[i-8];
  95066. sum += qlp_coeff[6] * data[i-7];
  95067. sum += qlp_coeff[5] * data[i-6];
  95068. sum += qlp_coeff[4] * data[i-5];
  95069. sum += qlp_coeff[3] * data[i-4];
  95070. sum += qlp_coeff[2] * data[i-3];
  95071. sum += qlp_coeff[1] * data[i-2];
  95072. sum += qlp_coeff[0] * data[i-1];
  95073. data[i] = residual[i] + (sum >> lp_quantization);
  95074. }
  95075. }
  95076. else { /* order == 9 */
  95077. for(i = 0; i < (int)data_len; i++) {
  95078. sum = 0;
  95079. sum += qlp_coeff[8] * data[i-9];
  95080. sum += qlp_coeff[7] * data[i-8];
  95081. sum += qlp_coeff[6] * data[i-7];
  95082. sum += qlp_coeff[5] * data[i-6];
  95083. sum += qlp_coeff[4] * data[i-5];
  95084. sum += qlp_coeff[3] * data[i-4];
  95085. sum += qlp_coeff[2] * data[i-3];
  95086. sum += qlp_coeff[1] * data[i-2];
  95087. sum += qlp_coeff[0] * data[i-1];
  95088. data[i] = residual[i] + (sum >> lp_quantization);
  95089. }
  95090. }
  95091. }
  95092. }
  95093. else if(order > 4) {
  95094. if(order > 6) {
  95095. if(order == 8) {
  95096. for(i = 0; i < (int)data_len; i++) {
  95097. sum = 0;
  95098. sum += qlp_coeff[7] * data[i-8];
  95099. sum += qlp_coeff[6] * data[i-7];
  95100. sum += qlp_coeff[5] * data[i-6];
  95101. sum += qlp_coeff[4] * data[i-5];
  95102. sum += qlp_coeff[3] * data[i-4];
  95103. sum += qlp_coeff[2] * data[i-3];
  95104. sum += qlp_coeff[1] * data[i-2];
  95105. sum += qlp_coeff[0] * data[i-1];
  95106. data[i] = residual[i] + (sum >> lp_quantization);
  95107. }
  95108. }
  95109. else { /* order == 7 */
  95110. for(i = 0; i < (int)data_len; i++) {
  95111. sum = 0;
  95112. sum += qlp_coeff[6] * data[i-7];
  95113. sum += qlp_coeff[5] * data[i-6];
  95114. sum += qlp_coeff[4] * data[i-5];
  95115. sum += qlp_coeff[3] * data[i-4];
  95116. sum += qlp_coeff[2] * data[i-3];
  95117. sum += qlp_coeff[1] * data[i-2];
  95118. sum += qlp_coeff[0] * data[i-1];
  95119. data[i] = residual[i] + (sum >> lp_quantization);
  95120. }
  95121. }
  95122. }
  95123. else {
  95124. if(order == 6) {
  95125. for(i = 0; i < (int)data_len; i++) {
  95126. sum = 0;
  95127. sum += qlp_coeff[5] * data[i-6];
  95128. sum += qlp_coeff[4] * data[i-5];
  95129. sum += qlp_coeff[3] * data[i-4];
  95130. sum += qlp_coeff[2] * data[i-3];
  95131. sum += qlp_coeff[1] * data[i-2];
  95132. sum += qlp_coeff[0] * data[i-1];
  95133. data[i] = residual[i] + (sum >> lp_quantization);
  95134. }
  95135. }
  95136. else { /* order == 5 */
  95137. for(i = 0; i < (int)data_len; i++) {
  95138. sum = 0;
  95139. sum += qlp_coeff[4] * data[i-5];
  95140. sum += qlp_coeff[3] * data[i-4];
  95141. sum += qlp_coeff[2] * data[i-3];
  95142. sum += qlp_coeff[1] * data[i-2];
  95143. sum += qlp_coeff[0] * data[i-1];
  95144. data[i] = residual[i] + (sum >> lp_quantization);
  95145. }
  95146. }
  95147. }
  95148. }
  95149. else {
  95150. if(order > 2) {
  95151. if(order == 4) {
  95152. for(i = 0; i < (int)data_len; i++) {
  95153. sum = 0;
  95154. sum += qlp_coeff[3] * data[i-4];
  95155. sum += qlp_coeff[2] * data[i-3];
  95156. sum += qlp_coeff[1] * data[i-2];
  95157. sum += qlp_coeff[0] * data[i-1];
  95158. data[i] = residual[i] + (sum >> lp_quantization);
  95159. }
  95160. }
  95161. else { /* order == 3 */
  95162. for(i = 0; i < (int)data_len; i++) {
  95163. sum = 0;
  95164. sum += qlp_coeff[2] * data[i-3];
  95165. sum += qlp_coeff[1] * data[i-2];
  95166. sum += qlp_coeff[0] * data[i-1];
  95167. data[i] = residual[i] + (sum >> lp_quantization);
  95168. }
  95169. }
  95170. }
  95171. else {
  95172. if(order == 2) {
  95173. for(i = 0; i < (int)data_len; i++) {
  95174. sum = 0;
  95175. sum += qlp_coeff[1] * data[i-2];
  95176. sum += qlp_coeff[0] * data[i-1];
  95177. data[i] = residual[i] + (sum >> lp_quantization);
  95178. }
  95179. }
  95180. else { /* order == 1 */
  95181. for(i = 0; i < (int)data_len; i++)
  95182. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  95183. }
  95184. }
  95185. }
  95186. }
  95187. else { /* order > 12 */
  95188. for(i = 0; i < (int)data_len; i++) {
  95189. sum = 0;
  95190. switch(order) {
  95191. case 32: sum += qlp_coeff[31] * data[i-32];
  95192. case 31: sum += qlp_coeff[30] * data[i-31];
  95193. case 30: sum += qlp_coeff[29] * data[i-30];
  95194. case 29: sum += qlp_coeff[28] * data[i-29];
  95195. case 28: sum += qlp_coeff[27] * data[i-28];
  95196. case 27: sum += qlp_coeff[26] * data[i-27];
  95197. case 26: sum += qlp_coeff[25] * data[i-26];
  95198. case 25: sum += qlp_coeff[24] * data[i-25];
  95199. case 24: sum += qlp_coeff[23] * data[i-24];
  95200. case 23: sum += qlp_coeff[22] * data[i-23];
  95201. case 22: sum += qlp_coeff[21] * data[i-22];
  95202. case 21: sum += qlp_coeff[20] * data[i-21];
  95203. case 20: sum += qlp_coeff[19] * data[i-20];
  95204. case 19: sum += qlp_coeff[18] * data[i-19];
  95205. case 18: sum += qlp_coeff[17] * data[i-18];
  95206. case 17: sum += qlp_coeff[16] * data[i-17];
  95207. case 16: sum += qlp_coeff[15] * data[i-16];
  95208. case 15: sum += qlp_coeff[14] * data[i-15];
  95209. case 14: sum += qlp_coeff[13] * data[i-14];
  95210. case 13: sum += qlp_coeff[12] * data[i-13];
  95211. sum += qlp_coeff[11] * data[i-12];
  95212. sum += qlp_coeff[10] * data[i-11];
  95213. sum += qlp_coeff[ 9] * data[i-10];
  95214. sum += qlp_coeff[ 8] * data[i- 9];
  95215. sum += qlp_coeff[ 7] * data[i- 8];
  95216. sum += qlp_coeff[ 6] * data[i- 7];
  95217. sum += qlp_coeff[ 5] * data[i- 6];
  95218. sum += qlp_coeff[ 4] * data[i- 5];
  95219. sum += qlp_coeff[ 3] * data[i- 4];
  95220. sum += qlp_coeff[ 2] * data[i- 3];
  95221. sum += qlp_coeff[ 1] * data[i- 2];
  95222. sum += qlp_coeff[ 0] * data[i- 1];
  95223. }
  95224. data[i] = residual[i] + (sum >> lp_quantization);
  95225. }
  95226. }
  95227. }
  95228. #endif
  95229. 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[])
  95230. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  95231. {
  95232. unsigned i, j;
  95233. FLAC__int64 sum;
  95234. const FLAC__int32 *r = residual, *history;
  95235. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  95236. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  95237. for(i=0;i<order;i++)
  95238. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  95239. fprintf(stderr,"\n");
  95240. #endif
  95241. FLAC__ASSERT(order > 0);
  95242. for(i = 0; i < data_len; i++) {
  95243. sum = 0;
  95244. history = data;
  95245. for(j = 0; j < order; j++)
  95246. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  95247. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  95248. #ifdef _MSC_VER
  95249. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  95250. #else
  95251. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  95252. #endif
  95253. break;
  95254. }
  95255. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  95256. #ifdef _MSC_VER
  95257. 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));
  95258. #else
  95259. 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)));
  95260. #endif
  95261. break;
  95262. }
  95263. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  95264. }
  95265. }
  95266. #else /* fully unrolled version for normal use */
  95267. {
  95268. int i;
  95269. FLAC__int64 sum;
  95270. FLAC__ASSERT(order > 0);
  95271. FLAC__ASSERT(order <= 32);
  95272. /*
  95273. * We do unique versions up to 12th order since that's the subset limit.
  95274. * Also they are roughly ordered to match frequency of occurrence to
  95275. * minimize branching.
  95276. */
  95277. if(order <= 12) {
  95278. if(order > 8) {
  95279. if(order > 10) {
  95280. if(order == 12) {
  95281. for(i = 0; i < (int)data_len; i++) {
  95282. sum = 0;
  95283. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  95284. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  95285. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  95286. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  95287. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  95288. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  95289. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  95290. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  95291. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  95292. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  95293. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  95294. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  95295. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  95296. }
  95297. }
  95298. else { /* order == 11 */
  95299. for(i = 0; i < (int)data_len; i++) {
  95300. sum = 0;
  95301. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  95302. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  95303. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  95304. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  95305. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  95306. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  95307. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  95308. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  95309. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  95310. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  95311. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  95312. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  95313. }
  95314. }
  95315. }
  95316. else {
  95317. if(order == 10) {
  95318. for(i = 0; i < (int)data_len; i++) {
  95319. sum = 0;
  95320. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  95321. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  95322. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  95323. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  95324. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  95325. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  95326. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  95327. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  95328. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  95329. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  95330. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  95331. }
  95332. }
  95333. else { /* order == 9 */
  95334. for(i = 0; i < (int)data_len; i++) {
  95335. sum = 0;
  95336. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  95337. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  95338. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  95339. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  95340. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  95341. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  95342. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  95343. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  95344. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  95345. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  95346. }
  95347. }
  95348. }
  95349. }
  95350. else if(order > 4) {
  95351. if(order > 6) {
  95352. if(order == 8) {
  95353. for(i = 0; i < (int)data_len; i++) {
  95354. sum = 0;
  95355. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  95356. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  95357. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  95358. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  95359. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  95360. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  95361. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  95362. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  95363. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  95364. }
  95365. }
  95366. else { /* order == 7 */
  95367. for(i = 0; i < (int)data_len; i++) {
  95368. sum = 0;
  95369. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  95370. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  95371. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  95372. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  95373. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  95374. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  95375. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  95376. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  95377. }
  95378. }
  95379. }
  95380. else {
  95381. if(order == 6) {
  95382. for(i = 0; i < (int)data_len; i++) {
  95383. sum = 0;
  95384. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  95385. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  95386. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  95387. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  95388. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  95389. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  95390. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  95391. }
  95392. }
  95393. else { /* order == 5 */
  95394. for(i = 0; i < (int)data_len; i++) {
  95395. sum = 0;
  95396. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  95397. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  95398. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  95399. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  95400. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  95401. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  95402. }
  95403. }
  95404. }
  95405. }
  95406. else {
  95407. if(order > 2) {
  95408. if(order == 4) {
  95409. for(i = 0; i < (int)data_len; i++) {
  95410. sum = 0;
  95411. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  95412. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  95413. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  95414. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  95415. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  95416. }
  95417. }
  95418. else { /* order == 3 */
  95419. for(i = 0; i < (int)data_len; i++) {
  95420. sum = 0;
  95421. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  95422. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  95423. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  95424. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  95425. }
  95426. }
  95427. }
  95428. else {
  95429. if(order == 2) {
  95430. for(i = 0; i < (int)data_len; i++) {
  95431. sum = 0;
  95432. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  95433. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  95434. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  95435. }
  95436. }
  95437. else { /* order == 1 */
  95438. for(i = 0; i < (int)data_len; i++)
  95439. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  95440. }
  95441. }
  95442. }
  95443. }
  95444. else { /* order > 12 */
  95445. for(i = 0; i < (int)data_len; i++) {
  95446. sum = 0;
  95447. switch(order) {
  95448. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  95449. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  95450. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  95451. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  95452. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  95453. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  95454. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  95455. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  95456. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  95457. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  95458. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  95459. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  95460. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  95461. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  95462. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  95463. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  95464. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  95465. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  95466. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  95467. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  95468. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  95469. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  95470. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  95471. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  95472. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  95473. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  95474. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  95475. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  95476. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  95477. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  95478. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  95479. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  95480. }
  95481. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  95482. }
  95483. }
  95484. }
  95485. #endif
  95486. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95487. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  95488. {
  95489. FLAC__double error_scale;
  95490. FLAC__ASSERT(total_samples > 0);
  95491. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  95492. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  95493. }
  95494. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  95495. {
  95496. if(lpc_error > 0.0) {
  95497. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  95498. if(bps >= 0.0)
  95499. return bps;
  95500. else
  95501. return 0.0;
  95502. }
  95503. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  95504. return 1e32;
  95505. }
  95506. else {
  95507. return 0.0;
  95508. }
  95509. }
  95510. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  95511. {
  95512. 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 */
  95513. FLAC__double bits, best_bits, error_scale;
  95514. FLAC__ASSERT(max_order > 0);
  95515. FLAC__ASSERT(total_samples > 0);
  95516. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  95517. best_index = 0;
  95518. best_bits = (unsigned)(-1);
  95519. for(index = 0, order = 1; index < max_order; index++, order++) {
  95520. 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);
  95521. if(bits < best_bits) {
  95522. best_index = index;
  95523. best_bits = bits;
  95524. }
  95525. }
  95526. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  95527. }
  95528. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  95529. #endif
  95530. /*** End of inlined file: lpc_flac.c ***/
  95531. /*** Start of inlined file: md5.c ***/
  95532. /*** Start of inlined file: juce_FlacHeader.h ***/
  95533. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95534. // tasks..
  95535. #define VERSION "1.2.1"
  95536. #define FLAC__NO_DLL 1
  95537. #if JUCE_MSVC
  95538. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95539. #endif
  95540. #if JUCE_MAC
  95541. #define FLAC__SYS_DARWIN 1
  95542. #endif
  95543. /*** End of inlined file: juce_FlacHeader.h ***/
  95544. #if JUCE_USE_FLAC
  95545. #if HAVE_CONFIG_H
  95546. # include <config.h>
  95547. #endif
  95548. #include <stdlib.h> /* for malloc() */
  95549. #include <string.h> /* for memcpy() */
  95550. /*** Start of inlined file: md5.h ***/
  95551. #ifndef FLAC__PRIVATE__MD5_H
  95552. #define FLAC__PRIVATE__MD5_H
  95553. /*
  95554. * This is the header file for the MD5 message-digest algorithm.
  95555. * The algorithm is due to Ron Rivest. This code was
  95556. * written by Colin Plumb in 1993, no copyright is claimed.
  95557. * This code is in the public domain; do with it what you wish.
  95558. *
  95559. * Equivalent code is available from RSA Data Security, Inc.
  95560. * This code has been tested against that, and is equivalent,
  95561. * except that you don't need to include two pages of legalese
  95562. * with every copy.
  95563. *
  95564. * To compute the message digest of a chunk of bytes, declare an
  95565. * MD5Context structure, pass it to MD5Init, call MD5Update as
  95566. * needed on buffers full of bytes, and then call MD5Final, which
  95567. * will fill a supplied 16-byte array with the digest.
  95568. *
  95569. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  95570. * header definitions; now uses stuff from dpkg's config.h
  95571. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  95572. * Still in the public domain.
  95573. *
  95574. * Josh Coalson: made some changes to integrate with libFLAC.
  95575. * Still in the public domain, with no warranty.
  95576. */
  95577. typedef struct {
  95578. FLAC__uint32 in[16];
  95579. FLAC__uint32 buf[4];
  95580. FLAC__uint32 bytes[2];
  95581. FLAC__byte *internal_buf;
  95582. size_t capacity;
  95583. } FLAC__MD5Context;
  95584. void FLAC__MD5Init(FLAC__MD5Context *context);
  95585. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  95586. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  95587. #endif
  95588. /*** End of inlined file: md5.h ***/
  95589. #ifndef FLaC__INLINE
  95590. #define FLaC__INLINE
  95591. #endif
  95592. /*
  95593. * This code implements the MD5 message-digest algorithm.
  95594. * The algorithm is due to Ron Rivest. This code was
  95595. * written by Colin Plumb in 1993, no copyright is claimed.
  95596. * This code is in the public domain; do with it what you wish.
  95597. *
  95598. * Equivalent code is available from RSA Data Security, Inc.
  95599. * This code has been tested against that, and is equivalent,
  95600. * except that you don't need to include two pages of legalese
  95601. * with every copy.
  95602. *
  95603. * To compute the message digest of a chunk of bytes, declare an
  95604. * MD5Context structure, pass it to MD5Init, call MD5Update as
  95605. * needed on buffers full of bytes, and then call MD5Final, which
  95606. * will fill a supplied 16-byte array with the digest.
  95607. *
  95608. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  95609. * definitions; now uses stuff from dpkg's config.h.
  95610. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  95611. * Still in the public domain.
  95612. *
  95613. * Josh Coalson: made some changes to integrate with libFLAC.
  95614. * Still in the public domain.
  95615. */
  95616. /* The four core functions - F1 is optimized somewhat */
  95617. /* #define F1(x, y, z) (x & y | ~x & z) */
  95618. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  95619. #define F2(x, y, z) F1(z, x, y)
  95620. #define F3(x, y, z) (x ^ y ^ z)
  95621. #define F4(x, y, z) (y ^ (x | ~z))
  95622. /* This is the central step in the MD5 algorithm. */
  95623. #define MD5STEP(f,w,x,y,z,in,s) \
  95624. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  95625. /*
  95626. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  95627. * reflect the addition of 16 longwords of new data. MD5Update blocks
  95628. * the data and converts bytes into longwords for this routine.
  95629. */
  95630. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  95631. {
  95632. register FLAC__uint32 a, b, c, d;
  95633. a = buf[0];
  95634. b = buf[1];
  95635. c = buf[2];
  95636. d = buf[3];
  95637. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  95638. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  95639. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  95640. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  95641. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  95642. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  95643. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  95644. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  95645. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  95646. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  95647. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  95648. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  95649. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  95650. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  95651. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  95652. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  95653. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  95654. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  95655. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  95656. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  95657. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  95658. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  95659. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  95660. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  95661. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  95662. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  95663. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  95664. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  95665. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  95666. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  95667. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  95668. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  95669. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  95670. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  95671. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  95672. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  95673. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  95674. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  95675. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  95676. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  95677. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  95678. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  95679. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  95680. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  95681. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  95682. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  95683. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  95684. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  95685. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  95686. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  95687. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  95688. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  95689. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  95690. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  95691. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  95692. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  95693. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  95694. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  95695. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  95696. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  95697. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  95698. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  95699. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  95700. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  95701. buf[0] += a;
  95702. buf[1] += b;
  95703. buf[2] += c;
  95704. buf[3] += d;
  95705. }
  95706. #if WORDS_BIGENDIAN
  95707. //@@@@@@ OPT: use bswap/intrinsics
  95708. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  95709. {
  95710. register FLAC__uint32 x;
  95711. do {
  95712. x = *buf;
  95713. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  95714. *buf++ = (x >> 16) | (x << 16);
  95715. } while (--words);
  95716. }
  95717. static void byteSwapX16(FLAC__uint32 *buf)
  95718. {
  95719. register FLAC__uint32 x;
  95720. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95721. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95722. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95723. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95724. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95725. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95726. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95727. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95728. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95729. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95730. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95731. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95732. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95733. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95734. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95735. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  95736. }
  95737. #else
  95738. #define byteSwap(buf, words)
  95739. #define byteSwapX16(buf)
  95740. #endif
  95741. /*
  95742. * Update context to reflect the concatenation of another buffer full
  95743. * of bytes.
  95744. */
  95745. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  95746. {
  95747. FLAC__uint32 t;
  95748. /* Update byte count */
  95749. t = ctx->bytes[0];
  95750. if ((ctx->bytes[0] = t + len) < t)
  95751. ctx->bytes[1]++; /* Carry from low to high */
  95752. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  95753. if (t > len) {
  95754. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  95755. return;
  95756. }
  95757. /* First chunk is an odd size */
  95758. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  95759. byteSwapX16(ctx->in);
  95760. FLAC__MD5Transform(ctx->buf, ctx->in);
  95761. buf += t;
  95762. len -= t;
  95763. /* Process data in 64-byte chunks */
  95764. while (len >= 64) {
  95765. memcpy(ctx->in, buf, 64);
  95766. byteSwapX16(ctx->in);
  95767. FLAC__MD5Transform(ctx->buf, ctx->in);
  95768. buf += 64;
  95769. len -= 64;
  95770. }
  95771. /* Handle any remaining bytes of data. */
  95772. memcpy(ctx->in, buf, len);
  95773. }
  95774. /*
  95775. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  95776. * initialization constants.
  95777. */
  95778. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  95779. {
  95780. ctx->buf[0] = 0x67452301;
  95781. ctx->buf[1] = 0xefcdab89;
  95782. ctx->buf[2] = 0x98badcfe;
  95783. ctx->buf[3] = 0x10325476;
  95784. ctx->bytes[0] = 0;
  95785. ctx->bytes[1] = 0;
  95786. ctx->internal_buf = 0;
  95787. ctx->capacity = 0;
  95788. }
  95789. /*
  95790. * Final wrapup - pad to 64-byte boundary with the bit pattern
  95791. * 1 0* (64-bit count of bits processed, MSB-first)
  95792. */
  95793. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  95794. {
  95795. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  95796. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  95797. /* Set the first char of padding to 0x80. There is always room. */
  95798. *p++ = 0x80;
  95799. /* Bytes of padding needed to make 56 bytes (-8..55) */
  95800. count = 56 - 1 - count;
  95801. if (count < 0) { /* Padding forces an extra block */
  95802. memset(p, 0, count + 8);
  95803. byteSwapX16(ctx->in);
  95804. FLAC__MD5Transform(ctx->buf, ctx->in);
  95805. p = (FLAC__byte *)ctx->in;
  95806. count = 56;
  95807. }
  95808. memset(p, 0, count);
  95809. byteSwap(ctx->in, 14);
  95810. /* Append length in bits and transform */
  95811. ctx->in[14] = ctx->bytes[0] << 3;
  95812. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  95813. FLAC__MD5Transform(ctx->buf, ctx->in);
  95814. byteSwap(ctx->buf, 4);
  95815. memcpy(digest, ctx->buf, 16);
  95816. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  95817. if(0 != ctx->internal_buf) {
  95818. free(ctx->internal_buf);
  95819. ctx->internal_buf = 0;
  95820. ctx->capacity = 0;
  95821. }
  95822. }
  95823. /*
  95824. * Convert the incoming audio signal to a byte stream
  95825. */
  95826. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  95827. {
  95828. unsigned channel, sample;
  95829. register FLAC__int32 a_word;
  95830. register FLAC__byte *buf_ = buf;
  95831. #if WORDS_BIGENDIAN
  95832. #else
  95833. if(channels == 2 && bytes_per_sample == 2) {
  95834. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  95835. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  95836. for(sample = 0; sample < samples; sample++, buf1_+=2)
  95837. *buf1_ = (FLAC__int16)signal[1][sample];
  95838. }
  95839. else if(channels == 1 && bytes_per_sample == 2) {
  95840. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  95841. for(sample = 0; sample < samples; sample++)
  95842. *buf1_++ = (FLAC__int16)signal[0][sample];
  95843. }
  95844. else
  95845. #endif
  95846. if(bytes_per_sample == 2) {
  95847. if(channels == 2) {
  95848. for(sample = 0; sample < samples; sample++) {
  95849. a_word = signal[0][sample];
  95850. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95851. *buf_++ = (FLAC__byte)a_word;
  95852. a_word = signal[1][sample];
  95853. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95854. *buf_++ = (FLAC__byte)a_word;
  95855. }
  95856. }
  95857. else if(channels == 1) {
  95858. for(sample = 0; sample < samples; sample++) {
  95859. a_word = signal[0][sample];
  95860. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95861. *buf_++ = (FLAC__byte)a_word;
  95862. }
  95863. }
  95864. else {
  95865. for(sample = 0; sample < samples; sample++) {
  95866. for(channel = 0; channel < channels; channel++) {
  95867. a_word = signal[channel][sample];
  95868. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95869. *buf_++ = (FLAC__byte)a_word;
  95870. }
  95871. }
  95872. }
  95873. }
  95874. else if(bytes_per_sample == 3) {
  95875. if(channels == 2) {
  95876. for(sample = 0; sample < samples; sample++) {
  95877. a_word = signal[0][sample];
  95878. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95879. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95880. *buf_++ = (FLAC__byte)a_word;
  95881. a_word = signal[1][sample];
  95882. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95883. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95884. *buf_++ = (FLAC__byte)a_word;
  95885. }
  95886. }
  95887. else if(channels == 1) {
  95888. for(sample = 0; sample < samples; sample++) {
  95889. a_word = signal[0][sample];
  95890. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95891. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95892. *buf_++ = (FLAC__byte)a_word;
  95893. }
  95894. }
  95895. else {
  95896. for(sample = 0; sample < samples; sample++) {
  95897. for(channel = 0; channel < channels; channel++) {
  95898. a_word = signal[channel][sample];
  95899. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95900. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95901. *buf_++ = (FLAC__byte)a_word;
  95902. }
  95903. }
  95904. }
  95905. }
  95906. else if(bytes_per_sample == 1) {
  95907. if(channels == 2) {
  95908. for(sample = 0; sample < samples; sample++) {
  95909. a_word = signal[0][sample];
  95910. *buf_++ = (FLAC__byte)a_word;
  95911. a_word = signal[1][sample];
  95912. *buf_++ = (FLAC__byte)a_word;
  95913. }
  95914. }
  95915. else if(channels == 1) {
  95916. for(sample = 0; sample < samples; sample++) {
  95917. a_word = signal[0][sample];
  95918. *buf_++ = (FLAC__byte)a_word;
  95919. }
  95920. }
  95921. else {
  95922. for(sample = 0; sample < samples; sample++) {
  95923. for(channel = 0; channel < channels; channel++) {
  95924. a_word = signal[channel][sample];
  95925. *buf_++ = (FLAC__byte)a_word;
  95926. }
  95927. }
  95928. }
  95929. }
  95930. else { /* bytes_per_sample == 4, maybe optimize more later */
  95931. for(sample = 0; sample < samples; sample++) {
  95932. for(channel = 0; channel < channels; channel++) {
  95933. a_word = signal[channel][sample];
  95934. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95935. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95936. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95937. *buf_++ = (FLAC__byte)a_word;
  95938. }
  95939. }
  95940. }
  95941. }
  95942. /*
  95943. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  95944. */
  95945. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  95946. {
  95947. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  95948. /* overflow check */
  95949. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  95950. return false;
  95951. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  95952. return false;
  95953. if(ctx->capacity < bytes_needed) {
  95954. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  95955. if(0 == tmp) {
  95956. free(ctx->internal_buf);
  95957. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  95958. return false;
  95959. }
  95960. ctx->internal_buf = tmp;
  95961. ctx->capacity = bytes_needed;
  95962. }
  95963. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  95964. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  95965. return true;
  95966. }
  95967. #endif
  95968. /*** End of inlined file: md5.c ***/
  95969. /*** Start of inlined file: memory.c ***/
  95970. /*** Start of inlined file: juce_FlacHeader.h ***/
  95971. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95972. // tasks..
  95973. #define VERSION "1.2.1"
  95974. #define FLAC__NO_DLL 1
  95975. #if JUCE_MSVC
  95976. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95977. #endif
  95978. #if JUCE_MAC
  95979. #define FLAC__SYS_DARWIN 1
  95980. #endif
  95981. /*** End of inlined file: juce_FlacHeader.h ***/
  95982. #if JUCE_USE_FLAC
  95983. #if HAVE_CONFIG_H
  95984. # include <config.h>
  95985. #endif
  95986. /*** Start of inlined file: memory.h ***/
  95987. #ifndef FLAC__PRIVATE__MEMORY_H
  95988. #define FLAC__PRIVATE__MEMORY_H
  95989. #ifdef HAVE_CONFIG_H
  95990. #include <config.h>
  95991. #endif
  95992. #include <stdlib.h> /* for size_t */
  95993. /* Returns the unaligned address returned by malloc.
  95994. * Use free() on this address to deallocate.
  95995. */
  95996. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  95997. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  95998. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  95999. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  96000. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  96001. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96002. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  96003. #endif
  96004. #endif
  96005. /*** End of inlined file: memory.h ***/
  96006. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  96007. {
  96008. void *x;
  96009. FLAC__ASSERT(0 != aligned_address);
  96010. #ifdef FLAC__ALIGN_MALLOC_DATA
  96011. /* align on 32-byte (256-bit) boundary */
  96012. x = safe_malloc_add_2op_(bytes, /*+*/31);
  96013. #ifdef SIZEOF_VOIDP
  96014. #if SIZEOF_VOIDP == 4
  96015. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  96016. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  96017. #elif SIZEOF_VOIDP == 8
  96018. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  96019. #else
  96020. # error Unsupported sizeof(void*)
  96021. #endif
  96022. #else
  96023. /* there's got to be a better way to do this right for all archs */
  96024. if(sizeof(void*) == sizeof(unsigned))
  96025. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  96026. else if(sizeof(void*) == sizeof(FLAC__uint64))
  96027. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  96028. else
  96029. return 0;
  96030. #endif
  96031. #else
  96032. x = safe_malloc_(bytes);
  96033. *aligned_address = x;
  96034. #endif
  96035. return x;
  96036. }
  96037. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  96038. {
  96039. FLAC__int32 *pu; /* unaligned pointer */
  96040. union { /* union needed to comply with C99 pointer aliasing rules */
  96041. FLAC__int32 *pa; /* aligned pointer */
  96042. void *pv; /* aligned pointer alias */
  96043. } u;
  96044. FLAC__ASSERT(elements > 0);
  96045. FLAC__ASSERT(0 != unaligned_pointer);
  96046. FLAC__ASSERT(0 != aligned_pointer);
  96047. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  96048. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  96049. if(0 == pu) {
  96050. return false;
  96051. }
  96052. else {
  96053. if(*unaligned_pointer != 0)
  96054. free(*unaligned_pointer);
  96055. *unaligned_pointer = pu;
  96056. *aligned_pointer = u.pa;
  96057. return true;
  96058. }
  96059. }
  96060. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  96061. {
  96062. FLAC__uint32 *pu; /* unaligned pointer */
  96063. union { /* union needed to comply with C99 pointer aliasing rules */
  96064. FLAC__uint32 *pa; /* aligned pointer */
  96065. void *pv; /* aligned pointer alias */
  96066. } u;
  96067. FLAC__ASSERT(elements > 0);
  96068. FLAC__ASSERT(0 != unaligned_pointer);
  96069. FLAC__ASSERT(0 != aligned_pointer);
  96070. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  96071. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  96072. if(0 == pu) {
  96073. return false;
  96074. }
  96075. else {
  96076. if(*unaligned_pointer != 0)
  96077. free(*unaligned_pointer);
  96078. *unaligned_pointer = pu;
  96079. *aligned_pointer = u.pa;
  96080. return true;
  96081. }
  96082. }
  96083. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  96084. {
  96085. FLAC__uint64 *pu; /* unaligned pointer */
  96086. union { /* union needed to comply with C99 pointer aliasing rules */
  96087. FLAC__uint64 *pa; /* aligned pointer */
  96088. void *pv; /* aligned pointer alias */
  96089. } u;
  96090. FLAC__ASSERT(elements > 0);
  96091. FLAC__ASSERT(0 != unaligned_pointer);
  96092. FLAC__ASSERT(0 != aligned_pointer);
  96093. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  96094. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  96095. if(0 == pu) {
  96096. return false;
  96097. }
  96098. else {
  96099. if(*unaligned_pointer != 0)
  96100. free(*unaligned_pointer);
  96101. *unaligned_pointer = pu;
  96102. *aligned_pointer = u.pa;
  96103. return true;
  96104. }
  96105. }
  96106. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  96107. {
  96108. unsigned *pu; /* unaligned pointer */
  96109. union { /* union needed to comply with C99 pointer aliasing rules */
  96110. unsigned *pa; /* aligned pointer */
  96111. void *pv; /* aligned pointer alias */
  96112. } u;
  96113. FLAC__ASSERT(elements > 0);
  96114. FLAC__ASSERT(0 != unaligned_pointer);
  96115. FLAC__ASSERT(0 != aligned_pointer);
  96116. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  96117. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  96118. if(0 == pu) {
  96119. return false;
  96120. }
  96121. else {
  96122. if(*unaligned_pointer != 0)
  96123. free(*unaligned_pointer);
  96124. *unaligned_pointer = pu;
  96125. *aligned_pointer = u.pa;
  96126. return true;
  96127. }
  96128. }
  96129. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96130. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  96131. {
  96132. FLAC__real *pu; /* unaligned pointer */
  96133. union { /* union needed to comply with C99 pointer aliasing rules */
  96134. FLAC__real *pa; /* aligned pointer */
  96135. void *pv; /* aligned pointer alias */
  96136. } u;
  96137. FLAC__ASSERT(elements > 0);
  96138. FLAC__ASSERT(0 != unaligned_pointer);
  96139. FLAC__ASSERT(0 != aligned_pointer);
  96140. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  96141. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  96142. if(0 == pu) {
  96143. return false;
  96144. }
  96145. else {
  96146. if(*unaligned_pointer != 0)
  96147. free(*unaligned_pointer);
  96148. *unaligned_pointer = pu;
  96149. *aligned_pointer = u.pa;
  96150. return true;
  96151. }
  96152. }
  96153. #endif
  96154. #endif
  96155. /*** End of inlined file: memory.c ***/
  96156. /*** Start of inlined file: stream_decoder.c ***/
  96157. /*** Start of inlined file: juce_FlacHeader.h ***/
  96158. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96159. // tasks..
  96160. #define VERSION "1.2.1"
  96161. #define FLAC__NO_DLL 1
  96162. #if JUCE_MSVC
  96163. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96164. #endif
  96165. #if JUCE_MAC
  96166. #define FLAC__SYS_DARWIN 1
  96167. #endif
  96168. /*** End of inlined file: juce_FlacHeader.h ***/
  96169. #if JUCE_USE_FLAC
  96170. #if HAVE_CONFIG_H
  96171. # include <config.h>
  96172. #endif
  96173. #if defined _MSC_VER || defined __MINGW32__
  96174. #include <io.h> /* for _setmode() */
  96175. #include <fcntl.h> /* for _O_BINARY */
  96176. #endif
  96177. #if defined __CYGWIN__ || defined __EMX__
  96178. #include <io.h> /* for setmode(), O_BINARY */
  96179. #include <fcntl.h> /* for _O_BINARY */
  96180. #endif
  96181. #include <stdio.h>
  96182. #include <stdlib.h> /* for malloc() */
  96183. #include <string.h> /* for memset/memcpy() */
  96184. #include <sys/stat.h> /* for stat() */
  96185. #include <sys/types.h> /* for off_t */
  96186. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  96187. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  96188. #define fseeko fseek
  96189. #define ftello ftell
  96190. #endif
  96191. #endif
  96192. /*** Start of inlined file: stream_decoder.h ***/
  96193. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  96194. #define FLAC__PROTECTED__STREAM_DECODER_H
  96195. #if FLAC__HAS_OGG
  96196. #include "include/private/ogg_decoder_aspect.h"
  96197. #endif
  96198. typedef struct FLAC__StreamDecoderProtected {
  96199. FLAC__StreamDecoderState state;
  96200. unsigned channels;
  96201. FLAC__ChannelAssignment channel_assignment;
  96202. unsigned bits_per_sample;
  96203. unsigned sample_rate; /* in Hz */
  96204. unsigned blocksize; /* in samples (per channel) */
  96205. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  96206. #if FLAC__HAS_OGG
  96207. FLAC__OggDecoderAspect ogg_decoder_aspect;
  96208. #endif
  96209. } FLAC__StreamDecoderProtected;
  96210. /*
  96211. * return the number of input bytes consumed
  96212. */
  96213. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  96214. #endif
  96215. /*** End of inlined file: stream_decoder.h ***/
  96216. #ifdef max
  96217. #undef max
  96218. #endif
  96219. #define max(a,b) ((a)>(b)?(a):(b))
  96220. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96221. #ifdef _MSC_VER
  96222. #define FLAC__U64L(x) x
  96223. #else
  96224. #define FLAC__U64L(x) x##LLU
  96225. #endif
  96226. /* technically this should be in an "export.c" but this is convenient enough */
  96227. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  96228. #if FLAC__HAS_OGG
  96229. 1
  96230. #else
  96231. 0
  96232. #endif
  96233. ;
  96234. /***********************************************************************
  96235. *
  96236. * Private static data
  96237. *
  96238. ***********************************************************************/
  96239. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  96240. /***********************************************************************
  96241. *
  96242. * Private class method prototypes
  96243. *
  96244. ***********************************************************************/
  96245. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  96246. static FILE *get_binary_stdin_(void);
  96247. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  96248. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  96249. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  96250. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  96251. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  96252. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  96253. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  96254. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  96255. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  96256. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  96257. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  96258. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  96259. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  96260. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  96261. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  96262. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  96263. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  96264. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  96265. 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);
  96266. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  96267. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  96268. #if FLAC__HAS_OGG
  96269. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  96270. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  96271. #endif
  96272. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  96273. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  96274. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  96275. #if FLAC__HAS_OGG
  96276. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  96277. #endif
  96278. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  96279. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  96280. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  96281. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  96282. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  96283. /***********************************************************************
  96284. *
  96285. * Private class data
  96286. *
  96287. ***********************************************************************/
  96288. typedef struct FLAC__StreamDecoderPrivate {
  96289. #if FLAC__HAS_OGG
  96290. FLAC__bool is_ogg;
  96291. #endif
  96292. FLAC__StreamDecoderReadCallback read_callback;
  96293. FLAC__StreamDecoderSeekCallback seek_callback;
  96294. FLAC__StreamDecoderTellCallback tell_callback;
  96295. FLAC__StreamDecoderLengthCallback length_callback;
  96296. FLAC__StreamDecoderEofCallback eof_callback;
  96297. FLAC__StreamDecoderWriteCallback write_callback;
  96298. FLAC__StreamDecoderMetadataCallback metadata_callback;
  96299. FLAC__StreamDecoderErrorCallback error_callback;
  96300. /* generic 32-bit datapath: */
  96301. 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[]);
  96302. /* generic 64-bit datapath: */
  96303. 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[]);
  96304. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  96305. 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[]);
  96306. /* 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: */
  96307. 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[]);
  96308. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  96309. void *client_data;
  96310. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  96311. FLAC__BitReader *input;
  96312. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  96313. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  96314. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  96315. unsigned output_capacity, output_channels;
  96316. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  96317. FLAC__uint64 samples_decoded;
  96318. FLAC__bool has_stream_info, has_seek_table;
  96319. FLAC__StreamMetadata stream_info;
  96320. FLAC__StreamMetadata seek_table;
  96321. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  96322. FLAC__byte *metadata_filter_ids;
  96323. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  96324. FLAC__Frame frame;
  96325. FLAC__bool cached; /* true if there is a byte in lookahead */
  96326. FLAC__CPUInfo cpuinfo;
  96327. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  96328. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  96329. /* unaligned (original) pointers to allocated data */
  96330. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  96331. 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 */
  96332. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  96333. FLAC__bool is_seeking;
  96334. FLAC__MD5Context md5context;
  96335. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  96336. /* (the rest of these are only used for seeking) */
  96337. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  96338. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  96339. FLAC__uint64 target_sample;
  96340. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  96341. #if FLAC__HAS_OGG
  96342. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  96343. #endif
  96344. } FLAC__StreamDecoderPrivate;
  96345. /***********************************************************************
  96346. *
  96347. * Public static class data
  96348. *
  96349. ***********************************************************************/
  96350. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  96351. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  96352. "FLAC__STREAM_DECODER_READ_METADATA",
  96353. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  96354. "FLAC__STREAM_DECODER_READ_FRAME",
  96355. "FLAC__STREAM_DECODER_END_OF_STREAM",
  96356. "FLAC__STREAM_DECODER_OGG_ERROR",
  96357. "FLAC__STREAM_DECODER_SEEK_ERROR",
  96358. "FLAC__STREAM_DECODER_ABORTED",
  96359. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  96360. "FLAC__STREAM_DECODER_UNINITIALIZED"
  96361. };
  96362. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  96363. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  96364. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  96365. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  96366. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  96367. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  96368. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  96369. };
  96370. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  96371. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  96372. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  96373. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  96374. };
  96375. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  96376. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  96377. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  96378. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  96379. };
  96380. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  96381. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  96382. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  96383. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  96384. };
  96385. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  96386. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  96387. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  96388. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  96389. };
  96390. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  96391. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  96392. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  96393. };
  96394. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  96395. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  96396. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  96397. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  96398. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  96399. };
  96400. /***********************************************************************
  96401. *
  96402. * Class constructor/destructor
  96403. *
  96404. ***********************************************************************/
  96405. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  96406. {
  96407. FLAC__StreamDecoder *decoder;
  96408. unsigned i;
  96409. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  96410. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  96411. if(decoder == 0) {
  96412. return 0;
  96413. }
  96414. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  96415. if(decoder->protected_ == 0) {
  96416. free(decoder);
  96417. return 0;
  96418. }
  96419. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  96420. if(decoder->private_ == 0) {
  96421. free(decoder->protected_);
  96422. free(decoder);
  96423. return 0;
  96424. }
  96425. decoder->private_->input = FLAC__bitreader_new();
  96426. if(decoder->private_->input == 0) {
  96427. free(decoder->private_);
  96428. free(decoder->protected_);
  96429. free(decoder);
  96430. return 0;
  96431. }
  96432. decoder->private_->metadata_filter_ids_capacity = 16;
  96433. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  96434. FLAC__bitreader_delete(decoder->private_->input);
  96435. free(decoder->private_);
  96436. free(decoder->protected_);
  96437. free(decoder);
  96438. return 0;
  96439. }
  96440. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  96441. decoder->private_->output[i] = 0;
  96442. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  96443. }
  96444. decoder->private_->output_capacity = 0;
  96445. decoder->private_->output_channels = 0;
  96446. decoder->private_->has_seek_table = false;
  96447. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  96448. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  96449. decoder->private_->file = 0;
  96450. set_defaults_dec(decoder);
  96451. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  96452. return decoder;
  96453. }
  96454. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  96455. {
  96456. unsigned i;
  96457. FLAC__ASSERT(0 != decoder);
  96458. FLAC__ASSERT(0 != decoder->protected_);
  96459. FLAC__ASSERT(0 != decoder->private_);
  96460. FLAC__ASSERT(0 != decoder->private_->input);
  96461. (void)FLAC__stream_decoder_finish(decoder);
  96462. if(0 != decoder->private_->metadata_filter_ids)
  96463. free(decoder->private_->metadata_filter_ids);
  96464. FLAC__bitreader_delete(decoder->private_->input);
  96465. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  96466. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  96467. free(decoder->private_);
  96468. free(decoder->protected_);
  96469. free(decoder);
  96470. }
  96471. /***********************************************************************
  96472. *
  96473. * Public class methods
  96474. *
  96475. ***********************************************************************/
  96476. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  96477. FLAC__StreamDecoder *decoder,
  96478. FLAC__StreamDecoderReadCallback read_callback,
  96479. FLAC__StreamDecoderSeekCallback seek_callback,
  96480. FLAC__StreamDecoderTellCallback tell_callback,
  96481. FLAC__StreamDecoderLengthCallback length_callback,
  96482. FLAC__StreamDecoderEofCallback eof_callback,
  96483. FLAC__StreamDecoderWriteCallback write_callback,
  96484. FLAC__StreamDecoderMetadataCallback metadata_callback,
  96485. FLAC__StreamDecoderErrorCallback error_callback,
  96486. void *client_data,
  96487. FLAC__bool is_ogg
  96488. )
  96489. {
  96490. FLAC__ASSERT(0 != decoder);
  96491. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96492. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  96493. #if !FLAC__HAS_OGG
  96494. if(is_ogg)
  96495. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  96496. #endif
  96497. if(
  96498. 0 == read_callback ||
  96499. 0 == write_callback ||
  96500. 0 == error_callback ||
  96501. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  96502. )
  96503. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  96504. #if FLAC__HAS_OGG
  96505. decoder->private_->is_ogg = is_ogg;
  96506. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  96507. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  96508. #endif
  96509. /*
  96510. * get the CPU info and set the function pointers
  96511. */
  96512. FLAC__cpu_info(&decoder->private_->cpuinfo);
  96513. /* first default to the non-asm routines */
  96514. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  96515. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  96516. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  96517. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  96518. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  96519. /* now override with asm where appropriate */
  96520. #ifndef FLAC__NO_ASM
  96521. if(decoder->private_->cpuinfo.use_asm) {
  96522. #ifdef FLAC__CPU_IA32
  96523. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  96524. #ifdef FLAC__HAS_NASM
  96525. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  96526. if(decoder->private_->cpuinfo.data.ia32.bswap)
  96527. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  96528. #endif
  96529. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  96530. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  96531. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  96532. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  96533. }
  96534. else {
  96535. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  96536. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  96537. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  96538. }
  96539. #endif
  96540. #elif defined FLAC__CPU_PPC
  96541. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  96542. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  96543. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  96544. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  96545. }
  96546. #endif
  96547. }
  96548. #endif
  96549. /* from here on, errors are fatal */
  96550. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  96551. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96552. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  96553. }
  96554. decoder->private_->read_callback = read_callback;
  96555. decoder->private_->seek_callback = seek_callback;
  96556. decoder->private_->tell_callback = tell_callback;
  96557. decoder->private_->length_callback = length_callback;
  96558. decoder->private_->eof_callback = eof_callback;
  96559. decoder->private_->write_callback = write_callback;
  96560. decoder->private_->metadata_callback = metadata_callback;
  96561. decoder->private_->error_callback = error_callback;
  96562. decoder->private_->client_data = client_data;
  96563. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  96564. decoder->private_->samples_decoded = 0;
  96565. decoder->private_->has_stream_info = false;
  96566. decoder->private_->cached = false;
  96567. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  96568. decoder->private_->is_seeking = false;
  96569. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  96570. if(!FLAC__stream_decoder_reset(decoder)) {
  96571. /* above call sets the state for us */
  96572. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  96573. }
  96574. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  96575. }
  96576. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  96577. FLAC__StreamDecoder *decoder,
  96578. FLAC__StreamDecoderReadCallback read_callback,
  96579. FLAC__StreamDecoderSeekCallback seek_callback,
  96580. FLAC__StreamDecoderTellCallback tell_callback,
  96581. FLAC__StreamDecoderLengthCallback length_callback,
  96582. FLAC__StreamDecoderEofCallback eof_callback,
  96583. FLAC__StreamDecoderWriteCallback write_callback,
  96584. FLAC__StreamDecoderMetadataCallback metadata_callback,
  96585. FLAC__StreamDecoderErrorCallback error_callback,
  96586. void *client_data
  96587. )
  96588. {
  96589. return init_stream_internal_dec(
  96590. decoder,
  96591. read_callback,
  96592. seek_callback,
  96593. tell_callback,
  96594. length_callback,
  96595. eof_callback,
  96596. write_callback,
  96597. metadata_callback,
  96598. error_callback,
  96599. client_data,
  96600. /*is_ogg=*/false
  96601. );
  96602. }
  96603. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  96604. FLAC__StreamDecoder *decoder,
  96605. FLAC__StreamDecoderReadCallback read_callback,
  96606. FLAC__StreamDecoderSeekCallback seek_callback,
  96607. FLAC__StreamDecoderTellCallback tell_callback,
  96608. FLAC__StreamDecoderLengthCallback length_callback,
  96609. FLAC__StreamDecoderEofCallback eof_callback,
  96610. FLAC__StreamDecoderWriteCallback write_callback,
  96611. FLAC__StreamDecoderMetadataCallback metadata_callback,
  96612. FLAC__StreamDecoderErrorCallback error_callback,
  96613. void *client_data
  96614. )
  96615. {
  96616. return init_stream_internal_dec(
  96617. decoder,
  96618. read_callback,
  96619. seek_callback,
  96620. tell_callback,
  96621. length_callback,
  96622. eof_callback,
  96623. write_callback,
  96624. metadata_callback,
  96625. error_callback,
  96626. client_data,
  96627. /*is_ogg=*/true
  96628. );
  96629. }
  96630. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  96631. FLAC__StreamDecoder *decoder,
  96632. FILE *file,
  96633. FLAC__StreamDecoderWriteCallback write_callback,
  96634. FLAC__StreamDecoderMetadataCallback metadata_callback,
  96635. FLAC__StreamDecoderErrorCallback error_callback,
  96636. void *client_data,
  96637. FLAC__bool is_ogg
  96638. )
  96639. {
  96640. FLAC__ASSERT(0 != decoder);
  96641. FLAC__ASSERT(0 != file);
  96642. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96643. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  96644. if(0 == write_callback || 0 == error_callback)
  96645. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  96646. /*
  96647. * To make sure that our file does not go unclosed after an error, we
  96648. * must assign the FILE pointer before any further error can occur in
  96649. * this routine.
  96650. */
  96651. if(file == stdin)
  96652. file = get_binary_stdin_(); /* just to be safe */
  96653. decoder->private_->file = file;
  96654. return init_stream_internal_dec(
  96655. decoder,
  96656. file_read_callback_dec,
  96657. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  96658. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  96659. decoder->private_->file == stdin? 0: file_length_callback_,
  96660. file_eof_callback_,
  96661. write_callback,
  96662. metadata_callback,
  96663. error_callback,
  96664. client_data,
  96665. is_ogg
  96666. );
  96667. }
  96668. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  96669. FLAC__StreamDecoder *decoder,
  96670. FILE *file,
  96671. FLAC__StreamDecoderWriteCallback write_callback,
  96672. FLAC__StreamDecoderMetadataCallback metadata_callback,
  96673. FLAC__StreamDecoderErrorCallback error_callback,
  96674. void *client_data
  96675. )
  96676. {
  96677. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  96678. }
  96679. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  96680. FLAC__StreamDecoder *decoder,
  96681. FILE *file,
  96682. FLAC__StreamDecoderWriteCallback write_callback,
  96683. FLAC__StreamDecoderMetadataCallback metadata_callback,
  96684. FLAC__StreamDecoderErrorCallback error_callback,
  96685. void *client_data
  96686. )
  96687. {
  96688. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  96689. }
  96690. static FLAC__StreamDecoderInitStatus init_file_internal_(
  96691. FLAC__StreamDecoder *decoder,
  96692. const char *filename,
  96693. FLAC__StreamDecoderWriteCallback write_callback,
  96694. FLAC__StreamDecoderMetadataCallback metadata_callback,
  96695. FLAC__StreamDecoderErrorCallback error_callback,
  96696. void *client_data,
  96697. FLAC__bool is_ogg
  96698. )
  96699. {
  96700. FILE *file;
  96701. FLAC__ASSERT(0 != decoder);
  96702. /*
  96703. * To make sure that our file does not go unclosed after an error, we
  96704. * have to do the same entrance checks here that are later performed
  96705. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  96706. */
  96707. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96708. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  96709. if(0 == write_callback || 0 == error_callback)
  96710. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  96711. file = filename? fopen(filename, "rb") : stdin;
  96712. if(0 == file)
  96713. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  96714. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  96715. }
  96716. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  96717. FLAC__StreamDecoder *decoder,
  96718. const char *filename,
  96719. FLAC__StreamDecoderWriteCallback write_callback,
  96720. FLAC__StreamDecoderMetadataCallback metadata_callback,
  96721. FLAC__StreamDecoderErrorCallback error_callback,
  96722. void *client_data
  96723. )
  96724. {
  96725. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  96726. }
  96727. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  96728. FLAC__StreamDecoder *decoder,
  96729. const char *filename,
  96730. FLAC__StreamDecoderWriteCallback write_callback,
  96731. FLAC__StreamDecoderMetadataCallback metadata_callback,
  96732. FLAC__StreamDecoderErrorCallback error_callback,
  96733. void *client_data
  96734. )
  96735. {
  96736. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  96737. }
  96738. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  96739. {
  96740. FLAC__bool md5_failed = false;
  96741. unsigned i;
  96742. FLAC__ASSERT(0 != decoder);
  96743. FLAC__ASSERT(0 != decoder->private_);
  96744. FLAC__ASSERT(0 != decoder->protected_);
  96745. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  96746. return true;
  96747. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  96748. * always call FLAC__MD5Final()
  96749. */
  96750. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  96751. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  96752. free(decoder->private_->seek_table.data.seek_table.points);
  96753. decoder->private_->seek_table.data.seek_table.points = 0;
  96754. decoder->private_->has_seek_table = false;
  96755. }
  96756. FLAC__bitreader_free(decoder->private_->input);
  96757. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  96758. /* WATCHOUT:
  96759. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  96760. * output arrays have a buffer of up to 3 zeroes in front
  96761. * (at negative indices) for alignment purposes; we use 4
  96762. * to keep the data well-aligned.
  96763. */
  96764. if(0 != decoder->private_->output[i]) {
  96765. free(decoder->private_->output[i]-4);
  96766. decoder->private_->output[i] = 0;
  96767. }
  96768. if(0 != decoder->private_->residual_unaligned[i]) {
  96769. free(decoder->private_->residual_unaligned[i]);
  96770. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  96771. }
  96772. }
  96773. decoder->private_->output_capacity = 0;
  96774. decoder->private_->output_channels = 0;
  96775. #if FLAC__HAS_OGG
  96776. if(decoder->private_->is_ogg)
  96777. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  96778. #endif
  96779. if(0 != decoder->private_->file) {
  96780. if(decoder->private_->file != stdin)
  96781. fclose(decoder->private_->file);
  96782. decoder->private_->file = 0;
  96783. }
  96784. if(decoder->private_->do_md5_checking) {
  96785. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  96786. md5_failed = true;
  96787. }
  96788. decoder->private_->is_seeking = false;
  96789. set_defaults_dec(decoder);
  96790. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  96791. return !md5_failed;
  96792. }
  96793. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  96794. {
  96795. FLAC__ASSERT(0 != decoder);
  96796. FLAC__ASSERT(0 != decoder->private_);
  96797. FLAC__ASSERT(0 != decoder->protected_);
  96798. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96799. return false;
  96800. #if FLAC__HAS_OGG
  96801. /* can't check decoder->private_->is_ogg since that's not set until init time */
  96802. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  96803. return true;
  96804. #else
  96805. (void)value;
  96806. return false;
  96807. #endif
  96808. }
  96809. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  96810. {
  96811. FLAC__ASSERT(0 != decoder);
  96812. FLAC__ASSERT(0 != decoder->protected_);
  96813. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96814. return false;
  96815. decoder->protected_->md5_checking = value;
  96816. return true;
  96817. }
  96818. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  96819. {
  96820. FLAC__ASSERT(0 != decoder);
  96821. FLAC__ASSERT(0 != decoder->private_);
  96822. FLAC__ASSERT(0 != decoder->protected_);
  96823. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  96824. /* double protection */
  96825. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  96826. return false;
  96827. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96828. return false;
  96829. decoder->private_->metadata_filter[type] = true;
  96830. if(type == FLAC__METADATA_TYPE_APPLICATION)
  96831. decoder->private_->metadata_filter_ids_count = 0;
  96832. return true;
  96833. }
  96834. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  96835. {
  96836. FLAC__ASSERT(0 != decoder);
  96837. FLAC__ASSERT(0 != decoder->private_);
  96838. FLAC__ASSERT(0 != decoder->protected_);
  96839. FLAC__ASSERT(0 != id);
  96840. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96841. return false;
  96842. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  96843. return true;
  96844. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  96845. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  96846. 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))) {
  96847. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96848. return false;
  96849. }
  96850. decoder->private_->metadata_filter_ids_capacity *= 2;
  96851. }
  96852. 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));
  96853. decoder->private_->metadata_filter_ids_count++;
  96854. return true;
  96855. }
  96856. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  96857. {
  96858. unsigned i;
  96859. FLAC__ASSERT(0 != decoder);
  96860. FLAC__ASSERT(0 != decoder->private_);
  96861. FLAC__ASSERT(0 != decoder->protected_);
  96862. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96863. return false;
  96864. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  96865. decoder->private_->metadata_filter[i] = true;
  96866. decoder->private_->metadata_filter_ids_count = 0;
  96867. return true;
  96868. }
  96869. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  96870. {
  96871. FLAC__ASSERT(0 != decoder);
  96872. FLAC__ASSERT(0 != decoder->private_);
  96873. FLAC__ASSERT(0 != decoder->protected_);
  96874. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  96875. /* double protection */
  96876. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  96877. return false;
  96878. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96879. return false;
  96880. decoder->private_->metadata_filter[type] = false;
  96881. if(type == FLAC__METADATA_TYPE_APPLICATION)
  96882. decoder->private_->metadata_filter_ids_count = 0;
  96883. return true;
  96884. }
  96885. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  96886. {
  96887. FLAC__ASSERT(0 != decoder);
  96888. FLAC__ASSERT(0 != decoder->private_);
  96889. FLAC__ASSERT(0 != decoder->protected_);
  96890. FLAC__ASSERT(0 != id);
  96891. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96892. return false;
  96893. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  96894. return true;
  96895. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  96896. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  96897. 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))) {
  96898. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96899. return false;
  96900. }
  96901. decoder->private_->metadata_filter_ids_capacity *= 2;
  96902. }
  96903. 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));
  96904. decoder->private_->metadata_filter_ids_count++;
  96905. return true;
  96906. }
  96907. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  96908. {
  96909. FLAC__ASSERT(0 != decoder);
  96910. FLAC__ASSERT(0 != decoder->private_);
  96911. FLAC__ASSERT(0 != decoder->protected_);
  96912. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96913. return false;
  96914. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  96915. decoder->private_->metadata_filter_ids_count = 0;
  96916. return true;
  96917. }
  96918. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  96919. {
  96920. FLAC__ASSERT(0 != decoder);
  96921. FLAC__ASSERT(0 != decoder->protected_);
  96922. return decoder->protected_->state;
  96923. }
  96924. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  96925. {
  96926. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  96927. }
  96928. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  96929. {
  96930. FLAC__ASSERT(0 != decoder);
  96931. FLAC__ASSERT(0 != decoder->protected_);
  96932. return decoder->protected_->md5_checking;
  96933. }
  96934. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  96935. {
  96936. FLAC__ASSERT(0 != decoder);
  96937. FLAC__ASSERT(0 != decoder->protected_);
  96938. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  96939. }
  96940. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  96941. {
  96942. FLAC__ASSERT(0 != decoder);
  96943. FLAC__ASSERT(0 != decoder->protected_);
  96944. return decoder->protected_->channels;
  96945. }
  96946. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  96947. {
  96948. FLAC__ASSERT(0 != decoder);
  96949. FLAC__ASSERT(0 != decoder->protected_);
  96950. return decoder->protected_->channel_assignment;
  96951. }
  96952. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  96953. {
  96954. FLAC__ASSERT(0 != decoder);
  96955. FLAC__ASSERT(0 != decoder->protected_);
  96956. return decoder->protected_->bits_per_sample;
  96957. }
  96958. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  96959. {
  96960. FLAC__ASSERT(0 != decoder);
  96961. FLAC__ASSERT(0 != decoder->protected_);
  96962. return decoder->protected_->sample_rate;
  96963. }
  96964. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  96965. {
  96966. FLAC__ASSERT(0 != decoder);
  96967. FLAC__ASSERT(0 != decoder->protected_);
  96968. return decoder->protected_->blocksize;
  96969. }
  96970. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  96971. {
  96972. FLAC__ASSERT(0 != decoder);
  96973. FLAC__ASSERT(0 != decoder->private_);
  96974. FLAC__ASSERT(0 != position);
  96975. #if FLAC__HAS_OGG
  96976. if(decoder->private_->is_ogg)
  96977. return false;
  96978. #endif
  96979. if(0 == decoder->private_->tell_callback)
  96980. return false;
  96981. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  96982. return false;
  96983. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  96984. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  96985. return false;
  96986. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  96987. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  96988. return true;
  96989. }
  96990. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  96991. {
  96992. FLAC__ASSERT(0 != decoder);
  96993. FLAC__ASSERT(0 != decoder->private_);
  96994. FLAC__ASSERT(0 != decoder->protected_);
  96995. decoder->private_->samples_decoded = 0;
  96996. decoder->private_->do_md5_checking = false;
  96997. #if FLAC__HAS_OGG
  96998. if(decoder->private_->is_ogg)
  96999. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  97000. #endif
  97001. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  97002. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97003. return false;
  97004. }
  97005. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97006. return true;
  97007. }
  97008. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  97009. {
  97010. FLAC__ASSERT(0 != decoder);
  97011. FLAC__ASSERT(0 != decoder->private_);
  97012. FLAC__ASSERT(0 != decoder->protected_);
  97013. if(!FLAC__stream_decoder_flush(decoder)) {
  97014. /* above call sets the state for us */
  97015. return false;
  97016. }
  97017. #if FLAC__HAS_OGG
  97018. /*@@@ could go in !internal_reset_hack block below */
  97019. if(decoder->private_->is_ogg)
  97020. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  97021. #endif
  97022. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  97023. * (internal_reset_hack) don't try to rewind since we are already at
  97024. * the beginning of the stream and don't want to fail if the input is
  97025. * not seekable.
  97026. */
  97027. if(!decoder->private_->internal_reset_hack) {
  97028. if(decoder->private_->file == stdin)
  97029. return false; /* can't rewind stdin, reset fails */
  97030. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  97031. return false; /* seekable and seek fails, reset fails */
  97032. }
  97033. else
  97034. decoder->private_->internal_reset_hack = false;
  97035. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  97036. decoder->private_->has_stream_info = false;
  97037. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  97038. free(decoder->private_->seek_table.data.seek_table.points);
  97039. decoder->private_->seek_table.data.seek_table.points = 0;
  97040. decoder->private_->has_seek_table = false;
  97041. }
  97042. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  97043. /*
  97044. * This goes in reset() and not flush() because according to the spec, a
  97045. * fixed-blocksize stream must stay that way through the whole stream.
  97046. */
  97047. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  97048. /* We initialize the FLAC__MD5Context even though we may never use it. This
  97049. * is because md5 checking may be turned on to start and then turned off if
  97050. * a seek occurs. So we init the context here and finalize it in
  97051. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  97052. * properly.
  97053. */
  97054. FLAC__MD5Init(&decoder->private_->md5context);
  97055. decoder->private_->first_frame_offset = 0;
  97056. decoder->private_->unparseable_frame_count = 0;
  97057. return true;
  97058. }
  97059. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  97060. {
  97061. FLAC__bool got_a_frame;
  97062. FLAC__ASSERT(0 != decoder);
  97063. FLAC__ASSERT(0 != decoder->protected_);
  97064. while(1) {
  97065. switch(decoder->protected_->state) {
  97066. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  97067. if(!find_metadata_(decoder))
  97068. return false; /* above function sets the status for us */
  97069. break;
  97070. case FLAC__STREAM_DECODER_READ_METADATA:
  97071. if(!read_metadata_(decoder))
  97072. return false; /* above function sets the status for us */
  97073. else
  97074. return true;
  97075. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  97076. if(!frame_sync_(decoder))
  97077. return true; /* above function sets the status for us */
  97078. break;
  97079. case FLAC__STREAM_DECODER_READ_FRAME:
  97080. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  97081. return false; /* above function sets the status for us */
  97082. if(got_a_frame)
  97083. return true; /* above function sets the status for us */
  97084. break;
  97085. case FLAC__STREAM_DECODER_END_OF_STREAM:
  97086. case FLAC__STREAM_DECODER_ABORTED:
  97087. return true;
  97088. default:
  97089. FLAC__ASSERT(0);
  97090. return false;
  97091. }
  97092. }
  97093. }
  97094. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  97095. {
  97096. FLAC__ASSERT(0 != decoder);
  97097. FLAC__ASSERT(0 != decoder->protected_);
  97098. while(1) {
  97099. switch(decoder->protected_->state) {
  97100. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  97101. if(!find_metadata_(decoder))
  97102. return false; /* above function sets the status for us */
  97103. break;
  97104. case FLAC__STREAM_DECODER_READ_METADATA:
  97105. if(!read_metadata_(decoder))
  97106. return false; /* above function sets the status for us */
  97107. break;
  97108. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  97109. case FLAC__STREAM_DECODER_READ_FRAME:
  97110. case FLAC__STREAM_DECODER_END_OF_STREAM:
  97111. case FLAC__STREAM_DECODER_ABORTED:
  97112. return true;
  97113. default:
  97114. FLAC__ASSERT(0);
  97115. return false;
  97116. }
  97117. }
  97118. }
  97119. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  97120. {
  97121. FLAC__bool dummy;
  97122. FLAC__ASSERT(0 != decoder);
  97123. FLAC__ASSERT(0 != decoder->protected_);
  97124. while(1) {
  97125. switch(decoder->protected_->state) {
  97126. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  97127. if(!find_metadata_(decoder))
  97128. return false; /* above function sets the status for us */
  97129. break;
  97130. case FLAC__STREAM_DECODER_READ_METADATA:
  97131. if(!read_metadata_(decoder))
  97132. return false; /* above function sets the status for us */
  97133. break;
  97134. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  97135. if(!frame_sync_(decoder))
  97136. return true; /* above function sets the status for us */
  97137. break;
  97138. case FLAC__STREAM_DECODER_READ_FRAME:
  97139. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  97140. return false; /* above function sets the status for us */
  97141. break;
  97142. case FLAC__STREAM_DECODER_END_OF_STREAM:
  97143. case FLAC__STREAM_DECODER_ABORTED:
  97144. return true;
  97145. default:
  97146. FLAC__ASSERT(0);
  97147. return false;
  97148. }
  97149. }
  97150. }
  97151. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  97152. {
  97153. FLAC__bool got_a_frame;
  97154. FLAC__ASSERT(0 != decoder);
  97155. FLAC__ASSERT(0 != decoder->protected_);
  97156. while(1) {
  97157. switch(decoder->protected_->state) {
  97158. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  97159. case FLAC__STREAM_DECODER_READ_METADATA:
  97160. return false; /* above function sets the status for us */
  97161. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  97162. if(!frame_sync_(decoder))
  97163. return true; /* above function sets the status for us */
  97164. break;
  97165. case FLAC__STREAM_DECODER_READ_FRAME:
  97166. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  97167. return false; /* above function sets the status for us */
  97168. if(got_a_frame)
  97169. return true; /* above function sets the status for us */
  97170. break;
  97171. case FLAC__STREAM_DECODER_END_OF_STREAM:
  97172. case FLAC__STREAM_DECODER_ABORTED:
  97173. return true;
  97174. default:
  97175. FLAC__ASSERT(0);
  97176. return false;
  97177. }
  97178. }
  97179. }
  97180. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  97181. {
  97182. FLAC__uint64 length;
  97183. FLAC__ASSERT(0 != decoder);
  97184. if(
  97185. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  97186. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  97187. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  97188. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  97189. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  97190. )
  97191. return false;
  97192. if(0 == decoder->private_->seek_callback)
  97193. return false;
  97194. FLAC__ASSERT(decoder->private_->seek_callback);
  97195. FLAC__ASSERT(decoder->private_->tell_callback);
  97196. FLAC__ASSERT(decoder->private_->length_callback);
  97197. FLAC__ASSERT(decoder->private_->eof_callback);
  97198. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  97199. return false;
  97200. decoder->private_->is_seeking = true;
  97201. /* turn off md5 checking if a seek is attempted */
  97202. decoder->private_->do_md5_checking = false;
  97203. /* 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) */
  97204. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  97205. decoder->private_->is_seeking = false;
  97206. return false;
  97207. }
  97208. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  97209. if(
  97210. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  97211. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  97212. ) {
  97213. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  97214. /* above call sets the state for us */
  97215. decoder->private_->is_seeking = false;
  97216. return false;
  97217. }
  97218. /* check this again in case we didn't know total_samples the first time */
  97219. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  97220. decoder->private_->is_seeking = false;
  97221. return false;
  97222. }
  97223. }
  97224. {
  97225. const FLAC__bool ok =
  97226. #if FLAC__HAS_OGG
  97227. decoder->private_->is_ogg?
  97228. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  97229. #endif
  97230. seek_to_absolute_sample_(decoder, length, sample)
  97231. ;
  97232. decoder->private_->is_seeking = false;
  97233. return ok;
  97234. }
  97235. }
  97236. /***********************************************************************
  97237. *
  97238. * Protected class methods
  97239. *
  97240. ***********************************************************************/
  97241. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  97242. {
  97243. FLAC__ASSERT(0 != decoder);
  97244. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  97245. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  97246. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  97247. }
  97248. /***********************************************************************
  97249. *
  97250. * Private class methods
  97251. *
  97252. ***********************************************************************/
  97253. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  97254. {
  97255. #if FLAC__HAS_OGG
  97256. decoder->private_->is_ogg = false;
  97257. #endif
  97258. decoder->private_->read_callback = 0;
  97259. decoder->private_->seek_callback = 0;
  97260. decoder->private_->tell_callback = 0;
  97261. decoder->private_->length_callback = 0;
  97262. decoder->private_->eof_callback = 0;
  97263. decoder->private_->write_callback = 0;
  97264. decoder->private_->metadata_callback = 0;
  97265. decoder->private_->error_callback = 0;
  97266. decoder->private_->client_data = 0;
  97267. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  97268. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  97269. decoder->private_->metadata_filter_ids_count = 0;
  97270. decoder->protected_->md5_checking = false;
  97271. #if FLAC__HAS_OGG
  97272. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  97273. #endif
  97274. }
  97275. /*
  97276. * This will forcibly set stdin to binary mode (for OSes that require it)
  97277. */
  97278. FILE *get_binary_stdin_(void)
  97279. {
  97280. /* if something breaks here it is probably due to the presence or
  97281. * absence of an underscore before the identifiers 'setmode',
  97282. * 'fileno', and/or 'O_BINARY'; check your system header files.
  97283. */
  97284. #if defined _MSC_VER || defined __MINGW32__
  97285. _setmode(_fileno(stdin), _O_BINARY);
  97286. #elif defined __CYGWIN__
  97287. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  97288. setmode(_fileno(stdin), _O_BINARY);
  97289. #elif defined __EMX__
  97290. setmode(fileno(stdin), O_BINARY);
  97291. #endif
  97292. return stdin;
  97293. }
  97294. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  97295. {
  97296. unsigned i;
  97297. FLAC__int32 *tmp;
  97298. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  97299. return true;
  97300. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  97301. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  97302. if(0 != decoder->private_->output[i]) {
  97303. free(decoder->private_->output[i]-4);
  97304. decoder->private_->output[i] = 0;
  97305. }
  97306. if(0 != decoder->private_->residual_unaligned[i]) {
  97307. free(decoder->private_->residual_unaligned[i]);
  97308. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  97309. }
  97310. }
  97311. for(i = 0; i < channels; i++) {
  97312. /* WATCHOUT:
  97313. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  97314. * output arrays have a buffer of up to 3 zeroes in front
  97315. * (at negative indices) for alignment purposes; we use 4
  97316. * to keep the data well-aligned.
  97317. */
  97318. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  97319. if(tmp == 0) {
  97320. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97321. return false;
  97322. }
  97323. memset(tmp, 0, sizeof(FLAC__int32)*4);
  97324. decoder->private_->output[i] = tmp + 4;
  97325. /* WATCHOUT:
  97326. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  97327. */
  97328. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  97329. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97330. return false;
  97331. }
  97332. }
  97333. decoder->private_->output_capacity = size;
  97334. decoder->private_->output_channels = channels;
  97335. return true;
  97336. }
  97337. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  97338. {
  97339. size_t i;
  97340. FLAC__ASSERT(0 != decoder);
  97341. FLAC__ASSERT(0 != decoder->private_);
  97342. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  97343. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  97344. return true;
  97345. return false;
  97346. }
  97347. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  97348. {
  97349. FLAC__uint32 x;
  97350. unsigned i, id_;
  97351. FLAC__bool first = true;
  97352. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  97353. for(i = id_ = 0; i < 4; ) {
  97354. if(decoder->private_->cached) {
  97355. x = (FLAC__uint32)decoder->private_->lookahead;
  97356. decoder->private_->cached = false;
  97357. }
  97358. else {
  97359. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97360. return false; /* read_callback_ sets the state for us */
  97361. }
  97362. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  97363. first = true;
  97364. i++;
  97365. id_ = 0;
  97366. continue;
  97367. }
  97368. if(x == ID3V2_TAG_[id_]) {
  97369. id_++;
  97370. i = 0;
  97371. if(id_ == 3) {
  97372. if(!skip_id3v2_tag_(decoder))
  97373. return false; /* skip_id3v2_tag_ sets the state for us */
  97374. }
  97375. continue;
  97376. }
  97377. id_ = 0;
  97378. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  97379. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  97380. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97381. return false; /* read_callback_ sets the state for us */
  97382. /* 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 */
  97383. /* else we have to check if the second byte is the end of a sync code */
  97384. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  97385. decoder->private_->lookahead = (FLAC__byte)x;
  97386. decoder->private_->cached = true;
  97387. }
  97388. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  97389. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  97390. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  97391. return true;
  97392. }
  97393. }
  97394. i = 0;
  97395. if(first) {
  97396. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97397. first = false;
  97398. }
  97399. }
  97400. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  97401. return true;
  97402. }
  97403. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  97404. {
  97405. FLAC__bool is_last;
  97406. FLAC__uint32 i, x, type, length;
  97407. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  97408. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  97409. return false; /* read_callback_ sets the state for us */
  97410. is_last = x? true : false;
  97411. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  97412. return false; /* read_callback_ sets the state for us */
  97413. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  97414. return false; /* read_callback_ sets the state for us */
  97415. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  97416. if(!read_metadata_streaminfo_(decoder, is_last, length))
  97417. return false;
  97418. decoder->private_->has_stream_info = true;
  97419. 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))
  97420. decoder->private_->do_md5_checking = false;
  97421. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  97422. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  97423. }
  97424. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  97425. if(!read_metadata_seektable_(decoder, is_last, length))
  97426. return false;
  97427. decoder->private_->has_seek_table = true;
  97428. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  97429. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  97430. }
  97431. else {
  97432. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  97433. unsigned real_length = length;
  97434. FLAC__StreamMetadata block;
  97435. block.is_last = is_last;
  97436. block.type = (FLAC__MetadataType)type;
  97437. block.length = length;
  97438. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  97439. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  97440. return false; /* read_callback_ sets the state for us */
  97441. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  97442. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  97443. return false;
  97444. }
  97445. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  97446. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  97447. skip_it = !skip_it;
  97448. }
  97449. if(skip_it) {
  97450. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  97451. return false; /* read_callback_ sets the state for us */
  97452. }
  97453. else {
  97454. switch(type) {
  97455. case FLAC__METADATA_TYPE_PADDING:
  97456. /* skip the padding bytes */
  97457. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  97458. return false; /* read_callback_ sets the state for us */
  97459. break;
  97460. case FLAC__METADATA_TYPE_APPLICATION:
  97461. /* remember, we read the ID already */
  97462. if(real_length > 0) {
  97463. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  97464. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97465. return false;
  97466. }
  97467. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  97468. return false; /* read_callback_ sets the state for us */
  97469. }
  97470. else
  97471. block.data.application.data = 0;
  97472. break;
  97473. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  97474. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  97475. return false;
  97476. break;
  97477. case FLAC__METADATA_TYPE_CUESHEET:
  97478. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  97479. return false;
  97480. break;
  97481. case FLAC__METADATA_TYPE_PICTURE:
  97482. if(!read_metadata_picture_(decoder, &block.data.picture))
  97483. return false;
  97484. break;
  97485. case FLAC__METADATA_TYPE_STREAMINFO:
  97486. case FLAC__METADATA_TYPE_SEEKTABLE:
  97487. FLAC__ASSERT(0);
  97488. break;
  97489. default:
  97490. if(real_length > 0) {
  97491. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  97492. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97493. return false;
  97494. }
  97495. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  97496. return false; /* read_callback_ sets the state for us */
  97497. }
  97498. else
  97499. block.data.unknown.data = 0;
  97500. break;
  97501. }
  97502. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  97503. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  97504. /* now we have to free any malloc()ed data in the block */
  97505. switch(type) {
  97506. case FLAC__METADATA_TYPE_PADDING:
  97507. break;
  97508. case FLAC__METADATA_TYPE_APPLICATION:
  97509. if(0 != block.data.application.data)
  97510. free(block.data.application.data);
  97511. break;
  97512. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  97513. if(0 != block.data.vorbis_comment.vendor_string.entry)
  97514. free(block.data.vorbis_comment.vendor_string.entry);
  97515. if(block.data.vorbis_comment.num_comments > 0)
  97516. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  97517. if(0 != block.data.vorbis_comment.comments[i].entry)
  97518. free(block.data.vorbis_comment.comments[i].entry);
  97519. if(0 != block.data.vorbis_comment.comments)
  97520. free(block.data.vorbis_comment.comments);
  97521. break;
  97522. case FLAC__METADATA_TYPE_CUESHEET:
  97523. if(block.data.cue_sheet.num_tracks > 0)
  97524. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  97525. if(0 != block.data.cue_sheet.tracks[i].indices)
  97526. free(block.data.cue_sheet.tracks[i].indices);
  97527. if(0 != block.data.cue_sheet.tracks)
  97528. free(block.data.cue_sheet.tracks);
  97529. break;
  97530. case FLAC__METADATA_TYPE_PICTURE:
  97531. if(0 != block.data.picture.mime_type)
  97532. free(block.data.picture.mime_type);
  97533. if(0 != block.data.picture.description)
  97534. free(block.data.picture.description);
  97535. if(0 != block.data.picture.data)
  97536. free(block.data.picture.data);
  97537. break;
  97538. case FLAC__METADATA_TYPE_STREAMINFO:
  97539. case FLAC__METADATA_TYPE_SEEKTABLE:
  97540. FLAC__ASSERT(0);
  97541. default:
  97542. if(0 != block.data.unknown.data)
  97543. free(block.data.unknown.data);
  97544. break;
  97545. }
  97546. }
  97547. }
  97548. if(is_last) {
  97549. /* if this fails, it's OK, it's just a hint for the seek routine */
  97550. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  97551. decoder->private_->first_frame_offset = 0;
  97552. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97553. }
  97554. return true;
  97555. }
  97556. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  97557. {
  97558. FLAC__uint32 x;
  97559. unsigned bits, used_bits = 0;
  97560. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  97561. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  97562. decoder->private_->stream_info.is_last = is_last;
  97563. decoder->private_->stream_info.length = length;
  97564. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  97565. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  97566. return false; /* read_callback_ sets the state for us */
  97567. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  97568. used_bits += bits;
  97569. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  97570. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  97571. return false; /* read_callback_ sets the state for us */
  97572. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  97573. used_bits += bits;
  97574. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  97575. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  97576. return false; /* read_callback_ sets the state for us */
  97577. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  97578. used_bits += bits;
  97579. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  97580. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  97581. return false; /* read_callback_ sets the state for us */
  97582. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  97583. used_bits += bits;
  97584. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  97585. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  97586. return false; /* read_callback_ sets the state for us */
  97587. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  97588. used_bits += bits;
  97589. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  97590. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  97591. return false; /* read_callback_ sets the state for us */
  97592. decoder->private_->stream_info.data.stream_info.channels = x+1;
  97593. used_bits += bits;
  97594. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  97595. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  97596. return false; /* read_callback_ sets the state for us */
  97597. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  97598. used_bits += bits;
  97599. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  97600. 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))
  97601. return false; /* read_callback_ sets the state for us */
  97602. used_bits += bits;
  97603. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  97604. return false; /* read_callback_ sets the state for us */
  97605. used_bits += 16*8;
  97606. /* skip the rest of the block */
  97607. FLAC__ASSERT(used_bits % 8 == 0);
  97608. length -= (used_bits / 8);
  97609. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  97610. return false; /* read_callback_ sets the state for us */
  97611. return true;
  97612. }
  97613. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  97614. {
  97615. FLAC__uint32 i, x;
  97616. FLAC__uint64 xx;
  97617. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  97618. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  97619. decoder->private_->seek_table.is_last = is_last;
  97620. decoder->private_->seek_table.length = length;
  97621. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  97622. /* use realloc since we may pass through here several times (e.g. after seeking) */
  97623. 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)))) {
  97624. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97625. return false;
  97626. }
  97627. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  97628. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  97629. return false; /* read_callback_ sets the state for us */
  97630. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  97631. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  97632. return false; /* read_callback_ sets the state for us */
  97633. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  97634. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  97635. return false; /* read_callback_ sets the state for us */
  97636. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  97637. }
  97638. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  97639. /* if there is a partial point left, skip over it */
  97640. if(length > 0) {
  97641. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  97642. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  97643. return false; /* read_callback_ sets the state for us */
  97644. }
  97645. return true;
  97646. }
  97647. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  97648. {
  97649. FLAC__uint32 i;
  97650. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  97651. /* read vendor string */
  97652. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  97653. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  97654. return false; /* read_callback_ sets the state for us */
  97655. if(obj->vendor_string.length > 0) {
  97656. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  97657. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97658. return false;
  97659. }
  97660. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  97661. return false; /* read_callback_ sets the state for us */
  97662. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  97663. }
  97664. else
  97665. obj->vendor_string.entry = 0;
  97666. /* read num comments */
  97667. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  97668. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  97669. return false; /* read_callback_ sets the state for us */
  97670. /* read comments */
  97671. if(obj->num_comments > 0) {
  97672. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  97673. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97674. return false;
  97675. }
  97676. for(i = 0; i < obj->num_comments; i++) {
  97677. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  97678. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  97679. return false; /* read_callback_ sets the state for us */
  97680. if(obj->comments[i].length > 0) {
  97681. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  97682. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97683. return false;
  97684. }
  97685. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  97686. return false; /* read_callback_ sets the state for us */
  97687. obj->comments[i].entry[obj->comments[i].length] = '\0';
  97688. }
  97689. else
  97690. obj->comments[i].entry = 0;
  97691. }
  97692. }
  97693. else {
  97694. obj->comments = 0;
  97695. }
  97696. return true;
  97697. }
  97698. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  97699. {
  97700. FLAC__uint32 i, j, x;
  97701. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  97702. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  97703. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  97704. 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))
  97705. return false; /* read_callback_ sets the state for us */
  97706. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  97707. return false; /* read_callback_ sets the state for us */
  97708. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  97709. return false; /* read_callback_ sets the state for us */
  97710. obj->is_cd = x? true : false;
  97711. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  97712. return false; /* read_callback_ sets the state for us */
  97713. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  97714. return false; /* read_callback_ sets the state for us */
  97715. obj->num_tracks = x;
  97716. if(obj->num_tracks > 0) {
  97717. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  97718. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97719. return false;
  97720. }
  97721. for(i = 0; i < obj->num_tracks; i++) {
  97722. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  97723. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  97724. return false; /* read_callback_ sets the state for us */
  97725. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  97726. return false; /* read_callback_ sets the state for us */
  97727. track->number = (FLAC__byte)x;
  97728. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  97729. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  97730. return false; /* read_callback_ sets the state for us */
  97731. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  97732. return false; /* read_callback_ sets the state for us */
  97733. track->type = x;
  97734. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  97735. return false; /* read_callback_ sets the state for us */
  97736. track->pre_emphasis = x;
  97737. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  97738. return false; /* read_callback_ sets the state for us */
  97739. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  97740. return false; /* read_callback_ sets the state for us */
  97741. track->num_indices = (FLAC__byte)x;
  97742. if(track->num_indices > 0) {
  97743. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  97744. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97745. return false;
  97746. }
  97747. for(j = 0; j < track->num_indices; j++) {
  97748. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  97749. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  97750. return false; /* read_callback_ sets the state for us */
  97751. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  97752. return false; /* read_callback_ sets the state for us */
  97753. index->number = (FLAC__byte)x;
  97754. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  97755. return false; /* read_callback_ sets the state for us */
  97756. }
  97757. }
  97758. }
  97759. }
  97760. return true;
  97761. }
  97762. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  97763. {
  97764. FLAC__uint32 x;
  97765. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  97766. /* read type */
  97767. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  97768. return false; /* read_callback_ sets the state for us */
  97769. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  97770. /* read MIME type */
  97771. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  97772. return false; /* read_callback_ sets the state for us */
  97773. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  97774. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97775. return false;
  97776. }
  97777. if(x > 0) {
  97778. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  97779. return false; /* read_callback_ sets the state for us */
  97780. }
  97781. obj->mime_type[x] = '\0';
  97782. /* read description */
  97783. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  97784. return false; /* read_callback_ sets the state for us */
  97785. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  97786. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97787. return false;
  97788. }
  97789. if(x > 0) {
  97790. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  97791. return false; /* read_callback_ sets the state for us */
  97792. }
  97793. obj->description[x] = '\0';
  97794. /* read width */
  97795. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  97796. return false; /* read_callback_ sets the state for us */
  97797. /* read height */
  97798. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  97799. return false; /* read_callback_ sets the state for us */
  97800. /* read depth */
  97801. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  97802. return false; /* read_callback_ sets the state for us */
  97803. /* read colors */
  97804. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  97805. return false; /* read_callback_ sets the state for us */
  97806. /* read data */
  97807. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  97808. return false; /* read_callback_ sets the state for us */
  97809. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  97810. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97811. return false;
  97812. }
  97813. if(obj->data_length > 0) {
  97814. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  97815. return false; /* read_callback_ sets the state for us */
  97816. }
  97817. return true;
  97818. }
  97819. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  97820. {
  97821. FLAC__uint32 x;
  97822. unsigned i, skip;
  97823. /* skip the version and flags bytes */
  97824. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  97825. return false; /* read_callback_ sets the state for us */
  97826. /* get the size (in bytes) to skip */
  97827. skip = 0;
  97828. for(i = 0; i < 4; i++) {
  97829. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97830. return false; /* read_callback_ sets the state for us */
  97831. skip <<= 7;
  97832. skip |= (x & 0x7f);
  97833. }
  97834. /* skip the rest of the tag */
  97835. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  97836. return false; /* read_callback_ sets the state for us */
  97837. return true;
  97838. }
  97839. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  97840. {
  97841. FLAC__uint32 x;
  97842. FLAC__bool first = true;
  97843. /* If we know the total number of samples in the stream, stop if we've read that many. */
  97844. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  97845. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  97846. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  97847. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  97848. return true;
  97849. }
  97850. }
  97851. /* make sure we're byte aligned */
  97852. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  97853. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  97854. return false; /* read_callback_ sets the state for us */
  97855. }
  97856. while(1) {
  97857. if(decoder->private_->cached) {
  97858. x = (FLAC__uint32)decoder->private_->lookahead;
  97859. decoder->private_->cached = false;
  97860. }
  97861. else {
  97862. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97863. return false; /* read_callback_ sets the state for us */
  97864. }
  97865. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  97866. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  97867. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97868. return false; /* read_callback_ sets the state for us */
  97869. /* 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 */
  97870. /* else we have to check if the second byte is the end of a sync code */
  97871. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  97872. decoder->private_->lookahead = (FLAC__byte)x;
  97873. decoder->private_->cached = true;
  97874. }
  97875. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  97876. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  97877. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  97878. return true;
  97879. }
  97880. }
  97881. if(first) {
  97882. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97883. first = false;
  97884. }
  97885. }
  97886. return true;
  97887. }
  97888. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  97889. {
  97890. unsigned channel;
  97891. unsigned i;
  97892. FLAC__int32 mid, side;
  97893. unsigned frame_crc; /* the one we calculate from the input stream */
  97894. FLAC__uint32 x;
  97895. *got_a_frame = false;
  97896. /* init the CRC */
  97897. frame_crc = 0;
  97898. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  97899. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  97900. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  97901. if(!read_frame_header_(decoder))
  97902. return false;
  97903. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  97904. return true;
  97905. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  97906. return false;
  97907. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  97908. /*
  97909. * first figure the correct bits-per-sample of the subframe
  97910. */
  97911. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  97912. switch(decoder->private_->frame.header.channel_assignment) {
  97913. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  97914. /* no adjustment needed */
  97915. break;
  97916. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  97917. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  97918. if(channel == 1)
  97919. bps++;
  97920. break;
  97921. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  97922. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  97923. if(channel == 0)
  97924. bps++;
  97925. break;
  97926. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  97927. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  97928. if(channel == 1)
  97929. bps++;
  97930. break;
  97931. default:
  97932. FLAC__ASSERT(0);
  97933. }
  97934. /*
  97935. * now read it
  97936. */
  97937. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  97938. return false;
  97939. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  97940. return true;
  97941. }
  97942. if(!read_zero_padding_(decoder))
  97943. return false;
  97944. 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) */
  97945. return true;
  97946. /*
  97947. * Read the frame CRC-16 from the footer and check
  97948. */
  97949. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  97950. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  97951. return false; /* read_callback_ sets the state for us */
  97952. if(frame_crc == x) {
  97953. if(do_full_decode) {
  97954. /* Undo any special channel coding */
  97955. switch(decoder->private_->frame.header.channel_assignment) {
  97956. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  97957. /* do nothing */
  97958. break;
  97959. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  97960. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  97961. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  97962. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  97963. break;
  97964. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  97965. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  97966. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  97967. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  97968. break;
  97969. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  97970. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  97971. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  97972. #if 1
  97973. mid = decoder->private_->output[0][i];
  97974. side = decoder->private_->output[1][i];
  97975. mid <<= 1;
  97976. mid |= (side & 1); /* i.e. if 'side' is odd... */
  97977. decoder->private_->output[0][i] = (mid + side) >> 1;
  97978. decoder->private_->output[1][i] = (mid - side) >> 1;
  97979. #else
  97980. /* OPT: without 'side' temp variable */
  97981. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  97982. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  97983. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  97984. #endif
  97985. }
  97986. break;
  97987. default:
  97988. FLAC__ASSERT(0);
  97989. break;
  97990. }
  97991. }
  97992. }
  97993. else {
  97994. /* Bad frame, emit error and zero the output signal */
  97995. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  97996. if(do_full_decode) {
  97997. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  97998. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  97999. }
  98000. }
  98001. }
  98002. *got_a_frame = true;
  98003. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  98004. if(decoder->private_->next_fixed_block_size)
  98005. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  98006. /* put the latest values into the public section of the decoder instance */
  98007. decoder->protected_->channels = decoder->private_->frame.header.channels;
  98008. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  98009. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  98010. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  98011. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  98012. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  98013. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  98014. /* write it */
  98015. if(do_full_decode) {
  98016. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  98017. return false;
  98018. }
  98019. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98020. return true;
  98021. }
  98022. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  98023. {
  98024. FLAC__uint32 x;
  98025. FLAC__uint64 xx;
  98026. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  98027. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  98028. unsigned raw_header_len;
  98029. FLAC__bool is_unparseable = false;
  98030. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  98031. /* init the raw header with the saved bits from synchronization */
  98032. raw_header[0] = decoder->private_->header_warmup[0];
  98033. raw_header[1] = decoder->private_->header_warmup[1];
  98034. raw_header_len = 2;
  98035. /* check to make sure that reserved bit is 0 */
  98036. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  98037. is_unparseable = true;
  98038. /*
  98039. * Note that along the way as we read the header, we look for a sync
  98040. * code inside. If we find one it would indicate that our original
  98041. * sync was bad since there cannot be a sync code in a valid header.
  98042. *
  98043. * Three kinds of things can go wrong when reading the frame header:
  98044. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  98045. * If we don't find a sync code, it can end up looking like we read
  98046. * a valid but unparseable header, until getting to the frame header
  98047. * CRC. Even then we could get a false positive on the CRC.
  98048. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  98049. * future encoder).
  98050. * 3) We may be on a damaged frame which appears valid but unparseable.
  98051. *
  98052. * For all these reasons, we try and read a complete frame header as
  98053. * long as it seems valid, even if unparseable, up until the frame
  98054. * header CRC.
  98055. */
  98056. /*
  98057. * read in the raw header as bytes so we can CRC it, and parse it on the way
  98058. */
  98059. for(i = 0; i < 2; i++) {
  98060. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  98061. return false; /* read_callback_ sets the state for us */
  98062. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  98063. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  98064. decoder->private_->lookahead = (FLAC__byte)x;
  98065. decoder->private_->cached = true;
  98066. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  98067. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98068. return true;
  98069. }
  98070. raw_header[raw_header_len++] = (FLAC__byte)x;
  98071. }
  98072. switch(x = raw_header[2] >> 4) {
  98073. case 0:
  98074. is_unparseable = true;
  98075. break;
  98076. case 1:
  98077. decoder->private_->frame.header.blocksize = 192;
  98078. break;
  98079. case 2:
  98080. case 3:
  98081. case 4:
  98082. case 5:
  98083. decoder->private_->frame.header.blocksize = 576 << (x-2);
  98084. break;
  98085. case 6:
  98086. case 7:
  98087. blocksize_hint = x;
  98088. break;
  98089. case 8:
  98090. case 9:
  98091. case 10:
  98092. case 11:
  98093. case 12:
  98094. case 13:
  98095. case 14:
  98096. case 15:
  98097. decoder->private_->frame.header.blocksize = 256 << (x-8);
  98098. break;
  98099. default:
  98100. FLAC__ASSERT(0);
  98101. break;
  98102. }
  98103. switch(x = raw_header[2] & 0x0f) {
  98104. case 0:
  98105. if(decoder->private_->has_stream_info)
  98106. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  98107. else
  98108. is_unparseable = true;
  98109. break;
  98110. case 1:
  98111. decoder->private_->frame.header.sample_rate = 88200;
  98112. break;
  98113. case 2:
  98114. decoder->private_->frame.header.sample_rate = 176400;
  98115. break;
  98116. case 3:
  98117. decoder->private_->frame.header.sample_rate = 192000;
  98118. break;
  98119. case 4:
  98120. decoder->private_->frame.header.sample_rate = 8000;
  98121. break;
  98122. case 5:
  98123. decoder->private_->frame.header.sample_rate = 16000;
  98124. break;
  98125. case 6:
  98126. decoder->private_->frame.header.sample_rate = 22050;
  98127. break;
  98128. case 7:
  98129. decoder->private_->frame.header.sample_rate = 24000;
  98130. break;
  98131. case 8:
  98132. decoder->private_->frame.header.sample_rate = 32000;
  98133. break;
  98134. case 9:
  98135. decoder->private_->frame.header.sample_rate = 44100;
  98136. break;
  98137. case 10:
  98138. decoder->private_->frame.header.sample_rate = 48000;
  98139. break;
  98140. case 11:
  98141. decoder->private_->frame.header.sample_rate = 96000;
  98142. break;
  98143. case 12:
  98144. case 13:
  98145. case 14:
  98146. sample_rate_hint = x;
  98147. break;
  98148. case 15:
  98149. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  98150. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98151. return true;
  98152. default:
  98153. FLAC__ASSERT(0);
  98154. }
  98155. x = (unsigned)(raw_header[3] >> 4);
  98156. if(x & 8) {
  98157. decoder->private_->frame.header.channels = 2;
  98158. switch(x & 7) {
  98159. case 0:
  98160. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  98161. break;
  98162. case 1:
  98163. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  98164. break;
  98165. case 2:
  98166. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  98167. break;
  98168. default:
  98169. is_unparseable = true;
  98170. break;
  98171. }
  98172. }
  98173. else {
  98174. decoder->private_->frame.header.channels = (unsigned)x + 1;
  98175. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  98176. }
  98177. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  98178. case 0:
  98179. if(decoder->private_->has_stream_info)
  98180. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  98181. else
  98182. is_unparseable = true;
  98183. break;
  98184. case 1:
  98185. decoder->private_->frame.header.bits_per_sample = 8;
  98186. break;
  98187. case 2:
  98188. decoder->private_->frame.header.bits_per_sample = 12;
  98189. break;
  98190. case 4:
  98191. decoder->private_->frame.header.bits_per_sample = 16;
  98192. break;
  98193. case 5:
  98194. decoder->private_->frame.header.bits_per_sample = 20;
  98195. break;
  98196. case 6:
  98197. decoder->private_->frame.header.bits_per_sample = 24;
  98198. break;
  98199. case 3:
  98200. case 7:
  98201. is_unparseable = true;
  98202. break;
  98203. default:
  98204. FLAC__ASSERT(0);
  98205. break;
  98206. }
  98207. /* check to make sure that reserved bit is 0 */
  98208. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  98209. is_unparseable = true;
  98210. /* read the frame's starting sample number (or frame number as the case may be) */
  98211. if(
  98212. raw_header[1] & 0x01 ||
  98213. /*@@@ 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 */
  98214. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  98215. ) { /* variable blocksize */
  98216. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  98217. return false; /* read_callback_ sets the state for us */
  98218. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  98219. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  98220. decoder->private_->cached = true;
  98221. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  98222. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98223. return true;
  98224. }
  98225. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  98226. decoder->private_->frame.header.number.sample_number = xx;
  98227. }
  98228. else { /* fixed blocksize */
  98229. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  98230. return false; /* read_callback_ sets the state for us */
  98231. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  98232. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  98233. decoder->private_->cached = true;
  98234. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  98235. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98236. return true;
  98237. }
  98238. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  98239. decoder->private_->frame.header.number.frame_number = x;
  98240. }
  98241. if(blocksize_hint) {
  98242. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  98243. return false; /* read_callback_ sets the state for us */
  98244. raw_header[raw_header_len++] = (FLAC__byte)x;
  98245. if(blocksize_hint == 7) {
  98246. FLAC__uint32 _x;
  98247. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  98248. return false; /* read_callback_ sets the state for us */
  98249. raw_header[raw_header_len++] = (FLAC__byte)_x;
  98250. x = (x << 8) | _x;
  98251. }
  98252. decoder->private_->frame.header.blocksize = x+1;
  98253. }
  98254. if(sample_rate_hint) {
  98255. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  98256. return false; /* read_callback_ sets the state for us */
  98257. raw_header[raw_header_len++] = (FLAC__byte)x;
  98258. if(sample_rate_hint != 12) {
  98259. FLAC__uint32 _x;
  98260. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  98261. return false; /* read_callback_ sets the state for us */
  98262. raw_header[raw_header_len++] = (FLAC__byte)_x;
  98263. x = (x << 8) | _x;
  98264. }
  98265. if(sample_rate_hint == 12)
  98266. decoder->private_->frame.header.sample_rate = x*1000;
  98267. else if(sample_rate_hint == 13)
  98268. decoder->private_->frame.header.sample_rate = x;
  98269. else
  98270. decoder->private_->frame.header.sample_rate = x*10;
  98271. }
  98272. /* read the CRC-8 byte */
  98273. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  98274. return false; /* read_callback_ sets the state for us */
  98275. crc8 = (FLAC__byte)x;
  98276. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  98277. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  98278. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98279. return true;
  98280. }
  98281. /* calculate the sample number from the frame number if needed */
  98282. decoder->private_->next_fixed_block_size = 0;
  98283. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  98284. x = decoder->private_->frame.header.number.frame_number;
  98285. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  98286. if(decoder->private_->fixed_block_size)
  98287. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  98288. else if(decoder->private_->has_stream_info) {
  98289. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  98290. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  98291. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  98292. }
  98293. else
  98294. is_unparseable = true;
  98295. }
  98296. else if(x == 0) {
  98297. decoder->private_->frame.header.number.sample_number = 0;
  98298. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  98299. }
  98300. else {
  98301. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  98302. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  98303. }
  98304. }
  98305. if(is_unparseable) {
  98306. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  98307. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98308. return true;
  98309. }
  98310. return true;
  98311. }
  98312. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  98313. {
  98314. FLAC__uint32 x;
  98315. FLAC__bool wasted_bits;
  98316. unsigned i;
  98317. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  98318. return false; /* read_callback_ sets the state for us */
  98319. wasted_bits = (x & 1);
  98320. x &= 0xfe;
  98321. if(wasted_bits) {
  98322. unsigned u;
  98323. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  98324. return false; /* read_callback_ sets the state for us */
  98325. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  98326. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  98327. }
  98328. else
  98329. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  98330. /*
  98331. * Lots of magic numbers here
  98332. */
  98333. if(x & 0x80) {
  98334. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  98335. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98336. return true;
  98337. }
  98338. else if(x == 0) {
  98339. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  98340. return false;
  98341. }
  98342. else if(x == 2) {
  98343. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  98344. return false;
  98345. }
  98346. else if(x < 16) {
  98347. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  98348. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98349. return true;
  98350. }
  98351. else if(x <= 24) {
  98352. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  98353. return false;
  98354. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  98355. return true;
  98356. }
  98357. else if(x < 64) {
  98358. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  98359. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98360. return true;
  98361. }
  98362. else {
  98363. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  98364. return false;
  98365. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  98366. return true;
  98367. }
  98368. if(wasted_bits && do_full_decode) {
  98369. x = decoder->private_->frame.subframes[channel].wasted_bits;
  98370. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  98371. decoder->private_->output[channel][i] <<= x;
  98372. }
  98373. return true;
  98374. }
  98375. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  98376. {
  98377. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  98378. FLAC__int32 x;
  98379. unsigned i;
  98380. FLAC__int32 *output = decoder->private_->output[channel];
  98381. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  98382. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  98383. return false; /* read_callback_ sets the state for us */
  98384. subframe->value = x;
  98385. /* decode the subframe */
  98386. if(do_full_decode) {
  98387. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  98388. output[i] = x;
  98389. }
  98390. return true;
  98391. }
  98392. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  98393. {
  98394. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  98395. FLAC__int32 i32;
  98396. FLAC__uint32 u32;
  98397. unsigned u;
  98398. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  98399. subframe->residual = decoder->private_->residual[channel];
  98400. subframe->order = order;
  98401. /* read warm-up samples */
  98402. for(u = 0; u < order; u++) {
  98403. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  98404. return false; /* read_callback_ sets the state for us */
  98405. subframe->warmup[u] = i32;
  98406. }
  98407. /* read entropy coding method info */
  98408. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  98409. return false; /* read_callback_ sets the state for us */
  98410. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  98411. switch(subframe->entropy_coding_method.type) {
  98412. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  98413. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  98414. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  98415. return false; /* read_callback_ sets the state for us */
  98416. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  98417. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  98418. break;
  98419. default:
  98420. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  98421. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98422. return true;
  98423. }
  98424. /* read residual */
  98425. switch(subframe->entropy_coding_method.type) {
  98426. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  98427. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  98428. 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))
  98429. return false;
  98430. break;
  98431. default:
  98432. FLAC__ASSERT(0);
  98433. }
  98434. /* decode the subframe */
  98435. if(do_full_decode) {
  98436. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  98437. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  98438. }
  98439. return true;
  98440. }
  98441. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  98442. {
  98443. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  98444. FLAC__int32 i32;
  98445. FLAC__uint32 u32;
  98446. unsigned u;
  98447. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  98448. subframe->residual = decoder->private_->residual[channel];
  98449. subframe->order = order;
  98450. /* read warm-up samples */
  98451. for(u = 0; u < order; u++) {
  98452. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  98453. return false; /* read_callback_ sets the state for us */
  98454. subframe->warmup[u] = i32;
  98455. }
  98456. /* read qlp coeff precision */
  98457. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  98458. return false; /* read_callback_ sets the state for us */
  98459. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  98460. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  98461. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98462. return true;
  98463. }
  98464. subframe->qlp_coeff_precision = u32+1;
  98465. /* read qlp shift */
  98466. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  98467. return false; /* read_callback_ sets the state for us */
  98468. subframe->quantization_level = i32;
  98469. /* read quantized lp coefficiencts */
  98470. for(u = 0; u < order; u++) {
  98471. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  98472. return false; /* read_callback_ sets the state for us */
  98473. subframe->qlp_coeff[u] = i32;
  98474. }
  98475. /* read entropy coding method info */
  98476. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  98477. return false; /* read_callback_ sets the state for us */
  98478. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  98479. switch(subframe->entropy_coding_method.type) {
  98480. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  98481. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  98482. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  98483. return false; /* read_callback_ sets the state for us */
  98484. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  98485. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  98486. break;
  98487. default:
  98488. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  98489. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98490. return true;
  98491. }
  98492. /* read residual */
  98493. switch(subframe->entropy_coding_method.type) {
  98494. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  98495. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  98496. 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))
  98497. return false;
  98498. break;
  98499. default:
  98500. FLAC__ASSERT(0);
  98501. }
  98502. /* decode the subframe */
  98503. if(do_full_decode) {
  98504. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  98505. /*@@@@@@ technically not pessimistic enough, should be more like
  98506. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  98507. */
  98508. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  98509. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  98510. if(order <= 8)
  98511. 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);
  98512. else
  98513. 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);
  98514. }
  98515. else
  98516. 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);
  98517. else
  98518. 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);
  98519. }
  98520. return true;
  98521. }
  98522. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  98523. {
  98524. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  98525. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  98526. unsigned i;
  98527. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  98528. subframe->data = residual;
  98529. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  98530. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  98531. return false; /* read_callback_ sets the state for us */
  98532. residual[i] = x;
  98533. }
  98534. /* decode the subframe */
  98535. if(do_full_decode)
  98536. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  98537. return true;
  98538. }
  98539. 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)
  98540. {
  98541. FLAC__uint32 rice_parameter;
  98542. int i;
  98543. unsigned partition, sample, u;
  98544. const unsigned partitions = 1u << partition_order;
  98545. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  98546. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  98547. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  98548. /* sanity checks */
  98549. if(partition_order == 0) {
  98550. if(decoder->private_->frame.header.blocksize < predictor_order) {
  98551. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  98552. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98553. return true;
  98554. }
  98555. }
  98556. else {
  98557. if(partition_samples < predictor_order) {
  98558. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  98559. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98560. return true;
  98561. }
  98562. }
  98563. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  98564. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  98565. return false;
  98566. }
  98567. sample = 0;
  98568. for(partition = 0; partition < partitions; partition++) {
  98569. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  98570. return false; /* read_callback_ sets the state for us */
  98571. partitioned_rice_contents->parameters[partition] = rice_parameter;
  98572. if(rice_parameter < pesc) {
  98573. partitioned_rice_contents->raw_bits[partition] = 0;
  98574. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  98575. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  98576. return false; /* read_callback_ sets the state for us */
  98577. sample += u;
  98578. }
  98579. else {
  98580. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  98581. return false; /* read_callback_ sets the state for us */
  98582. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  98583. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  98584. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  98585. return false; /* read_callback_ sets the state for us */
  98586. residual[sample] = i;
  98587. }
  98588. }
  98589. }
  98590. return true;
  98591. }
  98592. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  98593. {
  98594. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  98595. FLAC__uint32 zero = 0;
  98596. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  98597. return false; /* read_callback_ sets the state for us */
  98598. if(zero != 0) {
  98599. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  98600. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98601. }
  98602. }
  98603. return true;
  98604. }
  98605. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  98606. {
  98607. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  98608. if(
  98609. #if FLAC__HAS_OGG
  98610. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  98611. !decoder->private_->is_ogg &&
  98612. #endif
  98613. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  98614. ) {
  98615. *bytes = 0;
  98616. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  98617. return false;
  98618. }
  98619. else if(*bytes > 0) {
  98620. /* While seeking, it is possible for our seek to land in the
  98621. * middle of audio data that looks exactly like a frame header
  98622. * from a future version of an encoder. When that happens, our
  98623. * error callback will get an
  98624. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  98625. * unparseable_frame_count. But there is a remote possibility
  98626. * that it is properly synced at such a "future-codec frame",
  98627. * so to make sure, we wait to see many "unparseable" errors in
  98628. * a row before bailing out.
  98629. */
  98630. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  98631. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  98632. return false;
  98633. }
  98634. else {
  98635. const FLAC__StreamDecoderReadStatus status =
  98636. #if FLAC__HAS_OGG
  98637. decoder->private_->is_ogg?
  98638. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  98639. #endif
  98640. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  98641. ;
  98642. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  98643. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  98644. return false;
  98645. }
  98646. else if(*bytes == 0) {
  98647. if(
  98648. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  98649. (
  98650. #if FLAC__HAS_OGG
  98651. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  98652. !decoder->private_->is_ogg &&
  98653. #endif
  98654. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  98655. )
  98656. ) {
  98657. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  98658. return false;
  98659. }
  98660. else
  98661. return true;
  98662. }
  98663. else
  98664. return true;
  98665. }
  98666. }
  98667. else {
  98668. /* abort to avoid a deadlock */
  98669. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  98670. return false;
  98671. }
  98672. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  98673. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  98674. * and at the same time hit the end of the stream (for example, seeking
  98675. * to a point that is after the beginning of the last Ogg page). There
  98676. * is no way to report an Ogg sync loss through the callbacks (see note
  98677. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  98678. * So to keep the decoder from stopping at this point we gate the call
  98679. * to the eof_callback and let the Ogg decoder aspect set the
  98680. * end-of-stream state when it is needed.
  98681. */
  98682. }
  98683. #if FLAC__HAS_OGG
  98684. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  98685. {
  98686. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  98687. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  98688. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  98689. /* we don't really have a way to handle lost sync via read
  98690. * callback so we'll let it pass and let the underlying
  98691. * FLAC decoder catch the error
  98692. */
  98693. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  98694. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  98695. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  98696. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  98697. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  98698. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  98699. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  98700. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  98701. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  98702. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  98703. default:
  98704. FLAC__ASSERT(0);
  98705. /* double protection */
  98706. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  98707. }
  98708. }
  98709. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  98710. {
  98711. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  98712. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  98713. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  98714. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  98715. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  98716. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  98717. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  98718. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  98719. default:
  98720. /* double protection: */
  98721. FLAC__ASSERT(0);
  98722. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  98723. }
  98724. }
  98725. #endif
  98726. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  98727. {
  98728. if(decoder->private_->is_seeking) {
  98729. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  98730. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  98731. FLAC__uint64 target_sample = decoder->private_->target_sample;
  98732. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  98733. #if FLAC__HAS_OGG
  98734. decoder->private_->got_a_frame = true;
  98735. #endif
  98736. decoder->private_->last_frame = *frame; /* save the frame */
  98737. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  98738. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  98739. /* kick out of seek mode */
  98740. decoder->private_->is_seeking = false;
  98741. /* shift out the samples before target_sample */
  98742. if(delta > 0) {
  98743. unsigned channel;
  98744. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  98745. for(channel = 0; channel < frame->header.channels; channel++)
  98746. newbuffer[channel] = buffer[channel] + delta;
  98747. decoder->private_->last_frame.header.blocksize -= delta;
  98748. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  98749. /* write the relevant samples */
  98750. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  98751. }
  98752. else {
  98753. /* write the relevant samples */
  98754. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  98755. }
  98756. }
  98757. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  98758. }
  98759. /*
  98760. * If we never got STREAMINFO, turn off MD5 checking to save
  98761. * cycles since we don't have a sum to compare to anyway
  98762. */
  98763. if(!decoder->private_->has_stream_info)
  98764. decoder->private_->do_md5_checking = false;
  98765. if(decoder->private_->do_md5_checking) {
  98766. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  98767. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  98768. }
  98769. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  98770. }
  98771. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  98772. {
  98773. if(!decoder->private_->is_seeking)
  98774. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  98775. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  98776. decoder->private_->unparseable_frame_count++;
  98777. }
  98778. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  98779. {
  98780. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  98781. FLAC__int64 pos = -1;
  98782. int i;
  98783. unsigned approx_bytes_per_frame;
  98784. FLAC__bool first_seek = true;
  98785. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  98786. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  98787. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  98788. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  98789. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  98790. /* take these from the current frame in case they've changed mid-stream */
  98791. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  98792. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  98793. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  98794. /* use values from stream info if we didn't decode a frame */
  98795. if(channels == 0)
  98796. channels = decoder->private_->stream_info.data.stream_info.channels;
  98797. if(bps == 0)
  98798. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  98799. /* we are just guessing here */
  98800. if(max_framesize > 0)
  98801. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  98802. /*
  98803. * Check if it's a known fixed-blocksize stream. Note that though
  98804. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  98805. * never get a STREAMINFO block when decoding so the value of
  98806. * min_blocksize might be zero.
  98807. */
  98808. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  98809. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  98810. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  98811. }
  98812. else
  98813. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  98814. /*
  98815. * First, we set an upper and lower bound on where in the
  98816. * stream we will search. For now we assume the worst case
  98817. * scenario, which is our best guess at the beginning of
  98818. * the first frame and end of the stream.
  98819. */
  98820. lower_bound = first_frame_offset;
  98821. lower_bound_sample = 0;
  98822. upper_bound = stream_length;
  98823. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  98824. /*
  98825. * Now we refine the bounds if we have a seektable with
  98826. * suitable points. Note that according to the spec they
  98827. * must be ordered by ascending sample number.
  98828. *
  98829. * Note: to protect against invalid seek tables we will ignore points
  98830. * that have frame_samples==0 or sample_number>=total_samples
  98831. */
  98832. if(seek_table) {
  98833. FLAC__uint64 new_lower_bound = lower_bound;
  98834. FLAC__uint64 new_upper_bound = upper_bound;
  98835. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  98836. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  98837. /* find the closest seek point <= target_sample, if it exists */
  98838. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  98839. if(
  98840. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  98841. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  98842. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  98843. seek_table->points[i].sample_number <= target_sample
  98844. )
  98845. break;
  98846. }
  98847. if(i >= 0) { /* i.e. we found a suitable seek point... */
  98848. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  98849. new_lower_bound_sample = seek_table->points[i].sample_number;
  98850. }
  98851. /* find the closest seek point > target_sample, if it exists */
  98852. for(i = 0; i < (int)seek_table->num_points; i++) {
  98853. if(
  98854. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  98855. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  98856. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  98857. seek_table->points[i].sample_number > target_sample
  98858. )
  98859. break;
  98860. }
  98861. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  98862. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  98863. new_upper_bound_sample = seek_table->points[i].sample_number;
  98864. }
  98865. /* final protection against unsorted seek tables; keep original values if bogus */
  98866. if(new_upper_bound >= new_lower_bound) {
  98867. lower_bound = new_lower_bound;
  98868. upper_bound = new_upper_bound;
  98869. lower_bound_sample = new_lower_bound_sample;
  98870. upper_bound_sample = new_upper_bound_sample;
  98871. }
  98872. }
  98873. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  98874. /* there are 2 insidious ways that the following equality occurs, which
  98875. * we need to fix:
  98876. * 1) total_samples is 0 (unknown) and target_sample is 0
  98877. * 2) total_samples is 0 (unknown) and target_sample happens to be
  98878. * exactly equal to the last seek point in the seek table; this
  98879. * means there is no seek point above it, and upper_bound_samples
  98880. * remains equal to the estimate (of target_samples) we made above
  98881. * in either case it does not hurt to move upper_bound_sample up by 1
  98882. */
  98883. if(upper_bound_sample == lower_bound_sample)
  98884. upper_bound_sample++;
  98885. decoder->private_->target_sample = target_sample;
  98886. while(1) {
  98887. /* check if the bounds are still ok */
  98888. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  98889. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98890. return false;
  98891. }
  98892. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98893. #if defined _MSC_VER || defined __MINGW32__
  98894. /* with VC++ you have to spoon feed it the casting */
  98895. 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;
  98896. #else
  98897. 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;
  98898. #endif
  98899. #else
  98900. /* a little less accurate: */
  98901. if(upper_bound - lower_bound < 0xffffffff)
  98902. 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;
  98903. else /* @@@ WATCHOUT, ~2TB limit */
  98904. 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;
  98905. #endif
  98906. if(pos >= (FLAC__int64)upper_bound)
  98907. pos = (FLAC__int64)upper_bound - 1;
  98908. if(pos < (FLAC__int64)lower_bound)
  98909. pos = (FLAC__int64)lower_bound;
  98910. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  98911. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98912. return false;
  98913. }
  98914. if(!FLAC__stream_decoder_flush(decoder)) {
  98915. /* above call sets the state for us */
  98916. return false;
  98917. }
  98918. /* Now we need to get a frame. First we need to reset our
  98919. * unparseable_frame_count; if we get too many unparseable
  98920. * frames in a row, the read callback will return
  98921. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  98922. * FLAC__stream_decoder_process_single() to return false.
  98923. */
  98924. decoder->private_->unparseable_frame_count = 0;
  98925. if(!FLAC__stream_decoder_process_single(decoder)) {
  98926. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98927. return false;
  98928. }
  98929. /* our write callback will change the state when it gets to the target frame */
  98930. /* 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 */
  98931. #if 0
  98932. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  98933. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  98934. break;
  98935. #endif
  98936. if(!decoder->private_->is_seeking)
  98937. break;
  98938. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  98939. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  98940. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  98941. if (pos == (FLAC__int64)lower_bound) {
  98942. /* can't move back any more than the first frame, something is fatally wrong */
  98943. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98944. return false;
  98945. }
  98946. /* our last move backwards wasn't big enough, try again */
  98947. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  98948. continue;
  98949. }
  98950. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  98951. first_seek = false;
  98952. /* make sure we are not seeking in corrupted stream */
  98953. if (this_frame_sample < lower_bound_sample) {
  98954. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98955. return false;
  98956. }
  98957. /* we need to narrow the search */
  98958. if(target_sample < this_frame_sample) {
  98959. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  98960. /*@@@@@@ what will decode position be if at end of stream? */
  98961. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  98962. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98963. return false;
  98964. }
  98965. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  98966. }
  98967. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  98968. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  98969. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  98970. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98971. return false;
  98972. }
  98973. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  98974. }
  98975. }
  98976. return true;
  98977. }
  98978. #if FLAC__HAS_OGG
  98979. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  98980. {
  98981. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  98982. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  98983. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  98984. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  98985. FLAC__bool did_a_seek;
  98986. unsigned iteration = 0;
  98987. /* In the first iterations, we will calculate the target byte position
  98988. * by the distance from the target sample to left_sample and
  98989. * right_sample (let's call it "proportional search"). After that, we
  98990. * will switch to binary search.
  98991. */
  98992. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  98993. /* We will switch to a linear search once our current sample is less
  98994. * than this number of samples ahead of the target sample
  98995. */
  98996. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  98997. /* If the total number of samples is unknown, use a large value, and
  98998. * force binary search immediately.
  98999. */
  99000. if(right_sample == 0) {
  99001. right_sample = (FLAC__uint64)(-1);
  99002. BINARY_SEARCH_AFTER_ITERATION = 0;
  99003. }
  99004. decoder->private_->target_sample = target_sample;
  99005. for( ; ; iteration++) {
  99006. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  99007. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  99008. pos = (right_pos + left_pos) / 2;
  99009. }
  99010. else {
  99011. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99012. #if defined _MSC_VER || defined __MINGW32__
  99013. /* with MSVC you have to spoon feed it the casting */
  99014. 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));
  99015. #else
  99016. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  99017. #endif
  99018. #else
  99019. /* a little less accurate: */
  99020. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  99021. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  99022. else /* @@@ WATCHOUT, ~2TB limit */
  99023. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  99024. #endif
  99025. /* @@@ TODO: might want to limit pos to some distance
  99026. * before EOF, to make sure we land before the last frame,
  99027. * thereby getting a this_frame_sample and so having a better
  99028. * estimate.
  99029. */
  99030. }
  99031. /* physical seek */
  99032. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  99033. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  99034. return false;
  99035. }
  99036. if(!FLAC__stream_decoder_flush(decoder)) {
  99037. /* above call sets the state for us */
  99038. return false;
  99039. }
  99040. did_a_seek = true;
  99041. }
  99042. else
  99043. did_a_seek = false;
  99044. decoder->private_->got_a_frame = false;
  99045. if(!FLAC__stream_decoder_process_single(decoder)) {
  99046. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  99047. return false;
  99048. }
  99049. if(!decoder->private_->got_a_frame) {
  99050. if(did_a_seek) {
  99051. /* this can happen if we seek to a point after the last frame; we drop
  99052. * to binary search right away in this case to avoid any wasted
  99053. * iterations of proportional search.
  99054. */
  99055. right_pos = pos;
  99056. BINARY_SEARCH_AFTER_ITERATION = 0;
  99057. }
  99058. else {
  99059. /* this can probably only happen if total_samples is unknown and the
  99060. * target_sample is past the end of the stream
  99061. */
  99062. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  99063. return false;
  99064. }
  99065. }
  99066. /* our write callback will change the state when it gets to the target frame */
  99067. else if(!decoder->private_->is_seeking) {
  99068. break;
  99069. }
  99070. else {
  99071. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  99072. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  99073. if (did_a_seek) {
  99074. if (this_frame_sample <= target_sample) {
  99075. /* The 'equal' case should not happen, since
  99076. * FLAC__stream_decoder_process_single()
  99077. * should recognize that it has hit the
  99078. * target sample and we would exit through
  99079. * the 'break' above.
  99080. */
  99081. FLAC__ASSERT(this_frame_sample != target_sample);
  99082. left_sample = this_frame_sample;
  99083. /* sanity check to avoid infinite loop */
  99084. if (left_pos == pos) {
  99085. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  99086. return false;
  99087. }
  99088. left_pos = pos;
  99089. }
  99090. else if(this_frame_sample > target_sample) {
  99091. right_sample = this_frame_sample;
  99092. /* sanity check to avoid infinite loop */
  99093. if (right_pos == pos) {
  99094. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  99095. return false;
  99096. }
  99097. right_pos = pos;
  99098. }
  99099. }
  99100. }
  99101. }
  99102. return true;
  99103. }
  99104. #endif
  99105. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  99106. {
  99107. (void)client_data;
  99108. if(*bytes > 0) {
  99109. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  99110. if(ferror(decoder->private_->file))
  99111. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  99112. else if(*bytes == 0)
  99113. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  99114. else
  99115. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  99116. }
  99117. else
  99118. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  99119. }
  99120. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  99121. {
  99122. (void)client_data;
  99123. if(decoder->private_->file == stdin)
  99124. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  99125. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  99126. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  99127. else
  99128. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  99129. }
  99130. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  99131. {
  99132. off_t pos;
  99133. (void)client_data;
  99134. if(decoder->private_->file == stdin)
  99135. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  99136. else if((pos = ftello(decoder->private_->file)) < 0)
  99137. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  99138. else {
  99139. *absolute_byte_offset = (FLAC__uint64)pos;
  99140. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  99141. }
  99142. }
  99143. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  99144. {
  99145. struct stat filestats;
  99146. (void)client_data;
  99147. if(decoder->private_->file == stdin)
  99148. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  99149. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  99150. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  99151. else {
  99152. *stream_length = (FLAC__uint64)filestats.st_size;
  99153. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  99154. }
  99155. }
  99156. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  99157. {
  99158. (void)client_data;
  99159. return feof(decoder->private_->file)? true : false;
  99160. }
  99161. #endif
  99162. /*** End of inlined file: stream_decoder.c ***/
  99163. /*** Start of inlined file: stream_encoder.c ***/
  99164. /*** Start of inlined file: juce_FlacHeader.h ***/
  99165. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  99166. // tasks..
  99167. #define VERSION "1.2.1"
  99168. #define FLAC__NO_DLL 1
  99169. #if JUCE_MSVC
  99170. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  99171. #endif
  99172. #if JUCE_MAC
  99173. #define FLAC__SYS_DARWIN 1
  99174. #endif
  99175. /*** End of inlined file: juce_FlacHeader.h ***/
  99176. #if JUCE_USE_FLAC
  99177. #if HAVE_CONFIG_H
  99178. # include <config.h>
  99179. #endif
  99180. #if defined _MSC_VER || defined __MINGW32__
  99181. #include <io.h> /* for _setmode() */
  99182. #include <fcntl.h> /* for _O_BINARY */
  99183. #endif
  99184. #if defined __CYGWIN__ || defined __EMX__
  99185. #include <io.h> /* for setmode(), O_BINARY */
  99186. #include <fcntl.h> /* for _O_BINARY */
  99187. #endif
  99188. #include <limits.h>
  99189. #include <stdio.h>
  99190. #include <stdlib.h> /* for malloc() */
  99191. #include <string.h> /* for memcpy() */
  99192. #include <sys/types.h> /* for off_t */
  99193. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  99194. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  99195. #define fseeko fseek
  99196. #define ftello ftell
  99197. #endif
  99198. #endif
  99199. /*** Start of inlined file: stream_encoder.h ***/
  99200. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  99201. #define FLAC__PROTECTED__STREAM_ENCODER_H
  99202. #if FLAC__HAS_OGG
  99203. #include "private/ogg_encoder_aspect.h"
  99204. #endif
  99205. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99206. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  99207. typedef enum {
  99208. FLAC__APODIZATION_BARTLETT,
  99209. FLAC__APODIZATION_BARTLETT_HANN,
  99210. FLAC__APODIZATION_BLACKMAN,
  99211. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  99212. FLAC__APODIZATION_CONNES,
  99213. FLAC__APODIZATION_FLATTOP,
  99214. FLAC__APODIZATION_GAUSS,
  99215. FLAC__APODIZATION_HAMMING,
  99216. FLAC__APODIZATION_HANN,
  99217. FLAC__APODIZATION_KAISER_BESSEL,
  99218. FLAC__APODIZATION_NUTTALL,
  99219. FLAC__APODIZATION_RECTANGLE,
  99220. FLAC__APODIZATION_TRIANGLE,
  99221. FLAC__APODIZATION_TUKEY,
  99222. FLAC__APODIZATION_WELCH
  99223. } FLAC__ApodizationFunction;
  99224. typedef struct {
  99225. FLAC__ApodizationFunction type;
  99226. union {
  99227. struct {
  99228. FLAC__real stddev;
  99229. } gauss;
  99230. struct {
  99231. FLAC__real p;
  99232. } tukey;
  99233. } parameters;
  99234. } FLAC__ApodizationSpecification;
  99235. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99236. typedef struct FLAC__StreamEncoderProtected {
  99237. FLAC__StreamEncoderState state;
  99238. FLAC__bool verify;
  99239. FLAC__bool streamable_subset;
  99240. FLAC__bool do_md5;
  99241. FLAC__bool do_mid_side_stereo;
  99242. FLAC__bool loose_mid_side_stereo;
  99243. unsigned channels;
  99244. unsigned bits_per_sample;
  99245. unsigned sample_rate;
  99246. unsigned blocksize;
  99247. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99248. unsigned num_apodizations;
  99249. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  99250. #endif
  99251. unsigned max_lpc_order;
  99252. unsigned qlp_coeff_precision;
  99253. FLAC__bool do_qlp_coeff_prec_search;
  99254. FLAC__bool do_exhaustive_model_search;
  99255. FLAC__bool do_escape_coding;
  99256. unsigned min_residual_partition_order;
  99257. unsigned max_residual_partition_order;
  99258. unsigned rice_parameter_search_dist;
  99259. FLAC__uint64 total_samples_estimate;
  99260. FLAC__StreamMetadata **metadata;
  99261. unsigned num_metadata_blocks;
  99262. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  99263. #if FLAC__HAS_OGG
  99264. FLAC__OggEncoderAspect ogg_encoder_aspect;
  99265. #endif
  99266. } FLAC__StreamEncoderProtected;
  99267. #endif
  99268. /*** End of inlined file: stream_encoder.h ***/
  99269. #if FLAC__HAS_OGG
  99270. #include "include/private/ogg_helper.h"
  99271. #include "include/private/ogg_mapping.h"
  99272. #endif
  99273. /*** Start of inlined file: stream_encoder_framing.h ***/
  99274. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  99275. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  99276. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  99277. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  99278. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  99279. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  99280. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  99281. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  99282. #endif
  99283. /*** End of inlined file: stream_encoder_framing.h ***/
  99284. /*** Start of inlined file: window.h ***/
  99285. #ifndef FLAC__PRIVATE__WINDOW_H
  99286. #define FLAC__PRIVATE__WINDOW_H
  99287. #ifdef HAVE_CONFIG_H
  99288. #include <config.h>
  99289. #endif
  99290. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99291. /*
  99292. * FLAC__window_*()
  99293. * --------------------------------------------------------------------
  99294. * Calculates window coefficients according to different apodization
  99295. * functions.
  99296. *
  99297. * OUT window[0,L-1]
  99298. * IN L (number of points in window)
  99299. */
  99300. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  99301. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  99302. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  99303. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  99304. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  99305. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  99306. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  99307. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  99308. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  99309. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  99310. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  99311. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  99312. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  99313. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  99314. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  99315. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  99316. #endif
  99317. /*** End of inlined file: window.h ***/
  99318. #ifndef FLaC__INLINE
  99319. #define FLaC__INLINE
  99320. #endif
  99321. #ifdef min
  99322. #undef min
  99323. #endif
  99324. #define min(x,y) ((x)<(y)?(x):(y))
  99325. #ifdef max
  99326. #undef max
  99327. #endif
  99328. #define max(x,y) ((x)>(y)?(x):(y))
  99329. /* Exact Rice codeword length calculation is off by default. The simple
  99330. * (and fast) estimation (of how many bits a residual value will be
  99331. * encoded with) in this encoder is very good, almost always yielding
  99332. * compression within 0.1% of exact calculation.
  99333. */
  99334. #undef EXACT_RICE_BITS_CALCULATION
  99335. /* Rice parameter searching is off by default. The simple (and fast)
  99336. * parameter estimation in this encoder is very good, almost always
  99337. * yielding compression within 0.1% of the optimal parameters.
  99338. */
  99339. #undef ENABLE_RICE_PARAMETER_SEARCH
  99340. typedef struct {
  99341. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  99342. unsigned size; /* of each data[] in samples */
  99343. unsigned tail;
  99344. } verify_input_fifo;
  99345. typedef struct {
  99346. const FLAC__byte *data;
  99347. unsigned capacity;
  99348. unsigned bytes;
  99349. } verify_output;
  99350. typedef enum {
  99351. ENCODER_IN_MAGIC = 0,
  99352. ENCODER_IN_METADATA = 1,
  99353. ENCODER_IN_AUDIO = 2
  99354. } EncoderStateHint;
  99355. static struct CompressionLevels {
  99356. FLAC__bool do_mid_side_stereo;
  99357. FLAC__bool loose_mid_side_stereo;
  99358. unsigned max_lpc_order;
  99359. unsigned qlp_coeff_precision;
  99360. FLAC__bool do_qlp_coeff_prec_search;
  99361. FLAC__bool do_escape_coding;
  99362. FLAC__bool do_exhaustive_model_search;
  99363. unsigned min_residual_partition_order;
  99364. unsigned max_residual_partition_order;
  99365. unsigned rice_parameter_search_dist;
  99366. } compression_levels_[] = {
  99367. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  99368. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  99369. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  99370. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  99371. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  99372. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  99373. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  99374. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  99375. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  99376. };
  99377. /***********************************************************************
  99378. *
  99379. * Private class method prototypes
  99380. *
  99381. ***********************************************************************/
  99382. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  99383. static void free_(FLAC__StreamEncoder *encoder);
  99384. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  99385. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  99386. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  99387. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  99388. #if FLAC__HAS_OGG
  99389. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  99390. #endif
  99391. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  99392. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  99393. static FLAC__bool process_subframe_(
  99394. FLAC__StreamEncoder *encoder,
  99395. unsigned min_partition_order,
  99396. unsigned max_partition_order,
  99397. const FLAC__FrameHeader *frame_header,
  99398. unsigned subframe_bps,
  99399. const FLAC__int32 integer_signal[],
  99400. FLAC__Subframe *subframe[2],
  99401. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  99402. FLAC__int32 *residual[2],
  99403. unsigned *best_subframe,
  99404. unsigned *best_bits
  99405. );
  99406. static FLAC__bool add_subframe_(
  99407. FLAC__StreamEncoder *encoder,
  99408. unsigned blocksize,
  99409. unsigned subframe_bps,
  99410. const FLAC__Subframe *subframe,
  99411. FLAC__BitWriter *frame
  99412. );
  99413. static unsigned evaluate_constant_subframe_(
  99414. FLAC__StreamEncoder *encoder,
  99415. const FLAC__int32 signal,
  99416. unsigned blocksize,
  99417. unsigned subframe_bps,
  99418. FLAC__Subframe *subframe
  99419. );
  99420. static unsigned evaluate_fixed_subframe_(
  99421. FLAC__StreamEncoder *encoder,
  99422. const FLAC__int32 signal[],
  99423. FLAC__int32 residual[],
  99424. FLAC__uint64 abs_residual_partition_sums[],
  99425. unsigned raw_bits_per_partition[],
  99426. unsigned blocksize,
  99427. unsigned subframe_bps,
  99428. unsigned order,
  99429. unsigned rice_parameter,
  99430. unsigned rice_parameter_limit,
  99431. unsigned min_partition_order,
  99432. unsigned max_partition_order,
  99433. FLAC__bool do_escape_coding,
  99434. unsigned rice_parameter_search_dist,
  99435. FLAC__Subframe *subframe,
  99436. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  99437. );
  99438. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99439. static unsigned evaluate_lpc_subframe_(
  99440. FLAC__StreamEncoder *encoder,
  99441. const FLAC__int32 signal[],
  99442. FLAC__int32 residual[],
  99443. FLAC__uint64 abs_residual_partition_sums[],
  99444. unsigned raw_bits_per_partition[],
  99445. const FLAC__real lp_coeff[],
  99446. unsigned blocksize,
  99447. unsigned subframe_bps,
  99448. unsigned order,
  99449. unsigned qlp_coeff_precision,
  99450. unsigned rice_parameter,
  99451. unsigned rice_parameter_limit,
  99452. unsigned min_partition_order,
  99453. unsigned max_partition_order,
  99454. FLAC__bool do_escape_coding,
  99455. unsigned rice_parameter_search_dist,
  99456. FLAC__Subframe *subframe,
  99457. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  99458. );
  99459. #endif
  99460. static unsigned evaluate_verbatim_subframe_(
  99461. FLAC__StreamEncoder *encoder,
  99462. const FLAC__int32 signal[],
  99463. unsigned blocksize,
  99464. unsigned subframe_bps,
  99465. FLAC__Subframe *subframe
  99466. );
  99467. static unsigned find_best_partition_order_(
  99468. struct FLAC__StreamEncoderPrivate *private_,
  99469. const FLAC__int32 residual[],
  99470. FLAC__uint64 abs_residual_partition_sums[],
  99471. unsigned raw_bits_per_partition[],
  99472. unsigned residual_samples,
  99473. unsigned predictor_order,
  99474. unsigned rice_parameter,
  99475. unsigned rice_parameter_limit,
  99476. unsigned min_partition_order,
  99477. unsigned max_partition_order,
  99478. unsigned bps,
  99479. FLAC__bool do_escape_coding,
  99480. unsigned rice_parameter_search_dist,
  99481. FLAC__EntropyCodingMethod *best_ecm
  99482. );
  99483. static void precompute_partition_info_sums_(
  99484. const FLAC__int32 residual[],
  99485. FLAC__uint64 abs_residual_partition_sums[],
  99486. unsigned residual_samples,
  99487. unsigned predictor_order,
  99488. unsigned min_partition_order,
  99489. unsigned max_partition_order,
  99490. unsigned bps
  99491. );
  99492. static void precompute_partition_info_escapes_(
  99493. const FLAC__int32 residual[],
  99494. unsigned raw_bits_per_partition[],
  99495. unsigned residual_samples,
  99496. unsigned predictor_order,
  99497. unsigned min_partition_order,
  99498. unsigned max_partition_order
  99499. );
  99500. static FLAC__bool set_partitioned_rice_(
  99501. #ifdef EXACT_RICE_BITS_CALCULATION
  99502. const FLAC__int32 residual[],
  99503. #endif
  99504. const FLAC__uint64 abs_residual_partition_sums[],
  99505. const unsigned raw_bits_per_partition[],
  99506. const unsigned residual_samples,
  99507. const unsigned predictor_order,
  99508. const unsigned suggested_rice_parameter,
  99509. const unsigned rice_parameter_limit,
  99510. const unsigned rice_parameter_search_dist,
  99511. const unsigned partition_order,
  99512. const FLAC__bool search_for_escapes,
  99513. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  99514. unsigned *bits
  99515. );
  99516. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  99517. /* verify-related routines: */
  99518. static void append_to_verify_fifo_(
  99519. verify_input_fifo *fifo,
  99520. const FLAC__int32 * const input[],
  99521. unsigned input_offset,
  99522. unsigned channels,
  99523. unsigned wide_samples
  99524. );
  99525. static void append_to_verify_fifo_interleaved_(
  99526. verify_input_fifo *fifo,
  99527. const FLAC__int32 input[],
  99528. unsigned input_offset,
  99529. unsigned channels,
  99530. unsigned wide_samples
  99531. );
  99532. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99533. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  99534. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  99535. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  99536. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99537. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  99538. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  99539. 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);
  99540. static FILE *get_binary_stdout_(void);
  99541. /***********************************************************************
  99542. *
  99543. * Private class data
  99544. *
  99545. ***********************************************************************/
  99546. typedef struct FLAC__StreamEncoderPrivate {
  99547. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  99548. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  99549. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  99550. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99551. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  99552. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  99553. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  99554. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  99555. #endif
  99556. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  99557. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  99558. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  99559. FLAC__int32 *residual_workspace_mid_side[2][2];
  99560. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  99561. FLAC__Subframe subframe_workspace_mid_side[2][2];
  99562. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  99563. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  99564. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  99565. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  99566. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  99567. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  99568. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  99569. unsigned best_subframe_mid_side[2];
  99570. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  99571. unsigned best_subframe_bits_mid_side[2];
  99572. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  99573. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  99574. FLAC__BitWriter *frame; /* the current frame being worked on */
  99575. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  99576. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  99577. FLAC__ChannelAssignment last_channel_assignment;
  99578. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  99579. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  99580. unsigned current_sample_number;
  99581. unsigned current_frame_number;
  99582. FLAC__MD5Context md5context;
  99583. FLAC__CPUInfo cpuinfo;
  99584. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99585. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  99586. #else
  99587. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  99588. #endif
  99589. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99590. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  99591. 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[]);
  99592. 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[]);
  99593. 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[]);
  99594. #endif
  99595. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  99596. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  99597. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  99598. FLAC__bool disable_constant_subframes;
  99599. FLAC__bool disable_fixed_subframes;
  99600. FLAC__bool disable_verbatim_subframes;
  99601. #if FLAC__HAS_OGG
  99602. FLAC__bool is_ogg;
  99603. #endif
  99604. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  99605. FLAC__StreamEncoderSeekCallback seek_callback;
  99606. FLAC__StreamEncoderTellCallback tell_callback;
  99607. FLAC__StreamEncoderWriteCallback write_callback;
  99608. FLAC__StreamEncoderMetadataCallback metadata_callback;
  99609. FLAC__StreamEncoderProgressCallback progress_callback;
  99610. void *client_data;
  99611. unsigned first_seekpoint_to_check;
  99612. FILE *file; /* only used when encoding to a file */
  99613. FLAC__uint64 bytes_written;
  99614. FLAC__uint64 samples_written;
  99615. unsigned frames_written;
  99616. unsigned total_frames_estimate;
  99617. /* unaligned (original) pointers to allocated data */
  99618. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  99619. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  99620. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99621. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  99622. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  99623. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  99624. FLAC__real *windowed_signal_unaligned;
  99625. #endif
  99626. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  99627. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  99628. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  99629. unsigned *raw_bits_per_partition_unaligned;
  99630. /*
  99631. * These fields have been moved here from private function local
  99632. * declarations merely to save stack space during encoding.
  99633. */
  99634. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99635. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  99636. #endif
  99637. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  99638. /*
  99639. * The data for the verify section
  99640. */
  99641. struct {
  99642. FLAC__StreamDecoder *decoder;
  99643. EncoderStateHint state_hint;
  99644. FLAC__bool needs_magic_hack;
  99645. verify_input_fifo input_fifo;
  99646. verify_output output;
  99647. struct {
  99648. FLAC__uint64 absolute_sample;
  99649. unsigned frame_number;
  99650. unsigned channel;
  99651. unsigned sample;
  99652. FLAC__int32 expected;
  99653. FLAC__int32 got;
  99654. } error_stats;
  99655. } verify;
  99656. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  99657. } FLAC__StreamEncoderPrivate;
  99658. /***********************************************************************
  99659. *
  99660. * Public static class data
  99661. *
  99662. ***********************************************************************/
  99663. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  99664. "FLAC__STREAM_ENCODER_OK",
  99665. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  99666. "FLAC__STREAM_ENCODER_OGG_ERROR",
  99667. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  99668. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  99669. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  99670. "FLAC__STREAM_ENCODER_IO_ERROR",
  99671. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  99672. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  99673. };
  99674. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  99675. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  99676. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  99677. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  99678. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  99679. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  99680. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  99681. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  99682. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  99683. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  99684. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  99685. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  99686. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  99687. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  99688. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  99689. };
  99690. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  99691. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  99692. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  99693. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  99694. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  99695. };
  99696. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  99697. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  99698. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  99699. };
  99700. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  99701. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  99702. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  99703. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  99704. };
  99705. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  99706. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  99707. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  99708. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  99709. };
  99710. /* Number of samples that will be overread to watch for end of stream. By
  99711. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  99712. * always try to read blocksize+1 samples before encoding a block, so that
  99713. * even if the stream has a total sample count that is an integral multiple
  99714. * of the blocksize, we will still notice when we are encoding the last
  99715. * block. This is needed, for example, to correctly set the end-of-stream
  99716. * marker in Ogg FLAC.
  99717. *
  99718. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  99719. * not really any reason to change it.
  99720. */
  99721. static const unsigned OVERREAD_ = 1;
  99722. /***********************************************************************
  99723. *
  99724. * Class constructor/destructor
  99725. *
  99726. */
  99727. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  99728. {
  99729. FLAC__StreamEncoder *encoder;
  99730. unsigned i;
  99731. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  99732. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  99733. if(encoder == 0) {
  99734. return 0;
  99735. }
  99736. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  99737. if(encoder->protected_ == 0) {
  99738. free(encoder);
  99739. return 0;
  99740. }
  99741. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  99742. if(encoder->private_ == 0) {
  99743. free(encoder->protected_);
  99744. free(encoder);
  99745. return 0;
  99746. }
  99747. encoder->private_->frame = FLAC__bitwriter_new();
  99748. if(encoder->private_->frame == 0) {
  99749. free(encoder->private_);
  99750. free(encoder->protected_);
  99751. free(encoder);
  99752. return 0;
  99753. }
  99754. encoder->private_->file = 0;
  99755. set_defaults_enc(encoder);
  99756. encoder->private_->is_being_deleted = false;
  99757. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99758. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  99759. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  99760. }
  99761. for(i = 0; i < 2; i++) {
  99762. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  99763. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  99764. }
  99765. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99766. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  99767. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  99768. }
  99769. for(i = 0; i < 2; i++) {
  99770. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  99771. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  99772. }
  99773. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99774. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  99775. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  99776. }
  99777. for(i = 0; i < 2; i++) {
  99778. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  99779. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  99780. }
  99781. for(i = 0; i < 2; i++)
  99782. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  99783. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  99784. return encoder;
  99785. }
  99786. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  99787. {
  99788. unsigned i;
  99789. FLAC__ASSERT(0 != encoder);
  99790. FLAC__ASSERT(0 != encoder->protected_);
  99791. FLAC__ASSERT(0 != encoder->private_);
  99792. FLAC__ASSERT(0 != encoder->private_->frame);
  99793. encoder->private_->is_being_deleted = true;
  99794. (void)FLAC__stream_encoder_finish(encoder);
  99795. if(0 != encoder->private_->verify.decoder)
  99796. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  99797. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99798. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  99799. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  99800. }
  99801. for(i = 0; i < 2; i++) {
  99802. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  99803. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  99804. }
  99805. for(i = 0; i < 2; i++)
  99806. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  99807. FLAC__bitwriter_delete(encoder->private_->frame);
  99808. free(encoder->private_);
  99809. free(encoder->protected_);
  99810. free(encoder);
  99811. }
  99812. /***********************************************************************
  99813. *
  99814. * Public class methods
  99815. *
  99816. ***********************************************************************/
  99817. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  99818. FLAC__StreamEncoder *encoder,
  99819. FLAC__StreamEncoderReadCallback read_callback,
  99820. FLAC__StreamEncoderWriteCallback write_callback,
  99821. FLAC__StreamEncoderSeekCallback seek_callback,
  99822. FLAC__StreamEncoderTellCallback tell_callback,
  99823. FLAC__StreamEncoderMetadataCallback metadata_callback,
  99824. void *client_data,
  99825. FLAC__bool is_ogg
  99826. )
  99827. {
  99828. unsigned i;
  99829. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  99830. FLAC__ASSERT(0 != encoder);
  99831. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99832. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  99833. #if !FLAC__HAS_OGG
  99834. if(is_ogg)
  99835. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  99836. #endif
  99837. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  99838. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  99839. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  99840. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  99841. if(encoder->protected_->channels != 2) {
  99842. encoder->protected_->do_mid_side_stereo = false;
  99843. encoder->protected_->loose_mid_side_stereo = false;
  99844. }
  99845. else if(!encoder->protected_->do_mid_side_stereo)
  99846. encoder->protected_->loose_mid_side_stereo = false;
  99847. if(encoder->protected_->bits_per_sample >= 32)
  99848. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  99849. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  99850. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  99851. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  99852. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  99853. if(encoder->protected_->blocksize == 0) {
  99854. if(encoder->protected_->max_lpc_order == 0)
  99855. encoder->protected_->blocksize = 1152;
  99856. else
  99857. encoder->protected_->blocksize = 4096;
  99858. }
  99859. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  99860. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  99861. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  99862. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  99863. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  99864. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  99865. if(encoder->protected_->qlp_coeff_precision == 0) {
  99866. if(encoder->protected_->bits_per_sample < 16) {
  99867. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  99868. /* @@@ until then we'll make a guess */
  99869. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  99870. }
  99871. else if(encoder->protected_->bits_per_sample == 16) {
  99872. if(encoder->protected_->blocksize <= 192)
  99873. encoder->protected_->qlp_coeff_precision = 7;
  99874. else if(encoder->protected_->blocksize <= 384)
  99875. encoder->protected_->qlp_coeff_precision = 8;
  99876. else if(encoder->protected_->blocksize <= 576)
  99877. encoder->protected_->qlp_coeff_precision = 9;
  99878. else if(encoder->protected_->blocksize <= 1152)
  99879. encoder->protected_->qlp_coeff_precision = 10;
  99880. else if(encoder->protected_->blocksize <= 2304)
  99881. encoder->protected_->qlp_coeff_precision = 11;
  99882. else if(encoder->protected_->blocksize <= 4608)
  99883. encoder->protected_->qlp_coeff_precision = 12;
  99884. else
  99885. encoder->protected_->qlp_coeff_precision = 13;
  99886. }
  99887. else {
  99888. if(encoder->protected_->blocksize <= 384)
  99889. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  99890. else if(encoder->protected_->blocksize <= 1152)
  99891. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  99892. else
  99893. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  99894. }
  99895. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  99896. }
  99897. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  99898. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  99899. if(encoder->protected_->streamable_subset) {
  99900. if(
  99901. encoder->protected_->blocksize != 192 &&
  99902. encoder->protected_->blocksize != 576 &&
  99903. encoder->protected_->blocksize != 1152 &&
  99904. encoder->protected_->blocksize != 2304 &&
  99905. encoder->protected_->blocksize != 4608 &&
  99906. encoder->protected_->blocksize != 256 &&
  99907. encoder->protected_->blocksize != 512 &&
  99908. encoder->protected_->blocksize != 1024 &&
  99909. encoder->protected_->blocksize != 2048 &&
  99910. encoder->protected_->blocksize != 4096 &&
  99911. encoder->protected_->blocksize != 8192 &&
  99912. encoder->protected_->blocksize != 16384
  99913. )
  99914. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  99915. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  99916. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  99917. if(
  99918. encoder->protected_->bits_per_sample != 8 &&
  99919. encoder->protected_->bits_per_sample != 12 &&
  99920. encoder->protected_->bits_per_sample != 16 &&
  99921. encoder->protected_->bits_per_sample != 20 &&
  99922. encoder->protected_->bits_per_sample != 24
  99923. )
  99924. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  99925. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  99926. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  99927. if(
  99928. encoder->protected_->sample_rate <= 48000 &&
  99929. (
  99930. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  99931. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  99932. )
  99933. ) {
  99934. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  99935. }
  99936. }
  99937. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  99938. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  99939. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  99940. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  99941. #if FLAC__HAS_OGG
  99942. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  99943. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  99944. unsigned i;
  99945. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  99946. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  99947. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  99948. for( ; i > 0; i--)
  99949. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  99950. encoder->protected_->metadata[0] = vc;
  99951. break;
  99952. }
  99953. }
  99954. }
  99955. #endif
  99956. /* keep track of any SEEKTABLE block */
  99957. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  99958. unsigned i;
  99959. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  99960. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  99961. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  99962. break; /* take only the first one */
  99963. }
  99964. }
  99965. }
  99966. /* validate metadata */
  99967. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  99968. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99969. metadata_has_seektable = false;
  99970. metadata_has_vorbis_comment = false;
  99971. metadata_picture_has_type1 = false;
  99972. metadata_picture_has_type2 = false;
  99973. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  99974. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  99975. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  99976. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99977. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  99978. if(metadata_has_seektable) /* only one is allowed */
  99979. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99980. metadata_has_seektable = true;
  99981. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  99982. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99983. }
  99984. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  99985. if(metadata_has_vorbis_comment) /* only one is allowed */
  99986. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99987. metadata_has_vorbis_comment = true;
  99988. }
  99989. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  99990. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  99991. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99992. }
  99993. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  99994. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  99995. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99996. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  99997. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  99998. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99999. metadata_picture_has_type1 = true;
  100000. /* standard icon must be 32x32 pixel PNG */
  100001. if(
  100002. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  100003. (
  100004. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  100005. m->data.picture.width != 32 ||
  100006. m->data.picture.height != 32
  100007. )
  100008. )
  100009. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  100010. }
  100011. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  100012. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  100013. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  100014. metadata_picture_has_type2 = true;
  100015. }
  100016. }
  100017. }
  100018. encoder->private_->input_capacity = 0;
  100019. for(i = 0; i < encoder->protected_->channels; i++) {
  100020. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  100021. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100022. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  100023. #endif
  100024. }
  100025. for(i = 0; i < 2; i++) {
  100026. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  100027. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100028. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  100029. #endif
  100030. }
  100031. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100032. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  100033. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  100034. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  100035. #endif
  100036. for(i = 0; i < encoder->protected_->channels; i++) {
  100037. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  100038. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  100039. encoder->private_->best_subframe[i] = 0;
  100040. }
  100041. for(i = 0; i < 2; i++) {
  100042. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  100043. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  100044. encoder->private_->best_subframe_mid_side[i] = 0;
  100045. }
  100046. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  100047. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  100048. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100049. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  100050. #else
  100051. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  100052. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  100053. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  100054. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  100055. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  100056. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  100057. 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);
  100058. #endif
  100059. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  100060. encoder->private_->loose_mid_side_stereo_frames = 1;
  100061. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  100062. encoder->private_->current_sample_number = 0;
  100063. encoder->private_->current_frame_number = 0;
  100064. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  100065. 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? */
  100066. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  100067. /*
  100068. * get the CPU info and set the function pointers
  100069. */
  100070. FLAC__cpu_info(&encoder->private_->cpuinfo);
  100071. /* first default to the non-asm routines */
  100072. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100073. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  100074. #endif
  100075. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  100076. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100077. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  100078. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  100079. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  100080. #endif
  100081. /* now override with asm where appropriate */
  100082. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100083. # ifndef FLAC__NO_ASM
  100084. if(encoder->private_->cpuinfo.use_asm) {
  100085. # ifdef FLAC__CPU_IA32
  100086. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  100087. # ifdef FLAC__HAS_NASM
  100088. if(encoder->private_->cpuinfo.data.ia32.sse) {
  100089. if(encoder->protected_->max_lpc_order < 4)
  100090. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  100091. else if(encoder->protected_->max_lpc_order < 8)
  100092. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  100093. else if(encoder->protected_->max_lpc_order < 12)
  100094. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  100095. else
  100096. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  100097. }
  100098. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  100099. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  100100. else
  100101. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  100102. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  100103. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  100104. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  100105. }
  100106. else {
  100107. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  100108. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  100109. }
  100110. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  100111. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  100112. # endif /* FLAC__HAS_NASM */
  100113. # endif /* FLAC__CPU_IA32 */
  100114. }
  100115. # endif /* !FLAC__NO_ASM */
  100116. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  100117. /* finally override based on wide-ness if necessary */
  100118. if(encoder->private_->use_wide_by_block) {
  100119. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  100120. }
  100121. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  100122. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  100123. #if FLAC__HAS_OGG
  100124. encoder->private_->is_ogg = is_ogg;
  100125. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  100126. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  100127. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100128. }
  100129. #endif
  100130. encoder->private_->read_callback = read_callback;
  100131. encoder->private_->write_callback = write_callback;
  100132. encoder->private_->seek_callback = seek_callback;
  100133. encoder->private_->tell_callback = tell_callback;
  100134. encoder->private_->metadata_callback = metadata_callback;
  100135. encoder->private_->client_data = client_data;
  100136. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  100137. /* the above function sets the state for us in case of an error */
  100138. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100139. }
  100140. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  100141. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  100142. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100143. }
  100144. /*
  100145. * Set up the verify stuff if necessary
  100146. */
  100147. if(encoder->protected_->verify) {
  100148. /*
  100149. * First, set up the fifo which will hold the
  100150. * original signal to compare against
  100151. */
  100152. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  100153. for(i = 0; i < encoder->protected_->channels; i++) {
  100154. 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))) {
  100155. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  100156. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100157. }
  100158. }
  100159. encoder->private_->verify.input_fifo.tail = 0;
  100160. /*
  100161. * Now set up a stream decoder for verification
  100162. */
  100163. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  100164. if(0 == encoder->private_->verify.decoder) {
  100165. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  100166. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100167. }
  100168. 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) {
  100169. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  100170. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100171. }
  100172. }
  100173. encoder->private_->verify.error_stats.absolute_sample = 0;
  100174. encoder->private_->verify.error_stats.frame_number = 0;
  100175. encoder->private_->verify.error_stats.channel = 0;
  100176. encoder->private_->verify.error_stats.sample = 0;
  100177. encoder->private_->verify.error_stats.expected = 0;
  100178. encoder->private_->verify.error_stats.got = 0;
  100179. /*
  100180. * These must be done before we write any metadata, because that
  100181. * calls the write_callback, which uses these values.
  100182. */
  100183. encoder->private_->first_seekpoint_to_check = 0;
  100184. encoder->private_->samples_written = 0;
  100185. encoder->protected_->streaminfo_offset = 0;
  100186. encoder->protected_->seektable_offset = 0;
  100187. encoder->protected_->audio_offset = 0;
  100188. /*
  100189. * write the stream header
  100190. */
  100191. if(encoder->protected_->verify)
  100192. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  100193. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  100194. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100195. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100196. }
  100197. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  100198. /* the above function sets the state for us in case of an error */
  100199. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100200. }
  100201. /*
  100202. * write the STREAMINFO metadata block
  100203. */
  100204. if(encoder->protected_->verify)
  100205. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  100206. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  100207. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  100208. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  100209. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  100210. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  100211. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  100212. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  100213. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  100214. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  100215. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  100216. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  100217. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  100218. if(encoder->protected_->do_md5)
  100219. FLAC__MD5Init(&encoder->private_->md5context);
  100220. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  100221. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100222. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100223. }
  100224. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  100225. /* the above function sets the state for us in case of an error */
  100226. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100227. }
  100228. /*
  100229. * Now that the STREAMINFO block is written, we can init this to an
  100230. * absurdly-high value...
  100231. */
  100232. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  100233. /* ... and clear this to 0 */
  100234. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  100235. /*
  100236. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  100237. * if not, we will write an empty one (FLAC__add_metadata_block()
  100238. * automatically supplies the vendor string).
  100239. *
  100240. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  100241. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  100242. * true it will have already insured that the metadata list is properly
  100243. * ordered.)
  100244. */
  100245. if(!metadata_has_vorbis_comment) {
  100246. FLAC__StreamMetadata vorbis_comment;
  100247. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  100248. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  100249. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  100250. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  100251. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  100252. vorbis_comment.data.vorbis_comment.num_comments = 0;
  100253. vorbis_comment.data.vorbis_comment.comments = 0;
  100254. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  100255. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100256. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100257. }
  100258. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  100259. /* the above function sets the state for us in case of an error */
  100260. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100261. }
  100262. }
  100263. /*
  100264. * write the user's metadata blocks
  100265. */
  100266. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  100267. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  100268. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  100269. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100270. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100271. }
  100272. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  100273. /* the above function sets the state for us in case of an error */
  100274. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100275. }
  100276. }
  100277. /* now that all the metadata is written, we save the stream offset */
  100278. 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 */
  100279. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100280. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100281. }
  100282. if(encoder->protected_->verify)
  100283. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  100284. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  100285. }
  100286. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  100287. FLAC__StreamEncoder *encoder,
  100288. FLAC__StreamEncoderWriteCallback write_callback,
  100289. FLAC__StreamEncoderSeekCallback seek_callback,
  100290. FLAC__StreamEncoderTellCallback tell_callback,
  100291. FLAC__StreamEncoderMetadataCallback metadata_callback,
  100292. void *client_data
  100293. )
  100294. {
  100295. return init_stream_internal_enc(
  100296. encoder,
  100297. /*read_callback=*/0,
  100298. write_callback,
  100299. seek_callback,
  100300. tell_callback,
  100301. metadata_callback,
  100302. client_data,
  100303. /*is_ogg=*/false
  100304. );
  100305. }
  100306. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  100307. FLAC__StreamEncoder *encoder,
  100308. FLAC__StreamEncoderReadCallback read_callback,
  100309. FLAC__StreamEncoderWriteCallback write_callback,
  100310. FLAC__StreamEncoderSeekCallback seek_callback,
  100311. FLAC__StreamEncoderTellCallback tell_callback,
  100312. FLAC__StreamEncoderMetadataCallback metadata_callback,
  100313. void *client_data
  100314. )
  100315. {
  100316. return init_stream_internal_enc(
  100317. encoder,
  100318. read_callback,
  100319. write_callback,
  100320. seek_callback,
  100321. tell_callback,
  100322. metadata_callback,
  100323. client_data,
  100324. /*is_ogg=*/true
  100325. );
  100326. }
  100327. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  100328. FLAC__StreamEncoder *encoder,
  100329. FILE *file,
  100330. FLAC__StreamEncoderProgressCallback progress_callback,
  100331. void *client_data,
  100332. FLAC__bool is_ogg
  100333. )
  100334. {
  100335. FLAC__StreamEncoderInitStatus init_status;
  100336. FLAC__ASSERT(0 != encoder);
  100337. FLAC__ASSERT(0 != file);
  100338. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100339. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  100340. /* double protection */
  100341. if(file == 0) {
  100342. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  100343. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100344. }
  100345. /*
  100346. * To make sure that our file does not go unclosed after an error, we
  100347. * must assign the FILE pointer before any further error can occur in
  100348. * this routine.
  100349. */
  100350. if(file == stdout)
  100351. file = get_binary_stdout_(); /* just to be safe */
  100352. encoder->private_->file = file;
  100353. encoder->private_->progress_callback = progress_callback;
  100354. encoder->private_->bytes_written = 0;
  100355. encoder->private_->samples_written = 0;
  100356. encoder->private_->frames_written = 0;
  100357. init_status = init_stream_internal_enc(
  100358. encoder,
  100359. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  100360. file_write_callback_,
  100361. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  100362. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  100363. /*metadata_callback=*/0,
  100364. client_data,
  100365. is_ogg
  100366. );
  100367. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  100368. /* the above function sets the state for us in case of an error */
  100369. return init_status;
  100370. }
  100371. {
  100372. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  100373. FLAC__ASSERT(blocksize != 0);
  100374. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  100375. }
  100376. return init_status;
  100377. }
  100378. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  100379. FLAC__StreamEncoder *encoder,
  100380. FILE *file,
  100381. FLAC__StreamEncoderProgressCallback progress_callback,
  100382. void *client_data
  100383. )
  100384. {
  100385. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  100386. }
  100387. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  100388. FLAC__StreamEncoder *encoder,
  100389. FILE *file,
  100390. FLAC__StreamEncoderProgressCallback progress_callback,
  100391. void *client_data
  100392. )
  100393. {
  100394. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  100395. }
  100396. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  100397. FLAC__StreamEncoder *encoder,
  100398. const char *filename,
  100399. FLAC__StreamEncoderProgressCallback progress_callback,
  100400. void *client_data,
  100401. FLAC__bool is_ogg
  100402. )
  100403. {
  100404. FILE *file;
  100405. FLAC__ASSERT(0 != encoder);
  100406. /*
  100407. * To make sure that our file does not go unclosed after an error, we
  100408. * have to do the same entrance checks here that are later performed
  100409. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  100410. */
  100411. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100412. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  100413. file = filename? fopen(filename, "w+b") : stdout;
  100414. if(file == 0) {
  100415. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  100416. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  100417. }
  100418. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  100419. }
  100420. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  100421. FLAC__StreamEncoder *encoder,
  100422. const char *filename,
  100423. FLAC__StreamEncoderProgressCallback progress_callback,
  100424. void *client_data
  100425. )
  100426. {
  100427. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  100428. }
  100429. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  100430. FLAC__StreamEncoder *encoder,
  100431. const char *filename,
  100432. FLAC__StreamEncoderProgressCallback progress_callback,
  100433. void *client_data
  100434. )
  100435. {
  100436. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  100437. }
  100438. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  100439. {
  100440. FLAC__bool error = false;
  100441. FLAC__ASSERT(0 != encoder);
  100442. FLAC__ASSERT(0 != encoder->private_);
  100443. FLAC__ASSERT(0 != encoder->protected_);
  100444. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  100445. return true;
  100446. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  100447. if(encoder->private_->current_sample_number != 0) {
  100448. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  100449. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  100450. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  100451. error = true;
  100452. }
  100453. }
  100454. if(encoder->protected_->do_md5)
  100455. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  100456. if(!encoder->private_->is_being_deleted) {
  100457. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  100458. if(encoder->private_->seek_callback) {
  100459. #if FLAC__HAS_OGG
  100460. if(encoder->private_->is_ogg)
  100461. update_ogg_metadata_(encoder);
  100462. else
  100463. #endif
  100464. update_metadata_(encoder);
  100465. /* check if an error occurred while updating metadata */
  100466. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  100467. error = true;
  100468. }
  100469. if(encoder->private_->metadata_callback)
  100470. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  100471. }
  100472. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  100473. if(!error)
  100474. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  100475. error = true;
  100476. }
  100477. }
  100478. if(0 != encoder->private_->file) {
  100479. if(encoder->private_->file != stdout)
  100480. fclose(encoder->private_->file);
  100481. encoder->private_->file = 0;
  100482. }
  100483. #if FLAC__HAS_OGG
  100484. if(encoder->private_->is_ogg)
  100485. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  100486. #endif
  100487. free_(encoder);
  100488. set_defaults_enc(encoder);
  100489. if(!error)
  100490. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  100491. return !error;
  100492. }
  100493. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  100494. {
  100495. FLAC__ASSERT(0 != encoder);
  100496. FLAC__ASSERT(0 != encoder->private_);
  100497. FLAC__ASSERT(0 != encoder->protected_);
  100498. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100499. return false;
  100500. #if FLAC__HAS_OGG
  100501. /* can't check encoder->private_->is_ogg since that's not set until init time */
  100502. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  100503. return true;
  100504. #else
  100505. (void)value;
  100506. return false;
  100507. #endif
  100508. }
  100509. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100510. {
  100511. FLAC__ASSERT(0 != encoder);
  100512. FLAC__ASSERT(0 != encoder->private_);
  100513. FLAC__ASSERT(0 != encoder->protected_);
  100514. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100515. return false;
  100516. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  100517. encoder->protected_->verify = value;
  100518. #endif
  100519. return true;
  100520. }
  100521. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100522. {
  100523. FLAC__ASSERT(0 != encoder);
  100524. FLAC__ASSERT(0 != encoder->private_);
  100525. FLAC__ASSERT(0 != encoder->protected_);
  100526. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100527. return false;
  100528. encoder->protected_->streamable_subset = value;
  100529. return true;
  100530. }
  100531. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100532. {
  100533. FLAC__ASSERT(0 != encoder);
  100534. FLAC__ASSERT(0 != encoder->private_);
  100535. FLAC__ASSERT(0 != encoder->protected_);
  100536. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100537. return false;
  100538. encoder->protected_->do_md5 = value;
  100539. return true;
  100540. }
  100541. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  100542. {
  100543. FLAC__ASSERT(0 != encoder);
  100544. FLAC__ASSERT(0 != encoder->private_);
  100545. FLAC__ASSERT(0 != encoder->protected_);
  100546. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100547. return false;
  100548. encoder->protected_->channels = value;
  100549. return true;
  100550. }
  100551. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  100552. {
  100553. FLAC__ASSERT(0 != encoder);
  100554. FLAC__ASSERT(0 != encoder->private_);
  100555. FLAC__ASSERT(0 != encoder->protected_);
  100556. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100557. return false;
  100558. encoder->protected_->bits_per_sample = value;
  100559. return true;
  100560. }
  100561. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  100562. {
  100563. FLAC__ASSERT(0 != encoder);
  100564. FLAC__ASSERT(0 != encoder->private_);
  100565. FLAC__ASSERT(0 != encoder->protected_);
  100566. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100567. return false;
  100568. encoder->protected_->sample_rate = value;
  100569. return true;
  100570. }
  100571. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  100572. {
  100573. FLAC__bool ok = true;
  100574. FLAC__ASSERT(0 != encoder);
  100575. FLAC__ASSERT(0 != encoder->private_);
  100576. FLAC__ASSERT(0 != encoder->protected_);
  100577. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100578. return false;
  100579. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  100580. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  100581. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  100582. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  100583. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100584. #if 0
  100585. /* was: */
  100586. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  100587. /* but it's too hard to specify the string in a locale-specific way */
  100588. #else
  100589. encoder->protected_->num_apodizations = 1;
  100590. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  100591. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  100592. #endif
  100593. #endif
  100594. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  100595. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  100596. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  100597. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  100598. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  100599. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  100600. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  100601. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  100602. return ok;
  100603. }
  100604. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  100605. {
  100606. FLAC__ASSERT(0 != encoder);
  100607. FLAC__ASSERT(0 != encoder->private_);
  100608. FLAC__ASSERT(0 != encoder->protected_);
  100609. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100610. return false;
  100611. encoder->protected_->blocksize = value;
  100612. return true;
  100613. }
  100614. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100615. {
  100616. FLAC__ASSERT(0 != encoder);
  100617. FLAC__ASSERT(0 != encoder->private_);
  100618. FLAC__ASSERT(0 != encoder->protected_);
  100619. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100620. return false;
  100621. encoder->protected_->do_mid_side_stereo = value;
  100622. return true;
  100623. }
  100624. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100625. {
  100626. FLAC__ASSERT(0 != encoder);
  100627. FLAC__ASSERT(0 != encoder->private_);
  100628. FLAC__ASSERT(0 != encoder->protected_);
  100629. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100630. return false;
  100631. encoder->protected_->loose_mid_side_stereo = value;
  100632. return true;
  100633. }
  100634. /*@@@@add to tests*/
  100635. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  100636. {
  100637. FLAC__ASSERT(0 != encoder);
  100638. FLAC__ASSERT(0 != encoder->private_);
  100639. FLAC__ASSERT(0 != encoder->protected_);
  100640. FLAC__ASSERT(0 != specification);
  100641. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100642. return false;
  100643. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  100644. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  100645. #else
  100646. encoder->protected_->num_apodizations = 0;
  100647. while(1) {
  100648. const char *s = strchr(specification, ';');
  100649. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  100650. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  100651. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  100652. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  100653. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  100654. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  100655. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  100656. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  100657. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  100658. else if(n==6 && 0 == strncmp("connes" , specification, n))
  100659. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  100660. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  100661. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  100662. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  100663. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  100664. if (stddev > 0.0 && stddev <= 0.5) {
  100665. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  100666. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  100667. }
  100668. }
  100669. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  100670. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  100671. else if(n==4 && 0 == strncmp("hann" , specification, n))
  100672. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  100673. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  100674. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  100675. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  100676. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  100677. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  100678. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  100679. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  100680. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  100681. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  100682. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  100683. if (p >= 0.0 && p <= 1.0) {
  100684. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  100685. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  100686. }
  100687. }
  100688. else if(n==5 && 0 == strncmp("welch" , specification, n))
  100689. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  100690. if (encoder->protected_->num_apodizations == 32)
  100691. break;
  100692. if (s)
  100693. specification = s+1;
  100694. else
  100695. break;
  100696. }
  100697. if(encoder->protected_->num_apodizations == 0) {
  100698. encoder->protected_->num_apodizations = 1;
  100699. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  100700. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  100701. }
  100702. #endif
  100703. return true;
  100704. }
  100705. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  100706. {
  100707. FLAC__ASSERT(0 != encoder);
  100708. FLAC__ASSERT(0 != encoder->private_);
  100709. FLAC__ASSERT(0 != encoder->protected_);
  100710. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100711. return false;
  100712. encoder->protected_->max_lpc_order = value;
  100713. return true;
  100714. }
  100715. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  100716. {
  100717. FLAC__ASSERT(0 != encoder);
  100718. FLAC__ASSERT(0 != encoder->private_);
  100719. FLAC__ASSERT(0 != encoder->protected_);
  100720. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100721. return false;
  100722. encoder->protected_->qlp_coeff_precision = value;
  100723. return true;
  100724. }
  100725. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100726. {
  100727. FLAC__ASSERT(0 != encoder);
  100728. FLAC__ASSERT(0 != encoder->private_);
  100729. FLAC__ASSERT(0 != encoder->protected_);
  100730. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100731. return false;
  100732. encoder->protected_->do_qlp_coeff_prec_search = value;
  100733. return true;
  100734. }
  100735. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100736. {
  100737. FLAC__ASSERT(0 != encoder);
  100738. FLAC__ASSERT(0 != encoder->private_);
  100739. FLAC__ASSERT(0 != encoder->protected_);
  100740. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100741. return false;
  100742. #if 0
  100743. /*@@@ deprecated: */
  100744. encoder->protected_->do_escape_coding = value;
  100745. #else
  100746. (void)value;
  100747. #endif
  100748. return true;
  100749. }
  100750. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100751. {
  100752. FLAC__ASSERT(0 != encoder);
  100753. FLAC__ASSERT(0 != encoder->private_);
  100754. FLAC__ASSERT(0 != encoder->protected_);
  100755. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100756. return false;
  100757. encoder->protected_->do_exhaustive_model_search = value;
  100758. return true;
  100759. }
  100760. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  100761. {
  100762. FLAC__ASSERT(0 != encoder);
  100763. FLAC__ASSERT(0 != encoder->private_);
  100764. FLAC__ASSERT(0 != encoder->protected_);
  100765. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100766. return false;
  100767. encoder->protected_->min_residual_partition_order = value;
  100768. return true;
  100769. }
  100770. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  100771. {
  100772. FLAC__ASSERT(0 != encoder);
  100773. FLAC__ASSERT(0 != encoder->private_);
  100774. FLAC__ASSERT(0 != encoder->protected_);
  100775. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100776. return false;
  100777. encoder->protected_->max_residual_partition_order = value;
  100778. return true;
  100779. }
  100780. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  100781. {
  100782. FLAC__ASSERT(0 != encoder);
  100783. FLAC__ASSERT(0 != encoder->private_);
  100784. FLAC__ASSERT(0 != encoder->protected_);
  100785. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100786. return false;
  100787. #if 0
  100788. /*@@@ deprecated: */
  100789. encoder->protected_->rice_parameter_search_dist = value;
  100790. #else
  100791. (void)value;
  100792. #endif
  100793. return true;
  100794. }
  100795. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  100796. {
  100797. FLAC__ASSERT(0 != encoder);
  100798. FLAC__ASSERT(0 != encoder->private_);
  100799. FLAC__ASSERT(0 != encoder->protected_);
  100800. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100801. return false;
  100802. encoder->protected_->total_samples_estimate = value;
  100803. return true;
  100804. }
  100805. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  100806. {
  100807. FLAC__ASSERT(0 != encoder);
  100808. FLAC__ASSERT(0 != encoder->private_);
  100809. FLAC__ASSERT(0 != encoder->protected_);
  100810. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100811. return false;
  100812. if(0 == metadata)
  100813. num_blocks = 0;
  100814. if(0 == num_blocks)
  100815. metadata = 0;
  100816. /* realloc() does not do exactly what we want so... */
  100817. if(encoder->protected_->metadata) {
  100818. free(encoder->protected_->metadata);
  100819. encoder->protected_->metadata = 0;
  100820. encoder->protected_->num_metadata_blocks = 0;
  100821. }
  100822. if(num_blocks) {
  100823. FLAC__StreamMetadata **m;
  100824. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  100825. return false;
  100826. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  100827. encoder->protected_->metadata = m;
  100828. encoder->protected_->num_metadata_blocks = num_blocks;
  100829. }
  100830. #if FLAC__HAS_OGG
  100831. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  100832. return false;
  100833. #endif
  100834. return true;
  100835. }
  100836. /*
  100837. * These three functions are not static, but not publically exposed in
  100838. * include/FLAC/ either. They are used by the test suite.
  100839. */
  100840. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100841. {
  100842. FLAC__ASSERT(0 != encoder);
  100843. FLAC__ASSERT(0 != encoder->private_);
  100844. FLAC__ASSERT(0 != encoder->protected_);
  100845. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100846. return false;
  100847. encoder->private_->disable_constant_subframes = value;
  100848. return true;
  100849. }
  100850. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100851. {
  100852. FLAC__ASSERT(0 != encoder);
  100853. FLAC__ASSERT(0 != encoder->private_);
  100854. FLAC__ASSERT(0 != encoder->protected_);
  100855. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100856. return false;
  100857. encoder->private_->disable_fixed_subframes = value;
  100858. return true;
  100859. }
  100860. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100861. {
  100862. FLAC__ASSERT(0 != encoder);
  100863. FLAC__ASSERT(0 != encoder->private_);
  100864. FLAC__ASSERT(0 != encoder->protected_);
  100865. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100866. return false;
  100867. encoder->private_->disable_verbatim_subframes = value;
  100868. return true;
  100869. }
  100870. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  100871. {
  100872. FLAC__ASSERT(0 != encoder);
  100873. FLAC__ASSERT(0 != encoder->private_);
  100874. FLAC__ASSERT(0 != encoder->protected_);
  100875. return encoder->protected_->state;
  100876. }
  100877. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  100878. {
  100879. FLAC__ASSERT(0 != encoder);
  100880. FLAC__ASSERT(0 != encoder->private_);
  100881. FLAC__ASSERT(0 != encoder->protected_);
  100882. if(encoder->protected_->verify)
  100883. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  100884. else
  100885. return FLAC__STREAM_DECODER_UNINITIALIZED;
  100886. }
  100887. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  100888. {
  100889. FLAC__ASSERT(0 != encoder);
  100890. FLAC__ASSERT(0 != encoder->private_);
  100891. FLAC__ASSERT(0 != encoder->protected_);
  100892. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  100893. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  100894. else
  100895. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  100896. }
  100897. 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)
  100898. {
  100899. FLAC__ASSERT(0 != encoder);
  100900. FLAC__ASSERT(0 != encoder->private_);
  100901. FLAC__ASSERT(0 != encoder->protected_);
  100902. if(0 != absolute_sample)
  100903. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  100904. if(0 != frame_number)
  100905. *frame_number = encoder->private_->verify.error_stats.frame_number;
  100906. if(0 != channel)
  100907. *channel = encoder->private_->verify.error_stats.channel;
  100908. if(0 != sample)
  100909. *sample = encoder->private_->verify.error_stats.sample;
  100910. if(0 != expected)
  100911. *expected = encoder->private_->verify.error_stats.expected;
  100912. if(0 != got)
  100913. *got = encoder->private_->verify.error_stats.got;
  100914. }
  100915. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  100916. {
  100917. FLAC__ASSERT(0 != encoder);
  100918. FLAC__ASSERT(0 != encoder->private_);
  100919. FLAC__ASSERT(0 != encoder->protected_);
  100920. return encoder->protected_->verify;
  100921. }
  100922. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  100923. {
  100924. FLAC__ASSERT(0 != encoder);
  100925. FLAC__ASSERT(0 != encoder->private_);
  100926. FLAC__ASSERT(0 != encoder->protected_);
  100927. return encoder->protected_->streamable_subset;
  100928. }
  100929. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  100930. {
  100931. FLAC__ASSERT(0 != encoder);
  100932. FLAC__ASSERT(0 != encoder->private_);
  100933. FLAC__ASSERT(0 != encoder->protected_);
  100934. return encoder->protected_->do_md5;
  100935. }
  100936. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  100937. {
  100938. FLAC__ASSERT(0 != encoder);
  100939. FLAC__ASSERT(0 != encoder->private_);
  100940. FLAC__ASSERT(0 != encoder->protected_);
  100941. return encoder->protected_->channels;
  100942. }
  100943. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  100944. {
  100945. FLAC__ASSERT(0 != encoder);
  100946. FLAC__ASSERT(0 != encoder->private_);
  100947. FLAC__ASSERT(0 != encoder->protected_);
  100948. return encoder->protected_->bits_per_sample;
  100949. }
  100950. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  100951. {
  100952. FLAC__ASSERT(0 != encoder);
  100953. FLAC__ASSERT(0 != encoder->private_);
  100954. FLAC__ASSERT(0 != encoder->protected_);
  100955. return encoder->protected_->sample_rate;
  100956. }
  100957. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  100958. {
  100959. FLAC__ASSERT(0 != encoder);
  100960. FLAC__ASSERT(0 != encoder->private_);
  100961. FLAC__ASSERT(0 != encoder->protected_);
  100962. return encoder->protected_->blocksize;
  100963. }
  100964. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  100965. {
  100966. FLAC__ASSERT(0 != encoder);
  100967. FLAC__ASSERT(0 != encoder->private_);
  100968. FLAC__ASSERT(0 != encoder->protected_);
  100969. return encoder->protected_->do_mid_side_stereo;
  100970. }
  100971. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  100972. {
  100973. FLAC__ASSERT(0 != encoder);
  100974. FLAC__ASSERT(0 != encoder->private_);
  100975. FLAC__ASSERT(0 != encoder->protected_);
  100976. return encoder->protected_->loose_mid_side_stereo;
  100977. }
  100978. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  100979. {
  100980. FLAC__ASSERT(0 != encoder);
  100981. FLAC__ASSERT(0 != encoder->private_);
  100982. FLAC__ASSERT(0 != encoder->protected_);
  100983. return encoder->protected_->max_lpc_order;
  100984. }
  100985. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  100986. {
  100987. FLAC__ASSERT(0 != encoder);
  100988. FLAC__ASSERT(0 != encoder->private_);
  100989. FLAC__ASSERT(0 != encoder->protected_);
  100990. return encoder->protected_->qlp_coeff_precision;
  100991. }
  100992. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  100993. {
  100994. FLAC__ASSERT(0 != encoder);
  100995. FLAC__ASSERT(0 != encoder->private_);
  100996. FLAC__ASSERT(0 != encoder->protected_);
  100997. return encoder->protected_->do_qlp_coeff_prec_search;
  100998. }
  100999. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  101000. {
  101001. FLAC__ASSERT(0 != encoder);
  101002. FLAC__ASSERT(0 != encoder->private_);
  101003. FLAC__ASSERT(0 != encoder->protected_);
  101004. return encoder->protected_->do_escape_coding;
  101005. }
  101006. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  101007. {
  101008. FLAC__ASSERT(0 != encoder);
  101009. FLAC__ASSERT(0 != encoder->private_);
  101010. FLAC__ASSERT(0 != encoder->protected_);
  101011. return encoder->protected_->do_exhaustive_model_search;
  101012. }
  101013. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  101014. {
  101015. FLAC__ASSERT(0 != encoder);
  101016. FLAC__ASSERT(0 != encoder->private_);
  101017. FLAC__ASSERT(0 != encoder->protected_);
  101018. return encoder->protected_->min_residual_partition_order;
  101019. }
  101020. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  101021. {
  101022. FLAC__ASSERT(0 != encoder);
  101023. FLAC__ASSERT(0 != encoder->private_);
  101024. FLAC__ASSERT(0 != encoder->protected_);
  101025. return encoder->protected_->max_residual_partition_order;
  101026. }
  101027. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  101028. {
  101029. FLAC__ASSERT(0 != encoder);
  101030. FLAC__ASSERT(0 != encoder->private_);
  101031. FLAC__ASSERT(0 != encoder->protected_);
  101032. return encoder->protected_->rice_parameter_search_dist;
  101033. }
  101034. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  101035. {
  101036. FLAC__ASSERT(0 != encoder);
  101037. FLAC__ASSERT(0 != encoder->private_);
  101038. FLAC__ASSERT(0 != encoder->protected_);
  101039. return encoder->protected_->total_samples_estimate;
  101040. }
  101041. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  101042. {
  101043. unsigned i, j = 0, channel;
  101044. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  101045. FLAC__ASSERT(0 != encoder);
  101046. FLAC__ASSERT(0 != encoder->private_);
  101047. FLAC__ASSERT(0 != encoder->protected_);
  101048. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  101049. do {
  101050. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  101051. if(encoder->protected_->verify)
  101052. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  101053. for(channel = 0; channel < channels; channel++)
  101054. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  101055. if(encoder->protected_->do_mid_side_stereo) {
  101056. FLAC__ASSERT(channels == 2);
  101057. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  101058. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  101059. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  101060. 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' ! */
  101061. }
  101062. }
  101063. else
  101064. j += n;
  101065. encoder->private_->current_sample_number += n;
  101066. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  101067. if(encoder->private_->current_sample_number > blocksize) {
  101068. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  101069. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  101070. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  101071. return false;
  101072. /* move unprocessed overread samples to beginnings of arrays */
  101073. for(channel = 0; channel < channels; channel++)
  101074. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  101075. if(encoder->protected_->do_mid_side_stereo) {
  101076. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  101077. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  101078. }
  101079. encoder->private_->current_sample_number = 1;
  101080. }
  101081. } while(j < samples);
  101082. return true;
  101083. }
  101084. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  101085. {
  101086. unsigned i, j, k, channel;
  101087. FLAC__int32 x, mid, side;
  101088. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  101089. FLAC__ASSERT(0 != encoder);
  101090. FLAC__ASSERT(0 != encoder->private_);
  101091. FLAC__ASSERT(0 != encoder->protected_);
  101092. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  101093. j = k = 0;
  101094. /*
  101095. * we have several flavors of the same basic loop, optimized for
  101096. * different conditions:
  101097. */
  101098. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  101099. /*
  101100. * stereo coding: unroll channel loop
  101101. */
  101102. do {
  101103. if(encoder->protected_->verify)
  101104. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  101105. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  101106. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  101107. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  101108. x = buffer[k++];
  101109. encoder->private_->integer_signal[1][i] = x;
  101110. mid += x;
  101111. side -= x;
  101112. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  101113. encoder->private_->integer_signal_mid_side[1][i] = side;
  101114. encoder->private_->integer_signal_mid_side[0][i] = mid;
  101115. }
  101116. encoder->private_->current_sample_number = i;
  101117. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  101118. if(i > blocksize) {
  101119. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  101120. return false;
  101121. /* move unprocessed overread samples to beginnings of arrays */
  101122. FLAC__ASSERT(i == blocksize+OVERREAD_);
  101123. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  101124. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  101125. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  101126. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  101127. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  101128. encoder->private_->current_sample_number = 1;
  101129. }
  101130. } while(j < samples);
  101131. }
  101132. else {
  101133. /*
  101134. * independent channel coding: buffer each channel in inner loop
  101135. */
  101136. do {
  101137. if(encoder->protected_->verify)
  101138. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  101139. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  101140. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  101141. for(channel = 0; channel < channels; channel++)
  101142. encoder->private_->integer_signal[channel][i] = buffer[k++];
  101143. }
  101144. encoder->private_->current_sample_number = i;
  101145. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  101146. if(i > blocksize) {
  101147. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  101148. return false;
  101149. /* move unprocessed overread samples to beginnings of arrays */
  101150. FLAC__ASSERT(i == blocksize+OVERREAD_);
  101151. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  101152. for(channel = 0; channel < channels; channel++)
  101153. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  101154. encoder->private_->current_sample_number = 1;
  101155. }
  101156. } while(j < samples);
  101157. }
  101158. return true;
  101159. }
  101160. /***********************************************************************
  101161. *
  101162. * Private class methods
  101163. *
  101164. ***********************************************************************/
  101165. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  101166. {
  101167. FLAC__ASSERT(0 != encoder);
  101168. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  101169. encoder->protected_->verify = true;
  101170. #else
  101171. encoder->protected_->verify = false;
  101172. #endif
  101173. encoder->protected_->streamable_subset = true;
  101174. encoder->protected_->do_md5 = true;
  101175. encoder->protected_->do_mid_side_stereo = false;
  101176. encoder->protected_->loose_mid_side_stereo = false;
  101177. encoder->protected_->channels = 2;
  101178. encoder->protected_->bits_per_sample = 16;
  101179. encoder->protected_->sample_rate = 44100;
  101180. encoder->protected_->blocksize = 0;
  101181. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101182. encoder->protected_->num_apodizations = 1;
  101183. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  101184. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  101185. #endif
  101186. encoder->protected_->max_lpc_order = 0;
  101187. encoder->protected_->qlp_coeff_precision = 0;
  101188. encoder->protected_->do_qlp_coeff_prec_search = false;
  101189. encoder->protected_->do_exhaustive_model_search = false;
  101190. encoder->protected_->do_escape_coding = false;
  101191. encoder->protected_->min_residual_partition_order = 0;
  101192. encoder->protected_->max_residual_partition_order = 0;
  101193. encoder->protected_->rice_parameter_search_dist = 0;
  101194. encoder->protected_->total_samples_estimate = 0;
  101195. encoder->protected_->metadata = 0;
  101196. encoder->protected_->num_metadata_blocks = 0;
  101197. encoder->private_->seek_table = 0;
  101198. encoder->private_->disable_constant_subframes = false;
  101199. encoder->private_->disable_fixed_subframes = false;
  101200. encoder->private_->disable_verbatim_subframes = false;
  101201. #if FLAC__HAS_OGG
  101202. encoder->private_->is_ogg = false;
  101203. #endif
  101204. encoder->private_->read_callback = 0;
  101205. encoder->private_->write_callback = 0;
  101206. encoder->private_->seek_callback = 0;
  101207. encoder->private_->tell_callback = 0;
  101208. encoder->private_->metadata_callback = 0;
  101209. encoder->private_->progress_callback = 0;
  101210. encoder->private_->client_data = 0;
  101211. #if FLAC__HAS_OGG
  101212. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  101213. #endif
  101214. }
  101215. void free_(FLAC__StreamEncoder *encoder)
  101216. {
  101217. unsigned i, channel;
  101218. FLAC__ASSERT(0 != encoder);
  101219. if(encoder->protected_->metadata) {
  101220. free(encoder->protected_->metadata);
  101221. encoder->protected_->metadata = 0;
  101222. encoder->protected_->num_metadata_blocks = 0;
  101223. }
  101224. for(i = 0; i < encoder->protected_->channels; i++) {
  101225. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  101226. free(encoder->private_->integer_signal_unaligned[i]);
  101227. encoder->private_->integer_signal_unaligned[i] = 0;
  101228. }
  101229. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101230. if(0 != encoder->private_->real_signal_unaligned[i]) {
  101231. free(encoder->private_->real_signal_unaligned[i]);
  101232. encoder->private_->real_signal_unaligned[i] = 0;
  101233. }
  101234. #endif
  101235. }
  101236. for(i = 0; i < 2; i++) {
  101237. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  101238. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  101239. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  101240. }
  101241. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101242. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  101243. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  101244. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  101245. }
  101246. #endif
  101247. }
  101248. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101249. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  101250. if(0 != encoder->private_->window_unaligned[i]) {
  101251. free(encoder->private_->window_unaligned[i]);
  101252. encoder->private_->window_unaligned[i] = 0;
  101253. }
  101254. }
  101255. if(0 != encoder->private_->windowed_signal_unaligned) {
  101256. free(encoder->private_->windowed_signal_unaligned);
  101257. encoder->private_->windowed_signal_unaligned = 0;
  101258. }
  101259. #endif
  101260. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  101261. for(i = 0; i < 2; i++) {
  101262. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  101263. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  101264. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  101265. }
  101266. }
  101267. }
  101268. for(channel = 0; channel < 2; channel++) {
  101269. for(i = 0; i < 2; i++) {
  101270. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  101271. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  101272. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  101273. }
  101274. }
  101275. }
  101276. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  101277. free(encoder->private_->abs_residual_partition_sums_unaligned);
  101278. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  101279. }
  101280. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  101281. free(encoder->private_->raw_bits_per_partition_unaligned);
  101282. encoder->private_->raw_bits_per_partition_unaligned = 0;
  101283. }
  101284. if(encoder->protected_->verify) {
  101285. for(i = 0; i < encoder->protected_->channels; i++) {
  101286. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  101287. free(encoder->private_->verify.input_fifo.data[i]);
  101288. encoder->private_->verify.input_fifo.data[i] = 0;
  101289. }
  101290. }
  101291. }
  101292. FLAC__bitwriter_free(encoder->private_->frame);
  101293. }
  101294. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  101295. {
  101296. FLAC__bool ok;
  101297. unsigned i, channel;
  101298. FLAC__ASSERT(new_blocksize > 0);
  101299. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  101300. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  101301. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  101302. if(new_blocksize <= encoder->private_->input_capacity)
  101303. return true;
  101304. ok = true;
  101305. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  101306. * requires that the input arrays (in our case the integer signals)
  101307. * have a buffer of up to 3 zeroes in front (at negative indices) for
  101308. * alignment purposes; we use 4 in front to keep the data well-aligned.
  101309. */
  101310. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  101311. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  101312. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  101313. encoder->private_->integer_signal[i] += 4;
  101314. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101315. #if 0 /* @@@ currently unused */
  101316. if(encoder->protected_->max_lpc_order > 0)
  101317. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  101318. #endif
  101319. #endif
  101320. }
  101321. for(i = 0; ok && i < 2; i++) {
  101322. 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]);
  101323. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  101324. encoder->private_->integer_signal_mid_side[i] += 4;
  101325. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101326. #if 0 /* @@@ currently unused */
  101327. if(encoder->protected_->max_lpc_order > 0)
  101328. 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]);
  101329. #endif
  101330. #endif
  101331. }
  101332. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101333. if(ok && encoder->protected_->max_lpc_order > 0) {
  101334. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  101335. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  101336. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  101337. }
  101338. #endif
  101339. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  101340. for(i = 0; ok && i < 2; i++) {
  101341. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  101342. }
  101343. }
  101344. for(channel = 0; ok && channel < 2; channel++) {
  101345. for(i = 0; ok && i < 2; i++) {
  101346. 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]);
  101347. }
  101348. }
  101349. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  101350. /*@@@ 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) */
  101351. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  101352. if(encoder->protected_->do_escape_coding)
  101353. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  101354. /* now adjust the windows if the blocksize has changed */
  101355. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101356. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  101357. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  101358. switch(encoder->protected_->apodizations[i].type) {
  101359. case FLAC__APODIZATION_BARTLETT:
  101360. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  101361. break;
  101362. case FLAC__APODIZATION_BARTLETT_HANN:
  101363. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  101364. break;
  101365. case FLAC__APODIZATION_BLACKMAN:
  101366. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  101367. break;
  101368. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  101369. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  101370. break;
  101371. case FLAC__APODIZATION_CONNES:
  101372. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  101373. break;
  101374. case FLAC__APODIZATION_FLATTOP:
  101375. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  101376. break;
  101377. case FLAC__APODIZATION_GAUSS:
  101378. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  101379. break;
  101380. case FLAC__APODIZATION_HAMMING:
  101381. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  101382. break;
  101383. case FLAC__APODIZATION_HANN:
  101384. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  101385. break;
  101386. case FLAC__APODIZATION_KAISER_BESSEL:
  101387. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  101388. break;
  101389. case FLAC__APODIZATION_NUTTALL:
  101390. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  101391. break;
  101392. case FLAC__APODIZATION_RECTANGLE:
  101393. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  101394. break;
  101395. case FLAC__APODIZATION_TRIANGLE:
  101396. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  101397. break;
  101398. case FLAC__APODIZATION_TUKEY:
  101399. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  101400. break;
  101401. case FLAC__APODIZATION_WELCH:
  101402. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  101403. break;
  101404. default:
  101405. FLAC__ASSERT(0);
  101406. /* double protection */
  101407. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  101408. break;
  101409. }
  101410. }
  101411. }
  101412. #endif
  101413. if(ok)
  101414. encoder->private_->input_capacity = new_blocksize;
  101415. else
  101416. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  101417. return ok;
  101418. }
  101419. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  101420. {
  101421. const FLAC__byte *buffer;
  101422. size_t bytes;
  101423. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  101424. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  101425. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  101426. return false;
  101427. }
  101428. if(encoder->protected_->verify) {
  101429. encoder->private_->verify.output.data = buffer;
  101430. encoder->private_->verify.output.bytes = bytes;
  101431. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  101432. encoder->private_->verify.needs_magic_hack = true;
  101433. }
  101434. else {
  101435. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  101436. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  101437. FLAC__bitwriter_clear(encoder->private_->frame);
  101438. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  101439. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  101440. return false;
  101441. }
  101442. }
  101443. }
  101444. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  101445. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  101446. FLAC__bitwriter_clear(encoder->private_->frame);
  101447. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101448. return false;
  101449. }
  101450. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  101451. FLAC__bitwriter_clear(encoder->private_->frame);
  101452. if(samples > 0) {
  101453. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  101454. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  101455. }
  101456. return true;
  101457. }
  101458. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  101459. {
  101460. FLAC__StreamEncoderWriteStatus status;
  101461. FLAC__uint64 output_position = 0;
  101462. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  101463. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  101464. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101465. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  101466. }
  101467. /*
  101468. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  101469. */
  101470. if(samples == 0) {
  101471. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  101472. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  101473. encoder->protected_->streaminfo_offset = output_position;
  101474. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  101475. encoder->protected_->seektable_offset = output_position;
  101476. }
  101477. /*
  101478. * Mark the current seek point if hit (if audio_offset == 0 that
  101479. * means we're still writing metadata and haven't hit the first
  101480. * frame yet)
  101481. */
  101482. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  101483. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  101484. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  101485. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  101486. FLAC__uint64 test_sample;
  101487. unsigned i;
  101488. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  101489. test_sample = encoder->private_->seek_table->points[i].sample_number;
  101490. if(test_sample > frame_last_sample) {
  101491. break;
  101492. }
  101493. else if(test_sample >= frame_first_sample) {
  101494. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  101495. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  101496. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  101497. encoder->private_->first_seekpoint_to_check++;
  101498. /* DO NOT: "break;" and here's why:
  101499. * The seektable template may contain more than one target
  101500. * sample for any given frame; we will keep looping, generating
  101501. * duplicate seekpoints for them, and we'll clean it up later,
  101502. * just before writing the seektable back to the metadata.
  101503. */
  101504. }
  101505. else {
  101506. encoder->private_->first_seekpoint_to_check++;
  101507. }
  101508. }
  101509. }
  101510. #if FLAC__HAS_OGG
  101511. if(encoder->private_->is_ogg) {
  101512. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  101513. &encoder->protected_->ogg_encoder_aspect,
  101514. buffer,
  101515. bytes,
  101516. samples,
  101517. encoder->private_->current_frame_number,
  101518. is_last_block,
  101519. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  101520. encoder,
  101521. encoder->private_->client_data
  101522. );
  101523. }
  101524. else
  101525. #endif
  101526. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  101527. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  101528. encoder->private_->bytes_written += bytes;
  101529. encoder->private_->samples_written += samples;
  101530. /* we keep a high watermark on the number of frames written because
  101531. * when the encoder goes back to write metadata, 'current_frame'
  101532. * will drop back to 0.
  101533. */
  101534. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  101535. }
  101536. else
  101537. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101538. return status;
  101539. }
  101540. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  101541. void update_metadata_(const FLAC__StreamEncoder *encoder)
  101542. {
  101543. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  101544. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  101545. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  101546. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  101547. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  101548. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  101549. FLAC__StreamEncoderSeekStatus seek_status;
  101550. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  101551. /* All this is based on intimate knowledge of the stream header
  101552. * layout, but a change to the header format that would break this
  101553. * would also break all streams encoded in the previous format.
  101554. */
  101555. /*
  101556. * Write MD5 signature
  101557. */
  101558. {
  101559. const unsigned md5_offset =
  101560. FLAC__STREAM_METADATA_HEADER_LENGTH +
  101561. (
  101562. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  101563. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  101564. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  101565. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  101566. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  101567. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  101568. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  101569. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  101570. ) / 8;
  101571. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  101572. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  101573. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101574. return;
  101575. }
  101576. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  101577. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101578. return;
  101579. }
  101580. }
  101581. /*
  101582. * Write total samples
  101583. */
  101584. {
  101585. const unsigned total_samples_byte_offset =
  101586. FLAC__STREAM_METADATA_HEADER_LENGTH +
  101587. (
  101588. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  101589. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  101590. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  101591. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  101592. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  101593. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  101594. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  101595. - 4
  101596. ) / 8;
  101597. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  101598. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  101599. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  101600. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  101601. b[4] = (FLAC__byte)(samples & 0xFF);
  101602. 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) {
  101603. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  101604. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101605. return;
  101606. }
  101607. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  101608. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101609. return;
  101610. }
  101611. }
  101612. /*
  101613. * Write min/max framesize
  101614. */
  101615. {
  101616. const unsigned min_framesize_offset =
  101617. FLAC__STREAM_METADATA_HEADER_LENGTH +
  101618. (
  101619. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  101620. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  101621. ) / 8;
  101622. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  101623. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  101624. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  101625. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  101626. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  101627. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  101628. 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) {
  101629. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  101630. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101631. return;
  101632. }
  101633. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  101634. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101635. return;
  101636. }
  101637. }
  101638. /*
  101639. * Write seektable
  101640. */
  101641. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  101642. unsigned i;
  101643. FLAC__format_seektable_sort(encoder->private_->seek_table);
  101644. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  101645. 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) {
  101646. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  101647. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101648. return;
  101649. }
  101650. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  101651. FLAC__uint64 xx;
  101652. unsigned x;
  101653. xx = encoder->private_->seek_table->points[i].sample_number;
  101654. b[7] = (FLAC__byte)xx; xx >>= 8;
  101655. b[6] = (FLAC__byte)xx; xx >>= 8;
  101656. b[5] = (FLAC__byte)xx; xx >>= 8;
  101657. b[4] = (FLAC__byte)xx; xx >>= 8;
  101658. b[3] = (FLAC__byte)xx; xx >>= 8;
  101659. b[2] = (FLAC__byte)xx; xx >>= 8;
  101660. b[1] = (FLAC__byte)xx; xx >>= 8;
  101661. b[0] = (FLAC__byte)xx; xx >>= 8;
  101662. xx = encoder->private_->seek_table->points[i].stream_offset;
  101663. b[15] = (FLAC__byte)xx; xx >>= 8;
  101664. b[14] = (FLAC__byte)xx; xx >>= 8;
  101665. b[13] = (FLAC__byte)xx; xx >>= 8;
  101666. b[12] = (FLAC__byte)xx; xx >>= 8;
  101667. b[11] = (FLAC__byte)xx; xx >>= 8;
  101668. b[10] = (FLAC__byte)xx; xx >>= 8;
  101669. b[9] = (FLAC__byte)xx; xx >>= 8;
  101670. b[8] = (FLAC__byte)xx; xx >>= 8;
  101671. x = encoder->private_->seek_table->points[i].frame_samples;
  101672. b[17] = (FLAC__byte)x; x >>= 8;
  101673. b[16] = (FLAC__byte)x; x >>= 8;
  101674. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  101675. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101676. return;
  101677. }
  101678. }
  101679. }
  101680. }
  101681. #if FLAC__HAS_OGG
  101682. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  101683. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  101684. {
  101685. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  101686. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  101687. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  101688. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  101689. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  101690. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  101691. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  101692. FLAC__STREAM_SYNC_LENGTH
  101693. ;
  101694. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  101695. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  101696. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  101697. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  101698. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  101699. ogg_page page;
  101700. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  101701. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  101702. /* Pre-check that client supports seeking, since we don't want the
  101703. * ogg_helper code to ever have to deal with this condition.
  101704. */
  101705. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  101706. return;
  101707. /* All this is based on intimate knowledge of the stream header
  101708. * layout, but a change to the header format that would break this
  101709. * would also break all streams encoded in the previous format.
  101710. */
  101711. /**
  101712. ** Write STREAMINFO stats
  101713. **/
  101714. simple_ogg_page__init(&page);
  101715. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  101716. simple_ogg_page__clear(&page);
  101717. return; /* state already set */
  101718. }
  101719. /*
  101720. * Write MD5 signature
  101721. */
  101722. {
  101723. const unsigned md5_offset =
  101724. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  101725. FLAC__STREAM_METADATA_HEADER_LENGTH +
  101726. (
  101727. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  101728. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  101729. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  101730. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  101731. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  101732. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  101733. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  101734. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  101735. ) / 8;
  101736. if(md5_offset + 16 > (unsigned)page.body_len) {
  101737. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  101738. simple_ogg_page__clear(&page);
  101739. return;
  101740. }
  101741. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  101742. }
  101743. /*
  101744. * Write total samples
  101745. */
  101746. {
  101747. const unsigned total_samples_byte_offset =
  101748. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  101749. FLAC__STREAM_METADATA_HEADER_LENGTH +
  101750. (
  101751. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  101752. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  101753. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  101754. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  101755. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  101756. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  101757. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  101758. - 4
  101759. ) / 8;
  101760. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  101761. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  101762. simple_ogg_page__clear(&page);
  101763. return;
  101764. }
  101765. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  101766. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  101767. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  101768. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  101769. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  101770. b[4] = (FLAC__byte)(samples & 0xFF);
  101771. memcpy(page.body + total_samples_byte_offset, b, 5);
  101772. }
  101773. /*
  101774. * Write min/max framesize
  101775. */
  101776. {
  101777. const unsigned min_framesize_offset =
  101778. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  101779. FLAC__STREAM_METADATA_HEADER_LENGTH +
  101780. (
  101781. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  101782. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  101783. ) / 8;
  101784. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  101785. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  101786. simple_ogg_page__clear(&page);
  101787. return;
  101788. }
  101789. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  101790. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  101791. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  101792. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  101793. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  101794. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  101795. memcpy(page.body + min_framesize_offset, b, 6);
  101796. }
  101797. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  101798. simple_ogg_page__clear(&page);
  101799. return; /* state already set */
  101800. }
  101801. simple_ogg_page__clear(&page);
  101802. /*
  101803. * Write seektable
  101804. */
  101805. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  101806. unsigned i;
  101807. FLAC__byte *p;
  101808. FLAC__format_seektable_sort(encoder->private_->seek_table);
  101809. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  101810. simple_ogg_page__init(&page);
  101811. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  101812. simple_ogg_page__clear(&page);
  101813. return; /* state already set */
  101814. }
  101815. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  101816. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  101817. simple_ogg_page__clear(&page);
  101818. return;
  101819. }
  101820. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  101821. FLAC__uint64 xx;
  101822. unsigned x;
  101823. xx = encoder->private_->seek_table->points[i].sample_number;
  101824. b[7] = (FLAC__byte)xx; xx >>= 8;
  101825. b[6] = (FLAC__byte)xx; xx >>= 8;
  101826. b[5] = (FLAC__byte)xx; xx >>= 8;
  101827. b[4] = (FLAC__byte)xx; xx >>= 8;
  101828. b[3] = (FLAC__byte)xx; xx >>= 8;
  101829. b[2] = (FLAC__byte)xx; xx >>= 8;
  101830. b[1] = (FLAC__byte)xx; xx >>= 8;
  101831. b[0] = (FLAC__byte)xx; xx >>= 8;
  101832. xx = encoder->private_->seek_table->points[i].stream_offset;
  101833. b[15] = (FLAC__byte)xx; xx >>= 8;
  101834. b[14] = (FLAC__byte)xx; xx >>= 8;
  101835. b[13] = (FLAC__byte)xx; xx >>= 8;
  101836. b[12] = (FLAC__byte)xx; xx >>= 8;
  101837. b[11] = (FLAC__byte)xx; xx >>= 8;
  101838. b[10] = (FLAC__byte)xx; xx >>= 8;
  101839. b[9] = (FLAC__byte)xx; xx >>= 8;
  101840. b[8] = (FLAC__byte)xx; xx >>= 8;
  101841. x = encoder->private_->seek_table->points[i].frame_samples;
  101842. b[17] = (FLAC__byte)x; x >>= 8;
  101843. b[16] = (FLAC__byte)x; x >>= 8;
  101844. memcpy(p, b, 18);
  101845. }
  101846. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  101847. simple_ogg_page__clear(&page);
  101848. return; /* state already set */
  101849. }
  101850. simple_ogg_page__clear(&page);
  101851. }
  101852. }
  101853. #endif
  101854. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  101855. {
  101856. FLAC__uint16 crc;
  101857. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  101858. /*
  101859. * Accumulate raw signal to the MD5 signature
  101860. */
  101861. 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)) {
  101862. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  101863. return false;
  101864. }
  101865. /*
  101866. * Process the frame header and subframes into the frame bitbuffer
  101867. */
  101868. if(!process_subframes_(encoder, is_fractional_block)) {
  101869. /* the above function sets the state for us in case of an error */
  101870. return false;
  101871. }
  101872. /*
  101873. * Zero-pad the frame to a byte_boundary
  101874. */
  101875. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  101876. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  101877. return false;
  101878. }
  101879. /*
  101880. * CRC-16 the whole thing
  101881. */
  101882. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  101883. if(
  101884. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  101885. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  101886. ) {
  101887. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  101888. return false;
  101889. }
  101890. /*
  101891. * Write it
  101892. */
  101893. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  101894. /* the above function sets the state for us in case of an error */
  101895. return false;
  101896. }
  101897. /*
  101898. * Get ready for the next frame
  101899. */
  101900. encoder->private_->current_sample_number = 0;
  101901. encoder->private_->current_frame_number++;
  101902. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  101903. return true;
  101904. }
  101905. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  101906. {
  101907. FLAC__FrameHeader frame_header;
  101908. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  101909. FLAC__bool do_independent, do_mid_side;
  101910. /*
  101911. * Calculate the min,max Rice partition orders
  101912. */
  101913. if(is_fractional_block) {
  101914. max_partition_order = 0;
  101915. }
  101916. else {
  101917. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  101918. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  101919. }
  101920. min_partition_order = min(min_partition_order, max_partition_order);
  101921. /*
  101922. * Setup the frame
  101923. */
  101924. frame_header.blocksize = encoder->protected_->blocksize;
  101925. frame_header.sample_rate = encoder->protected_->sample_rate;
  101926. frame_header.channels = encoder->protected_->channels;
  101927. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  101928. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  101929. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  101930. frame_header.number.frame_number = encoder->private_->current_frame_number;
  101931. /*
  101932. * Figure out what channel assignments to try
  101933. */
  101934. if(encoder->protected_->do_mid_side_stereo) {
  101935. if(encoder->protected_->loose_mid_side_stereo) {
  101936. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  101937. do_independent = true;
  101938. do_mid_side = true;
  101939. }
  101940. else {
  101941. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  101942. do_mid_side = !do_independent;
  101943. }
  101944. }
  101945. else {
  101946. do_independent = true;
  101947. do_mid_side = true;
  101948. }
  101949. }
  101950. else {
  101951. do_independent = true;
  101952. do_mid_side = false;
  101953. }
  101954. FLAC__ASSERT(do_independent || do_mid_side);
  101955. /*
  101956. * Check for wasted bits; set effective bps for each subframe
  101957. */
  101958. if(do_independent) {
  101959. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  101960. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  101961. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  101962. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  101963. }
  101964. }
  101965. if(do_mid_side) {
  101966. FLAC__ASSERT(encoder->protected_->channels == 2);
  101967. for(channel = 0; channel < 2; channel++) {
  101968. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  101969. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  101970. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  101971. }
  101972. }
  101973. /*
  101974. * First do a normal encoding pass of each independent channel
  101975. */
  101976. if(do_independent) {
  101977. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  101978. if(!
  101979. process_subframe_(
  101980. encoder,
  101981. min_partition_order,
  101982. max_partition_order,
  101983. &frame_header,
  101984. encoder->private_->subframe_bps[channel],
  101985. encoder->private_->integer_signal[channel],
  101986. encoder->private_->subframe_workspace_ptr[channel],
  101987. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  101988. encoder->private_->residual_workspace[channel],
  101989. encoder->private_->best_subframe+channel,
  101990. encoder->private_->best_subframe_bits+channel
  101991. )
  101992. )
  101993. return false;
  101994. }
  101995. }
  101996. /*
  101997. * Now do mid and side channels if requested
  101998. */
  101999. if(do_mid_side) {
  102000. FLAC__ASSERT(encoder->protected_->channels == 2);
  102001. for(channel = 0; channel < 2; channel++) {
  102002. if(!
  102003. process_subframe_(
  102004. encoder,
  102005. min_partition_order,
  102006. max_partition_order,
  102007. &frame_header,
  102008. encoder->private_->subframe_bps_mid_side[channel],
  102009. encoder->private_->integer_signal_mid_side[channel],
  102010. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  102011. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  102012. encoder->private_->residual_workspace_mid_side[channel],
  102013. encoder->private_->best_subframe_mid_side+channel,
  102014. encoder->private_->best_subframe_bits_mid_side+channel
  102015. )
  102016. )
  102017. return false;
  102018. }
  102019. }
  102020. /*
  102021. * Compose the frame bitbuffer
  102022. */
  102023. if(do_mid_side) {
  102024. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  102025. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  102026. FLAC__ChannelAssignment channel_assignment;
  102027. FLAC__ASSERT(encoder->protected_->channels == 2);
  102028. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  102029. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  102030. }
  102031. else {
  102032. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  102033. unsigned min_bits;
  102034. int ca;
  102035. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  102036. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  102037. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  102038. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  102039. FLAC__ASSERT(do_independent && do_mid_side);
  102040. /* We have to figure out which channel assignent results in the smallest frame */
  102041. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  102042. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  102043. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  102044. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  102045. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  102046. min_bits = bits[channel_assignment];
  102047. for(ca = 1; ca <= 3; ca++) {
  102048. if(bits[ca] < min_bits) {
  102049. min_bits = bits[ca];
  102050. channel_assignment = (FLAC__ChannelAssignment)ca;
  102051. }
  102052. }
  102053. }
  102054. frame_header.channel_assignment = channel_assignment;
  102055. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  102056. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102057. return false;
  102058. }
  102059. switch(channel_assignment) {
  102060. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  102061. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  102062. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  102063. break;
  102064. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  102065. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  102066. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  102067. break;
  102068. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  102069. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  102070. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  102071. break;
  102072. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  102073. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  102074. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  102075. break;
  102076. default:
  102077. FLAC__ASSERT(0);
  102078. }
  102079. switch(channel_assignment) {
  102080. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  102081. left_bps = encoder->private_->subframe_bps [0];
  102082. right_bps = encoder->private_->subframe_bps [1];
  102083. break;
  102084. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  102085. left_bps = encoder->private_->subframe_bps [0];
  102086. right_bps = encoder->private_->subframe_bps_mid_side[1];
  102087. break;
  102088. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  102089. left_bps = encoder->private_->subframe_bps_mid_side[1];
  102090. right_bps = encoder->private_->subframe_bps [1];
  102091. break;
  102092. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  102093. left_bps = encoder->private_->subframe_bps_mid_side[0];
  102094. right_bps = encoder->private_->subframe_bps_mid_side[1];
  102095. break;
  102096. default:
  102097. FLAC__ASSERT(0);
  102098. }
  102099. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  102100. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  102101. return false;
  102102. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  102103. return false;
  102104. }
  102105. else {
  102106. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  102107. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102108. return false;
  102109. }
  102110. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  102111. 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)) {
  102112. /* the above function sets the state for us in case of an error */
  102113. return false;
  102114. }
  102115. }
  102116. }
  102117. if(encoder->protected_->loose_mid_side_stereo) {
  102118. encoder->private_->loose_mid_side_stereo_frame_count++;
  102119. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  102120. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  102121. }
  102122. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  102123. return true;
  102124. }
  102125. FLAC__bool process_subframe_(
  102126. FLAC__StreamEncoder *encoder,
  102127. unsigned min_partition_order,
  102128. unsigned max_partition_order,
  102129. const FLAC__FrameHeader *frame_header,
  102130. unsigned subframe_bps,
  102131. const FLAC__int32 integer_signal[],
  102132. FLAC__Subframe *subframe[2],
  102133. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  102134. FLAC__int32 *residual[2],
  102135. unsigned *best_subframe,
  102136. unsigned *best_bits
  102137. )
  102138. {
  102139. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102140. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  102141. #else
  102142. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  102143. #endif
  102144. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102145. FLAC__double lpc_residual_bits_per_sample;
  102146. 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 */
  102147. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  102148. unsigned min_lpc_order, max_lpc_order, lpc_order;
  102149. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  102150. #endif
  102151. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  102152. unsigned rice_parameter;
  102153. unsigned _candidate_bits, _best_bits;
  102154. unsigned _best_subframe;
  102155. /* only use RICE2 partitions if stream bps > 16 */
  102156. 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;
  102157. FLAC__ASSERT(frame_header->blocksize > 0);
  102158. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  102159. _best_subframe = 0;
  102160. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  102161. _best_bits = UINT_MAX;
  102162. else
  102163. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  102164. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  102165. unsigned signal_is_constant = false;
  102166. 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);
  102167. /* check for constant subframe */
  102168. if(
  102169. !encoder->private_->disable_constant_subframes &&
  102170. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102171. fixed_residual_bits_per_sample[1] == 0.0
  102172. #else
  102173. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  102174. #endif
  102175. ) {
  102176. /* the above means it's possible all samples are the same value; now double-check it: */
  102177. unsigned i;
  102178. signal_is_constant = true;
  102179. for(i = 1; i < frame_header->blocksize; i++) {
  102180. if(integer_signal[0] != integer_signal[i]) {
  102181. signal_is_constant = false;
  102182. break;
  102183. }
  102184. }
  102185. }
  102186. if(signal_is_constant) {
  102187. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  102188. if(_candidate_bits < _best_bits) {
  102189. _best_subframe = !_best_subframe;
  102190. _best_bits = _candidate_bits;
  102191. }
  102192. }
  102193. else {
  102194. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  102195. /* encode fixed */
  102196. if(encoder->protected_->do_exhaustive_model_search) {
  102197. min_fixed_order = 0;
  102198. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  102199. }
  102200. else {
  102201. min_fixed_order = max_fixed_order = guess_fixed_order;
  102202. }
  102203. if(max_fixed_order >= frame_header->blocksize)
  102204. max_fixed_order = frame_header->blocksize - 1;
  102205. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  102206. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102207. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  102208. continue; /* don't even try */
  102209. 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 */
  102210. #else
  102211. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  102212. continue; /* don't even try */
  102213. 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 */
  102214. #endif
  102215. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  102216. if(rice_parameter >= rice_parameter_limit) {
  102217. #ifdef DEBUG_VERBOSE
  102218. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  102219. #endif
  102220. rice_parameter = rice_parameter_limit - 1;
  102221. }
  102222. _candidate_bits =
  102223. evaluate_fixed_subframe_(
  102224. encoder,
  102225. integer_signal,
  102226. residual[!_best_subframe],
  102227. encoder->private_->abs_residual_partition_sums,
  102228. encoder->private_->raw_bits_per_partition,
  102229. frame_header->blocksize,
  102230. subframe_bps,
  102231. fixed_order,
  102232. rice_parameter,
  102233. rice_parameter_limit,
  102234. min_partition_order,
  102235. max_partition_order,
  102236. encoder->protected_->do_escape_coding,
  102237. encoder->protected_->rice_parameter_search_dist,
  102238. subframe[!_best_subframe],
  102239. partitioned_rice_contents[!_best_subframe]
  102240. );
  102241. if(_candidate_bits < _best_bits) {
  102242. _best_subframe = !_best_subframe;
  102243. _best_bits = _candidate_bits;
  102244. }
  102245. }
  102246. }
  102247. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102248. /* encode lpc */
  102249. if(encoder->protected_->max_lpc_order > 0) {
  102250. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  102251. max_lpc_order = frame_header->blocksize-1;
  102252. else
  102253. max_lpc_order = encoder->protected_->max_lpc_order;
  102254. if(max_lpc_order > 0) {
  102255. unsigned a;
  102256. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  102257. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  102258. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  102259. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  102260. if(autoc[0] != 0.0) {
  102261. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  102262. if(encoder->protected_->do_exhaustive_model_search) {
  102263. min_lpc_order = 1;
  102264. }
  102265. else {
  102266. const unsigned guess_lpc_order =
  102267. FLAC__lpc_compute_best_order(
  102268. lpc_error,
  102269. max_lpc_order,
  102270. frame_header->blocksize,
  102271. subframe_bps + (
  102272. encoder->protected_->do_qlp_coeff_prec_search?
  102273. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  102274. encoder->protected_->qlp_coeff_precision
  102275. )
  102276. );
  102277. min_lpc_order = max_lpc_order = guess_lpc_order;
  102278. }
  102279. if(max_lpc_order >= frame_header->blocksize)
  102280. max_lpc_order = frame_header->blocksize - 1;
  102281. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  102282. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  102283. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  102284. continue; /* don't even try */
  102285. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  102286. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  102287. if(rice_parameter >= rice_parameter_limit) {
  102288. #ifdef DEBUG_VERBOSE
  102289. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  102290. #endif
  102291. rice_parameter = rice_parameter_limit - 1;
  102292. }
  102293. if(encoder->protected_->do_qlp_coeff_prec_search) {
  102294. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  102295. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  102296. if(subframe_bps <= 17) {
  102297. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  102298. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  102299. }
  102300. else
  102301. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  102302. }
  102303. else {
  102304. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  102305. }
  102306. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  102307. _candidate_bits =
  102308. evaluate_lpc_subframe_(
  102309. encoder,
  102310. integer_signal,
  102311. residual[!_best_subframe],
  102312. encoder->private_->abs_residual_partition_sums,
  102313. encoder->private_->raw_bits_per_partition,
  102314. encoder->private_->lp_coeff[lpc_order-1],
  102315. frame_header->blocksize,
  102316. subframe_bps,
  102317. lpc_order,
  102318. qlp_coeff_precision,
  102319. rice_parameter,
  102320. rice_parameter_limit,
  102321. min_partition_order,
  102322. max_partition_order,
  102323. encoder->protected_->do_escape_coding,
  102324. encoder->protected_->rice_parameter_search_dist,
  102325. subframe[!_best_subframe],
  102326. partitioned_rice_contents[!_best_subframe]
  102327. );
  102328. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  102329. if(_candidate_bits < _best_bits) {
  102330. _best_subframe = !_best_subframe;
  102331. _best_bits = _candidate_bits;
  102332. }
  102333. }
  102334. }
  102335. }
  102336. }
  102337. }
  102338. }
  102339. }
  102340. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  102341. }
  102342. }
  102343. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  102344. if(_best_bits == UINT_MAX) {
  102345. FLAC__ASSERT(_best_subframe == 0);
  102346. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  102347. }
  102348. *best_subframe = _best_subframe;
  102349. *best_bits = _best_bits;
  102350. return true;
  102351. }
  102352. FLAC__bool add_subframe_(
  102353. FLAC__StreamEncoder *encoder,
  102354. unsigned blocksize,
  102355. unsigned subframe_bps,
  102356. const FLAC__Subframe *subframe,
  102357. FLAC__BitWriter *frame
  102358. )
  102359. {
  102360. switch(subframe->type) {
  102361. case FLAC__SUBFRAME_TYPE_CONSTANT:
  102362. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  102363. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102364. return false;
  102365. }
  102366. break;
  102367. case FLAC__SUBFRAME_TYPE_FIXED:
  102368. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  102369. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102370. return false;
  102371. }
  102372. break;
  102373. case FLAC__SUBFRAME_TYPE_LPC:
  102374. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  102375. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102376. return false;
  102377. }
  102378. break;
  102379. case FLAC__SUBFRAME_TYPE_VERBATIM:
  102380. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  102381. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102382. return false;
  102383. }
  102384. break;
  102385. default:
  102386. FLAC__ASSERT(0);
  102387. }
  102388. return true;
  102389. }
  102390. #define SPOTCHECK_ESTIMATE 0
  102391. #if SPOTCHECK_ESTIMATE
  102392. static void spotcheck_subframe_estimate_(
  102393. FLAC__StreamEncoder *encoder,
  102394. unsigned blocksize,
  102395. unsigned subframe_bps,
  102396. const FLAC__Subframe *subframe,
  102397. unsigned estimate
  102398. )
  102399. {
  102400. FLAC__bool ret;
  102401. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  102402. if(frame == 0) {
  102403. fprintf(stderr, "EST: can't allocate frame\n");
  102404. return;
  102405. }
  102406. if(!FLAC__bitwriter_init(frame)) {
  102407. fprintf(stderr, "EST: can't init frame\n");
  102408. return;
  102409. }
  102410. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  102411. FLAC__ASSERT(ret);
  102412. {
  102413. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  102414. if(estimate != actual)
  102415. 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);
  102416. }
  102417. FLAC__bitwriter_delete(frame);
  102418. }
  102419. #endif
  102420. unsigned evaluate_constant_subframe_(
  102421. FLAC__StreamEncoder *encoder,
  102422. const FLAC__int32 signal,
  102423. unsigned blocksize,
  102424. unsigned subframe_bps,
  102425. FLAC__Subframe *subframe
  102426. )
  102427. {
  102428. unsigned estimate;
  102429. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  102430. subframe->data.constant.value = signal;
  102431. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  102432. #if SPOTCHECK_ESTIMATE
  102433. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  102434. #else
  102435. (void)encoder, (void)blocksize;
  102436. #endif
  102437. return estimate;
  102438. }
  102439. unsigned evaluate_fixed_subframe_(
  102440. FLAC__StreamEncoder *encoder,
  102441. const FLAC__int32 signal[],
  102442. FLAC__int32 residual[],
  102443. FLAC__uint64 abs_residual_partition_sums[],
  102444. unsigned raw_bits_per_partition[],
  102445. unsigned blocksize,
  102446. unsigned subframe_bps,
  102447. unsigned order,
  102448. unsigned rice_parameter,
  102449. unsigned rice_parameter_limit,
  102450. unsigned min_partition_order,
  102451. unsigned max_partition_order,
  102452. FLAC__bool do_escape_coding,
  102453. unsigned rice_parameter_search_dist,
  102454. FLAC__Subframe *subframe,
  102455. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102456. )
  102457. {
  102458. unsigned i, residual_bits, estimate;
  102459. const unsigned residual_samples = blocksize - order;
  102460. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  102461. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  102462. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  102463. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  102464. subframe->data.fixed.residual = residual;
  102465. residual_bits =
  102466. find_best_partition_order_(
  102467. encoder->private_,
  102468. residual,
  102469. abs_residual_partition_sums,
  102470. raw_bits_per_partition,
  102471. residual_samples,
  102472. order,
  102473. rice_parameter,
  102474. rice_parameter_limit,
  102475. min_partition_order,
  102476. max_partition_order,
  102477. subframe_bps,
  102478. do_escape_coding,
  102479. rice_parameter_search_dist,
  102480. &subframe->data.fixed.entropy_coding_method
  102481. );
  102482. subframe->data.fixed.order = order;
  102483. for(i = 0; i < order; i++)
  102484. subframe->data.fixed.warmup[i] = signal[i];
  102485. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  102486. #if SPOTCHECK_ESTIMATE
  102487. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  102488. #endif
  102489. return estimate;
  102490. }
  102491. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102492. unsigned evaluate_lpc_subframe_(
  102493. FLAC__StreamEncoder *encoder,
  102494. const FLAC__int32 signal[],
  102495. FLAC__int32 residual[],
  102496. FLAC__uint64 abs_residual_partition_sums[],
  102497. unsigned raw_bits_per_partition[],
  102498. const FLAC__real lp_coeff[],
  102499. unsigned blocksize,
  102500. unsigned subframe_bps,
  102501. unsigned order,
  102502. unsigned qlp_coeff_precision,
  102503. unsigned rice_parameter,
  102504. unsigned rice_parameter_limit,
  102505. unsigned min_partition_order,
  102506. unsigned max_partition_order,
  102507. FLAC__bool do_escape_coding,
  102508. unsigned rice_parameter_search_dist,
  102509. FLAC__Subframe *subframe,
  102510. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102511. )
  102512. {
  102513. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  102514. unsigned i, residual_bits, estimate;
  102515. int quantization, ret;
  102516. const unsigned residual_samples = blocksize - order;
  102517. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  102518. if(subframe_bps <= 16) {
  102519. FLAC__ASSERT(order > 0);
  102520. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  102521. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  102522. }
  102523. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  102524. if(ret != 0)
  102525. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  102526. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  102527. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  102528. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  102529. else
  102530. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  102531. else
  102532. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  102533. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  102534. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  102535. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  102536. subframe->data.lpc.residual = residual;
  102537. residual_bits =
  102538. find_best_partition_order_(
  102539. encoder->private_,
  102540. residual,
  102541. abs_residual_partition_sums,
  102542. raw_bits_per_partition,
  102543. residual_samples,
  102544. order,
  102545. rice_parameter,
  102546. rice_parameter_limit,
  102547. min_partition_order,
  102548. max_partition_order,
  102549. subframe_bps,
  102550. do_escape_coding,
  102551. rice_parameter_search_dist,
  102552. &subframe->data.lpc.entropy_coding_method
  102553. );
  102554. subframe->data.lpc.order = order;
  102555. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  102556. subframe->data.lpc.quantization_level = quantization;
  102557. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  102558. for(i = 0; i < order; i++)
  102559. subframe->data.lpc.warmup[i] = signal[i];
  102560. 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;
  102561. #if SPOTCHECK_ESTIMATE
  102562. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  102563. #endif
  102564. return estimate;
  102565. }
  102566. #endif
  102567. unsigned evaluate_verbatim_subframe_(
  102568. FLAC__StreamEncoder *encoder,
  102569. const FLAC__int32 signal[],
  102570. unsigned blocksize,
  102571. unsigned subframe_bps,
  102572. FLAC__Subframe *subframe
  102573. )
  102574. {
  102575. unsigned estimate;
  102576. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  102577. subframe->data.verbatim.data = signal;
  102578. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  102579. #if SPOTCHECK_ESTIMATE
  102580. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  102581. #else
  102582. (void)encoder;
  102583. #endif
  102584. return estimate;
  102585. }
  102586. unsigned find_best_partition_order_(
  102587. FLAC__StreamEncoderPrivate *private_,
  102588. const FLAC__int32 residual[],
  102589. FLAC__uint64 abs_residual_partition_sums[],
  102590. unsigned raw_bits_per_partition[],
  102591. unsigned residual_samples,
  102592. unsigned predictor_order,
  102593. unsigned rice_parameter,
  102594. unsigned rice_parameter_limit,
  102595. unsigned min_partition_order,
  102596. unsigned max_partition_order,
  102597. unsigned bps,
  102598. FLAC__bool do_escape_coding,
  102599. unsigned rice_parameter_search_dist,
  102600. FLAC__EntropyCodingMethod *best_ecm
  102601. )
  102602. {
  102603. unsigned residual_bits, best_residual_bits = 0;
  102604. unsigned best_parameters_index = 0;
  102605. unsigned best_partition_order = 0;
  102606. const unsigned blocksize = residual_samples + predictor_order;
  102607. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  102608. min_partition_order = min(min_partition_order, max_partition_order);
  102609. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  102610. if(do_escape_coding)
  102611. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  102612. {
  102613. int partition_order;
  102614. unsigned sum;
  102615. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  102616. if(!
  102617. set_partitioned_rice_(
  102618. #ifdef EXACT_RICE_BITS_CALCULATION
  102619. residual,
  102620. #endif
  102621. abs_residual_partition_sums+sum,
  102622. raw_bits_per_partition+sum,
  102623. residual_samples,
  102624. predictor_order,
  102625. rice_parameter,
  102626. rice_parameter_limit,
  102627. rice_parameter_search_dist,
  102628. (unsigned)partition_order,
  102629. do_escape_coding,
  102630. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  102631. &residual_bits
  102632. )
  102633. )
  102634. {
  102635. FLAC__ASSERT(best_residual_bits != 0);
  102636. break;
  102637. }
  102638. sum += 1u << partition_order;
  102639. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  102640. best_residual_bits = residual_bits;
  102641. best_parameters_index = !best_parameters_index;
  102642. best_partition_order = partition_order;
  102643. }
  102644. }
  102645. }
  102646. best_ecm->data.partitioned_rice.order = best_partition_order;
  102647. {
  102648. /*
  102649. * We are allowed to de-const the pointer based on our special
  102650. * knowledge; it is const to the outside world.
  102651. */
  102652. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  102653. unsigned partition;
  102654. /* save best parameters and raw_bits */
  102655. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  102656. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  102657. if(do_escape_coding)
  102658. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  102659. /*
  102660. * Now need to check if the type should be changed to
  102661. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  102662. * size of the rice parameters.
  102663. */
  102664. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  102665. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  102666. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  102667. break;
  102668. }
  102669. }
  102670. }
  102671. return best_residual_bits;
  102672. }
  102673. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  102674. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  102675. const FLAC__int32 residual[],
  102676. FLAC__uint64 abs_residual_partition_sums[],
  102677. unsigned blocksize,
  102678. unsigned predictor_order,
  102679. unsigned min_partition_order,
  102680. unsigned max_partition_order
  102681. );
  102682. #endif
  102683. void precompute_partition_info_sums_(
  102684. const FLAC__int32 residual[],
  102685. FLAC__uint64 abs_residual_partition_sums[],
  102686. unsigned residual_samples,
  102687. unsigned predictor_order,
  102688. unsigned min_partition_order,
  102689. unsigned max_partition_order,
  102690. unsigned bps
  102691. )
  102692. {
  102693. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  102694. unsigned partitions = 1u << max_partition_order;
  102695. FLAC__ASSERT(default_partition_samples > predictor_order);
  102696. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  102697. /* slightly pessimistic but still catches all common cases */
  102698. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  102699. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  102700. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  102701. return;
  102702. }
  102703. #endif
  102704. /* first do max_partition_order */
  102705. {
  102706. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  102707. /* slightly pessimistic but still catches all common cases */
  102708. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  102709. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  102710. FLAC__uint32 abs_residual_partition_sum;
  102711. for(partition = residual_sample = 0; partition < partitions; partition++) {
  102712. end += default_partition_samples;
  102713. abs_residual_partition_sum = 0;
  102714. for( ; residual_sample < end; residual_sample++)
  102715. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  102716. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  102717. }
  102718. }
  102719. else { /* have to pessimistically use 64 bits for accumulator */
  102720. FLAC__uint64 abs_residual_partition_sum;
  102721. for(partition = residual_sample = 0; partition < partitions; partition++) {
  102722. end += default_partition_samples;
  102723. abs_residual_partition_sum = 0;
  102724. for( ; residual_sample < end; residual_sample++)
  102725. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  102726. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  102727. }
  102728. }
  102729. }
  102730. /* now merge partitions for lower orders */
  102731. {
  102732. unsigned from_partition = 0, to_partition = partitions;
  102733. int partition_order;
  102734. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  102735. unsigned i;
  102736. partitions >>= 1;
  102737. for(i = 0; i < partitions; i++) {
  102738. abs_residual_partition_sums[to_partition++] =
  102739. abs_residual_partition_sums[from_partition ] +
  102740. abs_residual_partition_sums[from_partition+1];
  102741. from_partition += 2;
  102742. }
  102743. }
  102744. }
  102745. }
  102746. void precompute_partition_info_escapes_(
  102747. const FLAC__int32 residual[],
  102748. unsigned raw_bits_per_partition[],
  102749. unsigned residual_samples,
  102750. unsigned predictor_order,
  102751. unsigned min_partition_order,
  102752. unsigned max_partition_order
  102753. )
  102754. {
  102755. int partition_order;
  102756. unsigned from_partition, to_partition = 0;
  102757. const unsigned blocksize = residual_samples + predictor_order;
  102758. /* first do max_partition_order */
  102759. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  102760. FLAC__int32 r;
  102761. FLAC__uint32 rmax;
  102762. unsigned partition, partition_sample, partition_samples, residual_sample;
  102763. const unsigned partitions = 1u << partition_order;
  102764. const unsigned default_partition_samples = blocksize >> partition_order;
  102765. FLAC__ASSERT(default_partition_samples > predictor_order);
  102766. for(partition = residual_sample = 0; partition < partitions; partition++) {
  102767. partition_samples = default_partition_samples;
  102768. if(partition == 0)
  102769. partition_samples -= predictor_order;
  102770. rmax = 0;
  102771. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  102772. r = residual[residual_sample++];
  102773. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  102774. if(r < 0)
  102775. rmax |= ~r;
  102776. else
  102777. rmax |= r;
  102778. }
  102779. /* now we know all residual values are in the range [-rmax-1,rmax] */
  102780. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  102781. }
  102782. to_partition = partitions;
  102783. break; /*@@@ yuck, should remove the 'for' loop instead */
  102784. }
  102785. /* now merge partitions for lower orders */
  102786. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  102787. unsigned m;
  102788. unsigned i;
  102789. const unsigned partitions = 1u << partition_order;
  102790. for(i = 0; i < partitions; i++) {
  102791. m = raw_bits_per_partition[from_partition];
  102792. from_partition++;
  102793. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  102794. from_partition++;
  102795. to_partition++;
  102796. }
  102797. }
  102798. }
  102799. #ifdef EXACT_RICE_BITS_CALCULATION
  102800. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  102801. const unsigned rice_parameter,
  102802. const unsigned partition_samples,
  102803. const FLAC__int32 *residual
  102804. )
  102805. {
  102806. unsigned i, partition_bits =
  102807. 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 */
  102808. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  102809. ;
  102810. for(i = 0; i < partition_samples; i++)
  102811. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  102812. return partition_bits;
  102813. }
  102814. #else
  102815. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  102816. const unsigned rice_parameter,
  102817. const unsigned partition_samples,
  102818. const FLAC__uint64 abs_residual_partition_sum
  102819. )
  102820. {
  102821. return
  102822. 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 */
  102823. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  102824. (
  102825. rice_parameter?
  102826. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  102827. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  102828. )
  102829. - (partition_samples >> 1)
  102830. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  102831. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  102832. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  102833. * So the subtraction term tries to guess how many extra bits were contributed.
  102834. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  102835. */
  102836. ;
  102837. }
  102838. #endif
  102839. FLAC__bool set_partitioned_rice_(
  102840. #ifdef EXACT_RICE_BITS_CALCULATION
  102841. const FLAC__int32 residual[],
  102842. #endif
  102843. const FLAC__uint64 abs_residual_partition_sums[],
  102844. const unsigned raw_bits_per_partition[],
  102845. const unsigned residual_samples,
  102846. const unsigned predictor_order,
  102847. const unsigned suggested_rice_parameter,
  102848. const unsigned rice_parameter_limit,
  102849. const unsigned rice_parameter_search_dist,
  102850. const unsigned partition_order,
  102851. const FLAC__bool search_for_escapes,
  102852. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  102853. unsigned *bits
  102854. )
  102855. {
  102856. unsigned rice_parameter, partition_bits;
  102857. unsigned best_partition_bits, best_rice_parameter = 0;
  102858. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  102859. unsigned *parameters, *raw_bits;
  102860. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  102861. unsigned min_rice_parameter, max_rice_parameter;
  102862. #else
  102863. (void)rice_parameter_search_dist;
  102864. #endif
  102865. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  102866. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  102867. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  102868. parameters = partitioned_rice_contents->parameters;
  102869. raw_bits = partitioned_rice_contents->raw_bits;
  102870. if(partition_order == 0) {
  102871. best_partition_bits = (unsigned)(-1);
  102872. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  102873. if(rice_parameter_search_dist) {
  102874. if(suggested_rice_parameter < rice_parameter_search_dist)
  102875. min_rice_parameter = 0;
  102876. else
  102877. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  102878. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  102879. if(max_rice_parameter >= rice_parameter_limit) {
  102880. #ifdef DEBUG_VERBOSE
  102881. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  102882. #endif
  102883. max_rice_parameter = rice_parameter_limit - 1;
  102884. }
  102885. }
  102886. else
  102887. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  102888. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  102889. #else
  102890. rice_parameter = suggested_rice_parameter;
  102891. #endif
  102892. #ifdef EXACT_RICE_BITS_CALCULATION
  102893. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  102894. #else
  102895. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  102896. #endif
  102897. if(partition_bits < best_partition_bits) {
  102898. best_rice_parameter = rice_parameter;
  102899. best_partition_bits = partition_bits;
  102900. }
  102901. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  102902. }
  102903. #endif
  102904. if(search_for_escapes) {
  102905. 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;
  102906. if(partition_bits <= best_partition_bits) {
  102907. raw_bits[0] = raw_bits_per_partition[0];
  102908. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  102909. best_partition_bits = partition_bits;
  102910. }
  102911. else
  102912. raw_bits[0] = 0;
  102913. }
  102914. parameters[0] = best_rice_parameter;
  102915. bits_ += best_partition_bits;
  102916. }
  102917. else {
  102918. unsigned partition, residual_sample;
  102919. unsigned partition_samples;
  102920. FLAC__uint64 mean, k;
  102921. const unsigned partitions = 1u << partition_order;
  102922. for(partition = residual_sample = 0; partition < partitions; partition++) {
  102923. partition_samples = (residual_samples+predictor_order) >> partition_order;
  102924. if(partition == 0) {
  102925. if(partition_samples <= predictor_order)
  102926. return false;
  102927. else
  102928. partition_samples -= predictor_order;
  102929. }
  102930. mean = abs_residual_partition_sums[partition];
  102931. /* we are basically calculating the size in bits of the
  102932. * average residual magnitude in the partition:
  102933. * rice_parameter = floor(log2(mean/partition_samples))
  102934. * 'mean' is not a good name for the variable, it is
  102935. * actually the sum of magnitudes of all residual values
  102936. * in the partition, so the actual mean is
  102937. * mean/partition_samples
  102938. */
  102939. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  102940. ;
  102941. if(rice_parameter >= rice_parameter_limit) {
  102942. #ifdef DEBUG_VERBOSE
  102943. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  102944. #endif
  102945. rice_parameter = rice_parameter_limit - 1;
  102946. }
  102947. best_partition_bits = (unsigned)(-1);
  102948. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  102949. if(rice_parameter_search_dist) {
  102950. if(rice_parameter < rice_parameter_search_dist)
  102951. min_rice_parameter = 0;
  102952. else
  102953. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  102954. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  102955. if(max_rice_parameter >= rice_parameter_limit) {
  102956. #ifdef DEBUG_VERBOSE
  102957. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  102958. #endif
  102959. max_rice_parameter = rice_parameter_limit - 1;
  102960. }
  102961. }
  102962. else
  102963. min_rice_parameter = max_rice_parameter = rice_parameter;
  102964. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  102965. #endif
  102966. #ifdef EXACT_RICE_BITS_CALCULATION
  102967. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  102968. #else
  102969. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  102970. #endif
  102971. if(partition_bits < best_partition_bits) {
  102972. best_rice_parameter = rice_parameter;
  102973. best_partition_bits = partition_bits;
  102974. }
  102975. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  102976. }
  102977. #endif
  102978. if(search_for_escapes) {
  102979. 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;
  102980. if(partition_bits <= best_partition_bits) {
  102981. raw_bits[partition] = raw_bits_per_partition[partition];
  102982. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  102983. best_partition_bits = partition_bits;
  102984. }
  102985. else
  102986. raw_bits[partition] = 0;
  102987. }
  102988. parameters[partition] = best_rice_parameter;
  102989. bits_ += best_partition_bits;
  102990. residual_sample += partition_samples;
  102991. }
  102992. }
  102993. *bits = bits_;
  102994. return true;
  102995. }
  102996. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  102997. {
  102998. unsigned i, shift;
  102999. FLAC__int32 x = 0;
  103000. for(i = 0; i < samples && !(x&1); i++)
  103001. x |= signal[i];
  103002. if(x == 0) {
  103003. shift = 0;
  103004. }
  103005. else {
  103006. for(shift = 0; !(x&1); shift++)
  103007. x >>= 1;
  103008. }
  103009. if(shift > 0) {
  103010. for(i = 0; i < samples; i++)
  103011. signal[i] >>= shift;
  103012. }
  103013. return shift;
  103014. }
  103015. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  103016. {
  103017. unsigned channel;
  103018. for(channel = 0; channel < channels; channel++)
  103019. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  103020. fifo->tail += wide_samples;
  103021. FLAC__ASSERT(fifo->tail <= fifo->size);
  103022. }
  103023. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  103024. {
  103025. unsigned channel;
  103026. unsigned sample, wide_sample;
  103027. unsigned tail = fifo->tail;
  103028. sample = input_offset * channels;
  103029. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  103030. for(channel = 0; channel < channels; channel++)
  103031. fifo->data[channel][tail] = input[sample++];
  103032. tail++;
  103033. }
  103034. fifo->tail = tail;
  103035. FLAC__ASSERT(fifo->tail <= fifo->size);
  103036. }
  103037. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  103038. {
  103039. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  103040. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  103041. (void)decoder;
  103042. if(encoder->private_->verify.needs_magic_hack) {
  103043. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  103044. *bytes = FLAC__STREAM_SYNC_LENGTH;
  103045. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  103046. encoder->private_->verify.needs_magic_hack = false;
  103047. }
  103048. else {
  103049. if(encoded_bytes == 0) {
  103050. /*
  103051. * If we get here, a FIFO underflow has occurred,
  103052. * which means there is a bug somewhere.
  103053. */
  103054. FLAC__ASSERT(0);
  103055. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  103056. }
  103057. else if(encoded_bytes < *bytes)
  103058. *bytes = encoded_bytes;
  103059. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  103060. encoder->private_->verify.output.data += *bytes;
  103061. encoder->private_->verify.output.bytes -= *bytes;
  103062. }
  103063. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  103064. }
  103065. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  103066. {
  103067. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  103068. unsigned channel;
  103069. const unsigned channels = frame->header.channels;
  103070. const unsigned blocksize = frame->header.blocksize;
  103071. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  103072. (void)decoder;
  103073. for(channel = 0; channel < channels; channel++) {
  103074. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  103075. unsigned i, sample = 0;
  103076. FLAC__int32 expect = 0, got = 0;
  103077. for(i = 0; i < blocksize; i++) {
  103078. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  103079. sample = i;
  103080. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  103081. got = (FLAC__int32)buffer[channel][i];
  103082. break;
  103083. }
  103084. }
  103085. FLAC__ASSERT(i < blocksize);
  103086. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  103087. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  103088. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  103089. encoder->private_->verify.error_stats.channel = channel;
  103090. encoder->private_->verify.error_stats.sample = sample;
  103091. encoder->private_->verify.error_stats.expected = expect;
  103092. encoder->private_->verify.error_stats.got = got;
  103093. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  103094. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  103095. }
  103096. }
  103097. /* dequeue the frame from the fifo */
  103098. encoder->private_->verify.input_fifo.tail -= blocksize;
  103099. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  103100. for(channel = 0; channel < channels; channel++)
  103101. 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]));
  103102. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  103103. }
  103104. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  103105. {
  103106. (void)decoder, (void)metadata, (void)client_data;
  103107. }
  103108. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  103109. {
  103110. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  103111. (void)decoder, (void)status;
  103112. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103113. }
  103114. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  103115. {
  103116. (void)client_data;
  103117. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  103118. if (*bytes == 0) {
  103119. if (feof(encoder->private_->file))
  103120. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  103121. else if (ferror(encoder->private_->file))
  103122. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  103123. }
  103124. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  103125. }
  103126. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  103127. {
  103128. (void)client_data;
  103129. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  103130. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  103131. else
  103132. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  103133. }
  103134. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  103135. {
  103136. off_t offset;
  103137. (void)client_data;
  103138. offset = ftello(encoder->private_->file);
  103139. if(offset < 0) {
  103140. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  103141. }
  103142. else {
  103143. *absolute_byte_offset = (FLAC__uint64)offset;
  103144. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  103145. }
  103146. }
  103147. #ifdef FLAC__VALGRIND_TESTING
  103148. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  103149. {
  103150. size_t ret = fwrite(ptr, size, nmemb, stream);
  103151. if(!ferror(stream))
  103152. fflush(stream);
  103153. return ret;
  103154. }
  103155. #else
  103156. #define local__fwrite fwrite
  103157. #endif
  103158. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  103159. {
  103160. (void)client_data, (void)current_frame;
  103161. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  103162. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  103163. #if FLAC__HAS_OGG
  103164. /* We would like to be able to use 'samples > 0' in the
  103165. * clause here but currently because of the nature of our
  103166. * Ogg writing implementation, 'samples' is always 0 (see
  103167. * ogg_encoder_aspect.c). The downside is extra progress
  103168. * callbacks.
  103169. */
  103170. encoder->private_->is_ogg? true :
  103171. #endif
  103172. samples > 0
  103173. );
  103174. if(call_it) {
  103175. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  103176. * because at this point in the callback chain, the stats
  103177. * have not been updated. Only after we return and control
  103178. * gets back to write_frame_() are the stats updated
  103179. */
  103180. 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);
  103181. }
  103182. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  103183. }
  103184. else
  103185. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  103186. }
  103187. /*
  103188. * This will forcibly set stdout to binary mode (for OSes that require it)
  103189. */
  103190. FILE *get_binary_stdout_(void)
  103191. {
  103192. /* if something breaks here it is probably due to the presence or
  103193. * absence of an underscore before the identifiers 'setmode',
  103194. * 'fileno', and/or 'O_BINARY'; check your system header files.
  103195. */
  103196. #if defined _MSC_VER || defined __MINGW32__
  103197. _setmode(_fileno(stdout), _O_BINARY);
  103198. #elif defined __CYGWIN__
  103199. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  103200. setmode(_fileno(stdout), _O_BINARY);
  103201. #elif defined __EMX__
  103202. setmode(fileno(stdout), O_BINARY);
  103203. #endif
  103204. return stdout;
  103205. }
  103206. #endif
  103207. /*** End of inlined file: stream_encoder.c ***/
  103208. /*** Start of inlined file: stream_encoder_framing.c ***/
  103209. /*** Start of inlined file: juce_FlacHeader.h ***/
  103210. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  103211. // tasks..
  103212. #define VERSION "1.2.1"
  103213. #define FLAC__NO_DLL 1
  103214. #if JUCE_MSVC
  103215. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  103216. #endif
  103217. #if JUCE_MAC
  103218. #define FLAC__SYS_DARWIN 1
  103219. #endif
  103220. /*** End of inlined file: juce_FlacHeader.h ***/
  103221. #if JUCE_USE_FLAC
  103222. #if HAVE_CONFIG_H
  103223. # include <config.h>
  103224. #endif
  103225. #include <stdio.h>
  103226. #include <string.h> /* for strlen() */
  103227. #ifdef max
  103228. #undef max
  103229. #endif
  103230. #define max(x,y) ((x)>(y)?(x):(y))
  103231. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  103232. 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);
  103233. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  103234. {
  103235. unsigned i, j;
  103236. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  103237. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  103238. return false;
  103239. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  103240. return false;
  103241. /*
  103242. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  103243. */
  103244. i = metadata->length;
  103245. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  103246. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  103247. i -= metadata->data.vorbis_comment.vendor_string.length;
  103248. i += vendor_string_length;
  103249. }
  103250. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  103251. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  103252. return false;
  103253. switch(metadata->type) {
  103254. case FLAC__METADATA_TYPE_STREAMINFO:
  103255. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  103256. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  103257. return false;
  103258. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  103259. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  103260. return false;
  103261. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  103262. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  103263. return false;
  103264. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  103265. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  103266. return false;
  103267. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  103268. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  103269. return false;
  103270. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  103271. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  103272. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  103273. return false;
  103274. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  103275. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  103276. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  103277. return false;
  103278. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  103279. return false;
  103280. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  103281. return false;
  103282. break;
  103283. case FLAC__METADATA_TYPE_PADDING:
  103284. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  103285. return false;
  103286. break;
  103287. case FLAC__METADATA_TYPE_APPLICATION:
  103288. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  103289. return false;
  103290. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  103291. return false;
  103292. break;
  103293. case FLAC__METADATA_TYPE_SEEKTABLE:
  103294. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  103295. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  103296. return false;
  103297. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  103298. return false;
  103299. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  103300. return false;
  103301. }
  103302. break;
  103303. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  103304. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  103305. return false;
  103306. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  103307. return false;
  103308. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  103309. return false;
  103310. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  103311. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  103312. return false;
  103313. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  103314. return false;
  103315. }
  103316. break;
  103317. case FLAC__METADATA_TYPE_CUESHEET:
  103318. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  103319. 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))
  103320. return false;
  103321. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  103322. return false;
  103323. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  103324. return false;
  103325. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  103326. return false;
  103327. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  103328. return false;
  103329. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  103330. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  103331. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  103332. return false;
  103333. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  103334. return false;
  103335. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  103336. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  103337. return false;
  103338. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  103339. return false;
  103340. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  103341. return false;
  103342. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  103343. return false;
  103344. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  103345. return false;
  103346. for(j = 0; j < track->num_indices; j++) {
  103347. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  103348. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  103349. return false;
  103350. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  103351. return false;
  103352. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  103353. return false;
  103354. }
  103355. }
  103356. break;
  103357. case FLAC__METADATA_TYPE_PICTURE:
  103358. {
  103359. size_t len;
  103360. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  103361. return false;
  103362. len = strlen(metadata->data.picture.mime_type);
  103363. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  103364. return false;
  103365. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  103366. return false;
  103367. len = strlen((const char *)metadata->data.picture.description);
  103368. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  103369. return false;
  103370. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  103371. return false;
  103372. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  103373. return false;
  103374. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  103375. return false;
  103376. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  103377. return false;
  103378. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  103379. return false;
  103380. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  103381. return false;
  103382. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  103383. return false;
  103384. }
  103385. break;
  103386. default:
  103387. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  103388. return false;
  103389. break;
  103390. }
  103391. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  103392. return true;
  103393. }
  103394. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  103395. {
  103396. unsigned u, blocksize_hint, sample_rate_hint;
  103397. FLAC__byte crc;
  103398. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  103399. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  103400. return false;
  103401. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  103402. return false;
  103403. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  103404. return false;
  103405. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  103406. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  103407. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  103408. blocksize_hint = 0;
  103409. switch(header->blocksize) {
  103410. case 192: u = 1; break;
  103411. case 576: u = 2; break;
  103412. case 1152: u = 3; break;
  103413. case 2304: u = 4; break;
  103414. case 4608: u = 5; break;
  103415. case 256: u = 8; break;
  103416. case 512: u = 9; break;
  103417. case 1024: u = 10; break;
  103418. case 2048: u = 11; break;
  103419. case 4096: u = 12; break;
  103420. case 8192: u = 13; break;
  103421. case 16384: u = 14; break;
  103422. case 32768: u = 15; break;
  103423. default:
  103424. if(header->blocksize <= 0x100)
  103425. blocksize_hint = u = 6;
  103426. else
  103427. blocksize_hint = u = 7;
  103428. break;
  103429. }
  103430. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  103431. return false;
  103432. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  103433. sample_rate_hint = 0;
  103434. switch(header->sample_rate) {
  103435. case 88200: u = 1; break;
  103436. case 176400: u = 2; break;
  103437. case 192000: u = 3; break;
  103438. case 8000: u = 4; break;
  103439. case 16000: u = 5; break;
  103440. case 22050: u = 6; break;
  103441. case 24000: u = 7; break;
  103442. case 32000: u = 8; break;
  103443. case 44100: u = 9; break;
  103444. case 48000: u = 10; break;
  103445. case 96000: u = 11; break;
  103446. default:
  103447. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  103448. sample_rate_hint = u = 12;
  103449. else if(header->sample_rate % 10 == 0)
  103450. sample_rate_hint = u = 14;
  103451. else if(header->sample_rate <= 0xffff)
  103452. sample_rate_hint = u = 13;
  103453. else
  103454. u = 0;
  103455. break;
  103456. }
  103457. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  103458. return false;
  103459. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  103460. switch(header->channel_assignment) {
  103461. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  103462. u = header->channels - 1;
  103463. break;
  103464. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  103465. FLAC__ASSERT(header->channels == 2);
  103466. u = 8;
  103467. break;
  103468. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  103469. FLAC__ASSERT(header->channels == 2);
  103470. u = 9;
  103471. break;
  103472. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  103473. FLAC__ASSERT(header->channels == 2);
  103474. u = 10;
  103475. break;
  103476. default:
  103477. FLAC__ASSERT(0);
  103478. }
  103479. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  103480. return false;
  103481. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  103482. switch(header->bits_per_sample) {
  103483. case 8 : u = 1; break;
  103484. case 12: u = 2; break;
  103485. case 16: u = 4; break;
  103486. case 20: u = 5; break;
  103487. case 24: u = 6; break;
  103488. default: u = 0; break;
  103489. }
  103490. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  103491. return false;
  103492. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  103493. return false;
  103494. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  103495. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  103496. return false;
  103497. }
  103498. else {
  103499. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  103500. return false;
  103501. }
  103502. if(blocksize_hint)
  103503. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  103504. return false;
  103505. switch(sample_rate_hint) {
  103506. case 12:
  103507. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  103508. return false;
  103509. break;
  103510. case 13:
  103511. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  103512. return false;
  103513. break;
  103514. case 14:
  103515. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  103516. return false;
  103517. break;
  103518. }
  103519. /* write the CRC */
  103520. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  103521. return false;
  103522. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  103523. return false;
  103524. return true;
  103525. }
  103526. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  103527. {
  103528. FLAC__bool ok;
  103529. ok =
  103530. 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) &&
  103531. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  103532. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  103533. ;
  103534. return ok;
  103535. }
  103536. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  103537. {
  103538. unsigned i;
  103539. 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))
  103540. return false;
  103541. if(wasted_bits)
  103542. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  103543. return false;
  103544. for(i = 0; i < subframe->order; i++)
  103545. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  103546. return false;
  103547. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  103548. return false;
  103549. switch(subframe->entropy_coding_method.type) {
  103550. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  103551. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  103552. if(!add_residual_partitioned_rice_(
  103553. bw,
  103554. subframe->residual,
  103555. residual_samples,
  103556. subframe->order,
  103557. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  103558. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  103559. subframe->entropy_coding_method.data.partitioned_rice.order,
  103560. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  103561. ))
  103562. return false;
  103563. break;
  103564. default:
  103565. FLAC__ASSERT(0);
  103566. }
  103567. return true;
  103568. }
  103569. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  103570. {
  103571. unsigned i;
  103572. 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))
  103573. return false;
  103574. if(wasted_bits)
  103575. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  103576. return false;
  103577. for(i = 0; i < subframe->order; i++)
  103578. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  103579. return false;
  103580. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  103581. return false;
  103582. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  103583. return false;
  103584. for(i = 0; i < subframe->order; i++)
  103585. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  103586. return false;
  103587. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  103588. return false;
  103589. switch(subframe->entropy_coding_method.type) {
  103590. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  103591. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  103592. if(!add_residual_partitioned_rice_(
  103593. bw,
  103594. subframe->residual,
  103595. residual_samples,
  103596. subframe->order,
  103597. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  103598. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  103599. subframe->entropy_coding_method.data.partitioned_rice.order,
  103600. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  103601. ))
  103602. return false;
  103603. break;
  103604. default:
  103605. FLAC__ASSERT(0);
  103606. }
  103607. return true;
  103608. }
  103609. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  103610. {
  103611. unsigned i;
  103612. const FLAC__int32 *signal = subframe->data;
  103613. 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))
  103614. return false;
  103615. if(wasted_bits)
  103616. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  103617. return false;
  103618. for(i = 0; i < samples; i++)
  103619. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  103620. return false;
  103621. return true;
  103622. }
  103623. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  103624. {
  103625. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  103626. return false;
  103627. switch(method->type) {
  103628. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  103629. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  103630. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  103631. return false;
  103632. break;
  103633. default:
  103634. FLAC__ASSERT(0);
  103635. }
  103636. return true;
  103637. }
  103638. 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)
  103639. {
  103640. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  103641. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  103642. if(partition_order == 0) {
  103643. unsigned i;
  103644. if(raw_bits[0] == 0) {
  103645. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  103646. return false;
  103647. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  103648. return false;
  103649. }
  103650. else {
  103651. FLAC__ASSERT(rice_parameters[0] == 0);
  103652. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  103653. return false;
  103654. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  103655. return false;
  103656. for(i = 0; i < residual_samples; i++) {
  103657. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  103658. return false;
  103659. }
  103660. }
  103661. return true;
  103662. }
  103663. else {
  103664. unsigned i, j, k = 0, k_last = 0;
  103665. unsigned partition_samples;
  103666. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  103667. for(i = 0; i < (1u<<partition_order); i++) {
  103668. partition_samples = default_partition_samples;
  103669. if(i == 0)
  103670. partition_samples -= predictor_order;
  103671. k += partition_samples;
  103672. if(raw_bits[i] == 0) {
  103673. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  103674. return false;
  103675. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  103676. return false;
  103677. }
  103678. else {
  103679. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  103680. return false;
  103681. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  103682. return false;
  103683. for(j = k_last; j < k; j++) {
  103684. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  103685. return false;
  103686. }
  103687. }
  103688. k_last = k;
  103689. }
  103690. return true;
  103691. }
  103692. }
  103693. #endif
  103694. /*** End of inlined file: stream_encoder_framing.c ***/
  103695. /*** Start of inlined file: window_flac.c ***/
  103696. /*** Start of inlined file: juce_FlacHeader.h ***/
  103697. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  103698. // tasks..
  103699. #define VERSION "1.2.1"
  103700. #define FLAC__NO_DLL 1
  103701. #if JUCE_MSVC
  103702. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  103703. #endif
  103704. #if JUCE_MAC
  103705. #define FLAC__SYS_DARWIN 1
  103706. #endif
  103707. /*** End of inlined file: juce_FlacHeader.h ***/
  103708. #if JUCE_USE_FLAC
  103709. #if HAVE_CONFIG_H
  103710. # include <config.h>
  103711. #endif
  103712. #include <math.h>
  103713. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103714. #ifndef M_PI
  103715. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  103716. #define M_PI 3.14159265358979323846
  103717. #endif
  103718. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  103719. {
  103720. const FLAC__int32 N = L - 1;
  103721. FLAC__int32 n;
  103722. if (L & 1) {
  103723. for (n = 0; n <= N/2; n++)
  103724. window[n] = 2.0f * n / (float)N;
  103725. for (; n <= N; n++)
  103726. window[n] = 2.0f - 2.0f * n / (float)N;
  103727. }
  103728. else {
  103729. for (n = 0; n <= L/2-1; n++)
  103730. window[n] = 2.0f * n / (float)N;
  103731. for (; n <= N; n++)
  103732. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  103733. }
  103734. }
  103735. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  103736. {
  103737. const FLAC__int32 N = L - 1;
  103738. FLAC__int32 n;
  103739. for (n = 0; n < L; n++)
  103740. 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)));
  103741. }
  103742. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  103743. {
  103744. const FLAC__int32 N = L - 1;
  103745. FLAC__int32 n;
  103746. for (n = 0; n < L; n++)
  103747. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  103748. }
  103749. /* 4-term -92dB side-lobe */
  103750. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  103751. {
  103752. const FLAC__int32 N = L - 1;
  103753. FLAC__int32 n;
  103754. for (n = 0; n <= N; n++)
  103755. 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));
  103756. }
  103757. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  103758. {
  103759. const FLAC__int32 N = L - 1;
  103760. const double N2 = (double)N / 2.;
  103761. FLAC__int32 n;
  103762. for (n = 0; n <= N; n++) {
  103763. double k = ((double)n - N2) / N2;
  103764. k = 1.0f - k * k;
  103765. window[n] = (FLAC__real)(k * k);
  103766. }
  103767. }
  103768. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  103769. {
  103770. const FLAC__int32 N = L - 1;
  103771. FLAC__int32 n;
  103772. for (n = 0; n < L; n++)
  103773. 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));
  103774. }
  103775. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  103776. {
  103777. const FLAC__int32 N = L - 1;
  103778. const double N2 = (double)N / 2.;
  103779. FLAC__int32 n;
  103780. for (n = 0; n <= N; n++) {
  103781. const double k = ((double)n - N2) / (stddev * N2);
  103782. window[n] = (FLAC__real)exp(-0.5f * k * k);
  103783. }
  103784. }
  103785. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  103786. {
  103787. const FLAC__int32 N = L - 1;
  103788. FLAC__int32 n;
  103789. for (n = 0; n < L; n++)
  103790. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  103791. }
  103792. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  103793. {
  103794. const FLAC__int32 N = L - 1;
  103795. FLAC__int32 n;
  103796. for (n = 0; n < L; n++)
  103797. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  103798. }
  103799. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  103800. {
  103801. const FLAC__int32 N = L - 1;
  103802. FLAC__int32 n;
  103803. for (n = 0; n < L; n++)
  103804. 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));
  103805. }
  103806. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  103807. {
  103808. const FLAC__int32 N = L - 1;
  103809. FLAC__int32 n;
  103810. for (n = 0; n < L; n++)
  103811. 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));
  103812. }
  103813. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  103814. {
  103815. FLAC__int32 n;
  103816. for (n = 0; n < L; n++)
  103817. window[n] = 1.0f;
  103818. }
  103819. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  103820. {
  103821. FLAC__int32 n;
  103822. if (L & 1) {
  103823. for (n = 1; n <= L+1/2; n++)
  103824. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  103825. for (; n <= L; n++)
  103826. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  103827. }
  103828. else {
  103829. for (n = 1; n <= L/2; n++)
  103830. window[n-1] = 2.0f * n / (float)L;
  103831. for (; n <= L; n++)
  103832. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  103833. }
  103834. }
  103835. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  103836. {
  103837. if (p <= 0.0)
  103838. FLAC__window_rectangle(window, L);
  103839. else if (p >= 1.0)
  103840. FLAC__window_hann(window, L);
  103841. else {
  103842. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  103843. FLAC__int32 n;
  103844. /* start with rectangle... */
  103845. FLAC__window_rectangle(window, L);
  103846. /* ...replace ends with hann */
  103847. if (Np > 0) {
  103848. for (n = 0; n <= Np; n++) {
  103849. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  103850. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  103851. }
  103852. }
  103853. }
  103854. }
  103855. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  103856. {
  103857. const FLAC__int32 N = L - 1;
  103858. const double N2 = (double)N / 2.;
  103859. FLAC__int32 n;
  103860. for (n = 0; n <= N; n++) {
  103861. const double k = ((double)n - N2) / N2;
  103862. window[n] = (FLAC__real)(1.0f - k * k);
  103863. }
  103864. }
  103865. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  103866. #endif
  103867. /*** End of inlined file: window_flac.c ***/
  103868. #else
  103869. #include <FLAC/all.h>
  103870. #endif
  103871. }
  103872. #undef max
  103873. #undef min
  103874. BEGIN_JUCE_NAMESPACE
  103875. static const char* const flacFormatName = "FLAC file";
  103876. static const char* const flacExtensions[] = { ".flac", 0 };
  103877. class FlacReader : public AudioFormatReader
  103878. {
  103879. public:
  103880. FlacReader (InputStream* const in)
  103881. : AudioFormatReader (in, TRANS (flacFormatName)),
  103882. reservoir (2, 0),
  103883. reservoirStart (0),
  103884. samplesInReservoir (0),
  103885. scanningForLength (false)
  103886. {
  103887. using namespace FlacNamespace;
  103888. lengthInSamples = 0;
  103889. decoder = FLAC__stream_decoder_new();
  103890. ok = FLAC__stream_decoder_init_stream (decoder,
  103891. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  103892. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  103893. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  103894. if (ok)
  103895. {
  103896. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  103897. if (lengthInSamples == 0 && sampleRate > 0)
  103898. {
  103899. // the length hasn't been stored in the metadata, so we'll need to
  103900. // work it out the length the hard way, by scanning the whole file..
  103901. scanningForLength = true;
  103902. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  103903. scanningForLength = false;
  103904. const int64 tempLength = lengthInSamples;
  103905. FLAC__stream_decoder_reset (decoder);
  103906. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  103907. lengthInSamples = tempLength;
  103908. }
  103909. }
  103910. }
  103911. ~FlacReader()
  103912. {
  103913. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  103914. }
  103915. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  103916. {
  103917. sampleRate = info.sample_rate;
  103918. bitsPerSample = info.bits_per_sample;
  103919. lengthInSamples = (unsigned int) info.total_samples;
  103920. numChannels = info.channels;
  103921. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  103922. }
  103923. // returns the number of samples read
  103924. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  103925. int64 startSampleInFile, int numSamples)
  103926. {
  103927. using namespace FlacNamespace;
  103928. if (! ok)
  103929. return false;
  103930. while (numSamples > 0)
  103931. {
  103932. if (startSampleInFile >= reservoirStart
  103933. && startSampleInFile < reservoirStart + samplesInReservoir)
  103934. {
  103935. const int num = (int) jmin ((int64) numSamples,
  103936. reservoirStart + samplesInReservoir - startSampleInFile);
  103937. jassert (num > 0);
  103938. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  103939. if (destSamples[i] != 0)
  103940. memcpy (destSamples[i] + startOffsetInDestBuffer,
  103941. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  103942. sizeof (int) * num);
  103943. startOffsetInDestBuffer += num;
  103944. startSampleInFile += num;
  103945. numSamples -= num;
  103946. }
  103947. else
  103948. {
  103949. if (startSampleInFile >= (int) lengthInSamples)
  103950. {
  103951. samplesInReservoir = 0;
  103952. }
  103953. else if (startSampleInFile < reservoirStart
  103954. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  103955. {
  103956. // had some problems with flac crashing if the read pos is aligned more
  103957. // accurately than this. Probably fixed in newer versions of the library, though.
  103958. reservoirStart = (int) (startSampleInFile & ~511);
  103959. samplesInReservoir = 0;
  103960. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  103961. }
  103962. else
  103963. {
  103964. reservoirStart += samplesInReservoir;
  103965. samplesInReservoir = 0;
  103966. FLAC__stream_decoder_process_single (decoder);
  103967. }
  103968. if (samplesInReservoir == 0)
  103969. break;
  103970. }
  103971. }
  103972. if (numSamples > 0)
  103973. {
  103974. for (int i = numDestChannels; --i >= 0;)
  103975. if (destSamples[i] != 0)
  103976. zeromem (destSamples[i] + startOffsetInDestBuffer,
  103977. sizeof (int) * numSamples);
  103978. }
  103979. return true;
  103980. }
  103981. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  103982. {
  103983. if (scanningForLength)
  103984. {
  103985. lengthInSamples += numSamples;
  103986. }
  103987. else
  103988. {
  103989. if (numSamples > reservoir.getNumSamples())
  103990. reservoir.setSize (numChannels, numSamples, false, false, true);
  103991. const int bitsToShift = 32 - bitsPerSample;
  103992. for (int i = 0; i < (int) numChannels; ++i)
  103993. {
  103994. const FlacNamespace::FLAC__int32* src = buffer[i];
  103995. int n = i;
  103996. while (src == 0 && n > 0)
  103997. src = buffer [--n];
  103998. if (src != 0)
  103999. {
  104000. int* dest = (int*) reservoir.getSampleData(i);
  104001. for (int j = 0; j < numSamples; ++j)
  104002. dest[j] = src[j] << bitsToShift;
  104003. }
  104004. }
  104005. samplesInReservoir = numSamples;
  104006. }
  104007. }
  104008. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  104009. {
  104010. using namespace FlacNamespace;
  104011. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  104012. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  104013. }
  104014. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  104015. {
  104016. using namespace FlacNamespace;
  104017. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  104018. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  104019. }
  104020. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  104021. {
  104022. using namespace FlacNamespace;
  104023. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  104024. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  104025. }
  104026. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  104027. {
  104028. using namespace FlacNamespace;
  104029. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  104030. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  104031. }
  104032. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  104033. {
  104034. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  104035. }
  104036. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  104037. const FlacNamespace::FLAC__Frame* frame,
  104038. const FlacNamespace::FLAC__int32* const buffer[],
  104039. void* client_data)
  104040. {
  104041. using namespace FlacNamespace;
  104042. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  104043. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  104044. }
  104045. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  104046. const FlacNamespace::FLAC__StreamMetadata* metadata,
  104047. void* client_data)
  104048. {
  104049. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  104050. }
  104051. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  104052. {
  104053. }
  104054. juce_UseDebuggingNewOperator
  104055. private:
  104056. FlacNamespace::FLAC__StreamDecoder* decoder;
  104057. AudioSampleBuffer reservoir;
  104058. int reservoirStart, samplesInReservoir;
  104059. bool ok, scanningForLength;
  104060. FlacReader (const FlacReader&);
  104061. FlacReader& operator= (const FlacReader&);
  104062. };
  104063. class FlacWriter : public AudioFormatWriter
  104064. {
  104065. public:
  104066. FlacWriter (OutputStream* const out,
  104067. const double sampleRate_,
  104068. const int numChannels_,
  104069. const int bitsPerSample_)
  104070. : AudioFormatWriter (out, TRANS (flacFormatName),
  104071. sampleRate_,
  104072. numChannels_,
  104073. bitsPerSample_)
  104074. {
  104075. using namespace FlacNamespace;
  104076. encoder = FLAC__stream_encoder_new();
  104077. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  104078. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  104079. FLAC__stream_encoder_set_channels (encoder, numChannels);
  104080. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  104081. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  104082. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  104083. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  104084. ok = FLAC__stream_encoder_init_stream (encoder,
  104085. encodeWriteCallback, encodeSeekCallback,
  104086. encodeTellCallback, encodeMetadataCallback,
  104087. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  104088. }
  104089. ~FlacWriter()
  104090. {
  104091. if (ok)
  104092. {
  104093. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  104094. output->flush();
  104095. }
  104096. else
  104097. {
  104098. output = 0; // to stop the base class deleting this, as it needs to be returned
  104099. // to the caller of createWriter()
  104100. }
  104101. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  104102. }
  104103. bool write (const int** samplesToWrite, int numSamples)
  104104. {
  104105. using namespace FlacNamespace;
  104106. if (! ok)
  104107. return false;
  104108. int* buf[3];
  104109. const int bitsToShift = 32 - bitsPerSample;
  104110. if (bitsToShift > 0)
  104111. {
  104112. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  104113. temp.setSize (sizeof (int) * numSamples * numChannelsToWrite);
  104114. buf[0] = (int*) temp.getData();
  104115. buf[1] = buf[0] + numSamples;
  104116. buf[2] = 0;
  104117. for (int i = numChannelsToWrite; --i >= 0;)
  104118. {
  104119. if (samplesToWrite[i] != 0)
  104120. {
  104121. for (int j = 0; j < numSamples; ++j)
  104122. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  104123. }
  104124. }
  104125. samplesToWrite = (const int**) buf;
  104126. }
  104127. return FLAC__stream_encoder_process (encoder,
  104128. (const FLAC__int32**) samplesToWrite,
  104129. numSamples) != 0;
  104130. }
  104131. bool writeData (const void* const data, const int size) const
  104132. {
  104133. return output->write (data, size);
  104134. }
  104135. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  104136. {
  104137. using namespace FlacNamespace;
  104138. b += bytes;
  104139. for (int i = 0; i < bytes; ++i)
  104140. {
  104141. *(--b) = (FLAC__byte) (val & 0xff);
  104142. val >>= 8;
  104143. }
  104144. }
  104145. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  104146. {
  104147. using namespace FlacNamespace;
  104148. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  104149. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  104150. const unsigned int channelsMinus1 = info.channels - 1;
  104151. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  104152. packUint32 (info.min_blocksize, buffer, 2);
  104153. packUint32 (info.max_blocksize, buffer + 2, 2);
  104154. packUint32 (info.min_framesize, buffer + 4, 3);
  104155. packUint32 (info.max_framesize, buffer + 7, 3);
  104156. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  104157. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  104158. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  104159. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  104160. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  104161. memcpy (buffer + 18, info.md5sum, 16);
  104162. const bool seekOk = output->setPosition (4);
  104163. (void) seekOk;
  104164. // if this fails, you've given it an output stream that can't seek! It needs
  104165. // to be able to seek back to write the header
  104166. jassert (seekOk);
  104167. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  104168. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  104169. }
  104170. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  104171. const FlacNamespace::FLAC__byte buffer[],
  104172. size_t bytes,
  104173. unsigned int /*samples*/,
  104174. unsigned int /*current_frame*/,
  104175. void* client_data)
  104176. {
  104177. using namespace FlacNamespace;
  104178. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  104179. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  104180. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  104181. }
  104182. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  104183. {
  104184. using namespace FlacNamespace;
  104185. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  104186. }
  104187. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  104188. {
  104189. using namespace FlacNamespace;
  104190. if (client_data == 0)
  104191. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  104192. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  104193. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  104194. }
  104195. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  104196. {
  104197. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  104198. }
  104199. juce_UseDebuggingNewOperator
  104200. bool ok;
  104201. private:
  104202. FlacNamespace::FLAC__StreamEncoder* encoder;
  104203. MemoryBlock temp;
  104204. FlacWriter (const FlacWriter&);
  104205. FlacWriter& operator= (const FlacWriter&);
  104206. };
  104207. FlacAudioFormat::FlacAudioFormat()
  104208. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  104209. {
  104210. }
  104211. FlacAudioFormat::~FlacAudioFormat()
  104212. {
  104213. }
  104214. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  104215. {
  104216. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  104217. return Array <int> (rates);
  104218. }
  104219. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  104220. {
  104221. const int depths[] = { 16, 24, 0 };
  104222. return Array <int> (depths);
  104223. }
  104224. bool FlacAudioFormat::canDoStereo()
  104225. {
  104226. return true;
  104227. }
  104228. bool FlacAudioFormat::canDoMono()
  104229. {
  104230. return true;
  104231. }
  104232. bool FlacAudioFormat::isCompressed()
  104233. {
  104234. return true;
  104235. }
  104236. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  104237. const bool deleteStreamIfOpeningFails)
  104238. {
  104239. ScopedPointer<FlacReader> r (new FlacReader (in));
  104240. if (r->sampleRate != 0)
  104241. return r.release();
  104242. if (! deleteStreamIfOpeningFails)
  104243. r->input = 0;
  104244. return 0;
  104245. }
  104246. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  104247. double sampleRate,
  104248. unsigned int numberOfChannels,
  104249. int bitsPerSample,
  104250. const StringPairArray& /*metadataValues*/,
  104251. int /*qualityOptionIndex*/)
  104252. {
  104253. if (getPossibleBitDepths().contains (bitsPerSample))
  104254. {
  104255. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample));
  104256. if (w->ok)
  104257. return w.release();
  104258. }
  104259. return 0;
  104260. }
  104261. END_JUCE_NAMESPACE
  104262. #endif
  104263. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  104264. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  104265. #if JUCE_USE_OGGVORBIS
  104266. #if JUCE_MAC
  104267. #define __MACOSX__ 1
  104268. #endif
  104269. namespace OggVorbisNamespace
  104270. {
  104271. #if JUCE_INCLUDE_OGGVORBIS_CODE
  104272. /*** Start of inlined file: vorbisenc.h ***/
  104273. #ifndef _OV_ENC_H_
  104274. #define _OV_ENC_H_
  104275. #ifdef __cplusplus
  104276. extern "C"
  104277. {
  104278. #endif /* __cplusplus */
  104279. /*** Start of inlined file: codec.h ***/
  104280. #ifndef _vorbis_codec_h_
  104281. #define _vorbis_codec_h_
  104282. #ifdef __cplusplus
  104283. extern "C"
  104284. {
  104285. #endif /* __cplusplus */
  104286. /*** Start of inlined file: ogg.h ***/
  104287. #ifndef _OGG_H
  104288. #define _OGG_H
  104289. #ifdef __cplusplus
  104290. extern "C" {
  104291. #endif
  104292. /*** Start of inlined file: os_types.h ***/
  104293. #ifndef _OS_TYPES_H
  104294. #define _OS_TYPES_H
  104295. /* make it easy on the folks that want to compile the libs with a
  104296. different malloc than stdlib */
  104297. #define _ogg_malloc malloc
  104298. #define _ogg_calloc calloc
  104299. #define _ogg_realloc realloc
  104300. #define _ogg_free free
  104301. #if defined(_WIN32)
  104302. # if defined(__CYGWIN__)
  104303. # include <_G_config.h>
  104304. typedef _G_int64_t ogg_int64_t;
  104305. typedef _G_int32_t ogg_int32_t;
  104306. typedef _G_uint32_t ogg_uint32_t;
  104307. typedef _G_int16_t ogg_int16_t;
  104308. typedef _G_uint16_t ogg_uint16_t;
  104309. # elif defined(__MINGW32__)
  104310. typedef short ogg_int16_t;
  104311. typedef unsigned short ogg_uint16_t;
  104312. typedef int ogg_int32_t;
  104313. typedef unsigned int ogg_uint32_t;
  104314. typedef long long ogg_int64_t;
  104315. typedef unsigned long long ogg_uint64_t;
  104316. # elif defined(__MWERKS__)
  104317. typedef long long ogg_int64_t;
  104318. typedef int ogg_int32_t;
  104319. typedef unsigned int ogg_uint32_t;
  104320. typedef short ogg_int16_t;
  104321. typedef unsigned short ogg_uint16_t;
  104322. # else
  104323. /* MSVC/Borland */
  104324. typedef __int64 ogg_int64_t;
  104325. typedef __int32 ogg_int32_t;
  104326. typedef unsigned __int32 ogg_uint32_t;
  104327. typedef __int16 ogg_int16_t;
  104328. typedef unsigned __int16 ogg_uint16_t;
  104329. # endif
  104330. #elif defined(__MACOS__)
  104331. # include <sys/types.h>
  104332. typedef SInt16 ogg_int16_t;
  104333. typedef UInt16 ogg_uint16_t;
  104334. typedef SInt32 ogg_int32_t;
  104335. typedef UInt32 ogg_uint32_t;
  104336. typedef SInt64 ogg_int64_t;
  104337. #elif defined(__MACOSX__) /* MacOS X Framework build */
  104338. # include <sys/types.h>
  104339. typedef int16_t ogg_int16_t;
  104340. typedef u_int16_t ogg_uint16_t;
  104341. typedef int32_t ogg_int32_t;
  104342. typedef u_int32_t ogg_uint32_t;
  104343. typedef int64_t ogg_int64_t;
  104344. #elif defined(__BEOS__)
  104345. /* Be */
  104346. # include <inttypes.h>
  104347. typedef int16_t ogg_int16_t;
  104348. typedef u_int16_t ogg_uint16_t;
  104349. typedef int32_t ogg_int32_t;
  104350. typedef u_int32_t ogg_uint32_t;
  104351. typedef int64_t ogg_int64_t;
  104352. #elif defined (__EMX__)
  104353. /* OS/2 GCC */
  104354. typedef short ogg_int16_t;
  104355. typedef unsigned short ogg_uint16_t;
  104356. typedef int ogg_int32_t;
  104357. typedef unsigned int ogg_uint32_t;
  104358. typedef long long ogg_int64_t;
  104359. #elif defined (DJGPP)
  104360. /* DJGPP */
  104361. typedef short ogg_int16_t;
  104362. typedef int ogg_int32_t;
  104363. typedef unsigned int ogg_uint32_t;
  104364. typedef long long ogg_int64_t;
  104365. #elif defined(R5900)
  104366. /* PS2 EE */
  104367. typedef long ogg_int64_t;
  104368. typedef int ogg_int32_t;
  104369. typedef unsigned ogg_uint32_t;
  104370. typedef short ogg_int16_t;
  104371. #elif defined(__SYMBIAN32__)
  104372. /* Symbian GCC */
  104373. typedef signed short ogg_int16_t;
  104374. typedef unsigned short ogg_uint16_t;
  104375. typedef signed int ogg_int32_t;
  104376. typedef unsigned int ogg_uint32_t;
  104377. typedef long long int ogg_int64_t;
  104378. #else
  104379. # include <sys/types.h>
  104380. /*** Start of inlined file: config_types.h ***/
  104381. #ifndef __CONFIG_TYPES_H__
  104382. #define __CONFIG_TYPES_H__
  104383. typedef int16_t ogg_int16_t;
  104384. typedef unsigned short ogg_uint16_t;
  104385. typedef int32_t ogg_int32_t;
  104386. typedef unsigned int ogg_uint32_t;
  104387. typedef int64_t ogg_int64_t;
  104388. #endif
  104389. /*** End of inlined file: config_types.h ***/
  104390. #endif
  104391. #endif /* _OS_TYPES_H */
  104392. /*** End of inlined file: os_types.h ***/
  104393. typedef struct {
  104394. long endbyte;
  104395. int endbit;
  104396. unsigned char *buffer;
  104397. unsigned char *ptr;
  104398. long storage;
  104399. } oggpack_buffer;
  104400. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  104401. typedef struct {
  104402. unsigned char *header;
  104403. long header_len;
  104404. unsigned char *body;
  104405. long body_len;
  104406. } ogg_page;
  104407. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  104408. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  104409. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  104410. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  104411. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  104412. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  104413. }
  104414. /* ogg_stream_state contains the current encode/decode state of a logical
  104415. Ogg bitstream **********************************************************/
  104416. typedef struct {
  104417. unsigned char *body_data; /* bytes from packet bodies */
  104418. long body_storage; /* storage elements allocated */
  104419. long body_fill; /* elements stored; fill mark */
  104420. long body_returned; /* elements of fill returned */
  104421. int *lacing_vals; /* The values that will go to the segment table */
  104422. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  104423. this way, but it is simple coupled to the
  104424. lacing fifo */
  104425. long lacing_storage;
  104426. long lacing_fill;
  104427. long lacing_packet;
  104428. long lacing_returned;
  104429. unsigned char header[282]; /* working space for header encode */
  104430. int header_fill;
  104431. int e_o_s; /* set when we have buffered the last packet in the
  104432. logical bitstream */
  104433. int b_o_s; /* set after we've written the initial page
  104434. of a logical bitstream */
  104435. long serialno;
  104436. long pageno;
  104437. ogg_int64_t packetno; /* sequence number for decode; the framing
  104438. knows where there's a hole in the data,
  104439. but we need coupling so that the codec
  104440. (which is in a seperate abstraction
  104441. layer) also knows about the gap */
  104442. ogg_int64_t granulepos;
  104443. } ogg_stream_state;
  104444. /* ogg_packet is used to encapsulate the data and metadata belonging
  104445. to a single raw Ogg/Vorbis packet *************************************/
  104446. typedef struct {
  104447. unsigned char *packet;
  104448. long bytes;
  104449. long b_o_s;
  104450. long e_o_s;
  104451. ogg_int64_t granulepos;
  104452. ogg_int64_t packetno; /* sequence number for decode; the framing
  104453. knows where there's a hole in the data,
  104454. but we need coupling so that the codec
  104455. (which is in a seperate abstraction
  104456. layer) also knows about the gap */
  104457. } ogg_packet;
  104458. typedef struct {
  104459. unsigned char *data;
  104460. int storage;
  104461. int fill;
  104462. int returned;
  104463. int unsynced;
  104464. int headerbytes;
  104465. int bodybytes;
  104466. } ogg_sync_state;
  104467. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  104468. extern void oggpack_writeinit(oggpack_buffer *b);
  104469. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  104470. extern void oggpack_writealign(oggpack_buffer *b);
  104471. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  104472. extern void oggpack_reset(oggpack_buffer *b);
  104473. extern void oggpack_writeclear(oggpack_buffer *b);
  104474. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  104475. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  104476. extern long oggpack_look(oggpack_buffer *b,int bits);
  104477. extern long oggpack_look1(oggpack_buffer *b);
  104478. extern void oggpack_adv(oggpack_buffer *b,int bits);
  104479. extern void oggpack_adv1(oggpack_buffer *b);
  104480. extern long oggpack_read(oggpack_buffer *b,int bits);
  104481. extern long oggpack_read1(oggpack_buffer *b);
  104482. extern long oggpack_bytes(oggpack_buffer *b);
  104483. extern long oggpack_bits(oggpack_buffer *b);
  104484. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  104485. extern void oggpackB_writeinit(oggpack_buffer *b);
  104486. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  104487. extern void oggpackB_writealign(oggpack_buffer *b);
  104488. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  104489. extern void oggpackB_reset(oggpack_buffer *b);
  104490. extern void oggpackB_writeclear(oggpack_buffer *b);
  104491. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  104492. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  104493. extern long oggpackB_look(oggpack_buffer *b,int bits);
  104494. extern long oggpackB_look1(oggpack_buffer *b);
  104495. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  104496. extern void oggpackB_adv1(oggpack_buffer *b);
  104497. extern long oggpackB_read(oggpack_buffer *b,int bits);
  104498. extern long oggpackB_read1(oggpack_buffer *b);
  104499. extern long oggpackB_bytes(oggpack_buffer *b);
  104500. extern long oggpackB_bits(oggpack_buffer *b);
  104501. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  104502. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  104503. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  104504. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  104505. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  104506. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  104507. extern int ogg_sync_init(ogg_sync_state *oy);
  104508. extern int ogg_sync_clear(ogg_sync_state *oy);
  104509. extern int ogg_sync_reset(ogg_sync_state *oy);
  104510. extern int ogg_sync_destroy(ogg_sync_state *oy);
  104511. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  104512. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  104513. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  104514. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  104515. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  104516. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  104517. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  104518. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  104519. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  104520. extern int ogg_stream_clear(ogg_stream_state *os);
  104521. extern int ogg_stream_reset(ogg_stream_state *os);
  104522. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  104523. extern int ogg_stream_destroy(ogg_stream_state *os);
  104524. extern int ogg_stream_eos(ogg_stream_state *os);
  104525. extern void ogg_page_checksum_set(ogg_page *og);
  104526. extern int ogg_page_version(ogg_page *og);
  104527. extern int ogg_page_continued(ogg_page *og);
  104528. extern int ogg_page_bos(ogg_page *og);
  104529. extern int ogg_page_eos(ogg_page *og);
  104530. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  104531. extern int ogg_page_serialno(ogg_page *og);
  104532. extern long ogg_page_pageno(ogg_page *og);
  104533. extern int ogg_page_packets(ogg_page *og);
  104534. extern void ogg_packet_clear(ogg_packet *op);
  104535. #ifdef __cplusplus
  104536. }
  104537. #endif
  104538. #endif /* _OGG_H */
  104539. /*** End of inlined file: ogg.h ***/
  104540. typedef struct vorbis_info{
  104541. int version;
  104542. int channels;
  104543. long rate;
  104544. /* The below bitrate declarations are *hints*.
  104545. Combinations of the three values carry the following implications:
  104546. all three set to the same value:
  104547. implies a fixed rate bitstream
  104548. only nominal set:
  104549. implies a VBR stream that averages the nominal bitrate. No hard
  104550. upper/lower limit
  104551. upper and or lower set:
  104552. implies a VBR bitstream that obeys the bitrate limits. nominal
  104553. may also be set to give a nominal rate.
  104554. none set:
  104555. the coder does not care to speculate.
  104556. */
  104557. long bitrate_upper;
  104558. long bitrate_nominal;
  104559. long bitrate_lower;
  104560. long bitrate_window;
  104561. void *codec_setup;
  104562. } vorbis_info;
  104563. /* vorbis_dsp_state buffers the current vorbis audio
  104564. analysis/synthesis state. The DSP state belongs to a specific
  104565. logical bitstream ****************************************************/
  104566. typedef struct vorbis_dsp_state{
  104567. int analysisp;
  104568. vorbis_info *vi;
  104569. float **pcm;
  104570. float **pcmret;
  104571. int pcm_storage;
  104572. int pcm_current;
  104573. int pcm_returned;
  104574. int preextrapolate;
  104575. int eofflag;
  104576. long lW;
  104577. long W;
  104578. long nW;
  104579. long centerW;
  104580. ogg_int64_t granulepos;
  104581. ogg_int64_t sequence;
  104582. ogg_int64_t glue_bits;
  104583. ogg_int64_t time_bits;
  104584. ogg_int64_t floor_bits;
  104585. ogg_int64_t res_bits;
  104586. void *backend_state;
  104587. } vorbis_dsp_state;
  104588. typedef struct vorbis_block{
  104589. /* necessary stream state for linking to the framing abstraction */
  104590. float **pcm; /* this is a pointer into local storage */
  104591. oggpack_buffer opb;
  104592. long lW;
  104593. long W;
  104594. long nW;
  104595. int pcmend;
  104596. int mode;
  104597. int eofflag;
  104598. ogg_int64_t granulepos;
  104599. ogg_int64_t sequence;
  104600. vorbis_dsp_state *vd; /* For read-only access of configuration */
  104601. /* local storage to avoid remallocing; it's up to the mapping to
  104602. structure it */
  104603. void *localstore;
  104604. long localtop;
  104605. long localalloc;
  104606. long totaluse;
  104607. struct alloc_chain *reap;
  104608. /* bitmetrics for the frame */
  104609. long glue_bits;
  104610. long time_bits;
  104611. long floor_bits;
  104612. long res_bits;
  104613. void *internal;
  104614. } vorbis_block;
  104615. /* vorbis_block is a single block of data to be processed as part of
  104616. the analysis/synthesis stream; it belongs to a specific logical
  104617. bitstream, but is independant from other vorbis_blocks belonging to
  104618. that logical bitstream. *************************************************/
  104619. struct alloc_chain{
  104620. void *ptr;
  104621. struct alloc_chain *next;
  104622. };
  104623. /* vorbis_info contains all the setup information specific to the
  104624. specific compression/decompression mode in progress (eg,
  104625. psychoacoustic settings, channel setup, options, codebook
  104626. etc). vorbis_info and substructures are in backends.h.
  104627. *********************************************************************/
  104628. /* the comments are not part of vorbis_info so that vorbis_info can be
  104629. static storage */
  104630. typedef struct vorbis_comment{
  104631. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  104632. whatever vendor is set to in encode */
  104633. char **user_comments;
  104634. int *comment_lengths;
  104635. int comments;
  104636. char *vendor;
  104637. } vorbis_comment;
  104638. /* libvorbis encodes in two abstraction layers; first we perform DSP
  104639. and produce a packet (see docs/analysis.txt). The packet is then
  104640. coded into a framed OggSquish bitstream by the second layer (see
  104641. docs/framing.txt). Decode is the reverse process; we sync/frame
  104642. the bitstream and extract individual packets, then decode the
  104643. packet back into PCM audio.
  104644. The extra framing/packetizing is used in streaming formats, such as
  104645. files. Over the net (such as with UDP), the framing and
  104646. packetization aren't necessary as they're provided by the transport
  104647. and the streaming layer is not used */
  104648. /* Vorbis PRIMITIVES: general ***************************************/
  104649. extern void vorbis_info_init(vorbis_info *vi);
  104650. extern void vorbis_info_clear(vorbis_info *vi);
  104651. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  104652. extern void vorbis_comment_init(vorbis_comment *vc);
  104653. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  104654. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  104655. const char *tag, char *contents);
  104656. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  104657. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  104658. extern void vorbis_comment_clear(vorbis_comment *vc);
  104659. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  104660. extern int vorbis_block_clear(vorbis_block *vb);
  104661. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  104662. extern double vorbis_granule_time(vorbis_dsp_state *v,
  104663. ogg_int64_t granulepos);
  104664. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  104665. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  104666. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  104667. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  104668. vorbis_comment *vc,
  104669. ogg_packet *op,
  104670. ogg_packet *op_comm,
  104671. ogg_packet *op_code);
  104672. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  104673. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  104674. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  104675. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  104676. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  104677. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  104678. ogg_packet *op);
  104679. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  104680. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  104681. ogg_packet *op);
  104682. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  104683. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  104684. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  104685. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  104686. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  104687. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  104688. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  104689. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  104690. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  104691. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  104692. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  104693. /* Vorbis ERRORS and return codes ***********************************/
  104694. #define OV_FALSE -1
  104695. #define OV_EOF -2
  104696. #define OV_HOLE -3
  104697. #define OV_EREAD -128
  104698. #define OV_EFAULT -129
  104699. #define OV_EIMPL -130
  104700. #define OV_EINVAL -131
  104701. #define OV_ENOTVORBIS -132
  104702. #define OV_EBADHEADER -133
  104703. #define OV_EVERSION -134
  104704. #define OV_ENOTAUDIO -135
  104705. #define OV_EBADPACKET -136
  104706. #define OV_EBADLINK -137
  104707. #define OV_ENOSEEK -138
  104708. #ifdef __cplusplus
  104709. }
  104710. #endif /* __cplusplus */
  104711. #endif
  104712. /*** End of inlined file: codec.h ***/
  104713. extern int vorbis_encode_init(vorbis_info *vi,
  104714. long channels,
  104715. long rate,
  104716. long max_bitrate,
  104717. long nominal_bitrate,
  104718. long min_bitrate);
  104719. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  104720. long channels,
  104721. long rate,
  104722. long max_bitrate,
  104723. long nominal_bitrate,
  104724. long min_bitrate);
  104725. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  104726. long channels,
  104727. long rate,
  104728. float quality /* quality level from 0. (lo) to 1. (hi) */
  104729. );
  104730. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  104731. long channels,
  104732. long rate,
  104733. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  104734. );
  104735. extern int vorbis_encode_setup_init(vorbis_info *vi);
  104736. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  104737. /* deprecated rate management supported only for compatability */
  104738. #define OV_ECTL_RATEMANAGE_GET 0x10
  104739. #define OV_ECTL_RATEMANAGE_SET 0x11
  104740. #define OV_ECTL_RATEMANAGE_AVG 0x12
  104741. #define OV_ECTL_RATEMANAGE_HARD 0x13
  104742. struct ovectl_ratemanage_arg {
  104743. int management_active;
  104744. long bitrate_hard_min;
  104745. long bitrate_hard_max;
  104746. double bitrate_hard_window;
  104747. long bitrate_av_lo;
  104748. long bitrate_av_hi;
  104749. double bitrate_av_window;
  104750. double bitrate_av_window_center;
  104751. };
  104752. /* new rate setup */
  104753. #define OV_ECTL_RATEMANAGE2_GET 0x14
  104754. #define OV_ECTL_RATEMANAGE2_SET 0x15
  104755. struct ovectl_ratemanage2_arg {
  104756. int management_active;
  104757. long bitrate_limit_min_kbps;
  104758. long bitrate_limit_max_kbps;
  104759. long bitrate_limit_reservoir_bits;
  104760. double bitrate_limit_reservoir_bias;
  104761. long bitrate_average_kbps;
  104762. double bitrate_average_damping;
  104763. };
  104764. #define OV_ECTL_LOWPASS_GET 0x20
  104765. #define OV_ECTL_LOWPASS_SET 0x21
  104766. #define OV_ECTL_IBLOCK_GET 0x30
  104767. #define OV_ECTL_IBLOCK_SET 0x31
  104768. #ifdef __cplusplus
  104769. }
  104770. #endif /* __cplusplus */
  104771. #endif
  104772. /*** End of inlined file: vorbisenc.h ***/
  104773. /*** Start of inlined file: vorbisfile.h ***/
  104774. #ifndef _OV_FILE_H_
  104775. #define _OV_FILE_H_
  104776. #ifdef __cplusplus
  104777. extern "C"
  104778. {
  104779. #endif /* __cplusplus */
  104780. #include <stdio.h>
  104781. /* The function prototypes for the callbacks are basically the same as for
  104782. * the stdio functions fread, fseek, fclose, ftell.
  104783. * The one difference is that the FILE * arguments have been replaced with
  104784. * a void * - this is to be used as a pointer to whatever internal data these
  104785. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  104786. *
  104787. * If you use other functions, check the docs for these functions and return
  104788. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  104789. * unseekable
  104790. */
  104791. typedef struct {
  104792. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  104793. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  104794. int (*close_func) (void *datasource);
  104795. long (*tell_func) (void *datasource);
  104796. } ov_callbacks;
  104797. #define NOTOPEN 0
  104798. #define PARTOPEN 1
  104799. #define OPENED 2
  104800. #define STREAMSET 3
  104801. #define INITSET 4
  104802. typedef struct OggVorbis_File {
  104803. void *datasource; /* Pointer to a FILE *, etc. */
  104804. int seekable;
  104805. ogg_int64_t offset;
  104806. ogg_int64_t end;
  104807. ogg_sync_state oy;
  104808. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  104809. stream appears */
  104810. int links;
  104811. ogg_int64_t *offsets;
  104812. ogg_int64_t *dataoffsets;
  104813. long *serialnos;
  104814. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  104815. compatability; x2 size, stores both
  104816. beginning and end values */
  104817. vorbis_info *vi;
  104818. vorbis_comment *vc;
  104819. /* Decoding working state local storage */
  104820. ogg_int64_t pcm_offset;
  104821. int ready_state;
  104822. long current_serialno;
  104823. int current_link;
  104824. double bittrack;
  104825. double samptrack;
  104826. ogg_stream_state os; /* take physical pages, weld into a logical
  104827. stream of packets */
  104828. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  104829. vorbis_block vb; /* local working space for packet->PCM decode */
  104830. ov_callbacks callbacks;
  104831. } OggVorbis_File;
  104832. extern int ov_clear(OggVorbis_File *vf);
  104833. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  104834. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  104835. char *initial, long ibytes, ov_callbacks callbacks);
  104836. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  104837. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  104838. char *initial, long ibytes, ov_callbacks callbacks);
  104839. extern int ov_test_open(OggVorbis_File *vf);
  104840. extern long ov_bitrate(OggVorbis_File *vf,int i);
  104841. extern long ov_bitrate_instant(OggVorbis_File *vf);
  104842. extern long ov_streams(OggVorbis_File *vf);
  104843. extern long ov_seekable(OggVorbis_File *vf);
  104844. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  104845. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  104846. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  104847. extern double ov_time_total(OggVorbis_File *vf,int i);
  104848. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  104849. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  104850. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  104851. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  104852. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  104853. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  104854. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  104855. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  104856. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  104857. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  104858. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  104859. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  104860. extern double ov_time_tell(OggVorbis_File *vf);
  104861. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  104862. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  104863. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  104864. int *bitstream);
  104865. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  104866. int bigendianp,int word,int sgned,int *bitstream);
  104867. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  104868. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  104869. extern int ov_halfrate_p(OggVorbis_File *vf);
  104870. #ifdef __cplusplus
  104871. }
  104872. #endif /* __cplusplus */
  104873. #endif
  104874. /*** End of inlined file: vorbisfile.h ***/
  104875. /*** Start of inlined file: bitwise.c ***/
  104876. /* We're 'LSb' endian; if we write a word but read individual bits,
  104877. then we'll read the lsb first */
  104878. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  104879. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  104880. // tasks..
  104881. #if JUCE_MSVC
  104882. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  104883. #endif
  104884. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  104885. #if JUCE_USE_OGGVORBIS
  104886. #include <string.h>
  104887. #include <stdlib.h>
  104888. #define BUFFER_INCREMENT 256
  104889. static const unsigned long mask[]=
  104890. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  104891. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  104892. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  104893. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  104894. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  104895. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  104896. 0x3fffffff,0x7fffffff,0xffffffff };
  104897. static const unsigned int mask8B[]=
  104898. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  104899. void oggpack_writeinit(oggpack_buffer *b){
  104900. memset(b,0,sizeof(*b));
  104901. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  104902. b->buffer[0]='\0';
  104903. b->storage=BUFFER_INCREMENT;
  104904. }
  104905. void oggpackB_writeinit(oggpack_buffer *b){
  104906. oggpack_writeinit(b);
  104907. }
  104908. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  104909. long bytes=bits>>3;
  104910. bits-=bytes*8;
  104911. b->ptr=b->buffer+bytes;
  104912. b->endbit=bits;
  104913. b->endbyte=bytes;
  104914. *b->ptr&=mask[bits];
  104915. }
  104916. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  104917. long bytes=bits>>3;
  104918. bits-=bytes*8;
  104919. b->ptr=b->buffer+bytes;
  104920. b->endbit=bits;
  104921. b->endbyte=bytes;
  104922. *b->ptr&=mask8B[bits];
  104923. }
  104924. /* Takes only up to 32 bits. */
  104925. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  104926. if(b->endbyte+4>=b->storage){
  104927. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  104928. b->storage+=BUFFER_INCREMENT;
  104929. b->ptr=b->buffer+b->endbyte;
  104930. }
  104931. value&=mask[bits];
  104932. bits+=b->endbit;
  104933. b->ptr[0]|=value<<b->endbit;
  104934. if(bits>=8){
  104935. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  104936. if(bits>=16){
  104937. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  104938. if(bits>=24){
  104939. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  104940. if(bits>=32){
  104941. if(b->endbit)
  104942. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  104943. else
  104944. b->ptr[4]=0;
  104945. }
  104946. }
  104947. }
  104948. }
  104949. b->endbyte+=bits/8;
  104950. b->ptr+=bits/8;
  104951. b->endbit=bits&7;
  104952. }
  104953. /* Takes only up to 32 bits. */
  104954. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  104955. if(b->endbyte+4>=b->storage){
  104956. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  104957. b->storage+=BUFFER_INCREMENT;
  104958. b->ptr=b->buffer+b->endbyte;
  104959. }
  104960. value=(value&mask[bits])<<(32-bits);
  104961. bits+=b->endbit;
  104962. b->ptr[0]|=value>>(24+b->endbit);
  104963. if(bits>=8){
  104964. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  104965. if(bits>=16){
  104966. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  104967. if(bits>=24){
  104968. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  104969. if(bits>=32){
  104970. if(b->endbit)
  104971. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  104972. else
  104973. b->ptr[4]=0;
  104974. }
  104975. }
  104976. }
  104977. }
  104978. b->endbyte+=bits/8;
  104979. b->ptr+=bits/8;
  104980. b->endbit=bits&7;
  104981. }
  104982. void oggpack_writealign(oggpack_buffer *b){
  104983. int bits=8-b->endbit;
  104984. if(bits<8)
  104985. oggpack_write(b,0,bits);
  104986. }
  104987. void oggpackB_writealign(oggpack_buffer *b){
  104988. int bits=8-b->endbit;
  104989. if(bits<8)
  104990. oggpackB_write(b,0,bits);
  104991. }
  104992. static void oggpack_writecopy_helper(oggpack_buffer *b,
  104993. void *source,
  104994. long bits,
  104995. void (*w)(oggpack_buffer *,
  104996. unsigned long,
  104997. int),
  104998. int msb){
  104999. unsigned char *ptr=(unsigned char *)source;
  105000. long bytes=bits/8;
  105001. bits-=bytes*8;
  105002. if(b->endbit){
  105003. int i;
  105004. /* unaligned copy. Do it the hard way. */
  105005. for(i=0;i<bytes;i++)
  105006. w(b,(unsigned long)(ptr[i]),8);
  105007. }else{
  105008. /* aligned block copy */
  105009. if(b->endbyte+bytes+1>=b->storage){
  105010. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  105011. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  105012. b->ptr=b->buffer+b->endbyte;
  105013. }
  105014. memmove(b->ptr,source,bytes);
  105015. b->ptr+=bytes;
  105016. b->endbyte+=bytes;
  105017. *b->ptr=0;
  105018. }
  105019. if(bits){
  105020. if(msb)
  105021. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  105022. else
  105023. w(b,(unsigned long)(ptr[bytes]),bits);
  105024. }
  105025. }
  105026. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  105027. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  105028. }
  105029. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  105030. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  105031. }
  105032. void oggpack_reset(oggpack_buffer *b){
  105033. b->ptr=b->buffer;
  105034. b->buffer[0]=0;
  105035. b->endbit=b->endbyte=0;
  105036. }
  105037. void oggpackB_reset(oggpack_buffer *b){
  105038. oggpack_reset(b);
  105039. }
  105040. void oggpack_writeclear(oggpack_buffer *b){
  105041. _ogg_free(b->buffer);
  105042. memset(b,0,sizeof(*b));
  105043. }
  105044. void oggpackB_writeclear(oggpack_buffer *b){
  105045. oggpack_writeclear(b);
  105046. }
  105047. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  105048. memset(b,0,sizeof(*b));
  105049. b->buffer=b->ptr=buf;
  105050. b->storage=bytes;
  105051. }
  105052. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  105053. oggpack_readinit(b,buf,bytes);
  105054. }
  105055. /* Read in bits without advancing the bitptr; bits <= 32 */
  105056. long oggpack_look(oggpack_buffer *b,int bits){
  105057. unsigned long ret;
  105058. unsigned long m=mask[bits];
  105059. bits+=b->endbit;
  105060. if(b->endbyte+4>=b->storage){
  105061. /* not the main path */
  105062. if(b->endbyte*8+bits>b->storage*8)return(-1);
  105063. }
  105064. ret=b->ptr[0]>>b->endbit;
  105065. if(bits>8){
  105066. ret|=b->ptr[1]<<(8-b->endbit);
  105067. if(bits>16){
  105068. ret|=b->ptr[2]<<(16-b->endbit);
  105069. if(bits>24){
  105070. ret|=b->ptr[3]<<(24-b->endbit);
  105071. if(bits>32 && b->endbit)
  105072. ret|=b->ptr[4]<<(32-b->endbit);
  105073. }
  105074. }
  105075. }
  105076. return(m&ret);
  105077. }
  105078. /* Read in bits without advancing the bitptr; bits <= 32 */
  105079. long oggpackB_look(oggpack_buffer *b,int bits){
  105080. unsigned long ret;
  105081. int m=32-bits;
  105082. bits+=b->endbit;
  105083. if(b->endbyte+4>=b->storage){
  105084. /* not the main path */
  105085. if(b->endbyte*8+bits>b->storage*8)return(-1);
  105086. }
  105087. ret=b->ptr[0]<<(24+b->endbit);
  105088. if(bits>8){
  105089. ret|=b->ptr[1]<<(16+b->endbit);
  105090. if(bits>16){
  105091. ret|=b->ptr[2]<<(8+b->endbit);
  105092. if(bits>24){
  105093. ret|=b->ptr[3]<<(b->endbit);
  105094. if(bits>32 && b->endbit)
  105095. ret|=b->ptr[4]>>(8-b->endbit);
  105096. }
  105097. }
  105098. }
  105099. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  105100. }
  105101. long oggpack_look1(oggpack_buffer *b){
  105102. if(b->endbyte>=b->storage)return(-1);
  105103. return((b->ptr[0]>>b->endbit)&1);
  105104. }
  105105. long oggpackB_look1(oggpack_buffer *b){
  105106. if(b->endbyte>=b->storage)return(-1);
  105107. return((b->ptr[0]>>(7-b->endbit))&1);
  105108. }
  105109. void oggpack_adv(oggpack_buffer *b,int bits){
  105110. bits+=b->endbit;
  105111. b->ptr+=bits/8;
  105112. b->endbyte+=bits/8;
  105113. b->endbit=bits&7;
  105114. }
  105115. void oggpackB_adv(oggpack_buffer *b,int bits){
  105116. oggpack_adv(b,bits);
  105117. }
  105118. void oggpack_adv1(oggpack_buffer *b){
  105119. if(++(b->endbit)>7){
  105120. b->endbit=0;
  105121. b->ptr++;
  105122. b->endbyte++;
  105123. }
  105124. }
  105125. void oggpackB_adv1(oggpack_buffer *b){
  105126. oggpack_adv1(b);
  105127. }
  105128. /* bits <= 32 */
  105129. long oggpack_read(oggpack_buffer *b,int bits){
  105130. long ret;
  105131. unsigned long m=mask[bits];
  105132. bits+=b->endbit;
  105133. if(b->endbyte+4>=b->storage){
  105134. /* not the main path */
  105135. ret=-1L;
  105136. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  105137. }
  105138. ret=b->ptr[0]>>b->endbit;
  105139. if(bits>8){
  105140. ret|=b->ptr[1]<<(8-b->endbit);
  105141. if(bits>16){
  105142. ret|=b->ptr[2]<<(16-b->endbit);
  105143. if(bits>24){
  105144. ret|=b->ptr[3]<<(24-b->endbit);
  105145. if(bits>32 && b->endbit){
  105146. ret|=b->ptr[4]<<(32-b->endbit);
  105147. }
  105148. }
  105149. }
  105150. }
  105151. ret&=m;
  105152. overflow:
  105153. b->ptr+=bits/8;
  105154. b->endbyte+=bits/8;
  105155. b->endbit=bits&7;
  105156. return(ret);
  105157. }
  105158. /* bits <= 32 */
  105159. long oggpackB_read(oggpack_buffer *b,int bits){
  105160. long ret;
  105161. long m=32-bits;
  105162. bits+=b->endbit;
  105163. if(b->endbyte+4>=b->storage){
  105164. /* not the main path */
  105165. ret=-1L;
  105166. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  105167. }
  105168. ret=b->ptr[0]<<(24+b->endbit);
  105169. if(bits>8){
  105170. ret|=b->ptr[1]<<(16+b->endbit);
  105171. if(bits>16){
  105172. ret|=b->ptr[2]<<(8+b->endbit);
  105173. if(bits>24){
  105174. ret|=b->ptr[3]<<(b->endbit);
  105175. if(bits>32 && b->endbit)
  105176. ret|=b->ptr[4]>>(8-b->endbit);
  105177. }
  105178. }
  105179. }
  105180. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  105181. overflow:
  105182. b->ptr+=bits/8;
  105183. b->endbyte+=bits/8;
  105184. b->endbit=bits&7;
  105185. return(ret);
  105186. }
  105187. long oggpack_read1(oggpack_buffer *b){
  105188. long ret;
  105189. if(b->endbyte>=b->storage){
  105190. /* not the main path */
  105191. ret=-1L;
  105192. goto overflow;
  105193. }
  105194. ret=(b->ptr[0]>>b->endbit)&1;
  105195. overflow:
  105196. b->endbit++;
  105197. if(b->endbit>7){
  105198. b->endbit=0;
  105199. b->ptr++;
  105200. b->endbyte++;
  105201. }
  105202. return(ret);
  105203. }
  105204. long oggpackB_read1(oggpack_buffer *b){
  105205. long ret;
  105206. if(b->endbyte>=b->storage){
  105207. /* not the main path */
  105208. ret=-1L;
  105209. goto overflow;
  105210. }
  105211. ret=(b->ptr[0]>>(7-b->endbit))&1;
  105212. overflow:
  105213. b->endbit++;
  105214. if(b->endbit>7){
  105215. b->endbit=0;
  105216. b->ptr++;
  105217. b->endbyte++;
  105218. }
  105219. return(ret);
  105220. }
  105221. long oggpack_bytes(oggpack_buffer *b){
  105222. return(b->endbyte+(b->endbit+7)/8);
  105223. }
  105224. long oggpack_bits(oggpack_buffer *b){
  105225. return(b->endbyte*8+b->endbit);
  105226. }
  105227. long oggpackB_bytes(oggpack_buffer *b){
  105228. return oggpack_bytes(b);
  105229. }
  105230. long oggpackB_bits(oggpack_buffer *b){
  105231. return oggpack_bits(b);
  105232. }
  105233. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  105234. return(b->buffer);
  105235. }
  105236. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  105237. return oggpack_get_buffer(b);
  105238. }
  105239. /* Self test of the bitwise routines; everything else is based on
  105240. them, so they damned well better be solid. */
  105241. #ifdef _V_SELFTEST
  105242. #include <stdio.h>
  105243. static int ilog(unsigned int v){
  105244. int ret=0;
  105245. while(v){
  105246. ret++;
  105247. v>>=1;
  105248. }
  105249. return(ret);
  105250. }
  105251. oggpack_buffer o;
  105252. oggpack_buffer r;
  105253. void report(char *in){
  105254. fprintf(stderr,"%s",in);
  105255. exit(1);
  105256. }
  105257. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  105258. long bytes,i;
  105259. unsigned char *buffer;
  105260. oggpack_reset(&o);
  105261. for(i=0;i<vals;i++)
  105262. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  105263. buffer=oggpack_get_buffer(&o);
  105264. bytes=oggpack_bytes(&o);
  105265. if(bytes!=compsize)report("wrong number of bytes!\n");
  105266. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  105267. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  105268. report("wrote incorrect value!\n");
  105269. }
  105270. oggpack_readinit(&r,buffer,bytes);
  105271. for(i=0;i<vals;i++){
  105272. int tbit=bits?bits:ilog(b[i]);
  105273. if(oggpack_look(&r,tbit)==-1)
  105274. report("out of data!\n");
  105275. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  105276. report("looked at incorrect value!\n");
  105277. if(tbit==1)
  105278. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  105279. report("looked at single bit incorrect value!\n");
  105280. if(tbit==1){
  105281. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  105282. report("read incorrect single bit value!\n");
  105283. }else{
  105284. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  105285. report("read incorrect value!\n");
  105286. }
  105287. }
  105288. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  105289. }
  105290. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  105291. long bytes,i;
  105292. unsigned char *buffer;
  105293. oggpackB_reset(&o);
  105294. for(i=0;i<vals;i++)
  105295. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  105296. buffer=oggpackB_get_buffer(&o);
  105297. bytes=oggpackB_bytes(&o);
  105298. if(bytes!=compsize)report("wrong number of bytes!\n");
  105299. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  105300. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  105301. report("wrote incorrect value!\n");
  105302. }
  105303. oggpackB_readinit(&r,buffer,bytes);
  105304. for(i=0;i<vals;i++){
  105305. int tbit=bits?bits:ilog(b[i]);
  105306. if(oggpackB_look(&r,tbit)==-1)
  105307. report("out of data!\n");
  105308. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  105309. report("looked at incorrect value!\n");
  105310. if(tbit==1)
  105311. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  105312. report("looked at single bit incorrect value!\n");
  105313. if(tbit==1){
  105314. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  105315. report("read incorrect single bit value!\n");
  105316. }else{
  105317. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  105318. report("read incorrect value!\n");
  105319. }
  105320. }
  105321. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  105322. }
  105323. int main(void){
  105324. unsigned char *buffer;
  105325. long bytes,i;
  105326. static unsigned long testbuffer1[]=
  105327. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  105328. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  105329. int test1size=43;
  105330. static unsigned long testbuffer2[]=
  105331. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  105332. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  105333. 85525151,0,12321,1,349528352};
  105334. int test2size=21;
  105335. static unsigned long testbuffer3[]=
  105336. {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,
  105337. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  105338. int test3size=56;
  105339. static unsigned long large[]=
  105340. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  105341. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  105342. 85525151,0,12321,1,2146528352};
  105343. int onesize=33;
  105344. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  105345. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  105346. 223,4};
  105347. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  105348. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  105349. 245,251,128};
  105350. int twosize=6;
  105351. static int two[6]={61,255,255,251,231,29};
  105352. static int twoB[6]={247,63,255,253,249,120};
  105353. int threesize=54;
  105354. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  105355. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  105356. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  105357. 100,52,4,14,18,86,77,1};
  105358. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  105359. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  105360. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  105361. 200,20,254,4,58,106,176,144,0};
  105362. int foursize=38;
  105363. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  105364. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  105365. 28,2,133,0,1};
  105366. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  105367. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  105368. 129,10,4,32};
  105369. int fivesize=45;
  105370. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  105371. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  105372. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  105373. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  105374. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  105375. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  105376. int sixsize=7;
  105377. static int six[7]={17,177,170,242,169,19,148};
  105378. static int sixB[7]={136,141,85,79,149,200,41};
  105379. /* Test read/write together */
  105380. /* Later we test against pregenerated bitstreams */
  105381. oggpack_writeinit(&o);
  105382. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  105383. cliptest(testbuffer1,test1size,0,one,onesize);
  105384. fprintf(stderr,"ok.");
  105385. fprintf(stderr,"\nNull bit call (LSb): ");
  105386. cliptest(testbuffer3,test3size,0,two,twosize);
  105387. fprintf(stderr,"ok.");
  105388. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  105389. cliptest(testbuffer2,test2size,0,three,threesize);
  105390. fprintf(stderr,"ok.");
  105391. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  105392. oggpack_reset(&o);
  105393. for(i=0;i<test2size;i++)
  105394. oggpack_write(&o,large[i],32);
  105395. buffer=oggpack_get_buffer(&o);
  105396. bytes=oggpack_bytes(&o);
  105397. oggpack_readinit(&r,buffer,bytes);
  105398. for(i=0;i<test2size;i++){
  105399. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  105400. if(oggpack_look(&r,32)!=large[i]){
  105401. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  105402. oggpack_look(&r,32),large[i]);
  105403. report("read incorrect value!\n");
  105404. }
  105405. oggpack_adv(&r,32);
  105406. }
  105407. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  105408. fprintf(stderr,"ok.");
  105409. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  105410. cliptest(testbuffer1,test1size,7,four,foursize);
  105411. fprintf(stderr,"ok.");
  105412. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  105413. cliptest(testbuffer2,test2size,17,five,fivesize);
  105414. fprintf(stderr,"ok.");
  105415. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  105416. cliptest(testbuffer3,test3size,1,six,sixsize);
  105417. fprintf(stderr,"ok.");
  105418. fprintf(stderr,"\nTesting read past end (LSb): ");
  105419. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  105420. for(i=0;i<64;i++){
  105421. if(oggpack_read(&r,1)!=0){
  105422. fprintf(stderr,"failed; got -1 prematurely.\n");
  105423. exit(1);
  105424. }
  105425. }
  105426. if(oggpack_look(&r,1)!=-1 ||
  105427. oggpack_read(&r,1)!=-1){
  105428. fprintf(stderr,"failed; read past end without -1.\n");
  105429. exit(1);
  105430. }
  105431. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  105432. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  105433. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  105434. exit(1);
  105435. }
  105436. if(oggpack_look(&r,18)!=0 ||
  105437. oggpack_look(&r,18)!=0){
  105438. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  105439. exit(1);
  105440. }
  105441. if(oggpack_look(&r,19)!=-1 ||
  105442. oggpack_look(&r,19)!=-1){
  105443. fprintf(stderr,"failed; read past end without -1.\n");
  105444. exit(1);
  105445. }
  105446. if(oggpack_look(&r,32)!=-1 ||
  105447. oggpack_look(&r,32)!=-1){
  105448. fprintf(stderr,"failed; read past end without -1.\n");
  105449. exit(1);
  105450. }
  105451. oggpack_writeclear(&o);
  105452. fprintf(stderr,"ok.\n");
  105453. /********** lazy, cut-n-paste retest with MSb packing ***********/
  105454. /* Test read/write together */
  105455. /* Later we test against pregenerated bitstreams */
  105456. oggpackB_writeinit(&o);
  105457. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  105458. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  105459. fprintf(stderr,"ok.");
  105460. fprintf(stderr,"\nNull bit call (MSb): ");
  105461. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  105462. fprintf(stderr,"ok.");
  105463. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  105464. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  105465. fprintf(stderr,"ok.");
  105466. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  105467. oggpackB_reset(&o);
  105468. for(i=0;i<test2size;i++)
  105469. oggpackB_write(&o,large[i],32);
  105470. buffer=oggpackB_get_buffer(&o);
  105471. bytes=oggpackB_bytes(&o);
  105472. oggpackB_readinit(&r,buffer,bytes);
  105473. for(i=0;i<test2size;i++){
  105474. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  105475. if(oggpackB_look(&r,32)!=large[i]){
  105476. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  105477. oggpackB_look(&r,32),large[i]);
  105478. report("read incorrect value!\n");
  105479. }
  105480. oggpackB_adv(&r,32);
  105481. }
  105482. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  105483. fprintf(stderr,"ok.");
  105484. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  105485. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  105486. fprintf(stderr,"ok.");
  105487. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  105488. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  105489. fprintf(stderr,"ok.");
  105490. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  105491. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  105492. fprintf(stderr,"ok.");
  105493. fprintf(stderr,"\nTesting read past end (MSb): ");
  105494. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  105495. for(i=0;i<64;i++){
  105496. if(oggpackB_read(&r,1)!=0){
  105497. fprintf(stderr,"failed; got -1 prematurely.\n");
  105498. exit(1);
  105499. }
  105500. }
  105501. if(oggpackB_look(&r,1)!=-1 ||
  105502. oggpackB_read(&r,1)!=-1){
  105503. fprintf(stderr,"failed; read past end without -1.\n");
  105504. exit(1);
  105505. }
  105506. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  105507. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  105508. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  105509. exit(1);
  105510. }
  105511. if(oggpackB_look(&r,18)!=0 ||
  105512. oggpackB_look(&r,18)!=0){
  105513. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  105514. exit(1);
  105515. }
  105516. if(oggpackB_look(&r,19)!=-1 ||
  105517. oggpackB_look(&r,19)!=-1){
  105518. fprintf(stderr,"failed; read past end without -1.\n");
  105519. exit(1);
  105520. }
  105521. if(oggpackB_look(&r,32)!=-1 ||
  105522. oggpackB_look(&r,32)!=-1){
  105523. fprintf(stderr,"failed; read past end without -1.\n");
  105524. exit(1);
  105525. }
  105526. oggpackB_writeclear(&o);
  105527. fprintf(stderr,"ok.\n\n");
  105528. return(0);
  105529. }
  105530. #endif /* _V_SELFTEST */
  105531. #undef BUFFER_INCREMENT
  105532. #endif
  105533. /*** End of inlined file: bitwise.c ***/
  105534. /*** Start of inlined file: framing.c ***/
  105535. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  105536. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  105537. // tasks..
  105538. #if JUCE_MSVC
  105539. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  105540. #endif
  105541. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  105542. #if JUCE_USE_OGGVORBIS
  105543. #include <stdlib.h>
  105544. #include <string.h>
  105545. /* A complete description of Ogg framing exists in docs/framing.html */
  105546. int ogg_page_version(ogg_page *og){
  105547. return((int)(og->header[4]));
  105548. }
  105549. int ogg_page_continued(ogg_page *og){
  105550. return((int)(og->header[5]&0x01));
  105551. }
  105552. int ogg_page_bos(ogg_page *og){
  105553. return((int)(og->header[5]&0x02));
  105554. }
  105555. int ogg_page_eos(ogg_page *og){
  105556. return((int)(og->header[5]&0x04));
  105557. }
  105558. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  105559. unsigned char *page=og->header;
  105560. ogg_int64_t granulepos=page[13]&(0xff);
  105561. granulepos= (granulepos<<8)|(page[12]&0xff);
  105562. granulepos= (granulepos<<8)|(page[11]&0xff);
  105563. granulepos= (granulepos<<8)|(page[10]&0xff);
  105564. granulepos= (granulepos<<8)|(page[9]&0xff);
  105565. granulepos= (granulepos<<8)|(page[8]&0xff);
  105566. granulepos= (granulepos<<8)|(page[7]&0xff);
  105567. granulepos= (granulepos<<8)|(page[6]&0xff);
  105568. return(granulepos);
  105569. }
  105570. int ogg_page_serialno(ogg_page *og){
  105571. return(og->header[14] |
  105572. (og->header[15]<<8) |
  105573. (og->header[16]<<16) |
  105574. (og->header[17]<<24));
  105575. }
  105576. long ogg_page_pageno(ogg_page *og){
  105577. return(og->header[18] |
  105578. (og->header[19]<<8) |
  105579. (og->header[20]<<16) |
  105580. (og->header[21]<<24));
  105581. }
  105582. /* returns the number of packets that are completed on this page (if
  105583. the leading packet is begun on a previous page, but ends on this
  105584. page, it's counted */
  105585. /* NOTE:
  105586. If a page consists of a packet begun on a previous page, and a new
  105587. packet begun (but not completed) on this page, the return will be:
  105588. ogg_page_packets(page) ==1,
  105589. ogg_page_continued(page) !=0
  105590. If a page happens to be a single packet that was begun on a
  105591. previous page, and spans to the next page (in the case of a three or
  105592. more page packet), the return will be:
  105593. ogg_page_packets(page) ==0,
  105594. ogg_page_continued(page) !=0
  105595. */
  105596. int ogg_page_packets(ogg_page *og){
  105597. int i,n=og->header[26],count=0;
  105598. for(i=0;i<n;i++)
  105599. if(og->header[27+i]<255)count++;
  105600. return(count);
  105601. }
  105602. #if 0
  105603. /* helper to initialize lookup for direct-table CRC (illustrative; we
  105604. use the static init below) */
  105605. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  105606. int i;
  105607. unsigned long r;
  105608. r = index << 24;
  105609. for (i=0; i<8; i++)
  105610. if (r & 0x80000000UL)
  105611. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  105612. polynomial, although we use an
  105613. unreflected alg and an init/final
  105614. of 0, not 0xffffffff */
  105615. else
  105616. r<<=1;
  105617. return (r & 0xffffffffUL);
  105618. }
  105619. #endif
  105620. static const ogg_uint32_t crc_lookup[256]={
  105621. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  105622. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  105623. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  105624. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  105625. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  105626. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  105627. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  105628. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  105629. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  105630. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  105631. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  105632. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  105633. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  105634. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  105635. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  105636. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  105637. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  105638. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  105639. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  105640. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  105641. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  105642. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  105643. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  105644. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  105645. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  105646. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  105647. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  105648. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  105649. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  105650. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  105651. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  105652. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  105653. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  105654. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  105655. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  105656. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  105657. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  105658. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  105659. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  105660. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  105661. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  105662. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  105663. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  105664. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  105665. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  105666. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  105667. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  105668. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  105669. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  105670. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  105671. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  105672. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  105673. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  105674. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  105675. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  105676. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  105677. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  105678. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  105679. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  105680. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  105681. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  105682. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  105683. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  105684. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  105685. /* init the encode/decode logical stream state */
  105686. int ogg_stream_init(ogg_stream_state *os,int serialno){
  105687. if(os){
  105688. memset(os,0,sizeof(*os));
  105689. os->body_storage=16*1024;
  105690. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  105691. os->lacing_storage=1024;
  105692. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  105693. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  105694. os->serialno=serialno;
  105695. return(0);
  105696. }
  105697. return(-1);
  105698. }
  105699. /* _clear does not free os, only the non-flat storage within */
  105700. int ogg_stream_clear(ogg_stream_state *os){
  105701. if(os){
  105702. if(os->body_data)_ogg_free(os->body_data);
  105703. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  105704. if(os->granule_vals)_ogg_free(os->granule_vals);
  105705. memset(os,0,sizeof(*os));
  105706. }
  105707. return(0);
  105708. }
  105709. int ogg_stream_destroy(ogg_stream_state *os){
  105710. if(os){
  105711. ogg_stream_clear(os);
  105712. _ogg_free(os);
  105713. }
  105714. return(0);
  105715. }
  105716. /* Helpers for ogg_stream_encode; this keeps the structure and
  105717. what's happening fairly clear */
  105718. static void _os_body_expand(ogg_stream_state *os,int needed){
  105719. if(os->body_storage<=os->body_fill+needed){
  105720. os->body_storage+=(needed+1024);
  105721. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  105722. }
  105723. }
  105724. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  105725. if(os->lacing_storage<=os->lacing_fill+needed){
  105726. os->lacing_storage+=(needed+32);
  105727. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  105728. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  105729. }
  105730. }
  105731. /* checksum the page */
  105732. /* Direct table CRC; note that this will be faster in the future if we
  105733. perform the checksum silmultaneously with other copies */
  105734. void ogg_page_checksum_set(ogg_page *og){
  105735. if(og){
  105736. ogg_uint32_t crc_reg=0;
  105737. int i;
  105738. /* safety; needed for API behavior, but not framing code */
  105739. og->header[22]=0;
  105740. og->header[23]=0;
  105741. og->header[24]=0;
  105742. og->header[25]=0;
  105743. for(i=0;i<og->header_len;i++)
  105744. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  105745. for(i=0;i<og->body_len;i++)
  105746. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  105747. og->header[22]=(unsigned char)(crc_reg&0xff);
  105748. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  105749. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  105750. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  105751. }
  105752. }
  105753. /* submit data to the internal buffer of the framing engine */
  105754. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  105755. int lacing_vals=op->bytes/255+1,i;
  105756. if(os->body_returned){
  105757. /* advance packet data according to the body_returned pointer. We
  105758. had to keep it around to return a pointer into the buffer last
  105759. call */
  105760. os->body_fill-=os->body_returned;
  105761. if(os->body_fill)
  105762. memmove(os->body_data,os->body_data+os->body_returned,
  105763. os->body_fill);
  105764. os->body_returned=0;
  105765. }
  105766. /* make sure we have the buffer storage */
  105767. _os_body_expand(os,op->bytes);
  105768. _os_lacing_expand(os,lacing_vals);
  105769. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  105770. the liability of overly clean abstraction for the time being. It
  105771. will actually be fairly easy to eliminate the extra copy in the
  105772. future */
  105773. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  105774. os->body_fill+=op->bytes;
  105775. /* Store lacing vals for this packet */
  105776. for(i=0;i<lacing_vals-1;i++){
  105777. os->lacing_vals[os->lacing_fill+i]=255;
  105778. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  105779. }
  105780. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  105781. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  105782. /* flag the first segment as the beginning of the packet */
  105783. os->lacing_vals[os->lacing_fill]|= 0x100;
  105784. os->lacing_fill+=lacing_vals;
  105785. /* for the sake of completeness */
  105786. os->packetno++;
  105787. if(op->e_o_s)os->e_o_s=1;
  105788. return(0);
  105789. }
  105790. /* This will flush remaining packets into a page (returning nonzero),
  105791. even if there is not enough data to trigger a flush normally
  105792. (undersized page). If there are no packets or partial packets to
  105793. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  105794. try to flush a normal sized page like ogg_stream_pageout; a call to
  105795. ogg_stream_flush does not guarantee that all packets have flushed.
  105796. Only a return value of 0 from ogg_stream_flush indicates all packet
  105797. data is flushed into pages.
  105798. since ogg_stream_flush will flush the last page in a stream even if
  105799. it's undersized, you almost certainly want to use ogg_stream_pageout
  105800. (and *not* ogg_stream_flush) unless you specifically need to flush
  105801. an page regardless of size in the middle of a stream. */
  105802. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  105803. int i;
  105804. int vals=0;
  105805. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  105806. int bytes=0;
  105807. long acc=0;
  105808. ogg_int64_t granule_pos=-1;
  105809. if(maxvals==0)return(0);
  105810. /* construct a page */
  105811. /* decide how many segments to include */
  105812. /* If this is the initial header case, the first page must only include
  105813. the initial header packet */
  105814. if(os->b_o_s==0){ /* 'initial header page' case */
  105815. granule_pos=0;
  105816. for(vals=0;vals<maxvals;vals++){
  105817. if((os->lacing_vals[vals]&0x0ff)<255){
  105818. vals++;
  105819. break;
  105820. }
  105821. }
  105822. }else{
  105823. for(vals=0;vals<maxvals;vals++){
  105824. if(acc>4096)break;
  105825. acc+=os->lacing_vals[vals]&0x0ff;
  105826. if((os->lacing_vals[vals]&0xff)<255)
  105827. granule_pos=os->granule_vals[vals];
  105828. }
  105829. }
  105830. /* construct the header in temp storage */
  105831. memcpy(os->header,"OggS",4);
  105832. /* stream structure version */
  105833. os->header[4]=0x00;
  105834. /* continued packet flag? */
  105835. os->header[5]=0x00;
  105836. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  105837. /* first page flag? */
  105838. if(os->b_o_s==0)os->header[5]|=0x02;
  105839. /* last page flag? */
  105840. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  105841. os->b_o_s=1;
  105842. /* 64 bits of PCM position */
  105843. for(i=6;i<14;i++){
  105844. os->header[i]=(unsigned char)(granule_pos&0xff);
  105845. granule_pos>>=8;
  105846. }
  105847. /* 32 bits of stream serial number */
  105848. {
  105849. long serialno=os->serialno;
  105850. for(i=14;i<18;i++){
  105851. os->header[i]=(unsigned char)(serialno&0xff);
  105852. serialno>>=8;
  105853. }
  105854. }
  105855. /* 32 bits of page counter (we have both counter and page header
  105856. because this val can roll over) */
  105857. if(os->pageno==-1)os->pageno=0; /* because someone called
  105858. stream_reset; this would be a
  105859. strange thing to do in an
  105860. encode stream, but it has
  105861. plausible uses */
  105862. {
  105863. long pageno=os->pageno++;
  105864. for(i=18;i<22;i++){
  105865. os->header[i]=(unsigned char)(pageno&0xff);
  105866. pageno>>=8;
  105867. }
  105868. }
  105869. /* zero for computation; filled in later */
  105870. os->header[22]=0;
  105871. os->header[23]=0;
  105872. os->header[24]=0;
  105873. os->header[25]=0;
  105874. /* segment table */
  105875. os->header[26]=(unsigned char)(vals&0xff);
  105876. for(i=0;i<vals;i++)
  105877. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  105878. /* set pointers in the ogg_page struct */
  105879. og->header=os->header;
  105880. og->header_len=os->header_fill=vals+27;
  105881. og->body=os->body_data+os->body_returned;
  105882. og->body_len=bytes;
  105883. /* advance the lacing data and set the body_returned pointer */
  105884. os->lacing_fill-=vals;
  105885. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  105886. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  105887. os->body_returned+=bytes;
  105888. /* calculate the checksum */
  105889. ogg_page_checksum_set(og);
  105890. /* done */
  105891. return(1);
  105892. }
  105893. /* This constructs pages from buffered packet segments. The pointers
  105894. returned are to static buffers; do not free. The returned buffers are
  105895. good only until the next call (using the same ogg_stream_state) */
  105896. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  105897. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  105898. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  105899. os->lacing_fill>=255 || /* 'segment table full' case */
  105900. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  105901. return(ogg_stream_flush(os,og));
  105902. }
  105903. /* not enough data to construct a page and not end of stream */
  105904. return(0);
  105905. }
  105906. int ogg_stream_eos(ogg_stream_state *os){
  105907. return os->e_o_s;
  105908. }
  105909. /* DECODING PRIMITIVES: packet streaming layer **********************/
  105910. /* This has two layers to place more of the multi-serialno and paging
  105911. control in the application's hands. First, we expose a data buffer
  105912. using ogg_sync_buffer(). The app either copies into the
  105913. buffer, or passes it directly to read(), etc. We then call
  105914. ogg_sync_wrote() to tell how many bytes we just added.
  105915. Pages are returned (pointers into the buffer in ogg_sync_state)
  105916. by ogg_sync_pageout(). The page is then submitted to
  105917. ogg_stream_pagein() along with the appropriate
  105918. ogg_stream_state* (ie, matching serialno). We then get raw
  105919. packets out calling ogg_stream_packetout() with a
  105920. ogg_stream_state. */
  105921. /* initialize the struct to a known state */
  105922. int ogg_sync_init(ogg_sync_state *oy){
  105923. if(oy){
  105924. memset(oy,0,sizeof(*oy));
  105925. }
  105926. return(0);
  105927. }
  105928. /* clear non-flat storage within */
  105929. int ogg_sync_clear(ogg_sync_state *oy){
  105930. if(oy){
  105931. if(oy->data)_ogg_free(oy->data);
  105932. ogg_sync_init(oy);
  105933. }
  105934. return(0);
  105935. }
  105936. int ogg_sync_destroy(ogg_sync_state *oy){
  105937. if(oy){
  105938. ogg_sync_clear(oy);
  105939. _ogg_free(oy);
  105940. }
  105941. return(0);
  105942. }
  105943. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  105944. /* first, clear out any space that has been previously returned */
  105945. if(oy->returned){
  105946. oy->fill-=oy->returned;
  105947. if(oy->fill>0)
  105948. memmove(oy->data,oy->data+oy->returned,oy->fill);
  105949. oy->returned=0;
  105950. }
  105951. if(size>oy->storage-oy->fill){
  105952. /* We need to extend the internal buffer */
  105953. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  105954. if(oy->data)
  105955. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  105956. else
  105957. oy->data=(unsigned char*) _ogg_malloc(newsize);
  105958. oy->storage=newsize;
  105959. }
  105960. /* expose a segment at least as large as requested at the fill mark */
  105961. return((char *)oy->data+oy->fill);
  105962. }
  105963. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  105964. if(oy->fill+bytes>oy->storage)return(-1);
  105965. oy->fill+=bytes;
  105966. return(0);
  105967. }
  105968. /* sync the stream. This is meant to be useful for finding page
  105969. boundaries.
  105970. return values for this:
  105971. -n) skipped n bytes
  105972. 0) page not ready; more data (no bytes skipped)
  105973. n) page synced at current location; page length n bytes
  105974. */
  105975. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  105976. unsigned char *page=oy->data+oy->returned;
  105977. unsigned char *next;
  105978. long bytes=oy->fill-oy->returned;
  105979. if(oy->headerbytes==0){
  105980. int headerbytes,i;
  105981. if(bytes<27)return(0); /* not enough for a header */
  105982. /* verify capture pattern */
  105983. if(memcmp(page,"OggS",4))goto sync_fail;
  105984. headerbytes=page[26]+27;
  105985. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  105986. /* count up body length in the segment table */
  105987. for(i=0;i<page[26];i++)
  105988. oy->bodybytes+=page[27+i];
  105989. oy->headerbytes=headerbytes;
  105990. }
  105991. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  105992. /* The whole test page is buffered. Verify the checksum */
  105993. {
  105994. /* Grab the checksum bytes, set the header field to zero */
  105995. char chksum[4];
  105996. ogg_page log;
  105997. memcpy(chksum,page+22,4);
  105998. memset(page+22,0,4);
  105999. /* set up a temp page struct and recompute the checksum */
  106000. log.header=page;
  106001. log.header_len=oy->headerbytes;
  106002. log.body=page+oy->headerbytes;
  106003. log.body_len=oy->bodybytes;
  106004. ogg_page_checksum_set(&log);
  106005. /* Compare */
  106006. if(memcmp(chksum,page+22,4)){
  106007. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  106008. at all) */
  106009. /* replace the computed checksum with the one actually read in */
  106010. memcpy(page+22,chksum,4);
  106011. /* Bad checksum. Lose sync */
  106012. goto sync_fail;
  106013. }
  106014. }
  106015. /* yes, have a whole page all ready to go */
  106016. {
  106017. unsigned char *page=oy->data+oy->returned;
  106018. long bytes;
  106019. if(og){
  106020. og->header=page;
  106021. og->header_len=oy->headerbytes;
  106022. og->body=page+oy->headerbytes;
  106023. og->body_len=oy->bodybytes;
  106024. }
  106025. oy->unsynced=0;
  106026. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  106027. oy->headerbytes=0;
  106028. oy->bodybytes=0;
  106029. return(bytes);
  106030. }
  106031. sync_fail:
  106032. oy->headerbytes=0;
  106033. oy->bodybytes=0;
  106034. /* search for possible capture */
  106035. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  106036. if(!next)
  106037. next=oy->data+oy->fill;
  106038. oy->returned=next-oy->data;
  106039. return(-(next-page));
  106040. }
  106041. /* sync the stream and get a page. Keep trying until we find a page.
  106042. Supress 'sync errors' after reporting the first.
  106043. return values:
  106044. -1) recapture (hole in data)
  106045. 0) need more data
  106046. 1) page returned
  106047. Returns pointers into buffered data; invalidated by next call to
  106048. _stream, _clear, _init, or _buffer */
  106049. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  106050. /* all we need to do is verify a page at the head of the stream
  106051. buffer. If it doesn't verify, we look for the next potential
  106052. frame */
  106053. for(;;){
  106054. long ret=ogg_sync_pageseek(oy,og);
  106055. if(ret>0){
  106056. /* have a page */
  106057. return(1);
  106058. }
  106059. if(ret==0){
  106060. /* need more data */
  106061. return(0);
  106062. }
  106063. /* head did not start a synced page... skipped some bytes */
  106064. if(!oy->unsynced){
  106065. oy->unsynced=1;
  106066. return(-1);
  106067. }
  106068. /* loop. keep looking */
  106069. }
  106070. }
  106071. /* add the incoming page to the stream state; we decompose the page
  106072. into packet segments here as well. */
  106073. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  106074. unsigned char *header=og->header;
  106075. unsigned char *body=og->body;
  106076. long bodysize=og->body_len;
  106077. int segptr=0;
  106078. int version=ogg_page_version(og);
  106079. int continued=ogg_page_continued(og);
  106080. int bos=ogg_page_bos(og);
  106081. int eos=ogg_page_eos(og);
  106082. ogg_int64_t granulepos=ogg_page_granulepos(og);
  106083. int serialno=ogg_page_serialno(og);
  106084. long pageno=ogg_page_pageno(og);
  106085. int segments=header[26];
  106086. /* clean up 'returned data' */
  106087. {
  106088. long lr=os->lacing_returned;
  106089. long br=os->body_returned;
  106090. /* body data */
  106091. if(br){
  106092. os->body_fill-=br;
  106093. if(os->body_fill)
  106094. memmove(os->body_data,os->body_data+br,os->body_fill);
  106095. os->body_returned=0;
  106096. }
  106097. if(lr){
  106098. /* segment table */
  106099. if(os->lacing_fill-lr){
  106100. memmove(os->lacing_vals,os->lacing_vals+lr,
  106101. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  106102. memmove(os->granule_vals,os->granule_vals+lr,
  106103. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  106104. }
  106105. os->lacing_fill-=lr;
  106106. os->lacing_packet-=lr;
  106107. os->lacing_returned=0;
  106108. }
  106109. }
  106110. /* check the serial number */
  106111. if(serialno!=os->serialno)return(-1);
  106112. if(version>0)return(-1);
  106113. _os_lacing_expand(os,segments+1);
  106114. /* are we in sequence? */
  106115. if(pageno!=os->pageno){
  106116. int i;
  106117. /* unroll previous partial packet (if any) */
  106118. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  106119. os->body_fill-=os->lacing_vals[i]&0xff;
  106120. os->lacing_fill=os->lacing_packet;
  106121. /* make a note of dropped data in segment table */
  106122. if(os->pageno!=-1){
  106123. os->lacing_vals[os->lacing_fill++]=0x400;
  106124. os->lacing_packet++;
  106125. }
  106126. }
  106127. /* are we a 'continued packet' page? If so, we may need to skip
  106128. some segments */
  106129. if(continued){
  106130. if(os->lacing_fill<1 ||
  106131. os->lacing_vals[os->lacing_fill-1]==0x400){
  106132. bos=0;
  106133. for(;segptr<segments;segptr++){
  106134. int val=header[27+segptr];
  106135. body+=val;
  106136. bodysize-=val;
  106137. if(val<255){
  106138. segptr++;
  106139. break;
  106140. }
  106141. }
  106142. }
  106143. }
  106144. if(bodysize){
  106145. _os_body_expand(os,bodysize);
  106146. memcpy(os->body_data+os->body_fill,body,bodysize);
  106147. os->body_fill+=bodysize;
  106148. }
  106149. {
  106150. int saved=-1;
  106151. while(segptr<segments){
  106152. int val=header[27+segptr];
  106153. os->lacing_vals[os->lacing_fill]=val;
  106154. os->granule_vals[os->lacing_fill]=-1;
  106155. if(bos){
  106156. os->lacing_vals[os->lacing_fill]|=0x100;
  106157. bos=0;
  106158. }
  106159. if(val<255)saved=os->lacing_fill;
  106160. os->lacing_fill++;
  106161. segptr++;
  106162. if(val<255)os->lacing_packet=os->lacing_fill;
  106163. }
  106164. /* set the granulepos on the last granuleval of the last full packet */
  106165. if(saved!=-1){
  106166. os->granule_vals[saved]=granulepos;
  106167. }
  106168. }
  106169. if(eos){
  106170. os->e_o_s=1;
  106171. if(os->lacing_fill>0)
  106172. os->lacing_vals[os->lacing_fill-1]|=0x200;
  106173. }
  106174. os->pageno=pageno+1;
  106175. return(0);
  106176. }
  106177. /* clear things to an initial state. Good to call, eg, before seeking */
  106178. int ogg_sync_reset(ogg_sync_state *oy){
  106179. oy->fill=0;
  106180. oy->returned=0;
  106181. oy->unsynced=0;
  106182. oy->headerbytes=0;
  106183. oy->bodybytes=0;
  106184. return(0);
  106185. }
  106186. int ogg_stream_reset(ogg_stream_state *os){
  106187. os->body_fill=0;
  106188. os->body_returned=0;
  106189. os->lacing_fill=0;
  106190. os->lacing_packet=0;
  106191. os->lacing_returned=0;
  106192. os->header_fill=0;
  106193. os->e_o_s=0;
  106194. os->b_o_s=0;
  106195. os->pageno=-1;
  106196. os->packetno=0;
  106197. os->granulepos=0;
  106198. return(0);
  106199. }
  106200. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  106201. ogg_stream_reset(os);
  106202. os->serialno=serialno;
  106203. return(0);
  106204. }
  106205. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  106206. /* The last part of decode. We have the stream broken into packet
  106207. segments. Now we need to group them into packets (or return the
  106208. out of sync markers) */
  106209. int ptr=os->lacing_returned;
  106210. if(os->lacing_packet<=ptr)return(0);
  106211. if(os->lacing_vals[ptr]&0x400){
  106212. /* we need to tell the codec there's a gap; it might need to
  106213. handle previous packet dependencies. */
  106214. os->lacing_returned++;
  106215. os->packetno++;
  106216. return(-1);
  106217. }
  106218. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  106219. to ask if there's a whole packet
  106220. waiting */
  106221. /* Gather the whole packet. We'll have no holes or a partial packet */
  106222. {
  106223. int size=os->lacing_vals[ptr]&0xff;
  106224. int bytes=size;
  106225. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  106226. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  106227. while(size==255){
  106228. int val=os->lacing_vals[++ptr];
  106229. size=val&0xff;
  106230. if(val&0x200)eos=0x200;
  106231. bytes+=size;
  106232. }
  106233. if(op){
  106234. op->e_o_s=eos;
  106235. op->b_o_s=bos;
  106236. op->packet=os->body_data+os->body_returned;
  106237. op->packetno=os->packetno;
  106238. op->granulepos=os->granule_vals[ptr];
  106239. op->bytes=bytes;
  106240. }
  106241. if(adv){
  106242. os->body_returned+=bytes;
  106243. os->lacing_returned=ptr+1;
  106244. os->packetno++;
  106245. }
  106246. }
  106247. return(1);
  106248. }
  106249. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  106250. return _packetout(os,op,1);
  106251. }
  106252. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  106253. return _packetout(os,op,0);
  106254. }
  106255. void ogg_packet_clear(ogg_packet *op) {
  106256. _ogg_free(op->packet);
  106257. memset(op, 0, sizeof(*op));
  106258. }
  106259. #ifdef _V_SELFTEST
  106260. #include <stdio.h>
  106261. ogg_stream_state os_en, os_de;
  106262. ogg_sync_state oy;
  106263. void checkpacket(ogg_packet *op,int len, int no, int pos){
  106264. long j;
  106265. static int sequence=0;
  106266. static int lastno=0;
  106267. if(op->bytes!=len){
  106268. fprintf(stderr,"incorrect packet length!\n");
  106269. exit(1);
  106270. }
  106271. if(op->granulepos!=pos){
  106272. fprintf(stderr,"incorrect packet position!\n");
  106273. exit(1);
  106274. }
  106275. /* packet number just follows sequence/gap; adjust the input number
  106276. for that */
  106277. if(no==0){
  106278. sequence=0;
  106279. }else{
  106280. sequence++;
  106281. if(no>lastno+1)
  106282. sequence++;
  106283. }
  106284. lastno=no;
  106285. if(op->packetno!=sequence){
  106286. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  106287. (long)(op->packetno),sequence);
  106288. exit(1);
  106289. }
  106290. /* Test data */
  106291. for(j=0;j<op->bytes;j++)
  106292. if(op->packet[j]!=((j+no)&0xff)){
  106293. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  106294. j,op->packet[j],(j+no)&0xff);
  106295. exit(1);
  106296. }
  106297. }
  106298. void check_page(unsigned char *data,const int *header,ogg_page *og){
  106299. long j;
  106300. /* Test data */
  106301. for(j=0;j<og->body_len;j++)
  106302. if(og->body[j]!=data[j]){
  106303. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  106304. j,data[j],og->body[j]);
  106305. exit(1);
  106306. }
  106307. /* Test header */
  106308. for(j=0;j<og->header_len;j++){
  106309. if(og->header[j]!=header[j]){
  106310. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  106311. for(j=0;j<header[26]+27;j++)
  106312. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  106313. fprintf(stderr,"\n");
  106314. exit(1);
  106315. }
  106316. }
  106317. if(og->header_len!=header[26]+27){
  106318. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  106319. og->header_len,header[26]+27);
  106320. exit(1);
  106321. }
  106322. }
  106323. void print_header(ogg_page *og){
  106324. int j;
  106325. fprintf(stderr,"\nHEADER:\n");
  106326. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  106327. og->header[0],og->header[1],og->header[2],og->header[3],
  106328. (int)og->header[4],(int)og->header[5]);
  106329. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  106330. (og->header[9]<<24)|(og->header[8]<<16)|
  106331. (og->header[7]<<8)|og->header[6],
  106332. (og->header[17]<<24)|(og->header[16]<<16)|
  106333. (og->header[15]<<8)|og->header[14],
  106334. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  106335. (og->header[19]<<8)|og->header[18]);
  106336. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  106337. (int)og->header[22],(int)og->header[23],
  106338. (int)og->header[24],(int)og->header[25],
  106339. (int)og->header[26]);
  106340. for(j=27;j<og->header_len;j++)
  106341. fprintf(stderr,"%d ",(int)og->header[j]);
  106342. fprintf(stderr,")\n\n");
  106343. }
  106344. void copy_page(ogg_page *og){
  106345. unsigned char *temp=_ogg_malloc(og->header_len);
  106346. memcpy(temp,og->header,og->header_len);
  106347. og->header=temp;
  106348. temp=_ogg_malloc(og->body_len);
  106349. memcpy(temp,og->body,og->body_len);
  106350. og->body=temp;
  106351. }
  106352. void free_page(ogg_page *og){
  106353. _ogg_free (og->header);
  106354. _ogg_free (og->body);
  106355. }
  106356. void error(void){
  106357. fprintf(stderr,"error!\n");
  106358. exit(1);
  106359. }
  106360. /* 17 only */
  106361. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  106362. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  106363. 0x01,0x02,0x03,0x04,0,0,0,0,
  106364. 0x15,0xed,0xec,0x91,
  106365. 1,
  106366. 17};
  106367. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  106368. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  106369. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  106370. 0x01,0x02,0x03,0x04,0,0,0,0,
  106371. 0x59,0x10,0x6c,0x2c,
  106372. 1,
  106373. 17};
  106374. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  106375. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  106376. 0x01,0x02,0x03,0x04,1,0,0,0,
  106377. 0x89,0x33,0x85,0xce,
  106378. 13,
  106379. 254,255,0,255,1,255,245,255,255,0,
  106380. 255,255,90};
  106381. /* nil packets; beginning,middle,end */
  106382. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  106383. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  106384. 0x01,0x02,0x03,0x04,0,0,0,0,
  106385. 0xff,0x7b,0x23,0x17,
  106386. 1,
  106387. 0};
  106388. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  106389. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  106390. 0x01,0x02,0x03,0x04,1,0,0,0,
  106391. 0x5c,0x3f,0x66,0xcb,
  106392. 17,
  106393. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  106394. 255,255,90,0};
  106395. /* large initial packet */
  106396. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  106397. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  106398. 0x01,0x02,0x03,0x04,0,0,0,0,
  106399. 0x01,0x27,0x31,0xaa,
  106400. 18,
  106401. 255,255,255,255,255,255,255,255,
  106402. 255,255,255,255,255,255,255,255,255,10};
  106403. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  106404. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  106405. 0x01,0x02,0x03,0x04,1,0,0,0,
  106406. 0x7f,0x4e,0x8a,0xd2,
  106407. 4,
  106408. 255,4,255,0};
  106409. /* continuing packet test */
  106410. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  106411. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  106412. 0x01,0x02,0x03,0x04,0,0,0,0,
  106413. 0xff,0x7b,0x23,0x17,
  106414. 1,
  106415. 0};
  106416. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  106417. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  106418. 0x01,0x02,0x03,0x04,1,0,0,0,
  106419. 0x54,0x05,0x51,0xc8,
  106420. 17,
  106421. 255,255,255,255,255,255,255,255,
  106422. 255,255,255,255,255,255,255,255,255};
  106423. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  106424. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  106425. 0x01,0x02,0x03,0x04,2,0,0,0,
  106426. 0xc8,0xc3,0xcb,0xed,
  106427. 5,
  106428. 10,255,4,255,0};
  106429. /* page with the 255 segment limit */
  106430. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  106431. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  106432. 0x01,0x02,0x03,0x04,0,0,0,0,
  106433. 0xff,0x7b,0x23,0x17,
  106434. 1,
  106435. 0};
  106436. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  106437. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  106438. 0x01,0x02,0x03,0x04,1,0,0,0,
  106439. 0xed,0x2a,0x2e,0xa7,
  106440. 255,
  106441. 10,10,10,10,10,10,10,10,
  106442. 10,10,10,10,10,10,10,10,
  106443. 10,10,10,10,10,10,10,10,
  106444. 10,10,10,10,10,10,10,10,
  106445. 10,10,10,10,10,10,10,10,
  106446. 10,10,10,10,10,10,10,10,
  106447. 10,10,10,10,10,10,10,10,
  106448. 10,10,10,10,10,10,10,10,
  106449. 10,10,10,10,10,10,10,10,
  106450. 10,10,10,10,10,10,10,10,
  106451. 10,10,10,10,10,10,10,10,
  106452. 10,10,10,10,10,10,10,10,
  106453. 10,10,10,10,10,10,10,10,
  106454. 10,10,10,10,10,10,10,10,
  106455. 10,10,10,10,10,10,10,10,
  106456. 10,10,10,10,10,10,10,10,
  106457. 10,10,10,10,10,10,10,10,
  106458. 10,10,10,10,10,10,10,10,
  106459. 10,10,10,10,10,10,10,10,
  106460. 10,10,10,10,10,10,10,10,
  106461. 10,10,10,10,10,10,10,10,
  106462. 10,10,10,10,10,10,10,10,
  106463. 10,10,10,10,10,10,10,10,
  106464. 10,10,10,10,10,10,10,10,
  106465. 10,10,10,10,10,10,10,10,
  106466. 10,10,10,10,10,10,10,10,
  106467. 10,10,10,10,10,10,10,10,
  106468. 10,10,10,10,10,10,10,10,
  106469. 10,10,10,10,10,10,10,10,
  106470. 10,10,10,10,10,10,10,10,
  106471. 10,10,10,10,10,10,10,10,
  106472. 10,10,10,10,10,10,10};
  106473. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  106474. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  106475. 0x01,0x02,0x03,0x04,2,0,0,0,
  106476. 0x6c,0x3b,0x82,0x3d,
  106477. 1,
  106478. 50};
  106479. /* packet that overspans over an entire page */
  106480. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  106481. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  106482. 0x01,0x02,0x03,0x04,0,0,0,0,
  106483. 0xff,0x7b,0x23,0x17,
  106484. 1,
  106485. 0};
  106486. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  106487. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  106488. 0x01,0x02,0x03,0x04,1,0,0,0,
  106489. 0x3c,0xd9,0x4d,0x3f,
  106490. 17,
  106491. 100,255,255,255,255,255,255,255,255,
  106492. 255,255,255,255,255,255,255,255};
  106493. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  106494. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  106495. 0x01,0x02,0x03,0x04,2,0,0,0,
  106496. 0x01,0xd2,0xe5,0xe5,
  106497. 17,
  106498. 255,255,255,255,255,255,255,255,
  106499. 255,255,255,255,255,255,255,255,255};
  106500. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  106501. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  106502. 0x01,0x02,0x03,0x04,3,0,0,0,
  106503. 0xef,0xdd,0x88,0xde,
  106504. 7,
  106505. 255,255,75,255,4,255,0};
  106506. /* packet that overspans over an entire page */
  106507. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  106508. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  106509. 0x01,0x02,0x03,0x04,0,0,0,0,
  106510. 0xff,0x7b,0x23,0x17,
  106511. 1,
  106512. 0};
  106513. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  106514. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  106515. 0x01,0x02,0x03,0x04,1,0,0,0,
  106516. 0x3c,0xd9,0x4d,0x3f,
  106517. 17,
  106518. 100,255,255,255,255,255,255,255,255,
  106519. 255,255,255,255,255,255,255,255};
  106520. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  106521. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  106522. 0x01,0x02,0x03,0x04,2,0,0,0,
  106523. 0xd4,0xe0,0x60,0xe5,
  106524. 1,0};
  106525. void test_pack(const int *pl, const int **headers, int byteskip,
  106526. int pageskip, int packetskip){
  106527. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  106528. long inptr=0;
  106529. long outptr=0;
  106530. long deptr=0;
  106531. long depacket=0;
  106532. long granule_pos=7,pageno=0;
  106533. int i,j,packets,pageout=pageskip;
  106534. int eosflag=0;
  106535. int bosflag=0;
  106536. int byteskipcount=0;
  106537. ogg_stream_reset(&os_en);
  106538. ogg_stream_reset(&os_de);
  106539. ogg_sync_reset(&oy);
  106540. for(packets=0;packets<packetskip;packets++)
  106541. depacket+=pl[packets];
  106542. for(packets=0;;packets++)if(pl[packets]==-1)break;
  106543. for(i=0;i<packets;i++){
  106544. /* construct a test packet */
  106545. ogg_packet op;
  106546. int len=pl[i];
  106547. op.packet=data+inptr;
  106548. op.bytes=len;
  106549. op.e_o_s=(pl[i+1]<0?1:0);
  106550. op.granulepos=granule_pos;
  106551. granule_pos+=1024;
  106552. for(j=0;j<len;j++)data[inptr++]=i+j;
  106553. /* submit the test packet */
  106554. ogg_stream_packetin(&os_en,&op);
  106555. /* retrieve any finished pages */
  106556. {
  106557. ogg_page og;
  106558. while(ogg_stream_pageout(&os_en,&og)){
  106559. /* We have a page. Check it carefully */
  106560. fprintf(stderr,"%ld, ",pageno);
  106561. if(headers[pageno]==NULL){
  106562. fprintf(stderr,"coded too many pages!\n");
  106563. exit(1);
  106564. }
  106565. check_page(data+outptr,headers[pageno],&og);
  106566. outptr+=og.body_len;
  106567. pageno++;
  106568. if(pageskip){
  106569. bosflag=1;
  106570. pageskip--;
  106571. deptr+=og.body_len;
  106572. }
  106573. /* have a complete page; submit it to sync/decode */
  106574. {
  106575. ogg_page og_de;
  106576. ogg_packet op_de,op_de2;
  106577. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  106578. char *next=buf;
  106579. byteskipcount+=og.header_len;
  106580. if(byteskipcount>byteskip){
  106581. memcpy(next,og.header,byteskipcount-byteskip);
  106582. next+=byteskipcount-byteskip;
  106583. byteskipcount=byteskip;
  106584. }
  106585. byteskipcount+=og.body_len;
  106586. if(byteskipcount>byteskip){
  106587. memcpy(next,og.body,byteskipcount-byteskip);
  106588. next+=byteskipcount-byteskip;
  106589. byteskipcount=byteskip;
  106590. }
  106591. ogg_sync_wrote(&oy,next-buf);
  106592. while(1){
  106593. int ret=ogg_sync_pageout(&oy,&og_de);
  106594. if(ret==0)break;
  106595. if(ret<0)continue;
  106596. /* got a page. Happy happy. Verify that it's good. */
  106597. fprintf(stderr,"(%ld), ",pageout);
  106598. check_page(data+deptr,headers[pageout],&og_de);
  106599. deptr+=og_de.body_len;
  106600. pageout++;
  106601. /* submit it to deconstitution */
  106602. ogg_stream_pagein(&os_de,&og_de);
  106603. /* packets out? */
  106604. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  106605. ogg_stream_packetpeek(&os_de,NULL);
  106606. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  106607. /* verify peek and out match */
  106608. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  106609. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  106610. depacket);
  106611. exit(1);
  106612. }
  106613. /* verify the packet! */
  106614. /* check data */
  106615. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  106616. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  106617. depacket);
  106618. exit(1);
  106619. }
  106620. /* check bos flag */
  106621. if(bosflag==0 && op_de.b_o_s==0){
  106622. fprintf(stderr,"b_o_s flag not set on packet!\n");
  106623. exit(1);
  106624. }
  106625. if(bosflag && op_de.b_o_s){
  106626. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  106627. exit(1);
  106628. }
  106629. bosflag=1;
  106630. depacket+=op_de.bytes;
  106631. /* check eos flag */
  106632. if(eosflag){
  106633. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  106634. exit(1);
  106635. }
  106636. if(op_de.e_o_s)eosflag=1;
  106637. /* check granulepos flag */
  106638. if(op_de.granulepos!=-1){
  106639. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  106640. }
  106641. }
  106642. }
  106643. }
  106644. }
  106645. }
  106646. }
  106647. _ogg_free(data);
  106648. if(headers[pageno]!=NULL){
  106649. fprintf(stderr,"did not write last page!\n");
  106650. exit(1);
  106651. }
  106652. if(headers[pageout]!=NULL){
  106653. fprintf(stderr,"did not decode last page!\n");
  106654. exit(1);
  106655. }
  106656. if(inptr!=outptr){
  106657. fprintf(stderr,"encoded page data incomplete!\n");
  106658. exit(1);
  106659. }
  106660. if(inptr!=deptr){
  106661. fprintf(stderr,"decoded page data incomplete!\n");
  106662. exit(1);
  106663. }
  106664. if(inptr!=depacket){
  106665. fprintf(stderr,"decoded packet data incomplete!\n");
  106666. exit(1);
  106667. }
  106668. if(!eosflag){
  106669. fprintf(stderr,"Never got a packet with EOS set!\n");
  106670. exit(1);
  106671. }
  106672. fprintf(stderr,"ok.\n");
  106673. }
  106674. int main(void){
  106675. ogg_stream_init(&os_en,0x04030201);
  106676. ogg_stream_init(&os_de,0x04030201);
  106677. ogg_sync_init(&oy);
  106678. /* Exercise each code path in the framing code. Also verify that
  106679. the checksums are working. */
  106680. {
  106681. /* 17 only */
  106682. const int packets[]={17, -1};
  106683. const int *headret[]={head1_0,NULL};
  106684. fprintf(stderr,"testing single page encoding... ");
  106685. test_pack(packets,headret,0,0,0);
  106686. }
  106687. {
  106688. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  106689. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  106690. const int *headret[]={head1_1,head2_1,NULL};
  106691. fprintf(stderr,"testing basic page encoding... ");
  106692. test_pack(packets,headret,0,0,0);
  106693. }
  106694. {
  106695. /* nil packets; beginning,middle,end */
  106696. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  106697. const int *headret[]={head1_2,head2_2,NULL};
  106698. fprintf(stderr,"testing basic nil packets... ");
  106699. test_pack(packets,headret,0,0,0);
  106700. }
  106701. {
  106702. /* large initial packet */
  106703. const int packets[]={4345,259,255,-1};
  106704. const int *headret[]={head1_3,head2_3,NULL};
  106705. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  106706. test_pack(packets,headret,0,0,0);
  106707. }
  106708. {
  106709. /* continuing packet test */
  106710. const int packets[]={0,4345,259,255,-1};
  106711. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  106712. fprintf(stderr,"testing single packet page span... ");
  106713. test_pack(packets,headret,0,0,0);
  106714. }
  106715. /* page with the 255 segment limit */
  106716. {
  106717. const int packets[]={0,10,10,10,10,10,10,10,10,
  106718. 10,10,10,10,10,10,10,10,
  106719. 10,10,10,10,10,10,10,10,
  106720. 10,10,10,10,10,10,10,10,
  106721. 10,10,10,10,10,10,10,10,
  106722. 10,10,10,10,10,10,10,10,
  106723. 10,10,10,10,10,10,10,10,
  106724. 10,10,10,10,10,10,10,10,
  106725. 10,10,10,10,10,10,10,10,
  106726. 10,10,10,10,10,10,10,10,
  106727. 10,10,10,10,10,10,10,10,
  106728. 10,10,10,10,10,10,10,10,
  106729. 10,10,10,10,10,10,10,10,
  106730. 10,10,10,10,10,10,10,10,
  106731. 10,10,10,10,10,10,10,10,
  106732. 10,10,10,10,10,10,10,10,
  106733. 10,10,10,10,10,10,10,10,
  106734. 10,10,10,10,10,10,10,10,
  106735. 10,10,10,10,10,10,10,10,
  106736. 10,10,10,10,10,10,10,10,
  106737. 10,10,10,10,10,10,10,10,
  106738. 10,10,10,10,10,10,10,10,
  106739. 10,10,10,10,10,10,10,10,
  106740. 10,10,10,10,10,10,10,10,
  106741. 10,10,10,10,10,10,10,10,
  106742. 10,10,10,10,10,10,10,10,
  106743. 10,10,10,10,10,10,10,10,
  106744. 10,10,10,10,10,10,10,10,
  106745. 10,10,10,10,10,10,10,10,
  106746. 10,10,10,10,10,10,10,10,
  106747. 10,10,10,10,10,10,10,10,
  106748. 10,10,10,10,10,10,10,50,-1};
  106749. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  106750. fprintf(stderr,"testing max packet segments... ");
  106751. test_pack(packets,headret,0,0,0);
  106752. }
  106753. {
  106754. /* packet that overspans over an entire page */
  106755. const int packets[]={0,100,9000,259,255,-1};
  106756. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  106757. fprintf(stderr,"testing very large packets... ");
  106758. test_pack(packets,headret,0,0,0);
  106759. }
  106760. {
  106761. /* test for the libogg 1.1.1 resync in large continuation bug
  106762. found by Josh Coalson) */
  106763. const int packets[]={0,100,9000,259,255,-1};
  106764. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  106765. fprintf(stderr,"testing continuation resync in very large packets... ");
  106766. test_pack(packets,headret,100,2,3);
  106767. }
  106768. {
  106769. /* term only page. why not? */
  106770. const int packets[]={0,100,4080,-1};
  106771. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  106772. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  106773. test_pack(packets,headret,0,0,0);
  106774. }
  106775. {
  106776. /* build a bunch of pages for testing */
  106777. unsigned char *data=_ogg_malloc(1024*1024);
  106778. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  106779. int inptr=0,i,j;
  106780. ogg_page og[5];
  106781. ogg_stream_reset(&os_en);
  106782. for(i=0;pl[i]!=-1;i++){
  106783. ogg_packet op;
  106784. int len=pl[i];
  106785. op.packet=data+inptr;
  106786. op.bytes=len;
  106787. op.e_o_s=(pl[i+1]<0?1:0);
  106788. op.granulepos=(i+1)*1000;
  106789. for(j=0;j<len;j++)data[inptr++]=i+j;
  106790. ogg_stream_packetin(&os_en,&op);
  106791. }
  106792. _ogg_free(data);
  106793. /* retrieve finished pages */
  106794. for(i=0;i<5;i++){
  106795. if(ogg_stream_pageout(&os_en,&og[i])==0){
  106796. fprintf(stderr,"Too few pages output building sync tests!\n");
  106797. exit(1);
  106798. }
  106799. copy_page(&og[i]);
  106800. }
  106801. /* Test lost pages on pagein/packetout: no rollback */
  106802. {
  106803. ogg_page temp;
  106804. ogg_packet test;
  106805. fprintf(stderr,"Testing loss of pages... ");
  106806. ogg_sync_reset(&oy);
  106807. ogg_stream_reset(&os_de);
  106808. for(i=0;i<5;i++){
  106809. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  106810. og[i].header_len);
  106811. ogg_sync_wrote(&oy,og[i].header_len);
  106812. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  106813. ogg_sync_wrote(&oy,og[i].body_len);
  106814. }
  106815. ogg_sync_pageout(&oy,&temp);
  106816. ogg_stream_pagein(&os_de,&temp);
  106817. ogg_sync_pageout(&oy,&temp);
  106818. ogg_stream_pagein(&os_de,&temp);
  106819. ogg_sync_pageout(&oy,&temp);
  106820. /* skip */
  106821. ogg_sync_pageout(&oy,&temp);
  106822. ogg_stream_pagein(&os_de,&temp);
  106823. /* do we get the expected results/packets? */
  106824. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106825. checkpacket(&test,0,0,0);
  106826. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106827. checkpacket(&test,100,1,-1);
  106828. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106829. checkpacket(&test,4079,2,3000);
  106830. if(ogg_stream_packetout(&os_de,&test)!=-1){
  106831. fprintf(stderr,"Error: loss of page did not return error\n");
  106832. exit(1);
  106833. }
  106834. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106835. checkpacket(&test,76,5,-1);
  106836. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106837. checkpacket(&test,34,6,-1);
  106838. fprintf(stderr,"ok.\n");
  106839. }
  106840. /* Test lost pages on pagein/packetout: rollback with continuation */
  106841. {
  106842. ogg_page temp;
  106843. ogg_packet test;
  106844. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  106845. ogg_sync_reset(&oy);
  106846. ogg_stream_reset(&os_de);
  106847. for(i=0;i<5;i++){
  106848. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  106849. og[i].header_len);
  106850. ogg_sync_wrote(&oy,og[i].header_len);
  106851. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  106852. ogg_sync_wrote(&oy,og[i].body_len);
  106853. }
  106854. ogg_sync_pageout(&oy,&temp);
  106855. ogg_stream_pagein(&os_de,&temp);
  106856. ogg_sync_pageout(&oy,&temp);
  106857. ogg_stream_pagein(&os_de,&temp);
  106858. ogg_sync_pageout(&oy,&temp);
  106859. ogg_stream_pagein(&os_de,&temp);
  106860. ogg_sync_pageout(&oy,&temp);
  106861. /* skip */
  106862. ogg_sync_pageout(&oy,&temp);
  106863. ogg_stream_pagein(&os_de,&temp);
  106864. /* do we get the expected results/packets? */
  106865. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106866. checkpacket(&test,0,0,0);
  106867. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106868. checkpacket(&test,100,1,-1);
  106869. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106870. checkpacket(&test,4079,2,3000);
  106871. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106872. checkpacket(&test,2956,3,4000);
  106873. if(ogg_stream_packetout(&os_de,&test)!=-1){
  106874. fprintf(stderr,"Error: loss of page did not return error\n");
  106875. exit(1);
  106876. }
  106877. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106878. checkpacket(&test,300,13,14000);
  106879. fprintf(stderr,"ok.\n");
  106880. }
  106881. /* the rest only test sync */
  106882. {
  106883. ogg_page og_de;
  106884. /* Test fractional page inputs: incomplete capture */
  106885. fprintf(stderr,"Testing sync on partial inputs... ");
  106886. ogg_sync_reset(&oy);
  106887. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  106888. 3);
  106889. ogg_sync_wrote(&oy,3);
  106890. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106891. /* Test fractional page inputs: incomplete fixed header */
  106892. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  106893. 20);
  106894. ogg_sync_wrote(&oy,20);
  106895. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106896. /* Test fractional page inputs: incomplete header */
  106897. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  106898. 5);
  106899. ogg_sync_wrote(&oy,5);
  106900. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106901. /* Test fractional page inputs: incomplete body */
  106902. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  106903. og[1].header_len-28);
  106904. ogg_sync_wrote(&oy,og[1].header_len-28);
  106905. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106906. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  106907. ogg_sync_wrote(&oy,1000);
  106908. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106909. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  106910. og[1].body_len-1000);
  106911. ogg_sync_wrote(&oy,og[1].body_len-1000);
  106912. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  106913. fprintf(stderr,"ok.\n");
  106914. }
  106915. /* Test fractional page inputs: page + incomplete capture */
  106916. {
  106917. ogg_page og_de;
  106918. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  106919. ogg_sync_reset(&oy);
  106920. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  106921. og[1].header_len);
  106922. ogg_sync_wrote(&oy,og[1].header_len);
  106923. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  106924. og[1].body_len);
  106925. ogg_sync_wrote(&oy,og[1].body_len);
  106926. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  106927. 20);
  106928. ogg_sync_wrote(&oy,20);
  106929. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  106930. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106931. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  106932. og[1].header_len-20);
  106933. ogg_sync_wrote(&oy,og[1].header_len-20);
  106934. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  106935. og[1].body_len);
  106936. ogg_sync_wrote(&oy,og[1].body_len);
  106937. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  106938. fprintf(stderr,"ok.\n");
  106939. }
  106940. /* Test recapture: garbage + page */
  106941. {
  106942. ogg_page og_de;
  106943. fprintf(stderr,"Testing search for capture... ");
  106944. ogg_sync_reset(&oy);
  106945. /* 'garbage' */
  106946. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  106947. og[1].body_len);
  106948. ogg_sync_wrote(&oy,og[1].body_len);
  106949. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  106950. og[1].header_len);
  106951. ogg_sync_wrote(&oy,og[1].header_len);
  106952. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  106953. og[1].body_len);
  106954. ogg_sync_wrote(&oy,og[1].body_len);
  106955. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  106956. 20);
  106957. ogg_sync_wrote(&oy,20);
  106958. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106959. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  106960. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106961. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  106962. og[2].header_len-20);
  106963. ogg_sync_wrote(&oy,og[2].header_len-20);
  106964. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  106965. og[2].body_len);
  106966. ogg_sync_wrote(&oy,og[2].body_len);
  106967. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  106968. fprintf(stderr,"ok.\n");
  106969. }
  106970. /* Test recapture: page + garbage + page */
  106971. {
  106972. ogg_page og_de;
  106973. fprintf(stderr,"Testing recapture... ");
  106974. ogg_sync_reset(&oy);
  106975. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  106976. og[1].header_len);
  106977. ogg_sync_wrote(&oy,og[1].header_len);
  106978. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  106979. og[1].body_len);
  106980. ogg_sync_wrote(&oy,og[1].body_len);
  106981. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  106982. og[2].header_len);
  106983. ogg_sync_wrote(&oy,og[2].header_len);
  106984. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  106985. og[2].header_len);
  106986. ogg_sync_wrote(&oy,og[2].header_len);
  106987. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  106988. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  106989. og[2].body_len-5);
  106990. ogg_sync_wrote(&oy,og[2].body_len-5);
  106991. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  106992. og[3].header_len);
  106993. ogg_sync_wrote(&oy,og[3].header_len);
  106994. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  106995. og[3].body_len);
  106996. ogg_sync_wrote(&oy,og[3].body_len);
  106997. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106998. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  106999. fprintf(stderr,"ok.\n");
  107000. }
  107001. /* Free page data that was previously copied */
  107002. {
  107003. for(i=0;i<5;i++){
  107004. free_page(&og[i]);
  107005. }
  107006. }
  107007. }
  107008. return(0);
  107009. }
  107010. #endif
  107011. #endif
  107012. /*** End of inlined file: framing.c ***/
  107013. /*** Start of inlined file: analysis.c ***/
  107014. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107015. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107016. // tasks..
  107017. #if JUCE_MSVC
  107018. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107019. #endif
  107020. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107021. #if JUCE_USE_OGGVORBIS
  107022. #include <stdio.h>
  107023. #include <string.h>
  107024. #include <math.h>
  107025. /*** Start of inlined file: codec_internal.h ***/
  107026. #ifndef _V_CODECI_H_
  107027. #define _V_CODECI_H_
  107028. /*** Start of inlined file: envelope.h ***/
  107029. #ifndef _V_ENVELOPE_
  107030. #define _V_ENVELOPE_
  107031. /*** Start of inlined file: mdct.h ***/
  107032. #ifndef _OGG_mdct_H_
  107033. #define _OGG_mdct_H_
  107034. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  107035. #ifdef MDCT_INTEGERIZED
  107036. #define DATA_TYPE int
  107037. #define REG_TYPE register int
  107038. #define TRIGBITS 14
  107039. #define cPI3_8 6270
  107040. #define cPI2_8 11585
  107041. #define cPI1_8 15137
  107042. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  107043. #define MULT_NORM(x) ((x)>>TRIGBITS)
  107044. #define HALVE(x) ((x)>>1)
  107045. #else
  107046. #define DATA_TYPE float
  107047. #define REG_TYPE float
  107048. #define cPI3_8 .38268343236508977175F
  107049. #define cPI2_8 .70710678118654752441F
  107050. #define cPI1_8 .92387953251128675613F
  107051. #define FLOAT_CONV(x) (x)
  107052. #define MULT_NORM(x) (x)
  107053. #define HALVE(x) ((x)*.5f)
  107054. #endif
  107055. typedef struct {
  107056. int n;
  107057. int log2n;
  107058. DATA_TYPE *trig;
  107059. int *bitrev;
  107060. DATA_TYPE scale;
  107061. } mdct_lookup;
  107062. extern void mdct_init(mdct_lookup *lookup,int n);
  107063. extern void mdct_clear(mdct_lookup *l);
  107064. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  107065. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  107066. #endif
  107067. /*** End of inlined file: mdct.h ***/
  107068. #define VE_PRE 16
  107069. #define VE_WIN 4
  107070. #define VE_POST 2
  107071. #define VE_AMP (VE_PRE+VE_POST-1)
  107072. #define VE_BANDS 7
  107073. #define VE_NEARDC 15
  107074. #define VE_MINSTRETCH 2 /* a bit less than short block */
  107075. #define VE_MAXSTRETCH 12 /* one-third full block */
  107076. typedef struct {
  107077. float ampbuf[VE_AMP];
  107078. int ampptr;
  107079. float nearDC[VE_NEARDC];
  107080. float nearDC_acc;
  107081. float nearDC_partialacc;
  107082. int nearptr;
  107083. } envelope_filter_state;
  107084. typedef struct {
  107085. int begin;
  107086. int end;
  107087. float *window;
  107088. float total;
  107089. } envelope_band;
  107090. typedef struct {
  107091. int ch;
  107092. int winlength;
  107093. int searchstep;
  107094. float minenergy;
  107095. mdct_lookup mdct;
  107096. float *mdct_win;
  107097. envelope_band band[VE_BANDS];
  107098. envelope_filter_state *filter;
  107099. int stretch;
  107100. int *mark;
  107101. long storage;
  107102. long current;
  107103. long curmark;
  107104. long cursor;
  107105. } envelope_lookup;
  107106. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  107107. extern void _ve_envelope_clear(envelope_lookup *e);
  107108. extern long _ve_envelope_search(vorbis_dsp_state *v);
  107109. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  107110. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  107111. #endif
  107112. /*** End of inlined file: envelope.h ***/
  107113. /*** Start of inlined file: codebook.h ***/
  107114. #ifndef _V_CODEBOOK_H_
  107115. #define _V_CODEBOOK_H_
  107116. /* This structure encapsulates huffman and VQ style encoding books; it
  107117. doesn't do anything specific to either.
  107118. valuelist/quantlist are nonNULL (and q_* significant) only if
  107119. there's entry->value mapping to be done.
  107120. If encode-side mapping must be done (and thus the entry needs to be
  107121. hunted), the auxiliary encode pointer will point to a decision
  107122. tree. This is true of both VQ and huffman, but is mostly useful
  107123. with VQ.
  107124. */
  107125. typedef struct static_codebook{
  107126. long dim; /* codebook dimensions (elements per vector) */
  107127. long entries; /* codebook entries */
  107128. long *lengthlist; /* codeword lengths in bits */
  107129. /* mapping ***************************************************************/
  107130. int maptype; /* 0=none
  107131. 1=implicitly populated values from map column
  107132. 2=listed arbitrary values */
  107133. /* The below does a linear, single monotonic sequence mapping. */
  107134. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  107135. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  107136. int q_quant; /* bits: 0 < quant <= 16 */
  107137. int q_sequencep; /* bitflag */
  107138. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  107139. map == 2: list of dim*entries quantized entry vals
  107140. */
  107141. /* encode helpers ********************************************************/
  107142. struct encode_aux_nearestmatch *nearest_tree;
  107143. struct encode_aux_threshmatch *thresh_tree;
  107144. struct encode_aux_pigeonhole *pigeon_tree;
  107145. int allocedp;
  107146. } static_codebook;
  107147. /* this structures an arbitrary trained book to quickly find the
  107148. nearest cell match */
  107149. typedef struct encode_aux_nearestmatch{
  107150. /* pre-calculated partitioning tree */
  107151. long *ptr0;
  107152. long *ptr1;
  107153. long *p; /* decision points (each is an entry) */
  107154. long *q; /* decision points (each is an entry) */
  107155. long aux; /* number of tree entries */
  107156. long alloc;
  107157. } encode_aux_nearestmatch;
  107158. /* assumes a maptype of 1; encode side only, so that's OK */
  107159. typedef struct encode_aux_threshmatch{
  107160. float *quantthresh;
  107161. long *quantmap;
  107162. int quantvals;
  107163. int threshvals;
  107164. } encode_aux_threshmatch;
  107165. typedef struct encode_aux_pigeonhole{
  107166. float min;
  107167. float del;
  107168. int mapentries;
  107169. int quantvals;
  107170. long *pigeonmap;
  107171. long fittotal;
  107172. long *fitlist;
  107173. long *fitmap;
  107174. long *fitlength;
  107175. } encode_aux_pigeonhole;
  107176. typedef struct codebook{
  107177. long dim; /* codebook dimensions (elements per vector) */
  107178. long entries; /* codebook entries */
  107179. long used_entries; /* populated codebook entries */
  107180. const static_codebook *c;
  107181. /* for encode, the below are entry-ordered, fully populated */
  107182. /* for decode, the below are ordered by bitreversed codeword and only
  107183. used entries are populated */
  107184. float *valuelist; /* list of dim*entries actual entry values */
  107185. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  107186. int *dec_index; /* only used if sparseness collapsed */
  107187. char *dec_codelengths;
  107188. ogg_uint32_t *dec_firsttable;
  107189. int dec_firsttablen;
  107190. int dec_maxlength;
  107191. } codebook;
  107192. extern void vorbis_staticbook_clear(static_codebook *b);
  107193. extern void vorbis_staticbook_destroy(static_codebook *b);
  107194. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  107195. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  107196. extern void vorbis_book_clear(codebook *b);
  107197. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  107198. extern float *_book_logdist(const static_codebook *b,float *vals);
  107199. extern float _float32_unpack(long val);
  107200. extern long _float32_pack(float val);
  107201. extern int _best(codebook *book, float *a, int step);
  107202. extern int _ilog(unsigned int v);
  107203. extern long _book_maptype1_quantvals(const static_codebook *b);
  107204. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  107205. extern long vorbis_book_codeword(codebook *book,int entry);
  107206. extern long vorbis_book_codelen(codebook *book,int entry);
  107207. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  107208. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  107209. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  107210. extern int vorbis_book_errorv(codebook *book, float *a);
  107211. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  107212. oggpack_buffer *b);
  107213. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  107214. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  107215. oggpack_buffer *b,int n);
  107216. extern long vorbis_book_decodev_set(codebook *book, float *a,
  107217. oggpack_buffer *b,int n);
  107218. extern long vorbis_book_decodev_add(codebook *book, float *a,
  107219. oggpack_buffer *b,int n);
  107220. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  107221. long off,int ch,
  107222. oggpack_buffer *b,int n);
  107223. #endif
  107224. /*** End of inlined file: codebook.h ***/
  107225. #define BLOCKTYPE_IMPULSE 0
  107226. #define BLOCKTYPE_PADDING 1
  107227. #define BLOCKTYPE_TRANSITION 0
  107228. #define BLOCKTYPE_LONG 1
  107229. #define PACKETBLOBS 15
  107230. typedef struct vorbis_block_internal{
  107231. float **pcmdelay; /* this is a pointer into local storage */
  107232. float ampmax;
  107233. int blocktype;
  107234. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  107235. blob [PACKETBLOBS/2] points to
  107236. the oggpack_buffer in the
  107237. main vorbis_block */
  107238. } vorbis_block_internal;
  107239. typedef void vorbis_look_floor;
  107240. typedef void vorbis_look_residue;
  107241. typedef void vorbis_look_transform;
  107242. /* mode ************************************************************/
  107243. typedef struct {
  107244. int blockflag;
  107245. int windowtype;
  107246. int transformtype;
  107247. int mapping;
  107248. } vorbis_info_mode;
  107249. typedef void vorbis_info_floor;
  107250. typedef void vorbis_info_residue;
  107251. typedef void vorbis_info_mapping;
  107252. /*** Start of inlined file: psy.h ***/
  107253. #ifndef _V_PSY_H_
  107254. #define _V_PSY_H_
  107255. /*** Start of inlined file: smallft.h ***/
  107256. #ifndef _V_SMFT_H_
  107257. #define _V_SMFT_H_
  107258. typedef struct {
  107259. int n;
  107260. float *trigcache;
  107261. int *splitcache;
  107262. } drft_lookup;
  107263. extern void drft_forward(drft_lookup *l,float *data);
  107264. extern void drft_backward(drft_lookup *l,float *data);
  107265. extern void drft_init(drft_lookup *l,int n);
  107266. extern void drft_clear(drft_lookup *l);
  107267. #endif
  107268. /*** End of inlined file: smallft.h ***/
  107269. /*** Start of inlined file: backends.h ***/
  107270. /* this is exposed up here because we need it for static modes.
  107271. Lookups for each backend aren't exposed because there's no reason
  107272. to do so */
  107273. #ifndef _vorbis_backend_h_
  107274. #define _vorbis_backend_h_
  107275. /* this would all be simpler/shorter with templates, but.... */
  107276. /* Floor backend generic *****************************************/
  107277. typedef struct{
  107278. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  107279. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  107280. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  107281. void (*free_info) (vorbis_info_floor *);
  107282. void (*free_look) (vorbis_look_floor *);
  107283. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  107284. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  107285. void *buffer,float *);
  107286. } vorbis_func_floor;
  107287. typedef struct{
  107288. int order;
  107289. long rate;
  107290. long barkmap;
  107291. int ampbits;
  107292. int ampdB;
  107293. int numbooks; /* <= 16 */
  107294. int books[16];
  107295. float lessthan; /* encode-only config setting hacks for libvorbis */
  107296. float greaterthan; /* encode-only config setting hacks for libvorbis */
  107297. } vorbis_info_floor0;
  107298. #define VIF_POSIT 63
  107299. #define VIF_CLASS 16
  107300. #define VIF_PARTS 31
  107301. typedef struct{
  107302. int partitions; /* 0 to 31 */
  107303. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  107304. int class_dim[VIF_CLASS]; /* 1 to 8 */
  107305. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  107306. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  107307. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  107308. int mult; /* 1 2 3 or 4 */
  107309. int postlist[VIF_POSIT+2]; /* first two implicit */
  107310. /* encode side analysis parameters */
  107311. float maxover;
  107312. float maxunder;
  107313. float maxerr;
  107314. float twofitweight;
  107315. float twofitatten;
  107316. int n;
  107317. } vorbis_info_floor1;
  107318. /* Residue backend generic *****************************************/
  107319. typedef struct{
  107320. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  107321. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  107322. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  107323. vorbis_info_residue *);
  107324. void (*free_info) (vorbis_info_residue *);
  107325. void (*free_look) (vorbis_look_residue *);
  107326. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  107327. float **,int *,int);
  107328. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  107329. vorbis_look_residue *,
  107330. float **,float **,int *,int,long **);
  107331. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  107332. float **,int *,int);
  107333. } vorbis_func_residue;
  107334. typedef struct vorbis_info_residue0{
  107335. /* block-partitioned VQ coded straight residue */
  107336. long begin;
  107337. long end;
  107338. /* first stage (lossless partitioning) */
  107339. int grouping; /* group n vectors per partition */
  107340. int partitions; /* possible codebooks for a partition */
  107341. int groupbook; /* huffbook for partitioning */
  107342. int secondstages[64]; /* expanded out to pointers in lookup */
  107343. int booklist[256]; /* list of second stage books */
  107344. float classmetric1[64];
  107345. float classmetric2[64];
  107346. } vorbis_info_residue0;
  107347. /* Mapping backend generic *****************************************/
  107348. typedef struct{
  107349. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  107350. oggpack_buffer *);
  107351. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  107352. void (*free_info) (vorbis_info_mapping *);
  107353. int (*forward) (struct vorbis_block *vb);
  107354. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  107355. } vorbis_func_mapping;
  107356. typedef struct vorbis_info_mapping0{
  107357. int submaps; /* <= 16 */
  107358. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  107359. int floorsubmap[16]; /* [mux] submap to floors */
  107360. int residuesubmap[16]; /* [mux] submap to residue */
  107361. int coupling_steps;
  107362. int coupling_mag[256];
  107363. int coupling_ang[256];
  107364. } vorbis_info_mapping0;
  107365. #endif
  107366. /*** End of inlined file: backends.h ***/
  107367. #ifndef EHMER_MAX
  107368. #define EHMER_MAX 56
  107369. #endif
  107370. /* psychoacoustic setup ********************************************/
  107371. #define P_BANDS 17 /* 62Hz to 16kHz */
  107372. #define P_LEVELS 8 /* 30dB to 100dB */
  107373. #define P_LEVEL_0 30. /* 30 dB */
  107374. #define P_NOISECURVES 3
  107375. #define NOISE_COMPAND_LEVELS 40
  107376. typedef struct vorbis_info_psy{
  107377. int blockflag;
  107378. float ath_adjatt;
  107379. float ath_maxatt;
  107380. float tone_masteratt[P_NOISECURVES];
  107381. float tone_centerboost;
  107382. float tone_decay;
  107383. float tone_abs_limit;
  107384. float toneatt[P_BANDS];
  107385. int noisemaskp;
  107386. float noisemaxsupp;
  107387. float noisewindowlo;
  107388. float noisewindowhi;
  107389. int noisewindowlomin;
  107390. int noisewindowhimin;
  107391. int noisewindowfixed;
  107392. float noiseoff[P_NOISECURVES][P_BANDS];
  107393. float noisecompand[NOISE_COMPAND_LEVELS];
  107394. float max_curve_dB;
  107395. int normal_channel_p;
  107396. int normal_point_p;
  107397. int normal_start;
  107398. int normal_partition;
  107399. double normal_thresh;
  107400. } vorbis_info_psy;
  107401. typedef struct{
  107402. int eighth_octave_lines;
  107403. /* for block long/short tuning; encode only */
  107404. float preecho_thresh[VE_BANDS];
  107405. float postecho_thresh[VE_BANDS];
  107406. float stretch_penalty;
  107407. float preecho_minenergy;
  107408. float ampmax_att_per_sec;
  107409. /* channel coupling config */
  107410. int coupling_pkHz[PACKETBLOBS];
  107411. int coupling_pointlimit[2][PACKETBLOBS];
  107412. int coupling_prepointamp[PACKETBLOBS];
  107413. int coupling_postpointamp[PACKETBLOBS];
  107414. int sliding_lowpass[2][PACKETBLOBS];
  107415. } vorbis_info_psy_global;
  107416. typedef struct {
  107417. float ampmax;
  107418. int channels;
  107419. vorbis_info_psy_global *gi;
  107420. int coupling_pointlimit[2][P_NOISECURVES];
  107421. } vorbis_look_psy_global;
  107422. typedef struct {
  107423. int n;
  107424. struct vorbis_info_psy *vi;
  107425. float ***tonecurves;
  107426. float **noiseoffset;
  107427. float *ath;
  107428. long *octave; /* in n.ocshift format */
  107429. long *bark;
  107430. long firstoc;
  107431. long shiftoc;
  107432. int eighth_octave_lines; /* power of two, please */
  107433. int total_octave_lines;
  107434. long rate; /* cache it */
  107435. float m_val; /* Masking compensation value */
  107436. } vorbis_look_psy;
  107437. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  107438. vorbis_info_psy_global *gi,int n,long rate);
  107439. extern void _vp_psy_clear(vorbis_look_psy *p);
  107440. extern void *_vi_psy_dup(void *source);
  107441. extern void _vi_psy_free(vorbis_info_psy *i);
  107442. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  107443. extern void _vp_remove_floor(vorbis_look_psy *p,
  107444. float *mdct,
  107445. int *icodedflr,
  107446. float *residue,
  107447. int sliding_lowpass);
  107448. extern void _vp_noisemask(vorbis_look_psy *p,
  107449. float *logmdct,
  107450. float *logmask);
  107451. extern void _vp_tonemask(vorbis_look_psy *p,
  107452. float *logfft,
  107453. float *logmask,
  107454. float global_specmax,
  107455. float local_specmax);
  107456. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  107457. float *noise,
  107458. float *tone,
  107459. int offset_select,
  107460. float *logmask,
  107461. float *mdct,
  107462. float *logmdct);
  107463. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  107464. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  107465. vorbis_info_psy_global *g,
  107466. vorbis_look_psy *p,
  107467. vorbis_info_mapping0 *vi,
  107468. float **mdct);
  107469. extern void _vp_couple(int blobno,
  107470. vorbis_info_psy_global *g,
  107471. vorbis_look_psy *p,
  107472. vorbis_info_mapping0 *vi,
  107473. float **res,
  107474. float **mag_memo,
  107475. int **mag_sort,
  107476. int **ifloor,
  107477. int *nonzero,
  107478. int sliding_lowpass);
  107479. extern void _vp_noise_normalize(vorbis_look_psy *p,
  107480. float *in,float *out,int *sortedindex);
  107481. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  107482. float *magnitudes,int *sortedindex);
  107483. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  107484. vorbis_look_psy *p,
  107485. vorbis_info_mapping0 *vi,
  107486. float **mags);
  107487. extern void hf_reduction(vorbis_info_psy_global *g,
  107488. vorbis_look_psy *p,
  107489. vorbis_info_mapping0 *vi,
  107490. float **mdct);
  107491. #endif
  107492. /*** End of inlined file: psy.h ***/
  107493. /*** Start of inlined file: bitrate.h ***/
  107494. #ifndef _V_BITRATE_H_
  107495. #define _V_BITRATE_H_
  107496. /*** Start of inlined file: os.h ***/
  107497. #ifndef _OS_H
  107498. #define _OS_H
  107499. /********************************************************************
  107500. * *
  107501. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  107502. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  107503. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  107504. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  107505. * *
  107506. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  107507. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  107508. * *
  107509. ********************************************************************
  107510. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  107511. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  107512. ********************************************************************/
  107513. #ifdef HAVE_CONFIG_H
  107514. #include "config.h"
  107515. #endif
  107516. #include <math.h>
  107517. /*** Start of inlined file: misc.h ***/
  107518. #ifndef _V_RANDOM_H_
  107519. #define _V_RANDOM_H_
  107520. extern int analysis_noisy;
  107521. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  107522. extern void _vorbis_block_ripcord(vorbis_block *vb);
  107523. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  107524. ogg_int64_t off);
  107525. #ifdef DEBUG_MALLOC
  107526. #define _VDBG_GRAPHFILE "malloc.m"
  107527. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  107528. extern void _VDBG_free(void *ptr,char *file,long line);
  107529. #ifndef MISC_C
  107530. #undef _ogg_malloc
  107531. #undef _ogg_calloc
  107532. #undef _ogg_realloc
  107533. #undef _ogg_free
  107534. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  107535. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  107536. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  107537. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  107538. #endif
  107539. #endif
  107540. #endif
  107541. /*** End of inlined file: misc.h ***/
  107542. #ifndef _V_IFDEFJAIL_H_
  107543. # define _V_IFDEFJAIL_H_
  107544. # ifdef __GNUC__
  107545. # define STIN static __inline__
  107546. # elif _WIN32
  107547. # define STIN static __inline
  107548. # else
  107549. # define STIN static
  107550. # endif
  107551. #ifdef DJGPP
  107552. # define rint(x) (floor((x)+0.5f))
  107553. #endif
  107554. #ifndef M_PI
  107555. # define M_PI (3.1415926536f)
  107556. #endif
  107557. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  107558. # include <malloc.h>
  107559. # define rint(x) (floor((x)+0.5f))
  107560. # define NO_FLOAT_MATH_LIB
  107561. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  107562. #endif
  107563. #if defined(__SYMBIAN32__) && defined(__WINS__)
  107564. void *_alloca(size_t size);
  107565. # define alloca _alloca
  107566. #endif
  107567. #ifndef FAST_HYPOT
  107568. # define FAST_HYPOT hypot
  107569. #endif
  107570. #endif
  107571. #ifdef HAVE_ALLOCA_H
  107572. # include <alloca.h>
  107573. #endif
  107574. #ifdef USE_MEMORY_H
  107575. # include <memory.h>
  107576. #endif
  107577. #ifndef min
  107578. # define min(x,y) ((x)>(y)?(y):(x))
  107579. #endif
  107580. #ifndef max
  107581. # define max(x,y) ((x)<(y)?(y):(x))
  107582. #endif
  107583. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  107584. # define VORBIS_FPU_CONTROL
  107585. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  107586. Because of encapsulation constraints (GCC can't see inside the asm
  107587. block and so we end up doing stupid things like a store/load that
  107588. is collectively a noop), we do it this way */
  107589. /* we must set up the fpu before this works!! */
  107590. typedef ogg_int16_t vorbis_fpu_control;
  107591. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  107592. ogg_int16_t ret;
  107593. ogg_int16_t temp;
  107594. __asm__ __volatile__("fnstcw %0\n\t"
  107595. "movw %0,%%dx\n\t"
  107596. "orw $62463,%%dx\n\t"
  107597. "movw %%dx,%1\n\t"
  107598. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  107599. *fpu=ret;
  107600. }
  107601. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  107602. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  107603. }
  107604. /* assumes the FPU is in round mode! */
  107605. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  107606. we get extra fst/fld to
  107607. truncate precision */
  107608. int i;
  107609. __asm__("fistl %0": "=m"(i) : "t"(f));
  107610. return(i);
  107611. }
  107612. #endif
  107613. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  107614. # define VORBIS_FPU_CONTROL
  107615. typedef ogg_int16_t vorbis_fpu_control;
  107616. static __inline int vorbis_ftoi(double f){
  107617. int i;
  107618. __asm{
  107619. fld f
  107620. fistp i
  107621. }
  107622. return i;
  107623. }
  107624. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  107625. }
  107626. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  107627. }
  107628. #endif
  107629. #ifndef VORBIS_FPU_CONTROL
  107630. typedef int vorbis_fpu_control;
  107631. static int vorbis_ftoi(double f){
  107632. return (int)(f+.5);
  107633. }
  107634. /* We don't have special code for this compiler/arch, so do it the slow way */
  107635. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  107636. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  107637. #endif
  107638. #endif /* _OS_H */
  107639. /*** End of inlined file: os.h ***/
  107640. /* encode side bitrate tracking */
  107641. typedef struct bitrate_manager_state {
  107642. int managed;
  107643. long avg_reservoir;
  107644. long minmax_reservoir;
  107645. long avg_bitsper;
  107646. long min_bitsper;
  107647. long max_bitsper;
  107648. long short_per_long;
  107649. double avgfloat;
  107650. vorbis_block *vb;
  107651. int choice;
  107652. } bitrate_manager_state;
  107653. typedef struct bitrate_manager_info{
  107654. long avg_rate;
  107655. long min_rate;
  107656. long max_rate;
  107657. long reservoir_bits;
  107658. double reservoir_bias;
  107659. double slew_damp;
  107660. } bitrate_manager_info;
  107661. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  107662. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  107663. extern int vorbis_bitrate_managed(vorbis_block *vb);
  107664. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  107665. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  107666. #endif
  107667. /*** End of inlined file: bitrate.h ***/
  107668. static int ilog(unsigned int v){
  107669. int ret=0;
  107670. while(v){
  107671. ret++;
  107672. v>>=1;
  107673. }
  107674. return(ret);
  107675. }
  107676. static int ilog2(unsigned int v){
  107677. int ret=0;
  107678. if(v)--v;
  107679. while(v){
  107680. ret++;
  107681. v>>=1;
  107682. }
  107683. return(ret);
  107684. }
  107685. typedef struct private_state {
  107686. /* local lookup storage */
  107687. envelope_lookup *ve; /* envelope lookup */
  107688. int window[2];
  107689. vorbis_look_transform **transform[2]; /* block, type */
  107690. drft_lookup fft_look[2];
  107691. int modebits;
  107692. vorbis_look_floor **flr;
  107693. vorbis_look_residue **residue;
  107694. vorbis_look_psy *psy;
  107695. vorbis_look_psy_global *psy_g_look;
  107696. /* local storage, only used on the encoding side. This way the
  107697. application does not need to worry about freeing some packets'
  107698. memory and not others'; packet storage is always tracked.
  107699. Cleared next call to a _dsp_ function */
  107700. unsigned char *header;
  107701. unsigned char *header1;
  107702. unsigned char *header2;
  107703. bitrate_manager_state bms;
  107704. ogg_int64_t sample_count;
  107705. } private_state;
  107706. /* codec_setup_info contains all the setup information specific to the
  107707. specific compression/decompression mode in progress (eg,
  107708. psychoacoustic settings, channel setup, options, codebook
  107709. etc).
  107710. *********************************************************************/
  107711. /*** Start of inlined file: highlevel.h ***/
  107712. typedef struct highlevel_byblocktype {
  107713. double tone_mask_setting;
  107714. double tone_peaklimit_setting;
  107715. double noise_bias_setting;
  107716. double noise_compand_setting;
  107717. } highlevel_byblocktype;
  107718. typedef struct highlevel_encode_setup {
  107719. void *setup;
  107720. int set_in_stone;
  107721. double base_setting;
  107722. double long_setting;
  107723. double short_setting;
  107724. double impulse_noisetune;
  107725. int managed;
  107726. long bitrate_min;
  107727. long bitrate_av;
  107728. double bitrate_av_damp;
  107729. long bitrate_max;
  107730. long bitrate_reservoir;
  107731. double bitrate_reservoir_bias;
  107732. int impulse_block_p;
  107733. int noise_normalize_p;
  107734. double stereo_point_setting;
  107735. double lowpass_kHz;
  107736. double ath_floating_dB;
  107737. double ath_absolute_dB;
  107738. double amplitude_track_dBpersec;
  107739. double trigger_setting;
  107740. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  107741. } highlevel_encode_setup;
  107742. /*** End of inlined file: highlevel.h ***/
  107743. typedef struct codec_setup_info {
  107744. /* Vorbis supports only short and long blocks, but allows the
  107745. encoder to choose the sizes */
  107746. long blocksizes[2];
  107747. /* modes are the primary means of supporting on-the-fly different
  107748. blocksizes, different channel mappings (LR or M/A),
  107749. different residue backends, etc. Each mode consists of a
  107750. blocksize flag and a mapping (along with the mapping setup */
  107751. int modes;
  107752. int maps;
  107753. int floors;
  107754. int residues;
  107755. int books;
  107756. int psys; /* encode only */
  107757. vorbis_info_mode *mode_param[64];
  107758. int map_type[64];
  107759. vorbis_info_mapping *map_param[64];
  107760. int floor_type[64];
  107761. vorbis_info_floor *floor_param[64];
  107762. int residue_type[64];
  107763. vorbis_info_residue *residue_param[64];
  107764. static_codebook *book_param[256];
  107765. codebook *fullbooks;
  107766. vorbis_info_psy *psy_param[4]; /* encode only */
  107767. vorbis_info_psy_global psy_g_param;
  107768. bitrate_manager_info bi;
  107769. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  107770. highly redundant structure, but
  107771. improves clarity of program flow. */
  107772. int halfrate_flag; /* painless downsample for decode */
  107773. } codec_setup_info;
  107774. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  107775. extern void _vp_global_free(vorbis_look_psy_global *look);
  107776. #endif
  107777. /*** End of inlined file: codec_internal.h ***/
  107778. /*** Start of inlined file: registry.h ***/
  107779. #ifndef _V_REG_H_
  107780. #define _V_REG_H_
  107781. #define VI_TRANSFORMB 1
  107782. #define VI_WINDOWB 1
  107783. #define VI_TIMEB 1
  107784. #define VI_FLOORB 2
  107785. #define VI_RESB 3
  107786. #define VI_MAPB 1
  107787. extern vorbis_func_floor *_floor_P[];
  107788. extern vorbis_func_residue *_residue_P[];
  107789. extern vorbis_func_mapping *_mapping_P[];
  107790. #endif
  107791. /*** End of inlined file: registry.h ***/
  107792. /*** Start of inlined file: scales.h ***/
  107793. #ifndef _V_SCALES_H_
  107794. #define _V_SCALES_H_
  107795. #include <math.h>
  107796. /* 20log10(x) */
  107797. #define VORBIS_IEEE_FLOAT32 1
  107798. #ifdef VORBIS_IEEE_FLOAT32
  107799. static float unitnorm(float x){
  107800. union {
  107801. ogg_uint32_t i;
  107802. float f;
  107803. } ix;
  107804. ix.f = x;
  107805. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  107806. return ix.f;
  107807. }
  107808. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  107809. static float todB(const float *x){
  107810. union {
  107811. ogg_uint32_t i;
  107812. float f;
  107813. } ix;
  107814. ix.f = *x;
  107815. ix.i = ix.i&0x7fffffff;
  107816. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  107817. }
  107818. #define todB_nn(x) todB(x)
  107819. #else
  107820. static float unitnorm(float x){
  107821. if(x<0)return(-1.f);
  107822. return(1.f);
  107823. }
  107824. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  107825. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  107826. #endif
  107827. #define fromdB(x) (exp((x)*.11512925f))
  107828. /* The bark scale equations are approximations, since the original
  107829. table was somewhat hand rolled. The below are chosen to have the
  107830. best possible fit to the rolled tables, thus their somewhat odd
  107831. appearance (these are more accurate and over a longer range than
  107832. the oft-quoted bark equations found in the texts I have). The
  107833. approximations are valid from 0 - 30kHz (nyquist) or so.
  107834. all f in Hz, z in Bark */
  107835. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  107836. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  107837. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  107838. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  107839. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  107840. 0.0 */
  107841. #define toOC(n) (log(n)*1.442695f-5.965784f)
  107842. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  107843. #endif
  107844. /*** End of inlined file: scales.h ***/
  107845. int analysis_noisy=1;
  107846. /* decides between modes, dispatches to the appropriate mapping. */
  107847. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  107848. int ret,i;
  107849. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  107850. vb->glue_bits=0;
  107851. vb->time_bits=0;
  107852. vb->floor_bits=0;
  107853. vb->res_bits=0;
  107854. /* first things first. Make sure encode is ready */
  107855. for(i=0;i<PACKETBLOBS;i++)
  107856. oggpack_reset(vbi->packetblob[i]);
  107857. /* we only have one mapping type (0), and we let the mapping code
  107858. itself figure out what soft mode to use. This allows easier
  107859. bitrate management */
  107860. if((ret=_mapping_P[0]->forward(vb)))
  107861. return(ret);
  107862. if(op){
  107863. if(vorbis_bitrate_managed(vb))
  107864. /* The app is using a bitmanaged mode... but not using the
  107865. bitrate management interface. */
  107866. return(OV_EINVAL);
  107867. op->packet=oggpack_get_buffer(&vb->opb);
  107868. op->bytes=oggpack_bytes(&vb->opb);
  107869. op->b_o_s=0;
  107870. op->e_o_s=vb->eofflag;
  107871. op->granulepos=vb->granulepos;
  107872. op->packetno=vb->sequence; /* for sake of completeness */
  107873. }
  107874. return(0);
  107875. }
  107876. /* there was no great place to put this.... */
  107877. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  107878. int j;
  107879. FILE *of;
  107880. char buffer[80];
  107881. /* if(i==5870){*/
  107882. sprintf(buffer,"%s_%d.m",base,i);
  107883. of=fopen(buffer,"w");
  107884. if(!of)perror("failed to open data dump file");
  107885. for(j=0;j<n;j++){
  107886. if(bark){
  107887. float b=toBARK((4000.f*j/n)+.25);
  107888. fprintf(of,"%f ",b);
  107889. }else
  107890. if(off!=0)
  107891. fprintf(of,"%f ",(double)(j+off)/8000.);
  107892. else
  107893. fprintf(of,"%f ",(double)j);
  107894. if(dB){
  107895. float val;
  107896. if(v[j]==0.)
  107897. val=-140.;
  107898. else
  107899. val=todB(v+j);
  107900. fprintf(of,"%f\n",val);
  107901. }else{
  107902. fprintf(of,"%f\n",v[j]);
  107903. }
  107904. }
  107905. fclose(of);
  107906. /* } */
  107907. }
  107908. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  107909. ogg_int64_t off){
  107910. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  107911. }
  107912. #endif
  107913. /*** End of inlined file: analysis.c ***/
  107914. /*** Start of inlined file: bitrate.c ***/
  107915. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107916. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107917. // tasks..
  107918. #if JUCE_MSVC
  107919. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107920. #endif
  107921. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107922. #if JUCE_USE_OGGVORBIS
  107923. #include <stdlib.h>
  107924. #include <string.h>
  107925. #include <math.h>
  107926. /* compute bitrate tracking setup */
  107927. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  107928. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  107929. bitrate_manager_info *bi=&ci->bi;
  107930. memset(bm,0,sizeof(*bm));
  107931. if(bi && (bi->reservoir_bits>0)){
  107932. long ratesamples=vi->rate;
  107933. int halfsamples=ci->blocksizes[0]>>1;
  107934. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  107935. bm->managed=1;
  107936. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  107937. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  107938. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  107939. bm->avgfloat=PACKETBLOBS/2;
  107940. /* not a necessary fix, but one that leads to a more balanced
  107941. typical initialization */
  107942. {
  107943. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  107944. bm->minmax_reservoir=desired_fill;
  107945. bm->avg_reservoir=desired_fill;
  107946. }
  107947. }
  107948. }
  107949. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  107950. memset(bm,0,sizeof(*bm));
  107951. return;
  107952. }
  107953. int vorbis_bitrate_managed(vorbis_block *vb){
  107954. vorbis_dsp_state *vd=vb->vd;
  107955. private_state *b=(private_state*)vd->backend_state;
  107956. bitrate_manager_state *bm=&b->bms;
  107957. if(bm && bm->managed)return(1);
  107958. return(0);
  107959. }
  107960. /* finish taking in the block we just processed */
  107961. int vorbis_bitrate_addblock(vorbis_block *vb){
  107962. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  107963. vorbis_dsp_state *vd=vb->vd;
  107964. private_state *b=(private_state*)vd->backend_state;
  107965. bitrate_manager_state *bm=&b->bms;
  107966. vorbis_info *vi=vd->vi;
  107967. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107968. bitrate_manager_info *bi=&ci->bi;
  107969. int choice=rint(bm->avgfloat);
  107970. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  107971. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  107972. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  107973. int samples=ci->blocksizes[vb->W]>>1;
  107974. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  107975. if(!bm->managed){
  107976. /* not a bitrate managed stream, but for API simplicity, we'll
  107977. buffer the packet to keep the code path clean */
  107978. if(bm->vb)return(-1); /* one has been submitted without
  107979. being claimed */
  107980. bm->vb=vb;
  107981. return(0);
  107982. }
  107983. bm->vb=vb;
  107984. /* look ahead for avg floater */
  107985. if(bm->avg_bitsper>0){
  107986. double slew=0.;
  107987. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  107988. double slewlimit= 15./bi->slew_damp;
  107989. /* choosing a new floater:
  107990. if we're over target, we slew down
  107991. if we're under target, we slew up
  107992. choose slew as follows: look through packetblobs of this frame
  107993. and set slew as the first in the appropriate direction that
  107994. gives us the slew we want. This may mean no slew if delta is
  107995. already favorable.
  107996. Then limit slew to slew max */
  107997. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  107998. while(choice>0 && this_bits>avg_target_bits &&
  107999. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  108000. choice--;
  108001. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  108002. }
  108003. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  108004. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  108005. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  108006. choice++;
  108007. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  108008. }
  108009. }
  108010. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  108011. if(slew<-slewlimit)slew=-slewlimit;
  108012. if(slew>slewlimit)slew=slewlimit;
  108013. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  108014. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  108015. }
  108016. /* enforce min(if used) on the current floater (if used) */
  108017. if(bm->min_bitsper>0){
  108018. /* do we need to force the bitrate up? */
  108019. if(this_bits<min_target_bits){
  108020. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  108021. choice++;
  108022. if(choice>=PACKETBLOBS)break;
  108023. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  108024. }
  108025. }
  108026. }
  108027. /* enforce max (if used) on the current floater (if used) */
  108028. if(bm->max_bitsper>0){
  108029. /* do we need to force the bitrate down? */
  108030. if(this_bits>max_target_bits){
  108031. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  108032. choice--;
  108033. if(choice<0)break;
  108034. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  108035. }
  108036. }
  108037. }
  108038. /* Choice of packetblobs now made based on floater, and min/max
  108039. requirements. Now boundary check extreme choices */
  108040. if(choice<0){
  108041. /* choosing a smaller packetblob is insufficient to trim bitrate.
  108042. frame will need to be truncated */
  108043. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  108044. bm->choice=choice=0;
  108045. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  108046. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  108047. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  108048. }
  108049. }else{
  108050. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  108051. if(choice>=PACKETBLOBS)
  108052. choice=PACKETBLOBS-1;
  108053. bm->choice=choice;
  108054. /* prop up bitrate according to demand. pad this frame out with zeroes */
  108055. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  108056. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  108057. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  108058. }
  108059. /* now we have the final packet and the final packet size. Update statistics */
  108060. /* min and max reservoir */
  108061. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  108062. if(max_target_bits>0 && this_bits>max_target_bits){
  108063. bm->minmax_reservoir+=(this_bits-max_target_bits);
  108064. }else if(min_target_bits>0 && this_bits<min_target_bits){
  108065. bm->minmax_reservoir+=(this_bits-min_target_bits);
  108066. }else{
  108067. /* inbetween; we want to take reservoir toward but not past desired_fill */
  108068. if(bm->minmax_reservoir>desired_fill){
  108069. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  108070. bm->minmax_reservoir+=(this_bits-max_target_bits);
  108071. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  108072. }else{
  108073. bm->minmax_reservoir=desired_fill;
  108074. }
  108075. }else{
  108076. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  108077. bm->minmax_reservoir+=(this_bits-min_target_bits);
  108078. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  108079. }else{
  108080. bm->minmax_reservoir=desired_fill;
  108081. }
  108082. }
  108083. }
  108084. }
  108085. /* avg reservoir */
  108086. if(bm->avg_bitsper>0){
  108087. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  108088. bm->avg_reservoir+=this_bits-avg_target_bits;
  108089. }
  108090. return(0);
  108091. }
  108092. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  108093. private_state *b=(private_state*)vd->backend_state;
  108094. bitrate_manager_state *bm=&b->bms;
  108095. vorbis_block *vb=bm->vb;
  108096. int choice=PACKETBLOBS/2;
  108097. if(!vb)return 0;
  108098. if(op){
  108099. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  108100. if(vorbis_bitrate_managed(vb))
  108101. choice=bm->choice;
  108102. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  108103. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  108104. op->b_o_s=0;
  108105. op->e_o_s=vb->eofflag;
  108106. op->granulepos=vb->granulepos;
  108107. op->packetno=vb->sequence; /* for sake of completeness */
  108108. }
  108109. bm->vb=0;
  108110. return(1);
  108111. }
  108112. #endif
  108113. /*** End of inlined file: bitrate.c ***/
  108114. /*** Start of inlined file: block.c ***/
  108115. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108116. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108117. // tasks..
  108118. #if JUCE_MSVC
  108119. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108120. #endif
  108121. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108122. #if JUCE_USE_OGGVORBIS
  108123. #include <stdio.h>
  108124. #include <stdlib.h>
  108125. #include <string.h>
  108126. /*** Start of inlined file: window.h ***/
  108127. #ifndef _V_WINDOW_
  108128. #define _V_WINDOW_
  108129. extern float *_vorbis_window_get(int n);
  108130. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  108131. int lW,int W,int nW);
  108132. #endif
  108133. /*** End of inlined file: window.h ***/
  108134. /*** Start of inlined file: lpc.h ***/
  108135. #ifndef _V_LPC_H_
  108136. #define _V_LPC_H_
  108137. /* simple linear scale LPC code */
  108138. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  108139. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  108140. float *data,long n);
  108141. #endif
  108142. /*** End of inlined file: lpc.h ***/
  108143. /* pcm accumulator examples (not exhaustive):
  108144. <-------------- lW ---------------->
  108145. <--------------- W ---------------->
  108146. : .....|..... _______________ |
  108147. : .''' | '''_--- | |\ |
  108148. :.....''' |_____--- '''......| | \_______|
  108149. :.................|__________________|_______|__|______|
  108150. |<------ Sl ------>| > Sr < |endW
  108151. |beginSl |endSl | |endSr
  108152. |beginW |endlW |beginSr
  108153. |< lW >|
  108154. <--------------- W ---------------->
  108155. | | .. ______________ |
  108156. | | ' `/ | ---_ |
  108157. |___.'___/`. | ---_____|
  108158. |_______|__|_______|_________________|
  108159. | >|Sl|< |<------ Sr ----->|endW
  108160. | | |endSl |beginSr |endSr
  108161. |beginW | |endlW
  108162. mult[0] |beginSl mult[n]
  108163. <-------------- lW ----------------->
  108164. |<--W-->|
  108165. : .............. ___ | |
  108166. : .''' |`/ \ | |
  108167. :.....''' |/`....\|...|
  108168. :.........................|___|___|___|
  108169. |Sl |Sr |endW
  108170. | | |endSr
  108171. | |beginSr
  108172. | |endSl
  108173. |beginSl
  108174. |beginW
  108175. */
  108176. /* block abstraction setup *********************************************/
  108177. #ifndef WORD_ALIGN
  108178. #define WORD_ALIGN 8
  108179. #endif
  108180. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  108181. int i;
  108182. memset(vb,0,sizeof(*vb));
  108183. vb->vd=v;
  108184. vb->localalloc=0;
  108185. vb->localstore=NULL;
  108186. if(v->analysisp){
  108187. vorbis_block_internal *vbi=(vorbis_block_internal*)
  108188. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  108189. vbi->ampmax=-9999;
  108190. for(i=0;i<PACKETBLOBS;i++){
  108191. if(i==PACKETBLOBS/2){
  108192. vbi->packetblob[i]=&vb->opb;
  108193. }else{
  108194. vbi->packetblob[i]=
  108195. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  108196. }
  108197. oggpack_writeinit(vbi->packetblob[i]);
  108198. }
  108199. }
  108200. return(0);
  108201. }
  108202. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  108203. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  108204. if(bytes+vb->localtop>vb->localalloc){
  108205. /* can't just _ogg_realloc... there are outstanding pointers */
  108206. if(vb->localstore){
  108207. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  108208. vb->totaluse+=vb->localtop;
  108209. link->next=vb->reap;
  108210. link->ptr=vb->localstore;
  108211. vb->reap=link;
  108212. }
  108213. /* highly conservative */
  108214. vb->localalloc=bytes;
  108215. vb->localstore=_ogg_malloc(vb->localalloc);
  108216. vb->localtop=0;
  108217. }
  108218. {
  108219. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  108220. vb->localtop+=bytes;
  108221. return ret;
  108222. }
  108223. }
  108224. /* reap the chain, pull the ripcord */
  108225. void _vorbis_block_ripcord(vorbis_block *vb){
  108226. /* reap the chain */
  108227. struct alloc_chain *reap=vb->reap;
  108228. while(reap){
  108229. struct alloc_chain *next=reap->next;
  108230. _ogg_free(reap->ptr);
  108231. memset(reap,0,sizeof(*reap));
  108232. _ogg_free(reap);
  108233. reap=next;
  108234. }
  108235. /* consolidate storage */
  108236. if(vb->totaluse){
  108237. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  108238. vb->localalloc+=vb->totaluse;
  108239. vb->totaluse=0;
  108240. }
  108241. /* pull the ripcord */
  108242. vb->localtop=0;
  108243. vb->reap=NULL;
  108244. }
  108245. int vorbis_block_clear(vorbis_block *vb){
  108246. int i;
  108247. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  108248. _vorbis_block_ripcord(vb);
  108249. if(vb->localstore)_ogg_free(vb->localstore);
  108250. if(vbi){
  108251. for(i=0;i<PACKETBLOBS;i++){
  108252. oggpack_writeclear(vbi->packetblob[i]);
  108253. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  108254. }
  108255. _ogg_free(vbi);
  108256. }
  108257. memset(vb,0,sizeof(*vb));
  108258. return(0);
  108259. }
  108260. /* Analysis side code, but directly related to blocking. Thus it's
  108261. here and not in analysis.c (which is for analysis transforms only).
  108262. The init is here because some of it is shared */
  108263. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  108264. int i;
  108265. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108266. private_state *b=NULL;
  108267. int hs;
  108268. if(ci==NULL) return 1;
  108269. hs=ci->halfrate_flag;
  108270. memset(v,0,sizeof(*v));
  108271. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  108272. v->vi=vi;
  108273. b->modebits=ilog2(ci->modes);
  108274. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  108275. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  108276. /* MDCT is tranform 0 */
  108277. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  108278. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  108279. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  108280. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  108281. /* Vorbis I uses only window type 0 */
  108282. b->window[0]=ilog2(ci->blocksizes[0])-6;
  108283. b->window[1]=ilog2(ci->blocksizes[1])-6;
  108284. if(encp){ /* encode/decode differ here */
  108285. /* analysis always needs an fft */
  108286. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  108287. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  108288. /* finish the codebooks */
  108289. if(!ci->fullbooks){
  108290. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  108291. for(i=0;i<ci->books;i++)
  108292. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  108293. }
  108294. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  108295. for(i=0;i<ci->psys;i++){
  108296. _vp_psy_init(b->psy+i,
  108297. ci->psy_param[i],
  108298. &ci->psy_g_param,
  108299. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  108300. vi->rate);
  108301. }
  108302. v->analysisp=1;
  108303. }else{
  108304. /* finish the codebooks */
  108305. if(!ci->fullbooks){
  108306. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  108307. for(i=0;i<ci->books;i++){
  108308. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  108309. /* decode codebooks are now standalone after init */
  108310. vorbis_staticbook_destroy(ci->book_param[i]);
  108311. ci->book_param[i]=NULL;
  108312. }
  108313. }
  108314. }
  108315. /* initialize the storage vectors. blocksize[1] is small for encode,
  108316. but the correct size for decode */
  108317. v->pcm_storage=ci->blocksizes[1];
  108318. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  108319. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  108320. {
  108321. int i;
  108322. for(i=0;i<vi->channels;i++)
  108323. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  108324. }
  108325. /* all 1 (large block) or 0 (small block) */
  108326. /* explicitly set for the sake of clarity */
  108327. v->lW=0; /* previous window size */
  108328. v->W=0; /* current window size */
  108329. /* all vector indexes */
  108330. v->centerW=ci->blocksizes[1]/2;
  108331. v->pcm_current=v->centerW;
  108332. /* initialize all the backend lookups */
  108333. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  108334. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  108335. for(i=0;i<ci->floors;i++)
  108336. b->flr[i]=_floor_P[ci->floor_type[i]]->
  108337. look(v,ci->floor_param[i]);
  108338. for(i=0;i<ci->residues;i++)
  108339. b->residue[i]=_residue_P[ci->residue_type[i]]->
  108340. look(v,ci->residue_param[i]);
  108341. return 0;
  108342. }
  108343. /* arbitrary settings and spec-mandated numbers get filled in here */
  108344. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  108345. private_state *b=NULL;
  108346. if(_vds_shared_init(v,vi,1))return 1;
  108347. b=(private_state*)v->backend_state;
  108348. b->psy_g_look=_vp_global_look(vi);
  108349. /* Initialize the envelope state storage */
  108350. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  108351. _ve_envelope_init(b->ve,vi);
  108352. vorbis_bitrate_init(vi,&b->bms);
  108353. /* compressed audio packets start after the headers
  108354. with sequence number 3 */
  108355. v->sequence=3;
  108356. return(0);
  108357. }
  108358. void vorbis_dsp_clear(vorbis_dsp_state *v){
  108359. int i;
  108360. if(v){
  108361. vorbis_info *vi=v->vi;
  108362. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  108363. private_state *b=(private_state*)v->backend_state;
  108364. if(b){
  108365. if(b->ve){
  108366. _ve_envelope_clear(b->ve);
  108367. _ogg_free(b->ve);
  108368. }
  108369. if(b->transform[0]){
  108370. mdct_clear((mdct_lookup*) b->transform[0][0]);
  108371. _ogg_free(b->transform[0][0]);
  108372. _ogg_free(b->transform[0]);
  108373. }
  108374. if(b->transform[1]){
  108375. mdct_clear((mdct_lookup*) b->transform[1][0]);
  108376. _ogg_free(b->transform[1][0]);
  108377. _ogg_free(b->transform[1]);
  108378. }
  108379. if(b->flr){
  108380. for(i=0;i<ci->floors;i++)
  108381. _floor_P[ci->floor_type[i]]->
  108382. free_look(b->flr[i]);
  108383. _ogg_free(b->flr);
  108384. }
  108385. if(b->residue){
  108386. for(i=0;i<ci->residues;i++)
  108387. _residue_P[ci->residue_type[i]]->
  108388. free_look(b->residue[i]);
  108389. _ogg_free(b->residue);
  108390. }
  108391. if(b->psy){
  108392. for(i=0;i<ci->psys;i++)
  108393. _vp_psy_clear(b->psy+i);
  108394. _ogg_free(b->psy);
  108395. }
  108396. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  108397. vorbis_bitrate_clear(&b->bms);
  108398. drft_clear(&b->fft_look[0]);
  108399. drft_clear(&b->fft_look[1]);
  108400. }
  108401. if(v->pcm){
  108402. for(i=0;i<vi->channels;i++)
  108403. if(v->pcm[i])_ogg_free(v->pcm[i]);
  108404. _ogg_free(v->pcm);
  108405. if(v->pcmret)_ogg_free(v->pcmret);
  108406. }
  108407. if(b){
  108408. /* free header, header1, header2 */
  108409. if(b->header)_ogg_free(b->header);
  108410. if(b->header1)_ogg_free(b->header1);
  108411. if(b->header2)_ogg_free(b->header2);
  108412. _ogg_free(b);
  108413. }
  108414. memset(v,0,sizeof(*v));
  108415. }
  108416. }
  108417. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  108418. int i;
  108419. vorbis_info *vi=v->vi;
  108420. private_state *b=(private_state*)v->backend_state;
  108421. /* free header, header1, header2 */
  108422. if(b->header)_ogg_free(b->header);b->header=NULL;
  108423. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  108424. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  108425. /* Do we have enough storage space for the requested buffer? If not,
  108426. expand the PCM (and envelope) storage */
  108427. if(v->pcm_current+vals>=v->pcm_storage){
  108428. v->pcm_storage=v->pcm_current+vals*2;
  108429. for(i=0;i<vi->channels;i++){
  108430. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  108431. }
  108432. }
  108433. for(i=0;i<vi->channels;i++)
  108434. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  108435. return(v->pcmret);
  108436. }
  108437. static void _preextrapolate_helper(vorbis_dsp_state *v){
  108438. int i;
  108439. int order=32;
  108440. float *lpc=(float*)alloca(order*sizeof(*lpc));
  108441. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  108442. long j;
  108443. v->preextrapolate=1;
  108444. if(v->pcm_current-v->centerW>order*2){ /* safety */
  108445. for(i=0;i<v->vi->channels;i++){
  108446. /* need to run the extrapolation in reverse! */
  108447. for(j=0;j<v->pcm_current;j++)
  108448. work[j]=v->pcm[i][v->pcm_current-j-1];
  108449. /* prime as above */
  108450. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  108451. /* run the predictor filter */
  108452. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  108453. order,
  108454. work+v->pcm_current-v->centerW,
  108455. v->centerW);
  108456. for(j=0;j<v->pcm_current;j++)
  108457. v->pcm[i][v->pcm_current-j-1]=work[j];
  108458. }
  108459. }
  108460. }
  108461. /* call with val<=0 to set eof */
  108462. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  108463. vorbis_info *vi=v->vi;
  108464. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108465. if(vals<=0){
  108466. int order=32;
  108467. int i;
  108468. float *lpc=(float*) alloca(order*sizeof(*lpc));
  108469. /* if it wasn't done earlier (very short sample) */
  108470. if(!v->preextrapolate)
  108471. _preextrapolate_helper(v);
  108472. /* We're encoding the end of the stream. Just make sure we have
  108473. [at least] a few full blocks of zeroes at the end. */
  108474. /* actually, we don't want zeroes; that could drop a large
  108475. amplitude off a cliff, creating spread spectrum noise that will
  108476. suck to encode. Extrapolate for the sake of cleanliness. */
  108477. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  108478. v->eofflag=v->pcm_current;
  108479. v->pcm_current+=ci->blocksizes[1]*3;
  108480. for(i=0;i<vi->channels;i++){
  108481. if(v->eofflag>order*2){
  108482. /* extrapolate with LPC to fill in */
  108483. long n;
  108484. /* make a predictor filter */
  108485. n=v->eofflag;
  108486. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  108487. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  108488. /* run the predictor filter */
  108489. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  108490. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  108491. }else{
  108492. /* not enough data to extrapolate (unlikely to happen due to
  108493. guarding the overlap, but bulletproof in case that
  108494. assumtion goes away). zeroes will do. */
  108495. memset(v->pcm[i]+v->eofflag,0,
  108496. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  108497. }
  108498. }
  108499. }else{
  108500. if(v->pcm_current+vals>v->pcm_storage)
  108501. return(OV_EINVAL);
  108502. v->pcm_current+=vals;
  108503. /* we may want to reverse extrapolate the beginning of a stream
  108504. too... in case we're beginning on a cliff! */
  108505. /* clumsy, but simple. It only runs once, so simple is good. */
  108506. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  108507. _preextrapolate_helper(v);
  108508. }
  108509. return(0);
  108510. }
  108511. /* do the deltas, envelope shaping, pre-echo and determine the size of
  108512. the next block on which to continue analysis */
  108513. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  108514. int i;
  108515. vorbis_info *vi=v->vi;
  108516. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108517. private_state *b=(private_state*)v->backend_state;
  108518. vorbis_look_psy_global *g=b->psy_g_look;
  108519. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  108520. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  108521. /* check to see if we're started... */
  108522. if(!v->preextrapolate)return(0);
  108523. /* check to see if we're done... */
  108524. if(v->eofflag==-1)return(0);
  108525. /* By our invariant, we have lW, W and centerW set. Search for
  108526. the next boundary so we can determine nW (the next window size)
  108527. which lets us compute the shape of the current block's window */
  108528. /* we do an envelope search even on a single blocksize; we may still
  108529. be throwing more bits at impulses, and envelope search handles
  108530. marking impulses too. */
  108531. {
  108532. long bp=_ve_envelope_search(v);
  108533. if(bp==-1){
  108534. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  108535. full long block */
  108536. v->nW=0;
  108537. }else{
  108538. if(ci->blocksizes[0]==ci->blocksizes[1])
  108539. v->nW=0;
  108540. else
  108541. v->nW=bp;
  108542. }
  108543. }
  108544. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  108545. {
  108546. /* center of next block + next block maximum right side. */
  108547. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  108548. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  108549. although this check is
  108550. less strict that the
  108551. _ve_envelope_search,
  108552. the search is not run
  108553. if we only use one
  108554. block size */
  108555. }
  108556. /* fill in the block. Note that for a short window, lW and nW are *short*
  108557. regardless of actual settings in the stream */
  108558. _vorbis_block_ripcord(vb);
  108559. vb->lW=v->lW;
  108560. vb->W=v->W;
  108561. vb->nW=v->nW;
  108562. if(v->W){
  108563. if(!v->lW || !v->nW){
  108564. vbi->blocktype=BLOCKTYPE_TRANSITION;
  108565. /*fprintf(stderr,"-");*/
  108566. }else{
  108567. vbi->blocktype=BLOCKTYPE_LONG;
  108568. /*fprintf(stderr,"_");*/
  108569. }
  108570. }else{
  108571. if(_ve_envelope_mark(v)){
  108572. vbi->blocktype=BLOCKTYPE_IMPULSE;
  108573. /*fprintf(stderr,"|");*/
  108574. }else{
  108575. vbi->blocktype=BLOCKTYPE_PADDING;
  108576. /*fprintf(stderr,".");*/
  108577. }
  108578. }
  108579. vb->vd=v;
  108580. vb->sequence=v->sequence++;
  108581. vb->granulepos=v->granulepos;
  108582. vb->pcmend=ci->blocksizes[v->W];
  108583. /* copy the vectors; this uses the local storage in vb */
  108584. /* this tracks 'strongest peak' for later psychoacoustics */
  108585. /* moved to the global psy state; clean this mess up */
  108586. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  108587. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  108588. vbi->ampmax=g->ampmax;
  108589. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  108590. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  108591. for(i=0;i<vi->channels;i++){
  108592. vbi->pcmdelay[i]=
  108593. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  108594. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  108595. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  108596. /* before we added the delay
  108597. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  108598. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  108599. */
  108600. }
  108601. /* handle eof detection: eof==0 means that we've not yet received EOF
  108602. eof>0 marks the last 'real' sample in pcm[]
  108603. eof<0 'no more to do'; doesn't get here */
  108604. if(v->eofflag){
  108605. if(v->centerW>=v->eofflag){
  108606. v->eofflag=-1;
  108607. vb->eofflag=1;
  108608. return(1);
  108609. }
  108610. }
  108611. /* advance storage vectors and clean up */
  108612. {
  108613. int new_centerNext=ci->blocksizes[1]/2;
  108614. int movementW=centerNext-new_centerNext;
  108615. if(movementW>0){
  108616. _ve_envelope_shift(b->ve,movementW);
  108617. v->pcm_current-=movementW;
  108618. for(i=0;i<vi->channels;i++)
  108619. memmove(v->pcm[i],v->pcm[i]+movementW,
  108620. v->pcm_current*sizeof(*v->pcm[i]));
  108621. v->lW=v->W;
  108622. v->W=v->nW;
  108623. v->centerW=new_centerNext;
  108624. if(v->eofflag){
  108625. v->eofflag-=movementW;
  108626. if(v->eofflag<=0)v->eofflag=-1;
  108627. /* do not add padding to end of stream! */
  108628. if(v->centerW>=v->eofflag){
  108629. v->granulepos+=movementW-(v->centerW-v->eofflag);
  108630. }else{
  108631. v->granulepos+=movementW;
  108632. }
  108633. }else{
  108634. v->granulepos+=movementW;
  108635. }
  108636. }
  108637. }
  108638. /* done */
  108639. return(1);
  108640. }
  108641. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  108642. vorbis_info *vi=v->vi;
  108643. codec_setup_info *ci;
  108644. int hs;
  108645. if(!v->backend_state)return -1;
  108646. if(!vi)return -1;
  108647. ci=(codec_setup_info*) vi->codec_setup;
  108648. if(!ci)return -1;
  108649. hs=ci->halfrate_flag;
  108650. v->centerW=ci->blocksizes[1]>>(hs+1);
  108651. v->pcm_current=v->centerW>>hs;
  108652. v->pcm_returned=-1;
  108653. v->granulepos=-1;
  108654. v->sequence=-1;
  108655. v->eofflag=0;
  108656. ((private_state *)(v->backend_state))->sample_count=-1;
  108657. return(0);
  108658. }
  108659. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  108660. if(_vds_shared_init(v,vi,0)) return 1;
  108661. vorbis_synthesis_restart(v);
  108662. return 0;
  108663. }
  108664. /* Unlike in analysis, the window is only partially applied for each
  108665. block. The time domain envelope is not yet handled at the point of
  108666. calling (as it relies on the previous block). */
  108667. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  108668. vorbis_info *vi=v->vi;
  108669. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108670. private_state *b=(private_state*)v->backend_state;
  108671. int hs=ci->halfrate_flag;
  108672. int i,j;
  108673. if(!vb)return(OV_EINVAL);
  108674. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  108675. v->lW=v->W;
  108676. v->W=vb->W;
  108677. v->nW=-1;
  108678. if((v->sequence==-1)||
  108679. (v->sequence+1 != vb->sequence)){
  108680. v->granulepos=-1; /* out of sequence; lose count */
  108681. b->sample_count=-1;
  108682. }
  108683. v->sequence=vb->sequence;
  108684. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  108685. was called on block */
  108686. int n=ci->blocksizes[v->W]>>(hs+1);
  108687. int n0=ci->blocksizes[0]>>(hs+1);
  108688. int n1=ci->blocksizes[1]>>(hs+1);
  108689. int thisCenter;
  108690. int prevCenter;
  108691. v->glue_bits+=vb->glue_bits;
  108692. v->time_bits+=vb->time_bits;
  108693. v->floor_bits+=vb->floor_bits;
  108694. v->res_bits+=vb->res_bits;
  108695. if(v->centerW){
  108696. thisCenter=n1;
  108697. prevCenter=0;
  108698. }else{
  108699. thisCenter=0;
  108700. prevCenter=n1;
  108701. }
  108702. /* v->pcm is now used like a two-stage double buffer. We don't want
  108703. to have to constantly shift *or* adjust memory usage. Don't
  108704. accept a new block until the old is shifted out */
  108705. for(j=0;j<vi->channels;j++){
  108706. /* the overlap/add section */
  108707. if(v->lW){
  108708. if(v->W){
  108709. /* large/large */
  108710. float *w=_vorbis_window_get(b->window[1]-hs);
  108711. float *pcm=v->pcm[j]+prevCenter;
  108712. float *p=vb->pcm[j];
  108713. for(i=0;i<n1;i++)
  108714. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  108715. }else{
  108716. /* large/small */
  108717. float *w=_vorbis_window_get(b->window[0]-hs);
  108718. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  108719. float *p=vb->pcm[j];
  108720. for(i=0;i<n0;i++)
  108721. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  108722. }
  108723. }else{
  108724. if(v->W){
  108725. /* small/large */
  108726. float *w=_vorbis_window_get(b->window[0]-hs);
  108727. float *pcm=v->pcm[j]+prevCenter;
  108728. float *p=vb->pcm[j]+n1/2-n0/2;
  108729. for(i=0;i<n0;i++)
  108730. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  108731. for(;i<n1/2+n0/2;i++)
  108732. pcm[i]=p[i];
  108733. }else{
  108734. /* small/small */
  108735. float *w=_vorbis_window_get(b->window[0]-hs);
  108736. float *pcm=v->pcm[j]+prevCenter;
  108737. float *p=vb->pcm[j];
  108738. for(i=0;i<n0;i++)
  108739. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  108740. }
  108741. }
  108742. /* the copy section */
  108743. {
  108744. float *pcm=v->pcm[j]+thisCenter;
  108745. float *p=vb->pcm[j]+n;
  108746. for(i=0;i<n;i++)
  108747. pcm[i]=p[i];
  108748. }
  108749. }
  108750. if(v->centerW)
  108751. v->centerW=0;
  108752. else
  108753. v->centerW=n1;
  108754. /* deal with initial packet state; we do this using the explicit
  108755. pcm_returned==-1 flag otherwise we're sensitive to first block
  108756. being short or long */
  108757. if(v->pcm_returned==-1){
  108758. v->pcm_returned=thisCenter;
  108759. v->pcm_current=thisCenter;
  108760. }else{
  108761. v->pcm_returned=prevCenter;
  108762. v->pcm_current=prevCenter+
  108763. ((ci->blocksizes[v->lW]/4+
  108764. ci->blocksizes[v->W]/4)>>hs);
  108765. }
  108766. }
  108767. /* track the frame number... This is for convenience, but also
  108768. making sure our last packet doesn't end with added padding. If
  108769. the last packet is partial, the number of samples we'll have to
  108770. return will be past the vb->granulepos.
  108771. This is not foolproof! It will be confused if we begin
  108772. decoding at the last page after a seek or hole. In that case,
  108773. we don't have a starting point to judge where the last frame
  108774. is. For this reason, vorbisfile will always try to make sure
  108775. it reads the last two marked pages in proper sequence */
  108776. if(b->sample_count==-1){
  108777. b->sample_count=0;
  108778. }else{
  108779. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  108780. }
  108781. if(v->granulepos==-1){
  108782. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  108783. v->granulepos=vb->granulepos;
  108784. /* is this a short page? */
  108785. if(b->sample_count>v->granulepos){
  108786. /* corner case; if this is both the first and last audio page,
  108787. then spec says the end is cut, not beginning */
  108788. if(vb->eofflag){
  108789. /* trim the end */
  108790. /* no preceeding granulepos; assume we started at zero (we'd
  108791. have to in a short single-page stream) */
  108792. /* granulepos could be -1 due to a seek, but that would result
  108793. in a long count, not short count */
  108794. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  108795. }else{
  108796. /* trim the beginning */
  108797. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  108798. if(v->pcm_returned>v->pcm_current)
  108799. v->pcm_returned=v->pcm_current;
  108800. }
  108801. }
  108802. }
  108803. }else{
  108804. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  108805. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  108806. if(v->granulepos>vb->granulepos){
  108807. long extra=v->granulepos-vb->granulepos;
  108808. if(extra)
  108809. if(vb->eofflag){
  108810. /* partial last frame. Strip the extra samples off */
  108811. v->pcm_current-=extra>>hs;
  108812. } /* else {Shouldn't happen *unless* the bitstream is out of
  108813. spec. Either way, believe the bitstream } */
  108814. } /* else {Shouldn't happen *unless* the bitstream is out of
  108815. spec. Either way, believe the bitstream } */
  108816. v->granulepos=vb->granulepos;
  108817. }
  108818. }
  108819. /* Update, cleanup */
  108820. if(vb->eofflag)v->eofflag=1;
  108821. return(0);
  108822. }
  108823. /* pcm==NULL indicates we just want the pending samples, no more */
  108824. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  108825. vorbis_info *vi=v->vi;
  108826. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  108827. if(pcm){
  108828. int i;
  108829. for(i=0;i<vi->channels;i++)
  108830. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  108831. *pcm=v->pcmret;
  108832. }
  108833. return(v->pcm_current-v->pcm_returned);
  108834. }
  108835. return(0);
  108836. }
  108837. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  108838. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  108839. v->pcm_returned+=n;
  108840. return(0);
  108841. }
  108842. /* intended for use with a specific vorbisfile feature; we want access
  108843. to the [usually synthetic/postextrapolated] buffer and lapping at
  108844. the end of a decode cycle, specifically, a half-short-block worth.
  108845. This funtion works like pcmout above, except it will also expose
  108846. this implicit buffer data not normally decoded. */
  108847. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  108848. vorbis_info *vi=v->vi;
  108849. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  108850. int hs=ci->halfrate_flag;
  108851. int n=ci->blocksizes[v->W]>>(hs+1);
  108852. int n0=ci->blocksizes[0]>>(hs+1);
  108853. int n1=ci->blocksizes[1]>>(hs+1);
  108854. int i,j;
  108855. if(v->pcm_returned<0)return 0;
  108856. /* our returned data ends at pcm_returned; because the synthesis pcm
  108857. buffer is a two-fragment ring, that means our data block may be
  108858. fragmented by buffering, wrapping or a short block not filling
  108859. out a buffer. To simplify things, we unfragment if it's at all
  108860. possibly needed. Otherwise, we'd need to call lapout more than
  108861. once as well as hold additional dsp state. Opt for
  108862. simplicity. */
  108863. /* centerW was advanced by blockin; it would be the center of the
  108864. *next* block */
  108865. if(v->centerW==n1){
  108866. /* the data buffer wraps; swap the halves */
  108867. /* slow, sure, small */
  108868. for(j=0;j<vi->channels;j++){
  108869. float *p=v->pcm[j];
  108870. for(i=0;i<n1;i++){
  108871. float temp=p[i];
  108872. p[i]=p[i+n1];
  108873. p[i+n1]=temp;
  108874. }
  108875. }
  108876. v->pcm_current-=n1;
  108877. v->pcm_returned-=n1;
  108878. v->centerW=0;
  108879. }
  108880. /* solidify buffer into contiguous space */
  108881. if((v->lW^v->W)==1){
  108882. /* long/short or short/long */
  108883. for(j=0;j<vi->channels;j++){
  108884. float *s=v->pcm[j];
  108885. float *d=v->pcm[j]+(n1-n0)/2;
  108886. for(i=(n1+n0)/2-1;i>=0;--i)
  108887. d[i]=s[i];
  108888. }
  108889. v->pcm_returned+=(n1-n0)/2;
  108890. v->pcm_current+=(n1-n0)/2;
  108891. }else{
  108892. if(v->lW==0){
  108893. /* short/short */
  108894. for(j=0;j<vi->channels;j++){
  108895. float *s=v->pcm[j];
  108896. float *d=v->pcm[j]+n1-n0;
  108897. for(i=n0-1;i>=0;--i)
  108898. d[i]=s[i];
  108899. }
  108900. v->pcm_returned+=n1-n0;
  108901. v->pcm_current+=n1-n0;
  108902. }
  108903. }
  108904. if(pcm){
  108905. int i;
  108906. for(i=0;i<vi->channels;i++)
  108907. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  108908. *pcm=v->pcmret;
  108909. }
  108910. return(n1+n-v->pcm_returned);
  108911. }
  108912. float *vorbis_window(vorbis_dsp_state *v,int W){
  108913. vorbis_info *vi=v->vi;
  108914. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  108915. int hs=ci->halfrate_flag;
  108916. private_state *b=(private_state*)v->backend_state;
  108917. if(b->window[W]-1<0)return NULL;
  108918. return _vorbis_window_get(b->window[W]-hs);
  108919. }
  108920. #endif
  108921. /*** End of inlined file: block.c ***/
  108922. /*** Start of inlined file: codebook.c ***/
  108923. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108924. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108925. // tasks..
  108926. #if JUCE_MSVC
  108927. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108928. #endif
  108929. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108930. #if JUCE_USE_OGGVORBIS
  108931. #include <stdlib.h>
  108932. #include <string.h>
  108933. #include <math.h>
  108934. /* packs the given codebook into the bitstream **************************/
  108935. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  108936. long i,j;
  108937. int ordered=0;
  108938. /* first the basic parameters */
  108939. oggpack_write(opb,0x564342,24);
  108940. oggpack_write(opb,c->dim,16);
  108941. oggpack_write(opb,c->entries,24);
  108942. /* pack the codewords. There are two packings; length ordered and
  108943. length random. Decide between the two now. */
  108944. for(i=1;i<c->entries;i++)
  108945. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  108946. if(i==c->entries)ordered=1;
  108947. if(ordered){
  108948. /* length ordered. We only need to say how many codewords of
  108949. each length. The actual codewords are generated
  108950. deterministically */
  108951. long count=0;
  108952. oggpack_write(opb,1,1); /* ordered */
  108953. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  108954. for(i=1;i<c->entries;i++){
  108955. long thisx=c->lengthlist[i];
  108956. long last=c->lengthlist[i-1];
  108957. if(thisx>last){
  108958. for(j=last;j<thisx;j++){
  108959. oggpack_write(opb,i-count,_ilog(c->entries-count));
  108960. count=i;
  108961. }
  108962. }
  108963. }
  108964. oggpack_write(opb,i-count,_ilog(c->entries-count));
  108965. }else{
  108966. /* length random. Again, we don't code the codeword itself, just
  108967. the length. This time, though, we have to encode each length */
  108968. oggpack_write(opb,0,1); /* unordered */
  108969. /* algortihmic mapping has use for 'unused entries', which we tag
  108970. here. The algorithmic mapping happens as usual, but the unused
  108971. entry has no codeword. */
  108972. for(i=0;i<c->entries;i++)
  108973. if(c->lengthlist[i]==0)break;
  108974. if(i==c->entries){
  108975. oggpack_write(opb,0,1); /* no unused entries */
  108976. for(i=0;i<c->entries;i++)
  108977. oggpack_write(opb,c->lengthlist[i]-1,5);
  108978. }else{
  108979. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  108980. for(i=0;i<c->entries;i++){
  108981. if(c->lengthlist[i]==0){
  108982. oggpack_write(opb,0,1);
  108983. }else{
  108984. oggpack_write(opb,1,1);
  108985. oggpack_write(opb,c->lengthlist[i]-1,5);
  108986. }
  108987. }
  108988. }
  108989. }
  108990. /* is the entry number the desired return value, or do we have a
  108991. mapping? If we have a mapping, what type? */
  108992. oggpack_write(opb,c->maptype,4);
  108993. switch(c->maptype){
  108994. case 0:
  108995. /* no mapping */
  108996. break;
  108997. case 1:case 2:
  108998. /* implicitly populated value mapping */
  108999. /* explicitly populated value mapping */
  109000. if(!c->quantlist){
  109001. /* no quantlist? error */
  109002. return(-1);
  109003. }
  109004. /* values that define the dequantization */
  109005. oggpack_write(opb,c->q_min,32);
  109006. oggpack_write(opb,c->q_delta,32);
  109007. oggpack_write(opb,c->q_quant-1,4);
  109008. oggpack_write(opb,c->q_sequencep,1);
  109009. {
  109010. int quantvals;
  109011. switch(c->maptype){
  109012. case 1:
  109013. /* a single column of (c->entries/c->dim) quantized values for
  109014. building a full value list algorithmically (square lattice) */
  109015. quantvals=_book_maptype1_quantvals(c);
  109016. break;
  109017. case 2:
  109018. /* every value (c->entries*c->dim total) specified explicitly */
  109019. quantvals=c->entries*c->dim;
  109020. break;
  109021. default: /* NOT_REACHABLE */
  109022. quantvals=-1;
  109023. }
  109024. /* quantized values */
  109025. for(i=0;i<quantvals;i++)
  109026. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  109027. }
  109028. break;
  109029. default:
  109030. /* error case; we don't have any other map types now */
  109031. return(-1);
  109032. }
  109033. return(0);
  109034. }
  109035. /* unpacks a codebook from the packet buffer into the codebook struct,
  109036. readies the codebook auxiliary structures for decode *************/
  109037. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  109038. long i,j;
  109039. memset(s,0,sizeof(*s));
  109040. s->allocedp=1;
  109041. /* make sure alignment is correct */
  109042. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  109043. /* first the basic parameters */
  109044. s->dim=oggpack_read(opb,16);
  109045. s->entries=oggpack_read(opb,24);
  109046. if(s->entries==-1)goto _eofout;
  109047. /* codeword ordering.... length ordered or unordered? */
  109048. switch((int)oggpack_read(opb,1)){
  109049. case 0:
  109050. /* unordered */
  109051. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  109052. /* allocated but unused entries? */
  109053. if(oggpack_read(opb,1)){
  109054. /* yes, unused entries */
  109055. for(i=0;i<s->entries;i++){
  109056. if(oggpack_read(opb,1)){
  109057. long num=oggpack_read(opb,5);
  109058. if(num==-1)goto _eofout;
  109059. s->lengthlist[i]=num+1;
  109060. }else
  109061. s->lengthlist[i]=0;
  109062. }
  109063. }else{
  109064. /* all entries used; no tagging */
  109065. for(i=0;i<s->entries;i++){
  109066. long num=oggpack_read(opb,5);
  109067. if(num==-1)goto _eofout;
  109068. s->lengthlist[i]=num+1;
  109069. }
  109070. }
  109071. break;
  109072. case 1:
  109073. /* ordered */
  109074. {
  109075. long length=oggpack_read(opb,5)+1;
  109076. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  109077. for(i=0;i<s->entries;){
  109078. long num=oggpack_read(opb,_ilog(s->entries-i));
  109079. if(num==-1)goto _eofout;
  109080. for(j=0;j<num && i<s->entries;j++,i++)
  109081. s->lengthlist[i]=length;
  109082. length++;
  109083. }
  109084. }
  109085. break;
  109086. default:
  109087. /* EOF */
  109088. return(-1);
  109089. }
  109090. /* Do we have a mapping to unpack? */
  109091. switch((s->maptype=oggpack_read(opb,4))){
  109092. case 0:
  109093. /* no mapping */
  109094. break;
  109095. case 1: case 2:
  109096. /* implicitly populated value mapping */
  109097. /* explicitly populated value mapping */
  109098. s->q_min=oggpack_read(opb,32);
  109099. s->q_delta=oggpack_read(opb,32);
  109100. s->q_quant=oggpack_read(opb,4)+1;
  109101. s->q_sequencep=oggpack_read(opb,1);
  109102. {
  109103. int quantvals=0;
  109104. switch(s->maptype){
  109105. case 1:
  109106. quantvals=_book_maptype1_quantvals(s);
  109107. break;
  109108. case 2:
  109109. quantvals=s->entries*s->dim;
  109110. break;
  109111. }
  109112. /* quantized values */
  109113. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  109114. for(i=0;i<quantvals;i++)
  109115. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  109116. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  109117. }
  109118. break;
  109119. default:
  109120. goto _errout;
  109121. }
  109122. /* all set */
  109123. return(0);
  109124. _errout:
  109125. _eofout:
  109126. vorbis_staticbook_clear(s);
  109127. return(-1);
  109128. }
  109129. /* returns the number of bits ************************************************/
  109130. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  109131. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  109132. return(book->c->lengthlist[a]);
  109133. }
  109134. /* One the encode side, our vector writers are each designed for a
  109135. specific purpose, and the encoder is not flexible without modification:
  109136. The LSP vector coder uses a single stage nearest-match with no
  109137. interleave, so no step and no error return. This is specced by floor0
  109138. and doesn't change.
  109139. Residue0 encoding interleaves, uses multiple stages, and each stage
  109140. peels of a specific amount of resolution from a lattice (thus we want
  109141. to match by threshold, not nearest match). Residue doesn't *have* to
  109142. be encoded that way, but to change it, one will need to add more
  109143. infrastructure on the encode side (decode side is specced and simpler) */
  109144. /* floor0 LSP (single stage, non interleaved, nearest match) */
  109145. /* returns entry number and *modifies a* to the quantization value *****/
  109146. int vorbis_book_errorv(codebook *book,float *a){
  109147. int dim=book->dim,k;
  109148. int best=_best(book,a,1);
  109149. for(k=0;k<dim;k++)
  109150. a[k]=(book->valuelist+best*dim)[k];
  109151. return(best);
  109152. }
  109153. /* returns the number of bits and *modifies a* to the quantization value *****/
  109154. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  109155. int k,dim=book->dim;
  109156. for(k=0;k<dim;k++)
  109157. a[k]=(book->valuelist+best*dim)[k];
  109158. return(vorbis_book_encode(book,best,b));
  109159. }
  109160. /* the 'eliminate the decode tree' optimization actually requires the
  109161. codewords to be MSb first, not LSb. This is an annoying inelegancy
  109162. (and one of the first places where carefully thought out design
  109163. turned out to be wrong; Vorbis II and future Ogg codecs should go
  109164. to an MSb bitpacker), but not actually the huge hit it appears to
  109165. be. The first-stage decode table catches most words so that
  109166. bitreverse is not in the main execution path. */
  109167. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  109168. int read=book->dec_maxlength;
  109169. long lo,hi;
  109170. long lok = oggpack_look(b,book->dec_firsttablen);
  109171. if (lok >= 0) {
  109172. long entry = book->dec_firsttable[lok];
  109173. if(entry&0x80000000UL){
  109174. lo=(entry>>15)&0x7fff;
  109175. hi=book->used_entries-(entry&0x7fff);
  109176. }else{
  109177. oggpack_adv(b, book->dec_codelengths[entry-1]);
  109178. return(entry-1);
  109179. }
  109180. }else{
  109181. lo=0;
  109182. hi=book->used_entries;
  109183. }
  109184. lok = oggpack_look(b, read);
  109185. while(lok<0 && read>1)
  109186. lok = oggpack_look(b, --read);
  109187. if(lok<0)return -1;
  109188. /* bisect search for the codeword in the ordered list */
  109189. {
  109190. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  109191. while(hi-lo>1){
  109192. long p=(hi-lo)>>1;
  109193. long test=book->codelist[lo+p]>testword;
  109194. lo+=p&(test-1);
  109195. hi-=p&(-test);
  109196. }
  109197. if(book->dec_codelengths[lo]<=read){
  109198. oggpack_adv(b, book->dec_codelengths[lo]);
  109199. return(lo);
  109200. }
  109201. }
  109202. oggpack_adv(b, read);
  109203. return(-1);
  109204. }
  109205. /* Decode side is specced and easier, because we don't need to find
  109206. matches using different criteria; we simply read and map. There are
  109207. two things we need to do 'depending':
  109208. We may need to support interleave. We don't really, but it's
  109209. convenient to do it here rather than rebuild the vector later.
  109210. Cascades may be additive or multiplicitive; this is not inherent in
  109211. the codebook, but set in the code using the codebook. Like
  109212. interleaving, it's easiest to do it here.
  109213. addmul==0 -> declarative (set the value)
  109214. addmul==1 -> additive
  109215. addmul==2 -> multiplicitive */
  109216. /* returns the [original, not compacted] entry number or -1 on eof *********/
  109217. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  109218. long packed_entry=decode_packed_entry_number(book,b);
  109219. if(packed_entry>=0)
  109220. return(book->dec_index[packed_entry]);
  109221. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  109222. return(packed_entry);
  109223. }
  109224. /* returns 0 on OK or -1 on eof *************************************/
  109225. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  109226. int step=n/book->dim;
  109227. long *entry = (long*)alloca(sizeof(*entry)*step);
  109228. float **t = (float**)alloca(sizeof(*t)*step);
  109229. int i,j,o;
  109230. for (i = 0; i < step; i++) {
  109231. entry[i]=decode_packed_entry_number(book,b);
  109232. if(entry[i]==-1)return(-1);
  109233. t[i] = book->valuelist+entry[i]*book->dim;
  109234. }
  109235. for(i=0,o=0;i<book->dim;i++,o+=step)
  109236. for (j=0;j<step;j++)
  109237. a[o+j]+=t[j][i];
  109238. return(0);
  109239. }
  109240. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  109241. int i,j,entry;
  109242. float *t;
  109243. if(book->dim>8){
  109244. for(i=0;i<n;){
  109245. entry = decode_packed_entry_number(book,b);
  109246. if(entry==-1)return(-1);
  109247. t = book->valuelist+entry*book->dim;
  109248. for (j=0;j<book->dim;)
  109249. a[i++]+=t[j++];
  109250. }
  109251. }else{
  109252. for(i=0;i<n;){
  109253. entry = decode_packed_entry_number(book,b);
  109254. if(entry==-1)return(-1);
  109255. t = book->valuelist+entry*book->dim;
  109256. j=0;
  109257. switch((int)book->dim){
  109258. case 8:
  109259. a[i++]+=t[j++];
  109260. case 7:
  109261. a[i++]+=t[j++];
  109262. case 6:
  109263. a[i++]+=t[j++];
  109264. case 5:
  109265. a[i++]+=t[j++];
  109266. case 4:
  109267. a[i++]+=t[j++];
  109268. case 3:
  109269. a[i++]+=t[j++];
  109270. case 2:
  109271. a[i++]+=t[j++];
  109272. case 1:
  109273. a[i++]+=t[j++];
  109274. case 0:
  109275. break;
  109276. }
  109277. }
  109278. }
  109279. return(0);
  109280. }
  109281. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  109282. int i,j,entry;
  109283. float *t;
  109284. for(i=0;i<n;){
  109285. entry = decode_packed_entry_number(book,b);
  109286. if(entry==-1)return(-1);
  109287. t = book->valuelist+entry*book->dim;
  109288. for (j=0;j<book->dim;)
  109289. a[i++]=t[j++];
  109290. }
  109291. return(0);
  109292. }
  109293. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  109294. oggpack_buffer *b,int n){
  109295. long i,j,entry;
  109296. int chptr=0;
  109297. for(i=offset/ch;i<(offset+n)/ch;){
  109298. entry = decode_packed_entry_number(book,b);
  109299. if(entry==-1)return(-1);
  109300. {
  109301. const float *t = book->valuelist+entry*book->dim;
  109302. for (j=0;j<book->dim;j++){
  109303. a[chptr++][i]+=t[j];
  109304. if(chptr==ch){
  109305. chptr=0;
  109306. i++;
  109307. }
  109308. }
  109309. }
  109310. }
  109311. return(0);
  109312. }
  109313. #ifdef _V_SELFTEST
  109314. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  109315. number of vectors through (keeping track of the quantized values),
  109316. and decode using the unpacked book. quantized version of in should
  109317. exactly equal out */
  109318. #include <stdio.h>
  109319. #include "vorbis/book/lsp20_0.vqh"
  109320. #include "vorbis/book/res0a_13.vqh"
  109321. #define TESTSIZE 40
  109322. float test1[TESTSIZE]={
  109323. 0.105939f,
  109324. 0.215373f,
  109325. 0.429117f,
  109326. 0.587974f,
  109327. 0.181173f,
  109328. 0.296583f,
  109329. 0.515707f,
  109330. 0.715261f,
  109331. 0.162327f,
  109332. 0.263834f,
  109333. 0.342876f,
  109334. 0.406025f,
  109335. 0.103571f,
  109336. 0.223561f,
  109337. 0.368513f,
  109338. 0.540313f,
  109339. 0.136672f,
  109340. 0.395882f,
  109341. 0.587183f,
  109342. 0.652476f,
  109343. 0.114338f,
  109344. 0.417300f,
  109345. 0.525486f,
  109346. 0.698679f,
  109347. 0.147492f,
  109348. 0.324481f,
  109349. 0.643089f,
  109350. 0.757582f,
  109351. 0.139556f,
  109352. 0.215795f,
  109353. 0.324559f,
  109354. 0.399387f,
  109355. 0.120236f,
  109356. 0.267420f,
  109357. 0.446940f,
  109358. 0.608760f,
  109359. 0.115587f,
  109360. 0.287234f,
  109361. 0.571081f,
  109362. 0.708603f,
  109363. };
  109364. float test3[TESTSIZE]={
  109365. 0,1,-2,3,4,-5,6,7,8,9,
  109366. 8,-2,7,-1,4,6,8,3,1,-9,
  109367. 10,11,12,13,14,15,26,17,18,19,
  109368. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  109369. static_codebook *testlist[]={&_vq_book_lsp20_0,
  109370. &_vq_book_res0a_13,NULL};
  109371. float *testvec[]={test1,test3};
  109372. int main(){
  109373. oggpack_buffer write;
  109374. oggpack_buffer read;
  109375. long ptr=0,i;
  109376. oggpack_writeinit(&write);
  109377. fprintf(stderr,"Testing codebook abstraction...:\n");
  109378. while(testlist[ptr]){
  109379. codebook c;
  109380. static_codebook s;
  109381. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  109382. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  109383. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  109384. memset(iv,0,sizeof(*iv)*TESTSIZE);
  109385. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  109386. /* pack the codebook, write the testvector */
  109387. oggpack_reset(&write);
  109388. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  109389. we can write */
  109390. vorbis_staticbook_pack(testlist[ptr],&write);
  109391. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  109392. for(i=0;i<TESTSIZE;i+=c.dim){
  109393. int best=_best(&c,qv+i,1);
  109394. vorbis_book_encodev(&c,best,qv+i,&write);
  109395. }
  109396. vorbis_book_clear(&c);
  109397. fprintf(stderr,"OK.\n");
  109398. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  109399. /* transfer the write data to a read buffer and unpack/read */
  109400. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  109401. if(vorbis_staticbook_unpack(&read,&s)){
  109402. fprintf(stderr,"Error unpacking codebook.\n");
  109403. exit(1);
  109404. }
  109405. if(vorbis_book_init_decode(&c,&s)){
  109406. fprintf(stderr,"Error initializing codebook.\n");
  109407. exit(1);
  109408. }
  109409. for(i=0;i<TESTSIZE;i+=c.dim)
  109410. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  109411. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  109412. exit(1);
  109413. }
  109414. for(i=0;i<TESTSIZE;i++)
  109415. if(fabs(qv[i]-iv[i])>.000001){
  109416. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  109417. iv[i],qv[i],i);
  109418. exit(1);
  109419. }
  109420. fprintf(stderr,"OK\n");
  109421. ptr++;
  109422. }
  109423. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  109424. exit(0);
  109425. }
  109426. #endif
  109427. #endif
  109428. /*** End of inlined file: codebook.c ***/
  109429. /*** Start of inlined file: envelope.c ***/
  109430. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109431. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109432. // tasks..
  109433. #if JUCE_MSVC
  109434. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109435. #endif
  109436. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109437. #if JUCE_USE_OGGVORBIS
  109438. #include <stdlib.h>
  109439. #include <string.h>
  109440. #include <stdio.h>
  109441. #include <math.h>
  109442. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  109443. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109444. vorbis_info_psy_global *gi=&ci->psy_g_param;
  109445. int ch=vi->channels;
  109446. int i,j;
  109447. int n=e->winlength=128;
  109448. e->searchstep=64; /* not random */
  109449. e->minenergy=gi->preecho_minenergy;
  109450. e->ch=ch;
  109451. e->storage=128;
  109452. e->cursor=ci->blocksizes[1]/2;
  109453. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  109454. mdct_init(&e->mdct,n);
  109455. for(i=0;i<n;i++){
  109456. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  109457. e->mdct_win[i]*=e->mdct_win[i];
  109458. }
  109459. /* magic follows */
  109460. e->band[0].begin=2; e->band[0].end=4;
  109461. e->band[1].begin=4; e->band[1].end=5;
  109462. e->band[2].begin=6; e->band[2].end=6;
  109463. e->band[3].begin=9; e->band[3].end=8;
  109464. e->band[4].begin=13; e->band[4].end=8;
  109465. e->band[5].begin=17; e->band[5].end=8;
  109466. e->band[6].begin=22; e->band[6].end=8;
  109467. for(j=0;j<VE_BANDS;j++){
  109468. n=e->band[j].end;
  109469. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  109470. for(i=0;i<n;i++){
  109471. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  109472. e->band[j].total+=e->band[j].window[i];
  109473. }
  109474. e->band[j].total=1./e->band[j].total;
  109475. }
  109476. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  109477. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  109478. }
  109479. void _ve_envelope_clear(envelope_lookup *e){
  109480. int i;
  109481. mdct_clear(&e->mdct);
  109482. for(i=0;i<VE_BANDS;i++)
  109483. _ogg_free(e->band[i].window);
  109484. _ogg_free(e->mdct_win);
  109485. _ogg_free(e->filter);
  109486. _ogg_free(e->mark);
  109487. memset(e,0,sizeof(*e));
  109488. }
  109489. /* fairly straight threshhold-by-band based until we find something
  109490. that works better and isn't patented. */
  109491. static int _ve_amp(envelope_lookup *ve,
  109492. vorbis_info_psy_global *gi,
  109493. float *data,
  109494. envelope_band *bands,
  109495. envelope_filter_state *filters,
  109496. long pos){
  109497. long n=ve->winlength;
  109498. int ret=0;
  109499. long i,j;
  109500. float decay;
  109501. /* we want to have a 'minimum bar' for energy, else we're just
  109502. basing blocks on quantization noise that outweighs the signal
  109503. itself (for low power signals) */
  109504. float minV=ve->minenergy;
  109505. float *vec=(float*) alloca(n*sizeof(*vec));
  109506. /* stretch is used to gradually lengthen the number of windows
  109507. considered prevoius-to-potential-trigger */
  109508. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  109509. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  109510. if(penalty<0.f)penalty=0.f;
  109511. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  109512. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  109513. totalshift+pos*ve->searchstep);*/
  109514. /* window and transform */
  109515. for(i=0;i<n;i++)
  109516. vec[i]=data[i]*ve->mdct_win[i];
  109517. mdct_forward(&ve->mdct,vec,vec);
  109518. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  109519. /* near-DC spreading function; this has nothing to do with
  109520. psychoacoustics, just sidelobe leakage and window size */
  109521. {
  109522. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  109523. int ptr=filters->nearptr;
  109524. /* the accumulation is regularly refreshed from scratch to avoid
  109525. floating point creep */
  109526. if(ptr==0){
  109527. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  109528. filters->nearDC_partialacc=temp;
  109529. }else{
  109530. decay=filters->nearDC_acc+=temp;
  109531. filters->nearDC_partialacc+=temp;
  109532. }
  109533. filters->nearDC_acc-=filters->nearDC[ptr];
  109534. filters->nearDC[ptr]=temp;
  109535. decay*=(1./(VE_NEARDC+1));
  109536. filters->nearptr++;
  109537. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  109538. decay=todB(&decay)*.5-15.f;
  109539. }
  109540. /* perform spreading and limiting, also smooth the spectrum. yes,
  109541. the MDCT results in all real coefficients, but it still *behaves*
  109542. like real/imaginary pairs */
  109543. for(i=0;i<n/2;i+=2){
  109544. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  109545. val=todB(&val)*.5f;
  109546. if(val<decay)val=decay;
  109547. if(val<minV)val=minV;
  109548. vec[i>>1]=val;
  109549. decay-=8.;
  109550. }
  109551. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  109552. /* perform preecho/postecho triggering by band */
  109553. for(j=0;j<VE_BANDS;j++){
  109554. float acc=0.;
  109555. float valmax,valmin;
  109556. /* accumulate amplitude */
  109557. for(i=0;i<bands[j].end;i++)
  109558. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  109559. acc*=bands[j].total;
  109560. /* convert amplitude to delta */
  109561. {
  109562. int p,thisx=filters[j].ampptr;
  109563. float postmax,postmin,premax=-99999.f,premin=99999.f;
  109564. p=thisx;
  109565. p--;
  109566. if(p<0)p+=VE_AMP;
  109567. postmax=max(acc,filters[j].ampbuf[p]);
  109568. postmin=min(acc,filters[j].ampbuf[p]);
  109569. for(i=0;i<stretch;i++){
  109570. p--;
  109571. if(p<0)p+=VE_AMP;
  109572. premax=max(premax,filters[j].ampbuf[p]);
  109573. premin=min(premin,filters[j].ampbuf[p]);
  109574. }
  109575. valmin=postmin-premin;
  109576. valmax=postmax-premax;
  109577. /*filters[j].markers[pos]=valmax;*/
  109578. filters[j].ampbuf[thisx]=acc;
  109579. filters[j].ampptr++;
  109580. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  109581. }
  109582. /* look at min/max, decide trigger */
  109583. if(valmax>gi->preecho_thresh[j]+penalty){
  109584. ret|=1;
  109585. ret|=4;
  109586. }
  109587. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  109588. }
  109589. return(ret);
  109590. }
  109591. #if 0
  109592. static int seq=0;
  109593. static ogg_int64_t totalshift=-1024;
  109594. #endif
  109595. long _ve_envelope_search(vorbis_dsp_state *v){
  109596. vorbis_info *vi=v->vi;
  109597. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  109598. vorbis_info_psy_global *gi=&ci->psy_g_param;
  109599. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  109600. long i,j;
  109601. int first=ve->current/ve->searchstep;
  109602. int last=v->pcm_current/ve->searchstep-VE_WIN;
  109603. if(first<0)first=0;
  109604. /* make sure we have enough storage to match the PCM */
  109605. if(last+VE_WIN+VE_POST>ve->storage){
  109606. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  109607. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  109608. }
  109609. for(j=first;j<last;j++){
  109610. int ret=0;
  109611. ve->stretch++;
  109612. if(ve->stretch>VE_MAXSTRETCH*2)
  109613. ve->stretch=VE_MAXSTRETCH*2;
  109614. for(i=0;i<ve->ch;i++){
  109615. float *pcm=v->pcm[i]+ve->searchstep*(j);
  109616. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  109617. }
  109618. ve->mark[j+VE_POST]=0;
  109619. if(ret&1){
  109620. ve->mark[j]=1;
  109621. ve->mark[j+1]=1;
  109622. }
  109623. if(ret&2){
  109624. ve->mark[j]=1;
  109625. if(j>0)ve->mark[j-1]=1;
  109626. }
  109627. if(ret&4)ve->stretch=-1;
  109628. }
  109629. ve->current=last*ve->searchstep;
  109630. {
  109631. long centerW=v->centerW;
  109632. long testW=
  109633. centerW+
  109634. ci->blocksizes[v->W]/4+
  109635. ci->blocksizes[1]/2+
  109636. ci->blocksizes[0]/4;
  109637. j=ve->cursor;
  109638. while(j<ve->current-(ve->searchstep)){/* account for postecho
  109639. working back one window */
  109640. if(j>=testW)return(1);
  109641. ve->cursor=j;
  109642. if(ve->mark[j/ve->searchstep]){
  109643. if(j>centerW){
  109644. #if 0
  109645. if(j>ve->curmark){
  109646. float *marker=alloca(v->pcm_current*sizeof(*marker));
  109647. int l,m;
  109648. memset(marker,0,sizeof(*marker)*v->pcm_current);
  109649. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  109650. seq,
  109651. (totalshift+ve->cursor)/44100.,
  109652. (totalshift+j)/44100.);
  109653. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  109654. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  109655. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  109656. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  109657. for(m=0;m<VE_BANDS;m++){
  109658. char buf[80];
  109659. sprintf(buf,"delL%d",m);
  109660. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  109661. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  109662. }
  109663. for(m=0;m<VE_BANDS;m++){
  109664. char buf[80];
  109665. sprintf(buf,"delR%d",m);
  109666. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  109667. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  109668. }
  109669. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  109670. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  109671. seq++;
  109672. }
  109673. #endif
  109674. ve->curmark=j;
  109675. if(j>=testW)return(1);
  109676. return(0);
  109677. }
  109678. }
  109679. j+=ve->searchstep;
  109680. }
  109681. }
  109682. return(-1);
  109683. }
  109684. int _ve_envelope_mark(vorbis_dsp_state *v){
  109685. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  109686. vorbis_info *vi=v->vi;
  109687. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109688. long centerW=v->centerW;
  109689. long beginW=centerW-ci->blocksizes[v->W]/4;
  109690. long endW=centerW+ci->blocksizes[v->W]/4;
  109691. if(v->W){
  109692. beginW-=ci->blocksizes[v->lW]/4;
  109693. endW+=ci->blocksizes[v->nW]/4;
  109694. }else{
  109695. beginW-=ci->blocksizes[0]/4;
  109696. endW+=ci->blocksizes[0]/4;
  109697. }
  109698. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  109699. {
  109700. long first=beginW/ve->searchstep;
  109701. long last=endW/ve->searchstep;
  109702. long i;
  109703. for(i=first;i<last;i++)
  109704. if(ve->mark[i])return(1);
  109705. }
  109706. return(0);
  109707. }
  109708. void _ve_envelope_shift(envelope_lookup *e,long shift){
  109709. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  109710. ahead of ve->current */
  109711. int smallshift=shift/e->searchstep;
  109712. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  109713. #if 0
  109714. for(i=0;i<VE_BANDS*e->ch;i++)
  109715. memmove(e->filter[i].markers,
  109716. e->filter[i].markers+smallshift,
  109717. (1024-smallshift)*sizeof(*(*e->filter).markers));
  109718. totalshift+=shift;
  109719. #endif
  109720. e->current-=shift;
  109721. if(e->curmark>=0)
  109722. e->curmark-=shift;
  109723. e->cursor-=shift;
  109724. }
  109725. #endif
  109726. /*** End of inlined file: envelope.c ***/
  109727. /*** Start of inlined file: floor0.c ***/
  109728. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109729. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109730. // tasks..
  109731. #if JUCE_MSVC
  109732. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109733. #endif
  109734. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109735. #if JUCE_USE_OGGVORBIS
  109736. #include <stdlib.h>
  109737. #include <string.h>
  109738. #include <math.h>
  109739. /*** Start of inlined file: lsp.h ***/
  109740. #ifndef _V_LSP_H_
  109741. #define _V_LSP_H_
  109742. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  109743. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  109744. float *lsp,int m,
  109745. float amp,float ampoffset);
  109746. #endif
  109747. /*** End of inlined file: lsp.h ***/
  109748. #include <stdio.h>
  109749. typedef struct {
  109750. int ln;
  109751. int m;
  109752. int **linearmap;
  109753. int n[2];
  109754. vorbis_info_floor0 *vi;
  109755. long bits;
  109756. long frames;
  109757. } vorbis_look_floor0;
  109758. /***********************************************/
  109759. static void floor0_free_info(vorbis_info_floor *i){
  109760. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  109761. if(info){
  109762. memset(info,0,sizeof(*info));
  109763. _ogg_free(info);
  109764. }
  109765. }
  109766. static void floor0_free_look(vorbis_look_floor *i){
  109767. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  109768. if(look){
  109769. if(look->linearmap){
  109770. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  109771. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  109772. _ogg_free(look->linearmap);
  109773. }
  109774. memset(look,0,sizeof(*look));
  109775. _ogg_free(look);
  109776. }
  109777. }
  109778. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  109779. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109780. int j;
  109781. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  109782. info->order=oggpack_read(opb,8);
  109783. info->rate=oggpack_read(opb,16);
  109784. info->barkmap=oggpack_read(opb,16);
  109785. info->ampbits=oggpack_read(opb,6);
  109786. info->ampdB=oggpack_read(opb,8);
  109787. info->numbooks=oggpack_read(opb,4)+1;
  109788. if(info->order<1)goto err_out;
  109789. if(info->rate<1)goto err_out;
  109790. if(info->barkmap<1)goto err_out;
  109791. if(info->numbooks<1)goto err_out;
  109792. for(j=0;j<info->numbooks;j++){
  109793. info->books[j]=oggpack_read(opb,8);
  109794. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  109795. }
  109796. return(info);
  109797. err_out:
  109798. floor0_free_info(info);
  109799. return(NULL);
  109800. }
  109801. /* initialize Bark scale and normalization lookups. We could do this
  109802. with static tables, but Vorbis allows a number of possible
  109803. combinations, so it's best to do it computationally.
  109804. The below is authoritative in terms of defining scale mapping.
  109805. Note that the scale depends on the sampling rate as well as the
  109806. linear block and mapping sizes */
  109807. static void floor0_map_lazy_init(vorbis_block *vb,
  109808. vorbis_info_floor *infoX,
  109809. vorbis_look_floor0 *look){
  109810. if(!look->linearmap[vb->W]){
  109811. vorbis_dsp_state *vd=vb->vd;
  109812. vorbis_info *vi=vd->vi;
  109813. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109814. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  109815. int W=vb->W;
  109816. int n=ci->blocksizes[W]/2,j;
  109817. /* we choose a scaling constant so that:
  109818. floor(bark(rate/2-1)*C)=mapped-1
  109819. floor(bark(rate/2)*C)=mapped */
  109820. float scale=look->ln/toBARK(info->rate/2.f);
  109821. /* the mapping from a linear scale to a smaller bark scale is
  109822. straightforward. We do *not* make sure that the linear mapping
  109823. does not skip bark-scale bins; the decoder simply skips them and
  109824. the encoder may do what it wishes in filling them. They're
  109825. necessary in some mapping combinations to keep the scale spacing
  109826. accurate */
  109827. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  109828. for(j=0;j<n;j++){
  109829. int val=floor( toBARK((info->rate/2.f)/n*j)
  109830. *scale); /* bark numbers represent band edges */
  109831. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  109832. look->linearmap[W][j]=val;
  109833. }
  109834. look->linearmap[W][j]=-1;
  109835. look->n[W]=n;
  109836. }
  109837. }
  109838. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  109839. vorbis_info_floor *i){
  109840. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  109841. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  109842. look->m=info->order;
  109843. look->ln=info->barkmap;
  109844. look->vi=info;
  109845. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  109846. return look;
  109847. }
  109848. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  109849. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  109850. vorbis_info_floor0 *info=look->vi;
  109851. int j,k;
  109852. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  109853. if(ampraw>0){ /* also handles the -1 out of data case */
  109854. long maxval=(1<<info->ampbits)-1;
  109855. float amp=(float)ampraw/maxval*info->ampdB;
  109856. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  109857. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  109858. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  109859. codebook *b=ci->fullbooks+info->books[booknum];
  109860. float last=0.f;
  109861. /* the additional b->dim is a guard against any possible stack
  109862. smash; b->dim is provably more than we can overflow the
  109863. vector */
  109864. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  109865. for(j=0;j<look->m;j+=b->dim)
  109866. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  109867. for(j=0;j<look->m;){
  109868. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  109869. last=lsp[j-1];
  109870. }
  109871. lsp[look->m]=amp;
  109872. return(lsp);
  109873. }
  109874. }
  109875. eop:
  109876. return(NULL);
  109877. }
  109878. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  109879. void *memo,float *out){
  109880. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  109881. vorbis_info_floor0 *info=look->vi;
  109882. floor0_map_lazy_init(vb,info,look);
  109883. if(memo){
  109884. float *lsp=(float *)memo;
  109885. float amp=lsp[look->m];
  109886. /* take the coefficients back to a spectral envelope curve */
  109887. vorbis_lsp_to_curve(out,
  109888. look->linearmap[vb->W],
  109889. look->n[vb->W],
  109890. look->ln,
  109891. lsp,look->m,amp,(float)info->ampdB);
  109892. return(1);
  109893. }
  109894. memset(out,0,sizeof(*out)*look->n[vb->W]);
  109895. return(0);
  109896. }
  109897. /* export hooks */
  109898. vorbis_func_floor floor0_exportbundle={
  109899. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  109900. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  109901. };
  109902. #endif
  109903. /*** End of inlined file: floor0.c ***/
  109904. /*** Start of inlined file: floor1.c ***/
  109905. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109906. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109907. // tasks..
  109908. #if JUCE_MSVC
  109909. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109910. #endif
  109911. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109912. #if JUCE_USE_OGGVORBIS
  109913. #include <stdlib.h>
  109914. #include <string.h>
  109915. #include <math.h>
  109916. #include <stdio.h>
  109917. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  109918. typedef struct {
  109919. int sorted_index[VIF_POSIT+2];
  109920. int forward_index[VIF_POSIT+2];
  109921. int reverse_index[VIF_POSIT+2];
  109922. int hineighbor[VIF_POSIT];
  109923. int loneighbor[VIF_POSIT];
  109924. int posts;
  109925. int n;
  109926. int quant_q;
  109927. vorbis_info_floor1 *vi;
  109928. long phrasebits;
  109929. long postbits;
  109930. long frames;
  109931. } vorbis_look_floor1;
  109932. typedef struct lsfit_acc{
  109933. long x0;
  109934. long x1;
  109935. long xa;
  109936. long ya;
  109937. long x2a;
  109938. long y2a;
  109939. long xya;
  109940. long an;
  109941. } lsfit_acc;
  109942. /***********************************************/
  109943. static void floor1_free_info(vorbis_info_floor *i){
  109944. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  109945. if(info){
  109946. memset(info,0,sizeof(*info));
  109947. _ogg_free(info);
  109948. }
  109949. }
  109950. static void floor1_free_look(vorbis_look_floor *i){
  109951. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  109952. if(look){
  109953. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  109954. (float)look->phrasebits/look->frames,
  109955. (float)look->postbits/look->frames,
  109956. (float)(look->postbits+look->phrasebits)/look->frames);*/
  109957. memset(look,0,sizeof(*look));
  109958. _ogg_free(look);
  109959. }
  109960. }
  109961. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  109962. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  109963. int j,k;
  109964. int count=0;
  109965. int rangebits;
  109966. int maxposit=info->postlist[1];
  109967. int maxclass=-1;
  109968. /* save out partitions */
  109969. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  109970. for(j=0;j<info->partitions;j++){
  109971. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  109972. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  109973. }
  109974. /* save out partition classes */
  109975. for(j=0;j<maxclass+1;j++){
  109976. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  109977. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  109978. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  109979. for(k=0;k<(1<<info->class_subs[j]);k++)
  109980. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  109981. }
  109982. /* save out the post list */
  109983. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  109984. oggpack_write(opb,ilog2(maxposit),4);
  109985. rangebits=ilog2(maxposit);
  109986. for(j=0,k=0;j<info->partitions;j++){
  109987. count+=info->class_dim[info->partitionclass[j]];
  109988. for(;k<count;k++)
  109989. oggpack_write(opb,info->postlist[k+2],rangebits);
  109990. }
  109991. }
  109992. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  109993. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109994. int j,k,count=0,maxclass=-1,rangebits;
  109995. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  109996. /* read partitions */
  109997. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  109998. for(j=0;j<info->partitions;j++){
  109999. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  110000. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  110001. }
  110002. /* read partition classes */
  110003. for(j=0;j<maxclass+1;j++){
  110004. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  110005. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  110006. if(info->class_subs[j]<0)
  110007. goto err_out;
  110008. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  110009. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  110010. goto err_out;
  110011. for(k=0;k<(1<<info->class_subs[j]);k++){
  110012. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  110013. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  110014. goto err_out;
  110015. }
  110016. }
  110017. /* read the post list */
  110018. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  110019. rangebits=oggpack_read(opb,4);
  110020. for(j=0,k=0;j<info->partitions;j++){
  110021. count+=info->class_dim[info->partitionclass[j]];
  110022. for(;k<count;k++){
  110023. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  110024. if(t<0 || t>=(1<<rangebits))
  110025. goto err_out;
  110026. }
  110027. }
  110028. info->postlist[0]=0;
  110029. info->postlist[1]=1<<rangebits;
  110030. return(info);
  110031. err_out:
  110032. floor1_free_info(info);
  110033. return(NULL);
  110034. }
  110035. static int icomp(const void *a,const void *b){
  110036. return(**(int **)a-**(int **)b);
  110037. }
  110038. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  110039. vorbis_info_floor *in){
  110040. int *sortpointer[VIF_POSIT+2];
  110041. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  110042. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  110043. int i,j,n=0;
  110044. look->vi=info;
  110045. look->n=info->postlist[1];
  110046. /* we drop each position value in-between already decoded values,
  110047. and use linear interpolation to predict each new value past the
  110048. edges. The positions are read in the order of the position
  110049. list... we precompute the bounding positions in the lookup. Of
  110050. course, the neighbors can change (if a position is declined), but
  110051. this is an initial mapping */
  110052. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  110053. n+=2;
  110054. look->posts=n;
  110055. /* also store a sorted position index */
  110056. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  110057. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  110058. /* points from sort order back to range number */
  110059. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  110060. /* points from range order to sorted position */
  110061. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  110062. /* we actually need the post values too */
  110063. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  110064. /* quantize values to multiplier spec */
  110065. switch(info->mult){
  110066. case 1: /* 1024 -> 256 */
  110067. look->quant_q=256;
  110068. break;
  110069. case 2: /* 1024 -> 128 */
  110070. look->quant_q=128;
  110071. break;
  110072. case 3: /* 1024 -> 86 */
  110073. look->quant_q=86;
  110074. break;
  110075. case 4: /* 1024 -> 64 */
  110076. look->quant_q=64;
  110077. break;
  110078. }
  110079. /* discover our neighbors for decode where we don't use fit flags
  110080. (that would push the neighbors outward) */
  110081. for(i=0;i<n-2;i++){
  110082. int lo=0;
  110083. int hi=1;
  110084. int lx=0;
  110085. int hx=look->n;
  110086. int currentx=info->postlist[i+2];
  110087. for(j=0;j<i+2;j++){
  110088. int x=info->postlist[j];
  110089. if(x>lx && x<currentx){
  110090. lo=j;
  110091. lx=x;
  110092. }
  110093. if(x<hx && x>currentx){
  110094. hi=j;
  110095. hx=x;
  110096. }
  110097. }
  110098. look->loneighbor[i]=lo;
  110099. look->hineighbor[i]=hi;
  110100. }
  110101. return(look);
  110102. }
  110103. static int render_point(int x0,int x1,int y0,int y1,int x){
  110104. y0&=0x7fff; /* mask off flag */
  110105. y1&=0x7fff;
  110106. {
  110107. int dy=y1-y0;
  110108. int adx=x1-x0;
  110109. int ady=abs(dy);
  110110. int err=ady*(x-x0);
  110111. int off=err/adx;
  110112. if(dy<0)return(y0-off);
  110113. return(y0+off);
  110114. }
  110115. }
  110116. static int vorbis_dBquant(const float *x){
  110117. int i= *x*7.3142857f+1023.5f;
  110118. if(i>1023)return(1023);
  110119. if(i<0)return(0);
  110120. return i;
  110121. }
  110122. static float FLOOR1_fromdB_LOOKUP[256]={
  110123. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  110124. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  110125. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  110126. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  110127. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  110128. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  110129. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  110130. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  110131. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  110132. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  110133. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  110134. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  110135. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  110136. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  110137. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  110138. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  110139. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  110140. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  110141. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  110142. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  110143. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  110144. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  110145. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  110146. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  110147. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  110148. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  110149. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  110150. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  110151. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  110152. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  110153. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  110154. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  110155. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  110156. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  110157. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  110158. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  110159. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  110160. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  110161. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  110162. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  110163. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  110164. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  110165. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  110166. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  110167. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  110168. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  110169. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  110170. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  110171. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  110172. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  110173. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  110174. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  110175. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  110176. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  110177. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  110178. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  110179. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  110180. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  110181. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  110182. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  110183. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  110184. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  110185. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  110186. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  110187. };
  110188. static void render_line(int x0,int x1,int y0,int y1,float *d){
  110189. int dy=y1-y0;
  110190. int adx=x1-x0;
  110191. int ady=abs(dy);
  110192. int base=dy/adx;
  110193. int sy=(dy<0?base-1:base+1);
  110194. int x=x0;
  110195. int y=y0;
  110196. int err=0;
  110197. ady-=abs(base*adx);
  110198. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  110199. while(++x<x1){
  110200. err=err+ady;
  110201. if(err>=adx){
  110202. err-=adx;
  110203. y+=sy;
  110204. }else{
  110205. y+=base;
  110206. }
  110207. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  110208. }
  110209. }
  110210. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  110211. int dy=y1-y0;
  110212. int adx=x1-x0;
  110213. int ady=abs(dy);
  110214. int base=dy/adx;
  110215. int sy=(dy<0?base-1:base+1);
  110216. int x=x0;
  110217. int y=y0;
  110218. int err=0;
  110219. ady-=abs(base*adx);
  110220. d[x]=y;
  110221. while(++x<x1){
  110222. err=err+ady;
  110223. if(err>=adx){
  110224. err-=adx;
  110225. y+=sy;
  110226. }else{
  110227. y+=base;
  110228. }
  110229. d[x]=y;
  110230. }
  110231. }
  110232. /* the floor has already been filtered to only include relevant sections */
  110233. static int accumulate_fit(const float *flr,const float *mdct,
  110234. int x0, int x1,lsfit_acc *a,
  110235. int n,vorbis_info_floor1 *info){
  110236. long i;
  110237. 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;
  110238. memset(a,0,sizeof(*a));
  110239. a->x0=x0;
  110240. a->x1=x1;
  110241. if(x1>=n)x1=n-1;
  110242. for(i=x0;i<=x1;i++){
  110243. int quantized=vorbis_dBquant(flr+i);
  110244. if(quantized){
  110245. if(mdct[i]+info->twofitatten>=flr[i]){
  110246. xa += i;
  110247. ya += quantized;
  110248. x2a += i*i;
  110249. y2a += quantized*quantized;
  110250. xya += i*quantized;
  110251. na++;
  110252. }else{
  110253. xb += i;
  110254. yb += quantized;
  110255. x2b += i*i;
  110256. y2b += quantized*quantized;
  110257. xyb += i*quantized;
  110258. nb++;
  110259. }
  110260. }
  110261. }
  110262. xb+=xa;
  110263. yb+=ya;
  110264. x2b+=x2a;
  110265. y2b+=y2a;
  110266. xyb+=xya;
  110267. nb+=na;
  110268. /* weight toward the actually used frequencies if we meet the threshhold */
  110269. {
  110270. int weight=nb*info->twofitweight/(na+1);
  110271. a->xa=xa*weight+xb;
  110272. a->ya=ya*weight+yb;
  110273. a->x2a=x2a*weight+x2b;
  110274. a->y2a=y2a*weight+y2b;
  110275. a->xya=xya*weight+xyb;
  110276. a->an=na*weight+nb;
  110277. }
  110278. return(na);
  110279. }
  110280. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  110281. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  110282. long x0=a[0].x0;
  110283. long x1=a[fits-1].x1;
  110284. for(i=0;i<fits;i++){
  110285. x+=a[i].xa;
  110286. y+=a[i].ya;
  110287. x2+=a[i].x2a;
  110288. y2+=a[i].y2a;
  110289. xy+=a[i].xya;
  110290. an+=a[i].an;
  110291. }
  110292. if(*y0>=0){
  110293. x+= x0;
  110294. y+= *y0;
  110295. x2+= x0 * x0;
  110296. y2+= *y0 * *y0;
  110297. xy+= *y0 * x0;
  110298. an++;
  110299. }
  110300. if(*y1>=0){
  110301. x+= x1;
  110302. y+= *y1;
  110303. x2+= x1 * x1;
  110304. y2+= *y1 * *y1;
  110305. xy+= *y1 * x1;
  110306. an++;
  110307. }
  110308. if(an){
  110309. /* need 64 bit multiplies, which C doesn't give portably as int */
  110310. double fx=x;
  110311. double fy=y;
  110312. double fx2=x2;
  110313. double fxy=xy;
  110314. double denom=1./(an*fx2-fx*fx);
  110315. double a=(fy*fx2-fxy*fx)*denom;
  110316. double b=(an*fxy-fx*fy)*denom;
  110317. *y0=rint(a+b*x0);
  110318. *y1=rint(a+b*x1);
  110319. /* limit to our range! */
  110320. if(*y0>1023)*y0=1023;
  110321. if(*y1>1023)*y1=1023;
  110322. if(*y0<0)*y0=0;
  110323. if(*y1<0)*y1=0;
  110324. }else{
  110325. *y0=0;
  110326. *y1=0;
  110327. }
  110328. }
  110329. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  110330. long y=0;
  110331. int i;
  110332. for(i=0;i<fits && y==0;i++)
  110333. y+=a[i].ya;
  110334. *y0=*y1=y;
  110335. }*/
  110336. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  110337. const float *mdct,
  110338. vorbis_info_floor1 *info){
  110339. int dy=y1-y0;
  110340. int adx=x1-x0;
  110341. int ady=abs(dy);
  110342. int base=dy/adx;
  110343. int sy=(dy<0?base-1:base+1);
  110344. int x=x0;
  110345. int y=y0;
  110346. int err=0;
  110347. int val=vorbis_dBquant(mask+x);
  110348. int mse=0;
  110349. int n=0;
  110350. ady-=abs(base*adx);
  110351. mse=(y-val);
  110352. mse*=mse;
  110353. n++;
  110354. if(mdct[x]+info->twofitatten>=mask[x]){
  110355. if(y+info->maxover<val)return(1);
  110356. if(y-info->maxunder>val)return(1);
  110357. }
  110358. while(++x<x1){
  110359. err=err+ady;
  110360. if(err>=adx){
  110361. err-=adx;
  110362. y+=sy;
  110363. }else{
  110364. y+=base;
  110365. }
  110366. val=vorbis_dBquant(mask+x);
  110367. mse+=((y-val)*(y-val));
  110368. n++;
  110369. if(mdct[x]+info->twofitatten>=mask[x]){
  110370. if(val){
  110371. if(y+info->maxover<val)return(1);
  110372. if(y-info->maxunder>val)return(1);
  110373. }
  110374. }
  110375. }
  110376. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  110377. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  110378. if(mse/n>info->maxerr)return(1);
  110379. return(0);
  110380. }
  110381. static int post_Y(int *A,int *B,int pos){
  110382. if(A[pos]<0)
  110383. return B[pos];
  110384. if(B[pos]<0)
  110385. return A[pos];
  110386. return (A[pos]+B[pos])>>1;
  110387. }
  110388. int *floor1_fit(vorbis_block *vb,void *look_,
  110389. const float *logmdct, /* in */
  110390. const float *logmask){
  110391. long i,j;
  110392. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  110393. vorbis_info_floor1 *info=look->vi;
  110394. long n=look->n;
  110395. long posts=look->posts;
  110396. long nonzero=0;
  110397. lsfit_acc fits[VIF_POSIT+1];
  110398. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  110399. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  110400. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  110401. int hineighbor[VIF_POSIT+2];
  110402. int *output=NULL;
  110403. int memo[VIF_POSIT+2];
  110404. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  110405. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  110406. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  110407. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  110408. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  110409. /* quantize the relevant floor points and collect them into line fit
  110410. structures (one per minimal division) at the same time */
  110411. if(posts==0){
  110412. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  110413. }else{
  110414. for(i=0;i<posts-1;i++)
  110415. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  110416. look->sorted_index[i+1],fits+i,
  110417. n,info);
  110418. }
  110419. if(nonzero){
  110420. /* start by fitting the implicit base case.... */
  110421. int y0=-200;
  110422. int y1=-200;
  110423. fit_line(fits,posts-1,&y0,&y1);
  110424. fit_valueA[0]=y0;
  110425. fit_valueB[0]=y0;
  110426. fit_valueB[1]=y1;
  110427. fit_valueA[1]=y1;
  110428. /* Non degenerate case */
  110429. /* start progressive splitting. This is a greedy, non-optimal
  110430. algorithm, but simple and close enough to the best
  110431. answer. */
  110432. for(i=2;i<posts;i++){
  110433. int sortpos=look->reverse_index[i];
  110434. int ln=loneighbor[sortpos];
  110435. int hn=hineighbor[sortpos];
  110436. /* eliminate repeat searches of a particular range with a memo */
  110437. if(memo[ln]!=hn){
  110438. /* haven't performed this error search yet */
  110439. int lsortpos=look->reverse_index[ln];
  110440. int hsortpos=look->reverse_index[hn];
  110441. memo[ln]=hn;
  110442. {
  110443. /* A note: we want to bound/minimize *local*, not global, error */
  110444. int lx=info->postlist[ln];
  110445. int hx=info->postlist[hn];
  110446. int ly=post_Y(fit_valueA,fit_valueB,ln);
  110447. int hy=post_Y(fit_valueA,fit_valueB,hn);
  110448. if(ly==-1 || hy==-1){
  110449. exit(1);
  110450. }
  110451. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  110452. /* outside error bounds/begin search area. Split it. */
  110453. int ly0=-200;
  110454. int ly1=-200;
  110455. int hy0=-200;
  110456. int hy1=-200;
  110457. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  110458. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  110459. /* store new edge values */
  110460. fit_valueB[ln]=ly0;
  110461. if(ln==0)fit_valueA[ln]=ly0;
  110462. fit_valueA[i]=ly1;
  110463. fit_valueB[i]=hy0;
  110464. fit_valueA[hn]=hy1;
  110465. if(hn==1)fit_valueB[hn]=hy1;
  110466. if(ly1>=0 || hy0>=0){
  110467. /* store new neighbor values */
  110468. for(j=sortpos-1;j>=0;j--)
  110469. if(hineighbor[j]==hn)
  110470. hineighbor[j]=i;
  110471. else
  110472. break;
  110473. for(j=sortpos+1;j<posts;j++)
  110474. if(loneighbor[j]==ln)
  110475. loneighbor[j]=i;
  110476. else
  110477. break;
  110478. }
  110479. }else{
  110480. fit_valueA[i]=-200;
  110481. fit_valueB[i]=-200;
  110482. }
  110483. }
  110484. }
  110485. }
  110486. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  110487. output[0]=post_Y(fit_valueA,fit_valueB,0);
  110488. output[1]=post_Y(fit_valueA,fit_valueB,1);
  110489. /* fill in posts marked as not using a fit; we will zero
  110490. back out to 'unused' when encoding them so long as curve
  110491. interpolation doesn't force them into use */
  110492. for(i=2;i<posts;i++){
  110493. int ln=look->loneighbor[i-2];
  110494. int hn=look->hineighbor[i-2];
  110495. int x0=info->postlist[ln];
  110496. int x1=info->postlist[hn];
  110497. int y0=output[ln];
  110498. int y1=output[hn];
  110499. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  110500. int vx=post_Y(fit_valueA,fit_valueB,i);
  110501. if(vx>=0 && predicted!=vx){
  110502. output[i]=vx;
  110503. }else{
  110504. output[i]= predicted|0x8000;
  110505. }
  110506. }
  110507. }
  110508. return(output);
  110509. }
  110510. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  110511. int *A,int *B,
  110512. int del){
  110513. long i;
  110514. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  110515. long posts=look->posts;
  110516. int *output=NULL;
  110517. if(A && B){
  110518. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  110519. for(i=0;i<posts;i++){
  110520. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  110521. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  110522. }
  110523. }
  110524. return(output);
  110525. }
  110526. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  110527. void*look_,
  110528. int *post,int *ilogmask){
  110529. long i,j;
  110530. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  110531. vorbis_info_floor1 *info=look->vi;
  110532. long posts=look->posts;
  110533. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  110534. int out[VIF_POSIT+2];
  110535. static_codebook **sbooks=ci->book_param;
  110536. codebook *books=ci->fullbooks;
  110537. static long seq=0;
  110538. /* quantize values to multiplier spec */
  110539. if(post){
  110540. for(i=0;i<posts;i++){
  110541. int val=post[i]&0x7fff;
  110542. switch(info->mult){
  110543. case 1: /* 1024 -> 256 */
  110544. val>>=2;
  110545. break;
  110546. case 2: /* 1024 -> 128 */
  110547. val>>=3;
  110548. break;
  110549. case 3: /* 1024 -> 86 */
  110550. val/=12;
  110551. break;
  110552. case 4: /* 1024 -> 64 */
  110553. val>>=4;
  110554. break;
  110555. }
  110556. post[i]=val | (post[i]&0x8000);
  110557. }
  110558. out[0]=post[0];
  110559. out[1]=post[1];
  110560. /* find prediction values for each post and subtract them */
  110561. for(i=2;i<posts;i++){
  110562. int ln=look->loneighbor[i-2];
  110563. int hn=look->hineighbor[i-2];
  110564. int x0=info->postlist[ln];
  110565. int x1=info->postlist[hn];
  110566. int y0=post[ln];
  110567. int y1=post[hn];
  110568. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  110569. if((post[i]&0x8000) || (predicted==post[i])){
  110570. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  110571. in interpolation */
  110572. out[i]=0;
  110573. }else{
  110574. int headroom=(look->quant_q-predicted<predicted?
  110575. look->quant_q-predicted:predicted);
  110576. int val=post[i]-predicted;
  110577. /* at this point the 'deviation' value is in the range +/- max
  110578. range, but the real, unique range can always be mapped to
  110579. only [0-maxrange). So we want to wrap the deviation into
  110580. this limited range, but do it in the way that least screws
  110581. an essentially gaussian probability distribution. */
  110582. if(val<0)
  110583. if(val<-headroom)
  110584. val=headroom-val-1;
  110585. else
  110586. val=-1-(val<<1);
  110587. else
  110588. if(val>=headroom)
  110589. val= val+headroom;
  110590. else
  110591. val<<=1;
  110592. out[i]=val;
  110593. post[ln]&=0x7fff;
  110594. post[hn]&=0x7fff;
  110595. }
  110596. }
  110597. /* we have everything we need. pack it out */
  110598. /* mark nontrivial floor */
  110599. oggpack_write(opb,1,1);
  110600. /* beginning/end post */
  110601. look->frames++;
  110602. look->postbits+=ilog(look->quant_q-1)*2;
  110603. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  110604. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  110605. /* partition by partition */
  110606. for(i=0,j=2;i<info->partitions;i++){
  110607. int classx=info->partitionclass[i];
  110608. int cdim=info->class_dim[classx];
  110609. int csubbits=info->class_subs[classx];
  110610. int csub=1<<csubbits;
  110611. int bookas[8]={0,0,0,0,0,0,0,0};
  110612. int cval=0;
  110613. int cshift=0;
  110614. int k,l;
  110615. /* generate the partition's first stage cascade value */
  110616. if(csubbits){
  110617. int maxval[8];
  110618. for(k=0;k<csub;k++){
  110619. int booknum=info->class_subbook[classx][k];
  110620. if(booknum<0){
  110621. maxval[k]=1;
  110622. }else{
  110623. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  110624. }
  110625. }
  110626. for(k=0;k<cdim;k++){
  110627. for(l=0;l<csub;l++){
  110628. int val=out[j+k];
  110629. if(val<maxval[l]){
  110630. bookas[k]=l;
  110631. break;
  110632. }
  110633. }
  110634. cval|= bookas[k]<<cshift;
  110635. cshift+=csubbits;
  110636. }
  110637. /* write it */
  110638. look->phrasebits+=
  110639. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  110640. #ifdef TRAIN_FLOOR1
  110641. {
  110642. FILE *of;
  110643. char buffer[80];
  110644. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  110645. vb->pcmend/2,posts-2,class);
  110646. of=fopen(buffer,"a");
  110647. fprintf(of,"%d\n",cval);
  110648. fclose(of);
  110649. }
  110650. #endif
  110651. }
  110652. /* write post values */
  110653. for(k=0;k<cdim;k++){
  110654. int book=info->class_subbook[classx][bookas[k]];
  110655. if(book>=0){
  110656. /* hack to allow training with 'bad' books */
  110657. if(out[j+k]<(books+book)->entries)
  110658. look->postbits+=vorbis_book_encode(books+book,
  110659. out[j+k],opb);
  110660. /*else
  110661. fprintf(stderr,"+!");*/
  110662. #ifdef TRAIN_FLOOR1
  110663. {
  110664. FILE *of;
  110665. char buffer[80];
  110666. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  110667. vb->pcmend/2,posts-2,class,bookas[k]);
  110668. of=fopen(buffer,"a");
  110669. fprintf(of,"%d\n",out[j+k]);
  110670. fclose(of);
  110671. }
  110672. #endif
  110673. }
  110674. }
  110675. j+=cdim;
  110676. }
  110677. {
  110678. /* generate quantized floor equivalent to what we'd unpack in decode */
  110679. /* render the lines */
  110680. int hx=0;
  110681. int lx=0;
  110682. int ly=post[0]*info->mult;
  110683. for(j=1;j<look->posts;j++){
  110684. int current=look->forward_index[j];
  110685. int hy=post[current]&0x7fff;
  110686. if(hy==post[current]){
  110687. hy*=info->mult;
  110688. hx=info->postlist[current];
  110689. render_line0(lx,hx,ly,hy,ilogmask);
  110690. lx=hx;
  110691. ly=hy;
  110692. }
  110693. }
  110694. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  110695. seq++;
  110696. return(1);
  110697. }
  110698. }else{
  110699. oggpack_write(opb,0,1);
  110700. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  110701. seq++;
  110702. return(0);
  110703. }
  110704. }
  110705. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  110706. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  110707. vorbis_info_floor1 *info=look->vi;
  110708. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  110709. int i,j,k;
  110710. codebook *books=ci->fullbooks;
  110711. /* unpack wrapped/predicted values from stream */
  110712. if(oggpack_read(&vb->opb,1)==1){
  110713. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  110714. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  110715. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  110716. /* partition by partition */
  110717. for(i=0,j=2;i<info->partitions;i++){
  110718. int classx=info->partitionclass[i];
  110719. int cdim=info->class_dim[classx];
  110720. int csubbits=info->class_subs[classx];
  110721. int csub=1<<csubbits;
  110722. int cval=0;
  110723. /* decode the partition's first stage cascade value */
  110724. if(csubbits){
  110725. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  110726. if(cval==-1)goto eop;
  110727. }
  110728. for(k=0;k<cdim;k++){
  110729. int book=info->class_subbook[classx][cval&(csub-1)];
  110730. cval>>=csubbits;
  110731. if(book>=0){
  110732. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  110733. goto eop;
  110734. }else{
  110735. fit_value[j+k]=0;
  110736. }
  110737. }
  110738. j+=cdim;
  110739. }
  110740. /* unwrap positive values and reconsitute via linear interpolation */
  110741. for(i=2;i<look->posts;i++){
  110742. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  110743. info->postlist[look->hineighbor[i-2]],
  110744. fit_value[look->loneighbor[i-2]],
  110745. fit_value[look->hineighbor[i-2]],
  110746. info->postlist[i]);
  110747. int hiroom=look->quant_q-predicted;
  110748. int loroom=predicted;
  110749. int room=(hiroom<loroom?hiroom:loroom)<<1;
  110750. int val=fit_value[i];
  110751. if(val){
  110752. if(val>=room){
  110753. if(hiroom>loroom){
  110754. val = val-loroom;
  110755. }else{
  110756. val = -1-(val-hiroom);
  110757. }
  110758. }else{
  110759. if(val&1){
  110760. val= -((val+1)>>1);
  110761. }else{
  110762. val>>=1;
  110763. }
  110764. }
  110765. fit_value[i]=val+predicted;
  110766. fit_value[look->loneighbor[i-2]]&=0x7fff;
  110767. fit_value[look->hineighbor[i-2]]&=0x7fff;
  110768. }else{
  110769. fit_value[i]=predicted|0x8000;
  110770. }
  110771. }
  110772. return(fit_value);
  110773. }
  110774. eop:
  110775. return(NULL);
  110776. }
  110777. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  110778. float *out){
  110779. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  110780. vorbis_info_floor1 *info=look->vi;
  110781. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  110782. int n=ci->blocksizes[vb->W]/2;
  110783. int j;
  110784. if(memo){
  110785. /* render the lines */
  110786. int *fit_value=(int *)memo;
  110787. int hx=0;
  110788. int lx=0;
  110789. int ly=fit_value[0]*info->mult;
  110790. for(j=1;j<look->posts;j++){
  110791. int current=look->forward_index[j];
  110792. int hy=fit_value[current]&0x7fff;
  110793. if(hy==fit_value[current]){
  110794. hy*=info->mult;
  110795. hx=info->postlist[current];
  110796. render_line(lx,hx,ly,hy,out);
  110797. lx=hx;
  110798. ly=hy;
  110799. }
  110800. }
  110801. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  110802. return(1);
  110803. }
  110804. memset(out,0,sizeof(*out)*n);
  110805. return(0);
  110806. }
  110807. /* export hooks */
  110808. vorbis_func_floor floor1_exportbundle={
  110809. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  110810. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  110811. };
  110812. #endif
  110813. /*** End of inlined file: floor1.c ***/
  110814. /*** Start of inlined file: info.c ***/
  110815. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110816. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110817. // tasks..
  110818. #if JUCE_MSVC
  110819. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110820. #endif
  110821. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110822. #if JUCE_USE_OGGVORBIS
  110823. /* general handling of the header and the vorbis_info structure (and
  110824. substructures) */
  110825. #include <stdlib.h>
  110826. #include <string.h>
  110827. #include <ctype.h>
  110828. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  110829. while(bytes--){
  110830. oggpack_write(o,*s++,8);
  110831. }
  110832. }
  110833. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  110834. while(bytes--){
  110835. *buf++=oggpack_read(o,8);
  110836. }
  110837. }
  110838. void vorbis_comment_init(vorbis_comment *vc){
  110839. memset(vc,0,sizeof(*vc));
  110840. }
  110841. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  110842. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  110843. (vc->comments+2)*sizeof(*vc->user_comments));
  110844. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  110845. (vc->comments+2)*sizeof(*vc->comment_lengths));
  110846. vc->comment_lengths[vc->comments]=strlen(comment);
  110847. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  110848. strcpy(vc->user_comments[vc->comments], comment);
  110849. vc->comments++;
  110850. vc->user_comments[vc->comments]=NULL;
  110851. }
  110852. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  110853. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  110854. strcpy(comment, tag);
  110855. strcat(comment, "=");
  110856. strcat(comment, contents);
  110857. vorbis_comment_add(vc, comment);
  110858. }
  110859. /* This is more or less the same as strncasecmp - but that doesn't exist
  110860. * everywhere, and this is a fairly trivial function, so we include it */
  110861. static int tagcompare(const char *s1, const char *s2, int n){
  110862. int c=0;
  110863. while(c < n){
  110864. if(toupper(s1[c]) != toupper(s2[c]))
  110865. return !0;
  110866. c++;
  110867. }
  110868. return 0;
  110869. }
  110870. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  110871. long i;
  110872. int found = 0;
  110873. int taglen = strlen(tag)+1; /* +1 for the = we append */
  110874. char *fulltag = (char*)alloca(taglen+ 1);
  110875. strcpy(fulltag, tag);
  110876. strcat(fulltag, "=");
  110877. for(i=0;i<vc->comments;i++){
  110878. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  110879. if(count == found)
  110880. /* We return a pointer to the data, not a copy */
  110881. return vc->user_comments[i] + taglen;
  110882. else
  110883. found++;
  110884. }
  110885. }
  110886. return NULL; /* didn't find anything */
  110887. }
  110888. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  110889. int i,count=0;
  110890. int taglen = strlen(tag)+1; /* +1 for the = we append */
  110891. char *fulltag = (char*)alloca(taglen+1);
  110892. strcpy(fulltag,tag);
  110893. strcat(fulltag, "=");
  110894. for(i=0;i<vc->comments;i++){
  110895. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  110896. count++;
  110897. }
  110898. return count;
  110899. }
  110900. void vorbis_comment_clear(vorbis_comment *vc){
  110901. if(vc){
  110902. long i;
  110903. for(i=0;i<vc->comments;i++)
  110904. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  110905. if(vc->user_comments)_ogg_free(vc->user_comments);
  110906. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  110907. if(vc->vendor)_ogg_free(vc->vendor);
  110908. }
  110909. memset(vc,0,sizeof(*vc));
  110910. }
  110911. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  110912. They may be equal, but short will never ge greater than long */
  110913. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  110914. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  110915. return ci ? ci->blocksizes[zo] : -1;
  110916. }
  110917. /* used by synthesis, which has a full, alloced vi */
  110918. void vorbis_info_init(vorbis_info *vi){
  110919. memset(vi,0,sizeof(*vi));
  110920. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  110921. }
  110922. void vorbis_info_clear(vorbis_info *vi){
  110923. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110924. int i;
  110925. if(ci){
  110926. for(i=0;i<ci->modes;i++)
  110927. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  110928. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  110929. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  110930. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  110931. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  110932. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  110933. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  110934. for(i=0;i<ci->books;i++){
  110935. if(ci->book_param[i]){
  110936. /* knows if the book was not alloced */
  110937. vorbis_staticbook_destroy(ci->book_param[i]);
  110938. }
  110939. if(ci->fullbooks)
  110940. vorbis_book_clear(ci->fullbooks+i);
  110941. }
  110942. if(ci->fullbooks)
  110943. _ogg_free(ci->fullbooks);
  110944. for(i=0;i<ci->psys;i++)
  110945. _vi_psy_free(ci->psy_param[i]);
  110946. _ogg_free(ci);
  110947. }
  110948. memset(vi,0,sizeof(*vi));
  110949. }
  110950. /* Header packing/unpacking ********************************************/
  110951. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  110952. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110953. if(!ci)return(OV_EFAULT);
  110954. vi->version=oggpack_read(opb,32);
  110955. if(vi->version!=0)return(OV_EVERSION);
  110956. vi->channels=oggpack_read(opb,8);
  110957. vi->rate=oggpack_read(opb,32);
  110958. vi->bitrate_upper=oggpack_read(opb,32);
  110959. vi->bitrate_nominal=oggpack_read(opb,32);
  110960. vi->bitrate_lower=oggpack_read(opb,32);
  110961. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  110962. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  110963. if(vi->rate<1)goto err_out;
  110964. if(vi->channels<1)goto err_out;
  110965. if(ci->blocksizes[0]<8)goto err_out;
  110966. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  110967. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  110968. return(0);
  110969. err_out:
  110970. vorbis_info_clear(vi);
  110971. return(OV_EBADHEADER);
  110972. }
  110973. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  110974. int i;
  110975. int vendorlen=oggpack_read(opb,32);
  110976. if(vendorlen<0)goto err_out;
  110977. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  110978. _v_readstring(opb,vc->vendor,vendorlen);
  110979. vc->comments=oggpack_read(opb,32);
  110980. if(vc->comments<0)goto err_out;
  110981. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  110982. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  110983. for(i=0;i<vc->comments;i++){
  110984. int len=oggpack_read(opb,32);
  110985. if(len<0)goto err_out;
  110986. vc->comment_lengths[i]=len;
  110987. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  110988. _v_readstring(opb,vc->user_comments[i],len);
  110989. }
  110990. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  110991. return(0);
  110992. err_out:
  110993. vorbis_comment_clear(vc);
  110994. return(OV_EBADHEADER);
  110995. }
  110996. /* all of the real encoding details are here. The modes, books,
  110997. everything */
  110998. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  110999. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111000. int i;
  111001. if(!ci)return(OV_EFAULT);
  111002. /* codebooks */
  111003. ci->books=oggpack_read(opb,8)+1;
  111004. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  111005. for(i=0;i<ci->books;i++){
  111006. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  111007. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  111008. }
  111009. /* time backend settings; hooks are unused */
  111010. {
  111011. int times=oggpack_read(opb,6)+1;
  111012. for(i=0;i<times;i++){
  111013. int test=oggpack_read(opb,16);
  111014. if(test<0 || test>=VI_TIMEB)goto err_out;
  111015. }
  111016. }
  111017. /* floor backend settings */
  111018. ci->floors=oggpack_read(opb,6)+1;
  111019. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  111020. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  111021. for(i=0;i<ci->floors;i++){
  111022. ci->floor_type[i]=oggpack_read(opb,16);
  111023. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  111024. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  111025. if(!ci->floor_param[i])goto err_out;
  111026. }
  111027. /* residue backend settings */
  111028. ci->residues=oggpack_read(opb,6)+1;
  111029. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  111030. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  111031. for(i=0;i<ci->residues;i++){
  111032. ci->residue_type[i]=oggpack_read(opb,16);
  111033. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  111034. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  111035. if(!ci->residue_param[i])goto err_out;
  111036. }
  111037. /* map backend settings */
  111038. ci->maps=oggpack_read(opb,6)+1;
  111039. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  111040. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  111041. for(i=0;i<ci->maps;i++){
  111042. ci->map_type[i]=oggpack_read(opb,16);
  111043. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  111044. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  111045. if(!ci->map_param[i])goto err_out;
  111046. }
  111047. /* mode settings */
  111048. ci->modes=oggpack_read(opb,6)+1;
  111049. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  111050. for(i=0;i<ci->modes;i++){
  111051. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  111052. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  111053. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  111054. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  111055. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  111056. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  111057. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  111058. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  111059. }
  111060. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  111061. return(0);
  111062. err_out:
  111063. vorbis_info_clear(vi);
  111064. return(OV_EBADHEADER);
  111065. }
  111066. /* The Vorbis header is in three packets; the initial small packet in
  111067. the first page that identifies basic parameters, a second packet
  111068. with bitstream comments and a third packet that holds the
  111069. codebook. */
  111070. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  111071. oggpack_buffer opb;
  111072. if(op){
  111073. oggpack_readinit(&opb,op->packet,op->bytes);
  111074. /* Which of the three types of header is this? */
  111075. /* Also verify header-ness, vorbis */
  111076. {
  111077. char buffer[6];
  111078. int packtype=oggpack_read(&opb,8);
  111079. memset(buffer,0,6);
  111080. _v_readstring(&opb,buffer,6);
  111081. if(memcmp(buffer,"vorbis",6)){
  111082. /* not a vorbis header */
  111083. return(OV_ENOTVORBIS);
  111084. }
  111085. switch(packtype){
  111086. case 0x01: /* least significant *bit* is read first */
  111087. if(!op->b_o_s){
  111088. /* Not the initial packet */
  111089. return(OV_EBADHEADER);
  111090. }
  111091. if(vi->rate!=0){
  111092. /* previously initialized info header */
  111093. return(OV_EBADHEADER);
  111094. }
  111095. return(_vorbis_unpack_info(vi,&opb));
  111096. case 0x03: /* least significant *bit* is read first */
  111097. if(vi->rate==0){
  111098. /* um... we didn't get the initial header */
  111099. return(OV_EBADHEADER);
  111100. }
  111101. return(_vorbis_unpack_comment(vc,&opb));
  111102. case 0x05: /* least significant *bit* is read first */
  111103. if(vi->rate==0 || vc->vendor==NULL){
  111104. /* um... we didn;t get the initial header or comments yet */
  111105. return(OV_EBADHEADER);
  111106. }
  111107. return(_vorbis_unpack_books(vi,&opb));
  111108. default:
  111109. /* Not a valid vorbis header type */
  111110. return(OV_EBADHEADER);
  111111. break;
  111112. }
  111113. }
  111114. }
  111115. return(OV_EBADHEADER);
  111116. }
  111117. /* pack side **********************************************************/
  111118. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  111119. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111120. if(!ci)return(OV_EFAULT);
  111121. /* preamble */
  111122. oggpack_write(opb,0x01,8);
  111123. _v_writestring(opb,"vorbis", 6);
  111124. /* basic information about the stream */
  111125. oggpack_write(opb,0x00,32);
  111126. oggpack_write(opb,vi->channels,8);
  111127. oggpack_write(opb,vi->rate,32);
  111128. oggpack_write(opb,vi->bitrate_upper,32);
  111129. oggpack_write(opb,vi->bitrate_nominal,32);
  111130. oggpack_write(opb,vi->bitrate_lower,32);
  111131. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  111132. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  111133. oggpack_write(opb,1,1);
  111134. return(0);
  111135. }
  111136. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  111137. char temp[]="Xiph.Org libVorbis I 20050304";
  111138. int bytes = strlen(temp);
  111139. /* preamble */
  111140. oggpack_write(opb,0x03,8);
  111141. _v_writestring(opb,"vorbis", 6);
  111142. /* vendor */
  111143. oggpack_write(opb,bytes,32);
  111144. _v_writestring(opb,temp, bytes);
  111145. /* comments */
  111146. oggpack_write(opb,vc->comments,32);
  111147. if(vc->comments){
  111148. int i;
  111149. for(i=0;i<vc->comments;i++){
  111150. if(vc->user_comments[i]){
  111151. oggpack_write(opb,vc->comment_lengths[i],32);
  111152. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  111153. }else{
  111154. oggpack_write(opb,0,32);
  111155. }
  111156. }
  111157. }
  111158. oggpack_write(opb,1,1);
  111159. return(0);
  111160. }
  111161. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  111162. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111163. int i;
  111164. if(!ci)return(OV_EFAULT);
  111165. oggpack_write(opb,0x05,8);
  111166. _v_writestring(opb,"vorbis", 6);
  111167. /* books */
  111168. oggpack_write(opb,ci->books-1,8);
  111169. for(i=0;i<ci->books;i++)
  111170. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  111171. /* times; hook placeholders */
  111172. oggpack_write(opb,0,6);
  111173. oggpack_write(opb,0,16);
  111174. /* floors */
  111175. oggpack_write(opb,ci->floors-1,6);
  111176. for(i=0;i<ci->floors;i++){
  111177. oggpack_write(opb,ci->floor_type[i],16);
  111178. if(_floor_P[ci->floor_type[i]]->pack)
  111179. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  111180. else
  111181. goto err_out;
  111182. }
  111183. /* residues */
  111184. oggpack_write(opb,ci->residues-1,6);
  111185. for(i=0;i<ci->residues;i++){
  111186. oggpack_write(opb,ci->residue_type[i],16);
  111187. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  111188. }
  111189. /* maps */
  111190. oggpack_write(opb,ci->maps-1,6);
  111191. for(i=0;i<ci->maps;i++){
  111192. oggpack_write(opb,ci->map_type[i],16);
  111193. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  111194. }
  111195. /* modes */
  111196. oggpack_write(opb,ci->modes-1,6);
  111197. for(i=0;i<ci->modes;i++){
  111198. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  111199. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  111200. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  111201. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  111202. }
  111203. oggpack_write(opb,1,1);
  111204. return(0);
  111205. err_out:
  111206. return(-1);
  111207. }
  111208. int vorbis_commentheader_out(vorbis_comment *vc,
  111209. ogg_packet *op){
  111210. oggpack_buffer opb;
  111211. oggpack_writeinit(&opb);
  111212. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  111213. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  111214. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  111215. op->bytes=oggpack_bytes(&opb);
  111216. op->b_o_s=0;
  111217. op->e_o_s=0;
  111218. op->granulepos=0;
  111219. op->packetno=1;
  111220. return 0;
  111221. }
  111222. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  111223. vorbis_comment *vc,
  111224. ogg_packet *op,
  111225. ogg_packet *op_comm,
  111226. ogg_packet *op_code){
  111227. int ret=OV_EIMPL;
  111228. vorbis_info *vi=v->vi;
  111229. oggpack_buffer opb;
  111230. private_state *b=(private_state*)v->backend_state;
  111231. if(!b){
  111232. ret=OV_EFAULT;
  111233. goto err_out;
  111234. }
  111235. /* first header packet **********************************************/
  111236. oggpack_writeinit(&opb);
  111237. if(_vorbis_pack_info(&opb,vi))goto err_out;
  111238. /* build the packet */
  111239. if(b->header)_ogg_free(b->header);
  111240. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  111241. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  111242. op->packet=b->header;
  111243. op->bytes=oggpack_bytes(&opb);
  111244. op->b_o_s=1;
  111245. op->e_o_s=0;
  111246. op->granulepos=0;
  111247. op->packetno=0;
  111248. /* second header packet (comments) **********************************/
  111249. oggpack_reset(&opb);
  111250. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  111251. if(b->header1)_ogg_free(b->header1);
  111252. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  111253. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  111254. op_comm->packet=b->header1;
  111255. op_comm->bytes=oggpack_bytes(&opb);
  111256. op_comm->b_o_s=0;
  111257. op_comm->e_o_s=0;
  111258. op_comm->granulepos=0;
  111259. op_comm->packetno=1;
  111260. /* third header packet (modes/codebooks) ****************************/
  111261. oggpack_reset(&opb);
  111262. if(_vorbis_pack_books(&opb,vi))goto err_out;
  111263. if(b->header2)_ogg_free(b->header2);
  111264. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  111265. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  111266. op_code->packet=b->header2;
  111267. op_code->bytes=oggpack_bytes(&opb);
  111268. op_code->b_o_s=0;
  111269. op_code->e_o_s=0;
  111270. op_code->granulepos=0;
  111271. op_code->packetno=2;
  111272. oggpack_writeclear(&opb);
  111273. return(0);
  111274. err_out:
  111275. oggpack_writeclear(&opb);
  111276. memset(op,0,sizeof(*op));
  111277. memset(op_comm,0,sizeof(*op_comm));
  111278. memset(op_code,0,sizeof(*op_code));
  111279. if(b->header)_ogg_free(b->header);
  111280. if(b->header1)_ogg_free(b->header1);
  111281. if(b->header2)_ogg_free(b->header2);
  111282. b->header=NULL;
  111283. b->header1=NULL;
  111284. b->header2=NULL;
  111285. return(ret);
  111286. }
  111287. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  111288. if(granulepos>=0)
  111289. return((double)granulepos/v->vi->rate);
  111290. return(-1);
  111291. }
  111292. #endif
  111293. /*** End of inlined file: info.c ***/
  111294. /*** Start of inlined file: lpc.c ***/
  111295. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  111296. are derived from code written by Jutta Degener and Carsten Bormann;
  111297. thus we include their copyright below. The entirety of this file
  111298. is freely redistributable on the condition that both of these
  111299. copyright notices are preserved without modification. */
  111300. /* Preserved Copyright: *********************************************/
  111301. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  111302. Technische Universita"t Berlin
  111303. Any use of this software is permitted provided that this notice is not
  111304. removed and that neither the authors nor the Technische Universita"t
  111305. Berlin are deemed to have made any representations as to the
  111306. suitability of this software for any purpose nor are held responsible
  111307. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  111308. THIS SOFTWARE.
  111309. As a matter of courtesy, the authors request to be informed about uses
  111310. this software has found, about bugs in this software, and about any
  111311. improvements that may be of general interest.
  111312. Berlin, 28.11.1994
  111313. Jutta Degener
  111314. Carsten Bormann
  111315. *********************************************************************/
  111316. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111317. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111318. // tasks..
  111319. #if JUCE_MSVC
  111320. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111321. #endif
  111322. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111323. #if JUCE_USE_OGGVORBIS
  111324. #include <stdlib.h>
  111325. #include <string.h>
  111326. #include <math.h>
  111327. /* Autocorrelation LPC coeff generation algorithm invented by
  111328. N. Levinson in 1947, modified by J. Durbin in 1959. */
  111329. /* Input : n elements of time doamin data
  111330. Output: m lpc coefficients, excitation energy */
  111331. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  111332. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  111333. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  111334. double error;
  111335. int i,j;
  111336. /* autocorrelation, p+1 lag coefficients */
  111337. j=m+1;
  111338. while(j--){
  111339. double d=0; /* double needed for accumulator depth */
  111340. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  111341. aut[j]=d;
  111342. }
  111343. /* Generate lpc coefficients from autocorr values */
  111344. error=aut[0];
  111345. for(i=0;i<m;i++){
  111346. double r= -aut[i+1];
  111347. if(error==0){
  111348. memset(lpci,0,m*sizeof(*lpci));
  111349. return 0;
  111350. }
  111351. /* Sum up this iteration's reflection coefficient; note that in
  111352. Vorbis we don't save it. If anyone wants to recycle this code
  111353. and needs reflection coefficients, save the results of 'r' from
  111354. each iteration. */
  111355. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  111356. r/=error;
  111357. /* Update LPC coefficients and total error */
  111358. lpc[i]=r;
  111359. for(j=0;j<i/2;j++){
  111360. double tmp=lpc[j];
  111361. lpc[j]+=r*lpc[i-1-j];
  111362. lpc[i-1-j]+=r*tmp;
  111363. }
  111364. if(i%2)lpc[j]+=lpc[j]*r;
  111365. error*=1.f-r*r;
  111366. }
  111367. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  111368. /* we need the error value to know how big an impulse to hit the
  111369. filter with later */
  111370. return error;
  111371. }
  111372. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  111373. float *data,long n){
  111374. /* in: coeff[0...m-1] LPC coefficients
  111375. prime[0...m-1] initial values (allocated size of n+m-1)
  111376. out: data[0...n-1] data samples */
  111377. long i,j,o,p;
  111378. float y;
  111379. float *work=(float*)alloca(sizeof(*work)*(m+n));
  111380. if(!prime)
  111381. for(i=0;i<m;i++)
  111382. work[i]=0.f;
  111383. else
  111384. for(i=0;i<m;i++)
  111385. work[i]=prime[i];
  111386. for(i=0;i<n;i++){
  111387. y=0;
  111388. o=i;
  111389. p=m;
  111390. for(j=0;j<m;j++)
  111391. y-=work[o++]*coeff[--p];
  111392. data[i]=work[o]=y;
  111393. }
  111394. }
  111395. #endif
  111396. /*** End of inlined file: lpc.c ***/
  111397. /*** Start of inlined file: lsp.c ***/
  111398. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  111399. an iterative root polisher (CACM algorithm 283). It *is* possible
  111400. to confuse this algorithm into not converging; that should only
  111401. happen with absurdly closely spaced roots (very sharp peaks in the
  111402. LPC f response) which in turn should be impossible in our use of
  111403. the code. If this *does* happen anyway, it's a bug in the floor
  111404. finder; find the cause of the confusion (probably a single bin
  111405. spike or accidental near-float-limit resolution problems) and
  111406. correct it. */
  111407. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111408. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111409. // tasks..
  111410. #if JUCE_MSVC
  111411. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111412. #endif
  111413. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111414. #if JUCE_USE_OGGVORBIS
  111415. #include <math.h>
  111416. #include <string.h>
  111417. #include <stdlib.h>
  111418. /*** Start of inlined file: lookup.h ***/
  111419. #ifndef _V_LOOKUP_H_
  111420. #ifdef FLOAT_LOOKUP
  111421. extern float vorbis_coslook(float a);
  111422. extern float vorbis_invsqlook(float a);
  111423. extern float vorbis_invsq2explook(int a);
  111424. extern float vorbis_fromdBlook(float a);
  111425. #endif
  111426. #ifdef INT_LOOKUP
  111427. extern long vorbis_invsqlook_i(long a,long e);
  111428. extern long vorbis_coslook_i(long a);
  111429. extern float vorbis_fromdBlook_i(long a);
  111430. #endif
  111431. #endif
  111432. /*** End of inlined file: lookup.h ***/
  111433. /* three possible LSP to f curve functions; the exact computation
  111434. (float), a lookup based float implementation, and an integer
  111435. implementation. The float lookup is likely the optimal choice on
  111436. any machine with an FPU. The integer implementation is *not* fixed
  111437. point (due to the need for a large dynamic range and thus a
  111438. seperately tracked exponent) and thus much more complex than the
  111439. relatively simple float implementations. It's mostly for future
  111440. work on a fully fixed point implementation for processors like the
  111441. ARM family. */
  111442. /* undefine both for the 'old' but more precise implementation */
  111443. #define FLOAT_LOOKUP
  111444. #undef INT_LOOKUP
  111445. #ifdef FLOAT_LOOKUP
  111446. /*** Start of inlined file: lookup.c ***/
  111447. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111448. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111449. // tasks..
  111450. #if JUCE_MSVC
  111451. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111452. #endif
  111453. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111454. #if JUCE_USE_OGGVORBIS
  111455. #include <math.h>
  111456. /*** Start of inlined file: lookup.h ***/
  111457. #ifndef _V_LOOKUP_H_
  111458. #ifdef FLOAT_LOOKUP
  111459. extern float vorbis_coslook(float a);
  111460. extern float vorbis_invsqlook(float a);
  111461. extern float vorbis_invsq2explook(int a);
  111462. extern float vorbis_fromdBlook(float a);
  111463. #endif
  111464. #ifdef INT_LOOKUP
  111465. extern long vorbis_invsqlook_i(long a,long e);
  111466. extern long vorbis_coslook_i(long a);
  111467. extern float vorbis_fromdBlook_i(long a);
  111468. #endif
  111469. #endif
  111470. /*** End of inlined file: lookup.h ***/
  111471. /*** Start of inlined file: lookup_data.h ***/
  111472. #ifndef _V_LOOKUP_DATA_H_
  111473. #ifdef FLOAT_LOOKUP
  111474. #define COS_LOOKUP_SZ 128
  111475. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  111476. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  111477. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  111478. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  111479. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  111480. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  111481. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  111482. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  111483. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  111484. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  111485. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  111486. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  111487. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  111488. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  111489. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  111490. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  111491. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  111492. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  111493. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  111494. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  111495. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  111496. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  111497. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  111498. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  111499. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  111500. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  111501. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  111502. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  111503. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  111504. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  111505. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  111506. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  111507. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  111508. -1.0000000000000f,
  111509. };
  111510. #define INVSQ_LOOKUP_SZ 32
  111511. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  111512. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  111513. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  111514. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  111515. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  111516. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  111517. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  111518. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  111519. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  111520. 1.000000000000f,
  111521. };
  111522. #define INVSQ2EXP_LOOKUP_MIN (-32)
  111523. #define INVSQ2EXP_LOOKUP_MAX 32
  111524. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  111525. INVSQ2EXP_LOOKUP_MIN+1]={
  111526. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  111527. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  111528. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  111529. 1024.f, 724.0773439f, 512.f, 362.038672f,
  111530. 256.f, 181.019336f, 128.f, 90.50966799f,
  111531. 64.f, 45.254834f, 32.f, 22.627417f,
  111532. 16.f, 11.3137085f, 8.f, 5.656854249f,
  111533. 4.f, 2.828427125f, 2.f, 1.414213562f,
  111534. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  111535. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  111536. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  111537. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  111538. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  111539. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  111540. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  111541. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  111542. 1.525878906e-05f,
  111543. };
  111544. #endif
  111545. #define FROMdB_LOOKUP_SZ 35
  111546. #define FROMdB2_LOOKUP_SZ 32
  111547. #define FROMdB_SHIFT 5
  111548. #define FROMdB2_SHIFT 3
  111549. #define FROMdB2_MASK 31
  111550. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  111551. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  111552. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  111553. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  111554. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  111555. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  111556. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  111557. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  111558. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  111559. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  111560. };
  111561. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  111562. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  111563. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  111564. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  111565. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  111566. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  111567. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  111568. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  111569. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  111570. };
  111571. #ifdef INT_LOOKUP
  111572. #define INVSQ_LOOKUP_I_SHIFT 10
  111573. #define INVSQ_LOOKUP_I_MASK 1023
  111574. static long INVSQ_LOOKUP_I[64+1]={
  111575. 92682l, 91966l, 91267l, 90583l,
  111576. 89915l, 89261l, 88621l, 87995l,
  111577. 87381l, 86781l, 86192l, 85616l,
  111578. 85051l, 84497l, 83953l, 83420l,
  111579. 82897l, 82384l, 81880l, 81385l,
  111580. 80899l, 80422l, 79953l, 79492l,
  111581. 79039l, 78594l, 78156l, 77726l,
  111582. 77302l, 76885l, 76475l, 76072l,
  111583. 75674l, 75283l, 74898l, 74519l,
  111584. 74146l, 73778l, 73415l, 73058l,
  111585. 72706l, 72359l, 72016l, 71679l,
  111586. 71347l, 71019l, 70695l, 70376l,
  111587. 70061l, 69750l, 69444l, 69141l,
  111588. 68842l, 68548l, 68256l, 67969l,
  111589. 67685l, 67405l, 67128l, 66855l,
  111590. 66585l, 66318l, 66054l, 65794l,
  111591. 65536l,
  111592. };
  111593. #define COS_LOOKUP_I_SHIFT 9
  111594. #define COS_LOOKUP_I_MASK 511
  111595. #define COS_LOOKUP_I_SZ 128
  111596. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  111597. 16384l, 16379l, 16364l, 16340l,
  111598. 16305l, 16261l, 16207l, 16143l,
  111599. 16069l, 15986l, 15893l, 15791l,
  111600. 15679l, 15557l, 15426l, 15286l,
  111601. 15137l, 14978l, 14811l, 14635l,
  111602. 14449l, 14256l, 14053l, 13842l,
  111603. 13623l, 13395l, 13160l, 12916l,
  111604. 12665l, 12406l, 12140l, 11866l,
  111605. 11585l, 11297l, 11003l, 10702l,
  111606. 10394l, 10080l, 9760l, 9434l,
  111607. 9102l, 8765l, 8423l, 8076l,
  111608. 7723l, 7366l, 7005l, 6639l,
  111609. 6270l, 5897l, 5520l, 5139l,
  111610. 4756l, 4370l, 3981l, 3590l,
  111611. 3196l, 2801l, 2404l, 2006l,
  111612. 1606l, 1205l, 804l, 402l,
  111613. 0l, -401l, -803l, -1204l,
  111614. -1605l, -2005l, -2403l, -2800l,
  111615. -3195l, -3589l, -3980l, -4369l,
  111616. -4755l, -5138l, -5519l, -5896l,
  111617. -6269l, -6638l, -7004l, -7365l,
  111618. -7722l, -8075l, -8422l, -8764l,
  111619. -9101l, -9433l, -9759l, -10079l,
  111620. -10393l, -10701l, -11002l, -11296l,
  111621. -11584l, -11865l, -12139l, -12405l,
  111622. -12664l, -12915l, -13159l, -13394l,
  111623. -13622l, -13841l, -14052l, -14255l,
  111624. -14448l, -14634l, -14810l, -14977l,
  111625. -15136l, -15285l, -15425l, -15556l,
  111626. -15678l, -15790l, -15892l, -15985l,
  111627. -16068l, -16142l, -16206l, -16260l,
  111628. -16304l, -16339l, -16363l, -16378l,
  111629. -16383l,
  111630. };
  111631. #endif
  111632. #endif
  111633. /*** End of inlined file: lookup_data.h ***/
  111634. #ifdef FLOAT_LOOKUP
  111635. /* interpolated lookup based cos function, domain 0 to PI only */
  111636. float vorbis_coslook(float a){
  111637. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  111638. int i=vorbis_ftoi(d-.5);
  111639. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  111640. }
  111641. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  111642. float vorbis_invsqlook(float a){
  111643. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  111644. int i=vorbis_ftoi(d-.5f);
  111645. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  111646. }
  111647. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  111648. float vorbis_invsq2explook(int a){
  111649. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  111650. }
  111651. #include <stdio.h>
  111652. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  111653. float vorbis_fromdBlook(float a){
  111654. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  111655. return (i<0)?1.f:
  111656. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  111657. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  111658. }
  111659. #endif
  111660. #ifdef INT_LOOKUP
  111661. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  111662. 16.16 format
  111663. returns in m.8 format */
  111664. long vorbis_invsqlook_i(long a,long e){
  111665. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  111666. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  111667. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  111668. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  111669. d)>>16); /* result 1.16 */
  111670. e+=32;
  111671. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  111672. e=(e>>1)-8;
  111673. return(val>>e);
  111674. }
  111675. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  111676. /* a is in n.12 format */
  111677. float vorbis_fromdBlook_i(long a){
  111678. int i=(-a)>>(12-FROMdB2_SHIFT);
  111679. return (i<0)?1.f:
  111680. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  111681. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  111682. }
  111683. /* interpolated lookup based cos function, domain 0 to PI only */
  111684. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  111685. long vorbis_coslook_i(long a){
  111686. int i=a>>COS_LOOKUP_I_SHIFT;
  111687. int d=a&COS_LOOKUP_I_MASK;
  111688. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  111689. COS_LOOKUP_I_SHIFT);
  111690. }
  111691. #endif
  111692. #endif
  111693. /*** End of inlined file: lookup.c ***/
  111694. /* catch this in the build system; we #include for
  111695. compilers (like gcc) that can't inline across
  111696. modules */
  111697. /* side effect: changes *lsp to cosines of lsp */
  111698. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  111699. float amp,float ampoffset){
  111700. int i;
  111701. float wdel=M_PI/ln;
  111702. vorbis_fpu_control fpu;
  111703. (void) fpu; // to avoid an unused variable warning
  111704. vorbis_fpu_setround(&fpu);
  111705. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  111706. i=0;
  111707. while(i<n){
  111708. int k=map[i];
  111709. int qexp;
  111710. float p=.7071067812f;
  111711. float q=.7071067812f;
  111712. float w=vorbis_coslook(wdel*k);
  111713. float *ftmp=lsp;
  111714. int c=m>>1;
  111715. do{
  111716. q*=ftmp[0]-w;
  111717. p*=ftmp[1]-w;
  111718. ftmp+=2;
  111719. }while(--c);
  111720. if(m&1){
  111721. /* odd order filter; slightly assymetric */
  111722. /* the last coefficient */
  111723. q*=ftmp[0]-w;
  111724. q*=q;
  111725. p*=p*(1.f-w*w);
  111726. }else{
  111727. /* even order filter; still symmetric */
  111728. q*=q*(1.f+w);
  111729. p*=p*(1.f-w);
  111730. }
  111731. q=frexp(p+q,&qexp);
  111732. q=vorbis_fromdBlook(amp*
  111733. vorbis_invsqlook(q)*
  111734. vorbis_invsq2explook(qexp+m)-
  111735. ampoffset);
  111736. do{
  111737. curve[i++]*=q;
  111738. }while(map[i]==k);
  111739. }
  111740. vorbis_fpu_restore(fpu);
  111741. }
  111742. #else
  111743. #ifdef INT_LOOKUP
  111744. /*** Start of inlined file: lookup.c ***/
  111745. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111746. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111747. // tasks..
  111748. #if JUCE_MSVC
  111749. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111750. #endif
  111751. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111752. #if JUCE_USE_OGGVORBIS
  111753. #include <math.h>
  111754. /*** Start of inlined file: lookup.h ***/
  111755. #ifndef _V_LOOKUP_H_
  111756. #ifdef FLOAT_LOOKUP
  111757. extern float vorbis_coslook(float a);
  111758. extern float vorbis_invsqlook(float a);
  111759. extern float vorbis_invsq2explook(int a);
  111760. extern float vorbis_fromdBlook(float a);
  111761. #endif
  111762. #ifdef INT_LOOKUP
  111763. extern long vorbis_invsqlook_i(long a,long e);
  111764. extern long vorbis_coslook_i(long a);
  111765. extern float vorbis_fromdBlook_i(long a);
  111766. #endif
  111767. #endif
  111768. /*** End of inlined file: lookup.h ***/
  111769. /*** Start of inlined file: lookup_data.h ***/
  111770. #ifndef _V_LOOKUP_DATA_H_
  111771. #ifdef FLOAT_LOOKUP
  111772. #define COS_LOOKUP_SZ 128
  111773. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  111774. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  111775. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  111776. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  111777. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  111778. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  111779. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  111780. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  111781. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  111782. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  111783. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  111784. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  111785. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  111786. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  111787. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  111788. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  111789. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  111790. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  111791. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  111792. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  111793. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  111794. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  111795. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  111796. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  111797. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  111798. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  111799. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  111800. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  111801. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  111802. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  111803. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  111804. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  111805. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  111806. -1.0000000000000f,
  111807. };
  111808. #define INVSQ_LOOKUP_SZ 32
  111809. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  111810. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  111811. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  111812. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  111813. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  111814. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  111815. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  111816. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  111817. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  111818. 1.000000000000f,
  111819. };
  111820. #define INVSQ2EXP_LOOKUP_MIN (-32)
  111821. #define INVSQ2EXP_LOOKUP_MAX 32
  111822. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  111823. INVSQ2EXP_LOOKUP_MIN+1]={
  111824. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  111825. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  111826. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  111827. 1024.f, 724.0773439f, 512.f, 362.038672f,
  111828. 256.f, 181.019336f, 128.f, 90.50966799f,
  111829. 64.f, 45.254834f, 32.f, 22.627417f,
  111830. 16.f, 11.3137085f, 8.f, 5.656854249f,
  111831. 4.f, 2.828427125f, 2.f, 1.414213562f,
  111832. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  111833. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  111834. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  111835. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  111836. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  111837. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  111838. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  111839. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  111840. 1.525878906e-05f,
  111841. };
  111842. #endif
  111843. #define FROMdB_LOOKUP_SZ 35
  111844. #define FROMdB2_LOOKUP_SZ 32
  111845. #define FROMdB_SHIFT 5
  111846. #define FROMdB2_SHIFT 3
  111847. #define FROMdB2_MASK 31
  111848. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  111849. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  111850. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  111851. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  111852. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  111853. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  111854. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  111855. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  111856. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  111857. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  111858. };
  111859. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  111860. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  111861. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  111862. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  111863. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  111864. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  111865. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  111866. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  111867. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  111868. };
  111869. #ifdef INT_LOOKUP
  111870. #define INVSQ_LOOKUP_I_SHIFT 10
  111871. #define INVSQ_LOOKUP_I_MASK 1023
  111872. static long INVSQ_LOOKUP_I[64+1]={
  111873. 92682l, 91966l, 91267l, 90583l,
  111874. 89915l, 89261l, 88621l, 87995l,
  111875. 87381l, 86781l, 86192l, 85616l,
  111876. 85051l, 84497l, 83953l, 83420l,
  111877. 82897l, 82384l, 81880l, 81385l,
  111878. 80899l, 80422l, 79953l, 79492l,
  111879. 79039l, 78594l, 78156l, 77726l,
  111880. 77302l, 76885l, 76475l, 76072l,
  111881. 75674l, 75283l, 74898l, 74519l,
  111882. 74146l, 73778l, 73415l, 73058l,
  111883. 72706l, 72359l, 72016l, 71679l,
  111884. 71347l, 71019l, 70695l, 70376l,
  111885. 70061l, 69750l, 69444l, 69141l,
  111886. 68842l, 68548l, 68256l, 67969l,
  111887. 67685l, 67405l, 67128l, 66855l,
  111888. 66585l, 66318l, 66054l, 65794l,
  111889. 65536l,
  111890. };
  111891. #define COS_LOOKUP_I_SHIFT 9
  111892. #define COS_LOOKUP_I_MASK 511
  111893. #define COS_LOOKUP_I_SZ 128
  111894. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  111895. 16384l, 16379l, 16364l, 16340l,
  111896. 16305l, 16261l, 16207l, 16143l,
  111897. 16069l, 15986l, 15893l, 15791l,
  111898. 15679l, 15557l, 15426l, 15286l,
  111899. 15137l, 14978l, 14811l, 14635l,
  111900. 14449l, 14256l, 14053l, 13842l,
  111901. 13623l, 13395l, 13160l, 12916l,
  111902. 12665l, 12406l, 12140l, 11866l,
  111903. 11585l, 11297l, 11003l, 10702l,
  111904. 10394l, 10080l, 9760l, 9434l,
  111905. 9102l, 8765l, 8423l, 8076l,
  111906. 7723l, 7366l, 7005l, 6639l,
  111907. 6270l, 5897l, 5520l, 5139l,
  111908. 4756l, 4370l, 3981l, 3590l,
  111909. 3196l, 2801l, 2404l, 2006l,
  111910. 1606l, 1205l, 804l, 402l,
  111911. 0l, -401l, -803l, -1204l,
  111912. -1605l, -2005l, -2403l, -2800l,
  111913. -3195l, -3589l, -3980l, -4369l,
  111914. -4755l, -5138l, -5519l, -5896l,
  111915. -6269l, -6638l, -7004l, -7365l,
  111916. -7722l, -8075l, -8422l, -8764l,
  111917. -9101l, -9433l, -9759l, -10079l,
  111918. -10393l, -10701l, -11002l, -11296l,
  111919. -11584l, -11865l, -12139l, -12405l,
  111920. -12664l, -12915l, -13159l, -13394l,
  111921. -13622l, -13841l, -14052l, -14255l,
  111922. -14448l, -14634l, -14810l, -14977l,
  111923. -15136l, -15285l, -15425l, -15556l,
  111924. -15678l, -15790l, -15892l, -15985l,
  111925. -16068l, -16142l, -16206l, -16260l,
  111926. -16304l, -16339l, -16363l, -16378l,
  111927. -16383l,
  111928. };
  111929. #endif
  111930. #endif
  111931. /*** End of inlined file: lookup_data.h ***/
  111932. #ifdef FLOAT_LOOKUP
  111933. /* interpolated lookup based cos function, domain 0 to PI only */
  111934. float vorbis_coslook(float a){
  111935. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  111936. int i=vorbis_ftoi(d-.5);
  111937. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  111938. }
  111939. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  111940. float vorbis_invsqlook(float a){
  111941. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  111942. int i=vorbis_ftoi(d-.5f);
  111943. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  111944. }
  111945. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  111946. float vorbis_invsq2explook(int a){
  111947. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  111948. }
  111949. #include <stdio.h>
  111950. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  111951. float vorbis_fromdBlook(float a){
  111952. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  111953. return (i<0)?1.f:
  111954. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  111955. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  111956. }
  111957. #endif
  111958. #ifdef INT_LOOKUP
  111959. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  111960. 16.16 format
  111961. returns in m.8 format */
  111962. long vorbis_invsqlook_i(long a,long e){
  111963. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  111964. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  111965. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  111966. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  111967. d)>>16); /* result 1.16 */
  111968. e+=32;
  111969. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  111970. e=(e>>1)-8;
  111971. return(val>>e);
  111972. }
  111973. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  111974. /* a is in n.12 format */
  111975. float vorbis_fromdBlook_i(long a){
  111976. int i=(-a)>>(12-FROMdB2_SHIFT);
  111977. return (i<0)?1.f:
  111978. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  111979. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  111980. }
  111981. /* interpolated lookup based cos function, domain 0 to PI only */
  111982. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  111983. long vorbis_coslook_i(long a){
  111984. int i=a>>COS_LOOKUP_I_SHIFT;
  111985. int d=a&COS_LOOKUP_I_MASK;
  111986. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  111987. COS_LOOKUP_I_SHIFT);
  111988. }
  111989. #endif
  111990. #endif
  111991. /*** End of inlined file: lookup.c ***/
  111992. /* catch this in the build system; we #include for
  111993. compilers (like gcc) that can't inline across
  111994. modules */
  111995. static int MLOOP_1[64]={
  111996. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  111997. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  111998. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  111999. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  112000. };
  112001. static int MLOOP_2[64]={
  112002. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  112003. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  112004. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  112005. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  112006. };
  112007. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  112008. /* side effect: changes *lsp to cosines of lsp */
  112009. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  112010. float amp,float ampoffset){
  112011. /* 0 <= m < 256 */
  112012. /* set up for using all int later */
  112013. int i;
  112014. int ampoffseti=rint(ampoffset*4096.f);
  112015. int ampi=rint(amp*16.f);
  112016. long *ilsp=alloca(m*sizeof(*ilsp));
  112017. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  112018. i=0;
  112019. while(i<n){
  112020. int j,k=map[i];
  112021. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  112022. unsigned long qi=46341;
  112023. int qexp=0,shift;
  112024. long wi=vorbis_coslook_i(k*65536/ln);
  112025. qi*=labs(ilsp[0]-wi);
  112026. pi*=labs(ilsp[1]-wi);
  112027. for(j=3;j<m;j+=2){
  112028. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  112029. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  112030. shift=MLOOP_3[(pi|qi)>>16];
  112031. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  112032. pi=(pi>>shift)*labs(ilsp[j]-wi);
  112033. qexp+=shift;
  112034. }
  112035. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  112036. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  112037. shift=MLOOP_3[(pi|qi)>>16];
  112038. /* pi,qi normalized collectively, both tracked using qexp */
  112039. if(m&1){
  112040. /* odd order filter; slightly assymetric */
  112041. /* the last coefficient */
  112042. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  112043. pi=(pi>>shift)<<14;
  112044. qexp+=shift;
  112045. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  112046. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  112047. shift=MLOOP_3[(pi|qi)>>16];
  112048. pi>>=shift;
  112049. qi>>=shift;
  112050. qexp+=shift-14*((m+1)>>1);
  112051. pi=((pi*pi)>>16);
  112052. qi=((qi*qi)>>16);
  112053. qexp=qexp*2+m;
  112054. pi*=(1<<14)-((wi*wi)>>14);
  112055. qi+=pi>>14;
  112056. }else{
  112057. /* even order filter; still symmetric */
  112058. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  112059. worth tracking step by step */
  112060. pi>>=shift;
  112061. qi>>=shift;
  112062. qexp+=shift-7*m;
  112063. pi=((pi*pi)>>16);
  112064. qi=((qi*qi)>>16);
  112065. qexp=qexp*2+m;
  112066. pi*=(1<<14)-wi;
  112067. qi*=(1<<14)+wi;
  112068. qi=(qi+pi)>>14;
  112069. }
  112070. /* we've let the normalization drift because it wasn't important;
  112071. however, for the lookup, things must be normalized again. We
  112072. need at most one right shift or a number of left shifts */
  112073. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  112074. qi>>=1; qexp++;
  112075. }else
  112076. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  112077. qi<<=1; qexp--;
  112078. }
  112079. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  112080. vorbis_invsqlook_i(qi,qexp)-
  112081. /* m.8, m+n<=8 */
  112082. ampoffseti); /* 8.12[0] */
  112083. curve[i]*=amp;
  112084. while(map[++i]==k)curve[i]*=amp;
  112085. }
  112086. }
  112087. #else
  112088. /* old, nonoptimized but simple version for any poor sap who needs to
  112089. figure out what the hell this code does, or wants the other
  112090. fraction of a dB precision */
  112091. /* side effect: changes *lsp to cosines of lsp */
  112092. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  112093. float amp,float ampoffset){
  112094. int i;
  112095. float wdel=M_PI/ln;
  112096. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  112097. i=0;
  112098. while(i<n){
  112099. int j,k=map[i];
  112100. float p=.5f;
  112101. float q=.5f;
  112102. float w=2.f*cos(wdel*k);
  112103. for(j=1;j<m;j+=2){
  112104. q *= w-lsp[j-1];
  112105. p *= w-lsp[j];
  112106. }
  112107. if(j==m){
  112108. /* odd order filter; slightly assymetric */
  112109. /* the last coefficient */
  112110. q*=w-lsp[j-1];
  112111. p*=p*(4.f-w*w);
  112112. q*=q;
  112113. }else{
  112114. /* even order filter; still symmetric */
  112115. p*=p*(2.f-w);
  112116. q*=q*(2.f+w);
  112117. }
  112118. q=fromdB(amp/sqrt(p+q)-ampoffset);
  112119. curve[i]*=q;
  112120. while(map[++i]==k)curve[i]*=q;
  112121. }
  112122. }
  112123. #endif
  112124. #endif
  112125. static void cheby(float *g, int ord) {
  112126. int i, j;
  112127. g[0] *= .5f;
  112128. for(i=2; i<= ord; i++) {
  112129. for(j=ord; j >= i; j--) {
  112130. g[j-2] -= g[j];
  112131. g[j] += g[j];
  112132. }
  112133. }
  112134. }
  112135. static int comp(const void *a,const void *b){
  112136. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  112137. }
  112138. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  112139. but there are root sets for which it gets into limit cycles
  112140. (exacerbated by zero suppression) and fails. We can't afford to
  112141. fail, even if the failure is 1 in 100,000,000, so we now use
  112142. Laguerre and later polish with Newton-Raphson (which can then
  112143. afford to fail) */
  112144. #define EPSILON 10e-7
  112145. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  112146. int i,m;
  112147. double lastdelta=0.f;
  112148. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  112149. for(i=0;i<=ord;i++)defl[i]=a[i];
  112150. for(m=ord;m>0;m--){
  112151. double newx=0.f,delta;
  112152. /* iterate a root */
  112153. while(1){
  112154. double p=defl[m],pp=0.f,ppp=0.f,denom;
  112155. /* eval the polynomial and its first two derivatives */
  112156. for(i=m;i>0;i--){
  112157. ppp = newx*ppp + pp;
  112158. pp = newx*pp + p;
  112159. p = newx*p + defl[i-1];
  112160. }
  112161. /* Laguerre's method */
  112162. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  112163. if(denom<0)
  112164. return(-1); /* complex root! The LPC generator handed us a bad filter */
  112165. if(pp>0){
  112166. denom = pp + sqrt(denom);
  112167. if(denom<EPSILON)denom=EPSILON;
  112168. }else{
  112169. denom = pp - sqrt(denom);
  112170. if(denom>-(EPSILON))denom=-(EPSILON);
  112171. }
  112172. delta = m*p/denom;
  112173. newx -= delta;
  112174. if(delta<0.f)delta*=-1;
  112175. if(fabs(delta/newx)<10e-12)break;
  112176. lastdelta=delta;
  112177. }
  112178. r[m-1]=newx;
  112179. /* forward deflation */
  112180. for(i=m;i>0;i--)
  112181. defl[i-1]+=newx*defl[i];
  112182. defl++;
  112183. }
  112184. return(0);
  112185. }
  112186. /* for spit-and-polish only */
  112187. static int Newton_Raphson(float *a,int ord,float *r){
  112188. int i, k, count=0;
  112189. double error=1.f;
  112190. double *root=(double*)alloca(ord*sizeof(*root));
  112191. for(i=0; i<ord;i++) root[i] = r[i];
  112192. while(error>1e-20){
  112193. error=0;
  112194. for(i=0; i<ord; i++) { /* Update each point. */
  112195. double pp=0.,delta;
  112196. double rooti=root[i];
  112197. double p=a[ord];
  112198. for(k=ord-1; k>= 0; k--) {
  112199. pp= pp* rooti + p;
  112200. p = p * rooti + a[k];
  112201. }
  112202. delta = p/pp;
  112203. root[i] -= delta;
  112204. error+= delta*delta;
  112205. }
  112206. if(count>40)return(-1);
  112207. count++;
  112208. }
  112209. /* Replaced the original bubble sort with a real sort. With your
  112210. help, we can eliminate the bubble sort in our lifetime. --Monty */
  112211. for(i=0; i<ord;i++) r[i] = root[i];
  112212. return(0);
  112213. }
  112214. /* Convert lpc coefficients to lsp coefficients */
  112215. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  112216. int order2=(m+1)>>1;
  112217. int g1_order,g2_order;
  112218. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  112219. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  112220. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  112221. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  112222. int i;
  112223. /* even and odd are slightly different base cases */
  112224. g1_order=(m+1)>>1;
  112225. g2_order=(m) >>1;
  112226. /* Compute the lengths of the x polynomials. */
  112227. /* Compute the first half of K & R F1 & F2 polynomials. */
  112228. /* Compute half of the symmetric and antisymmetric polynomials. */
  112229. /* Remove the roots at +1 and -1. */
  112230. g1[g1_order] = 1.f;
  112231. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  112232. g2[g2_order] = 1.f;
  112233. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  112234. if(g1_order>g2_order){
  112235. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  112236. }else{
  112237. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  112238. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  112239. }
  112240. /* Convert into polynomials in cos(alpha) */
  112241. cheby(g1,g1_order);
  112242. cheby(g2,g2_order);
  112243. /* Find the roots of the 2 even polynomials.*/
  112244. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  112245. Laguerre_With_Deflation(g2,g2_order,g2r))
  112246. return(-1);
  112247. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  112248. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  112249. qsort(g1r,g1_order,sizeof(*g1r),comp);
  112250. qsort(g2r,g2_order,sizeof(*g2r),comp);
  112251. for(i=0;i<g1_order;i++)
  112252. lsp[i*2] = acos(g1r[i]);
  112253. for(i=0;i<g2_order;i++)
  112254. lsp[i*2+1] = acos(g2r[i]);
  112255. return(0);
  112256. }
  112257. #endif
  112258. /*** End of inlined file: lsp.c ***/
  112259. /*** Start of inlined file: mapping0.c ***/
  112260. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112261. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112262. // tasks..
  112263. #if JUCE_MSVC
  112264. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112265. #endif
  112266. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112267. #if JUCE_USE_OGGVORBIS
  112268. #include <stdlib.h>
  112269. #include <stdio.h>
  112270. #include <string.h>
  112271. #include <math.h>
  112272. /* simplistic, wasteful way of doing this (unique lookup for each
  112273. mode/submapping); there should be a central repository for
  112274. identical lookups. That will require minor work, so I'm putting it
  112275. off as low priority.
  112276. Why a lookup for each backend in a given mode? Because the
  112277. blocksize is set by the mode, and low backend lookups may require
  112278. parameters from other areas of the mode/mapping */
  112279. static void mapping0_free_info(vorbis_info_mapping *i){
  112280. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  112281. if(info){
  112282. memset(info,0,sizeof(*info));
  112283. _ogg_free(info);
  112284. }
  112285. }
  112286. static int ilog3(unsigned int v){
  112287. int ret=0;
  112288. if(v)--v;
  112289. while(v){
  112290. ret++;
  112291. v>>=1;
  112292. }
  112293. return(ret);
  112294. }
  112295. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  112296. oggpack_buffer *opb){
  112297. int i;
  112298. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  112299. /* another 'we meant to do it this way' hack... up to beta 4, we
  112300. packed 4 binary zeros here to signify one submapping in use. We
  112301. now redefine that to mean four bitflags that indicate use of
  112302. deeper features; bit0:submappings, bit1:coupling,
  112303. bit2,3:reserved. This is backward compatable with all actual uses
  112304. of the beta code. */
  112305. if(info->submaps>1){
  112306. oggpack_write(opb,1,1);
  112307. oggpack_write(opb,info->submaps-1,4);
  112308. }else
  112309. oggpack_write(opb,0,1);
  112310. if(info->coupling_steps>0){
  112311. oggpack_write(opb,1,1);
  112312. oggpack_write(opb,info->coupling_steps-1,8);
  112313. for(i=0;i<info->coupling_steps;i++){
  112314. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  112315. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  112316. }
  112317. }else
  112318. oggpack_write(opb,0,1);
  112319. oggpack_write(opb,0,2); /* 2,3:reserved */
  112320. /* we don't write the channel submappings if we only have one... */
  112321. if(info->submaps>1){
  112322. for(i=0;i<vi->channels;i++)
  112323. oggpack_write(opb,info->chmuxlist[i],4);
  112324. }
  112325. for(i=0;i<info->submaps;i++){
  112326. oggpack_write(opb,0,8); /* time submap unused */
  112327. oggpack_write(opb,info->floorsubmap[i],8);
  112328. oggpack_write(opb,info->residuesubmap[i],8);
  112329. }
  112330. }
  112331. /* also responsible for range checking */
  112332. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  112333. int i;
  112334. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  112335. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112336. memset(info,0,sizeof(*info));
  112337. if(oggpack_read(opb,1))
  112338. info->submaps=oggpack_read(opb,4)+1;
  112339. else
  112340. info->submaps=1;
  112341. if(oggpack_read(opb,1)){
  112342. info->coupling_steps=oggpack_read(opb,8)+1;
  112343. for(i=0;i<info->coupling_steps;i++){
  112344. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  112345. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  112346. if(testM<0 ||
  112347. testA<0 ||
  112348. testM==testA ||
  112349. testM>=vi->channels ||
  112350. testA>=vi->channels) goto err_out;
  112351. }
  112352. }
  112353. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  112354. if(info->submaps>1){
  112355. for(i=0;i<vi->channels;i++){
  112356. info->chmuxlist[i]=oggpack_read(opb,4);
  112357. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  112358. }
  112359. }
  112360. for(i=0;i<info->submaps;i++){
  112361. oggpack_read(opb,8); /* time submap unused */
  112362. info->floorsubmap[i]=oggpack_read(opb,8);
  112363. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  112364. info->residuesubmap[i]=oggpack_read(opb,8);
  112365. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  112366. }
  112367. return info;
  112368. err_out:
  112369. mapping0_free_info(info);
  112370. return(NULL);
  112371. }
  112372. #if 0
  112373. static long seq=0;
  112374. static ogg_int64_t total=0;
  112375. static float FLOOR1_fromdB_LOOKUP[256]={
  112376. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  112377. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  112378. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  112379. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  112380. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  112381. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  112382. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  112383. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  112384. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  112385. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  112386. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  112387. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  112388. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  112389. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  112390. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  112391. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  112392. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  112393. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  112394. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  112395. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  112396. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  112397. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  112398. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  112399. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  112400. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  112401. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  112402. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  112403. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  112404. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  112405. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  112406. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  112407. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  112408. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  112409. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  112410. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  112411. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  112412. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  112413. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  112414. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  112415. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  112416. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  112417. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  112418. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  112419. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  112420. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  112421. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  112422. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  112423. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  112424. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  112425. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  112426. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  112427. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  112428. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  112429. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  112430. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  112431. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  112432. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  112433. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  112434. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  112435. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  112436. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  112437. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  112438. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  112439. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  112440. };
  112441. #endif
  112442. extern int *floor1_fit(vorbis_block *vb,void *look,
  112443. const float *logmdct, /* in */
  112444. const float *logmask);
  112445. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  112446. int *A,int *B,
  112447. int del);
  112448. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  112449. void*look,
  112450. int *post,int *ilogmask);
  112451. static int mapping0_forward(vorbis_block *vb){
  112452. vorbis_dsp_state *vd=vb->vd;
  112453. vorbis_info *vi=vd->vi;
  112454. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112455. private_state *b=(private_state*)vb->vd->backend_state;
  112456. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  112457. int n=vb->pcmend;
  112458. int i,j,k;
  112459. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  112460. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  112461. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  112462. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  112463. float global_ampmax=vbi->ampmax;
  112464. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  112465. int blocktype=vbi->blocktype;
  112466. int modenumber=vb->W;
  112467. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  112468. vorbis_look_psy *psy_look=
  112469. b->psy+blocktype+(vb->W?2:0);
  112470. vb->mode=modenumber;
  112471. for(i=0;i<vi->channels;i++){
  112472. float scale=4.f/n;
  112473. float scale_dB;
  112474. float *pcm =vb->pcm[i];
  112475. float *logfft =pcm;
  112476. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  112477. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  112478. todB estimation used on IEEE 754
  112479. compliant machines had a bug that
  112480. returned dB values about a third
  112481. of a decibel too high. The bug
  112482. was harmless because tunings
  112483. implicitly took that into
  112484. account. However, fixing the bug
  112485. in the estimator requires
  112486. changing all the tunings as well.
  112487. For now, it's easier to sync
  112488. things back up here, and
  112489. recalibrate the tunings in the
  112490. next major model upgrade. */
  112491. #if 0
  112492. if(vi->channels==2)
  112493. if(i==0)
  112494. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  112495. else
  112496. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  112497. #endif
  112498. /* window the PCM data */
  112499. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  112500. #if 0
  112501. if(vi->channels==2)
  112502. if(i==0)
  112503. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  112504. else
  112505. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  112506. #endif
  112507. /* transform the PCM data */
  112508. /* only MDCT right now.... */
  112509. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  112510. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  112511. drft_forward(&b->fft_look[vb->W],pcm);
  112512. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  112513. original todB estimation used on
  112514. IEEE 754 compliant machines had a
  112515. bug that returned dB values about
  112516. a third of a decibel too high.
  112517. The bug was harmless because
  112518. tunings implicitly took that into
  112519. account. However, fixing the bug
  112520. in the estimator requires
  112521. changing all the tunings as well.
  112522. For now, it's easier to sync
  112523. things back up here, and
  112524. recalibrate the tunings in the
  112525. next major model upgrade. */
  112526. local_ampmax[i]=logfft[0];
  112527. for(j=1;j<n-1;j+=2){
  112528. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  112529. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  112530. .345 is a hack; the original todB
  112531. estimation used on IEEE 754
  112532. compliant machines had a bug that
  112533. returned dB values about a third
  112534. of a decibel too high. The bug
  112535. was harmless because tunings
  112536. implicitly took that into
  112537. account. However, fixing the bug
  112538. in the estimator requires
  112539. changing all the tunings as well.
  112540. For now, it's easier to sync
  112541. things back up here, and
  112542. recalibrate the tunings in the
  112543. next major model upgrade. */
  112544. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  112545. }
  112546. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  112547. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  112548. #if 0
  112549. if(vi->channels==2){
  112550. if(i==0){
  112551. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  112552. }else{
  112553. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  112554. }
  112555. }
  112556. #endif
  112557. }
  112558. {
  112559. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  112560. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  112561. for(i=0;i<vi->channels;i++){
  112562. /* the encoder setup assumes that all the modes used by any
  112563. specific bitrate tweaking use the same floor */
  112564. int submap=info->chmuxlist[i];
  112565. /* the following makes things clearer to *me* anyway */
  112566. float *mdct =gmdct[i];
  112567. float *logfft =vb->pcm[i];
  112568. float *logmdct =logfft+n/2;
  112569. float *logmask =logfft;
  112570. vb->mode=modenumber;
  112571. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  112572. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  112573. for(j=0;j<n/2;j++)
  112574. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  112575. todB estimation used on IEEE 754
  112576. compliant machines had a bug that
  112577. returned dB values about a third
  112578. of a decibel too high. The bug
  112579. was harmless because tunings
  112580. implicitly took that into
  112581. account. However, fixing the bug
  112582. in the estimator requires
  112583. changing all the tunings as well.
  112584. For now, it's easier to sync
  112585. things back up here, and
  112586. recalibrate the tunings in the
  112587. next major model upgrade. */
  112588. #if 0
  112589. if(vi->channels==2){
  112590. if(i==0)
  112591. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  112592. else
  112593. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  112594. }else{
  112595. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  112596. }
  112597. #endif
  112598. /* first step; noise masking. Not only does 'noise masking'
  112599. give us curves from which we can decide how much resolution
  112600. to give noise parts of the spectrum, it also implicitly hands
  112601. us a tonality estimate (the larger the value in the
  112602. 'noise_depth' vector, the more tonal that area is) */
  112603. _vp_noisemask(psy_look,
  112604. logmdct,
  112605. noise); /* noise does not have by-frequency offset
  112606. bias applied yet */
  112607. #if 0
  112608. if(vi->channels==2){
  112609. if(i==0)
  112610. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  112611. else
  112612. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  112613. }
  112614. #endif
  112615. /* second step: 'all the other crap'; all the stuff that isn't
  112616. computed/fit for bitrate management goes in the second psy
  112617. vector. This includes tone masking, peak limiting and ATH */
  112618. _vp_tonemask(psy_look,
  112619. logfft,
  112620. tone,
  112621. global_ampmax,
  112622. local_ampmax[i]);
  112623. #if 0
  112624. if(vi->channels==2){
  112625. if(i==0)
  112626. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  112627. else
  112628. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  112629. }
  112630. #endif
  112631. /* third step; we offset the noise vectors, overlay tone
  112632. masking. We then do a floor1-specific line fit. If we're
  112633. performing bitrate management, the line fit is performed
  112634. multiple times for up/down tweakage on demand. */
  112635. #if 0
  112636. {
  112637. float aotuv[psy_look->n];
  112638. #endif
  112639. _vp_offset_and_mix(psy_look,
  112640. noise,
  112641. tone,
  112642. 1,
  112643. logmask,
  112644. mdct,
  112645. logmdct);
  112646. #if 0
  112647. if(vi->channels==2){
  112648. if(i==0)
  112649. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  112650. else
  112651. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  112652. }
  112653. }
  112654. #endif
  112655. #if 0
  112656. if(vi->channels==2){
  112657. if(i==0)
  112658. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  112659. else
  112660. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  112661. }
  112662. #endif
  112663. /* this algorithm is hardwired to floor 1 for now; abort out if
  112664. we're *not* floor1. This won't happen unless someone has
  112665. broken the encode setup lib. Guard it anyway. */
  112666. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  112667. floor_posts[i][PACKETBLOBS/2]=
  112668. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  112669. logmdct,
  112670. logmask);
  112671. /* are we managing bitrate? If so, perform two more fits for
  112672. later rate tweaking (fits represent hi/lo) */
  112673. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  112674. /* higher rate by way of lower noise curve */
  112675. _vp_offset_and_mix(psy_look,
  112676. noise,
  112677. tone,
  112678. 2,
  112679. logmask,
  112680. mdct,
  112681. logmdct);
  112682. #if 0
  112683. if(vi->channels==2){
  112684. if(i==0)
  112685. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  112686. else
  112687. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  112688. }
  112689. #endif
  112690. floor_posts[i][PACKETBLOBS-1]=
  112691. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  112692. logmdct,
  112693. logmask);
  112694. /* lower rate by way of higher noise curve */
  112695. _vp_offset_and_mix(psy_look,
  112696. noise,
  112697. tone,
  112698. 0,
  112699. logmask,
  112700. mdct,
  112701. logmdct);
  112702. #if 0
  112703. if(vi->channels==2)
  112704. if(i==0)
  112705. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  112706. else
  112707. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  112708. #endif
  112709. floor_posts[i][0]=
  112710. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  112711. logmdct,
  112712. logmask);
  112713. /* we also interpolate a range of intermediate curves for
  112714. intermediate rates */
  112715. for(k=1;k<PACKETBLOBS/2;k++)
  112716. floor_posts[i][k]=
  112717. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  112718. floor_posts[i][0],
  112719. floor_posts[i][PACKETBLOBS/2],
  112720. k*65536/(PACKETBLOBS/2));
  112721. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  112722. floor_posts[i][k]=
  112723. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  112724. floor_posts[i][PACKETBLOBS/2],
  112725. floor_posts[i][PACKETBLOBS-1],
  112726. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  112727. }
  112728. }
  112729. }
  112730. vbi->ampmax=global_ampmax;
  112731. /*
  112732. the next phases are performed once for vbr-only and PACKETBLOB
  112733. times for bitrate managed modes.
  112734. 1) encode actual mode being used
  112735. 2) encode the floor for each channel, compute coded mask curve/res
  112736. 3) normalize and couple.
  112737. 4) encode residue
  112738. 5) save packet bytes to the packetblob vector
  112739. */
  112740. /* iterate over the many masking curve fits we've created */
  112741. {
  112742. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  112743. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  112744. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  112745. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  112746. float **mag_memo;
  112747. int **mag_sort;
  112748. if(info->coupling_steps){
  112749. mag_memo=_vp_quantize_couple_memo(vb,
  112750. &ci->psy_g_param,
  112751. psy_look,
  112752. info,
  112753. gmdct);
  112754. mag_sort=_vp_quantize_couple_sort(vb,
  112755. psy_look,
  112756. info,
  112757. mag_memo);
  112758. hf_reduction(&ci->psy_g_param,
  112759. psy_look,
  112760. info,
  112761. mag_memo);
  112762. }
  112763. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  112764. if(psy_look->vi->normal_channel_p){
  112765. for(i=0;i<vi->channels;i++){
  112766. float *mdct =gmdct[i];
  112767. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  112768. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  112769. }
  112770. }
  112771. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  112772. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  112773. k++){
  112774. oggpack_buffer *opb=vbi->packetblob[k];
  112775. /* start out our new packet blob with packet type and mode */
  112776. /* Encode the packet type */
  112777. oggpack_write(opb,0,1);
  112778. /* Encode the modenumber */
  112779. /* Encode frame mode, pre,post windowsize, then dispatch */
  112780. oggpack_write(opb,modenumber,b->modebits);
  112781. if(vb->W){
  112782. oggpack_write(opb,vb->lW,1);
  112783. oggpack_write(opb,vb->nW,1);
  112784. }
  112785. /* encode floor, compute masking curve, sep out residue */
  112786. for(i=0;i<vi->channels;i++){
  112787. int submap=info->chmuxlist[i];
  112788. float *mdct =gmdct[i];
  112789. float *res =vb->pcm[i];
  112790. int *ilogmask=ilogmaskch[i]=
  112791. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  112792. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  112793. floor_posts[i][k],
  112794. ilogmask);
  112795. #if 0
  112796. {
  112797. char buf[80];
  112798. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  112799. float work[n/2];
  112800. for(j=0;j<n/2;j++)
  112801. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  112802. _analysis_output(buf,seq,work,n/2,1,1,0);
  112803. }
  112804. #endif
  112805. _vp_remove_floor(psy_look,
  112806. mdct,
  112807. ilogmask,
  112808. res,
  112809. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  112810. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  112811. #if 0
  112812. {
  112813. char buf[80];
  112814. float work[n/2];
  112815. for(j=0;j<n/2;j++)
  112816. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  112817. sprintf(buf,"resI%c%d",i?'R':'L',k);
  112818. _analysis_output(buf,seq,work,n/2,1,1,0);
  112819. }
  112820. #endif
  112821. }
  112822. /* our iteration is now based on masking curve, not prequant and
  112823. coupling. Only one prequant/coupling step */
  112824. /* quantize/couple */
  112825. /* incomplete implementation that assumes the tree is all depth
  112826. one, or no tree at all */
  112827. if(info->coupling_steps){
  112828. _vp_couple(k,
  112829. &ci->psy_g_param,
  112830. psy_look,
  112831. info,
  112832. vb->pcm,
  112833. mag_memo,
  112834. mag_sort,
  112835. ilogmaskch,
  112836. nonzero,
  112837. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  112838. }
  112839. /* classify and encode by submap */
  112840. for(i=0;i<info->submaps;i++){
  112841. int ch_in_bundle=0;
  112842. long **classifications;
  112843. int resnum=info->residuesubmap[i];
  112844. for(j=0;j<vi->channels;j++){
  112845. if(info->chmuxlist[j]==i){
  112846. zerobundle[ch_in_bundle]=0;
  112847. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  112848. res_bundle[ch_in_bundle]=vb->pcm[j];
  112849. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  112850. }
  112851. }
  112852. classifications=_residue_P[ci->residue_type[resnum]]->
  112853. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  112854. _residue_P[ci->residue_type[resnum]]->
  112855. forward(opb,vb,b->residue[resnum],
  112856. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  112857. }
  112858. /* ok, done encoding. Next protopacket. */
  112859. }
  112860. }
  112861. #if 0
  112862. seq++;
  112863. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  112864. #endif
  112865. return(0);
  112866. }
  112867. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  112868. vorbis_dsp_state *vd=vb->vd;
  112869. vorbis_info *vi=vd->vi;
  112870. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  112871. private_state *b=(private_state*)vd->backend_state;
  112872. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  112873. int i,j;
  112874. long n=vb->pcmend=ci->blocksizes[vb->W];
  112875. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  112876. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  112877. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  112878. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  112879. /* recover the spectral envelope; store it in the PCM vector for now */
  112880. for(i=0;i<vi->channels;i++){
  112881. int submap=info->chmuxlist[i];
  112882. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  112883. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  112884. if(floormemo[i])
  112885. nonzero[i]=1;
  112886. else
  112887. nonzero[i]=0;
  112888. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  112889. }
  112890. /* channel coupling can 'dirty' the nonzero listing */
  112891. for(i=0;i<info->coupling_steps;i++){
  112892. if(nonzero[info->coupling_mag[i]] ||
  112893. nonzero[info->coupling_ang[i]]){
  112894. nonzero[info->coupling_mag[i]]=1;
  112895. nonzero[info->coupling_ang[i]]=1;
  112896. }
  112897. }
  112898. /* recover the residue into our working vectors */
  112899. for(i=0;i<info->submaps;i++){
  112900. int ch_in_bundle=0;
  112901. for(j=0;j<vi->channels;j++){
  112902. if(info->chmuxlist[j]==i){
  112903. if(nonzero[j])
  112904. zerobundle[ch_in_bundle]=1;
  112905. else
  112906. zerobundle[ch_in_bundle]=0;
  112907. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  112908. }
  112909. }
  112910. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  112911. inverse(vb,b->residue[info->residuesubmap[i]],
  112912. pcmbundle,zerobundle,ch_in_bundle);
  112913. }
  112914. /* channel coupling */
  112915. for(i=info->coupling_steps-1;i>=0;i--){
  112916. float *pcmM=vb->pcm[info->coupling_mag[i]];
  112917. float *pcmA=vb->pcm[info->coupling_ang[i]];
  112918. for(j=0;j<n/2;j++){
  112919. float mag=pcmM[j];
  112920. float ang=pcmA[j];
  112921. if(mag>0)
  112922. if(ang>0){
  112923. pcmM[j]=mag;
  112924. pcmA[j]=mag-ang;
  112925. }else{
  112926. pcmA[j]=mag;
  112927. pcmM[j]=mag+ang;
  112928. }
  112929. else
  112930. if(ang>0){
  112931. pcmM[j]=mag;
  112932. pcmA[j]=mag+ang;
  112933. }else{
  112934. pcmA[j]=mag;
  112935. pcmM[j]=mag-ang;
  112936. }
  112937. }
  112938. }
  112939. /* compute and apply spectral envelope */
  112940. for(i=0;i<vi->channels;i++){
  112941. float *pcm=vb->pcm[i];
  112942. int submap=info->chmuxlist[i];
  112943. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  112944. inverse2(vb,b->flr[info->floorsubmap[submap]],
  112945. floormemo[i],pcm);
  112946. }
  112947. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  112948. /* only MDCT right now.... */
  112949. for(i=0;i<vi->channels;i++){
  112950. float *pcm=vb->pcm[i];
  112951. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  112952. }
  112953. /* all done! */
  112954. return(0);
  112955. }
  112956. /* export hooks */
  112957. vorbis_func_mapping mapping0_exportbundle={
  112958. &mapping0_pack,
  112959. &mapping0_unpack,
  112960. &mapping0_free_info,
  112961. &mapping0_forward,
  112962. &mapping0_inverse
  112963. };
  112964. #endif
  112965. /*** End of inlined file: mapping0.c ***/
  112966. /*** Start of inlined file: mdct.c ***/
  112967. /* this can also be run as an integer transform by uncommenting a
  112968. define in mdct.h; the integerization is a first pass and although
  112969. it's likely stable for Vorbis, the dynamic range is constrained and
  112970. roundoff isn't done (so it's noisy). Consider it functional, but
  112971. only a starting point. There's no point on a machine with an FPU */
  112972. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112973. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112974. // tasks..
  112975. #if JUCE_MSVC
  112976. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112977. #endif
  112978. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112979. #if JUCE_USE_OGGVORBIS
  112980. #include <stdio.h>
  112981. #include <stdlib.h>
  112982. #include <string.h>
  112983. #include <math.h>
  112984. /* build lookups for trig functions; also pre-figure scaling and
  112985. some window function algebra. */
  112986. void mdct_init(mdct_lookup *lookup,int n){
  112987. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  112988. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  112989. int i;
  112990. int n2=n>>1;
  112991. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  112992. lookup->n=n;
  112993. lookup->trig=T;
  112994. lookup->bitrev=bitrev;
  112995. /* trig lookups... */
  112996. for(i=0;i<n/4;i++){
  112997. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  112998. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  112999. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  113000. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  113001. }
  113002. for(i=0;i<n/8;i++){
  113003. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  113004. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  113005. }
  113006. /* bitreverse lookup... */
  113007. {
  113008. int mask=(1<<(log2n-1))-1,i,j;
  113009. int msb=1<<(log2n-2);
  113010. for(i=0;i<n/8;i++){
  113011. int acc=0;
  113012. for(j=0;msb>>j;j++)
  113013. if((msb>>j)&i)acc|=1<<j;
  113014. bitrev[i*2]=((~acc)&mask)-1;
  113015. bitrev[i*2+1]=acc;
  113016. }
  113017. }
  113018. lookup->scale=FLOAT_CONV(4.f/n);
  113019. }
  113020. /* 8 point butterfly (in place, 4 register) */
  113021. STIN void mdct_butterfly_8(DATA_TYPE *x){
  113022. REG_TYPE r0 = x[6] + x[2];
  113023. REG_TYPE r1 = x[6] - x[2];
  113024. REG_TYPE r2 = x[4] + x[0];
  113025. REG_TYPE r3 = x[4] - x[0];
  113026. x[6] = r0 + r2;
  113027. x[4] = r0 - r2;
  113028. r0 = x[5] - x[1];
  113029. r2 = x[7] - x[3];
  113030. x[0] = r1 + r0;
  113031. x[2] = r1 - r0;
  113032. r0 = x[5] + x[1];
  113033. r1 = x[7] + x[3];
  113034. x[3] = r2 + r3;
  113035. x[1] = r2 - r3;
  113036. x[7] = r1 + r0;
  113037. x[5] = r1 - r0;
  113038. }
  113039. /* 16 point butterfly (in place, 4 register) */
  113040. STIN void mdct_butterfly_16(DATA_TYPE *x){
  113041. REG_TYPE r0 = x[1] - x[9];
  113042. REG_TYPE r1 = x[0] - x[8];
  113043. x[8] += x[0];
  113044. x[9] += x[1];
  113045. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  113046. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  113047. r0 = x[3] - x[11];
  113048. r1 = x[10] - x[2];
  113049. x[10] += x[2];
  113050. x[11] += x[3];
  113051. x[2] = r0;
  113052. x[3] = r1;
  113053. r0 = x[12] - x[4];
  113054. r1 = x[13] - x[5];
  113055. x[12] += x[4];
  113056. x[13] += x[5];
  113057. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  113058. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  113059. r0 = x[14] - x[6];
  113060. r1 = x[15] - x[7];
  113061. x[14] += x[6];
  113062. x[15] += x[7];
  113063. x[6] = r0;
  113064. x[7] = r1;
  113065. mdct_butterfly_8(x);
  113066. mdct_butterfly_8(x+8);
  113067. }
  113068. /* 32 point butterfly (in place, 4 register) */
  113069. STIN void mdct_butterfly_32(DATA_TYPE *x){
  113070. REG_TYPE r0 = x[30] - x[14];
  113071. REG_TYPE r1 = x[31] - x[15];
  113072. x[30] += x[14];
  113073. x[31] += x[15];
  113074. x[14] = r0;
  113075. x[15] = r1;
  113076. r0 = x[28] - x[12];
  113077. r1 = x[29] - x[13];
  113078. x[28] += x[12];
  113079. x[29] += x[13];
  113080. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  113081. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  113082. r0 = x[26] - x[10];
  113083. r1 = x[27] - x[11];
  113084. x[26] += x[10];
  113085. x[27] += x[11];
  113086. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  113087. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  113088. r0 = x[24] - x[8];
  113089. r1 = x[25] - x[9];
  113090. x[24] += x[8];
  113091. x[25] += x[9];
  113092. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  113093. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  113094. r0 = x[22] - x[6];
  113095. r1 = x[7] - x[23];
  113096. x[22] += x[6];
  113097. x[23] += x[7];
  113098. x[6] = r1;
  113099. x[7] = r0;
  113100. r0 = x[4] - x[20];
  113101. r1 = x[5] - x[21];
  113102. x[20] += x[4];
  113103. x[21] += x[5];
  113104. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  113105. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  113106. r0 = x[2] - x[18];
  113107. r1 = x[3] - x[19];
  113108. x[18] += x[2];
  113109. x[19] += x[3];
  113110. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  113111. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  113112. r0 = x[0] - x[16];
  113113. r1 = x[1] - x[17];
  113114. x[16] += x[0];
  113115. x[17] += x[1];
  113116. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  113117. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  113118. mdct_butterfly_16(x);
  113119. mdct_butterfly_16(x+16);
  113120. }
  113121. /* N point first stage butterfly (in place, 2 register) */
  113122. STIN void mdct_butterfly_first(DATA_TYPE *T,
  113123. DATA_TYPE *x,
  113124. int points){
  113125. DATA_TYPE *x1 = x + points - 8;
  113126. DATA_TYPE *x2 = x + (points>>1) - 8;
  113127. REG_TYPE r0;
  113128. REG_TYPE r1;
  113129. do{
  113130. r0 = x1[6] - x2[6];
  113131. r1 = x1[7] - x2[7];
  113132. x1[6] += x2[6];
  113133. x1[7] += x2[7];
  113134. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  113135. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  113136. r0 = x1[4] - x2[4];
  113137. r1 = x1[5] - x2[5];
  113138. x1[4] += x2[4];
  113139. x1[5] += x2[5];
  113140. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  113141. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  113142. r0 = x1[2] - x2[2];
  113143. r1 = x1[3] - x2[3];
  113144. x1[2] += x2[2];
  113145. x1[3] += x2[3];
  113146. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  113147. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  113148. r0 = x1[0] - x2[0];
  113149. r1 = x1[1] - x2[1];
  113150. x1[0] += x2[0];
  113151. x1[1] += x2[1];
  113152. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  113153. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  113154. x1-=8;
  113155. x2-=8;
  113156. T+=16;
  113157. }while(x2>=x);
  113158. }
  113159. /* N/stage point generic N stage butterfly (in place, 2 register) */
  113160. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  113161. DATA_TYPE *x,
  113162. int points,
  113163. int trigint){
  113164. DATA_TYPE *x1 = x + points - 8;
  113165. DATA_TYPE *x2 = x + (points>>1) - 8;
  113166. REG_TYPE r0;
  113167. REG_TYPE r1;
  113168. do{
  113169. r0 = x1[6] - x2[6];
  113170. r1 = x1[7] - x2[7];
  113171. x1[6] += x2[6];
  113172. x1[7] += x2[7];
  113173. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  113174. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  113175. T+=trigint;
  113176. r0 = x1[4] - x2[4];
  113177. r1 = x1[5] - x2[5];
  113178. x1[4] += x2[4];
  113179. x1[5] += x2[5];
  113180. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  113181. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  113182. T+=trigint;
  113183. r0 = x1[2] - x2[2];
  113184. r1 = x1[3] - x2[3];
  113185. x1[2] += x2[2];
  113186. x1[3] += x2[3];
  113187. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  113188. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  113189. T+=trigint;
  113190. r0 = x1[0] - x2[0];
  113191. r1 = x1[1] - x2[1];
  113192. x1[0] += x2[0];
  113193. x1[1] += x2[1];
  113194. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  113195. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  113196. T+=trigint;
  113197. x1-=8;
  113198. x2-=8;
  113199. }while(x2>=x);
  113200. }
  113201. STIN void mdct_butterflies(mdct_lookup *init,
  113202. DATA_TYPE *x,
  113203. int points){
  113204. DATA_TYPE *T=init->trig;
  113205. int stages=init->log2n-5;
  113206. int i,j;
  113207. if(--stages>0){
  113208. mdct_butterfly_first(T,x,points);
  113209. }
  113210. for(i=1;--stages>0;i++){
  113211. for(j=0;j<(1<<i);j++)
  113212. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  113213. }
  113214. for(j=0;j<points;j+=32)
  113215. mdct_butterfly_32(x+j);
  113216. }
  113217. void mdct_clear(mdct_lookup *l){
  113218. if(l){
  113219. if(l->trig)_ogg_free(l->trig);
  113220. if(l->bitrev)_ogg_free(l->bitrev);
  113221. memset(l,0,sizeof(*l));
  113222. }
  113223. }
  113224. STIN void mdct_bitreverse(mdct_lookup *init,
  113225. DATA_TYPE *x){
  113226. int n = init->n;
  113227. int *bit = init->bitrev;
  113228. DATA_TYPE *w0 = x;
  113229. DATA_TYPE *w1 = x = w0+(n>>1);
  113230. DATA_TYPE *T = init->trig+n;
  113231. do{
  113232. DATA_TYPE *x0 = x+bit[0];
  113233. DATA_TYPE *x1 = x+bit[1];
  113234. REG_TYPE r0 = x0[1] - x1[1];
  113235. REG_TYPE r1 = x0[0] + x1[0];
  113236. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  113237. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  113238. w1 -= 4;
  113239. r0 = HALVE(x0[1] + x1[1]);
  113240. r1 = HALVE(x0[0] - x1[0]);
  113241. w0[0] = r0 + r2;
  113242. w1[2] = r0 - r2;
  113243. w0[1] = r1 + r3;
  113244. w1[3] = r3 - r1;
  113245. x0 = x+bit[2];
  113246. x1 = x+bit[3];
  113247. r0 = x0[1] - x1[1];
  113248. r1 = x0[0] + x1[0];
  113249. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  113250. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  113251. r0 = HALVE(x0[1] + x1[1]);
  113252. r1 = HALVE(x0[0] - x1[0]);
  113253. w0[2] = r0 + r2;
  113254. w1[0] = r0 - r2;
  113255. w0[3] = r1 + r3;
  113256. w1[1] = r3 - r1;
  113257. T += 4;
  113258. bit += 4;
  113259. w0 += 4;
  113260. }while(w0<w1);
  113261. }
  113262. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  113263. int n=init->n;
  113264. int n2=n>>1;
  113265. int n4=n>>2;
  113266. /* rotate */
  113267. DATA_TYPE *iX = in+n2-7;
  113268. DATA_TYPE *oX = out+n2+n4;
  113269. DATA_TYPE *T = init->trig+n4;
  113270. do{
  113271. oX -= 4;
  113272. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  113273. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  113274. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  113275. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  113276. iX -= 8;
  113277. T += 4;
  113278. }while(iX>=in);
  113279. iX = in+n2-8;
  113280. oX = out+n2+n4;
  113281. T = init->trig+n4;
  113282. do{
  113283. T -= 4;
  113284. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  113285. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  113286. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  113287. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  113288. iX -= 8;
  113289. oX += 4;
  113290. }while(iX>=in);
  113291. mdct_butterflies(init,out+n2,n2);
  113292. mdct_bitreverse(init,out);
  113293. /* roatate + window */
  113294. {
  113295. DATA_TYPE *oX1=out+n2+n4;
  113296. DATA_TYPE *oX2=out+n2+n4;
  113297. DATA_TYPE *iX =out;
  113298. T =init->trig+n2;
  113299. do{
  113300. oX1-=4;
  113301. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  113302. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  113303. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  113304. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  113305. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  113306. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  113307. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  113308. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  113309. oX2+=4;
  113310. iX += 8;
  113311. T += 8;
  113312. }while(iX<oX1);
  113313. iX=out+n2+n4;
  113314. oX1=out+n4;
  113315. oX2=oX1;
  113316. do{
  113317. oX1-=4;
  113318. iX-=4;
  113319. oX2[0] = -(oX1[3] = iX[3]);
  113320. oX2[1] = -(oX1[2] = iX[2]);
  113321. oX2[2] = -(oX1[1] = iX[1]);
  113322. oX2[3] = -(oX1[0] = iX[0]);
  113323. oX2+=4;
  113324. }while(oX2<iX);
  113325. iX=out+n2+n4;
  113326. oX1=out+n2+n4;
  113327. oX2=out+n2;
  113328. do{
  113329. oX1-=4;
  113330. oX1[0]= iX[3];
  113331. oX1[1]= iX[2];
  113332. oX1[2]= iX[1];
  113333. oX1[3]= iX[0];
  113334. iX+=4;
  113335. }while(oX1>oX2);
  113336. }
  113337. }
  113338. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  113339. int n=init->n;
  113340. int n2=n>>1;
  113341. int n4=n>>2;
  113342. int n8=n>>3;
  113343. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  113344. DATA_TYPE *w2=w+n2;
  113345. /* rotate */
  113346. /* window + rotate + step 1 */
  113347. REG_TYPE r0;
  113348. REG_TYPE r1;
  113349. DATA_TYPE *x0=in+n2+n4;
  113350. DATA_TYPE *x1=x0+1;
  113351. DATA_TYPE *T=init->trig+n2;
  113352. int i=0;
  113353. for(i=0;i<n8;i+=2){
  113354. x0 -=4;
  113355. T-=2;
  113356. r0= x0[2] + x1[0];
  113357. r1= x0[0] + x1[2];
  113358. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  113359. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  113360. x1 +=4;
  113361. }
  113362. x1=in+1;
  113363. for(;i<n2-n8;i+=2){
  113364. T-=2;
  113365. x0 -=4;
  113366. r0= x0[2] - x1[0];
  113367. r1= x0[0] - x1[2];
  113368. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  113369. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  113370. x1 +=4;
  113371. }
  113372. x0=in+n;
  113373. for(;i<n2;i+=2){
  113374. T-=2;
  113375. x0 -=4;
  113376. r0= -x0[2] - x1[0];
  113377. r1= -x0[0] - x1[2];
  113378. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  113379. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  113380. x1 +=4;
  113381. }
  113382. mdct_butterflies(init,w+n2,n2);
  113383. mdct_bitreverse(init,w);
  113384. /* roatate + window */
  113385. T=init->trig+n2;
  113386. x0=out+n2;
  113387. for(i=0;i<n4;i++){
  113388. x0--;
  113389. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  113390. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  113391. w+=2;
  113392. T+=2;
  113393. }
  113394. }
  113395. #endif
  113396. /*** End of inlined file: mdct.c ***/
  113397. /*** Start of inlined file: psy.c ***/
  113398. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113399. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113400. // tasks..
  113401. #if JUCE_MSVC
  113402. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113403. #endif
  113404. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113405. #if JUCE_USE_OGGVORBIS
  113406. #include <stdlib.h>
  113407. #include <math.h>
  113408. #include <string.h>
  113409. /*** Start of inlined file: masking.h ***/
  113410. #ifndef _V_MASKING_H_
  113411. #define _V_MASKING_H_
  113412. /* more detailed ATH; the bass if flat to save stressing the floor
  113413. overly for only a bin or two of savings. */
  113414. #define MAX_ATH 88
  113415. static float ATH[]={
  113416. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  113417. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  113418. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  113419. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  113420. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  113421. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  113422. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  113423. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  113424. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  113425. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  113426. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  113427. };
  113428. /* The tone masking curves from Ehmer's and Fielder's papers have been
  113429. replaced by an empirically collected data set. The previously
  113430. published values were, far too often, simply on crack. */
  113431. #define EHMER_OFFSET 16
  113432. #define EHMER_MAX 56
  113433. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  113434. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  113435. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  113436. for collection of these curves) */
  113437. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  113438. /* 62.5 Hz */
  113439. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  113440. -60, -60, -60, -60, -62, -62, -65, -73,
  113441. -69, -68, -68, -67, -70, -70, -72, -74,
  113442. -75, -79, -79, -80, -83, -88, -93, -100,
  113443. -110, -999, -999, -999, -999, -999, -999, -999,
  113444. -999, -999, -999, -999, -999, -999, -999, -999,
  113445. -999, -999, -999, -999, -999, -999, -999, -999},
  113446. { -48, -48, -48, -48, -48, -48, -48, -48,
  113447. -48, -48, -48, -48, -48, -53, -61, -66,
  113448. -66, -68, -67, -70, -76, -76, -72, -73,
  113449. -75, -76, -78, -79, -83, -88, -93, -100,
  113450. -110, -999, -999, -999, -999, -999, -999, -999,
  113451. -999, -999, -999, -999, -999, -999, -999, -999,
  113452. -999, -999, -999, -999, -999, -999, -999, -999},
  113453. { -37, -37, -37, -37, -37, -37, -37, -37,
  113454. -38, -40, -42, -46, -48, -53, -55, -62,
  113455. -65, -58, -56, -56, -61, -60, -65, -67,
  113456. -69, -71, -77, -77, -78, -80, -82, -84,
  113457. -88, -93, -98, -106, -112, -999, -999, -999,
  113458. -999, -999, -999, -999, -999, -999, -999, -999,
  113459. -999, -999, -999, -999, -999, -999, -999, -999},
  113460. { -25, -25, -25, -25, -25, -25, -25, -25,
  113461. -25, -26, -27, -29, -32, -38, -48, -52,
  113462. -52, -50, -48, -48, -51, -52, -54, -60,
  113463. -67, -67, -66, -68, -69, -73, -73, -76,
  113464. -80, -81, -81, -85, -85, -86, -88, -93,
  113465. -100, -110, -999, -999, -999, -999, -999, -999,
  113466. -999, -999, -999, -999, -999, -999, -999, -999},
  113467. { -16, -16, -16, -16, -16, -16, -16, -16,
  113468. -17, -19, -20, -22, -26, -28, -31, -40,
  113469. -47, -39, -39, -40, -42, -43, -47, -51,
  113470. -57, -52, -55, -55, -60, -58, -62, -63,
  113471. -70, -67, -69, -72, -73, -77, -80, -82,
  113472. -83, -87, -90, -94, -98, -104, -115, -999,
  113473. -999, -999, -999, -999, -999, -999, -999, -999},
  113474. { -8, -8, -8, -8, -8, -8, -8, -8,
  113475. -8, -8, -10, -11, -15, -19, -25, -30,
  113476. -34, -31, -30, -31, -29, -32, -35, -42,
  113477. -48, -42, -44, -46, -50, -50, -51, -52,
  113478. -59, -54, -55, -55, -58, -62, -63, -66,
  113479. -72, -73, -76, -75, -78, -80, -80, -81,
  113480. -84, -88, -90, -94, -98, -101, -106, -110}},
  113481. /* 88Hz */
  113482. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  113483. -66, -66, -66, -66, -66, -67, -67, -67,
  113484. -76, -72, -71, -74, -76, -76, -75, -78,
  113485. -79, -79, -81, -83, -86, -89, -93, -97,
  113486. -100, -105, -110, -999, -999, -999, -999, -999,
  113487. -999, -999, -999, -999, -999, -999, -999, -999,
  113488. -999, -999, -999, -999, -999, -999, -999, -999},
  113489. { -47, -47, -47, -47, -47, -47, -47, -47,
  113490. -47, -47, -47, -48, -51, -55, -59, -66,
  113491. -66, -66, -67, -66, -68, -69, -70, -74,
  113492. -79, -77, -77, -78, -80, -81, -82, -84,
  113493. -86, -88, -91, -95, -100, -108, -116, -999,
  113494. -999, -999, -999, -999, -999, -999, -999, -999,
  113495. -999, -999, -999, -999, -999, -999, -999, -999},
  113496. { -36, -36, -36, -36, -36, -36, -36, -36,
  113497. -36, -37, -37, -41, -44, -48, -51, -58,
  113498. -62, -60, -57, -59, -59, -60, -63, -65,
  113499. -72, -71, -70, -72, -74, -77, -76, -78,
  113500. -81, -81, -80, -83, -86, -91, -96, -100,
  113501. -105, -110, -999, -999, -999, -999, -999, -999,
  113502. -999, -999, -999, -999, -999, -999, -999, -999},
  113503. { -28, -28, -28, -28, -28, -28, -28, -28,
  113504. -28, -30, -32, -32, -33, -35, -41, -49,
  113505. -50, -49, -47, -48, -48, -52, -51, -57,
  113506. -65, -61, -59, -61, -64, -69, -70, -74,
  113507. -77, -77, -78, -81, -84, -85, -87, -90,
  113508. -92, -96, -100, -107, -112, -999, -999, -999,
  113509. -999, -999, -999, -999, -999, -999, -999, -999},
  113510. { -19, -19, -19, -19, -19, -19, -19, -19,
  113511. -20, -21, -23, -27, -30, -35, -36, -41,
  113512. -46, -44, -42, -40, -41, -41, -43, -48,
  113513. -55, -53, -52, -53, -56, -59, -58, -60,
  113514. -67, -66, -69, -71, -72, -75, -79, -81,
  113515. -84, -87, -90, -93, -97, -101, -107, -114,
  113516. -999, -999, -999, -999, -999, -999, -999, -999},
  113517. { -9, -9, -9, -9, -9, -9, -9, -9,
  113518. -11, -12, -12, -15, -16, -20, -23, -30,
  113519. -37, -34, -33, -34, -31, -32, -32, -38,
  113520. -47, -44, -41, -40, -47, -49, -46, -46,
  113521. -58, -50, -50, -54, -58, -62, -64, -67,
  113522. -67, -70, -72, -76, -79, -83, -87, -91,
  113523. -96, -100, -104, -110, -999, -999, -999, -999}},
  113524. /* 125 Hz */
  113525. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  113526. -62, -62, -63, -64, -66, -67, -66, -68,
  113527. -75, -72, -76, -75, -76, -78, -79, -82,
  113528. -84, -85, -90, -94, -101, -110, -999, -999,
  113529. -999, -999, -999, -999, -999, -999, -999, -999,
  113530. -999, -999, -999, -999, -999, -999, -999, -999,
  113531. -999, -999, -999, -999, -999, -999, -999, -999},
  113532. { -59, -59, -59, -59, -59, -59, -59, -59,
  113533. -59, -59, -59, -60, -60, -61, -63, -66,
  113534. -71, -68, -70, -70, -71, -72, -72, -75,
  113535. -81, -78, -79, -82, -83, -86, -90, -97,
  113536. -103, -113, -999, -999, -999, -999, -999, -999,
  113537. -999, -999, -999, -999, -999, -999, -999, -999,
  113538. -999, -999, -999, -999, -999, -999, -999, -999},
  113539. { -53, -53, -53, -53, -53, -53, -53, -53,
  113540. -53, -54, -55, -57, -56, -57, -55, -61,
  113541. -65, -60, -60, -62, -63, -63, -66, -68,
  113542. -74, -73, -75, -75, -78, -80, -80, -82,
  113543. -85, -90, -96, -101, -108, -999, -999, -999,
  113544. -999, -999, -999, -999, -999, -999, -999, -999,
  113545. -999, -999, -999, -999, -999, -999, -999, -999},
  113546. { -46, -46, -46, -46, -46, -46, -46, -46,
  113547. -46, -46, -47, -47, -47, -47, -48, -51,
  113548. -57, -51, -49, -50, -51, -53, -54, -59,
  113549. -66, -60, -62, -67, -67, -70, -72, -75,
  113550. -76, -78, -81, -85, -88, -94, -97, -104,
  113551. -112, -999, -999, -999, -999, -999, -999, -999,
  113552. -999, -999, -999, -999, -999, -999, -999, -999},
  113553. { -36, -36, -36, -36, -36, -36, -36, -36,
  113554. -39, -41, -42, -42, -39, -38, -41, -43,
  113555. -52, -44, -40, -39, -37, -37, -40, -47,
  113556. -54, -50, -48, -50, -55, -61, -59, -62,
  113557. -66, -66, -66, -69, -69, -73, -74, -74,
  113558. -75, -77, -79, -82, -87, -91, -95, -100,
  113559. -108, -115, -999, -999, -999, -999, -999, -999},
  113560. { -28, -26, -24, -22, -20, -20, -23, -29,
  113561. -30, -31, -28, -27, -28, -28, -28, -35,
  113562. -40, -33, -32, -29, -30, -30, -30, -37,
  113563. -45, -41, -37, -38, -45, -47, -47, -48,
  113564. -53, -49, -48, -50, -49, -49, -51, -52,
  113565. -58, -56, -57, -56, -60, -61, -62, -70,
  113566. -72, -74, -78, -83, -88, -93, -100, -106}},
  113567. /* 177 Hz */
  113568. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113569. -999, -110, -105, -100, -95, -91, -87, -83,
  113570. -80, -78, -76, -78, -78, -81, -83, -85,
  113571. -86, -85, -86, -87, -90, -97, -107, -999,
  113572. -999, -999, -999, -999, -999, -999, -999, -999,
  113573. -999, -999, -999, -999, -999, -999, -999, -999,
  113574. -999, -999, -999, -999, -999, -999, -999, -999},
  113575. {-999, -999, -999, -110, -105, -100, -95, -90,
  113576. -85, -81, -77, -73, -70, -67, -67, -68,
  113577. -75, -73, -70, -69, -70, -72, -75, -79,
  113578. -84, -83, -84, -86, -88, -89, -89, -93,
  113579. -98, -105, -112, -999, -999, -999, -999, -999,
  113580. -999, -999, -999, -999, -999, -999, -999, -999,
  113581. -999, -999, -999, -999, -999, -999, -999, -999},
  113582. {-105, -100, -95, -90, -85, -80, -76, -71,
  113583. -68, -68, -65, -63, -63, -62, -62, -64,
  113584. -65, -64, -61, -62, -63, -64, -66, -68,
  113585. -73, -73, -74, -75, -76, -81, -83, -85,
  113586. -88, -89, -92, -95, -100, -108, -999, -999,
  113587. -999, -999, -999, -999, -999, -999, -999, -999,
  113588. -999, -999, -999, -999, -999, -999, -999, -999},
  113589. { -80, -75, -71, -68, -65, -63, -62, -61,
  113590. -61, -61, -61, -59, -56, -57, -53, -50,
  113591. -58, -52, -50, -50, -52, -53, -54, -58,
  113592. -67, -63, -67, -68, -72, -75, -78, -80,
  113593. -81, -81, -82, -85, -89, -90, -93, -97,
  113594. -101, -107, -114, -999, -999, -999, -999, -999,
  113595. -999, -999, -999, -999, -999, -999, -999, -999},
  113596. { -65, -61, -59, -57, -56, -55, -55, -56,
  113597. -56, -57, -55, -53, -52, -47, -44, -44,
  113598. -50, -44, -41, -39, -39, -42, -40, -46,
  113599. -51, -49, -50, -53, -54, -63, -60, -61,
  113600. -62, -66, -66, -66, -70, -73, -74, -75,
  113601. -76, -75, -79, -85, -89, -91, -96, -102,
  113602. -110, -999, -999, -999, -999, -999, -999, -999},
  113603. { -52, -50, -49, -49, -48, -48, -48, -49,
  113604. -50, -50, -49, -46, -43, -39, -35, -33,
  113605. -38, -36, -32, -29, -32, -32, -32, -35,
  113606. -44, -39, -38, -38, -46, -50, -45, -46,
  113607. -53, -50, -50, -50, -54, -54, -53, -53,
  113608. -56, -57, -59, -66, -70, -72, -74, -79,
  113609. -83, -85, -90, -97, -114, -999, -999, -999}},
  113610. /* 250 Hz */
  113611. {{-999, -999, -999, -999, -999, -999, -110, -105,
  113612. -100, -95, -90, -86, -80, -75, -75, -79,
  113613. -80, -79, -80, -81, -82, -88, -95, -103,
  113614. -110, -999, -999, -999, -999, -999, -999, -999,
  113615. -999, -999, -999, -999, -999, -999, -999, -999,
  113616. -999, -999, -999, -999, -999, -999, -999, -999,
  113617. -999, -999, -999, -999, -999, -999, -999, -999},
  113618. {-999, -999, -999, -999, -108, -103, -98, -93,
  113619. -88, -83, -79, -78, -75, -71, -67, -68,
  113620. -73, -73, -72, -73, -75, -77, -80, -82,
  113621. -88, -93, -100, -107, -114, -999, -999, -999,
  113622. -999, -999, -999, -999, -999, -999, -999, -999,
  113623. -999, -999, -999, -999, -999, -999, -999, -999,
  113624. -999, -999, -999, -999, -999, -999, -999, -999},
  113625. {-999, -999, -999, -110, -105, -101, -96, -90,
  113626. -86, -81, -77, -73, -69, -66, -61, -62,
  113627. -66, -64, -62, -65, -66, -70, -72, -76,
  113628. -81, -80, -84, -90, -95, -102, -110, -999,
  113629. -999, -999, -999, -999, -999, -999, -999, -999,
  113630. -999, -999, -999, -999, -999, -999, -999, -999,
  113631. -999, -999, -999, -999, -999, -999, -999, -999},
  113632. {-999, -999, -999, -107, -103, -97, -92, -88,
  113633. -83, -79, -74, -70, -66, -59, -53, -58,
  113634. -62, -55, -54, -54, -54, -58, -61, -62,
  113635. -72, -70, -72, -75, -78, -80, -81, -80,
  113636. -83, -83, -88, -93, -100, -107, -115, -999,
  113637. -999, -999, -999, -999, -999, -999, -999, -999,
  113638. -999, -999, -999, -999, -999, -999, -999, -999},
  113639. {-999, -999, -999, -105, -100, -95, -90, -85,
  113640. -80, -75, -70, -66, -62, -56, -48, -44,
  113641. -48, -46, -46, -43, -46, -48, -48, -51,
  113642. -58, -58, -59, -60, -62, -62, -61, -61,
  113643. -65, -64, -65, -68, -70, -74, -75, -78,
  113644. -81, -86, -95, -110, -999, -999, -999, -999,
  113645. -999, -999, -999, -999, -999, -999, -999, -999},
  113646. {-999, -999, -105, -100, -95, -90, -85, -80,
  113647. -75, -70, -65, -61, -55, -49, -39, -33,
  113648. -40, -35, -32, -38, -40, -33, -35, -37,
  113649. -46, -41, -45, -44, -46, -42, -45, -46,
  113650. -52, -50, -50, -50, -54, -54, -55, -57,
  113651. -62, -64, -66, -68, -70, -76, -81, -90,
  113652. -100, -110, -999, -999, -999, -999, -999, -999}},
  113653. /* 354 hz */
  113654. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113655. -105, -98, -90, -85, -82, -83, -80, -78,
  113656. -84, -79, -80, -83, -87, -89, -91, -93,
  113657. -99, -106, -117, -999, -999, -999, -999, -999,
  113658. -999, -999, -999, -999, -999, -999, -999, -999,
  113659. -999, -999, -999, -999, -999, -999, -999, -999,
  113660. -999, -999, -999, -999, -999, -999, -999, -999},
  113661. {-999, -999, -999, -999, -999, -999, -999, -999,
  113662. -105, -98, -90, -85, -80, -75, -70, -68,
  113663. -74, -72, -74, -77, -80, -82, -85, -87,
  113664. -92, -89, -91, -95, -100, -106, -112, -999,
  113665. -999, -999, -999, -999, -999, -999, -999, -999,
  113666. -999, -999, -999, -999, -999, -999, -999, -999,
  113667. -999, -999, -999, -999, -999, -999, -999, -999},
  113668. {-999, -999, -999, -999, -999, -999, -999, -999,
  113669. -105, -98, -90, -83, -75, -71, -63, -64,
  113670. -67, -62, -64, -67, -70, -73, -77, -81,
  113671. -84, -83, -85, -89, -90, -93, -98, -104,
  113672. -109, -114, -999, -999, -999, -999, -999, -999,
  113673. -999, -999, -999, -999, -999, -999, -999, -999,
  113674. -999, -999, -999, -999, -999, -999, -999, -999},
  113675. {-999, -999, -999, -999, -999, -999, -999, -999,
  113676. -103, -96, -88, -81, -75, -68, -58, -54,
  113677. -56, -54, -56, -56, -58, -60, -63, -66,
  113678. -74, -69, -72, -72, -75, -74, -77, -81,
  113679. -81, -82, -84, -87, -93, -96, -99, -104,
  113680. -110, -999, -999, -999, -999, -999, -999, -999,
  113681. -999, -999, -999, -999, -999, -999, -999, -999},
  113682. {-999, -999, -999, -999, -999, -108, -102, -96,
  113683. -91, -85, -80, -74, -68, -60, -51, -46,
  113684. -48, -46, -43, -45, -47, -47, -49, -48,
  113685. -56, -53, -55, -58, -57, -63, -58, -60,
  113686. -66, -64, -67, -70, -70, -74, -77, -84,
  113687. -86, -89, -91, -93, -94, -101, -109, -118,
  113688. -999, -999, -999, -999, -999, -999, -999, -999},
  113689. {-999, -999, -999, -108, -103, -98, -93, -88,
  113690. -83, -78, -73, -68, -60, -53, -44, -35,
  113691. -38, -38, -34, -34, -36, -40, -41, -44,
  113692. -51, -45, -46, -47, -46, -54, -50, -49,
  113693. -50, -50, -50, -51, -54, -57, -58, -60,
  113694. -66, -66, -66, -64, -65, -68, -77, -82,
  113695. -87, -95, -110, -999, -999, -999, -999, -999}},
  113696. /* 500 Hz */
  113697. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113698. -107, -102, -97, -92, -87, -83, -78, -75,
  113699. -82, -79, -83, -85, -89, -92, -95, -98,
  113700. -101, -105, -109, -113, -999, -999, -999, -999,
  113701. -999, -999, -999, -999, -999, -999, -999, -999,
  113702. -999, -999, -999, -999, -999, -999, -999, -999,
  113703. -999, -999, -999, -999, -999, -999, -999, -999},
  113704. {-999, -999, -999, -999, -999, -999, -999, -106,
  113705. -100, -95, -90, -86, -81, -78, -74, -69,
  113706. -74, -74, -76, -79, -83, -84, -86, -89,
  113707. -92, -97, -93, -100, -103, -107, -110, -999,
  113708. -999, -999, -999, -999, -999, -999, -999, -999,
  113709. -999, -999, -999, -999, -999, -999, -999, -999,
  113710. -999, -999, -999, -999, -999, -999, -999, -999},
  113711. {-999, -999, -999, -999, -999, -999, -106, -100,
  113712. -95, -90, -87, -83, -80, -75, -69, -60,
  113713. -66, -66, -68, -70, -74, -78, -79, -81,
  113714. -81, -83, -84, -87, -93, -96, -99, -103,
  113715. -107, -110, -999, -999, -999, -999, -999, -999,
  113716. -999, -999, -999, -999, -999, -999, -999, -999,
  113717. -999, -999, -999, -999, -999, -999, -999, -999},
  113718. {-999, -999, -999, -999, -999, -108, -103, -98,
  113719. -93, -89, -85, -82, -78, -71, -62, -55,
  113720. -58, -58, -54, -54, -55, -59, -61, -62,
  113721. -70, -66, -66, -67, -70, -72, -75, -78,
  113722. -84, -84, -84, -88, -91, -90, -95, -98,
  113723. -102, -103, -106, -110, -999, -999, -999, -999,
  113724. -999, -999, -999, -999, -999, -999, -999, -999},
  113725. {-999, -999, -999, -999, -108, -103, -98, -94,
  113726. -90, -87, -82, -79, -73, -67, -58, -47,
  113727. -50, -45, -41, -45, -48, -44, -44, -49,
  113728. -54, -51, -48, -47, -49, -50, -51, -57,
  113729. -58, -60, -63, -69, -70, -69, -71, -74,
  113730. -78, -82, -90, -95, -101, -105, -110, -999,
  113731. -999, -999, -999, -999, -999, -999, -999, -999},
  113732. {-999, -999, -999, -105, -101, -97, -93, -90,
  113733. -85, -80, -77, -72, -65, -56, -48, -37,
  113734. -40, -36, -34, -40, -50, -47, -38, -41,
  113735. -47, -38, -35, -39, -38, -43, -40, -45,
  113736. -50, -45, -44, -47, -50, -55, -48, -48,
  113737. -52, -66, -70, -76, -82, -90, -97, -105,
  113738. -110, -999, -999, -999, -999, -999, -999, -999}},
  113739. /* 707 Hz */
  113740. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113741. -999, -108, -103, -98, -93, -86, -79, -76,
  113742. -83, -81, -85, -87, -89, -93, -98, -102,
  113743. -107, -112, -999, -999, -999, -999, -999, -999,
  113744. -999, -999, -999, -999, -999, -999, -999, -999,
  113745. -999, -999, -999, -999, -999, -999, -999, -999,
  113746. -999, -999, -999, -999, -999, -999, -999, -999},
  113747. {-999, -999, -999, -999, -999, -999, -999, -999,
  113748. -999, -108, -103, -98, -93, -86, -79, -71,
  113749. -77, -74, -77, -79, -81, -84, -85, -90,
  113750. -92, -93, -92, -98, -101, -108, -112, -999,
  113751. -999, -999, -999, -999, -999, -999, -999, -999,
  113752. -999, -999, -999, -999, -999, -999, -999, -999,
  113753. -999, -999, -999, -999, -999, -999, -999, -999},
  113754. {-999, -999, -999, -999, -999, -999, -999, -999,
  113755. -108, -103, -98, -93, -87, -78, -68, -65,
  113756. -66, -62, -65, -67, -70, -73, -75, -78,
  113757. -82, -82, -83, -84, -91, -93, -98, -102,
  113758. -106, -110, -999, -999, -999, -999, -999, -999,
  113759. -999, -999, -999, -999, -999, -999, -999, -999,
  113760. -999, -999, -999, -999, -999, -999, -999, -999},
  113761. {-999, -999, -999, -999, -999, -999, -999, -999,
  113762. -105, -100, -95, -90, -82, -74, -62, -57,
  113763. -58, -56, -51, -52, -52, -54, -54, -58,
  113764. -66, -59, -60, -63, -66, -69, -73, -79,
  113765. -83, -84, -80, -81, -81, -82, -88, -92,
  113766. -98, -105, -113, -999, -999, -999, -999, -999,
  113767. -999, -999, -999, -999, -999, -999, -999, -999},
  113768. {-999, -999, -999, -999, -999, -999, -999, -107,
  113769. -102, -97, -92, -84, -79, -69, -57, -47,
  113770. -52, -47, -44, -45, -50, -52, -42, -42,
  113771. -53, -43, -43, -48, -51, -56, -55, -52,
  113772. -57, -59, -61, -62, -67, -71, -78, -83,
  113773. -86, -94, -98, -103, -110, -999, -999, -999,
  113774. -999, -999, -999, -999, -999, -999, -999, -999},
  113775. {-999, -999, -999, -999, -999, -999, -105, -100,
  113776. -95, -90, -84, -78, -70, -61, -51, -41,
  113777. -40, -38, -40, -46, -52, -51, -41, -40,
  113778. -46, -40, -38, -38, -41, -46, -41, -46,
  113779. -47, -43, -43, -45, -41, -45, -56, -67,
  113780. -68, -83, -87, -90, -95, -102, -107, -113,
  113781. -999, -999, -999, -999, -999, -999, -999, -999}},
  113782. /* 1000 Hz */
  113783. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113784. -999, -109, -105, -101, -96, -91, -84, -77,
  113785. -82, -82, -85, -89, -94, -100, -106, -110,
  113786. -999, -999, -999, -999, -999, -999, -999, -999,
  113787. -999, -999, -999, -999, -999, -999, -999, -999,
  113788. -999, -999, -999, -999, -999, -999, -999, -999,
  113789. -999, -999, -999, -999, -999, -999, -999, -999},
  113790. {-999, -999, -999, -999, -999, -999, -999, -999,
  113791. -999, -106, -103, -98, -92, -85, -80, -71,
  113792. -75, -72, -76, -80, -84, -86, -89, -93,
  113793. -100, -107, -113, -999, -999, -999, -999, -999,
  113794. -999, -999, -999, -999, -999, -999, -999, -999,
  113795. -999, -999, -999, -999, -999, -999, -999, -999,
  113796. -999, -999, -999, -999, -999, -999, -999, -999},
  113797. {-999, -999, -999, -999, -999, -999, -999, -107,
  113798. -104, -101, -97, -92, -88, -84, -80, -64,
  113799. -66, -63, -64, -66, -69, -73, -77, -83,
  113800. -83, -86, -91, -98, -104, -111, -999, -999,
  113801. -999, -999, -999, -999, -999, -999, -999, -999,
  113802. -999, -999, -999, -999, -999, -999, -999, -999,
  113803. -999, -999, -999, -999, -999, -999, -999, -999},
  113804. {-999, -999, -999, -999, -999, -999, -999, -107,
  113805. -104, -101, -97, -92, -90, -84, -74, -57,
  113806. -58, -52, -55, -54, -50, -52, -50, -52,
  113807. -63, -62, -69, -76, -77, -78, -78, -79,
  113808. -82, -88, -94, -100, -106, -111, -999, -999,
  113809. -999, -999, -999, -999, -999, -999, -999, -999,
  113810. -999, -999, -999, -999, -999, -999, -999, -999},
  113811. {-999, -999, -999, -999, -999, -999, -106, -102,
  113812. -98, -95, -90, -85, -83, -78, -70, -50,
  113813. -50, -41, -44, -49, -47, -50, -50, -44,
  113814. -55, -46, -47, -48, -48, -54, -49, -49,
  113815. -58, -62, -71, -81, -87, -92, -97, -102,
  113816. -108, -114, -999, -999, -999, -999, -999, -999,
  113817. -999, -999, -999, -999, -999, -999, -999, -999},
  113818. {-999, -999, -999, -999, -999, -999, -106, -102,
  113819. -98, -95, -90, -85, -83, -78, -70, -45,
  113820. -43, -41, -47, -50, -51, -50, -49, -45,
  113821. -47, -41, -44, -41, -39, -43, -38, -37,
  113822. -40, -41, -44, -50, -58, -65, -73, -79,
  113823. -85, -92, -97, -101, -105, -109, -113, -999,
  113824. -999, -999, -999, -999, -999, -999, -999, -999}},
  113825. /* 1414 Hz */
  113826. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113827. -999, -999, -999, -107, -100, -95, -87, -81,
  113828. -85, -83, -88, -93, -100, -107, -114, -999,
  113829. -999, -999, -999, -999, -999, -999, -999, -999,
  113830. -999, -999, -999, -999, -999, -999, -999, -999,
  113831. -999, -999, -999, -999, -999, -999, -999, -999,
  113832. -999, -999, -999, -999, -999, -999, -999, -999},
  113833. {-999, -999, -999, -999, -999, -999, -999, -999,
  113834. -999, -999, -107, -101, -95, -88, -83, -76,
  113835. -73, -72, -79, -84, -90, -95, -100, -105,
  113836. -110, -115, -999, -999, -999, -999, -999, -999,
  113837. -999, -999, -999, -999, -999, -999, -999, -999,
  113838. -999, -999, -999, -999, -999, -999, -999, -999,
  113839. -999, -999, -999, -999, -999, -999, -999, -999},
  113840. {-999, -999, -999, -999, -999, -999, -999, -999,
  113841. -999, -999, -104, -98, -92, -87, -81, -70,
  113842. -65, -62, -67, -71, -74, -80, -85, -91,
  113843. -95, -99, -103, -108, -111, -114, -999, -999,
  113844. -999, -999, -999, -999, -999, -999, -999, -999,
  113845. -999, -999, -999, -999, -999, -999, -999, -999,
  113846. -999, -999, -999, -999, -999, -999, -999, -999},
  113847. {-999, -999, -999, -999, -999, -999, -999, -999,
  113848. -999, -999, -103, -97, -90, -85, -76, -60,
  113849. -56, -54, -60, -62, -61, -56, -63, -65,
  113850. -73, -74, -77, -75, -78, -81, -86, -87,
  113851. -88, -91, -94, -98, -103, -110, -999, -999,
  113852. -999, -999, -999, -999, -999, -999, -999, -999,
  113853. -999, -999, -999, -999, -999, -999, -999, -999},
  113854. {-999, -999, -999, -999, -999, -999, -999, -105,
  113855. -100, -97, -92, -86, -81, -79, -70, -57,
  113856. -51, -47, -51, -58, -60, -56, -53, -50,
  113857. -58, -52, -50, -50, -53, -55, -64, -69,
  113858. -71, -85, -82, -78, -81, -85, -95, -102,
  113859. -112, -999, -999, -999, -999, -999, -999, -999,
  113860. -999, -999, -999, -999, -999, -999, -999, -999},
  113861. {-999, -999, -999, -999, -999, -999, -999, -105,
  113862. -100, -97, -92, -85, -83, -79, -72, -49,
  113863. -40, -43, -43, -54, -56, -51, -50, -40,
  113864. -43, -38, -36, -35, -37, -38, -37, -44,
  113865. -54, -60, -57, -60, -70, -75, -84, -92,
  113866. -103, -112, -999, -999, -999, -999, -999, -999,
  113867. -999, -999, -999, -999, -999, -999, -999, -999}},
  113868. /* 2000 Hz */
  113869. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113870. -999, -999, -999, -110, -102, -95, -89, -82,
  113871. -83, -84, -90, -92, -99, -107, -113, -999,
  113872. -999, -999, -999, -999, -999, -999, -999, -999,
  113873. -999, -999, -999, -999, -999, -999, -999, -999,
  113874. -999, -999, -999, -999, -999, -999, -999, -999,
  113875. -999, -999, -999, -999, -999, -999, -999, -999},
  113876. {-999, -999, -999, -999, -999, -999, -999, -999,
  113877. -999, -999, -107, -101, -95, -89, -83, -72,
  113878. -74, -78, -85, -88, -88, -90, -92, -98,
  113879. -105, -111, -999, -999, -999, -999, -999, -999,
  113880. -999, -999, -999, -999, -999, -999, -999, -999,
  113881. -999, -999, -999, -999, -999, -999, -999, -999,
  113882. -999, -999, -999, -999, -999, -999, -999, -999},
  113883. {-999, -999, -999, -999, -999, -999, -999, -999,
  113884. -999, -109, -103, -97, -93, -87, -81, -70,
  113885. -70, -67, -75, -73, -76, -79, -81, -83,
  113886. -88, -89, -97, -103, -110, -999, -999, -999,
  113887. -999, -999, -999, -999, -999, -999, -999, -999,
  113888. -999, -999, -999, -999, -999, -999, -999, -999,
  113889. -999, -999, -999, -999, -999, -999, -999, -999},
  113890. {-999, -999, -999, -999, -999, -999, -999, -999,
  113891. -999, -107, -100, -94, -88, -83, -75, -63,
  113892. -59, -59, -63, -66, -60, -62, -67, -67,
  113893. -77, -76, -81, -88, -86, -92, -96, -102,
  113894. -109, -116, -999, -999, -999, -999, -999, -999,
  113895. -999, -999, -999, -999, -999, -999, -999, -999,
  113896. -999, -999, -999, -999, -999, -999, -999, -999},
  113897. {-999, -999, -999, -999, -999, -999, -999, -999,
  113898. -999, -105, -98, -92, -86, -81, -73, -56,
  113899. -52, -47, -55, -60, -58, -52, -51, -45,
  113900. -49, -50, -53, -54, -61, -71, -70, -69,
  113901. -78, -79, -87, -90, -96, -104, -112, -999,
  113902. -999, -999, -999, -999, -999, -999, -999, -999,
  113903. -999, -999, -999, -999, -999, -999, -999, -999},
  113904. {-999, -999, -999, -999, -999, -999, -999, -999,
  113905. -999, -103, -96, -90, -86, -78, -70, -51,
  113906. -42, -47, -48, -55, -54, -54, -53, -42,
  113907. -35, -28, -33, -38, -37, -44, -47, -49,
  113908. -54, -63, -68, -78, -82, -89, -94, -99,
  113909. -104, -109, -114, -999, -999, -999, -999, -999,
  113910. -999, -999, -999, -999, -999, -999, -999, -999}},
  113911. /* 2828 Hz */
  113912. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113913. -999, -999, -999, -999, -110, -100, -90, -79,
  113914. -85, -81, -82, -82, -89, -94, -99, -103,
  113915. -109, -115, -999, -999, -999, -999, -999, -999,
  113916. -999, -999, -999, -999, -999, -999, -999, -999,
  113917. -999, -999, -999, -999, -999, -999, -999, -999,
  113918. -999, -999, -999, -999, -999, -999, -999, -999},
  113919. {-999, -999, -999, -999, -999, -999, -999, -999,
  113920. -999, -999, -999, -999, -105, -97, -85, -72,
  113921. -74, -70, -70, -70, -76, -85, -91, -93,
  113922. -97, -103, -109, -115, -999, -999, -999, -999,
  113923. -999, -999, -999, -999, -999, -999, -999, -999,
  113924. -999, -999, -999, -999, -999, -999, -999, -999,
  113925. -999, -999, -999, -999, -999, -999, -999, -999},
  113926. {-999, -999, -999, -999, -999, -999, -999, -999,
  113927. -999, -999, -999, -999, -112, -93, -81, -68,
  113928. -62, -60, -60, -57, -63, -70, -77, -82,
  113929. -90, -93, -98, -104, -109, -113, -999, -999,
  113930. -999, -999, -999, -999, -999, -999, -999, -999,
  113931. -999, -999, -999, -999, -999, -999, -999, -999,
  113932. -999, -999, -999, -999, -999, -999, -999, -999},
  113933. {-999, -999, -999, -999, -999, -999, -999, -999,
  113934. -999, -999, -999, -113, -100, -93, -84, -63,
  113935. -58, -48, -53, -54, -52, -52, -57, -64,
  113936. -66, -76, -83, -81, -85, -85, -90, -95,
  113937. -98, -101, -103, -106, -108, -111, -999, -999,
  113938. -999, -999, -999, -999, -999, -999, -999, -999,
  113939. -999, -999, -999, -999, -999, -999, -999, -999},
  113940. {-999, -999, -999, -999, -999, -999, -999, -999,
  113941. -999, -999, -999, -105, -95, -86, -74, -53,
  113942. -50, -38, -43, -49, -43, -42, -39, -39,
  113943. -46, -52, -57, -56, -72, -69, -74, -81,
  113944. -87, -92, -94, -97, -99, -102, -105, -108,
  113945. -999, -999, -999, -999, -999, -999, -999, -999,
  113946. -999, -999, -999, -999, -999, -999, -999, -999},
  113947. {-999, -999, -999, -999, -999, -999, -999, -999,
  113948. -999, -999, -108, -99, -90, -76, -66, -45,
  113949. -43, -41, -44, -47, -43, -47, -40, -30,
  113950. -31, -31, -39, -33, -40, -41, -43, -53,
  113951. -59, -70, -73, -77, -79, -82, -84, -87,
  113952. -999, -999, -999, -999, -999, -999, -999, -999,
  113953. -999, -999, -999, -999, -999, -999, -999, -999}},
  113954. /* 4000 Hz */
  113955. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113956. -999, -999, -999, -999, -999, -110, -91, -76,
  113957. -75, -85, -93, -98, -104, -110, -999, -999,
  113958. -999, -999, -999, -999, -999, -999, -999, -999,
  113959. -999, -999, -999, -999, -999, -999, -999, -999,
  113960. -999, -999, -999, -999, -999, -999, -999, -999,
  113961. -999, -999, -999, -999, -999, -999, -999, -999},
  113962. {-999, -999, -999, -999, -999, -999, -999, -999,
  113963. -999, -999, -999, -999, -999, -110, -91, -70,
  113964. -70, -75, -86, -89, -94, -98, -101, -106,
  113965. -110, -999, -999, -999, -999, -999, -999, -999,
  113966. -999, -999, -999, -999, -999, -999, -999, -999,
  113967. -999, -999, -999, -999, -999, -999, -999, -999,
  113968. -999, -999, -999, -999, -999, -999, -999, -999},
  113969. {-999, -999, -999, -999, -999, -999, -999, -999,
  113970. -999, -999, -999, -999, -110, -95, -80, -60,
  113971. -65, -64, -74, -83, -88, -91, -95, -99,
  113972. -103, -107, -110, -999, -999, -999, -999, -999,
  113973. -999, -999, -999, -999, -999, -999, -999, -999,
  113974. -999, -999, -999, -999, -999, -999, -999, -999,
  113975. -999, -999, -999, -999, -999, -999, -999, -999},
  113976. {-999, -999, -999, -999, -999, -999, -999, -999,
  113977. -999, -999, -999, -999, -110, -95, -80, -58,
  113978. -55, -49, -66, -68, -71, -78, -78, -80,
  113979. -88, -85, -89, -97, -100, -105, -110, -999,
  113980. -999, -999, -999, -999, -999, -999, -999, -999,
  113981. -999, -999, -999, -999, -999, -999, -999, -999,
  113982. -999, -999, -999, -999, -999, -999, -999, -999},
  113983. {-999, -999, -999, -999, -999, -999, -999, -999,
  113984. -999, -999, -999, -999, -110, -95, -80, -53,
  113985. -52, -41, -59, -59, -49, -58, -56, -63,
  113986. -86, -79, -90, -93, -98, -103, -107, -112,
  113987. -999, -999, -999, -999, -999, -999, -999, -999,
  113988. -999, -999, -999, -999, -999, -999, -999, -999,
  113989. -999, -999, -999, -999, -999, -999, -999, -999},
  113990. {-999, -999, -999, -999, -999, -999, -999, -999,
  113991. -999, -999, -999, -110, -97, -91, -73, -45,
  113992. -40, -33, -53, -61, -49, -54, -50, -50,
  113993. -60, -52, -67, -74, -81, -92, -96, -100,
  113994. -105, -110, -999, -999, -999, -999, -999, -999,
  113995. -999, -999, -999, -999, -999, -999, -999, -999,
  113996. -999, -999, -999, -999, -999, -999, -999, -999}},
  113997. /* 5657 Hz */
  113998. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113999. -999, -999, -999, -113, -106, -99, -92, -77,
  114000. -80, -88, -97, -106, -115, -999, -999, -999,
  114001. -999, -999, -999, -999, -999, -999, -999, -999,
  114002. -999, -999, -999, -999, -999, -999, -999, -999,
  114003. -999, -999, -999, -999, -999, -999, -999, -999,
  114004. -999, -999, -999, -999, -999, -999, -999, -999},
  114005. {-999, -999, -999, -999, -999, -999, -999, -999,
  114006. -999, -999, -116, -109, -102, -95, -89, -74,
  114007. -72, -88, -87, -95, -102, -109, -116, -999,
  114008. -999, -999, -999, -999, -999, -999, -999, -999,
  114009. -999, -999, -999, -999, -999, -999, -999, -999,
  114010. -999, -999, -999, -999, -999, -999, -999, -999,
  114011. -999, -999, -999, -999, -999, -999, -999, -999},
  114012. {-999, -999, -999, -999, -999, -999, -999, -999,
  114013. -999, -999, -116, -109, -102, -95, -89, -75,
  114014. -66, -74, -77, -78, -86, -87, -90, -96,
  114015. -105, -115, -999, -999, -999, -999, -999, -999,
  114016. -999, -999, -999, -999, -999, -999, -999, -999,
  114017. -999, -999, -999, -999, -999, -999, -999, -999,
  114018. -999, -999, -999, -999, -999, -999, -999, -999},
  114019. {-999, -999, -999, -999, -999, -999, -999, -999,
  114020. -999, -999, -115, -108, -101, -94, -88, -66,
  114021. -56, -61, -70, -65, -78, -72, -83, -84,
  114022. -93, -98, -105, -110, -999, -999, -999, -999,
  114023. -999, -999, -999, -999, -999, -999, -999, -999,
  114024. -999, -999, -999, -999, -999, -999, -999, -999,
  114025. -999, -999, -999, -999, -999, -999, -999, -999},
  114026. {-999, -999, -999, -999, -999, -999, -999, -999,
  114027. -999, -999, -110, -105, -95, -89, -82, -57,
  114028. -52, -52, -59, -56, -59, -58, -69, -67,
  114029. -88, -82, -82, -89, -94, -100, -108, -999,
  114030. -999, -999, -999, -999, -999, -999, -999, -999,
  114031. -999, -999, -999, -999, -999, -999, -999, -999,
  114032. -999, -999, -999, -999, -999, -999, -999, -999},
  114033. {-999, -999, -999, -999, -999, -999, -999, -999,
  114034. -999, -110, -101, -96, -90, -83, -77, -54,
  114035. -43, -38, -50, -48, -52, -48, -42, -42,
  114036. -51, -52, -53, -59, -65, -71, -78, -85,
  114037. -95, -999, -999, -999, -999, -999, -999, -999,
  114038. -999, -999, -999, -999, -999, -999, -999, -999,
  114039. -999, -999, -999, -999, -999, -999, -999, -999}},
  114040. /* 8000 Hz */
  114041. {{-999, -999, -999, -999, -999, -999, -999, -999,
  114042. -999, -999, -999, -999, -120, -105, -86, -68,
  114043. -78, -79, -90, -100, -110, -999, -999, -999,
  114044. -999, -999, -999, -999, -999, -999, -999, -999,
  114045. -999, -999, -999, -999, -999, -999, -999, -999,
  114046. -999, -999, -999, -999, -999, -999, -999, -999,
  114047. -999, -999, -999, -999, -999, -999, -999, -999},
  114048. {-999, -999, -999, -999, -999, -999, -999, -999,
  114049. -999, -999, -999, -999, -120, -105, -86, -66,
  114050. -73, -77, -88, -96, -105, -115, -999, -999,
  114051. -999, -999, -999, -999, -999, -999, -999, -999,
  114052. -999, -999, -999, -999, -999, -999, -999, -999,
  114053. -999, -999, -999, -999, -999, -999, -999, -999,
  114054. -999, -999, -999, -999, -999, -999, -999, -999},
  114055. {-999, -999, -999, -999, -999, -999, -999, -999,
  114056. -999, -999, -999, -120, -105, -92, -80, -61,
  114057. -64, -68, -80, -87, -92, -100, -110, -999,
  114058. -999, -999, -999, -999, -999, -999, -999, -999,
  114059. -999, -999, -999, -999, -999, -999, -999, -999,
  114060. -999, -999, -999, -999, -999, -999, -999, -999,
  114061. -999, -999, -999, -999, -999, -999, -999, -999},
  114062. {-999, -999, -999, -999, -999, -999, -999, -999,
  114063. -999, -999, -999, -120, -104, -91, -79, -52,
  114064. -60, -54, -64, -69, -77, -80, -82, -84,
  114065. -85, -87, -88, -90, -999, -999, -999, -999,
  114066. -999, -999, -999, -999, -999, -999, -999, -999,
  114067. -999, -999, -999, -999, -999, -999, -999, -999,
  114068. -999, -999, -999, -999, -999, -999, -999, -999},
  114069. {-999, -999, -999, -999, -999, -999, -999, -999,
  114070. -999, -999, -999, -118, -100, -87, -77, -49,
  114071. -50, -44, -58, -61, -61, -67, -65, -62,
  114072. -62, -62, -65, -68, -999, -999, -999, -999,
  114073. -999, -999, -999, -999, -999, -999, -999, -999,
  114074. -999, -999, -999, -999, -999, -999, -999, -999,
  114075. -999, -999, -999, -999, -999, -999, -999, -999},
  114076. {-999, -999, -999, -999, -999, -999, -999, -999,
  114077. -999, -999, -999, -115, -98, -84, -62, -49,
  114078. -44, -38, -46, -49, -49, -46, -39, -37,
  114079. -39, -40, -42, -43, -999, -999, -999, -999,
  114080. -999, -999, -999, -999, -999, -999, -999, -999,
  114081. -999, -999, -999, -999, -999, -999, -999, -999,
  114082. -999, -999, -999, -999, -999, -999, -999, -999}},
  114083. /* 11314 Hz */
  114084. {{-999, -999, -999, -999, -999, -999, -999, -999,
  114085. -999, -999, -999, -999, -999, -110, -88, -74,
  114086. -77, -82, -82, -85, -90, -94, -99, -104,
  114087. -999, -999, -999, -999, -999, -999, -999, -999,
  114088. -999, -999, -999, -999, -999, -999, -999, -999,
  114089. -999, -999, -999, -999, -999, -999, -999, -999,
  114090. -999, -999, -999, -999, -999, -999, -999, -999},
  114091. {-999, -999, -999, -999, -999, -999, -999, -999,
  114092. -999, -999, -999, -999, -999, -110, -88, -66,
  114093. -70, -81, -80, -81, -84, -88, -91, -93,
  114094. -999, -999, -999, -999, -999, -999, -999, -999,
  114095. -999, -999, -999, -999, -999, -999, -999, -999,
  114096. -999, -999, -999, -999, -999, -999, -999, -999,
  114097. -999, -999, -999, -999, -999, -999, -999, -999},
  114098. {-999, -999, -999, -999, -999, -999, -999, -999,
  114099. -999, -999, -999, -999, -999, -110, -88, -61,
  114100. -63, -70, -71, -74, -77, -80, -83, -85,
  114101. -999, -999, -999, -999, -999, -999, -999, -999,
  114102. -999, -999, -999, -999, -999, -999, -999, -999,
  114103. -999, -999, -999, -999, -999, -999, -999, -999,
  114104. -999, -999, -999, -999, -999, -999, -999, -999},
  114105. {-999, -999, -999, -999, -999, -999, -999, -999,
  114106. -999, -999, -999, -999, -999, -110, -86, -62,
  114107. -63, -62, -62, -58, -52, -50, -50, -52,
  114108. -54, -999, -999, -999, -999, -999, -999, -999,
  114109. -999, -999, -999, -999, -999, -999, -999, -999,
  114110. -999, -999, -999, -999, -999, -999, -999, -999,
  114111. -999, -999, -999, -999, -999, -999, -999, -999},
  114112. {-999, -999, -999, -999, -999, -999, -999, -999,
  114113. -999, -999, -999, -999, -118, -108, -84, -53,
  114114. -50, -50, -50, -55, -47, -45, -40, -40,
  114115. -40, -999, -999, -999, -999, -999, -999, -999,
  114116. -999, -999, -999, -999, -999, -999, -999, -999,
  114117. -999, -999, -999, -999, -999, -999, -999, -999,
  114118. -999, -999, -999, -999, -999, -999, -999, -999},
  114119. {-999, -999, -999, -999, -999, -999, -999, -999,
  114120. -999, -999, -999, -999, -118, -100, -73, -43,
  114121. -37, -42, -43, -53, -38, -37, -35, -35,
  114122. -38, -999, -999, -999, -999, -999, -999, -999,
  114123. -999, -999, -999, -999, -999, -999, -999, -999,
  114124. -999, -999, -999, -999, -999, -999, -999, -999,
  114125. -999, -999, -999, -999, -999, -999, -999, -999}},
  114126. /* 16000 Hz */
  114127. {{-999, -999, -999, -999, -999, -999, -999, -999,
  114128. -999, -999, -999, -110, -100, -91, -84, -74,
  114129. -80, -80, -80, -80, -80, -999, -999, -999,
  114130. -999, -999, -999, -999, -999, -999, -999, -999,
  114131. -999, -999, -999, -999, -999, -999, -999, -999,
  114132. -999, -999, -999, -999, -999, -999, -999, -999,
  114133. -999, -999, -999, -999, -999, -999, -999, -999},
  114134. {-999, -999, -999, -999, -999, -999, -999, -999,
  114135. -999, -999, -999, -110, -100, -91, -84, -74,
  114136. -68, -68, -68, -68, -68, -999, -999, -999,
  114137. -999, -999, -999, -999, -999, -999, -999, -999,
  114138. -999, -999, -999, -999, -999, -999, -999, -999,
  114139. -999, -999, -999, -999, -999, -999, -999, -999,
  114140. -999, -999, -999, -999, -999, -999, -999, -999},
  114141. {-999, -999, -999, -999, -999, -999, -999, -999,
  114142. -999, -999, -999, -110, -100, -86, -78, -70,
  114143. -60, -45, -30, -21, -999, -999, -999, -999,
  114144. -999, -999, -999, -999, -999, -999, -999, -999,
  114145. -999, -999, -999, -999, -999, -999, -999, -999,
  114146. -999, -999, -999, -999, -999, -999, -999, -999,
  114147. -999, -999, -999, -999, -999, -999, -999, -999},
  114148. {-999, -999, -999, -999, -999, -999, -999, -999,
  114149. -999, -999, -999, -110, -100, -87, -78, -67,
  114150. -48, -38, -29, -21, -999, -999, -999, -999,
  114151. -999, -999, -999, -999, -999, -999, -999, -999,
  114152. -999, -999, -999, -999, -999, -999, -999, -999,
  114153. -999, -999, -999, -999, -999, -999, -999, -999,
  114154. -999, -999, -999, -999, -999, -999, -999, -999},
  114155. {-999, -999, -999, -999, -999, -999, -999, -999,
  114156. -999, -999, -999, -110, -100, -86, -69, -56,
  114157. -45, -35, -33, -29, -999, -999, -999, -999,
  114158. -999, -999, -999, -999, -999, -999, -999, -999,
  114159. -999, -999, -999, -999, -999, -999, -999, -999,
  114160. -999, -999, -999, -999, -999, -999, -999, -999,
  114161. -999, -999, -999, -999, -999, -999, -999, -999},
  114162. {-999, -999, -999, -999, -999, -999, -999, -999,
  114163. -999, -999, -999, -110, -100, -83, -71, -48,
  114164. -27, -38, -37, -34, -999, -999, -999, -999,
  114165. -999, -999, -999, -999, -999, -999, -999, -999,
  114166. -999, -999, -999, -999, -999, -999, -999, -999,
  114167. -999, -999, -999, -999, -999, -999, -999, -999,
  114168. -999, -999, -999, -999, -999, -999, -999, -999}}
  114169. };
  114170. #endif
  114171. /*** End of inlined file: masking.h ***/
  114172. #define NEGINF -9999.f
  114173. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  114174. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  114175. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  114176. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114177. vorbis_info_psy_global *gi=&ci->psy_g_param;
  114178. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  114179. look->channels=vi->channels;
  114180. look->ampmax=-9999.;
  114181. look->gi=gi;
  114182. return(look);
  114183. }
  114184. void _vp_global_free(vorbis_look_psy_global *look){
  114185. if(look){
  114186. memset(look,0,sizeof(*look));
  114187. _ogg_free(look);
  114188. }
  114189. }
  114190. void _vi_gpsy_free(vorbis_info_psy_global *i){
  114191. if(i){
  114192. memset(i,0,sizeof(*i));
  114193. _ogg_free(i);
  114194. }
  114195. }
  114196. void _vi_psy_free(vorbis_info_psy *i){
  114197. if(i){
  114198. memset(i,0,sizeof(*i));
  114199. _ogg_free(i);
  114200. }
  114201. }
  114202. static void min_curve(float *c,
  114203. float *c2){
  114204. int i;
  114205. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  114206. }
  114207. static void max_curve(float *c,
  114208. float *c2){
  114209. int i;
  114210. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  114211. }
  114212. static void attenuate_curve(float *c,float att){
  114213. int i;
  114214. for(i=0;i<EHMER_MAX;i++)
  114215. c[i]+=att;
  114216. }
  114217. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  114218. float center_boost, float center_decay_rate){
  114219. int i,j,k,m;
  114220. float ath[EHMER_MAX];
  114221. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  114222. float athc[P_LEVELS][EHMER_MAX];
  114223. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  114224. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  114225. memset(workc,0,sizeof(workc));
  114226. for(i=0;i<P_BANDS;i++){
  114227. /* we add back in the ATH to avoid low level curves falling off to
  114228. -infinity and unnecessarily cutting off high level curves in the
  114229. curve limiting (last step). */
  114230. /* A half-band's settings must be valid over the whole band, and
  114231. it's better to mask too little than too much */
  114232. int ath_offset=i*4;
  114233. for(j=0;j<EHMER_MAX;j++){
  114234. float min=999.;
  114235. for(k=0;k<4;k++)
  114236. if(j+k+ath_offset<MAX_ATH){
  114237. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  114238. }else{
  114239. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  114240. }
  114241. ath[j]=min;
  114242. }
  114243. /* copy curves into working space, replicate the 50dB curve to 30
  114244. and 40, replicate the 100dB curve to 110 */
  114245. for(j=0;j<6;j++)
  114246. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  114247. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  114248. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  114249. /* apply centered curve boost/decay */
  114250. for(j=0;j<P_LEVELS;j++){
  114251. for(k=0;k<EHMER_MAX;k++){
  114252. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  114253. if(adj<0. && center_boost>0)adj=0.;
  114254. if(adj>0. && center_boost<0)adj=0.;
  114255. workc[i][j][k]+=adj;
  114256. }
  114257. }
  114258. /* normalize curves so the driving amplitude is 0dB */
  114259. /* make temp curves with the ATH overlayed */
  114260. for(j=0;j<P_LEVELS;j++){
  114261. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  114262. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  114263. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  114264. max_curve(athc[j],workc[i][j]);
  114265. }
  114266. /* Now limit the louder curves.
  114267. the idea is this: We don't know what the playback attenuation
  114268. will be; 0dB SL moves every time the user twiddles the volume
  114269. knob. So that means we have to use a single 'most pessimal' curve
  114270. for all masking amplitudes, right? Wrong. The *loudest* sound
  114271. can be in (we assume) a range of ...+100dB] SL. However, sounds
  114272. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  114273. etc... */
  114274. for(j=1;j<P_LEVELS;j++){
  114275. min_curve(athc[j],athc[j-1]);
  114276. min_curve(workc[i][j],athc[j]);
  114277. }
  114278. }
  114279. for(i=0;i<P_BANDS;i++){
  114280. int hi_curve,lo_curve,bin;
  114281. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  114282. /* low frequency curves are measured with greater resolution than
  114283. the MDCT/FFT will actually give us; we want the curve applied
  114284. to the tone data to be pessimistic and thus apply the minimum
  114285. masking possible for a given bin. That means that a single bin
  114286. could span more than one octave and that the curve will be a
  114287. composite of multiple octaves. It also may mean that a single
  114288. bin may span > an eighth of an octave and that the eighth
  114289. octave values may also be composited. */
  114290. /* which octave curves will we be compositing? */
  114291. bin=floor(fromOC(i*.5)/binHz);
  114292. lo_curve= ceil(toOC(bin*binHz+1)*2);
  114293. hi_curve= floor(toOC((bin+1)*binHz)*2);
  114294. if(lo_curve>i)lo_curve=i;
  114295. if(lo_curve<0)lo_curve=0;
  114296. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  114297. for(m=0;m<P_LEVELS;m++){
  114298. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  114299. for(j=0;j<n;j++)brute_buffer[j]=999.;
  114300. /* render the curve into bins, then pull values back into curve.
  114301. The point is that any inherent subsampling aliasing results in
  114302. a safe minimum */
  114303. for(k=lo_curve;k<=hi_curve;k++){
  114304. int l=0;
  114305. for(j=0;j<EHMER_MAX;j++){
  114306. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  114307. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  114308. if(lo_bin<0)lo_bin=0;
  114309. if(lo_bin>n)lo_bin=n;
  114310. if(lo_bin<l)l=lo_bin;
  114311. if(hi_bin<0)hi_bin=0;
  114312. if(hi_bin>n)hi_bin=n;
  114313. for(;l<hi_bin && l<n;l++)
  114314. if(brute_buffer[l]>workc[k][m][j])
  114315. brute_buffer[l]=workc[k][m][j];
  114316. }
  114317. for(;l<n;l++)
  114318. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  114319. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  114320. }
  114321. /* be equally paranoid about being valid up to next half ocatve */
  114322. if(i+1<P_BANDS){
  114323. int l=0;
  114324. k=i+1;
  114325. for(j=0;j<EHMER_MAX;j++){
  114326. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  114327. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  114328. if(lo_bin<0)lo_bin=0;
  114329. if(lo_bin>n)lo_bin=n;
  114330. if(lo_bin<l)l=lo_bin;
  114331. if(hi_bin<0)hi_bin=0;
  114332. if(hi_bin>n)hi_bin=n;
  114333. for(;l<hi_bin && l<n;l++)
  114334. if(brute_buffer[l]>workc[k][m][j])
  114335. brute_buffer[l]=workc[k][m][j];
  114336. }
  114337. for(;l<n;l++)
  114338. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  114339. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  114340. }
  114341. for(j=0;j<EHMER_MAX;j++){
  114342. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  114343. if(bin<0){
  114344. ret[i][m][j+2]=-999.;
  114345. }else{
  114346. if(bin>=n){
  114347. ret[i][m][j+2]=-999.;
  114348. }else{
  114349. ret[i][m][j+2]=brute_buffer[bin];
  114350. }
  114351. }
  114352. }
  114353. /* add fenceposts */
  114354. for(j=0;j<EHMER_OFFSET;j++)
  114355. if(ret[i][m][j+2]>-200.f)break;
  114356. ret[i][m][0]=j;
  114357. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  114358. if(ret[i][m][j+2]>-200.f)
  114359. break;
  114360. ret[i][m][1]=j;
  114361. }
  114362. }
  114363. return(ret);
  114364. }
  114365. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  114366. vorbis_info_psy_global *gi,int n,long rate){
  114367. long i,j,lo=-99,hi=1;
  114368. long maxoc;
  114369. memset(p,0,sizeof(*p));
  114370. p->eighth_octave_lines=gi->eighth_octave_lines;
  114371. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  114372. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  114373. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  114374. p->total_octave_lines=maxoc-p->firstoc+1;
  114375. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  114376. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  114377. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  114378. p->vi=vi;
  114379. p->n=n;
  114380. p->rate=rate;
  114381. /* AoTuV HF weighting */
  114382. p->m_val = 1.;
  114383. if(rate < 26000) p->m_val = 0;
  114384. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  114385. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  114386. /* set up the lookups for a given blocksize and sample rate */
  114387. for(i=0,j=0;i<MAX_ATH-1;i++){
  114388. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  114389. float base=ATH[i];
  114390. if(j<endpos){
  114391. float delta=(ATH[i+1]-base)/(endpos-j);
  114392. for(;j<endpos && j<n;j++){
  114393. p->ath[j]=base+100.;
  114394. base+=delta;
  114395. }
  114396. }
  114397. }
  114398. for(i=0;i<n;i++){
  114399. float bark=toBARK(rate/(2*n)*i);
  114400. for(;lo+vi->noisewindowlomin<i &&
  114401. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  114402. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  114403. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  114404. p->bark[i]=((lo-1)<<16)+(hi-1);
  114405. }
  114406. for(i=0;i<n;i++)
  114407. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  114408. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  114409. vi->tone_centerboost,vi->tone_decay);
  114410. /* set up rolling noise median */
  114411. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  114412. for(i=0;i<P_NOISECURVES;i++)
  114413. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  114414. for(i=0;i<n;i++){
  114415. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  114416. int inthalfoc;
  114417. float del;
  114418. if(halfoc<0)halfoc=0;
  114419. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  114420. inthalfoc=(int)halfoc;
  114421. del=halfoc-inthalfoc;
  114422. for(j=0;j<P_NOISECURVES;j++)
  114423. p->noiseoffset[j][i]=
  114424. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  114425. p->vi->noiseoff[j][inthalfoc+1]*del;
  114426. }
  114427. #if 0
  114428. {
  114429. static int ls=0;
  114430. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  114431. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  114432. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  114433. }
  114434. #endif
  114435. }
  114436. void _vp_psy_clear(vorbis_look_psy *p){
  114437. int i,j;
  114438. if(p){
  114439. if(p->ath)_ogg_free(p->ath);
  114440. if(p->octave)_ogg_free(p->octave);
  114441. if(p->bark)_ogg_free(p->bark);
  114442. if(p->tonecurves){
  114443. for(i=0;i<P_BANDS;i++){
  114444. for(j=0;j<P_LEVELS;j++){
  114445. _ogg_free(p->tonecurves[i][j]);
  114446. }
  114447. _ogg_free(p->tonecurves[i]);
  114448. }
  114449. _ogg_free(p->tonecurves);
  114450. }
  114451. if(p->noiseoffset){
  114452. for(i=0;i<P_NOISECURVES;i++){
  114453. _ogg_free(p->noiseoffset[i]);
  114454. }
  114455. _ogg_free(p->noiseoffset);
  114456. }
  114457. memset(p,0,sizeof(*p));
  114458. }
  114459. }
  114460. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  114461. static void seed_curve(float *seed,
  114462. const float **curves,
  114463. float amp,
  114464. int oc, int n,
  114465. int linesper,float dBoffset){
  114466. int i,post1;
  114467. int seedptr;
  114468. const float *posts,*curve;
  114469. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  114470. choice=max(choice,0);
  114471. choice=min(choice,P_LEVELS-1);
  114472. posts=curves[choice];
  114473. curve=posts+2;
  114474. post1=(int)posts[1];
  114475. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  114476. for(i=posts[0];i<post1;i++){
  114477. if(seedptr>0){
  114478. float lin=amp+curve[i];
  114479. if(seed[seedptr]<lin)seed[seedptr]=lin;
  114480. }
  114481. seedptr+=linesper;
  114482. if(seedptr>=n)break;
  114483. }
  114484. }
  114485. static void seed_loop(vorbis_look_psy *p,
  114486. const float ***curves,
  114487. const float *f,
  114488. const float *flr,
  114489. float *seed,
  114490. float specmax){
  114491. vorbis_info_psy *vi=p->vi;
  114492. long n=p->n,i;
  114493. float dBoffset=vi->max_curve_dB-specmax;
  114494. /* prime the working vector with peak values */
  114495. for(i=0;i<n;i++){
  114496. float max=f[i];
  114497. long oc=p->octave[i];
  114498. while(i+1<n && p->octave[i+1]==oc){
  114499. i++;
  114500. if(f[i]>max)max=f[i];
  114501. }
  114502. if(max+6.f>flr[i]){
  114503. oc=oc>>p->shiftoc;
  114504. if(oc>=P_BANDS)oc=P_BANDS-1;
  114505. if(oc<0)oc=0;
  114506. seed_curve(seed,
  114507. curves[oc],
  114508. max,
  114509. p->octave[i]-p->firstoc,
  114510. p->total_octave_lines,
  114511. p->eighth_octave_lines,
  114512. dBoffset);
  114513. }
  114514. }
  114515. }
  114516. static void seed_chase(float *seeds, int linesper, long n){
  114517. long *posstack=(long*)alloca(n*sizeof(*posstack));
  114518. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  114519. long stack=0;
  114520. long pos=0;
  114521. long i;
  114522. for(i=0;i<n;i++){
  114523. if(stack<2){
  114524. posstack[stack]=i;
  114525. ampstack[stack++]=seeds[i];
  114526. }else{
  114527. while(1){
  114528. if(seeds[i]<ampstack[stack-1]){
  114529. posstack[stack]=i;
  114530. ampstack[stack++]=seeds[i];
  114531. break;
  114532. }else{
  114533. if(i<posstack[stack-1]+linesper){
  114534. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  114535. i<posstack[stack-2]+linesper){
  114536. /* we completely overlap, making stack-1 irrelevant. pop it */
  114537. stack--;
  114538. continue;
  114539. }
  114540. }
  114541. posstack[stack]=i;
  114542. ampstack[stack++]=seeds[i];
  114543. break;
  114544. }
  114545. }
  114546. }
  114547. }
  114548. /* the stack now contains only the positions that are relevant. Scan
  114549. 'em straight through */
  114550. for(i=0;i<stack;i++){
  114551. long endpos;
  114552. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  114553. endpos=posstack[i+1];
  114554. }else{
  114555. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  114556. discarded in short frames */
  114557. }
  114558. if(endpos>n)endpos=n;
  114559. for(;pos<endpos;pos++)
  114560. seeds[pos]=ampstack[i];
  114561. }
  114562. /* there. Linear time. I now remember this was on a problem set I
  114563. had in Grad Skool... I didn't solve it at the time ;-) */
  114564. }
  114565. /* bleaugh, this is more complicated than it needs to be */
  114566. #include<stdio.h>
  114567. static void max_seeds(vorbis_look_psy *p,
  114568. float *seed,
  114569. float *flr){
  114570. long n=p->total_octave_lines;
  114571. int linesper=p->eighth_octave_lines;
  114572. long linpos=0;
  114573. long pos;
  114574. seed_chase(seed,linesper,n); /* for masking */
  114575. pos=p->octave[0]-p->firstoc-(linesper>>1);
  114576. while(linpos+1<p->n){
  114577. float minV=seed[pos];
  114578. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  114579. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  114580. while(pos+1<=end){
  114581. pos++;
  114582. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  114583. minV=seed[pos];
  114584. }
  114585. end=pos+p->firstoc;
  114586. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  114587. if(flr[linpos]<minV)flr[linpos]=minV;
  114588. }
  114589. {
  114590. float minV=seed[p->total_octave_lines-1];
  114591. for(;linpos<p->n;linpos++)
  114592. if(flr[linpos]<minV)flr[linpos]=minV;
  114593. }
  114594. }
  114595. static void bark_noise_hybridmp(int n,const long *b,
  114596. const float *f,
  114597. float *noise,
  114598. const float offset,
  114599. const int fixed){
  114600. float *N=(float*) alloca(n*sizeof(*N));
  114601. float *X=(float*) alloca(n*sizeof(*N));
  114602. float *XX=(float*) alloca(n*sizeof(*N));
  114603. float *Y=(float*) alloca(n*sizeof(*N));
  114604. float *XY=(float*) alloca(n*sizeof(*N));
  114605. float tN, tX, tXX, tY, tXY;
  114606. int i;
  114607. int lo, hi;
  114608. float R, A, B, D;
  114609. float w, x, y;
  114610. tN = tX = tXX = tY = tXY = 0.f;
  114611. y = f[0] + offset;
  114612. if (y < 1.f) y = 1.f;
  114613. w = y * y * .5;
  114614. tN += w;
  114615. tX += w;
  114616. tY += w * y;
  114617. N[0] = tN;
  114618. X[0] = tX;
  114619. XX[0] = tXX;
  114620. Y[0] = tY;
  114621. XY[0] = tXY;
  114622. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  114623. y = f[i] + offset;
  114624. if (y < 1.f) y = 1.f;
  114625. w = y * y;
  114626. tN += w;
  114627. tX += w * x;
  114628. tXX += w * x * x;
  114629. tY += w * y;
  114630. tXY += w * x * y;
  114631. N[i] = tN;
  114632. X[i] = tX;
  114633. XX[i] = tXX;
  114634. Y[i] = tY;
  114635. XY[i] = tXY;
  114636. }
  114637. for (i = 0, x = 0.f;; i++, x += 1.f) {
  114638. lo = b[i] >> 16;
  114639. if( lo>=0 ) break;
  114640. hi = b[i] & 0xffff;
  114641. tN = N[hi] + N[-lo];
  114642. tX = X[hi] - X[-lo];
  114643. tXX = XX[hi] + XX[-lo];
  114644. tY = Y[hi] + Y[-lo];
  114645. tXY = XY[hi] - XY[-lo];
  114646. A = tY * tXX - tX * tXY;
  114647. B = tN * tXY - tX * tY;
  114648. D = tN * tXX - tX * tX;
  114649. R = (A + x * B) / D;
  114650. if (R < 0.f)
  114651. R = 0.f;
  114652. noise[i] = R - offset;
  114653. }
  114654. for ( ;; i++, x += 1.f) {
  114655. lo = b[i] >> 16;
  114656. hi = b[i] & 0xffff;
  114657. if(hi>=n)break;
  114658. tN = N[hi] - N[lo];
  114659. tX = X[hi] - X[lo];
  114660. tXX = XX[hi] - XX[lo];
  114661. tY = Y[hi] - Y[lo];
  114662. tXY = XY[hi] - XY[lo];
  114663. A = tY * tXX - tX * tXY;
  114664. B = tN * tXY - tX * tY;
  114665. D = tN * tXX - tX * tX;
  114666. R = (A + x * B) / D;
  114667. if (R < 0.f) R = 0.f;
  114668. noise[i] = R - offset;
  114669. }
  114670. for ( ; i < n; i++, x += 1.f) {
  114671. R = (A + x * B) / D;
  114672. if (R < 0.f) R = 0.f;
  114673. noise[i] = R - offset;
  114674. }
  114675. if (fixed <= 0) return;
  114676. for (i = 0, x = 0.f;; i++, x += 1.f) {
  114677. hi = i + fixed / 2;
  114678. lo = hi - fixed;
  114679. if(lo>=0)break;
  114680. tN = N[hi] + N[-lo];
  114681. tX = X[hi] - X[-lo];
  114682. tXX = XX[hi] + XX[-lo];
  114683. tY = Y[hi] + Y[-lo];
  114684. tXY = XY[hi] - XY[-lo];
  114685. A = tY * tXX - tX * tXY;
  114686. B = tN * tXY - tX * tY;
  114687. D = tN * tXX - tX * tX;
  114688. R = (A + x * B) / D;
  114689. if (R - offset < noise[i]) noise[i] = R - offset;
  114690. }
  114691. for ( ;; i++, x += 1.f) {
  114692. hi = i + fixed / 2;
  114693. lo = hi - fixed;
  114694. if(hi>=n)break;
  114695. tN = N[hi] - N[lo];
  114696. tX = X[hi] - X[lo];
  114697. tXX = XX[hi] - XX[lo];
  114698. tY = Y[hi] - Y[lo];
  114699. tXY = XY[hi] - XY[lo];
  114700. A = tY * tXX - tX * tXY;
  114701. B = tN * tXY - tX * tY;
  114702. D = tN * tXX - tX * tX;
  114703. R = (A + x * B) / D;
  114704. if (R - offset < noise[i]) noise[i] = R - offset;
  114705. }
  114706. for ( ; i < n; i++, x += 1.f) {
  114707. R = (A + x * B) / D;
  114708. if (R - offset < noise[i]) noise[i] = R - offset;
  114709. }
  114710. }
  114711. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  114712. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  114713. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  114714. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  114715. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  114716. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  114717. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  114718. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  114719. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  114720. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  114721. 973377.F, 913981.F, 858210.F, 805842.F,
  114722. 756669.F, 710497.F, 667142.F, 626433.F,
  114723. 588208.F, 552316.F, 518613.F, 486967.F,
  114724. 457252.F, 429351.F, 403152.F, 378551.F,
  114725. 355452.F, 333762.F, 313396.F, 294273.F,
  114726. 276316.F, 259455.F, 243623.F, 228757.F,
  114727. 214798.F, 201691.F, 189384.F, 177828.F,
  114728. 166977.F, 156788.F, 147221.F, 138237.F,
  114729. 129802.F, 121881.F, 114444.F, 107461.F,
  114730. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  114731. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  114732. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  114733. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  114734. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  114735. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  114736. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  114737. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  114738. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  114739. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  114740. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  114741. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  114742. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  114743. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  114744. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  114745. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  114746. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  114747. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  114748. 1084.32F, 1018.15F, 956.024F, 897.687F,
  114749. 842.910F, 791.475F, 743.179F, 697.830F,
  114750. 655.249F, 615.265F, 577.722F, 542.469F,
  114751. 509.367F, 478.286F, 449.101F, 421.696F,
  114752. 395.964F, 371.803F, 349.115F, 327.812F,
  114753. 307.809F, 289.026F, 271.390F, 254.830F,
  114754. 239.280F, 224.679F, 210.969F, 198.096F,
  114755. 186.008F, 174.658F, 164.000F, 153.993F,
  114756. 144.596F, 135.773F, 127.488F, 119.708F,
  114757. 112.404F, 105.545F, 99.1046F, 93.0572F,
  114758. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  114759. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  114760. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  114761. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  114762. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  114763. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  114764. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  114765. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  114766. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  114767. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  114768. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  114769. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  114770. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  114771. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  114772. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  114773. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  114774. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  114775. 1.20790F, 1.13419F, 1.06499F, 1.F
  114776. };
  114777. void _vp_remove_floor(vorbis_look_psy *p,
  114778. float *mdct,
  114779. int *codedflr,
  114780. float *residue,
  114781. int sliding_lowpass){
  114782. int i,n=p->n;
  114783. if(sliding_lowpass>n)sliding_lowpass=n;
  114784. for(i=0;i<sliding_lowpass;i++){
  114785. residue[i]=
  114786. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  114787. }
  114788. for(;i<n;i++)
  114789. residue[i]=0.;
  114790. }
  114791. void _vp_noisemask(vorbis_look_psy *p,
  114792. float *logmdct,
  114793. float *logmask){
  114794. int i,n=p->n;
  114795. float *work=(float*) alloca(n*sizeof(*work));
  114796. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  114797. 140.,-1);
  114798. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  114799. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  114800. p->vi->noisewindowfixed);
  114801. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  114802. #if 0
  114803. {
  114804. static int seq=0;
  114805. float work2[n];
  114806. for(i=0;i<n;i++){
  114807. work2[i]=logmask[i]+work[i];
  114808. }
  114809. if(seq&1)
  114810. _analysis_output("median2R",seq/2,work,n,1,0,0);
  114811. else
  114812. _analysis_output("median2L",seq/2,work,n,1,0,0);
  114813. if(seq&1)
  114814. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  114815. else
  114816. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  114817. seq++;
  114818. }
  114819. #endif
  114820. for(i=0;i<n;i++){
  114821. int dB=logmask[i]+.5;
  114822. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  114823. if(dB<0)dB=0;
  114824. logmask[i]= work[i]+p->vi->noisecompand[dB];
  114825. }
  114826. }
  114827. void _vp_tonemask(vorbis_look_psy *p,
  114828. float *logfft,
  114829. float *logmask,
  114830. float global_specmax,
  114831. float local_specmax){
  114832. int i,n=p->n;
  114833. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  114834. float att=local_specmax+p->vi->ath_adjatt;
  114835. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  114836. /* set the ATH (floating below localmax, not global max by a
  114837. specified att) */
  114838. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  114839. for(i=0;i<n;i++)
  114840. logmask[i]=p->ath[i]+att;
  114841. /* tone masking */
  114842. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  114843. max_seeds(p,seed,logmask);
  114844. }
  114845. void _vp_offset_and_mix(vorbis_look_psy *p,
  114846. float *noise,
  114847. float *tone,
  114848. int offset_select,
  114849. float *logmask,
  114850. float *mdct,
  114851. float *logmdct){
  114852. int i,n=p->n;
  114853. float de, coeffi, cx;/* AoTuV */
  114854. float toneatt=p->vi->tone_masteratt[offset_select];
  114855. cx = p->m_val;
  114856. for(i=0;i<n;i++){
  114857. float val= noise[i]+p->noiseoffset[offset_select][i];
  114858. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  114859. logmask[i]=max(val,tone[i]+toneatt);
  114860. /* AoTuV */
  114861. /** @ M1 **
  114862. The following codes improve a noise problem.
  114863. A fundamental idea uses the value of masking and carries out
  114864. the relative compensation of the MDCT.
  114865. However, this code is not perfect and all noise problems cannot be solved.
  114866. by Aoyumi @ 2004/04/18
  114867. */
  114868. if(offset_select == 1) {
  114869. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  114870. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  114871. if(val > coeffi){
  114872. /* mdct value is > -17.2 dB below floor */
  114873. de = 1.0-((val-coeffi)*0.005*cx);
  114874. /* pro-rated attenuation:
  114875. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  114876. -0.77 dB boost if mdct value is 0dB (relative to floor)
  114877. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  114878. etc... */
  114879. if(de < 0) de = 0.0001;
  114880. }else
  114881. /* mdct value is <= -17.2 dB below floor */
  114882. de = 1.0-((val-coeffi)*0.0003*cx);
  114883. /* pro-rated attenuation:
  114884. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  114885. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  114886. etc... */
  114887. mdct[i] *= de;
  114888. }
  114889. }
  114890. }
  114891. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  114892. vorbis_info *vi=vd->vi;
  114893. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114894. vorbis_info_psy_global *gi=&ci->psy_g_param;
  114895. int n=ci->blocksizes[vd->W]/2;
  114896. float secs=(float)n/vi->rate;
  114897. amp+=secs*gi->ampmax_att_per_sec;
  114898. if(amp<-9999)amp=-9999;
  114899. return(amp);
  114900. }
  114901. static void couple_lossless(float A, float B,
  114902. float *qA, float *qB){
  114903. int test1=fabs(*qA)>fabs(*qB);
  114904. test1-= fabs(*qA)<fabs(*qB);
  114905. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  114906. if(test1==1){
  114907. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  114908. }else{
  114909. float temp=*qB;
  114910. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  114911. *qA=temp;
  114912. }
  114913. if(*qB>fabs(*qA)*1.9999f){
  114914. *qB= -fabs(*qA)*2.f;
  114915. *qA= -*qA;
  114916. }
  114917. }
  114918. static float hypot_lookup[32]={
  114919. -0.009935, -0.011245, -0.012726, -0.014397,
  114920. -0.016282, -0.018407, -0.020800, -0.023494,
  114921. -0.026522, -0.029923, -0.033737, -0.038010,
  114922. -0.042787, -0.048121, -0.054064, -0.060671,
  114923. -0.068000, -0.076109, -0.085054, -0.094892,
  114924. -0.105675, -0.117451, -0.130260, -0.144134,
  114925. -0.159093, -0.175146, -0.192286, -0.210490,
  114926. -0.229718, -0.249913, -0.271001, -0.292893};
  114927. static void precomputed_couple_point(float premag,
  114928. int floorA,int floorB,
  114929. float *mag, float *ang){
  114930. int test=(floorA>floorB)-1;
  114931. int offset=31-abs(floorA-floorB);
  114932. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  114933. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  114934. *mag=premag*floormag;
  114935. *ang=0.f;
  114936. }
  114937. /* just like below, this is currently set up to only do
  114938. single-step-depth coupling. Otherwise, we'd have to do more
  114939. copying (which will be inevitable later) */
  114940. /* doing the real circular magnitude calculation is audibly superior
  114941. to (A+B)/sqrt(2) */
  114942. static float dipole_hypot(float a, float b){
  114943. if(a>0.){
  114944. if(b>0.)return sqrt(a*a+b*b);
  114945. if(a>-b)return sqrt(a*a-b*b);
  114946. return -sqrt(b*b-a*a);
  114947. }
  114948. if(b<0.)return -sqrt(a*a+b*b);
  114949. if(-a>b)return -sqrt(a*a-b*b);
  114950. return sqrt(b*b-a*a);
  114951. }
  114952. static float round_hypot(float a, float b){
  114953. if(a>0.){
  114954. if(b>0.)return sqrt(a*a+b*b);
  114955. if(a>-b)return sqrt(a*a+b*b);
  114956. return -sqrt(b*b+a*a);
  114957. }
  114958. if(b<0.)return -sqrt(a*a+b*b);
  114959. if(-a>b)return -sqrt(a*a+b*b);
  114960. return sqrt(b*b+a*a);
  114961. }
  114962. /* revert to round hypot for now */
  114963. float **_vp_quantize_couple_memo(vorbis_block *vb,
  114964. vorbis_info_psy_global *g,
  114965. vorbis_look_psy *p,
  114966. vorbis_info_mapping0 *vi,
  114967. float **mdct){
  114968. int i,j,n=p->n;
  114969. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  114970. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  114971. for(i=0;i<vi->coupling_steps;i++){
  114972. float *mdctM=mdct[vi->coupling_mag[i]];
  114973. float *mdctA=mdct[vi->coupling_ang[i]];
  114974. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  114975. for(j=0;j<limit;j++)
  114976. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  114977. for(;j<n;j++)
  114978. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  114979. }
  114980. return(ret);
  114981. }
  114982. /* this is for per-channel noise normalization */
  114983. static int apsort(const void *a, const void *b){
  114984. float f1=fabs(**(float**)a);
  114985. float f2=fabs(**(float**)b);
  114986. return (f1<f2)-(f1>f2);
  114987. }
  114988. int **_vp_quantize_couple_sort(vorbis_block *vb,
  114989. vorbis_look_psy *p,
  114990. vorbis_info_mapping0 *vi,
  114991. float **mags){
  114992. if(p->vi->normal_point_p){
  114993. int i,j,k,n=p->n;
  114994. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  114995. int partition=p->vi->normal_partition;
  114996. float **work=(float**) alloca(sizeof(*work)*partition);
  114997. for(i=0;i<vi->coupling_steps;i++){
  114998. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  114999. for(j=0;j<n;j+=partition){
  115000. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  115001. qsort(work,partition,sizeof(*work),apsort);
  115002. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  115003. }
  115004. }
  115005. return(ret);
  115006. }
  115007. return(NULL);
  115008. }
  115009. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  115010. float *magnitudes,int *sortedindex){
  115011. int i,j,n=p->n;
  115012. vorbis_info_psy *vi=p->vi;
  115013. int partition=vi->normal_partition;
  115014. float **work=(float**) alloca(sizeof(*work)*partition);
  115015. int start=vi->normal_start;
  115016. for(j=start;j<n;j+=partition){
  115017. if(j+partition>n)partition=n-j;
  115018. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  115019. qsort(work,partition,sizeof(*work),apsort);
  115020. for(i=0;i<partition;i++){
  115021. sortedindex[i+j-start]=work[i]-magnitudes;
  115022. }
  115023. }
  115024. }
  115025. void _vp_noise_normalize(vorbis_look_psy *p,
  115026. float *in,float *out,int *sortedindex){
  115027. int flag=0,i,j=0,n=p->n;
  115028. vorbis_info_psy *vi=p->vi;
  115029. int partition=vi->normal_partition;
  115030. int start=vi->normal_start;
  115031. if(start>n)start=n;
  115032. if(vi->normal_channel_p){
  115033. for(;j<start;j++)
  115034. out[j]=rint(in[j]);
  115035. for(;j+partition<=n;j+=partition){
  115036. float acc=0.;
  115037. int k;
  115038. for(i=j;i<j+partition;i++)
  115039. acc+=in[i]*in[i];
  115040. for(i=0;i<partition;i++){
  115041. k=sortedindex[i+j-start];
  115042. if(in[k]*in[k]>=.25f){
  115043. out[k]=rint(in[k]);
  115044. acc-=in[k]*in[k];
  115045. flag=1;
  115046. }else{
  115047. if(acc<vi->normal_thresh)break;
  115048. out[k]=unitnorm(in[k]);
  115049. acc-=1.;
  115050. }
  115051. }
  115052. for(;i<partition;i++){
  115053. k=sortedindex[i+j-start];
  115054. out[k]=0.;
  115055. }
  115056. }
  115057. }
  115058. for(;j<n;j++)
  115059. out[j]=rint(in[j]);
  115060. }
  115061. void _vp_couple(int blobno,
  115062. vorbis_info_psy_global *g,
  115063. vorbis_look_psy *p,
  115064. vorbis_info_mapping0 *vi,
  115065. float **res,
  115066. float **mag_memo,
  115067. int **mag_sort,
  115068. int **ifloor,
  115069. int *nonzero,
  115070. int sliding_lowpass){
  115071. int i,j,k,n=p->n;
  115072. /* perform any requested channel coupling */
  115073. /* point stereo can only be used in a first stage (in this encoder)
  115074. because of the dependency on floor lookups */
  115075. for(i=0;i<vi->coupling_steps;i++){
  115076. /* once we're doing multistage coupling in which a channel goes
  115077. through more than one coupling step, the floor vector
  115078. magnitudes will also have to be recalculated an propogated
  115079. along with PCM. Right now, we're not (that will wait until 5.1
  115080. most likely), so the code isn't here yet. The memory management
  115081. here is all assuming single depth couplings anyway. */
  115082. /* make sure coupling a zero and a nonzero channel results in two
  115083. nonzero channels. */
  115084. if(nonzero[vi->coupling_mag[i]] ||
  115085. nonzero[vi->coupling_ang[i]]){
  115086. float *rM=res[vi->coupling_mag[i]];
  115087. float *rA=res[vi->coupling_ang[i]];
  115088. float *qM=rM+n;
  115089. float *qA=rA+n;
  115090. int *floorM=ifloor[vi->coupling_mag[i]];
  115091. int *floorA=ifloor[vi->coupling_ang[i]];
  115092. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  115093. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  115094. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  115095. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  115096. int pointlimit=limit;
  115097. nonzero[vi->coupling_mag[i]]=1;
  115098. nonzero[vi->coupling_ang[i]]=1;
  115099. /* The threshold of a stereo is changed with the size of n */
  115100. if(n > 1000)
  115101. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  115102. for(j=0;j<p->n;j+=partition){
  115103. float acc=0.f;
  115104. for(k=0;k<partition;k++){
  115105. int l=k+j;
  115106. if(l<sliding_lowpass){
  115107. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  115108. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  115109. precomputed_couple_point(mag_memo[i][l],
  115110. floorM[l],floorA[l],
  115111. qM+l,qA+l);
  115112. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  115113. }else{
  115114. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  115115. }
  115116. }else{
  115117. qM[l]=0.;
  115118. qA[l]=0.;
  115119. }
  115120. }
  115121. if(p->vi->normal_point_p){
  115122. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  115123. int l=mag_sort[i][j+k];
  115124. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  115125. qM[l]=unitnorm(qM[l]);
  115126. acc-=1.f;
  115127. }
  115128. }
  115129. }
  115130. }
  115131. }
  115132. }
  115133. }
  115134. /* AoTuV */
  115135. /** @ M2 **
  115136. The boost problem by the combination of noise normalization and point stereo is eased.
  115137. However, this is a temporary patch.
  115138. by Aoyumi @ 2004/04/18
  115139. */
  115140. void hf_reduction(vorbis_info_psy_global *g,
  115141. vorbis_look_psy *p,
  115142. vorbis_info_mapping0 *vi,
  115143. float **mdct){
  115144. int i,j,n=p->n, de=0.3*p->m_val;
  115145. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  115146. for(i=0; i<vi->coupling_steps; i++){
  115147. /* for(j=start; j<limit; j++){} // ???*/
  115148. for(j=limit; j<n; j++)
  115149. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  115150. }
  115151. }
  115152. #endif
  115153. /*** End of inlined file: psy.c ***/
  115154. /*** Start of inlined file: registry.c ***/
  115155. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115156. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115157. // tasks..
  115158. #if JUCE_MSVC
  115159. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115160. #endif
  115161. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115162. #if JUCE_USE_OGGVORBIS
  115163. /* seems like major overkill now; the backend numbers will grow into
  115164. the infrastructure soon enough */
  115165. extern vorbis_func_floor floor0_exportbundle;
  115166. extern vorbis_func_floor floor1_exportbundle;
  115167. extern vorbis_func_residue residue0_exportbundle;
  115168. extern vorbis_func_residue residue1_exportbundle;
  115169. extern vorbis_func_residue residue2_exportbundle;
  115170. extern vorbis_func_mapping mapping0_exportbundle;
  115171. vorbis_func_floor *_floor_P[]={
  115172. &floor0_exportbundle,
  115173. &floor1_exportbundle,
  115174. };
  115175. vorbis_func_residue *_residue_P[]={
  115176. &residue0_exportbundle,
  115177. &residue1_exportbundle,
  115178. &residue2_exportbundle,
  115179. };
  115180. vorbis_func_mapping *_mapping_P[]={
  115181. &mapping0_exportbundle,
  115182. };
  115183. #endif
  115184. /*** End of inlined file: registry.c ***/
  115185. /*** Start of inlined file: res0.c ***/
  115186. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  115187. encode/decode loops are coded for clarity and performance is not
  115188. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  115189. it's slow. */
  115190. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115191. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115192. // tasks..
  115193. #if JUCE_MSVC
  115194. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115195. #endif
  115196. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115197. #if JUCE_USE_OGGVORBIS
  115198. #include <stdlib.h>
  115199. #include <string.h>
  115200. #include <math.h>
  115201. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  115202. #include <stdio.h>
  115203. #endif
  115204. typedef struct {
  115205. vorbis_info_residue0 *info;
  115206. int parts;
  115207. int stages;
  115208. codebook *fullbooks;
  115209. codebook *phrasebook;
  115210. codebook ***partbooks;
  115211. int partvals;
  115212. int **decodemap;
  115213. long postbits;
  115214. long phrasebits;
  115215. long frames;
  115216. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  115217. int train_seq;
  115218. long *training_data[8][64];
  115219. float training_max[8][64];
  115220. float training_min[8][64];
  115221. float tmin;
  115222. float tmax;
  115223. #endif
  115224. } vorbis_look_residue0;
  115225. void res0_free_info(vorbis_info_residue *i){
  115226. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  115227. if(info){
  115228. memset(info,0,sizeof(*info));
  115229. _ogg_free(info);
  115230. }
  115231. }
  115232. void res0_free_look(vorbis_look_residue *i){
  115233. int j;
  115234. if(i){
  115235. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  115236. #ifdef TRAIN_RES
  115237. {
  115238. int j,k,l;
  115239. for(j=0;j<look->parts;j++){
  115240. /*fprintf(stderr,"partition %d: ",j);*/
  115241. for(k=0;k<8;k++)
  115242. if(look->training_data[k][j]){
  115243. char buffer[80];
  115244. FILE *of;
  115245. codebook *statebook=look->partbooks[j][k];
  115246. /* long and short into the same bucket by current convention */
  115247. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  115248. of=fopen(buffer,"a");
  115249. for(l=0;l<statebook->entries;l++)
  115250. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  115251. fclose(of);
  115252. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  115253. look->training_min[k][j],look->training_max[k][j]);*/
  115254. _ogg_free(look->training_data[k][j]);
  115255. look->training_data[k][j]=NULL;
  115256. }
  115257. /*fprintf(stderr,"\n");*/
  115258. }
  115259. }
  115260. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  115261. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  115262. (float)look->phrasebits/look->frames,
  115263. (float)look->postbits/look->frames,
  115264. (float)(look->postbits+look->phrasebits)/look->frames);*/
  115265. #endif
  115266. /*vorbis_info_residue0 *info=look->info;
  115267. fprintf(stderr,
  115268. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  115269. "(%g/frame) \n",look->frames,look->phrasebits,
  115270. look->resbitsflat,
  115271. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  115272. for(j=0;j<look->parts;j++){
  115273. long acc=0;
  115274. fprintf(stderr,"\t[%d] == ",j);
  115275. for(k=0;k<look->stages;k++)
  115276. if((info->secondstages[j]>>k)&1){
  115277. fprintf(stderr,"%ld,",look->resbits[j][k]);
  115278. acc+=look->resbits[j][k];
  115279. }
  115280. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  115281. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  115282. }
  115283. fprintf(stderr,"\n");*/
  115284. for(j=0;j<look->parts;j++)
  115285. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  115286. _ogg_free(look->partbooks);
  115287. for(j=0;j<look->partvals;j++)
  115288. _ogg_free(look->decodemap[j]);
  115289. _ogg_free(look->decodemap);
  115290. memset(look,0,sizeof(*look));
  115291. _ogg_free(look);
  115292. }
  115293. }
  115294. static int icount(unsigned int v){
  115295. int ret=0;
  115296. while(v){
  115297. ret+=v&1;
  115298. v>>=1;
  115299. }
  115300. return(ret);
  115301. }
  115302. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  115303. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  115304. int j,acc=0;
  115305. oggpack_write(opb,info->begin,24);
  115306. oggpack_write(opb,info->end,24);
  115307. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  115308. code with a partitioned book */
  115309. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  115310. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  115311. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  115312. bitmask of one indicates this partition class has bits to write
  115313. this pass */
  115314. for(j=0;j<info->partitions;j++){
  115315. if(ilog(info->secondstages[j])>3){
  115316. /* yes, this is a minor hack due to not thinking ahead */
  115317. oggpack_write(opb,info->secondstages[j],3);
  115318. oggpack_write(opb,1,1);
  115319. oggpack_write(opb,info->secondstages[j]>>3,5);
  115320. }else
  115321. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  115322. acc+=icount(info->secondstages[j]);
  115323. }
  115324. for(j=0;j<acc;j++)
  115325. oggpack_write(opb,info->booklist[j],8);
  115326. }
  115327. /* vorbis_info is for range checking */
  115328. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  115329. int j,acc=0;
  115330. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  115331. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115332. info->begin=oggpack_read(opb,24);
  115333. info->end=oggpack_read(opb,24);
  115334. info->grouping=oggpack_read(opb,24)+1;
  115335. info->partitions=oggpack_read(opb,6)+1;
  115336. info->groupbook=oggpack_read(opb,8);
  115337. for(j=0;j<info->partitions;j++){
  115338. int cascade=oggpack_read(opb,3);
  115339. if(oggpack_read(opb,1))
  115340. cascade|=(oggpack_read(opb,5)<<3);
  115341. info->secondstages[j]=cascade;
  115342. acc+=icount(cascade);
  115343. }
  115344. for(j=0;j<acc;j++)
  115345. info->booklist[j]=oggpack_read(opb,8);
  115346. if(info->groupbook>=ci->books)goto errout;
  115347. for(j=0;j<acc;j++)
  115348. if(info->booklist[j]>=ci->books)goto errout;
  115349. return(info);
  115350. errout:
  115351. res0_free_info(info);
  115352. return(NULL);
  115353. }
  115354. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  115355. vorbis_info_residue *vr){
  115356. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  115357. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  115358. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  115359. int j,k,acc=0;
  115360. int dim;
  115361. int maxstage=0;
  115362. look->info=info;
  115363. look->parts=info->partitions;
  115364. look->fullbooks=ci->fullbooks;
  115365. look->phrasebook=ci->fullbooks+info->groupbook;
  115366. dim=look->phrasebook->dim;
  115367. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  115368. for(j=0;j<look->parts;j++){
  115369. int stages=ilog(info->secondstages[j]);
  115370. if(stages){
  115371. if(stages>maxstage)maxstage=stages;
  115372. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  115373. for(k=0;k<stages;k++)
  115374. if(info->secondstages[j]&(1<<k)){
  115375. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  115376. #ifdef TRAIN_RES
  115377. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  115378. sizeof(***look->training_data));
  115379. #endif
  115380. }
  115381. }
  115382. }
  115383. look->partvals=rint(pow((float)look->parts,(float)dim));
  115384. look->stages=maxstage;
  115385. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  115386. for(j=0;j<look->partvals;j++){
  115387. long val=j;
  115388. long mult=look->partvals/look->parts;
  115389. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  115390. for(k=0;k<dim;k++){
  115391. long deco=val/mult;
  115392. val-=deco*mult;
  115393. mult/=look->parts;
  115394. look->decodemap[j][k]=deco;
  115395. }
  115396. }
  115397. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  115398. {
  115399. static int train_seq=0;
  115400. look->train_seq=train_seq++;
  115401. }
  115402. #endif
  115403. return(look);
  115404. }
  115405. /* break an abstraction and copy some code for performance purposes */
  115406. static int local_book_besterror(codebook *book,float *a){
  115407. int dim=book->dim,i,k,o;
  115408. int best=0;
  115409. encode_aux_threshmatch *tt=book->c->thresh_tree;
  115410. /* find the quant val of each scalar */
  115411. for(k=0,o=dim;k<dim;++k){
  115412. float val=a[--o];
  115413. i=tt->threshvals>>1;
  115414. if(val<tt->quantthresh[i]){
  115415. if(val<tt->quantthresh[i-1]){
  115416. for(--i;i>0;--i)
  115417. if(val>=tt->quantthresh[i-1])
  115418. break;
  115419. }
  115420. }else{
  115421. for(++i;i<tt->threshvals-1;++i)
  115422. if(val<tt->quantthresh[i])break;
  115423. }
  115424. best=(best*tt->quantvals)+tt->quantmap[i];
  115425. }
  115426. /* regular lattices are easy :-) */
  115427. if(book->c->lengthlist[best]<=0){
  115428. const static_codebook *c=book->c;
  115429. int i,j;
  115430. float bestf=0.f;
  115431. float *e=book->valuelist;
  115432. best=-1;
  115433. for(i=0;i<book->entries;i++){
  115434. if(c->lengthlist[i]>0){
  115435. float thisx=0.f;
  115436. for(j=0;j<dim;j++){
  115437. float val=(e[j]-a[j]);
  115438. thisx+=val*val;
  115439. }
  115440. if(best==-1 || thisx<bestf){
  115441. bestf=thisx;
  115442. best=i;
  115443. }
  115444. }
  115445. e+=dim;
  115446. }
  115447. }
  115448. {
  115449. float *ptr=book->valuelist+best*dim;
  115450. for(i=0;i<dim;i++)
  115451. *a++ -= *ptr++;
  115452. }
  115453. return(best);
  115454. }
  115455. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  115456. codebook *book,long *acc){
  115457. int i,bits=0;
  115458. int dim=book->dim;
  115459. int step=n/dim;
  115460. for(i=0;i<step;i++){
  115461. int entry=local_book_besterror(book,vec+i*dim);
  115462. #ifdef TRAIN_RES
  115463. acc[entry]++;
  115464. #endif
  115465. bits+=vorbis_book_encode(book,entry,opb);
  115466. }
  115467. return(bits);
  115468. }
  115469. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  115470. float **in,int ch){
  115471. long i,j,k;
  115472. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  115473. vorbis_info_residue0 *info=look->info;
  115474. /* move all this setup out later */
  115475. int samples_per_partition=info->grouping;
  115476. int possible_partitions=info->partitions;
  115477. int n=info->end-info->begin;
  115478. int partvals=n/samples_per_partition;
  115479. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  115480. float scale=100./samples_per_partition;
  115481. /* we find the partition type for each partition of each
  115482. channel. We'll go back and do the interleaved encoding in a
  115483. bit. For now, clarity */
  115484. for(i=0;i<ch;i++){
  115485. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  115486. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  115487. }
  115488. for(i=0;i<partvals;i++){
  115489. int offset=i*samples_per_partition+info->begin;
  115490. for(j=0;j<ch;j++){
  115491. float max=0.;
  115492. float ent=0.;
  115493. for(k=0;k<samples_per_partition;k++){
  115494. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  115495. ent+=fabs(rint(in[j][offset+k]));
  115496. }
  115497. ent*=scale;
  115498. for(k=0;k<possible_partitions-1;k++)
  115499. if(max<=info->classmetric1[k] &&
  115500. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  115501. break;
  115502. partword[j][i]=k;
  115503. }
  115504. }
  115505. #ifdef TRAIN_RESAUX
  115506. {
  115507. FILE *of;
  115508. char buffer[80];
  115509. for(i=0;i<ch;i++){
  115510. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  115511. of=fopen(buffer,"a");
  115512. for(j=0;j<partvals;j++)
  115513. fprintf(of,"%ld, ",partword[i][j]);
  115514. fprintf(of,"\n");
  115515. fclose(of);
  115516. }
  115517. }
  115518. #endif
  115519. look->frames++;
  115520. return(partword);
  115521. }
  115522. /* designed for stereo or other modes where the partition size is an
  115523. integer multiple of the number of channels encoded in the current
  115524. submap */
  115525. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  115526. int ch){
  115527. long i,j,k,l;
  115528. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  115529. vorbis_info_residue0 *info=look->info;
  115530. /* move all this setup out later */
  115531. int samples_per_partition=info->grouping;
  115532. int possible_partitions=info->partitions;
  115533. int n=info->end-info->begin;
  115534. int partvals=n/samples_per_partition;
  115535. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  115536. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  115537. FILE *of;
  115538. char buffer[80];
  115539. #endif
  115540. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  115541. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  115542. for(i=0,l=info->begin/ch;i<partvals;i++){
  115543. float magmax=0.f;
  115544. float angmax=0.f;
  115545. for(j=0;j<samples_per_partition;j+=ch){
  115546. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  115547. for(k=1;k<ch;k++)
  115548. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  115549. l++;
  115550. }
  115551. for(j=0;j<possible_partitions-1;j++)
  115552. if(magmax<=info->classmetric1[j] &&
  115553. angmax<=info->classmetric2[j])
  115554. break;
  115555. partword[0][i]=j;
  115556. }
  115557. #ifdef TRAIN_RESAUX
  115558. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  115559. of=fopen(buffer,"a");
  115560. for(i=0;i<partvals;i++)
  115561. fprintf(of,"%ld, ",partword[0][i]);
  115562. fprintf(of,"\n");
  115563. fclose(of);
  115564. #endif
  115565. look->frames++;
  115566. return(partword);
  115567. }
  115568. static int _01forward(oggpack_buffer *opb,
  115569. vorbis_block *vb,vorbis_look_residue *vl,
  115570. float **in,int ch,
  115571. long **partword,
  115572. int (*encode)(oggpack_buffer *,float *,int,
  115573. codebook *,long *)){
  115574. long i,j,k,s;
  115575. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  115576. vorbis_info_residue0 *info=look->info;
  115577. /* move all this setup out later */
  115578. int samples_per_partition=info->grouping;
  115579. int possible_partitions=info->partitions;
  115580. int partitions_per_word=look->phrasebook->dim;
  115581. int n=info->end-info->begin;
  115582. int partvals=n/samples_per_partition;
  115583. long resbits[128];
  115584. long resvals[128];
  115585. #ifdef TRAIN_RES
  115586. for(i=0;i<ch;i++)
  115587. for(j=info->begin;j<info->end;j++){
  115588. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  115589. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  115590. }
  115591. #endif
  115592. memset(resbits,0,sizeof(resbits));
  115593. memset(resvals,0,sizeof(resvals));
  115594. /* we code the partition words for each channel, then the residual
  115595. words for a partition per channel until we've written all the
  115596. residual words for that partition word. Then write the next
  115597. partition channel words... */
  115598. for(s=0;s<look->stages;s++){
  115599. for(i=0;i<partvals;){
  115600. /* first we encode a partition codeword for each channel */
  115601. if(s==0){
  115602. for(j=0;j<ch;j++){
  115603. long val=partword[j][i];
  115604. for(k=1;k<partitions_per_word;k++){
  115605. val*=possible_partitions;
  115606. if(i+k<partvals)
  115607. val+=partword[j][i+k];
  115608. }
  115609. /* training hack */
  115610. if(val<look->phrasebook->entries)
  115611. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  115612. #if 0 /*def TRAIN_RES*/
  115613. else
  115614. fprintf(stderr,"!");
  115615. #endif
  115616. }
  115617. }
  115618. /* now we encode interleaved residual values for the partitions */
  115619. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  115620. long offset=i*samples_per_partition+info->begin;
  115621. for(j=0;j<ch;j++){
  115622. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  115623. if(info->secondstages[partword[j][i]]&(1<<s)){
  115624. codebook *statebook=look->partbooks[partword[j][i]][s];
  115625. if(statebook){
  115626. int ret;
  115627. long *accumulator=NULL;
  115628. #ifdef TRAIN_RES
  115629. accumulator=look->training_data[s][partword[j][i]];
  115630. {
  115631. int l;
  115632. float *samples=in[j]+offset;
  115633. for(l=0;l<samples_per_partition;l++){
  115634. if(samples[l]<look->training_min[s][partword[j][i]])
  115635. look->training_min[s][partword[j][i]]=samples[l];
  115636. if(samples[l]>look->training_max[s][partword[j][i]])
  115637. look->training_max[s][partword[j][i]]=samples[l];
  115638. }
  115639. }
  115640. #endif
  115641. ret=encode(opb,in[j]+offset,samples_per_partition,
  115642. statebook,accumulator);
  115643. look->postbits+=ret;
  115644. resbits[partword[j][i]]+=ret;
  115645. }
  115646. }
  115647. }
  115648. }
  115649. }
  115650. }
  115651. /*{
  115652. long total=0;
  115653. long totalbits=0;
  115654. fprintf(stderr,"%d :: ",vb->mode);
  115655. for(k=0;k<possible_partitions;k++){
  115656. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  115657. total+=resvals[k];
  115658. totalbits+=resbits[k];
  115659. }
  115660. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  115661. }*/
  115662. return(0);
  115663. }
  115664. /* a truncated packet here just means 'stop working'; it's not an error */
  115665. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  115666. float **in,int ch,
  115667. long (*decodepart)(codebook *, float *,
  115668. oggpack_buffer *,int)){
  115669. long i,j,k,l,s;
  115670. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  115671. vorbis_info_residue0 *info=look->info;
  115672. /* move all this setup out later */
  115673. int samples_per_partition=info->grouping;
  115674. int partitions_per_word=look->phrasebook->dim;
  115675. int n=info->end-info->begin;
  115676. int partvals=n/samples_per_partition;
  115677. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  115678. int ***partword=(int***)alloca(ch*sizeof(*partword));
  115679. for(j=0;j<ch;j++)
  115680. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  115681. for(s=0;s<look->stages;s++){
  115682. /* each loop decodes on partition codeword containing
  115683. partitions_pre_word partitions */
  115684. for(i=0,l=0;i<partvals;l++){
  115685. if(s==0){
  115686. /* fetch the partition word for each channel */
  115687. for(j=0;j<ch;j++){
  115688. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  115689. if(temp==-1)goto eopbreak;
  115690. partword[j][l]=look->decodemap[temp];
  115691. if(partword[j][l]==NULL)goto errout;
  115692. }
  115693. }
  115694. /* now we decode residual values for the partitions */
  115695. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  115696. for(j=0;j<ch;j++){
  115697. long offset=info->begin+i*samples_per_partition;
  115698. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  115699. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  115700. if(stagebook){
  115701. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  115702. samples_per_partition)==-1)goto eopbreak;
  115703. }
  115704. }
  115705. }
  115706. }
  115707. }
  115708. errout:
  115709. eopbreak:
  115710. return(0);
  115711. }
  115712. #if 0
  115713. /* residue 0 and 1 are just slight variants of one another. 0 is
  115714. interleaved, 1 is not */
  115715. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  115716. float **in,int *nonzero,int ch){
  115717. /* we encode only the nonzero parts of a bundle */
  115718. int i,used=0;
  115719. for(i=0;i<ch;i++)
  115720. if(nonzero[i])
  115721. in[used++]=in[i];
  115722. if(used)
  115723. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  115724. return(_01class(vb,vl,in,used));
  115725. else
  115726. return(0);
  115727. }
  115728. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  115729. float **in,float **out,int *nonzero,int ch,
  115730. long **partword){
  115731. /* we encode only the nonzero parts of a bundle */
  115732. int i,j,used=0,n=vb->pcmend/2;
  115733. for(i=0;i<ch;i++)
  115734. if(nonzero[i]){
  115735. if(out)
  115736. for(j=0;j<n;j++)
  115737. out[i][j]+=in[i][j];
  115738. in[used++]=in[i];
  115739. }
  115740. if(used){
  115741. int ret=_01forward(vb,vl,in,used,partword,
  115742. _interleaved_encodepart);
  115743. if(out){
  115744. used=0;
  115745. for(i=0;i<ch;i++)
  115746. if(nonzero[i]){
  115747. for(j=0;j<n;j++)
  115748. out[i][j]-=in[used][j];
  115749. used++;
  115750. }
  115751. }
  115752. return(ret);
  115753. }else{
  115754. return(0);
  115755. }
  115756. }
  115757. #endif
  115758. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  115759. float **in,int *nonzero,int ch){
  115760. int i,used=0;
  115761. for(i=0;i<ch;i++)
  115762. if(nonzero[i])
  115763. in[used++]=in[i];
  115764. if(used)
  115765. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  115766. else
  115767. return(0);
  115768. }
  115769. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  115770. float **in,float **out,int *nonzero,int ch,
  115771. long **partword){
  115772. int i,j,used=0,n=vb->pcmend/2;
  115773. for(i=0;i<ch;i++)
  115774. if(nonzero[i]){
  115775. if(out)
  115776. for(j=0;j<n;j++)
  115777. out[i][j]+=in[i][j];
  115778. in[used++]=in[i];
  115779. }
  115780. if(used){
  115781. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  115782. if(out){
  115783. used=0;
  115784. for(i=0;i<ch;i++)
  115785. if(nonzero[i]){
  115786. for(j=0;j<n;j++)
  115787. out[i][j]-=in[used][j];
  115788. used++;
  115789. }
  115790. }
  115791. return(ret);
  115792. }else{
  115793. return(0);
  115794. }
  115795. }
  115796. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  115797. float **in,int *nonzero,int ch){
  115798. int i,used=0;
  115799. for(i=0;i<ch;i++)
  115800. if(nonzero[i])
  115801. in[used++]=in[i];
  115802. if(used)
  115803. return(_01class(vb,vl,in,used));
  115804. else
  115805. return(0);
  115806. }
  115807. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  115808. float **in,int *nonzero,int ch){
  115809. int i,used=0;
  115810. for(i=0;i<ch;i++)
  115811. if(nonzero[i])
  115812. in[used++]=in[i];
  115813. if(used)
  115814. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  115815. else
  115816. return(0);
  115817. }
  115818. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  115819. float **in,int *nonzero,int ch){
  115820. int i,used=0;
  115821. for(i=0;i<ch;i++)
  115822. if(nonzero[i])used++;
  115823. if(used)
  115824. return(_2class(vb,vl,in,ch));
  115825. else
  115826. return(0);
  115827. }
  115828. /* res2 is slightly more different; all the channels are interleaved
  115829. into a single vector and encoded. */
  115830. int res2_forward(oggpack_buffer *opb,
  115831. vorbis_block *vb,vorbis_look_residue *vl,
  115832. float **in,float **out,int *nonzero,int ch,
  115833. long **partword){
  115834. long i,j,k,n=vb->pcmend/2,used=0;
  115835. /* don't duplicate the code; use a working vector hack for now and
  115836. reshape ourselves into a single channel res1 */
  115837. /* ugly; reallocs for each coupling pass :-( */
  115838. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  115839. for(i=0;i<ch;i++){
  115840. float *pcm=in[i];
  115841. if(nonzero[i])used++;
  115842. for(j=0,k=i;j<n;j++,k+=ch)
  115843. work[k]=pcm[j];
  115844. }
  115845. if(used){
  115846. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  115847. /* update the sofar vector */
  115848. if(out){
  115849. for(i=0;i<ch;i++){
  115850. float *pcm=in[i];
  115851. float *sofar=out[i];
  115852. for(j=0,k=i;j<n;j++,k+=ch)
  115853. sofar[j]+=pcm[j]-work[k];
  115854. }
  115855. }
  115856. return(ret);
  115857. }else{
  115858. return(0);
  115859. }
  115860. }
  115861. /* duplicate code here as speed is somewhat more important */
  115862. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  115863. float **in,int *nonzero,int ch){
  115864. long i,k,l,s;
  115865. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  115866. vorbis_info_residue0 *info=look->info;
  115867. /* move all this setup out later */
  115868. int samples_per_partition=info->grouping;
  115869. int partitions_per_word=look->phrasebook->dim;
  115870. int n=info->end-info->begin;
  115871. int partvals=n/samples_per_partition;
  115872. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  115873. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  115874. for(i=0;i<ch;i++)if(nonzero[i])break;
  115875. if(i==ch)return(0); /* no nonzero vectors */
  115876. for(s=0;s<look->stages;s++){
  115877. for(i=0,l=0;i<partvals;l++){
  115878. if(s==0){
  115879. /* fetch the partition word */
  115880. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  115881. if(temp==-1)goto eopbreak;
  115882. partword[l]=look->decodemap[temp];
  115883. if(partword[l]==NULL)goto errout;
  115884. }
  115885. /* now we decode residual values for the partitions */
  115886. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  115887. if(info->secondstages[partword[l][k]]&(1<<s)){
  115888. codebook *stagebook=look->partbooks[partword[l][k]][s];
  115889. if(stagebook){
  115890. if(vorbis_book_decodevv_add(stagebook,in,
  115891. i*samples_per_partition+info->begin,ch,
  115892. &vb->opb,samples_per_partition)==-1)
  115893. goto eopbreak;
  115894. }
  115895. }
  115896. }
  115897. }
  115898. errout:
  115899. eopbreak:
  115900. return(0);
  115901. }
  115902. vorbis_func_residue residue0_exportbundle={
  115903. NULL,
  115904. &res0_unpack,
  115905. &res0_look,
  115906. &res0_free_info,
  115907. &res0_free_look,
  115908. NULL,
  115909. NULL,
  115910. &res0_inverse
  115911. };
  115912. vorbis_func_residue residue1_exportbundle={
  115913. &res0_pack,
  115914. &res0_unpack,
  115915. &res0_look,
  115916. &res0_free_info,
  115917. &res0_free_look,
  115918. &res1_class,
  115919. &res1_forward,
  115920. &res1_inverse
  115921. };
  115922. vorbis_func_residue residue2_exportbundle={
  115923. &res0_pack,
  115924. &res0_unpack,
  115925. &res0_look,
  115926. &res0_free_info,
  115927. &res0_free_look,
  115928. &res2_class,
  115929. &res2_forward,
  115930. &res2_inverse
  115931. };
  115932. #endif
  115933. /*** End of inlined file: res0.c ***/
  115934. /*** Start of inlined file: sharedbook.c ***/
  115935. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115936. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115937. // tasks..
  115938. #if JUCE_MSVC
  115939. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115940. #endif
  115941. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115942. #if JUCE_USE_OGGVORBIS
  115943. #include <stdlib.h>
  115944. #include <math.h>
  115945. #include <string.h>
  115946. /**** pack/unpack helpers ******************************************/
  115947. int _ilog(unsigned int v){
  115948. int ret=0;
  115949. while(v){
  115950. ret++;
  115951. v>>=1;
  115952. }
  115953. return(ret);
  115954. }
  115955. /* 32 bit float (not IEEE; nonnormalized mantissa +
  115956. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  115957. Why not IEEE? It's just not that important here. */
  115958. #define VQ_FEXP 10
  115959. #define VQ_FMAN 21
  115960. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  115961. /* doesn't currently guard under/overflow */
  115962. long _float32_pack(float val){
  115963. int sign=0;
  115964. long exp;
  115965. long mant;
  115966. if(val<0){
  115967. sign=0x80000000;
  115968. val= -val;
  115969. }
  115970. exp= floor(log(val)/log(2.f));
  115971. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  115972. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  115973. return(sign|exp|mant);
  115974. }
  115975. float _float32_unpack(long val){
  115976. double mant=val&0x1fffff;
  115977. int sign=val&0x80000000;
  115978. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  115979. if(sign)mant= -mant;
  115980. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  115981. }
  115982. /* given a list of word lengths, generate a list of codewords. Works
  115983. for length ordered or unordered, always assigns the lowest valued
  115984. codewords first. Extended to handle unused entries (length 0) */
  115985. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  115986. long i,j,count=0;
  115987. ogg_uint32_t marker[33];
  115988. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  115989. memset(marker,0,sizeof(marker));
  115990. for(i=0;i<n;i++){
  115991. long length=l[i];
  115992. if(length>0){
  115993. ogg_uint32_t entry=marker[length];
  115994. /* when we claim a node for an entry, we also claim the nodes
  115995. below it (pruning off the imagined tree that may have dangled
  115996. from it) as well as blocking the use of any nodes directly
  115997. above for leaves */
  115998. /* update ourself */
  115999. if(length<32 && (entry>>length)){
  116000. /* error condition; the lengths must specify an overpopulated tree */
  116001. _ogg_free(r);
  116002. return(NULL);
  116003. }
  116004. r[count++]=entry;
  116005. /* Look to see if the next shorter marker points to the node
  116006. above. if so, update it and repeat. */
  116007. {
  116008. for(j=length;j>0;j--){
  116009. if(marker[j]&1){
  116010. /* have to jump branches */
  116011. if(j==1)
  116012. marker[1]++;
  116013. else
  116014. marker[j]=marker[j-1]<<1;
  116015. break; /* invariant says next upper marker would already
  116016. have been moved if it was on the same path */
  116017. }
  116018. marker[j]++;
  116019. }
  116020. }
  116021. /* prune the tree; the implicit invariant says all the longer
  116022. markers were dangling from our just-taken node. Dangle them
  116023. from our *new* node. */
  116024. for(j=length+1;j<33;j++)
  116025. if((marker[j]>>1) == entry){
  116026. entry=marker[j];
  116027. marker[j]=marker[j-1]<<1;
  116028. }else
  116029. break;
  116030. }else
  116031. if(sparsecount==0)count++;
  116032. }
  116033. /* bitreverse the words because our bitwise packer/unpacker is LSb
  116034. endian */
  116035. for(i=0,count=0;i<n;i++){
  116036. ogg_uint32_t temp=0;
  116037. for(j=0;j<l[i];j++){
  116038. temp<<=1;
  116039. temp|=(r[count]>>j)&1;
  116040. }
  116041. if(sparsecount){
  116042. if(l[i])
  116043. r[count++]=temp;
  116044. }else
  116045. r[count++]=temp;
  116046. }
  116047. return(r);
  116048. }
  116049. /* there might be a straightforward one-line way to do the below
  116050. that's portable and totally safe against roundoff, but I haven't
  116051. thought of it. Therefore, we opt on the side of caution */
  116052. long _book_maptype1_quantvals(const static_codebook *b){
  116053. long vals=floor(pow((float)b->entries,1.f/b->dim));
  116054. /* the above *should* be reliable, but we'll not assume that FP is
  116055. ever reliable when bitstream sync is at stake; verify via integer
  116056. means that vals really is the greatest value of dim for which
  116057. vals^b->bim <= b->entries */
  116058. /* treat the above as an initial guess */
  116059. while(1){
  116060. long acc=1;
  116061. long acc1=1;
  116062. int i;
  116063. for(i=0;i<b->dim;i++){
  116064. acc*=vals;
  116065. acc1*=vals+1;
  116066. }
  116067. if(acc<=b->entries && acc1>b->entries){
  116068. return(vals);
  116069. }else{
  116070. if(acc>b->entries){
  116071. vals--;
  116072. }else{
  116073. vals++;
  116074. }
  116075. }
  116076. }
  116077. }
  116078. /* unpack the quantized list of values for encode/decode ***********/
  116079. /* we need to deal with two map types: in map type 1, the values are
  116080. generated algorithmically (each column of the vector counts through
  116081. the values in the quant vector). in map type 2, all the values came
  116082. in in an explicit list. Both value lists must be unpacked */
  116083. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  116084. long j,k,count=0;
  116085. if(b->maptype==1 || b->maptype==2){
  116086. int quantvals;
  116087. float mindel=_float32_unpack(b->q_min);
  116088. float delta=_float32_unpack(b->q_delta);
  116089. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  116090. /* maptype 1 and 2 both use a quantized value vector, but
  116091. different sizes */
  116092. switch(b->maptype){
  116093. case 1:
  116094. /* most of the time, entries%dimensions == 0, but we need to be
  116095. well defined. We define that the possible vales at each
  116096. scalar is values == entries/dim. If entries%dim != 0, we'll
  116097. have 'too few' values (values*dim<entries), which means that
  116098. we'll have 'left over' entries; left over entries use zeroed
  116099. values (and are wasted). So don't generate codebooks like
  116100. that */
  116101. quantvals=_book_maptype1_quantvals(b);
  116102. for(j=0;j<b->entries;j++){
  116103. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  116104. float last=0.f;
  116105. int indexdiv=1;
  116106. for(k=0;k<b->dim;k++){
  116107. int index= (j/indexdiv)%quantvals;
  116108. float val=b->quantlist[index];
  116109. val=fabs(val)*delta+mindel+last;
  116110. if(b->q_sequencep)last=val;
  116111. if(sparsemap)
  116112. r[sparsemap[count]*b->dim+k]=val;
  116113. else
  116114. r[count*b->dim+k]=val;
  116115. indexdiv*=quantvals;
  116116. }
  116117. count++;
  116118. }
  116119. }
  116120. break;
  116121. case 2:
  116122. for(j=0;j<b->entries;j++){
  116123. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  116124. float last=0.f;
  116125. for(k=0;k<b->dim;k++){
  116126. float val=b->quantlist[j*b->dim+k];
  116127. val=fabs(val)*delta+mindel+last;
  116128. if(b->q_sequencep)last=val;
  116129. if(sparsemap)
  116130. r[sparsemap[count]*b->dim+k]=val;
  116131. else
  116132. r[count*b->dim+k]=val;
  116133. }
  116134. count++;
  116135. }
  116136. }
  116137. break;
  116138. }
  116139. return(r);
  116140. }
  116141. return(NULL);
  116142. }
  116143. void vorbis_staticbook_clear(static_codebook *b){
  116144. if(b->allocedp){
  116145. if(b->quantlist)_ogg_free(b->quantlist);
  116146. if(b->lengthlist)_ogg_free(b->lengthlist);
  116147. if(b->nearest_tree){
  116148. _ogg_free(b->nearest_tree->ptr0);
  116149. _ogg_free(b->nearest_tree->ptr1);
  116150. _ogg_free(b->nearest_tree->p);
  116151. _ogg_free(b->nearest_tree->q);
  116152. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  116153. _ogg_free(b->nearest_tree);
  116154. }
  116155. if(b->thresh_tree){
  116156. _ogg_free(b->thresh_tree->quantthresh);
  116157. _ogg_free(b->thresh_tree->quantmap);
  116158. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  116159. _ogg_free(b->thresh_tree);
  116160. }
  116161. memset(b,0,sizeof(*b));
  116162. }
  116163. }
  116164. void vorbis_staticbook_destroy(static_codebook *b){
  116165. if(b->allocedp){
  116166. vorbis_staticbook_clear(b);
  116167. _ogg_free(b);
  116168. }
  116169. }
  116170. void vorbis_book_clear(codebook *b){
  116171. /* static book is not cleared; we're likely called on the lookup and
  116172. the static codebook belongs to the info struct */
  116173. if(b->valuelist)_ogg_free(b->valuelist);
  116174. if(b->codelist)_ogg_free(b->codelist);
  116175. if(b->dec_index)_ogg_free(b->dec_index);
  116176. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  116177. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  116178. memset(b,0,sizeof(*b));
  116179. }
  116180. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  116181. memset(c,0,sizeof(*c));
  116182. c->c=s;
  116183. c->entries=s->entries;
  116184. c->used_entries=s->entries;
  116185. c->dim=s->dim;
  116186. c->codelist=_make_words(s->lengthlist,s->entries,0);
  116187. c->valuelist=_book_unquantize(s,s->entries,NULL);
  116188. return(0);
  116189. }
  116190. static int sort32a(const void *a,const void *b){
  116191. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  116192. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  116193. }
  116194. /* decode codebook arrangement is more heavily optimized than encode */
  116195. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  116196. int i,j,n=0,tabn;
  116197. int *sortindex;
  116198. memset(c,0,sizeof(*c));
  116199. /* count actually used entries */
  116200. for(i=0;i<s->entries;i++)
  116201. if(s->lengthlist[i]>0)
  116202. n++;
  116203. c->entries=s->entries;
  116204. c->used_entries=n;
  116205. c->dim=s->dim;
  116206. /* two different remappings go on here.
  116207. First, we collapse the likely sparse codebook down only to
  116208. actually represented values/words. This collapsing needs to be
  116209. indexed as map-valueless books are used to encode original entry
  116210. positions as integers.
  116211. Second, we reorder all vectors, including the entry index above,
  116212. by sorted bitreversed codeword to allow treeless decode. */
  116213. {
  116214. /* perform sort */
  116215. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  116216. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  116217. if(codes==NULL)goto err_out;
  116218. for(i=0;i<n;i++){
  116219. codes[i]=ogg_bitreverse(codes[i]);
  116220. codep[i]=codes+i;
  116221. }
  116222. qsort(codep,n,sizeof(*codep),sort32a);
  116223. sortindex=(int*)alloca(n*sizeof(*sortindex));
  116224. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  116225. /* the index is a reverse index */
  116226. for(i=0;i<n;i++){
  116227. int position=codep[i]-codes;
  116228. sortindex[position]=i;
  116229. }
  116230. for(i=0;i<n;i++)
  116231. c->codelist[sortindex[i]]=codes[i];
  116232. _ogg_free(codes);
  116233. }
  116234. c->valuelist=_book_unquantize(s,n,sortindex);
  116235. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  116236. for(n=0,i=0;i<s->entries;i++)
  116237. if(s->lengthlist[i]>0)
  116238. c->dec_index[sortindex[n++]]=i;
  116239. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  116240. for(n=0,i=0;i<s->entries;i++)
  116241. if(s->lengthlist[i]>0)
  116242. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  116243. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  116244. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  116245. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  116246. tabn=1<<c->dec_firsttablen;
  116247. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  116248. c->dec_maxlength=0;
  116249. for(i=0;i<n;i++){
  116250. if(c->dec_maxlength<c->dec_codelengths[i])
  116251. c->dec_maxlength=c->dec_codelengths[i];
  116252. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  116253. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  116254. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  116255. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  116256. }
  116257. }
  116258. /* now fill in 'unused' entries in the firsttable with hi/lo search
  116259. hints for the non-direct-hits */
  116260. {
  116261. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  116262. long lo=0,hi=0;
  116263. for(i=0;i<tabn;i++){
  116264. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  116265. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  116266. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  116267. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  116268. /* we only actually have 15 bits per hint to play with here.
  116269. In order to overflow gracefully (nothing breaks, efficiency
  116270. just drops), encode as the difference from the extremes. */
  116271. {
  116272. unsigned long loval=lo;
  116273. unsigned long hival=n-hi;
  116274. if(loval>0x7fff)loval=0x7fff;
  116275. if(hival>0x7fff)hival=0x7fff;
  116276. c->dec_firsttable[ogg_bitreverse(word)]=
  116277. 0x80000000UL | (loval<<15) | hival;
  116278. }
  116279. }
  116280. }
  116281. }
  116282. return(0);
  116283. err_out:
  116284. vorbis_book_clear(c);
  116285. return(-1);
  116286. }
  116287. static float _dist(int el,float *ref, float *b,int step){
  116288. int i;
  116289. float acc=0.f;
  116290. for(i=0;i<el;i++){
  116291. float val=(ref[i]-b[i*step]);
  116292. acc+=val*val;
  116293. }
  116294. return(acc);
  116295. }
  116296. int _best(codebook *book, float *a, int step){
  116297. encode_aux_threshmatch *tt=book->c->thresh_tree;
  116298. #if 0
  116299. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  116300. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  116301. #endif
  116302. int dim=book->dim;
  116303. int k,o;
  116304. /*int savebest=-1;
  116305. float saverr;*/
  116306. /* do we have a threshhold encode hint? */
  116307. if(tt){
  116308. int index=0,i;
  116309. /* find the quant val of each scalar */
  116310. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  116311. i=tt->threshvals>>1;
  116312. if(a[o]<tt->quantthresh[i]){
  116313. for(;i>0;i--)
  116314. if(a[o]>=tt->quantthresh[i-1])
  116315. break;
  116316. }else{
  116317. for(i++;i<tt->threshvals-1;i++)
  116318. if(a[o]<tt->quantthresh[i])break;
  116319. }
  116320. index=(index*tt->quantvals)+tt->quantmap[i];
  116321. }
  116322. /* regular lattices are easy :-) */
  116323. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  116324. use a decision tree after all
  116325. and fall through*/
  116326. return(index);
  116327. }
  116328. #if 0
  116329. /* do we have a pigeonhole encode hint? */
  116330. if(pt){
  116331. const static_codebook *c=book->c;
  116332. int i,besti=-1;
  116333. float best=0.f;
  116334. int entry=0;
  116335. /* dealing with sequentialness is a pain in the ass */
  116336. if(c->q_sequencep){
  116337. int pv;
  116338. long mul=1;
  116339. float qlast=0;
  116340. for(k=0,o=0;k<dim;k++,o+=step){
  116341. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  116342. if(pv<0 || pv>=pt->mapentries)break;
  116343. entry+=pt->pigeonmap[pv]*mul;
  116344. mul*=pt->quantvals;
  116345. qlast+=pv*pt->del+pt->min;
  116346. }
  116347. }else{
  116348. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  116349. int pv=(int)((a[o]-pt->min)/pt->del);
  116350. if(pv<0 || pv>=pt->mapentries)break;
  116351. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  116352. }
  116353. }
  116354. /* must be within the pigeonholable range; if we quant outside (or
  116355. in an entry that we define no list for), brute force it */
  116356. if(k==dim && pt->fitlength[entry]){
  116357. /* search the abbreviated list */
  116358. long *list=pt->fitlist+pt->fitmap[entry];
  116359. for(i=0;i<pt->fitlength[entry];i++){
  116360. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  116361. if(besti==-1 || this<best){
  116362. best=this;
  116363. besti=list[i];
  116364. }
  116365. }
  116366. return(besti);
  116367. }
  116368. }
  116369. if(nt){
  116370. /* optimized using the decision tree */
  116371. while(1){
  116372. float c=0.f;
  116373. float *p=book->valuelist+nt->p[ptr];
  116374. float *q=book->valuelist+nt->q[ptr];
  116375. for(k=0,o=0;k<dim;k++,o+=step)
  116376. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  116377. if(c>0.f) /* in A */
  116378. ptr= -nt->ptr0[ptr];
  116379. else /* in B */
  116380. ptr= -nt->ptr1[ptr];
  116381. if(ptr<=0)break;
  116382. }
  116383. return(-ptr);
  116384. }
  116385. #endif
  116386. /* brute force it! */
  116387. {
  116388. const static_codebook *c=book->c;
  116389. int i,besti=-1;
  116390. float best=0.f;
  116391. float *e=book->valuelist;
  116392. for(i=0;i<book->entries;i++){
  116393. if(c->lengthlist[i]>0){
  116394. float thisx=_dist(dim,e,a,step);
  116395. if(besti==-1 || thisx<best){
  116396. best=thisx;
  116397. besti=i;
  116398. }
  116399. }
  116400. e+=dim;
  116401. }
  116402. /*if(savebest!=-1 && savebest!=besti){
  116403. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  116404. "original:");
  116405. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  116406. fprintf(stderr,"\n"
  116407. "pigeonhole (entry %d, err %g):",savebest,saverr);
  116408. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  116409. (book->valuelist+savebest*dim)[i]);
  116410. fprintf(stderr,"\n"
  116411. "bruteforce (entry %d, err %g):",besti,best);
  116412. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  116413. (book->valuelist+besti*dim)[i]);
  116414. fprintf(stderr,"\n");
  116415. }*/
  116416. return(besti);
  116417. }
  116418. }
  116419. long vorbis_book_codeword(codebook *book,int entry){
  116420. if(book->c) /* only use with encode; decode optimizations are
  116421. allowed to break this */
  116422. return book->codelist[entry];
  116423. return -1;
  116424. }
  116425. long vorbis_book_codelen(codebook *book,int entry){
  116426. if(book->c) /* only use with encode; decode optimizations are
  116427. allowed to break this */
  116428. return book->c->lengthlist[entry];
  116429. return -1;
  116430. }
  116431. #ifdef _V_SELFTEST
  116432. /* Unit tests of the dequantizer; this stuff will be OK
  116433. cross-platform, I simply want to be sure that special mapping cases
  116434. actually work properly; a bug could go unnoticed for a while */
  116435. #include <stdio.h>
  116436. /* cases:
  116437. no mapping
  116438. full, explicit mapping
  116439. algorithmic mapping
  116440. nonsequential
  116441. sequential
  116442. */
  116443. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  116444. static long partial_quantlist1[]={0,7,2};
  116445. /* no mapping */
  116446. static_codebook test1={
  116447. 4,16,
  116448. NULL,
  116449. 0,
  116450. 0,0,0,0,
  116451. NULL,
  116452. NULL,NULL
  116453. };
  116454. static float *test1_result=NULL;
  116455. /* linear, full mapping, nonsequential */
  116456. static_codebook test2={
  116457. 4,3,
  116458. NULL,
  116459. 2,
  116460. -533200896,1611661312,4,0,
  116461. full_quantlist1,
  116462. NULL,NULL
  116463. };
  116464. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  116465. /* linear, full mapping, sequential */
  116466. static_codebook test3={
  116467. 4,3,
  116468. NULL,
  116469. 2,
  116470. -533200896,1611661312,4,1,
  116471. full_quantlist1,
  116472. NULL,NULL
  116473. };
  116474. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  116475. /* linear, algorithmic mapping, nonsequential */
  116476. static_codebook test4={
  116477. 3,27,
  116478. NULL,
  116479. 1,
  116480. -533200896,1611661312,4,0,
  116481. partial_quantlist1,
  116482. NULL,NULL
  116483. };
  116484. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  116485. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  116486. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  116487. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  116488. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  116489. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  116490. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  116491. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  116492. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  116493. /* linear, algorithmic mapping, sequential */
  116494. static_codebook test5={
  116495. 3,27,
  116496. NULL,
  116497. 1,
  116498. -533200896,1611661312,4,1,
  116499. partial_quantlist1,
  116500. NULL,NULL
  116501. };
  116502. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  116503. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  116504. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  116505. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  116506. -3, 1, 5, 4, 8,12, -1, 3, 7,
  116507. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  116508. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  116509. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  116510. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  116511. void run_test(static_codebook *b,float *comp){
  116512. float *out=_book_unquantize(b,b->entries,NULL);
  116513. int i;
  116514. if(comp){
  116515. if(!out){
  116516. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  116517. exit(1);
  116518. }
  116519. for(i=0;i<b->entries*b->dim;i++)
  116520. if(fabs(out[i]-comp[i])>.0001){
  116521. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  116522. "position %d, %g != %g\n",i,out[i],comp[i]);
  116523. exit(1);
  116524. }
  116525. }else{
  116526. if(out){
  116527. fprintf(stderr,"_book_unquantize returned a value array: \n"
  116528. " correct result should have been NULL\n");
  116529. exit(1);
  116530. }
  116531. }
  116532. }
  116533. int main(){
  116534. /* run the nine dequant tests, and compare to the hand-rolled results */
  116535. fprintf(stderr,"Dequant test 1... ");
  116536. run_test(&test1,test1_result);
  116537. fprintf(stderr,"OK\nDequant test 2... ");
  116538. run_test(&test2,test2_result);
  116539. fprintf(stderr,"OK\nDequant test 3... ");
  116540. run_test(&test3,test3_result);
  116541. fprintf(stderr,"OK\nDequant test 4... ");
  116542. run_test(&test4,test4_result);
  116543. fprintf(stderr,"OK\nDequant test 5... ");
  116544. run_test(&test5,test5_result);
  116545. fprintf(stderr,"OK\n\n");
  116546. return(0);
  116547. }
  116548. #endif
  116549. #endif
  116550. /*** End of inlined file: sharedbook.c ***/
  116551. /*** Start of inlined file: smallft.c ***/
  116552. /* FFT implementation from OggSquish, minus cosine transforms,
  116553. * minus all but radix 2/4 case. In Vorbis we only need this
  116554. * cut-down version.
  116555. *
  116556. * To do more than just power-of-two sized vectors, see the full
  116557. * version I wrote for NetLib.
  116558. *
  116559. * Note that the packing is a little strange; rather than the FFT r/i
  116560. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  116561. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  116562. * FORTRAN version
  116563. */
  116564. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116565. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116566. // tasks..
  116567. #if JUCE_MSVC
  116568. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116569. #endif
  116570. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116571. #if JUCE_USE_OGGVORBIS
  116572. #include <stdlib.h>
  116573. #include <string.h>
  116574. #include <math.h>
  116575. static void drfti1(int n, float *wa, int *ifac){
  116576. static int ntryh[4] = { 4,2,3,5 };
  116577. static float tpi = 6.28318530717958648f;
  116578. float arg,argh,argld,fi;
  116579. int ntry=0,i,j=-1;
  116580. int k1, l1, l2, ib;
  116581. int ld, ii, ip, is, nq, nr;
  116582. int ido, ipm, nfm1;
  116583. int nl=n;
  116584. int nf=0;
  116585. L101:
  116586. j++;
  116587. if (j < 4)
  116588. ntry=ntryh[j];
  116589. else
  116590. ntry+=2;
  116591. L104:
  116592. nq=nl/ntry;
  116593. nr=nl-ntry*nq;
  116594. if (nr!=0) goto L101;
  116595. nf++;
  116596. ifac[nf+1]=ntry;
  116597. nl=nq;
  116598. if(ntry!=2)goto L107;
  116599. if(nf==1)goto L107;
  116600. for (i=1;i<nf;i++){
  116601. ib=nf-i+1;
  116602. ifac[ib+1]=ifac[ib];
  116603. }
  116604. ifac[2] = 2;
  116605. L107:
  116606. if(nl!=1)goto L104;
  116607. ifac[0]=n;
  116608. ifac[1]=nf;
  116609. argh=tpi/n;
  116610. is=0;
  116611. nfm1=nf-1;
  116612. l1=1;
  116613. if(nfm1==0)return;
  116614. for (k1=0;k1<nfm1;k1++){
  116615. ip=ifac[k1+2];
  116616. ld=0;
  116617. l2=l1*ip;
  116618. ido=n/l2;
  116619. ipm=ip-1;
  116620. for (j=0;j<ipm;j++){
  116621. ld+=l1;
  116622. i=is;
  116623. argld=(float)ld*argh;
  116624. fi=0.f;
  116625. for (ii=2;ii<ido;ii+=2){
  116626. fi+=1.f;
  116627. arg=fi*argld;
  116628. wa[i++]=cos(arg);
  116629. wa[i++]=sin(arg);
  116630. }
  116631. is+=ido;
  116632. }
  116633. l1=l2;
  116634. }
  116635. }
  116636. static void fdrffti(int n, float *wsave, int *ifac){
  116637. if (n == 1) return;
  116638. drfti1(n, wsave+n, ifac);
  116639. }
  116640. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  116641. int i,k;
  116642. float ti2,tr2;
  116643. int t0,t1,t2,t3,t4,t5,t6;
  116644. t1=0;
  116645. t0=(t2=l1*ido);
  116646. t3=ido<<1;
  116647. for(k=0;k<l1;k++){
  116648. ch[t1<<1]=cc[t1]+cc[t2];
  116649. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  116650. t1+=ido;
  116651. t2+=ido;
  116652. }
  116653. if(ido<2)return;
  116654. if(ido==2)goto L105;
  116655. t1=0;
  116656. t2=t0;
  116657. for(k=0;k<l1;k++){
  116658. t3=t2;
  116659. t4=(t1<<1)+(ido<<1);
  116660. t5=t1;
  116661. t6=t1+t1;
  116662. for(i=2;i<ido;i+=2){
  116663. t3+=2;
  116664. t4-=2;
  116665. t5+=2;
  116666. t6+=2;
  116667. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  116668. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  116669. ch[t6]=cc[t5]+ti2;
  116670. ch[t4]=ti2-cc[t5];
  116671. ch[t6-1]=cc[t5-1]+tr2;
  116672. ch[t4-1]=cc[t5-1]-tr2;
  116673. }
  116674. t1+=ido;
  116675. t2+=ido;
  116676. }
  116677. if(ido%2==1)return;
  116678. L105:
  116679. t3=(t2=(t1=ido)-1);
  116680. t2+=t0;
  116681. for(k=0;k<l1;k++){
  116682. ch[t1]=-cc[t2];
  116683. ch[t1-1]=cc[t3];
  116684. t1+=ido<<1;
  116685. t2+=ido;
  116686. t3+=ido;
  116687. }
  116688. }
  116689. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  116690. float *wa2,float *wa3){
  116691. static float hsqt2 = .70710678118654752f;
  116692. int i,k,t0,t1,t2,t3,t4,t5,t6;
  116693. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  116694. t0=l1*ido;
  116695. t1=t0;
  116696. t4=t1<<1;
  116697. t2=t1+(t1<<1);
  116698. t3=0;
  116699. for(k=0;k<l1;k++){
  116700. tr1=cc[t1]+cc[t2];
  116701. tr2=cc[t3]+cc[t4];
  116702. ch[t5=t3<<2]=tr1+tr2;
  116703. ch[(ido<<2)+t5-1]=tr2-tr1;
  116704. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  116705. ch[t5]=cc[t2]-cc[t1];
  116706. t1+=ido;
  116707. t2+=ido;
  116708. t3+=ido;
  116709. t4+=ido;
  116710. }
  116711. if(ido<2)return;
  116712. if(ido==2)goto L105;
  116713. t1=0;
  116714. for(k=0;k<l1;k++){
  116715. t2=t1;
  116716. t4=t1<<2;
  116717. t5=(t6=ido<<1)+t4;
  116718. for(i=2;i<ido;i+=2){
  116719. t3=(t2+=2);
  116720. t4+=2;
  116721. t5-=2;
  116722. t3+=t0;
  116723. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  116724. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  116725. t3+=t0;
  116726. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  116727. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  116728. t3+=t0;
  116729. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  116730. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  116731. tr1=cr2+cr4;
  116732. tr4=cr4-cr2;
  116733. ti1=ci2+ci4;
  116734. ti4=ci2-ci4;
  116735. ti2=cc[t2]+ci3;
  116736. ti3=cc[t2]-ci3;
  116737. tr2=cc[t2-1]+cr3;
  116738. tr3=cc[t2-1]-cr3;
  116739. ch[t4-1]=tr1+tr2;
  116740. ch[t4]=ti1+ti2;
  116741. ch[t5-1]=tr3-ti4;
  116742. ch[t5]=tr4-ti3;
  116743. ch[t4+t6-1]=ti4+tr3;
  116744. ch[t4+t6]=tr4+ti3;
  116745. ch[t5+t6-1]=tr2-tr1;
  116746. ch[t5+t6]=ti1-ti2;
  116747. }
  116748. t1+=ido;
  116749. }
  116750. if(ido&1)return;
  116751. L105:
  116752. t2=(t1=t0+ido-1)+(t0<<1);
  116753. t3=ido<<2;
  116754. t4=ido;
  116755. t5=ido<<1;
  116756. t6=ido;
  116757. for(k=0;k<l1;k++){
  116758. ti1=-hsqt2*(cc[t1]+cc[t2]);
  116759. tr1=hsqt2*(cc[t1]-cc[t2]);
  116760. ch[t4-1]=tr1+cc[t6-1];
  116761. ch[t4+t5-1]=cc[t6-1]-tr1;
  116762. ch[t4]=ti1-cc[t1+t0];
  116763. ch[t4+t5]=ti1+cc[t1+t0];
  116764. t1+=ido;
  116765. t2+=ido;
  116766. t4+=t3;
  116767. t6+=ido;
  116768. }
  116769. }
  116770. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  116771. float *c2,float *ch,float *ch2,float *wa){
  116772. static float tpi=6.283185307179586f;
  116773. int idij,ipph,i,j,k,l,ic,ik,is;
  116774. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  116775. float dc2,ai1,ai2,ar1,ar2,ds2;
  116776. int nbd;
  116777. float dcp,arg,dsp,ar1h,ar2h;
  116778. int idp2,ipp2;
  116779. arg=tpi/(float)ip;
  116780. dcp=cos(arg);
  116781. dsp=sin(arg);
  116782. ipph=(ip+1)>>1;
  116783. ipp2=ip;
  116784. idp2=ido;
  116785. nbd=(ido-1)>>1;
  116786. t0=l1*ido;
  116787. t10=ip*ido;
  116788. if(ido==1)goto L119;
  116789. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  116790. t1=0;
  116791. for(j=1;j<ip;j++){
  116792. t1+=t0;
  116793. t2=t1;
  116794. for(k=0;k<l1;k++){
  116795. ch[t2]=c1[t2];
  116796. t2+=ido;
  116797. }
  116798. }
  116799. is=-ido;
  116800. t1=0;
  116801. if(nbd>l1){
  116802. for(j=1;j<ip;j++){
  116803. t1+=t0;
  116804. is+=ido;
  116805. t2= -ido+t1;
  116806. for(k=0;k<l1;k++){
  116807. idij=is-1;
  116808. t2+=ido;
  116809. t3=t2;
  116810. for(i=2;i<ido;i+=2){
  116811. idij+=2;
  116812. t3+=2;
  116813. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  116814. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  116815. }
  116816. }
  116817. }
  116818. }else{
  116819. for(j=1;j<ip;j++){
  116820. is+=ido;
  116821. idij=is-1;
  116822. t1+=t0;
  116823. t2=t1;
  116824. for(i=2;i<ido;i+=2){
  116825. idij+=2;
  116826. t2+=2;
  116827. t3=t2;
  116828. for(k=0;k<l1;k++){
  116829. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  116830. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  116831. t3+=ido;
  116832. }
  116833. }
  116834. }
  116835. }
  116836. t1=0;
  116837. t2=ipp2*t0;
  116838. if(nbd<l1){
  116839. for(j=1;j<ipph;j++){
  116840. t1+=t0;
  116841. t2-=t0;
  116842. t3=t1;
  116843. t4=t2;
  116844. for(i=2;i<ido;i+=2){
  116845. t3+=2;
  116846. t4+=2;
  116847. t5=t3-ido;
  116848. t6=t4-ido;
  116849. for(k=0;k<l1;k++){
  116850. t5+=ido;
  116851. t6+=ido;
  116852. c1[t5-1]=ch[t5-1]+ch[t6-1];
  116853. c1[t6-1]=ch[t5]-ch[t6];
  116854. c1[t5]=ch[t5]+ch[t6];
  116855. c1[t6]=ch[t6-1]-ch[t5-1];
  116856. }
  116857. }
  116858. }
  116859. }else{
  116860. for(j=1;j<ipph;j++){
  116861. t1+=t0;
  116862. t2-=t0;
  116863. t3=t1;
  116864. t4=t2;
  116865. for(k=0;k<l1;k++){
  116866. t5=t3;
  116867. t6=t4;
  116868. for(i=2;i<ido;i+=2){
  116869. t5+=2;
  116870. t6+=2;
  116871. c1[t5-1]=ch[t5-1]+ch[t6-1];
  116872. c1[t6-1]=ch[t5]-ch[t6];
  116873. c1[t5]=ch[t5]+ch[t6];
  116874. c1[t6]=ch[t6-1]-ch[t5-1];
  116875. }
  116876. t3+=ido;
  116877. t4+=ido;
  116878. }
  116879. }
  116880. }
  116881. L119:
  116882. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  116883. t1=0;
  116884. t2=ipp2*idl1;
  116885. for(j=1;j<ipph;j++){
  116886. t1+=t0;
  116887. t2-=t0;
  116888. t3=t1-ido;
  116889. t4=t2-ido;
  116890. for(k=0;k<l1;k++){
  116891. t3+=ido;
  116892. t4+=ido;
  116893. c1[t3]=ch[t3]+ch[t4];
  116894. c1[t4]=ch[t4]-ch[t3];
  116895. }
  116896. }
  116897. ar1=1.f;
  116898. ai1=0.f;
  116899. t1=0;
  116900. t2=ipp2*idl1;
  116901. t3=(ip-1)*idl1;
  116902. for(l=1;l<ipph;l++){
  116903. t1+=idl1;
  116904. t2-=idl1;
  116905. ar1h=dcp*ar1-dsp*ai1;
  116906. ai1=dcp*ai1+dsp*ar1;
  116907. ar1=ar1h;
  116908. t4=t1;
  116909. t5=t2;
  116910. t6=t3;
  116911. t7=idl1;
  116912. for(ik=0;ik<idl1;ik++){
  116913. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  116914. ch2[t5++]=ai1*c2[t6++];
  116915. }
  116916. dc2=ar1;
  116917. ds2=ai1;
  116918. ar2=ar1;
  116919. ai2=ai1;
  116920. t4=idl1;
  116921. t5=(ipp2-1)*idl1;
  116922. for(j=2;j<ipph;j++){
  116923. t4+=idl1;
  116924. t5-=idl1;
  116925. ar2h=dc2*ar2-ds2*ai2;
  116926. ai2=dc2*ai2+ds2*ar2;
  116927. ar2=ar2h;
  116928. t6=t1;
  116929. t7=t2;
  116930. t8=t4;
  116931. t9=t5;
  116932. for(ik=0;ik<idl1;ik++){
  116933. ch2[t6++]+=ar2*c2[t8++];
  116934. ch2[t7++]+=ai2*c2[t9++];
  116935. }
  116936. }
  116937. }
  116938. t1=0;
  116939. for(j=1;j<ipph;j++){
  116940. t1+=idl1;
  116941. t2=t1;
  116942. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  116943. }
  116944. if(ido<l1)goto L132;
  116945. t1=0;
  116946. t2=0;
  116947. for(k=0;k<l1;k++){
  116948. t3=t1;
  116949. t4=t2;
  116950. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  116951. t1+=ido;
  116952. t2+=t10;
  116953. }
  116954. goto L135;
  116955. L132:
  116956. for(i=0;i<ido;i++){
  116957. t1=i;
  116958. t2=i;
  116959. for(k=0;k<l1;k++){
  116960. cc[t2]=ch[t1];
  116961. t1+=ido;
  116962. t2+=t10;
  116963. }
  116964. }
  116965. L135:
  116966. t1=0;
  116967. t2=ido<<1;
  116968. t3=0;
  116969. t4=ipp2*t0;
  116970. for(j=1;j<ipph;j++){
  116971. t1+=t2;
  116972. t3+=t0;
  116973. t4-=t0;
  116974. t5=t1;
  116975. t6=t3;
  116976. t7=t4;
  116977. for(k=0;k<l1;k++){
  116978. cc[t5-1]=ch[t6];
  116979. cc[t5]=ch[t7];
  116980. t5+=t10;
  116981. t6+=ido;
  116982. t7+=ido;
  116983. }
  116984. }
  116985. if(ido==1)return;
  116986. if(nbd<l1)goto L141;
  116987. t1=-ido;
  116988. t3=0;
  116989. t4=0;
  116990. t5=ipp2*t0;
  116991. for(j=1;j<ipph;j++){
  116992. t1+=t2;
  116993. t3+=t2;
  116994. t4+=t0;
  116995. t5-=t0;
  116996. t6=t1;
  116997. t7=t3;
  116998. t8=t4;
  116999. t9=t5;
  117000. for(k=0;k<l1;k++){
  117001. for(i=2;i<ido;i+=2){
  117002. ic=idp2-i;
  117003. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  117004. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  117005. cc[i+t7]=ch[i+t8]+ch[i+t9];
  117006. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  117007. }
  117008. t6+=t10;
  117009. t7+=t10;
  117010. t8+=ido;
  117011. t9+=ido;
  117012. }
  117013. }
  117014. return;
  117015. L141:
  117016. t1=-ido;
  117017. t3=0;
  117018. t4=0;
  117019. t5=ipp2*t0;
  117020. for(j=1;j<ipph;j++){
  117021. t1+=t2;
  117022. t3+=t2;
  117023. t4+=t0;
  117024. t5-=t0;
  117025. for(i=2;i<ido;i+=2){
  117026. t6=idp2+t1-i;
  117027. t7=i+t3;
  117028. t8=i+t4;
  117029. t9=i+t5;
  117030. for(k=0;k<l1;k++){
  117031. cc[t7-1]=ch[t8-1]+ch[t9-1];
  117032. cc[t6-1]=ch[t8-1]-ch[t9-1];
  117033. cc[t7]=ch[t8]+ch[t9];
  117034. cc[t6]=ch[t9]-ch[t8];
  117035. t6+=t10;
  117036. t7+=t10;
  117037. t8+=ido;
  117038. t9+=ido;
  117039. }
  117040. }
  117041. }
  117042. }
  117043. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  117044. int i,k1,l1,l2;
  117045. int na,kh,nf;
  117046. int ip,iw,ido,idl1,ix2,ix3;
  117047. nf=ifac[1];
  117048. na=1;
  117049. l2=n;
  117050. iw=n;
  117051. for(k1=0;k1<nf;k1++){
  117052. kh=nf-k1;
  117053. ip=ifac[kh+1];
  117054. l1=l2/ip;
  117055. ido=n/l2;
  117056. idl1=ido*l1;
  117057. iw-=(ip-1)*ido;
  117058. na=1-na;
  117059. if(ip!=4)goto L102;
  117060. ix2=iw+ido;
  117061. ix3=ix2+ido;
  117062. if(na!=0)
  117063. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  117064. else
  117065. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  117066. goto L110;
  117067. L102:
  117068. if(ip!=2)goto L104;
  117069. if(na!=0)goto L103;
  117070. dradf2(ido,l1,c,ch,wa+iw-1);
  117071. goto L110;
  117072. L103:
  117073. dradf2(ido,l1,ch,c,wa+iw-1);
  117074. goto L110;
  117075. L104:
  117076. if(ido==1)na=1-na;
  117077. if(na!=0)goto L109;
  117078. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  117079. na=1;
  117080. goto L110;
  117081. L109:
  117082. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  117083. na=0;
  117084. L110:
  117085. l2=l1;
  117086. }
  117087. if(na==1)return;
  117088. for(i=0;i<n;i++)c[i]=ch[i];
  117089. }
  117090. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  117091. int i,k,t0,t1,t2,t3,t4,t5,t6;
  117092. float ti2,tr2;
  117093. t0=l1*ido;
  117094. t1=0;
  117095. t2=0;
  117096. t3=(ido<<1)-1;
  117097. for(k=0;k<l1;k++){
  117098. ch[t1]=cc[t2]+cc[t3+t2];
  117099. ch[t1+t0]=cc[t2]-cc[t3+t2];
  117100. t2=(t1+=ido)<<1;
  117101. }
  117102. if(ido<2)return;
  117103. if(ido==2)goto L105;
  117104. t1=0;
  117105. t2=0;
  117106. for(k=0;k<l1;k++){
  117107. t3=t1;
  117108. t5=(t4=t2)+(ido<<1);
  117109. t6=t0+t1;
  117110. for(i=2;i<ido;i+=2){
  117111. t3+=2;
  117112. t4+=2;
  117113. t5-=2;
  117114. t6+=2;
  117115. ch[t3-1]=cc[t4-1]+cc[t5-1];
  117116. tr2=cc[t4-1]-cc[t5-1];
  117117. ch[t3]=cc[t4]-cc[t5];
  117118. ti2=cc[t4]+cc[t5];
  117119. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  117120. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  117121. }
  117122. t2=(t1+=ido)<<1;
  117123. }
  117124. if(ido%2==1)return;
  117125. L105:
  117126. t1=ido-1;
  117127. t2=ido-1;
  117128. for(k=0;k<l1;k++){
  117129. ch[t1]=cc[t2]+cc[t2];
  117130. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  117131. t1+=ido;
  117132. t2+=ido<<1;
  117133. }
  117134. }
  117135. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  117136. float *wa2){
  117137. static float taur = -.5f;
  117138. static float taui = .8660254037844386f;
  117139. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  117140. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  117141. t0=l1*ido;
  117142. t1=0;
  117143. t2=t0<<1;
  117144. t3=ido<<1;
  117145. t4=ido+(ido<<1);
  117146. t5=0;
  117147. for(k=0;k<l1;k++){
  117148. tr2=cc[t3-1]+cc[t3-1];
  117149. cr2=cc[t5]+(taur*tr2);
  117150. ch[t1]=cc[t5]+tr2;
  117151. ci3=taui*(cc[t3]+cc[t3]);
  117152. ch[t1+t0]=cr2-ci3;
  117153. ch[t1+t2]=cr2+ci3;
  117154. t1+=ido;
  117155. t3+=t4;
  117156. t5+=t4;
  117157. }
  117158. if(ido==1)return;
  117159. t1=0;
  117160. t3=ido<<1;
  117161. for(k=0;k<l1;k++){
  117162. t7=t1+(t1<<1);
  117163. t6=(t5=t7+t3);
  117164. t8=t1;
  117165. t10=(t9=t1+t0)+t0;
  117166. for(i=2;i<ido;i+=2){
  117167. t5+=2;
  117168. t6-=2;
  117169. t7+=2;
  117170. t8+=2;
  117171. t9+=2;
  117172. t10+=2;
  117173. tr2=cc[t5-1]+cc[t6-1];
  117174. cr2=cc[t7-1]+(taur*tr2);
  117175. ch[t8-1]=cc[t7-1]+tr2;
  117176. ti2=cc[t5]-cc[t6];
  117177. ci2=cc[t7]+(taur*ti2);
  117178. ch[t8]=cc[t7]+ti2;
  117179. cr3=taui*(cc[t5-1]-cc[t6-1]);
  117180. ci3=taui*(cc[t5]+cc[t6]);
  117181. dr2=cr2-ci3;
  117182. dr3=cr2+ci3;
  117183. di2=ci2+cr3;
  117184. di3=ci2-cr3;
  117185. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  117186. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  117187. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  117188. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  117189. }
  117190. t1+=ido;
  117191. }
  117192. }
  117193. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  117194. float *wa2,float *wa3){
  117195. static float sqrt2=1.414213562373095f;
  117196. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  117197. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  117198. t0=l1*ido;
  117199. t1=0;
  117200. t2=ido<<2;
  117201. t3=0;
  117202. t6=ido<<1;
  117203. for(k=0;k<l1;k++){
  117204. t4=t3+t6;
  117205. t5=t1;
  117206. tr3=cc[t4-1]+cc[t4-1];
  117207. tr4=cc[t4]+cc[t4];
  117208. tr1=cc[t3]-cc[(t4+=t6)-1];
  117209. tr2=cc[t3]+cc[t4-1];
  117210. ch[t5]=tr2+tr3;
  117211. ch[t5+=t0]=tr1-tr4;
  117212. ch[t5+=t0]=tr2-tr3;
  117213. ch[t5+=t0]=tr1+tr4;
  117214. t1+=ido;
  117215. t3+=t2;
  117216. }
  117217. if(ido<2)return;
  117218. if(ido==2)goto L105;
  117219. t1=0;
  117220. for(k=0;k<l1;k++){
  117221. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  117222. t7=t1;
  117223. for(i=2;i<ido;i+=2){
  117224. t2+=2;
  117225. t3+=2;
  117226. t4-=2;
  117227. t5-=2;
  117228. t7+=2;
  117229. ti1=cc[t2]+cc[t5];
  117230. ti2=cc[t2]-cc[t5];
  117231. ti3=cc[t3]-cc[t4];
  117232. tr4=cc[t3]+cc[t4];
  117233. tr1=cc[t2-1]-cc[t5-1];
  117234. tr2=cc[t2-1]+cc[t5-1];
  117235. ti4=cc[t3-1]-cc[t4-1];
  117236. tr3=cc[t3-1]+cc[t4-1];
  117237. ch[t7-1]=tr2+tr3;
  117238. cr3=tr2-tr3;
  117239. ch[t7]=ti2+ti3;
  117240. ci3=ti2-ti3;
  117241. cr2=tr1-tr4;
  117242. cr4=tr1+tr4;
  117243. ci2=ti1+ti4;
  117244. ci4=ti1-ti4;
  117245. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  117246. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  117247. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  117248. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  117249. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  117250. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  117251. }
  117252. t1+=ido;
  117253. }
  117254. if(ido%2 == 1)return;
  117255. L105:
  117256. t1=ido;
  117257. t2=ido<<2;
  117258. t3=ido-1;
  117259. t4=ido+(ido<<1);
  117260. for(k=0;k<l1;k++){
  117261. t5=t3;
  117262. ti1=cc[t1]+cc[t4];
  117263. ti2=cc[t4]-cc[t1];
  117264. tr1=cc[t1-1]-cc[t4-1];
  117265. tr2=cc[t1-1]+cc[t4-1];
  117266. ch[t5]=tr2+tr2;
  117267. ch[t5+=t0]=sqrt2*(tr1-ti1);
  117268. ch[t5+=t0]=ti2+ti2;
  117269. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  117270. t3+=ido;
  117271. t1+=t2;
  117272. t4+=t2;
  117273. }
  117274. }
  117275. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  117276. float *c2,float *ch,float *ch2,float *wa){
  117277. static float tpi=6.283185307179586f;
  117278. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  117279. t11,t12;
  117280. float dc2,ai1,ai2,ar1,ar2,ds2;
  117281. int nbd;
  117282. float dcp,arg,dsp,ar1h,ar2h;
  117283. int ipp2;
  117284. t10=ip*ido;
  117285. t0=l1*ido;
  117286. arg=tpi/(float)ip;
  117287. dcp=cos(arg);
  117288. dsp=sin(arg);
  117289. nbd=(ido-1)>>1;
  117290. ipp2=ip;
  117291. ipph=(ip+1)>>1;
  117292. if(ido<l1)goto L103;
  117293. t1=0;
  117294. t2=0;
  117295. for(k=0;k<l1;k++){
  117296. t3=t1;
  117297. t4=t2;
  117298. for(i=0;i<ido;i++){
  117299. ch[t3]=cc[t4];
  117300. t3++;
  117301. t4++;
  117302. }
  117303. t1+=ido;
  117304. t2+=t10;
  117305. }
  117306. goto L106;
  117307. L103:
  117308. t1=0;
  117309. for(i=0;i<ido;i++){
  117310. t2=t1;
  117311. t3=t1;
  117312. for(k=0;k<l1;k++){
  117313. ch[t2]=cc[t3];
  117314. t2+=ido;
  117315. t3+=t10;
  117316. }
  117317. t1++;
  117318. }
  117319. L106:
  117320. t1=0;
  117321. t2=ipp2*t0;
  117322. t7=(t5=ido<<1);
  117323. for(j=1;j<ipph;j++){
  117324. t1+=t0;
  117325. t2-=t0;
  117326. t3=t1;
  117327. t4=t2;
  117328. t6=t5;
  117329. for(k=0;k<l1;k++){
  117330. ch[t3]=cc[t6-1]+cc[t6-1];
  117331. ch[t4]=cc[t6]+cc[t6];
  117332. t3+=ido;
  117333. t4+=ido;
  117334. t6+=t10;
  117335. }
  117336. t5+=t7;
  117337. }
  117338. if (ido == 1)goto L116;
  117339. if(nbd<l1)goto L112;
  117340. t1=0;
  117341. t2=ipp2*t0;
  117342. t7=0;
  117343. for(j=1;j<ipph;j++){
  117344. t1+=t0;
  117345. t2-=t0;
  117346. t3=t1;
  117347. t4=t2;
  117348. t7+=(ido<<1);
  117349. t8=t7;
  117350. for(k=0;k<l1;k++){
  117351. t5=t3;
  117352. t6=t4;
  117353. t9=t8;
  117354. t11=t8;
  117355. for(i=2;i<ido;i+=2){
  117356. t5+=2;
  117357. t6+=2;
  117358. t9+=2;
  117359. t11-=2;
  117360. ch[t5-1]=cc[t9-1]+cc[t11-1];
  117361. ch[t6-1]=cc[t9-1]-cc[t11-1];
  117362. ch[t5]=cc[t9]-cc[t11];
  117363. ch[t6]=cc[t9]+cc[t11];
  117364. }
  117365. t3+=ido;
  117366. t4+=ido;
  117367. t8+=t10;
  117368. }
  117369. }
  117370. goto L116;
  117371. L112:
  117372. t1=0;
  117373. t2=ipp2*t0;
  117374. t7=0;
  117375. for(j=1;j<ipph;j++){
  117376. t1+=t0;
  117377. t2-=t0;
  117378. t3=t1;
  117379. t4=t2;
  117380. t7+=(ido<<1);
  117381. t8=t7;
  117382. t9=t7;
  117383. for(i=2;i<ido;i+=2){
  117384. t3+=2;
  117385. t4+=2;
  117386. t8+=2;
  117387. t9-=2;
  117388. t5=t3;
  117389. t6=t4;
  117390. t11=t8;
  117391. t12=t9;
  117392. for(k=0;k<l1;k++){
  117393. ch[t5-1]=cc[t11-1]+cc[t12-1];
  117394. ch[t6-1]=cc[t11-1]-cc[t12-1];
  117395. ch[t5]=cc[t11]-cc[t12];
  117396. ch[t6]=cc[t11]+cc[t12];
  117397. t5+=ido;
  117398. t6+=ido;
  117399. t11+=t10;
  117400. t12+=t10;
  117401. }
  117402. }
  117403. }
  117404. L116:
  117405. ar1=1.f;
  117406. ai1=0.f;
  117407. t1=0;
  117408. t9=(t2=ipp2*idl1);
  117409. t3=(ip-1)*idl1;
  117410. for(l=1;l<ipph;l++){
  117411. t1+=idl1;
  117412. t2-=idl1;
  117413. ar1h=dcp*ar1-dsp*ai1;
  117414. ai1=dcp*ai1+dsp*ar1;
  117415. ar1=ar1h;
  117416. t4=t1;
  117417. t5=t2;
  117418. t6=0;
  117419. t7=idl1;
  117420. t8=t3;
  117421. for(ik=0;ik<idl1;ik++){
  117422. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  117423. c2[t5++]=ai1*ch2[t8++];
  117424. }
  117425. dc2=ar1;
  117426. ds2=ai1;
  117427. ar2=ar1;
  117428. ai2=ai1;
  117429. t6=idl1;
  117430. t7=t9-idl1;
  117431. for(j=2;j<ipph;j++){
  117432. t6+=idl1;
  117433. t7-=idl1;
  117434. ar2h=dc2*ar2-ds2*ai2;
  117435. ai2=dc2*ai2+ds2*ar2;
  117436. ar2=ar2h;
  117437. t4=t1;
  117438. t5=t2;
  117439. t11=t6;
  117440. t12=t7;
  117441. for(ik=0;ik<idl1;ik++){
  117442. c2[t4++]+=ar2*ch2[t11++];
  117443. c2[t5++]+=ai2*ch2[t12++];
  117444. }
  117445. }
  117446. }
  117447. t1=0;
  117448. for(j=1;j<ipph;j++){
  117449. t1+=idl1;
  117450. t2=t1;
  117451. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  117452. }
  117453. t1=0;
  117454. t2=ipp2*t0;
  117455. for(j=1;j<ipph;j++){
  117456. t1+=t0;
  117457. t2-=t0;
  117458. t3=t1;
  117459. t4=t2;
  117460. for(k=0;k<l1;k++){
  117461. ch[t3]=c1[t3]-c1[t4];
  117462. ch[t4]=c1[t3]+c1[t4];
  117463. t3+=ido;
  117464. t4+=ido;
  117465. }
  117466. }
  117467. if(ido==1)goto L132;
  117468. if(nbd<l1)goto L128;
  117469. t1=0;
  117470. t2=ipp2*t0;
  117471. for(j=1;j<ipph;j++){
  117472. t1+=t0;
  117473. t2-=t0;
  117474. t3=t1;
  117475. t4=t2;
  117476. for(k=0;k<l1;k++){
  117477. t5=t3;
  117478. t6=t4;
  117479. for(i=2;i<ido;i+=2){
  117480. t5+=2;
  117481. t6+=2;
  117482. ch[t5-1]=c1[t5-1]-c1[t6];
  117483. ch[t6-1]=c1[t5-1]+c1[t6];
  117484. ch[t5]=c1[t5]+c1[t6-1];
  117485. ch[t6]=c1[t5]-c1[t6-1];
  117486. }
  117487. t3+=ido;
  117488. t4+=ido;
  117489. }
  117490. }
  117491. goto L132;
  117492. L128:
  117493. t1=0;
  117494. t2=ipp2*t0;
  117495. for(j=1;j<ipph;j++){
  117496. t1+=t0;
  117497. t2-=t0;
  117498. t3=t1;
  117499. t4=t2;
  117500. for(i=2;i<ido;i+=2){
  117501. t3+=2;
  117502. t4+=2;
  117503. t5=t3;
  117504. t6=t4;
  117505. for(k=0;k<l1;k++){
  117506. ch[t5-1]=c1[t5-1]-c1[t6];
  117507. ch[t6-1]=c1[t5-1]+c1[t6];
  117508. ch[t5]=c1[t5]+c1[t6-1];
  117509. ch[t6]=c1[t5]-c1[t6-1];
  117510. t5+=ido;
  117511. t6+=ido;
  117512. }
  117513. }
  117514. }
  117515. L132:
  117516. if(ido==1)return;
  117517. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  117518. t1=0;
  117519. for(j=1;j<ip;j++){
  117520. t2=(t1+=t0);
  117521. for(k=0;k<l1;k++){
  117522. c1[t2]=ch[t2];
  117523. t2+=ido;
  117524. }
  117525. }
  117526. if(nbd>l1)goto L139;
  117527. is= -ido-1;
  117528. t1=0;
  117529. for(j=1;j<ip;j++){
  117530. is+=ido;
  117531. t1+=t0;
  117532. idij=is;
  117533. t2=t1;
  117534. for(i=2;i<ido;i+=2){
  117535. t2+=2;
  117536. idij+=2;
  117537. t3=t2;
  117538. for(k=0;k<l1;k++){
  117539. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  117540. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  117541. t3+=ido;
  117542. }
  117543. }
  117544. }
  117545. return;
  117546. L139:
  117547. is= -ido-1;
  117548. t1=0;
  117549. for(j=1;j<ip;j++){
  117550. is+=ido;
  117551. t1+=t0;
  117552. t2=t1;
  117553. for(k=0;k<l1;k++){
  117554. idij=is;
  117555. t3=t2;
  117556. for(i=2;i<ido;i+=2){
  117557. idij+=2;
  117558. t3+=2;
  117559. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  117560. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  117561. }
  117562. t2+=ido;
  117563. }
  117564. }
  117565. }
  117566. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  117567. int i,k1,l1,l2;
  117568. int na;
  117569. int nf,ip,iw,ix2,ix3,ido,idl1;
  117570. nf=ifac[1];
  117571. na=0;
  117572. l1=1;
  117573. iw=1;
  117574. for(k1=0;k1<nf;k1++){
  117575. ip=ifac[k1 + 2];
  117576. l2=ip*l1;
  117577. ido=n/l2;
  117578. idl1=ido*l1;
  117579. if(ip!=4)goto L103;
  117580. ix2=iw+ido;
  117581. ix3=ix2+ido;
  117582. if(na!=0)
  117583. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  117584. else
  117585. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  117586. na=1-na;
  117587. goto L115;
  117588. L103:
  117589. if(ip!=2)goto L106;
  117590. if(na!=0)
  117591. dradb2(ido,l1,ch,c,wa+iw-1);
  117592. else
  117593. dradb2(ido,l1,c,ch,wa+iw-1);
  117594. na=1-na;
  117595. goto L115;
  117596. L106:
  117597. if(ip!=3)goto L109;
  117598. ix2=iw+ido;
  117599. if(na!=0)
  117600. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  117601. else
  117602. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  117603. na=1-na;
  117604. goto L115;
  117605. L109:
  117606. /* The radix five case can be translated later..... */
  117607. /* if(ip!=5)goto L112;
  117608. ix2=iw+ido;
  117609. ix3=ix2+ido;
  117610. ix4=ix3+ido;
  117611. if(na!=0)
  117612. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  117613. else
  117614. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  117615. na=1-na;
  117616. goto L115;
  117617. L112:*/
  117618. if(na!=0)
  117619. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  117620. else
  117621. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  117622. if(ido==1)na=1-na;
  117623. L115:
  117624. l1=l2;
  117625. iw+=(ip-1)*ido;
  117626. }
  117627. if(na==0)return;
  117628. for(i=0;i<n;i++)c[i]=ch[i];
  117629. }
  117630. void drft_forward(drft_lookup *l,float *data){
  117631. if(l->n==1)return;
  117632. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  117633. }
  117634. void drft_backward(drft_lookup *l,float *data){
  117635. if (l->n==1)return;
  117636. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  117637. }
  117638. void drft_init(drft_lookup *l,int n){
  117639. l->n=n;
  117640. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  117641. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  117642. fdrffti(n, l->trigcache, l->splitcache);
  117643. }
  117644. void drft_clear(drft_lookup *l){
  117645. if(l){
  117646. if(l->trigcache)_ogg_free(l->trigcache);
  117647. if(l->splitcache)_ogg_free(l->splitcache);
  117648. memset(l,0,sizeof(*l));
  117649. }
  117650. }
  117651. #endif
  117652. /*** End of inlined file: smallft.c ***/
  117653. /*** Start of inlined file: synthesis.c ***/
  117654. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117655. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117656. // tasks..
  117657. #if JUCE_MSVC
  117658. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117659. #endif
  117660. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117661. #if JUCE_USE_OGGVORBIS
  117662. #include <stdio.h>
  117663. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  117664. vorbis_dsp_state *vd=vb->vd;
  117665. private_state *b=(private_state*)vd->backend_state;
  117666. vorbis_info *vi=vd->vi;
  117667. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  117668. oggpack_buffer *opb=&vb->opb;
  117669. int type,mode,i;
  117670. /* first things first. Make sure decode is ready */
  117671. _vorbis_block_ripcord(vb);
  117672. oggpack_readinit(opb,op->packet,op->bytes);
  117673. /* Check the packet type */
  117674. if(oggpack_read(opb,1)!=0){
  117675. /* Oops. This is not an audio data packet */
  117676. return(OV_ENOTAUDIO);
  117677. }
  117678. /* read our mode and pre/post windowsize */
  117679. mode=oggpack_read(opb,b->modebits);
  117680. if(mode==-1)return(OV_EBADPACKET);
  117681. vb->mode=mode;
  117682. vb->W=ci->mode_param[mode]->blockflag;
  117683. if(vb->W){
  117684. /* this doesn;t get mapped through mode selection as it's used
  117685. only for window selection */
  117686. vb->lW=oggpack_read(opb,1);
  117687. vb->nW=oggpack_read(opb,1);
  117688. if(vb->nW==-1) return(OV_EBADPACKET);
  117689. }else{
  117690. vb->lW=0;
  117691. vb->nW=0;
  117692. }
  117693. /* more setup */
  117694. vb->granulepos=op->granulepos;
  117695. vb->sequence=op->packetno;
  117696. vb->eofflag=op->e_o_s;
  117697. /* alloc pcm passback storage */
  117698. vb->pcmend=ci->blocksizes[vb->W];
  117699. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  117700. for(i=0;i<vi->channels;i++)
  117701. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  117702. /* unpack_header enforces range checking */
  117703. type=ci->map_type[ci->mode_param[mode]->mapping];
  117704. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  117705. mapping]));
  117706. }
  117707. /* used to track pcm position without actually performing decode.
  117708. Useful for sequential 'fast forward' */
  117709. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  117710. vorbis_dsp_state *vd=vb->vd;
  117711. private_state *b=(private_state*)vd->backend_state;
  117712. vorbis_info *vi=vd->vi;
  117713. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117714. oggpack_buffer *opb=&vb->opb;
  117715. int mode;
  117716. /* first things first. Make sure decode is ready */
  117717. _vorbis_block_ripcord(vb);
  117718. oggpack_readinit(opb,op->packet,op->bytes);
  117719. /* Check the packet type */
  117720. if(oggpack_read(opb,1)!=0){
  117721. /* Oops. This is not an audio data packet */
  117722. return(OV_ENOTAUDIO);
  117723. }
  117724. /* read our mode and pre/post windowsize */
  117725. mode=oggpack_read(opb,b->modebits);
  117726. if(mode==-1)return(OV_EBADPACKET);
  117727. vb->mode=mode;
  117728. vb->W=ci->mode_param[mode]->blockflag;
  117729. if(vb->W){
  117730. vb->lW=oggpack_read(opb,1);
  117731. vb->nW=oggpack_read(opb,1);
  117732. if(vb->nW==-1) return(OV_EBADPACKET);
  117733. }else{
  117734. vb->lW=0;
  117735. vb->nW=0;
  117736. }
  117737. /* more setup */
  117738. vb->granulepos=op->granulepos;
  117739. vb->sequence=op->packetno;
  117740. vb->eofflag=op->e_o_s;
  117741. /* no pcm */
  117742. vb->pcmend=0;
  117743. vb->pcm=NULL;
  117744. return(0);
  117745. }
  117746. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  117747. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117748. oggpack_buffer opb;
  117749. int mode;
  117750. oggpack_readinit(&opb,op->packet,op->bytes);
  117751. /* Check the packet type */
  117752. if(oggpack_read(&opb,1)!=0){
  117753. /* Oops. This is not an audio data packet */
  117754. return(OV_ENOTAUDIO);
  117755. }
  117756. {
  117757. int modebits=0;
  117758. int v=ci->modes;
  117759. while(v>1){
  117760. modebits++;
  117761. v>>=1;
  117762. }
  117763. /* read our mode and pre/post windowsize */
  117764. mode=oggpack_read(&opb,modebits);
  117765. }
  117766. if(mode==-1)return(OV_EBADPACKET);
  117767. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  117768. }
  117769. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  117770. /* set / clear half-sample-rate mode */
  117771. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117772. /* right now, our MDCT can't handle < 64 sample windows. */
  117773. if(ci->blocksizes[0]<=64 && flag)return -1;
  117774. ci->halfrate_flag=(flag?1:0);
  117775. return 0;
  117776. }
  117777. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  117778. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117779. return ci->halfrate_flag;
  117780. }
  117781. #endif
  117782. /*** End of inlined file: synthesis.c ***/
  117783. /*** Start of inlined file: vorbisenc.c ***/
  117784. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117785. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117786. // tasks..
  117787. #if JUCE_MSVC
  117788. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117789. #endif
  117790. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117791. #if JUCE_USE_OGGVORBIS
  117792. #include <stdlib.h>
  117793. #include <string.h>
  117794. #include <math.h>
  117795. /* careful with this; it's using static array sizing to make managing
  117796. all the modes a little less annoying. If we use a residue backend
  117797. with > 12 partition types, or a different division of iteration,
  117798. this needs to be updated. */
  117799. typedef struct {
  117800. static_codebook *books[12][3];
  117801. } static_bookblock;
  117802. typedef struct {
  117803. int res_type;
  117804. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  117805. vorbis_info_residue0 *res;
  117806. static_codebook *book_aux;
  117807. static_codebook *book_aux_managed;
  117808. static_bookblock *books_base;
  117809. static_bookblock *books_base_managed;
  117810. } vorbis_residue_template;
  117811. typedef struct {
  117812. vorbis_info_mapping0 *map;
  117813. vorbis_residue_template *res;
  117814. } vorbis_mapping_template;
  117815. typedef struct vp_adjblock{
  117816. int block[P_BANDS];
  117817. } vp_adjblock;
  117818. typedef struct {
  117819. int data[NOISE_COMPAND_LEVELS];
  117820. } compandblock;
  117821. /* high level configuration information for setting things up
  117822. step-by-step with the detailed vorbis_encode_ctl interface.
  117823. There's a fair amount of redundancy such that interactive setup
  117824. does not directly deal with any vorbis_info or codec_setup_info
  117825. initialization; it's all stored (until full init) in this highlevel
  117826. setup, then flushed out to the real codec setup structs later. */
  117827. typedef struct {
  117828. int att[P_NOISECURVES];
  117829. float boost;
  117830. float decay;
  117831. } att3;
  117832. typedef struct { int data[P_NOISECURVES]; } adj3;
  117833. typedef struct {
  117834. int pre[PACKETBLOBS];
  117835. int post[PACKETBLOBS];
  117836. float kHz[PACKETBLOBS];
  117837. float lowpasskHz[PACKETBLOBS];
  117838. } adj_stereo;
  117839. typedef struct {
  117840. int lo;
  117841. int hi;
  117842. int fixed;
  117843. } noiseguard;
  117844. typedef struct {
  117845. int data[P_NOISECURVES][17];
  117846. } noise3;
  117847. typedef struct {
  117848. int mappings;
  117849. double *rate_mapping;
  117850. double *quality_mapping;
  117851. int coupling_restriction;
  117852. long samplerate_min_restriction;
  117853. long samplerate_max_restriction;
  117854. int *blocksize_short;
  117855. int *blocksize_long;
  117856. att3 *psy_tone_masteratt;
  117857. int *psy_tone_0dB;
  117858. int *psy_tone_dBsuppress;
  117859. vp_adjblock *psy_tone_adj_impulse;
  117860. vp_adjblock *psy_tone_adj_long;
  117861. vp_adjblock *psy_tone_adj_other;
  117862. noiseguard *psy_noiseguards;
  117863. noise3 *psy_noise_bias_impulse;
  117864. noise3 *psy_noise_bias_padding;
  117865. noise3 *psy_noise_bias_trans;
  117866. noise3 *psy_noise_bias_long;
  117867. int *psy_noise_dBsuppress;
  117868. compandblock *psy_noise_compand;
  117869. double *psy_noise_compand_short_mapping;
  117870. double *psy_noise_compand_long_mapping;
  117871. int *psy_noise_normal_start[2];
  117872. int *psy_noise_normal_partition[2];
  117873. double *psy_noise_normal_thresh;
  117874. int *psy_ath_float;
  117875. int *psy_ath_abs;
  117876. double *psy_lowpass;
  117877. vorbis_info_psy_global *global_params;
  117878. double *global_mapping;
  117879. adj_stereo *stereo_modes;
  117880. static_codebook ***floor_books;
  117881. vorbis_info_floor1 *floor_params;
  117882. int *floor_short_mapping;
  117883. int *floor_long_mapping;
  117884. vorbis_mapping_template *maps;
  117885. } ve_setup_data_template;
  117886. /* a few static coder conventions */
  117887. static vorbis_info_mode _mode_template[2]={
  117888. {0,0,0,0},
  117889. {1,0,0,1}
  117890. };
  117891. static vorbis_info_mapping0 _map_nominal[2]={
  117892. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  117893. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  117894. };
  117895. /*** Start of inlined file: setup_44.h ***/
  117896. /*** Start of inlined file: floor_all.h ***/
  117897. /*** Start of inlined file: floor_books.h ***/
  117898. static long _huff_lengthlist_line_256x7_0sub1[] = {
  117899. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  117900. };
  117901. static static_codebook _huff_book_line_256x7_0sub1 = {
  117902. 1, 9,
  117903. _huff_lengthlist_line_256x7_0sub1,
  117904. 0, 0, 0, 0, 0,
  117905. NULL,
  117906. NULL,
  117907. NULL,
  117908. NULL,
  117909. 0
  117910. };
  117911. static long _huff_lengthlist_line_256x7_0sub2[] = {
  117912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  117913. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  117914. };
  117915. static static_codebook _huff_book_line_256x7_0sub2 = {
  117916. 1, 25,
  117917. _huff_lengthlist_line_256x7_0sub2,
  117918. 0, 0, 0, 0, 0,
  117919. NULL,
  117920. NULL,
  117921. NULL,
  117922. NULL,
  117923. 0
  117924. };
  117925. static long _huff_lengthlist_line_256x7_0sub3[] = {
  117926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  117928. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  117929. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  117930. };
  117931. static static_codebook _huff_book_line_256x7_0sub3 = {
  117932. 1, 64,
  117933. _huff_lengthlist_line_256x7_0sub3,
  117934. 0, 0, 0, 0, 0,
  117935. NULL,
  117936. NULL,
  117937. NULL,
  117938. NULL,
  117939. 0
  117940. };
  117941. static long _huff_lengthlist_line_256x7_1sub1[] = {
  117942. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  117943. };
  117944. static static_codebook _huff_book_line_256x7_1sub1 = {
  117945. 1, 9,
  117946. _huff_lengthlist_line_256x7_1sub1,
  117947. 0, 0, 0, 0, 0,
  117948. NULL,
  117949. NULL,
  117950. NULL,
  117951. NULL,
  117952. 0
  117953. };
  117954. static long _huff_lengthlist_line_256x7_1sub2[] = {
  117955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  117956. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  117957. };
  117958. static static_codebook _huff_book_line_256x7_1sub2 = {
  117959. 1, 25,
  117960. _huff_lengthlist_line_256x7_1sub2,
  117961. 0, 0, 0, 0, 0,
  117962. NULL,
  117963. NULL,
  117964. NULL,
  117965. NULL,
  117966. 0
  117967. };
  117968. static long _huff_lengthlist_line_256x7_1sub3[] = {
  117969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  117971. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  117972. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  117973. };
  117974. static static_codebook _huff_book_line_256x7_1sub3 = {
  117975. 1, 64,
  117976. _huff_lengthlist_line_256x7_1sub3,
  117977. 0, 0, 0, 0, 0,
  117978. NULL,
  117979. NULL,
  117980. NULL,
  117981. NULL,
  117982. 0
  117983. };
  117984. static long _huff_lengthlist_line_256x7_class0[] = {
  117985. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  117986. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  117987. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  117988. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  117989. };
  117990. static static_codebook _huff_book_line_256x7_class0 = {
  117991. 1, 64,
  117992. _huff_lengthlist_line_256x7_class0,
  117993. 0, 0, 0, 0, 0,
  117994. NULL,
  117995. NULL,
  117996. NULL,
  117997. NULL,
  117998. 0
  117999. };
  118000. static long _huff_lengthlist_line_256x7_class1[] = {
  118001. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  118002. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  118003. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  118004. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  118005. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  118006. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  118007. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  118008. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  118009. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  118010. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  118011. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  118012. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  118013. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  118014. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  118015. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  118016. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  118017. };
  118018. static static_codebook _huff_book_line_256x7_class1 = {
  118019. 1, 256,
  118020. _huff_lengthlist_line_256x7_class1,
  118021. 0, 0, 0, 0, 0,
  118022. NULL,
  118023. NULL,
  118024. NULL,
  118025. NULL,
  118026. 0
  118027. };
  118028. static long _huff_lengthlist_line_512x17_0sub0[] = {
  118029. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  118030. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  118031. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  118032. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  118033. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  118034. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  118035. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  118036. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  118037. };
  118038. static static_codebook _huff_book_line_512x17_0sub0 = {
  118039. 1, 128,
  118040. _huff_lengthlist_line_512x17_0sub0,
  118041. 0, 0, 0, 0, 0,
  118042. NULL,
  118043. NULL,
  118044. NULL,
  118045. NULL,
  118046. 0
  118047. };
  118048. static long _huff_lengthlist_line_512x17_1sub0[] = {
  118049. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  118050. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  118051. };
  118052. static static_codebook _huff_book_line_512x17_1sub0 = {
  118053. 1, 32,
  118054. _huff_lengthlist_line_512x17_1sub0,
  118055. 0, 0, 0, 0, 0,
  118056. NULL,
  118057. NULL,
  118058. NULL,
  118059. NULL,
  118060. 0
  118061. };
  118062. static long _huff_lengthlist_line_512x17_1sub1[] = {
  118063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118065. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  118066. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  118067. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  118068. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  118069. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  118070. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  118071. };
  118072. static static_codebook _huff_book_line_512x17_1sub1 = {
  118073. 1, 128,
  118074. _huff_lengthlist_line_512x17_1sub1,
  118075. 0, 0, 0, 0, 0,
  118076. NULL,
  118077. NULL,
  118078. NULL,
  118079. NULL,
  118080. 0
  118081. };
  118082. static long _huff_lengthlist_line_512x17_2sub1[] = {
  118083. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  118084. 5, 3,
  118085. };
  118086. static static_codebook _huff_book_line_512x17_2sub1 = {
  118087. 1, 18,
  118088. _huff_lengthlist_line_512x17_2sub1,
  118089. 0, 0, 0, 0, 0,
  118090. NULL,
  118091. NULL,
  118092. NULL,
  118093. NULL,
  118094. 0
  118095. };
  118096. static long _huff_lengthlist_line_512x17_2sub2[] = {
  118097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118098. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  118099. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  118100. 9, 8,
  118101. };
  118102. static static_codebook _huff_book_line_512x17_2sub2 = {
  118103. 1, 50,
  118104. _huff_lengthlist_line_512x17_2sub2,
  118105. 0, 0, 0, 0, 0,
  118106. NULL,
  118107. NULL,
  118108. NULL,
  118109. NULL,
  118110. 0
  118111. };
  118112. static long _huff_lengthlist_line_512x17_2sub3[] = {
  118113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118116. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  118117. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  118118. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118119. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118120. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118121. };
  118122. static static_codebook _huff_book_line_512x17_2sub3 = {
  118123. 1, 128,
  118124. _huff_lengthlist_line_512x17_2sub3,
  118125. 0, 0, 0, 0, 0,
  118126. NULL,
  118127. NULL,
  118128. NULL,
  118129. NULL,
  118130. 0
  118131. };
  118132. static long _huff_lengthlist_line_512x17_3sub1[] = {
  118133. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  118134. 5, 5,
  118135. };
  118136. static static_codebook _huff_book_line_512x17_3sub1 = {
  118137. 1, 18,
  118138. _huff_lengthlist_line_512x17_3sub1,
  118139. 0, 0, 0, 0, 0,
  118140. NULL,
  118141. NULL,
  118142. NULL,
  118143. NULL,
  118144. 0
  118145. };
  118146. static long _huff_lengthlist_line_512x17_3sub2[] = {
  118147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118148. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  118149. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  118150. 11,14,
  118151. };
  118152. static static_codebook _huff_book_line_512x17_3sub2 = {
  118153. 1, 50,
  118154. _huff_lengthlist_line_512x17_3sub2,
  118155. 0, 0, 0, 0, 0,
  118156. NULL,
  118157. NULL,
  118158. NULL,
  118159. NULL,
  118160. 0
  118161. };
  118162. static long _huff_lengthlist_line_512x17_3sub3[] = {
  118163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118166. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  118167. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118168. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118169. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118170. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118171. };
  118172. static static_codebook _huff_book_line_512x17_3sub3 = {
  118173. 1, 128,
  118174. _huff_lengthlist_line_512x17_3sub3,
  118175. 0, 0, 0, 0, 0,
  118176. NULL,
  118177. NULL,
  118178. NULL,
  118179. NULL,
  118180. 0
  118181. };
  118182. static long _huff_lengthlist_line_512x17_class1[] = {
  118183. 1, 2, 3, 6, 5, 4, 7, 7,
  118184. };
  118185. static static_codebook _huff_book_line_512x17_class1 = {
  118186. 1, 8,
  118187. _huff_lengthlist_line_512x17_class1,
  118188. 0, 0, 0, 0, 0,
  118189. NULL,
  118190. NULL,
  118191. NULL,
  118192. NULL,
  118193. 0
  118194. };
  118195. static long _huff_lengthlist_line_512x17_class2[] = {
  118196. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  118197. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  118198. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  118199. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  118200. };
  118201. static static_codebook _huff_book_line_512x17_class2 = {
  118202. 1, 64,
  118203. _huff_lengthlist_line_512x17_class2,
  118204. 0, 0, 0, 0, 0,
  118205. NULL,
  118206. NULL,
  118207. NULL,
  118208. NULL,
  118209. 0
  118210. };
  118211. static long _huff_lengthlist_line_512x17_class3[] = {
  118212. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  118213. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  118214. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  118215. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  118216. };
  118217. static static_codebook _huff_book_line_512x17_class3 = {
  118218. 1, 64,
  118219. _huff_lengthlist_line_512x17_class3,
  118220. 0, 0, 0, 0, 0,
  118221. NULL,
  118222. NULL,
  118223. NULL,
  118224. NULL,
  118225. 0
  118226. };
  118227. static long _huff_lengthlist_line_128x4_class0[] = {
  118228. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  118229. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  118230. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  118231. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  118232. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  118233. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  118234. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  118235. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  118236. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  118237. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  118238. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  118239. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  118240. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  118241. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  118242. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  118243. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  118244. };
  118245. static static_codebook _huff_book_line_128x4_class0 = {
  118246. 1, 256,
  118247. _huff_lengthlist_line_128x4_class0,
  118248. 0, 0, 0, 0, 0,
  118249. NULL,
  118250. NULL,
  118251. NULL,
  118252. NULL,
  118253. 0
  118254. };
  118255. static long _huff_lengthlist_line_128x4_0sub0[] = {
  118256. 2, 2, 2, 2,
  118257. };
  118258. static static_codebook _huff_book_line_128x4_0sub0 = {
  118259. 1, 4,
  118260. _huff_lengthlist_line_128x4_0sub0,
  118261. 0, 0, 0, 0, 0,
  118262. NULL,
  118263. NULL,
  118264. NULL,
  118265. NULL,
  118266. 0
  118267. };
  118268. static long _huff_lengthlist_line_128x4_0sub1[] = {
  118269. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  118270. };
  118271. static static_codebook _huff_book_line_128x4_0sub1 = {
  118272. 1, 10,
  118273. _huff_lengthlist_line_128x4_0sub1,
  118274. 0, 0, 0, 0, 0,
  118275. NULL,
  118276. NULL,
  118277. NULL,
  118278. NULL,
  118279. 0
  118280. };
  118281. static long _huff_lengthlist_line_128x4_0sub2[] = {
  118282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  118283. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  118284. };
  118285. static static_codebook _huff_book_line_128x4_0sub2 = {
  118286. 1, 25,
  118287. _huff_lengthlist_line_128x4_0sub2,
  118288. 0, 0, 0, 0, 0,
  118289. NULL,
  118290. NULL,
  118291. NULL,
  118292. NULL,
  118293. 0
  118294. };
  118295. static long _huff_lengthlist_line_128x4_0sub3[] = {
  118296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  118298. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  118299. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  118300. };
  118301. static static_codebook _huff_book_line_128x4_0sub3 = {
  118302. 1, 64,
  118303. _huff_lengthlist_line_128x4_0sub3,
  118304. 0, 0, 0, 0, 0,
  118305. NULL,
  118306. NULL,
  118307. NULL,
  118308. NULL,
  118309. 0
  118310. };
  118311. static long _huff_lengthlist_line_256x4_class0[] = {
  118312. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  118313. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  118314. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  118315. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  118316. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  118317. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  118318. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  118319. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  118320. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  118321. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  118322. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  118323. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  118324. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  118325. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  118326. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  118327. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  118328. };
  118329. static static_codebook _huff_book_line_256x4_class0 = {
  118330. 1, 256,
  118331. _huff_lengthlist_line_256x4_class0,
  118332. 0, 0, 0, 0, 0,
  118333. NULL,
  118334. NULL,
  118335. NULL,
  118336. NULL,
  118337. 0
  118338. };
  118339. static long _huff_lengthlist_line_256x4_0sub0[] = {
  118340. 2, 2, 2, 2,
  118341. };
  118342. static static_codebook _huff_book_line_256x4_0sub0 = {
  118343. 1, 4,
  118344. _huff_lengthlist_line_256x4_0sub0,
  118345. 0, 0, 0, 0, 0,
  118346. NULL,
  118347. NULL,
  118348. NULL,
  118349. NULL,
  118350. 0
  118351. };
  118352. static long _huff_lengthlist_line_256x4_0sub1[] = {
  118353. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  118354. };
  118355. static static_codebook _huff_book_line_256x4_0sub1 = {
  118356. 1, 10,
  118357. _huff_lengthlist_line_256x4_0sub1,
  118358. 0, 0, 0, 0, 0,
  118359. NULL,
  118360. NULL,
  118361. NULL,
  118362. NULL,
  118363. 0
  118364. };
  118365. static long _huff_lengthlist_line_256x4_0sub2[] = {
  118366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  118367. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  118368. };
  118369. static static_codebook _huff_book_line_256x4_0sub2 = {
  118370. 1, 25,
  118371. _huff_lengthlist_line_256x4_0sub2,
  118372. 0, 0, 0, 0, 0,
  118373. NULL,
  118374. NULL,
  118375. NULL,
  118376. NULL,
  118377. 0
  118378. };
  118379. static long _huff_lengthlist_line_256x4_0sub3[] = {
  118380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  118382. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  118383. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  118384. };
  118385. static static_codebook _huff_book_line_256x4_0sub3 = {
  118386. 1, 64,
  118387. _huff_lengthlist_line_256x4_0sub3,
  118388. 0, 0, 0, 0, 0,
  118389. NULL,
  118390. NULL,
  118391. NULL,
  118392. NULL,
  118393. 0
  118394. };
  118395. static long _huff_lengthlist_line_128x7_class0[] = {
  118396. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  118397. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  118398. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  118399. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  118400. };
  118401. static static_codebook _huff_book_line_128x7_class0 = {
  118402. 1, 64,
  118403. _huff_lengthlist_line_128x7_class0,
  118404. 0, 0, 0, 0, 0,
  118405. NULL,
  118406. NULL,
  118407. NULL,
  118408. NULL,
  118409. 0
  118410. };
  118411. static long _huff_lengthlist_line_128x7_class1[] = {
  118412. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  118413. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  118414. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  118415. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  118416. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  118417. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  118418. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  118419. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  118420. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  118421. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  118422. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  118423. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  118424. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  118425. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  118426. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  118427. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  118428. };
  118429. static static_codebook _huff_book_line_128x7_class1 = {
  118430. 1, 256,
  118431. _huff_lengthlist_line_128x7_class1,
  118432. 0, 0, 0, 0, 0,
  118433. NULL,
  118434. NULL,
  118435. NULL,
  118436. NULL,
  118437. 0
  118438. };
  118439. static long _huff_lengthlist_line_128x7_0sub1[] = {
  118440. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  118441. };
  118442. static static_codebook _huff_book_line_128x7_0sub1 = {
  118443. 1, 9,
  118444. _huff_lengthlist_line_128x7_0sub1,
  118445. 0, 0, 0, 0, 0,
  118446. NULL,
  118447. NULL,
  118448. NULL,
  118449. NULL,
  118450. 0
  118451. };
  118452. static long _huff_lengthlist_line_128x7_0sub2[] = {
  118453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  118454. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  118455. };
  118456. static static_codebook _huff_book_line_128x7_0sub2 = {
  118457. 1, 25,
  118458. _huff_lengthlist_line_128x7_0sub2,
  118459. 0, 0, 0, 0, 0,
  118460. NULL,
  118461. NULL,
  118462. NULL,
  118463. NULL,
  118464. 0
  118465. };
  118466. static long _huff_lengthlist_line_128x7_0sub3[] = {
  118467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  118469. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  118470. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  118471. };
  118472. static static_codebook _huff_book_line_128x7_0sub3 = {
  118473. 1, 64,
  118474. _huff_lengthlist_line_128x7_0sub3,
  118475. 0, 0, 0, 0, 0,
  118476. NULL,
  118477. NULL,
  118478. NULL,
  118479. NULL,
  118480. 0
  118481. };
  118482. static long _huff_lengthlist_line_128x7_1sub1[] = {
  118483. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  118484. };
  118485. static static_codebook _huff_book_line_128x7_1sub1 = {
  118486. 1, 9,
  118487. _huff_lengthlist_line_128x7_1sub1,
  118488. 0, 0, 0, 0, 0,
  118489. NULL,
  118490. NULL,
  118491. NULL,
  118492. NULL,
  118493. 0
  118494. };
  118495. static long _huff_lengthlist_line_128x7_1sub2[] = {
  118496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  118497. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  118498. };
  118499. static static_codebook _huff_book_line_128x7_1sub2 = {
  118500. 1, 25,
  118501. _huff_lengthlist_line_128x7_1sub2,
  118502. 0, 0, 0, 0, 0,
  118503. NULL,
  118504. NULL,
  118505. NULL,
  118506. NULL,
  118507. 0
  118508. };
  118509. static long _huff_lengthlist_line_128x7_1sub3[] = {
  118510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  118512. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  118513. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  118514. };
  118515. static static_codebook _huff_book_line_128x7_1sub3 = {
  118516. 1, 64,
  118517. _huff_lengthlist_line_128x7_1sub3,
  118518. 0, 0, 0, 0, 0,
  118519. NULL,
  118520. NULL,
  118521. NULL,
  118522. NULL,
  118523. 0
  118524. };
  118525. static long _huff_lengthlist_line_128x11_class1[] = {
  118526. 1, 6, 3, 7, 2, 4, 5, 7,
  118527. };
  118528. static static_codebook _huff_book_line_128x11_class1 = {
  118529. 1, 8,
  118530. _huff_lengthlist_line_128x11_class1,
  118531. 0, 0, 0, 0, 0,
  118532. NULL,
  118533. NULL,
  118534. NULL,
  118535. NULL,
  118536. 0
  118537. };
  118538. static long _huff_lengthlist_line_128x11_class2[] = {
  118539. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  118540. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  118541. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  118542. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  118543. };
  118544. static static_codebook _huff_book_line_128x11_class2 = {
  118545. 1, 64,
  118546. _huff_lengthlist_line_128x11_class2,
  118547. 0, 0, 0, 0, 0,
  118548. NULL,
  118549. NULL,
  118550. NULL,
  118551. NULL,
  118552. 0
  118553. };
  118554. static long _huff_lengthlist_line_128x11_class3[] = {
  118555. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  118556. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  118557. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  118558. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  118559. };
  118560. static static_codebook _huff_book_line_128x11_class3 = {
  118561. 1, 64,
  118562. _huff_lengthlist_line_128x11_class3,
  118563. 0, 0, 0, 0, 0,
  118564. NULL,
  118565. NULL,
  118566. NULL,
  118567. NULL,
  118568. 0
  118569. };
  118570. static long _huff_lengthlist_line_128x11_0sub0[] = {
  118571. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  118572. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  118573. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  118574. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  118575. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  118576. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  118577. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  118578. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  118579. };
  118580. static static_codebook _huff_book_line_128x11_0sub0 = {
  118581. 1, 128,
  118582. _huff_lengthlist_line_128x11_0sub0,
  118583. 0, 0, 0, 0, 0,
  118584. NULL,
  118585. NULL,
  118586. NULL,
  118587. NULL,
  118588. 0
  118589. };
  118590. static long _huff_lengthlist_line_128x11_1sub0[] = {
  118591. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  118592. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  118593. };
  118594. static static_codebook _huff_book_line_128x11_1sub0 = {
  118595. 1, 32,
  118596. _huff_lengthlist_line_128x11_1sub0,
  118597. 0, 0, 0, 0, 0,
  118598. NULL,
  118599. NULL,
  118600. NULL,
  118601. NULL,
  118602. 0
  118603. };
  118604. static long _huff_lengthlist_line_128x11_1sub1[] = {
  118605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118607. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  118608. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  118609. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  118610. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  118611. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  118612. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  118613. };
  118614. static static_codebook _huff_book_line_128x11_1sub1 = {
  118615. 1, 128,
  118616. _huff_lengthlist_line_128x11_1sub1,
  118617. 0, 0, 0, 0, 0,
  118618. NULL,
  118619. NULL,
  118620. NULL,
  118621. NULL,
  118622. 0
  118623. };
  118624. static long _huff_lengthlist_line_128x11_2sub1[] = {
  118625. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  118626. 5, 5,
  118627. };
  118628. static static_codebook _huff_book_line_128x11_2sub1 = {
  118629. 1, 18,
  118630. _huff_lengthlist_line_128x11_2sub1,
  118631. 0, 0, 0, 0, 0,
  118632. NULL,
  118633. NULL,
  118634. NULL,
  118635. NULL,
  118636. 0
  118637. };
  118638. static long _huff_lengthlist_line_128x11_2sub2[] = {
  118639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118640. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  118641. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  118642. 8,11,
  118643. };
  118644. static static_codebook _huff_book_line_128x11_2sub2 = {
  118645. 1, 50,
  118646. _huff_lengthlist_line_128x11_2sub2,
  118647. 0, 0, 0, 0, 0,
  118648. NULL,
  118649. NULL,
  118650. NULL,
  118651. NULL,
  118652. 0
  118653. };
  118654. static long _huff_lengthlist_line_128x11_2sub3[] = {
  118655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118658. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  118659. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118660. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118661. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118662. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118663. };
  118664. static static_codebook _huff_book_line_128x11_2sub3 = {
  118665. 1, 128,
  118666. _huff_lengthlist_line_128x11_2sub3,
  118667. 0, 0, 0, 0, 0,
  118668. NULL,
  118669. NULL,
  118670. NULL,
  118671. NULL,
  118672. 0
  118673. };
  118674. static long _huff_lengthlist_line_128x11_3sub1[] = {
  118675. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  118676. 5, 4,
  118677. };
  118678. static static_codebook _huff_book_line_128x11_3sub1 = {
  118679. 1, 18,
  118680. _huff_lengthlist_line_128x11_3sub1,
  118681. 0, 0, 0, 0, 0,
  118682. NULL,
  118683. NULL,
  118684. NULL,
  118685. NULL,
  118686. 0
  118687. };
  118688. static long _huff_lengthlist_line_128x11_3sub2[] = {
  118689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118690. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  118691. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  118692. 12, 6,
  118693. };
  118694. static static_codebook _huff_book_line_128x11_3sub2 = {
  118695. 1, 50,
  118696. _huff_lengthlist_line_128x11_3sub2,
  118697. 0, 0, 0, 0, 0,
  118698. NULL,
  118699. NULL,
  118700. NULL,
  118701. NULL,
  118702. 0
  118703. };
  118704. static long _huff_lengthlist_line_128x11_3sub3[] = {
  118705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118708. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  118709. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  118710. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118711. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118712. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  118713. };
  118714. static static_codebook _huff_book_line_128x11_3sub3 = {
  118715. 1, 128,
  118716. _huff_lengthlist_line_128x11_3sub3,
  118717. 0, 0, 0, 0, 0,
  118718. NULL,
  118719. NULL,
  118720. NULL,
  118721. NULL,
  118722. 0
  118723. };
  118724. static long _huff_lengthlist_line_128x17_class1[] = {
  118725. 1, 3, 4, 7, 2, 5, 6, 7,
  118726. };
  118727. static static_codebook _huff_book_line_128x17_class1 = {
  118728. 1, 8,
  118729. _huff_lengthlist_line_128x17_class1,
  118730. 0, 0, 0, 0, 0,
  118731. NULL,
  118732. NULL,
  118733. NULL,
  118734. NULL,
  118735. 0
  118736. };
  118737. static long _huff_lengthlist_line_128x17_class2[] = {
  118738. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  118739. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  118740. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  118741. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  118742. };
  118743. static static_codebook _huff_book_line_128x17_class2 = {
  118744. 1, 64,
  118745. _huff_lengthlist_line_128x17_class2,
  118746. 0, 0, 0, 0, 0,
  118747. NULL,
  118748. NULL,
  118749. NULL,
  118750. NULL,
  118751. 0
  118752. };
  118753. static long _huff_lengthlist_line_128x17_class3[] = {
  118754. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  118755. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  118756. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  118757. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  118758. };
  118759. static static_codebook _huff_book_line_128x17_class3 = {
  118760. 1, 64,
  118761. _huff_lengthlist_line_128x17_class3,
  118762. 0, 0, 0, 0, 0,
  118763. NULL,
  118764. NULL,
  118765. NULL,
  118766. NULL,
  118767. 0
  118768. };
  118769. static long _huff_lengthlist_line_128x17_0sub0[] = {
  118770. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  118771. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  118772. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  118773. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  118774. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  118775. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  118776. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  118777. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  118778. };
  118779. static static_codebook _huff_book_line_128x17_0sub0 = {
  118780. 1, 128,
  118781. _huff_lengthlist_line_128x17_0sub0,
  118782. 0, 0, 0, 0, 0,
  118783. NULL,
  118784. NULL,
  118785. NULL,
  118786. NULL,
  118787. 0
  118788. };
  118789. static long _huff_lengthlist_line_128x17_1sub0[] = {
  118790. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  118791. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  118792. };
  118793. static static_codebook _huff_book_line_128x17_1sub0 = {
  118794. 1, 32,
  118795. _huff_lengthlist_line_128x17_1sub0,
  118796. 0, 0, 0, 0, 0,
  118797. NULL,
  118798. NULL,
  118799. NULL,
  118800. NULL,
  118801. 0
  118802. };
  118803. static long _huff_lengthlist_line_128x17_1sub1[] = {
  118804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118806. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  118807. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  118808. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  118809. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  118810. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  118811. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  118812. };
  118813. static static_codebook _huff_book_line_128x17_1sub1 = {
  118814. 1, 128,
  118815. _huff_lengthlist_line_128x17_1sub1,
  118816. 0, 0, 0, 0, 0,
  118817. NULL,
  118818. NULL,
  118819. NULL,
  118820. NULL,
  118821. 0
  118822. };
  118823. static long _huff_lengthlist_line_128x17_2sub1[] = {
  118824. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  118825. 9, 4,
  118826. };
  118827. static static_codebook _huff_book_line_128x17_2sub1 = {
  118828. 1, 18,
  118829. _huff_lengthlist_line_128x17_2sub1,
  118830. 0, 0, 0, 0, 0,
  118831. NULL,
  118832. NULL,
  118833. NULL,
  118834. NULL,
  118835. 0
  118836. };
  118837. static long _huff_lengthlist_line_128x17_2sub2[] = {
  118838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118839. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  118840. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  118841. 13,13,
  118842. };
  118843. static static_codebook _huff_book_line_128x17_2sub2 = {
  118844. 1, 50,
  118845. _huff_lengthlist_line_128x17_2sub2,
  118846. 0, 0, 0, 0, 0,
  118847. NULL,
  118848. NULL,
  118849. NULL,
  118850. NULL,
  118851. 0
  118852. };
  118853. static long _huff_lengthlist_line_128x17_2sub3[] = {
  118854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118857. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118858. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  118859. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  118860. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  118861. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  118862. };
  118863. static static_codebook _huff_book_line_128x17_2sub3 = {
  118864. 1, 128,
  118865. _huff_lengthlist_line_128x17_2sub3,
  118866. 0, 0, 0, 0, 0,
  118867. NULL,
  118868. NULL,
  118869. NULL,
  118870. NULL,
  118871. 0
  118872. };
  118873. static long _huff_lengthlist_line_128x17_3sub1[] = {
  118874. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  118875. 6, 4,
  118876. };
  118877. static static_codebook _huff_book_line_128x17_3sub1 = {
  118878. 1, 18,
  118879. _huff_lengthlist_line_128x17_3sub1,
  118880. 0, 0, 0, 0, 0,
  118881. NULL,
  118882. NULL,
  118883. NULL,
  118884. NULL,
  118885. 0
  118886. };
  118887. static long _huff_lengthlist_line_128x17_3sub2[] = {
  118888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118889. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  118890. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  118891. 10, 8,
  118892. };
  118893. static static_codebook _huff_book_line_128x17_3sub2 = {
  118894. 1, 50,
  118895. _huff_lengthlist_line_128x17_3sub2,
  118896. 0, 0, 0, 0, 0,
  118897. NULL,
  118898. NULL,
  118899. NULL,
  118900. NULL,
  118901. 0
  118902. };
  118903. static long _huff_lengthlist_line_128x17_3sub3[] = {
  118904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118907. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  118908. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  118909. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  118910. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  118911. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  118912. };
  118913. static static_codebook _huff_book_line_128x17_3sub3 = {
  118914. 1, 128,
  118915. _huff_lengthlist_line_128x17_3sub3,
  118916. 0, 0, 0, 0, 0,
  118917. NULL,
  118918. NULL,
  118919. NULL,
  118920. NULL,
  118921. 0
  118922. };
  118923. static long _huff_lengthlist_line_1024x27_class1[] = {
  118924. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  118925. };
  118926. static static_codebook _huff_book_line_1024x27_class1 = {
  118927. 1, 16,
  118928. _huff_lengthlist_line_1024x27_class1,
  118929. 0, 0, 0, 0, 0,
  118930. NULL,
  118931. NULL,
  118932. NULL,
  118933. NULL,
  118934. 0
  118935. };
  118936. static long _huff_lengthlist_line_1024x27_class2[] = {
  118937. 1, 4, 2, 6, 3, 7, 5, 7,
  118938. };
  118939. static static_codebook _huff_book_line_1024x27_class2 = {
  118940. 1, 8,
  118941. _huff_lengthlist_line_1024x27_class2,
  118942. 0, 0, 0, 0, 0,
  118943. NULL,
  118944. NULL,
  118945. NULL,
  118946. NULL,
  118947. 0
  118948. };
  118949. static long _huff_lengthlist_line_1024x27_class3[] = {
  118950. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  118951. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  118952. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  118953. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  118954. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  118955. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  118956. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  118957. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  118958. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  118959. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  118960. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  118961. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  118962. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  118963. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  118964. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  118965. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  118966. };
  118967. static static_codebook _huff_book_line_1024x27_class3 = {
  118968. 1, 256,
  118969. _huff_lengthlist_line_1024x27_class3,
  118970. 0, 0, 0, 0, 0,
  118971. NULL,
  118972. NULL,
  118973. NULL,
  118974. NULL,
  118975. 0
  118976. };
  118977. static long _huff_lengthlist_line_1024x27_class4[] = {
  118978. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  118979. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  118980. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  118981. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  118982. };
  118983. static static_codebook _huff_book_line_1024x27_class4 = {
  118984. 1, 64,
  118985. _huff_lengthlist_line_1024x27_class4,
  118986. 0, 0, 0, 0, 0,
  118987. NULL,
  118988. NULL,
  118989. NULL,
  118990. NULL,
  118991. 0
  118992. };
  118993. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  118994. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  118995. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  118996. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  118997. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  118998. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  118999. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  119000. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  119001. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  119002. };
  119003. static static_codebook _huff_book_line_1024x27_0sub0 = {
  119004. 1, 128,
  119005. _huff_lengthlist_line_1024x27_0sub0,
  119006. 0, 0, 0, 0, 0,
  119007. NULL,
  119008. NULL,
  119009. NULL,
  119010. NULL,
  119011. 0
  119012. };
  119013. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  119014. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  119015. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  119016. };
  119017. static static_codebook _huff_book_line_1024x27_1sub0 = {
  119018. 1, 32,
  119019. _huff_lengthlist_line_1024x27_1sub0,
  119020. 0, 0, 0, 0, 0,
  119021. NULL,
  119022. NULL,
  119023. NULL,
  119024. NULL,
  119025. 0
  119026. };
  119027. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  119028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119030. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  119031. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  119032. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  119033. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  119034. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  119035. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  119036. };
  119037. static static_codebook _huff_book_line_1024x27_1sub1 = {
  119038. 1, 128,
  119039. _huff_lengthlist_line_1024x27_1sub1,
  119040. 0, 0, 0, 0, 0,
  119041. NULL,
  119042. NULL,
  119043. NULL,
  119044. NULL,
  119045. 0
  119046. };
  119047. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  119048. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  119049. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  119050. };
  119051. static static_codebook _huff_book_line_1024x27_2sub0 = {
  119052. 1, 32,
  119053. _huff_lengthlist_line_1024x27_2sub0,
  119054. 0, 0, 0, 0, 0,
  119055. NULL,
  119056. NULL,
  119057. NULL,
  119058. NULL,
  119059. 0
  119060. };
  119061. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  119062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119064. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  119065. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  119066. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  119067. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  119068. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  119069. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  119070. };
  119071. static static_codebook _huff_book_line_1024x27_2sub1 = {
  119072. 1, 128,
  119073. _huff_lengthlist_line_1024x27_2sub1,
  119074. 0, 0, 0, 0, 0,
  119075. NULL,
  119076. NULL,
  119077. NULL,
  119078. NULL,
  119079. 0
  119080. };
  119081. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  119082. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  119083. 5, 5,
  119084. };
  119085. static static_codebook _huff_book_line_1024x27_3sub1 = {
  119086. 1, 18,
  119087. _huff_lengthlist_line_1024x27_3sub1,
  119088. 0, 0, 0, 0, 0,
  119089. NULL,
  119090. NULL,
  119091. NULL,
  119092. NULL,
  119093. 0
  119094. };
  119095. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  119096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119097. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  119098. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  119099. 9,11,
  119100. };
  119101. static static_codebook _huff_book_line_1024x27_3sub2 = {
  119102. 1, 50,
  119103. _huff_lengthlist_line_1024x27_3sub2,
  119104. 0, 0, 0, 0, 0,
  119105. NULL,
  119106. NULL,
  119107. NULL,
  119108. NULL,
  119109. 0
  119110. };
  119111. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  119112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119115. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  119116. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  119117. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  119118. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  119119. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  119120. };
  119121. static static_codebook _huff_book_line_1024x27_3sub3 = {
  119122. 1, 128,
  119123. _huff_lengthlist_line_1024x27_3sub3,
  119124. 0, 0, 0, 0, 0,
  119125. NULL,
  119126. NULL,
  119127. NULL,
  119128. NULL,
  119129. 0
  119130. };
  119131. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  119132. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  119133. 5, 4,
  119134. };
  119135. static static_codebook _huff_book_line_1024x27_4sub1 = {
  119136. 1, 18,
  119137. _huff_lengthlist_line_1024x27_4sub1,
  119138. 0, 0, 0, 0, 0,
  119139. NULL,
  119140. NULL,
  119141. NULL,
  119142. NULL,
  119143. 0
  119144. };
  119145. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  119146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119147. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  119148. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  119149. 9,12,
  119150. };
  119151. static static_codebook _huff_book_line_1024x27_4sub2 = {
  119152. 1, 50,
  119153. _huff_lengthlist_line_1024x27_4sub2,
  119154. 0, 0, 0, 0, 0,
  119155. NULL,
  119156. NULL,
  119157. NULL,
  119158. NULL,
  119159. 0
  119160. };
  119161. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  119162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119165. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  119166. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  119167. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  119168. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  119169. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  119170. };
  119171. static static_codebook _huff_book_line_1024x27_4sub3 = {
  119172. 1, 128,
  119173. _huff_lengthlist_line_1024x27_4sub3,
  119174. 0, 0, 0, 0, 0,
  119175. NULL,
  119176. NULL,
  119177. NULL,
  119178. NULL,
  119179. 0
  119180. };
  119181. static long _huff_lengthlist_line_2048x27_class1[] = {
  119182. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  119183. };
  119184. static static_codebook _huff_book_line_2048x27_class1 = {
  119185. 1, 16,
  119186. _huff_lengthlist_line_2048x27_class1,
  119187. 0, 0, 0, 0, 0,
  119188. NULL,
  119189. NULL,
  119190. NULL,
  119191. NULL,
  119192. 0
  119193. };
  119194. static long _huff_lengthlist_line_2048x27_class2[] = {
  119195. 1, 2, 3, 6, 4, 7, 5, 7,
  119196. };
  119197. static static_codebook _huff_book_line_2048x27_class2 = {
  119198. 1, 8,
  119199. _huff_lengthlist_line_2048x27_class2,
  119200. 0, 0, 0, 0, 0,
  119201. NULL,
  119202. NULL,
  119203. NULL,
  119204. NULL,
  119205. 0
  119206. };
  119207. static long _huff_lengthlist_line_2048x27_class3[] = {
  119208. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  119209. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  119210. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  119211. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  119212. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  119213. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  119214. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  119215. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  119216. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  119217. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  119218. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  119219. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  119220. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  119221. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  119222. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  119223. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  119224. };
  119225. static static_codebook _huff_book_line_2048x27_class3 = {
  119226. 1, 256,
  119227. _huff_lengthlist_line_2048x27_class3,
  119228. 0, 0, 0, 0, 0,
  119229. NULL,
  119230. NULL,
  119231. NULL,
  119232. NULL,
  119233. 0
  119234. };
  119235. static long _huff_lengthlist_line_2048x27_class4[] = {
  119236. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  119237. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  119238. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  119239. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  119240. };
  119241. static static_codebook _huff_book_line_2048x27_class4 = {
  119242. 1, 64,
  119243. _huff_lengthlist_line_2048x27_class4,
  119244. 0, 0, 0, 0, 0,
  119245. NULL,
  119246. NULL,
  119247. NULL,
  119248. NULL,
  119249. 0
  119250. };
  119251. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  119252. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  119253. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  119254. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  119255. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  119256. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  119257. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  119258. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  119259. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  119260. };
  119261. static static_codebook _huff_book_line_2048x27_0sub0 = {
  119262. 1, 128,
  119263. _huff_lengthlist_line_2048x27_0sub0,
  119264. 0, 0, 0, 0, 0,
  119265. NULL,
  119266. NULL,
  119267. NULL,
  119268. NULL,
  119269. 0
  119270. };
  119271. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  119272. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  119273. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  119274. };
  119275. static static_codebook _huff_book_line_2048x27_1sub0 = {
  119276. 1, 32,
  119277. _huff_lengthlist_line_2048x27_1sub0,
  119278. 0, 0, 0, 0, 0,
  119279. NULL,
  119280. NULL,
  119281. NULL,
  119282. NULL,
  119283. 0
  119284. };
  119285. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  119286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119288. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  119289. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  119290. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  119291. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  119292. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  119293. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  119294. };
  119295. static static_codebook _huff_book_line_2048x27_1sub1 = {
  119296. 1, 128,
  119297. _huff_lengthlist_line_2048x27_1sub1,
  119298. 0, 0, 0, 0, 0,
  119299. NULL,
  119300. NULL,
  119301. NULL,
  119302. NULL,
  119303. 0
  119304. };
  119305. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  119306. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  119307. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  119308. };
  119309. static static_codebook _huff_book_line_2048x27_2sub0 = {
  119310. 1, 32,
  119311. _huff_lengthlist_line_2048x27_2sub0,
  119312. 0, 0, 0, 0, 0,
  119313. NULL,
  119314. NULL,
  119315. NULL,
  119316. NULL,
  119317. 0
  119318. };
  119319. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  119320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119322. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  119323. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  119324. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  119325. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  119326. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  119327. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  119328. };
  119329. static static_codebook _huff_book_line_2048x27_2sub1 = {
  119330. 1, 128,
  119331. _huff_lengthlist_line_2048x27_2sub1,
  119332. 0, 0, 0, 0, 0,
  119333. NULL,
  119334. NULL,
  119335. NULL,
  119336. NULL,
  119337. 0
  119338. };
  119339. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  119340. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  119341. 5, 5,
  119342. };
  119343. static static_codebook _huff_book_line_2048x27_3sub1 = {
  119344. 1, 18,
  119345. _huff_lengthlist_line_2048x27_3sub1,
  119346. 0, 0, 0, 0, 0,
  119347. NULL,
  119348. NULL,
  119349. NULL,
  119350. NULL,
  119351. 0
  119352. };
  119353. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  119354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119355. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  119356. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  119357. 10,12,
  119358. };
  119359. static static_codebook _huff_book_line_2048x27_3sub2 = {
  119360. 1, 50,
  119361. _huff_lengthlist_line_2048x27_3sub2,
  119362. 0, 0, 0, 0, 0,
  119363. NULL,
  119364. NULL,
  119365. NULL,
  119366. NULL,
  119367. 0
  119368. };
  119369. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  119370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119373. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  119374. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119375. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119376. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119377. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119378. };
  119379. static static_codebook _huff_book_line_2048x27_3sub3 = {
  119380. 1, 128,
  119381. _huff_lengthlist_line_2048x27_3sub3,
  119382. 0, 0, 0, 0, 0,
  119383. NULL,
  119384. NULL,
  119385. NULL,
  119386. NULL,
  119387. 0
  119388. };
  119389. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  119390. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  119391. 4, 5,
  119392. };
  119393. static static_codebook _huff_book_line_2048x27_4sub1 = {
  119394. 1, 18,
  119395. _huff_lengthlist_line_2048x27_4sub1,
  119396. 0, 0, 0, 0, 0,
  119397. NULL,
  119398. NULL,
  119399. NULL,
  119400. NULL,
  119401. 0
  119402. };
  119403. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  119404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119405. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  119406. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  119407. 10,10,
  119408. };
  119409. static static_codebook _huff_book_line_2048x27_4sub2 = {
  119410. 1, 50,
  119411. _huff_lengthlist_line_2048x27_4sub2,
  119412. 0, 0, 0, 0, 0,
  119413. NULL,
  119414. NULL,
  119415. NULL,
  119416. NULL,
  119417. 0
  119418. };
  119419. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  119420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119423. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  119424. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  119425. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119426. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119427. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  119428. };
  119429. static static_codebook _huff_book_line_2048x27_4sub3 = {
  119430. 1, 128,
  119431. _huff_lengthlist_line_2048x27_4sub3,
  119432. 0, 0, 0, 0, 0,
  119433. NULL,
  119434. NULL,
  119435. NULL,
  119436. NULL,
  119437. 0
  119438. };
  119439. static long _huff_lengthlist_line_256x4low_class0[] = {
  119440. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  119441. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  119442. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  119443. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  119444. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  119445. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  119446. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  119447. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  119448. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  119449. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  119450. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  119451. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  119452. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  119453. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  119454. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  119455. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  119456. };
  119457. static static_codebook _huff_book_line_256x4low_class0 = {
  119458. 1, 256,
  119459. _huff_lengthlist_line_256x4low_class0,
  119460. 0, 0, 0, 0, 0,
  119461. NULL,
  119462. NULL,
  119463. NULL,
  119464. NULL,
  119465. 0
  119466. };
  119467. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  119468. 1, 3, 2, 3,
  119469. };
  119470. static static_codebook _huff_book_line_256x4low_0sub0 = {
  119471. 1, 4,
  119472. _huff_lengthlist_line_256x4low_0sub0,
  119473. 0, 0, 0, 0, 0,
  119474. NULL,
  119475. NULL,
  119476. NULL,
  119477. NULL,
  119478. 0
  119479. };
  119480. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  119481. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  119482. };
  119483. static static_codebook _huff_book_line_256x4low_0sub1 = {
  119484. 1, 10,
  119485. _huff_lengthlist_line_256x4low_0sub1,
  119486. 0, 0, 0, 0, 0,
  119487. NULL,
  119488. NULL,
  119489. NULL,
  119490. NULL,
  119491. 0
  119492. };
  119493. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  119494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  119495. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  119496. };
  119497. static static_codebook _huff_book_line_256x4low_0sub2 = {
  119498. 1, 25,
  119499. _huff_lengthlist_line_256x4low_0sub2,
  119500. 0, 0, 0, 0, 0,
  119501. NULL,
  119502. NULL,
  119503. NULL,
  119504. NULL,
  119505. 0
  119506. };
  119507. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  119508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  119510. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  119511. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  119512. };
  119513. static static_codebook _huff_book_line_256x4low_0sub3 = {
  119514. 1, 64,
  119515. _huff_lengthlist_line_256x4low_0sub3,
  119516. 0, 0, 0, 0, 0,
  119517. NULL,
  119518. NULL,
  119519. NULL,
  119520. NULL,
  119521. 0
  119522. };
  119523. /*** End of inlined file: floor_books.h ***/
  119524. static static_codebook *_floor_128x4_books[]={
  119525. &_huff_book_line_128x4_class0,
  119526. &_huff_book_line_128x4_0sub0,
  119527. &_huff_book_line_128x4_0sub1,
  119528. &_huff_book_line_128x4_0sub2,
  119529. &_huff_book_line_128x4_0sub3,
  119530. };
  119531. static static_codebook *_floor_256x4_books[]={
  119532. &_huff_book_line_256x4_class0,
  119533. &_huff_book_line_256x4_0sub0,
  119534. &_huff_book_line_256x4_0sub1,
  119535. &_huff_book_line_256x4_0sub2,
  119536. &_huff_book_line_256x4_0sub3,
  119537. };
  119538. static static_codebook *_floor_128x7_books[]={
  119539. &_huff_book_line_128x7_class0,
  119540. &_huff_book_line_128x7_class1,
  119541. &_huff_book_line_128x7_0sub1,
  119542. &_huff_book_line_128x7_0sub2,
  119543. &_huff_book_line_128x7_0sub3,
  119544. &_huff_book_line_128x7_1sub1,
  119545. &_huff_book_line_128x7_1sub2,
  119546. &_huff_book_line_128x7_1sub3,
  119547. };
  119548. static static_codebook *_floor_256x7_books[]={
  119549. &_huff_book_line_256x7_class0,
  119550. &_huff_book_line_256x7_class1,
  119551. &_huff_book_line_256x7_0sub1,
  119552. &_huff_book_line_256x7_0sub2,
  119553. &_huff_book_line_256x7_0sub3,
  119554. &_huff_book_line_256x7_1sub1,
  119555. &_huff_book_line_256x7_1sub2,
  119556. &_huff_book_line_256x7_1sub3,
  119557. };
  119558. static static_codebook *_floor_128x11_books[]={
  119559. &_huff_book_line_128x11_class1,
  119560. &_huff_book_line_128x11_class2,
  119561. &_huff_book_line_128x11_class3,
  119562. &_huff_book_line_128x11_0sub0,
  119563. &_huff_book_line_128x11_1sub0,
  119564. &_huff_book_line_128x11_1sub1,
  119565. &_huff_book_line_128x11_2sub1,
  119566. &_huff_book_line_128x11_2sub2,
  119567. &_huff_book_line_128x11_2sub3,
  119568. &_huff_book_line_128x11_3sub1,
  119569. &_huff_book_line_128x11_3sub2,
  119570. &_huff_book_line_128x11_3sub3,
  119571. };
  119572. static static_codebook *_floor_128x17_books[]={
  119573. &_huff_book_line_128x17_class1,
  119574. &_huff_book_line_128x17_class2,
  119575. &_huff_book_line_128x17_class3,
  119576. &_huff_book_line_128x17_0sub0,
  119577. &_huff_book_line_128x17_1sub0,
  119578. &_huff_book_line_128x17_1sub1,
  119579. &_huff_book_line_128x17_2sub1,
  119580. &_huff_book_line_128x17_2sub2,
  119581. &_huff_book_line_128x17_2sub3,
  119582. &_huff_book_line_128x17_3sub1,
  119583. &_huff_book_line_128x17_3sub2,
  119584. &_huff_book_line_128x17_3sub3,
  119585. };
  119586. static static_codebook *_floor_256x4low_books[]={
  119587. &_huff_book_line_256x4low_class0,
  119588. &_huff_book_line_256x4low_0sub0,
  119589. &_huff_book_line_256x4low_0sub1,
  119590. &_huff_book_line_256x4low_0sub2,
  119591. &_huff_book_line_256x4low_0sub3,
  119592. };
  119593. static static_codebook *_floor_1024x27_books[]={
  119594. &_huff_book_line_1024x27_class1,
  119595. &_huff_book_line_1024x27_class2,
  119596. &_huff_book_line_1024x27_class3,
  119597. &_huff_book_line_1024x27_class4,
  119598. &_huff_book_line_1024x27_0sub0,
  119599. &_huff_book_line_1024x27_1sub0,
  119600. &_huff_book_line_1024x27_1sub1,
  119601. &_huff_book_line_1024x27_2sub0,
  119602. &_huff_book_line_1024x27_2sub1,
  119603. &_huff_book_line_1024x27_3sub1,
  119604. &_huff_book_line_1024x27_3sub2,
  119605. &_huff_book_line_1024x27_3sub3,
  119606. &_huff_book_line_1024x27_4sub1,
  119607. &_huff_book_line_1024x27_4sub2,
  119608. &_huff_book_line_1024x27_4sub3,
  119609. };
  119610. static static_codebook *_floor_2048x27_books[]={
  119611. &_huff_book_line_2048x27_class1,
  119612. &_huff_book_line_2048x27_class2,
  119613. &_huff_book_line_2048x27_class3,
  119614. &_huff_book_line_2048x27_class4,
  119615. &_huff_book_line_2048x27_0sub0,
  119616. &_huff_book_line_2048x27_1sub0,
  119617. &_huff_book_line_2048x27_1sub1,
  119618. &_huff_book_line_2048x27_2sub0,
  119619. &_huff_book_line_2048x27_2sub1,
  119620. &_huff_book_line_2048x27_3sub1,
  119621. &_huff_book_line_2048x27_3sub2,
  119622. &_huff_book_line_2048x27_3sub3,
  119623. &_huff_book_line_2048x27_4sub1,
  119624. &_huff_book_line_2048x27_4sub2,
  119625. &_huff_book_line_2048x27_4sub3,
  119626. };
  119627. static static_codebook *_floor_512x17_books[]={
  119628. &_huff_book_line_512x17_class1,
  119629. &_huff_book_line_512x17_class2,
  119630. &_huff_book_line_512x17_class3,
  119631. &_huff_book_line_512x17_0sub0,
  119632. &_huff_book_line_512x17_1sub0,
  119633. &_huff_book_line_512x17_1sub1,
  119634. &_huff_book_line_512x17_2sub1,
  119635. &_huff_book_line_512x17_2sub2,
  119636. &_huff_book_line_512x17_2sub3,
  119637. &_huff_book_line_512x17_3sub1,
  119638. &_huff_book_line_512x17_3sub2,
  119639. &_huff_book_line_512x17_3sub3,
  119640. };
  119641. static static_codebook **_floor_books[10]={
  119642. _floor_128x4_books,
  119643. _floor_256x4_books,
  119644. _floor_128x7_books,
  119645. _floor_256x7_books,
  119646. _floor_128x11_books,
  119647. _floor_128x17_books,
  119648. _floor_256x4low_books,
  119649. _floor_1024x27_books,
  119650. _floor_2048x27_books,
  119651. _floor_512x17_books,
  119652. };
  119653. static vorbis_info_floor1 _floor[10]={
  119654. /* 128 x 4 */
  119655. {
  119656. 1,{0},{4},{2},{0},
  119657. {{1,2,3,4}},
  119658. 4,{0,128, 33,8,16,70},
  119659. 60,30,500, 1.,18., -1
  119660. },
  119661. /* 256 x 4 */
  119662. {
  119663. 1,{0},{4},{2},{0},
  119664. {{1,2,3,4}},
  119665. 4,{0,256, 66,16,32,140},
  119666. 60,30,500, 1.,18., -1
  119667. },
  119668. /* 128 x 7 */
  119669. {
  119670. 2,{0,1},{3,4},{2,2},{0,1},
  119671. {{-1,2,3,4},{-1,5,6,7}},
  119672. 4,{0,128, 14,4,58, 2,8,28,90},
  119673. 60,30,500, 1.,18., -1
  119674. },
  119675. /* 256 x 7 */
  119676. {
  119677. 2,{0,1},{3,4},{2,2},{0,1},
  119678. {{-1,2,3,4},{-1,5,6,7}},
  119679. 4,{0,256, 28,8,116, 4,16,56,180},
  119680. 60,30,500, 1.,18., -1
  119681. },
  119682. /* 128 x 11 */
  119683. {
  119684. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  119685. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  119686. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  119687. 60,30,500, 1,18., -1
  119688. },
  119689. /* 128 x 17 */
  119690. {
  119691. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  119692. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  119693. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  119694. 60,30,500, 1,18., -1
  119695. },
  119696. /* 256 x 4 (low bitrate version) */
  119697. {
  119698. 1,{0},{4},{2},{0},
  119699. {{1,2,3,4}},
  119700. 4,{0,256, 66,16,32,140},
  119701. 60,30,500, 1.,18., -1
  119702. },
  119703. /* 1024 x 27 */
  119704. {
  119705. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  119706. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  119707. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  119708. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  119709. 60,30,500, 3,18., -1 /* lowpass */
  119710. },
  119711. /* 2048 x 27 */
  119712. {
  119713. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  119714. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  119715. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  119716. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  119717. 60,30,500, 3,18., -1 /* lowpass */
  119718. },
  119719. /* 512 x 17 */
  119720. {
  119721. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  119722. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  119723. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  119724. 7,23,39, 55,79,110, 156,232,360},
  119725. 60,30,500, 1,18., -1 /* lowpass! */
  119726. },
  119727. };
  119728. /*** End of inlined file: floor_all.h ***/
  119729. /*** Start of inlined file: residue_44.h ***/
  119730. /*** Start of inlined file: res_books_stereo.h ***/
  119731. static long _vq_quantlist__16c0_s_p1_0[] = {
  119732. 1,
  119733. 0,
  119734. 2,
  119735. };
  119736. static long _vq_lengthlist__16c0_s_p1_0[] = {
  119737. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  119738. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119742. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  119743. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119747. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  119748. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0,
  119765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  119783. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  119784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  119788. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  119789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  119793. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  119794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119828. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  119829. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119833. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  119834. 0, 0, 0, 0, 0, 9,10,12, 0, 0, 0, 0, 0, 0, 0, 0,
  119835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119838. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  119839. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  119840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0,
  120135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120147. 0,
  120148. };
  120149. static float _vq_quantthresh__16c0_s_p1_0[] = {
  120150. -0.5, 0.5,
  120151. };
  120152. static long _vq_quantmap__16c0_s_p1_0[] = {
  120153. 1, 0, 2,
  120154. };
  120155. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  120156. _vq_quantthresh__16c0_s_p1_0,
  120157. _vq_quantmap__16c0_s_p1_0,
  120158. 3,
  120159. 3
  120160. };
  120161. static static_codebook _16c0_s_p1_0 = {
  120162. 8, 6561,
  120163. _vq_lengthlist__16c0_s_p1_0,
  120164. 1, -535822336, 1611661312, 2, 0,
  120165. _vq_quantlist__16c0_s_p1_0,
  120166. NULL,
  120167. &_vq_auxt__16c0_s_p1_0,
  120168. NULL,
  120169. 0
  120170. };
  120171. static long _vq_quantlist__16c0_s_p2_0[] = {
  120172. 2,
  120173. 1,
  120174. 3,
  120175. 0,
  120176. 4,
  120177. };
  120178. static long _vq_lengthlist__16c0_s_p2_0[] = {
  120179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120218. 0,
  120219. };
  120220. static float _vq_quantthresh__16c0_s_p2_0[] = {
  120221. -1.5, -0.5, 0.5, 1.5,
  120222. };
  120223. static long _vq_quantmap__16c0_s_p2_0[] = {
  120224. 3, 1, 0, 2, 4,
  120225. };
  120226. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  120227. _vq_quantthresh__16c0_s_p2_0,
  120228. _vq_quantmap__16c0_s_p2_0,
  120229. 5,
  120230. 5
  120231. };
  120232. static static_codebook _16c0_s_p2_0 = {
  120233. 4, 625,
  120234. _vq_lengthlist__16c0_s_p2_0,
  120235. 1, -533725184, 1611661312, 3, 0,
  120236. _vq_quantlist__16c0_s_p2_0,
  120237. NULL,
  120238. &_vq_auxt__16c0_s_p2_0,
  120239. NULL,
  120240. 0
  120241. };
  120242. static long _vq_quantlist__16c0_s_p3_0[] = {
  120243. 2,
  120244. 1,
  120245. 3,
  120246. 0,
  120247. 4,
  120248. };
  120249. static long _vq_lengthlist__16c0_s_p3_0[] = {
  120250. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  120252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120253. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  120255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120256. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  120257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120289. 0,
  120290. };
  120291. static float _vq_quantthresh__16c0_s_p3_0[] = {
  120292. -1.5, -0.5, 0.5, 1.5,
  120293. };
  120294. static long _vq_quantmap__16c0_s_p3_0[] = {
  120295. 3, 1, 0, 2, 4,
  120296. };
  120297. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  120298. _vq_quantthresh__16c0_s_p3_0,
  120299. _vq_quantmap__16c0_s_p3_0,
  120300. 5,
  120301. 5
  120302. };
  120303. static static_codebook _16c0_s_p3_0 = {
  120304. 4, 625,
  120305. _vq_lengthlist__16c0_s_p3_0,
  120306. 1, -533725184, 1611661312, 3, 0,
  120307. _vq_quantlist__16c0_s_p3_0,
  120308. NULL,
  120309. &_vq_auxt__16c0_s_p3_0,
  120310. NULL,
  120311. 0
  120312. };
  120313. static long _vq_quantlist__16c0_s_p4_0[] = {
  120314. 4,
  120315. 3,
  120316. 5,
  120317. 2,
  120318. 6,
  120319. 1,
  120320. 7,
  120321. 0,
  120322. 8,
  120323. };
  120324. static long _vq_lengthlist__16c0_s_p4_0[] = {
  120325. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  120326. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  120327. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  120328. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  120329. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120330. 0,
  120331. };
  120332. static float _vq_quantthresh__16c0_s_p4_0[] = {
  120333. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  120334. };
  120335. static long _vq_quantmap__16c0_s_p4_0[] = {
  120336. 7, 5, 3, 1, 0, 2, 4, 6,
  120337. 8,
  120338. };
  120339. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  120340. _vq_quantthresh__16c0_s_p4_0,
  120341. _vq_quantmap__16c0_s_p4_0,
  120342. 9,
  120343. 9
  120344. };
  120345. static static_codebook _16c0_s_p4_0 = {
  120346. 2, 81,
  120347. _vq_lengthlist__16c0_s_p4_0,
  120348. 1, -531628032, 1611661312, 4, 0,
  120349. _vq_quantlist__16c0_s_p4_0,
  120350. NULL,
  120351. &_vq_auxt__16c0_s_p4_0,
  120352. NULL,
  120353. 0
  120354. };
  120355. static long _vq_quantlist__16c0_s_p5_0[] = {
  120356. 4,
  120357. 3,
  120358. 5,
  120359. 2,
  120360. 6,
  120361. 1,
  120362. 7,
  120363. 0,
  120364. 8,
  120365. };
  120366. static long _vq_lengthlist__16c0_s_p5_0[] = {
  120367. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  120368. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  120369. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  120370. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  120371. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  120372. 10,
  120373. };
  120374. static float _vq_quantthresh__16c0_s_p5_0[] = {
  120375. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  120376. };
  120377. static long _vq_quantmap__16c0_s_p5_0[] = {
  120378. 7, 5, 3, 1, 0, 2, 4, 6,
  120379. 8,
  120380. };
  120381. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  120382. _vq_quantthresh__16c0_s_p5_0,
  120383. _vq_quantmap__16c0_s_p5_0,
  120384. 9,
  120385. 9
  120386. };
  120387. static static_codebook _16c0_s_p5_0 = {
  120388. 2, 81,
  120389. _vq_lengthlist__16c0_s_p5_0,
  120390. 1, -531628032, 1611661312, 4, 0,
  120391. _vq_quantlist__16c0_s_p5_0,
  120392. NULL,
  120393. &_vq_auxt__16c0_s_p5_0,
  120394. NULL,
  120395. 0
  120396. };
  120397. static long _vq_quantlist__16c0_s_p6_0[] = {
  120398. 8,
  120399. 7,
  120400. 9,
  120401. 6,
  120402. 10,
  120403. 5,
  120404. 11,
  120405. 4,
  120406. 12,
  120407. 3,
  120408. 13,
  120409. 2,
  120410. 14,
  120411. 1,
  120412. 15,
  120413. 0,
  120414. 16,
  120415. };
  120416. static long _vq_lengthlist__16c0_s_p6_0[] = {
  120417. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  120418. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  120419. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  120420. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  120421. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  120422. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  120423. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  120424. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  120425. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  120426. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  120427. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  120428. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  120429. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  120430. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  120431. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  120432. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  120433. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  120434. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  120435. 14,
  120436. };
  120437. static float _vq_quantthresh__16c0_s_p6_0[] = {
  120438. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  120439. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  120440. };
  120441. static long _vq_quantmap__16c0_s_p6_0[] = {
  120442. 15, 13, 11, 9, 7, 5, 3, 1,
  120443. 0, 2, 4, 6, 8, 10, 12, 14,
  120444. 16,
  120445. };
  120446. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  120447. _vq_quantthresh__16c0_s_p6_0,
  120448. _vq_quantmap__16c0_s_p6_0,
  120449. 17,
  120450. 17
  120451. };
  120452. static static_codebook _16c0_s_p6_0 = {
  120453. 2, 289,
  120454. _vq_lengthlist__16c0_s_p6_0,
  120455. 1, -529530880, 1611661312, 5, 0,
  120456. _vq_quantlist__16c0_s_p6_0,
  120457. NULL,
  120458. &_vq_auxt__16c0_s_p6_0,
  120459. NULL,
  120460. 0
  120461. };
  120462. static long _vq_quantlist__16c0_s_p7_0[] = {
  120463. 1,
  120464. 0,
  120465. 2,
  120466. };
  120467. static long _vq_lengthlist__16c0_s_p7_0[] = {
  120468. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  120469. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  120470. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  120471. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  120472. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  120473. 13,
  120474. };
  120475. static float _vq_quantthresh__16c0_s_p7_0[] = {
  120476. -5.5, 5.5,
  120477. };
  120478. static long _vq_quantmap__16c0_s_p7_0[] = {
  120479. 1, 0, 2,
  120480. };
  120481. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  120482. _vq_quantthresh__16c0_s_p7_0,
  120483. _vq_quantmap__16c0_s_p7_0,
  120484. 3,
  120485. 3
  120486. };
  120487. static static_codebook _16c0_s_p7_0 = {
  120488. 4, 81,
  120489. _vq_lengthlist__16c0_s_p7_0,
  120490. 1, -529137664, 1618345984, 2, 0,
  120491. _vq_quantlist__16c0_s_p7_0,
  120492. NULL,
  120493. &_vq_auxt__16c0_s_p7_0,
  120494. NULL,
  120495. 0
  120496. };
  120497. static long _vq_quantlist__16c0_s_p7_1[] = {
  120498. 5,
  120499. 4,
  120500. 6,
  120501. 3,
  120502. 7,
  120503. 2,
  120504. 8,
  120505. 1,
  120506. 9,
  120507. 0,
  120508. 10,
  120509. };
  120510. static long _vq_lengthlist__16c0_s_p7_1[] = {
  120511. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  120512. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  120513. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  120514. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  120515. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  120516. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  120517. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  120518. 11,11,11, 9, 9, 9, 9,10,10,
  120519. };
  120520. static float _vq_quantthresh__16c0_s_p7_1[] = {
  120521. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  120522. 3.5, 4.5,
  120523. };
  120524. static long _vq_quantmap__16c0_s_p7_1[] = {
  120525. 9, 7, 5, 3, 1, 0, 2, 4,
  120526. 6, 8, 10,
  120527. };
  120528. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  120529. _vq_quantthresh__16c0_s_p7_1,
  120530. _vq_quantmap__16c0_s_p7_1,
  120531. 11,
  120532. 11
  120533. };
  120534. static static_codebook _16c0_s_p7_1 = {
  120535. 2, 121,
  120536. _vq_lengthlist__16c0_s_p7_1,
  120537. 1, -531365888, 1611661312, 4, 0,
  120538. _vq_quantlist__16c0_s_p7_1,
  120539. NULL,
  120540. &_vq_auxt__16c0_s_p7_1,
  120541. NULL,
  120542. 0
  120543. };
  120544. static long _vq_quantlist__16c0_s_p8_0[] = {
  120545. 6,
  120546. 5,
  120547. 7,
  120548. 4,
  120549. 8,
  120550. 3,
  120551. 9,
  120552. 2,
  120553. 10,
  120554. 1,
  120555. 11,
  120556. 0,
  120557. 12,
  120558. };
  120559. static long _vq_lengthlist__16c0_s_p8_0[] = {
  120560. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  120561. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  120562. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  120563. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  120564. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  120565. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  120566. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  120567. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  120568. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  120569. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  120570. 0,12,13,13,12,13,14,14,14,
  120571. };
  120572. static float _vq_quantthresh__16c0_s_p8_0[] = {
  120573. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  120574. 12.5, 17.5, 22.5, 27.5,
  120575. };
  120576. static long _vq_quantmap__16c0_s_p8_0[] = {
  120577. 11, 9, 7, 5, 3, 1, 0, 2,
  120578. 4, 6, 8, 10, 12,
  120579. };
  120580. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  120581. _vq_quantthresh__16c0_s_p8_0,
  120582. _vq_quantmap__16c0_s_p8_0,
  120583. 13,
  120584. 13
  120585. };
  120586. static static_codebook _16c0_s_p8_0 = {
  120587. 2, 169,
  120588. _vq_lengthlist__16c0_s_p8_0,
  120589. 1, -526516224, 1616117760, 4, 0,
  120590. _vq_quantlist__16c0_s_p8_0,
  120591. NULL,
  120592. &_vq_auxt__16c0_s_p8_0,
  120593. NULL,
  120594. 0
  120595. };
  120596. static long _vq_quantlist__16c0_s_p8_1[] = {
  120597. 2,
  120598. 1,
  120599. 3,
  120600. 0,
  120601. 4,
  120602. };
  120603. static long _vq_lengthlist__16c0_s_p8_1[] = {
  120604. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  120605. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  120606. };
  120607. static float _vq_quantthresh__16c0_s_p8_1[] = {
  120608. -1.5, -0.5, 0.5, 1.5,
  120609. };
  120610. static long _vq_quantmap__16c0_s_p8_1[] = {
  120611. 3, 1, 0, 2, 4,
  120612. };
  120613. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  120614. _vq_quantthresh__16c0_s_p8_1,
  120615. _vq_quantmap__16c0_s_p8_1,
  120616. 5,
  120617. 5
  120618. };
  120619. static static_codebook _16c0_s_p8_1 = {
  120620. 2, 25,
  120621. _vq_lengthlist__16c0_s_p8_1,
  120622. 1, -533725184, 1611661312, 3, 0,
  120623. _vq_quantlist__16c0_s_p8_1,
  120624. NULL,
  120625. &_vq_auxt__16c0_s_p8_1,
  120626. NULL,
  120627. 0
  120628. };
  120629. static long _vq_quantlist__16c0_s_p9_0[] = {
  120630. 1,
  120631. 0,
  120632. 2,
  120633. };
  120634. static long _vq_lengthlist__16c0_s_p9_0[] = {
  120635. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120636. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120637. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120638. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120639. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120640. 7,
  120641. };
  120642. static float _vq_quantthresh__16c0_s_p9_0[] = {
  120643. -157.5, 157.5,
  120644. };
  120645. static long _vq_quantmap__16c0_s_p9_0[] = {
  120646. 1, 0, 2,
  120647. };
  120648. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  120649. _vq_quantthresh__16c0_s_p9_0,
  120650. _vq_quantmap__16c0_s_p9_0,
  120651. 3,
  120652. 3
  120653. };
  120654. static static_codebook _16c0_s_p9_0 = {
  120655. 4, 81,
  120656. _vq_lengthlist__16c0_s_p9_0,
  120657. 1, -518803456, 1628680192, 2, 0,
  120658. _vq_quantlist__16c0_s_p9_0,
  120659. NULL,
  120660. &_vq_auxt__16c0_s_p9_0,
  120661. NULL,
  120662. 0
  120663. };
  120664. static long _vq_quantlist__16c0_s_p9_1[] = {
  120665. 7,
  120666. 6,
  120667. 8,
  120668. 5,
  120669. 9,
  120670. 4,
  120671. 10,
  120672. 3,
  120673. 11,
  120674. 2,
  120675. 12,
  120676. 1,
  120677. 13,
  120678. 0,
  120679. 14,
  120680. };
  120681. static long _vq_lengthlist__16c0_s_p9_1[] = {
  120682. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  120683. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  120684. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  120685. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  120686. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120687. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120688. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120689. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120690. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120691. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120692. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120693. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120694. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120695. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120696. 10,
  120697. };
  120698. static float _vq_quantthresh__16c0_s_p9_1[] = {
  120699. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  120700. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  120701. };
  120702. static long _vq_quantmap__16c0_s_p9_1[] = {
  120703. 13, 11, 9, 7, 5, 3, 1, 0,
  120704. 2, 4, 6, 8, 10, 12, 14,
  120705. };
  120706. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  120707. _vq_quantthresh__16c0_s_p9_1,
  120708. _vq_quantmap__16c0_s_p9_1,
  120709. 15,
  120710. 15
  120711. };
  120712. static static_codebook _16c0_s_p9_1 = {
  120713. 2, 225,
  120714. _vq_lengthlist__16c0_s_p9_1,
  120715. 1, -520986624, 1620377600, 4, 0,
  120716. _vq_quantlist__16c0_s_p9_1,
  120717. NULL,
  120718. &_vq_auxt__16c0_s_p9_1,
  120719. NULL,
  120720. 0
  120721. };
  120722. static long _vq_quantlist__16c0_s_p9_2[] = {
  120723. 10,
  120724. 9,
  120725. 11,
  120726. 8,
  120727. 12,
  120728. 7,
  120729. 13,
  120730. 6,
  120731. 14,
  120732. 5,
  120733. 15,
  120734. 4,
  120735. 16,
  120736. 3,
  120737. 17,
  120738. 2,
  120739. 18,
  120740. 1,
  120741. 19,
  120742. 0,
  120743. 20,
  120744. };
  120745. static long _vq_lengthlist__16c0_s_p9_2[] = {
  120746. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  120747. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  120748. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  120749. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  120750. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  120751. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  120752. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  120753. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  120754. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  120755. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  120756. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  120757. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  120758. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  120759. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  120760. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  120761. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  120762. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  120763. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  120764. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  120765. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  120766. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  120767. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  120768. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  120769. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  120770. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  120771. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  120772. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  120773. 10,11,10,10,11, 9,10,10,10,
  120774. };
  120775. static float _vq_quantthresh__16c0_s_p9_2[] = {
  120776. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  120777. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  120778. 6.5, 7.5, 8.5, 9.5,
  120779. };
  120780. static long _vq_quantmap__16c0_s_p9_2[] = {
  120781. 19, 17, 15, 13, 11, 9, 7, 5,
  120782. 3, 1, 0, 2, 4, 6, 8, 10,
  120783. 12, 14, 16, 18, 20,
  120784. };
  120785. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  120786. _vq_quantthresh__16c0_s_p9_2,
  120787. _vq_quantmap__16c0_s_p9_2,
  120788. 21,
  120789. 21
  120790. };
  120791. static static_codebook _16c0_s_p9_2 = {
  120792. 2, 441,
  120793. _vq_lengthlist__16c0_s_p9_2,
  120794. 1, -529268736, 1611661312, 5, 0,
  120795. _vq_quantlist__16c0_s_p9_2,
  120796. NULL,
  120797. &_vq_auxt__16c0_s_p9_2,
  120798. NULL,
  120799. 0
  120800. };
  120801. static long _huff_lengthlist__16c0_s_single[] = {
  120802. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  120803. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  120804. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  120805. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  120806. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  120807. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  120808. 16,16,18,18,
  120809. };
  120810. static static_codebook _huff_book__16c0_s_single = {
  120811. 2, 100,
  120812. _huff_lengthlist__16c0_s_single,
  120813. 0, 0, 0, 0, 0,
  120814. NULL,
  120815. NULL,
  120816. NULL,
  120817. NULL,
  120818. 0
  120819. };
  120820. static long _huff_lengthlist__16c1_s_long[] = {
  120821. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  120822. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  120823. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  120824. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  120825. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  120826. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  120827. 12,11,11,13,
  120828. };
  120829. static static_codebook _huff_book__16c1_s_long = {
  120830. 2, 100,
  120831. _huff_lengthlist__16c1_s_long,
  120832. 0, 0, 0, 0, 0,
  120833. NULL,
  120834. NULL,
  120835. NULL,
  120836. NULL,
  120837. 0
  120838. };
  120839. static long _vq_quantlist__16c1_s_p1_0[] = {
  120840. 1,
  120841. 0,
  120842. 2,
  120843. };
  120844. static long _vq_lengthlist__16c1_s_p1_0[] = {
  120845. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  120846. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120850. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  120851. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120855. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  120856. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  120891. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  120892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  120896. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  120897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 7, 9, 9, 0, 0,
  120901. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  120902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120936. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  120937. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120941. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  120942. 0, 0, 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  120943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120946. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  120947. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  120948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120999. 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121255. 0,
  121256. };
  121257. static float _vq_quantthresh__16c1_s_p1_0[] = {
  121258. -0.5, 0.5,
  121259. };
  121260. static long _vq_quantmap__16c1_s_p1_0[] = {
  121261. 1, 0, 2,
  121262. };
  121263. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  121264. _vq_quantthresh__16c1_s_p1_0,
  121265. _vq_quantmap__16c1_s_p1_0,
  121266. 3,
  121267. 3
  121268. };
  121269. static static_codebook _16c1_s_p1_0 = {
  121270. 8, 6561,
  121271. _vq_lengthlist__16c1_s_p1_0,
  121272. 1, -535822336, 1611661312, 2, 0,
  121273. _vq_quantlist__16c1_s_p1_0,
  121274. NULL,
  121275. &_vq_auxt__16c1_s_p1_0,
  121276. NULL,
  121277. 0
  121278. };
  121279. static long _vq_quantlist__16c1_s_p2_0[] = {
  121280. 2,
  121281. 1,
  121282. 3,
  121283. 0,
  121284. 4,
  121285. };
  121286. static long _vq_lengthlist__16c1_s_p2_0[] = {
  121287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121326. 0,
  121327. };
  121328. static float _vq_quantthresh__16c1_s_p2_0[] = {
  121329. -1.5, -0.5, 0.5, 1.5,
  121330. };
  121331. static long _vq_quantmap__16c1_s_p2_0[] = {
  121332. 3, 1, 0, 2, 4,
  121333. };
  121334. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  121335. _vq_quantthresh__16c1_s_p2_0,
  121336. _vq_quantmap__16c1_s_p2_0,
  121337. 5,
  121338. 5
  121339. };
  121340. static static_codebook _16c1_s_p2_0 = {
  121341. 4, 625,
  121342. _vq_lengthlist__16c1_s_p2_0,
  121343. 1, -533725184, 1611661312, 3, 0,
  121344. _vq_quantlist__16c1_s_p2_0,
  121345. NULL,
  121346. &_vq_auxt__16c1_s_p2_0,
  121347. NULL,
  121348. 0
  121349. };
  121350. static long _vq_quantlist__16c1_s_p3_0[] = {
  121351. 2,
  121352. 1,
  121353. 3,
  121354. 0,
  121355. 4,
  121356. };
  121357. static long _vq_lengthlist__16c1_s_p3_0[] = {
  121358. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  121360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121361. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  121363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121364. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  121365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121397. 0,
  121398. };
  121399. static float _vq_quantthresh__16c1_s_p3_0[] = {
  121400. -1.5, -0.5, 0.5, 1.5,
  121401. };
  121402. static long _vq_quantmap__16c1_s_p3_0[] = {
  121403. 3, 1, 0, 2, 4,
  121404. };
  121405. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  121406. _vq_quantthresh__16c1_s_p3_0,
  121407. _vq_quantmap__16c1_s_p3_0,
  121408. 5,
  121409. 5
  121410. };
  121411. static static_codebook _16c1_s_p3_0 = {
  121412. 4, 625,
  121413. _vq_lengthlist__16c1_s_p3_0,
  121414. 1, -533725184, 1611661312, 3, 0,
  121415. _vq_quantlist__16c1_s_p3_0,
  121416. NULL,
  121417. &_vq_auxt__16c1_s_p3_0,
  121418. NULL,
  121419. 0
  121420. };
  121421. static long _vq_quantlist__16c1_s_p4_0[] = {
  121422. 4,
  121423. 3,
  121424. 5,
  121425. 2,
  121426. 6,
  121427. 1,
  121428. 7,
  121429. 0,
  121430. 8,
  121431. };
  121432. static long _vq_lengthlist__16c1_s_p4_0[] = {
  121433. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  121434. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  121435. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  121436. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  121437. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121438. 0,
  121439. };
  121440. static float _vq_quantthresh__16c1_s_p4_0[] = {
  121441. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  121442. };
  121443. static long _vq_quantmap__16c1_s_p4_0[] = {
  121444. 7, 5, 3, 1, 0, 2, 4, 6,
  121445. 8,
  121446. };
  121447. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  121448. _vq_quantthresh__16c1_s_p4_0,
  121449. _vq_quantmap__16c1_s_p4_0,
  121450. 9,
  121451. 9
  121452. };
  121453. static static_codebook _16c1_s_p4_0 = {
  121454. 2, 81,
  121455. _vq_lengthlist__16c1_s_p4_0,
  121456. 1, -531628032, 1611661312, 4, 0,
  121457. _vq_quantlist__16c1_s_p4_0,
  121458. NULL,
  121459. &_vq_auxt__16c1_s_p4_0,
  121460. NULL,
  121461. 0
  121462. };
  121463. static long _vq_quantlist__16c1_s_p5_0[] = {
  121464. 4,
  121465. 3,
  121466. 5,
  121467. 2,
  121468. 6,
  121469. 1,
  121470. 7,
  121471. 0,
  121472. 8,
  121473. };
  121474. static long _vq_lengthlist__16c1_s_p5_0[] = {
  121475. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  121476. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  121477. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  121478. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  121479. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  121480. 10,
  121481. };
  121482. static float _vq_quantthresh__16c1_s_p5_0[] = {
  121483. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  121484. };
  121485. static long _vq_quantmap__16c1_s_p5_0[] = {
  121486. 7, 5, 3, 1, 0, 2, 4, 6,
  121487. 8,
  121488. };
  121489. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  121490. _vq_quantthresh__16c1_s_p5_0,
  121491. _vq_quantmap__16c1_s_p5_0,
  121492. 9,
  121493. 9
  121494. };
  121495. static static_codebook _16c1_s_p5_0 = {
  121496. 2, 81,
  121497. _vq_lengthlist__16c1_s_p5_0,
  121498. 1, -531628032, 1611661312, 4, 0,
  121499. _vq_quantlist__16c1_s_p5_0,
  121500. NULL,
  121501. &_vq_auxt__16c1_s_p5_0,
  121502. NULL,
  121503. 0
  121504. };
  121505. static long _vq_quantlist__16c1_s_p6_0[] = {
  121506. 8,
  121507. 7,
  121508. 9,
  121509. 6,
  121510. 10,
  121511. 5,
  121512. 11,
  121513. 4,
  121514. 12,
  121515. 3,
  121516. 13,
  121517. 2,
  121518. 14,
  121519. 1,
  121520. 15,
  121521. 0,
  121522. 16,
  121523. };
  121524. static long _vq_lengthlist__16c1_s_p6_0[] = {
  121525. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  121526. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  121527. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  121528. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  121529. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  121530. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  121531. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  121532. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  121533. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  121534. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  121535. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  121536. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  121537. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  121538. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  121539. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  121540. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  121541. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  121542. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  121543. 14,
  121544. };
  121545. static float _vq_quantthresh__16c1_s_p6_0[] = {
  121546. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  121547. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  121548. };
  121549. static long _vq_quantmap__16c1_s_p6_0[] = {
  121550. 15, 13, 11, 9, 7, 5, 3, 1,
  121551. 0, 2, 4, 6, 8, 10, 12, 14,
  121552. 16,
  121553. };
  121554. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  121555. _vq_quantthresh__16c1_s_p6_0,
  121556. _vq_quantmap__16c1_s_p6_0,
  121557. 17,
  121558. 17
  121559. };
  121560. static static_codebook _16c1_s_p6_0 = {
  121561. 2, 289,
  121562. _vq_lengthlist__16c1_s_p6_0,
  121563. 1, -529530880, 1611661312, 5, 0,
  121564. _vq_quantlist__16c1_s_p6_0,
  121565. NULL,
  121566. &_vq_auxt__16c1_s_p6_0,
  121567. NULL,
  121568. 0
  121569. };
  121570. static long _vq_quantlist__16c1_s_p7_0[] = {
  121571. 1,
  121572. 0,
  121573. 2,
  121574. };
  121575. static long _vq_lengthlist__16c1_s_p7_0[] = {
  121576. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  121577. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  121578. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  121579. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  121580. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  121581. 11,
  121582. };
  121583. static float _vq_quantthresh__16c1_s_p7_0[] = {
  121584. -5.5, 5.5,
  121585. };
  121586. static long _vq_quantmap__16c1_s_p7_0[] = {
  121587. 1, 0, 2,
  121588. };
  121589. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  121590. _vq_quantthresh__16c1_s_p7_0,
  121591. _vq_quantmap__16c1_s_p7_0,
  121592. 3,
  121593. 3
  121594. };
  121595. static static_codebook _16c1_s_p7_0 = {
  121596. 4, 81,
  121597. _vq_lengthlist__16c1_s_p7_0,
  121598. 1, -529137664, 1618345984, 2, 0,
  121599. _vq_quantlist__16c1_s_p7_0,
  121600. NULL,
  121601. &_vq_auxt__16c1_s_p7_0,
  121602. NULL,
  121603. 0
  121604. };
  121605. static long _vq_quantlist__16c1_s_p7_1[] = {
  121606. 5,
  121607. 4,
  121608. 6,
  121609. 3,
  121610. 7,
  121611. 2,
  121612. 8,
  121613. 1,
  121614. 9,
  121615. 0,
  121616. 10,
  121617. };
  121618. static long _vq_lengthlist__16c1_s_p7_1[] = {
  121619. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  121620. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  121621. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  121622. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  121623. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  121624. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  121625. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  121626. 10,10,10, 8, 8, 8, 8, 9, 9,
  121627. };
  121628. static float _vq_quantthresh__16c1_s_p7_1[] = {
  121629. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  121630. 3.5, 4.5,
  121631. };
  121632. static long _vq_quantmap__16c1_s_p7_1[] = {
  121633. 9, 7, 5, 3, 1, 0, 2, 4,
  121634. 6, 8, 10,
  121635. };
  121636. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  121637. _vq_quantthresh__16c1_s_p7_1,
  121638. _vq_quantmap__16c1_s_p7_1,
  121639. 11,
  121640. 11
  121641. };
  121642. static static_codebook _16c1_s_p7_1 = {
  121643. 2, 121,
  121644. _vq_lengthlist__16c1_s_p7_1,
  121645. 1, -531365888, 1611661312, 4, 0,
  121646. _vq_quantlist__16c1_s_p7_1,
  121647. NULL,
  121648. &_vq_auxt__16c1_s_p7_1,
  121649. NULL,
  121650. 0
  121651. };
  121652. static long _vq_quantlist__16c1_s_p8_0[] = {
  121653. 6,
  121654. 5,
  121655. 7,
  121656. 4,
  121657. 8,
  121658. 3,
  121659. 9,
  121660. 2,
  121661. 10,
  121662. 1,
  121663. 11,
  121664. 0,
  121665. 12,
  121666. };
  121667. static long _vq_lengthlist__16c1_s_p8_0[] = {
  121668. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  121669. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  121670. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  121671. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  121672. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  121673. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  121674. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  121675. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  121676. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  121677. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  121678. 0,12,12,12,12,13,13,14,15,
  121679. };
  121680. static float _vq_quantthresh__16c1_s_p8_0[] = {
  121681. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  121682. 12.5, 17.5, 22.5, 27.5,
  121683. };
  121684. static long _vq_quantmap__16c1_s_p8_0[] = {
  121685. 11, 9, 7, 5, 3, 1, 0, 2,
  121686. 4, 6, 8, 10, 12,
  121687. };
  121688. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  121689. _vq_quantthresh__16c1_s_p8_0,
  121690. _vq_quantmap__16c1_s_p8_0,
  121691. 13,
  121692. 13
  121693. };
  121694. static static_codebook _16c1_s_p8_0 = {
  121695. 2, 169,
  121696. _vq_lengthlist__16c1_s_p8_0,
  121697. 1, -526516224, 1616117760, 4, 0,
  121698. _vq_quantlist__16c1_s_p8_0,
  121699. NULL,
  121700. &_vq_auxt__16c1_s_p8_0,
  121701. NULL,
  121702. 0
  121703. };
  121704. static long _vq_quantlist__16c1_s_p8_1[] = {
  121705. 2,
  121706. 1,
  121707. 3,
  121708. 0,
  121709. 4,
  121710. };
  121711. static long _vq_lengthlist__16c1_s_p8_1[] = {
  121712. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  121713. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  121714. };
  121715. static float _vq_quantthresh__16c1_s_p8_1[] = {
  121716. -1.5, -0.5, 0.5, 1.5,
  121717. };
  121718. static long _vq_quantmap__16c1_s_p8_1[] = {
  121719. 3, 1, 0, 2, 4,
  121720. };
  121721. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  121722. _vq_quantthresh__16c1_s_p8_1,
  121723. _vq_quantmap__16c1_s_p8_1,
  121724. 5,
  121725. 5
  121726. };
  121727. static static_codebook _16c1_s_p8_1 = {
  121728. 2, 25,
  121729. _vq_lengthlist__16c1_s_p8_1,
  121730. 1, -533725184, 1611661312, 3, 0,
  121731. _vq_quantlist__16c1_s_p8_1,
  121732. NULL,
  121733. &_vq_auxt__16c1_s_p8_1,
  121734. NULL,
  121735. 0
  121736. };
  121737. static long _vq_quantlist__16c1_s_p9_0[] = {
  121738. 6,
  121739. 5,
  121740. 7,
  121741. 4,
  121742. 8,
  121743. 3,
  121744. 9,
  121745. 2,
  121746. 10,
  121747. 1,
  121748. 11,
  121749. 0,
  121750. 12,
  121751. };
  121752. static long _vq_lengthlist__16c1_s_p9_0[] = {
  121753. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121754. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121755. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121756. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121757. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121758. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121759. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121760. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121761. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121762. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121763. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121764. };
  121765. static float _vq_quantthresh__16c1_s_p9_0[] = {
  121766. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  121767. 787.5, 1102.5, 1417.5, 1732.5,
  121768. };
  121769. static long _vq_quantmap__16c1_s_p9_0[] = {
  121770. 11, 9, 7, 5, 3, 1, 0, 2,
  121771. 4, 6, 8, 10, 12,
  121772. };
  121773. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  121774. _vq_quantthresh__16c1_s_p9_0,
  121775. _vq_quantmap__16c1_s_p9_0,
  121776. 13,
  121777. 13
  121778. };
  121779. static static_codebook _16c1_s_p9_0 = {
  121780. 2, 169,
  121781. _vq_lengthlist__16c1_s_p9_0,
  121782. 1, -513964032, 1628680192, 4, 0,
  121783. _vq_quantlist__16c1_s_p9_0,
  121784. NULL,
  121785. &_vq_auxt__16c1_s_p9_0,
  121786. NULL,
  121787. 0
  121788. };
  121789. static long _vq_quantlist__16c1_s_p9_1[] = {
  121790. 7,
  121791. 6,
  121792. 8,
  121793. 5,
  121794. 9,
  121795. 4,
  121796. 10,
  121797. 3,
  121798. 11,
  121799. 2,
  121800. 12,
  121801. 1,
  121802. 13,
  121803. 0,
  121804. 14,
  121805. };
  121806. static long _vq_lengthlist__16c1_s_p9_1[] = {
  121807. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  121808. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  121809. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  121810. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  121811. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  121812. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  121813. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  121814. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  121815. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  121816. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  121817. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  121818. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  121819. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  121820. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  121821. 13,
  121822. };
  121823. static float _vq_quantthresh__16c1_s_p9_1[] = {
  121824. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  121825. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  121826. };
  121827. static long _vq_quantmap__16c1_s_p9_1[] = {
  121828. 13, 11, 9, 7, 5, 3, 1, 0,
  121829. 2, 4, 6, 8, 10, 12, 14,
  121830. };
  121831. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  121832. _vq_quantthresh__16c1_s_p9_1,
  121833. _vq_quantmap__16c1_s_p9_1,
  121834. 15,
  121835. 15
  121836. };
  121837. static static_codebook _16c1_s_p9_1 = {
  121838. 2, 225,
  121839. _vq_lengthlist__16c1_s_p9_1,
  121840. 1, -520986624, 1620377600, 4, 0,
  121841. _vq_quantlist__16c1_s_p9_1,
  121842. NULL,
  121843. &_vq_auxt__16c1_s_p9_1,
  121844. NULL,
  121845. 0
  121846. };
  121847. static long _vq_quantlist__16c1_s_p9_2[] = {
  121848. 10,
  121849. 9,
  121850. 11,
  121851. 8,
  121852. 12,
  121853. 7,
  121854. 13,
  121855. 6,
  121856. 14,
  121857. 5,
  121858. 15,
  121859. 4,
  121860. 16,
  121861. 3,
  121862. 17,
  121863. 2,
  121864. 18,
  121865. 1,
  121866. 19,
  121867. 0,
  121868. 20,
  121869. };
  121870. static long _vq_lengthlist__16c1_s_p9_2[] = {
  121871. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  121872. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  121873. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  121874. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  121875. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  121876. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  121877. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  121878. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  121879. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  121880. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  121881. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  121882. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  121883. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  121884. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  121885. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  121886. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  121887. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  121888. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  121889. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  121890. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  121891. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  121892. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  121893. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  121894. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  121895. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  121896. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  121897. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  121898. 11,11,11,11,12,11,11,12,11,
  121899. };
  121900. static float _vq_quantthresh__16c1_s_p9_2[] = {
  121901. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  121902. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  121903. 6.5, 7.5, 8.5, 9.5,
  121904. };
  121905. static long _vq_quantmap__16c1_s_p9_2[] = {
  121906. 19, 17, 15, 13, 11, 9, 7, 5,
  121907. 3, 1, 0, 2, 4, 6, 8, 10,
  121908. 12, 14, 16, 18, 20,
  121909. };
  121910. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  121911. _vq_quantthresh__16c1_s_p9_2,
  121912. _vq_quantmap__16c1_s_p9_2,
  121913. 21,
  121914. 21
  121915. };
  121916. static static_codebook _16c1_s_p9_2 = {
  121917. 2, 441,
  121918. _vq_lengthlist__16c1_s_p9_2,
  121919. 1, -529268736, 1611661312, 5, 0,
  121920. _vq_quantlist__16c1_s_p9_2,
  121921. NULL,
  121922. &_vq_auxt__16c1_s_p9_2,
  121923. NULL,
  121924. 0
  121925. };
  121926. static long _huff_lengthlist__16c1_s_short[] = {
  121927. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  121928. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  121929. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  121930. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  121931. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  121932. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  121933. 9, 9,10,13,
  121934. };
  121935. static static_codebook _huff_book__16c1_s_short = {
  121936. 2, 100,
  121937. _huff_lengthlist__16c1_s_short,
  121938. 0, 0, 0, 0, 0,
  121939. NULL,
  121940. NULL,
  121941. NULL,
  121942. NULL,
  121943. 0
  121944. };
  121945. static long _huff_lengthlist__16c2_s_long[] = {
  121946. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  121947. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  121948. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  121949. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  121950. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  121951. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  121952. 14,14,16,18,
  121953. };
  121954. static static_codebook _huff_book__16c2_s_long = {
  121955. 2, 100,
  121956. _huff_lengthlist__16c2_s_long,
  121957. 0, 0, 0, 0, 0,
  121958. NULL,
  121959. NULL,
  121960. NULL,
  121961. NULL,
  121962. 0
  121963. };
  121964. static long _vq_quantlist__16c2_s_p1_0[] = {
  121965. 1,
  121966. 0,
  121967. 2,
  121968. };
  121969. static long _vq_lengthlist__16c2_s_p1_0[] = {
  121970. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  121971. 0, 0, 4, 5, 5, 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,
  121976. };
  121977. static float _vq_quantthresh__16c2_s_p1_0[] = {
  121978. -0.5, 0.5,
  121979. };
  121980. static long _vq_quantmap__16c2_s_p1_0[] = {
  121981. 1, 0, 2,
  121982. };
  121983. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  121984. _vq_quantthresh__16c2_s_p1_0,
  121985. _vq_quantmap__16c2_s_p1_0,
  121986. 3,
  121987. 3
  121988. };
  121989. static static_codebook _16c2_s_p1_0 = {
  121990. 4, 81,
  121991. _vq_lengthlist__16c2_s_p1_0,
  121992. 1, -535822336, 1611661312, 2, 0,
  121993. _vq_quantlist__16c2_s_p1_0,
  121994. NULL,
  121995. &_vq_auxt__16c2_s_p1_0,
  121996. NULL,
  121997. 0
  121998. };
  121999. static long _vq_quantlist__16c2_s_p2_0[] = {
  122000. 2,
  122001. 1,
  122002. 3,
  122003. 0,
  122004. 4,
  122005. };
  122006. static long _vq_lengthlist__16c2_s_p2_0[] = {
  122007. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  122008. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  122009. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  122010. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  122011. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  122012. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  122013. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  122014. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  122015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 8, 8, 8,11,11, 0, 0, 0,
  122020. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  122021. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  122022. 0, 0, 0,12,13, 0, 0, 0,13,13, 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, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  122028. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  122029. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  122030. 13,13, 0, 0, 0,12,13, 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, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  122036. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  122037. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  122038. 0, 0,13,13, 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, 8,
  122043. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  122044. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  122045. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  122046. 13,
  122047. };
  122048. static float _vq_quantthresh__16c2_s_p2_0[] = {
  122049. -1.5, -0.5, 0.5, 1.5,
  122050. };
  122051. static long _vq_quantmap__16c2_s_p2_0[] = {
  122052. 3, 1, 0, 2, 4,
  122053. };
  122054. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  122055. _vq_quantthresh__16c2_s_p2_0,
  122056. _vq_quantmap__16c2_s_p2_0,
  122057. 5,
  122058. 5
  122059. };
  122060. static static_codebook _16c2_s_p2_0 = {
  122061. 4, 625,
  122062. _vq_lengthlist__16c2_s_p2_0,
  122063. 1, -533725184, 1611661312, 3, 0,
  122064. _vq_quantlist__16c2_s_p2_0,
  122065. NULL,
  122066. &_vq_auxt__16c2_s_p2_0,
  122067. NULL,
  122068. 0
  122069. };
  122070. static long _vq_quantlist__16c2_s_p3_0[] = {
  122071. 4,
  122072. 3,
  122073. 5,
  122074. 2,
  122075. 6,
  122076. 1,
  122077. 7,
  122078. 0,
  122079. 8,
  122080. };
  122081. static long _vq_lengthlist__16c2_s_p3_0[] = {
  122082. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  122083. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  122084. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  122085. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  122086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122087. 0,
  122088. };
  122089. static float _vq_quantthresh__16c2_s_p3_0[] = {
  122090. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122091. };
  122092. static long _vq_quantmap__16c2_s_p3_0[] = {
  122093. 7, 5, 3, 1, 0, 2, 4, 6,
  122094. 8,
  122095. };
  122096. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  122097. _vq_quantthresh__16c2_s_p3_0,
  122098. _vq_quantmap__16c2_s_p3_0,
  122099. 9,
  122100. 9
  122101. };
  122102. static static_codebook _16c2_s_p3_0 = {
  122103. 2, 81,
  122104. _vq_lengthlist__16c2_s_p3_0,
  122105. 1, -531628032, 1611661312, 4, 0,
  122106. _vq_quantlist__16c2_s_p3_0,
  122107. NULL,
  122108. &_vq_auxt__16c2_s_p3_0,
  122109. NULL,
  122110. 0
  122111. };
  122112. static long _vq_quantlist__16c2_s_p4_0[] = {
  122113. 8,
  122114. 7,
  122115. 9,
  122116. 6,
  122117. 10,
  122118. 5,
  122119. 11,
  122120. 4,
  122121. 12,
  122122. 3,
  122123. 13,
  122124. 2,
  122125. 14,
  122126. 1,
  122127. 15,
  122128. 0,
  122129. 16,
  122130. };
  122131. static long _vq_lengthlist__16c2_s_p4_0[] = {
  122132. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  122133. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  122134. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  122135. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  122136. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  122137. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  122138. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  122139. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  122140. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  122141. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  122142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122150. 0,
  122151. };
  122152. static float _vq_quantthresh__16c2_s_p4_0[] = {
  122153. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  122154. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  122155. };
  122156. static long _vq_quantmap__16c2_s_p4_0[] = {
  122157. 15, 13, 11, 9, 7, 5, 3, 1,
  122158. 0, 2, 4, 6, 8, 10, 12, 14,
  122159. 16,
  122160. };
  122161. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  122162. _vq_quantthresh__16c2_s_p4_0,
  122163. _vq_quantmap__16c2_s_p4_0,
  122164. 17,
  122165. 17
  122166. };
  122167. static static_codebook _16c2_s_p4_0 = {
  122168. 2, 289,
  122169. _vq_lengthlist__16c2_s_p4_0,
  122170. 1, -529530880, 1611661312, 5, 0,
  122171. _vq_quantlist__16c2_s_p4_0,
  122172. NULL,
  122173. &_vq_auxt__16c2_s_p4_0,
  122174. NULL,
  122175. 0
  122176. };
  122177. static long _vq_quantlist__16c2_s_p5_0[] = {
  122178. 1,
  122179. 0,
  122180. 2,
  122181. };
  122182. static long _vq_lengthlist__16c2_s_p5_0[] = {
  122183. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  122184. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  122185. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  122186. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  122187. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  122188. 12,
  122189. };
  122190. static float _vq_quantthresh__16c2_s_p5_0[] = {
  122191. -5.5, 5.5,
  122192. };
  122193. static long _vq_quantmap__16c2_s_p5_0[] = {
  122194. 1, 0, 2,
  122195. };
  122196. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  122197. _vq_quantthresh__16c2_s_p5_0,
  122198. _vq_quantmap__16c2_s_p5_0,
  122199. 3,
  122200. 3
  122201. };
  122202. static static_codebook _16c2_s_p5_0 = {
  122203. 4, 81,
  122204. _vq_lengthlist__16c2_s_p5_0,
  122205. 1, -529137664, 1618345984, 2, 0,
  122206. _vq_quantlist__16c2_s_p5_0,
  122207. NULL,
  122208. &_vq_auxt__16c2_s_p5_0,
  122209. NULL,
  122210. 0
  122211. };
  122212. static long _vq_quantlist__16c2_s_p5_1[] = {
  122213. 5,
  122214. 4,
  122215. 6,
  122216. 3,
  122217. 7,
  122218. 2,
  122219. 8,
  122220. 1,
  122221. 9,
  122222. 0,
  122223. 10,
  122224. };
  122225. static long _vq_lengthlist__16c2_s_p5_1[] = {
  122226. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  122227. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  122228. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  122229. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  122230. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  122231. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  122232. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  122233. 11,11,11, 7, 7, 8, 8, 8, 8,
  122234. };
  122235. static float _vq_quantthresh__16c2_s_p5_1[] = {
  122236. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  122237. 3.5, 4.5,
  122238. };
  122239. static long _vq_quantmap__16c2_s_p5_1[] = {
  122240. 9, 7, 5, 3, 1, 0, 2, 4,
  122241. 6, 8, 10,
  122242. };
  122243. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  122244. _vq_quantthresh__16c2_s_p5_1,
  122245. _vq_quantmap__16c2_s_p5_1,
  122246. 11,
  122247. 11
  122248. };
  122249. static static_codebook _16c2_s_p5_1 = {
  122250. 2, 121,
  122251. _vq_lengthlist__16c2_s_p5_1,
  122252. 1, -531365888, 1611661312, 4, 0,
  122253. _vq_quantlist__16c2_s_p5_1,
  122254. NULL,
  122255. &_vq_auxt__16c2_s_p5_1,
  122256. NULL,
  122257. 0
  122258. };
  122259. static long _vq_quantlist__16c2_s_p6_0[] = {
  122260. 6,
  122261. 5,
  122262. 7,
  122263. 4,
  122264. 8,
  122265. 3,
  122266. 9,
  122267. 2,
  122268. 10,
  122269. 1,
  122270. 11,
  122271. 0,
  122272. 12,
  122273. };
  122274. static long _vq_lengthlist__16c2_s_p6_0[] = {
  122275. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  122276. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  122277. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  122278. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  122279. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  122280. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  122281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122285. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122286. };
  122287. static float _vq_quantthresh__16c2_s_p6_0[] = {
  122288. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  122289. 12.5, 17.5, 22.5, 27.5,
  122290. };
  122291. static long _vq_quantmap__16c2_s_p6_0[] = {
  122292. 11, 9, 7, 5, 3, 1, 0, 2,
  122293. 4, 6, 8, 10, 12,
  122294. };
  122295. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  122296. _vq_quantthresh__16c2_s_p6_0,
  122297. _vq_quantmap__16c2_s_p6_0,
  122298. 13,
  122299. 13
  122300. };
  122301. static static_codebook _16c2_s_p6_0 = {
  122302. 2, 169,
  122303. _vq_lengthlist__16c2_s_p6_0,
  122304. 1, -526516224, 1616117760, 4, 0,
  122305. _vq_quantlist__16c2_s_p6_0,
  122306. NULL,
  122307. &_vq_auxt__16c2_s_p6_0,
  122308. NULL,
  122309. 0
  122310. };
  122311. static long _vq_quantlist__16c2_s_p6_1[] = {
  122312. 2,
  122313. 1,
  122314. 3,
  122315. 0,
  122316. 4,
  122317. };
  122318. static long _vq_lengthlist__16c2_s_p6_1[] = {
  122319. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  122320. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  122321. };
  122322. static float _vq_quantthresh__16c2_s_p6_1[] = {
  122323. -1.5, -0.5, 0.5, 1.5,
  122324. };
  122325. static long _vq_quantmap__16c2_s_p6_1[] = {
  122326. 3, 1, 0, 2, 4,
  122327. };
  122328. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  122329. _vq_quantthresh__16c2_s_p6_1,
  122330. _vq_quantmap__16c2_s_p6_1,
  122331. 5,
  122332. 5
  122333. };
  122334. static static_codebook _16c2_s_p6_1 = {
  122335. 2, 25,
  122336. _vq_lengthlist__16c2_s_p6_1,
  122337. 1, -533725184, 1611661312, 3, 0,
  122338. _vq_quantlist__16c2_s_p6_1,
  122339. NULL,
  122340. &_vq_auxt__16c2_s_p6_1,
  122341. NULL,
  122342. 0
  122343. };
  122344. static long _vq_quantlist__16c2_s_p7_0[] = {
  122345. 6,
  122346. 5,
  122347. 7,
  122348. 4,
  122349. 8,
  122350. 3,
  122351. 9,
  122352. 2,
  122353. 10,
  122354. 1,
  122355. 11,
  122356. 0,
  122357. 12,
  122358. };
  122359. static long _vq_lengthlist__16c2_s_p7_0[] = {
  122360. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  122361. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  122362. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  122363. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  122364. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  122365. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  122366. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  122367. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  122368. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  122369. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  122370. 18,13,14,13,13,14,13,15,14,
  122371. };
  122372. static float _vq_quantthresh__16c2_s_p7_0[] = {
  122373. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  122374. 27.5, 38.5, 49.5, 60.5,
  122375. };
  122376. static long _vq_quantmap__16c2_s_p7_0[] = {
  122377. 11, 9, 7, 5, 3, 1, 0, 2,
  122378. 4, 6, 8, 10, 12,
  122379. };
  122380. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  122381. _vq_quantthresh__16c2_s_p7_0,
  122382. _vq_quantmap__16c2_s_p7_0,
  122383. 13,
  122384. 13
  122385. };
  122386. static static_codebook _16c2_s_p7_0 = {
  122387. 2, 169,
  122388. _vq_lengthlist__16c2_s_p7_0,
  122389. 1, -523206656, 1618345984, 4, 0,
  122390. _vq_quantlist__16c2_s_p7_0,
  122391. NULL,
  122392. &_vq_auxt__16c2_s_p7_0,
  122393. NULL,
  122394. 0
  122395. };
  122396. static long _vq_quantlist__16c2_s_p7_1[] = {
  122397. 5,
  122398. 4,
  122399. 6,
  122400. 3,
  122401. 7,
  122402. 2,
  122403. 8,
  122404. 1,
  122405. 9,
  122406. 0,
  122407. 10,
  122408. };
  122409. static long _vq_lengthlist__16c2_s_p7_1[] = {
  122410. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  122411. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  122412. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  122413. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  122414. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  122415. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  122416. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  122417. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  122418. };
  122419. static float _vq_quantthresh__16c2_s_p7_1[] = {
  122420. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  122421. 3.5, 4.5,
  122422. };
  122423. static long _vq_quantmap__16c2_s_p7_1[] = {
  122424. 9, 7, 5, 3, 1, 0, 2, 4,
  122425. 6, 8, 10,
  122426. };
  122427. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  122428. _vq_quantthresh__16c2_s_p7_1,
  122429. _vq_quantmap__16c2_s_p7_1,
  122430. 11,
  122431. 11
  122432. };
  122433. static static_codebook _16c2_s_p7_1 = {
  122434. 2, 121,
  122435. _vq_lengthlist__16c2_s_p7_1,
  122436. 1, -531365888, 1611661312, 4, 0,
  122437. _vq_quantlist__16c2_s_p7_1,
  122438. NULL,
  122439. &_vq_auxt__16c2_s_p7_1,
  122440. NULL,
  122441. 0
  122442. };
  122443. static long _vq_quantlist__16c2_s_p8_0[] = {
  122444. 7,
  122445. 6,
  122446. 8,
  122447. 5,
  122448. 9,
  122449. 4,
  122450. 10,
  122451. 3,
  122452. 11,
  122453. 2,
  122454. 12,
  122455. 1,
  122456. 13,
  122457. 0,
  122458. 14,
  122459. };
  122460. static long _vq_lengthlist__16c2_s_p8_0[] = {
  122461. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  122462. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  122463. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  122464. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  122465. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  122466. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  122467. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  122468. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  122469. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  122470. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  122471. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  122472. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  122473. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  122474. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  122475. 13,
  122476. };
  122477. static float _vq_quantthresh__16c2_s_p8_0[] = {
  122478. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  122479. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  122480. };
  122481. static long _vq_quantmap__16c2_s_p8_0[] = {
  122482. 13, 11, 9, 7, 5, 3, 1, 0,
  122483. 2, 4, 6, 8, 10, 12, 14,
  122484. };
  122485. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  122486. _vq_quantthresh__16c2_s_p8_0,
  122487. _vq_quantmap__16c2_s_p8_0,
  122488. 15,
  122489. 15
  122490. };
  122491. static static_codebook _16c2_s_p8_0 = {
  122492. 2, 225,
  122493. _vq_lengthlist__16c2_s_p8_0,
  122494. 1, -520986624, 1620377600, 4, 0,
  122495. _vq_quantlist__16c2_s_p8_0,
  122496. NULL,
  122497. &_vq_auxt__16c2_s_p8_0,
  122498. NULL,
  122499. 0
  122500. };
  122501. static long _vq_quantlist__16c2_s_p8_1[] = {
  122502. 10,
  122503. 9,
  122504. 11,
  122505. 8,
  122506. 12,
  122507. 7,
  122508. 13,
  122509. 6,
  122510. 14,
  122511. 5,
  122512. 15,
  122513. 4,
  122514. 16,
  122515. 3,
  122516. 17,
  122517. 2,
  122518. 18,
  122519. 1,
  122520. 19,
  122521. 0,
  122522. 20,
  122523. };
  122524. static long _vq_lengthlist__16c2_s_p8_1[] = {
  122525. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  122526. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  122527. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  122528. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  122529. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  122530. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  122531. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  122532. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  122533. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  122534. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  122535. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  122536. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  122537. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  122538. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  122539. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  122540. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  122541. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  122542. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  122543. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  122544. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  122545. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  122546. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  122547. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  122548. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  122549. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  122550. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  122551. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  122552. 10,11,10,10,10,10,10,10,10,
  122553. };
  122554. static float _vq_quantthresh__16c2_s_p8_1[] = {
  122555. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  122556. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  122557. 6.5, 7.5, 8.5, 9.5,
  122558. };
  122559. static long _vq_quantmap__16c2_s_p8_1[] = {
  122560. 19, 17, 15, 13, 11, 9, 7, 5,
  122561. 3, 1, 0, 2, 4, 6, 8, 10,
  122562. 12, 14, 16, 18, 20,
  122563. };
  122564. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  122565. _vq_quantthresh__16c2_s_p8_1,
  122566. _vq_quantmap__16c2_s_p8_1,
  122567. 21,
  122568. 21
  122569. };
  122570. static static_codebook _16c2_s_p8_1 = {
  122571. 2, 441,
  122572. _vq_lengthlist__16c2_s_p8_1,
  122573. 1, -529268736, 1611661312, 5, 0,
  122574. _vq_quantlist__16c2_s_p8_1,
  122575. NULL,
  122576. &_vq_auxt__16c2_s_p8_1,
  122577. NULL,
  122578. 0
  122579. };
  122580. static long _vq_quantlist__16c2_s_p9_0[] = {
  122581. 6,
  122582. 5,
  122583. 7,
  122584. 4,
  122585. 8,
  122586. 3,
  122587. 9,
  122588. 2,
  122589. 10,
  122590. 1,
  122591. 11,
  122592. 0,
  122593. 12,
  122594. };
  122595. static long _vq_lengthlist__16c2_s_p9_0[] = {
  122596. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  122597. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  122598. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  122599. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  122600. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  122601. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122602. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122603. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122604. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122605. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122606. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122607. };
  122608. static float _vq_quantthresh__16c2_s_p9_0[] = {
  122609. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  122610. 2327.5, 3258.5, 4189.5, 5120.5,
  122611. };
  122612. static long _vq_quantmap__16c2_s_p9_0[] = {
  122613. 11, 9, 7, 5, 3, 1, 0, 2,
  122614. 4, 6, 8, 10, 12,
  122615. };
  122616. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  122617. _vq_quantthresh__16c2_s_p9_0,
  122618. _vq_quantmap__16c2_s_p9_0,
  122619. 13,
  122620. 13
  122621. };
  122622. static static_codebook _16c2_s_p9_0 = {
  122623. 2, 169,
  122624. _vq_lengthlist__16c2_s_p9_0,
  122625. 1, -510275072, 1631393792, 4, 0,
  122626. _vq_quantlist__16c2_s_p9_0,
  122627. NULL,
  122628. &_vq_auxt__16c2_s_p9_0,
  122629. NULL,
  122630. 0
  122631. };
  122632. static long _vq_quantlist__16c2_s_p9_1[] = {
  122633. 8,
  122634. 7,
  122635. 9,
  122636. 6,
  122637. 10,
  122638. 5,
  122639. 11,
  122640. 4,
  122641. 12,
  122642. 3,
  122643. 13,
  122644. 2,
  122645. 14,
  122646. 1,
  122647. 15,
  122648. 0,
  122649. 16,
  122650. };
  122651. static long _vq_lengthlist__16c2_s_p9_1[] = {
  122652. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  122653. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  122654. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  122655. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  122656. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  122657. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  122658. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  122659. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  122660. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  122661. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  122662. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122663. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122664. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122665. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122666. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122667. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  122668. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  122669. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122670. 10,
  122671. };
  122672. static float _vq_quantthresh__16c2_s_p9_1[] = {
  122673. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  122674. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  122675. };
  122676. static long _vq_quantmap__16c2_s_p9_1[] = {
  122677. 15, 13, 11, 9, 7, 5, 3, 1,
  122678. 0, 2, 4, 6, 8, 10, 12, 14,
  122679. 16,
  122680. };
  122681. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  122682. _vq_quantthresh__16c2_s_p9_1,
  122683. _vq_quantmap__16c2_s_p9_1,
  122684. 17,
  122685. 17
  122686. };
  122687. static static_codebook _16c2_s_p9_1 = {
  122688. 2, 289,
  122689. _vq_lengthlist__16c2_s_p9_1,
  122690. 1, -518488064, 1622704128, 5, 0,
  122691. _vq_quantlist__16c2_s_p9_1,
  122692. NULL,
  122693. &_vq_auxt__16c2_s_p9_1,
  122694. NULL,
  122695. 0
  122696. };
  122697. static long _vq_quantlist__16c2_s_p9_2[] = {
  122698. 13,
  122699. 12,
  122700. 14,
  122701. 11,
  122702. 15,
  122703. 10,
  122704. 16,
  122705. 9,
  122706. 17,
  122707. 8,
  122708. 18,
  122709. 7,
  122710. 19,
  122711. 6,
  122712. 20,
  122713. 5,
  122714. 21,
  122715. 4,
  122716. 22,
  122717. 3,
  122718. 23,
  122719. 2,
  122720. 24,
  122721. 1,
  122722. 25,
  122723. 0,
  122724. 26,
  122725. };
  122726. static long _vq_lengthlist__16c2_s_p9_2[] = {
  122727. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  122728. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  122729. };
  122730. static float _vq_quantthresh__16c2_s_p9_2[] = {
  122731. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  122732. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  122733. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  122734. 11.5, 12.5,
  122735. };
  122736. static long _vq_quantmap__16c2_s_p9_2[] = {
  122737. 25, 23, 21, 19, 17, 15, 13, 11,
  122738. 9, 7, 5, 3, 1, 0, 2, 4,
  122739. 6, 8, 10, 12, 14, 16, 18, 20,
  122740. 22, 24, 26,
  122741. };
  122742. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  122743. _vq_quantthresh__16c2_s_p9_2,
  122744. _vq_quantmap__16c2_s_p9_2,
  122745. 27,
  122746. 27
  122747. };
  122748. static static_codebook _16c2_s_p9_2 = {
  122749. 1, 27,
  122750. _vq_lengthlist__16c2_s_p9_2,
  122751. 1, -528875520, 1611661312, 5, 0,
  122752. _vq_quantlist__16c2_s_p9_2,
  122753. NULL,
  122754. &_vq_auxt__16c2_s_p9_2,
  122755. NULL,
  122756. 0
  122757. };
  122758. static long _huff_lengthlist__16c2_s_short[] = {
  122759. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  122760. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  122761. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  122762. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  122763. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  122764. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  122765. 15,12,14,14,
  122766. };
  122767. static static_codebook _huff_book__16c2_s_short = {
  122768. 2, 100,
  122769. _huff_lengthlist__16c2_s_short,
  122770. 0, 0, 0, 0, 0,
  122771. NULL,
  122772. NULL,
  122773. NULL,
  122774. NULL,
  122775. 0
  122776. };
  122777. static long _vq_quantlist__8c0_s_p1_0[] = {
  122778. 1,
  122779. 0,
  122780. 2,
  122781. };
  122782. static long _vq_lengthlist__8c0_s_p1_0[] = {
  122783. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122784. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122788. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  122789. 0, 0, 0, 7, 8, 9, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122794. 0, 0, 0, 0, 7, 9, 8, 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, 5, 8, 8, 0, 0, 0, 0,
  122829. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  122834. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 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, 7, 9,10, 0, 0,
  122839. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  122875. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  122880. 0, 0, 0, 0, 0, 9,10,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  122885. 0, 0, 0, 0, 0, 0, 8,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123193. 0,
  123194. };
  123195. static float _vq_quantthresh__8c0_s_p1_0[] = {
  123196. -0.5, 0.5,
  123197. };
  123198. static long _vq_quantmap__8c0_s_p1_0[] = {
  123199. 1, 0, 2,
  123200. };
  123201. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  123202. _vq_quantthresh__8c0_s_p1_0,
  123203. _vq_quantmap__8c0_s_p1_0,
  123204. 3,
  123205. 3
  123206. };
  123207. static static_codebook _8c0_s_p1_0 = {
  123208. 8, 6561,
  123209. _vq_lengthlist__8c0_s_p1_0,
  123210. 1, -535822336, 1611661312, 2, 0,
  123211. _vq_quantlist__8c0_s_p1_0,
  123212. NULL,
  123213. &_vq_auxt__8c0_s_p1_0,
  123214. NULL,
  123215. 0
  123216. };
  123217. static long _vq_quantlist__8c0_s_p2_0[] = {
  123218. 2,
  123219. 1,
  123220. 3,
  123221. 0,
  123222. 4,
  123223. };
  123224. static long _vq_lengthlist__8c0_s_p2_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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123264. 0,
  123265. };
  123266. static float _vq_quantthresh__8c0_s_p2_0[] = {
  123267. -1.5, -0.5, 0.5, 1.5,
  123268. };
  123269. static long _vq_quantmap__8c0_s_p2_0[] = {
  123270. 3, 1, 0, 2, 4,
  123271. };
  123272. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  123273. _vq_quantthresh__8c0_s_p2_0,
  123274. _vq_quantmap__8c0_s_p2_0,
  123275. 5,
  123276. 5
  123277. };
  123278. static static_codebook _8c0_s_p2_0 = {
  123279. 4, 625,
  123280. _vq_lengthlist__8c0_s_p2_0,
  123281. 1, -533725184, 1611661312, 3, 0,
  123282. _vq_quantlist__8c0_s_p2_0,
  123283. NULL,
  123284. &_vq_auxt__8c0_s_p2_0,
  123285. NULL,
  123286. 0
  123287. };
  123288. static long _vq_quantlist__8c0_s_p3_0[] = {
  123289. 2,
  123290. 1,
  123291. 3,
  123292. 0,
  123293. 4,
  123294. };
  123295. static long _vq_lengthlist__8c0_s_p3_0[] = {
  123296. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  123298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123299. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  123301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123302. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  123303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123335. 0,
  123336. };
  123337. static float _vq_quantthresh__8c0_s_p3_0[] = {
  123338. -1.5, -0.5, 0.5, 1.5,
  123339. };
  123340. static long _vq_quantmap__8c0_s_p3_0[] = {
  123341. 3, 1, 0, 2, 4,
  123342. };
  123343. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  123344. _vq_quantthresh__8c0_s_p3_0,
  123345. _vq_quantmap__8c0_s_p3_0,
  123346. 5,
  123347. 5
  123348. };
  123349. static static_codebook _8c0_s_p3_0 = {
  123350. 4, 625,
  123351. _vq_lengthlist__8c0_s_p3_0,
  123352. 1, -533725184, 1611661312, 3, 0,
  123353. _vq_quantlist__8c0_s_p3_0,
  123354. NULL,
  123355. &_vq_auxt__8c0_s_p3_0,
  123356. NULL,
  123357. 0
  123358. };
  123359. static long _vq_quantlist__8c0_s_p4_0[] = {
  123360. 4,
  123361. 3,
  123362. 5,
  123363. 2,
  123364. 6,
  123365. 1,
  123366. 7,
  123367. 0,
  123368. 8,
  123369. };
  123370. static long _vq_lengthlist__8c0_s_p4_0[] = {
  123371. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123372. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123373. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123374. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  123375. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123376. 0,
  123377. };
  123378. static float _vq_quantthresh__8c0_s_p4_0[] = {
  123379. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123380. };
  123381. static long _vq_quantmap__8c0_s_p4_0[] = {
  123382. 7, 5, 3, 1, 0, 2, 4, 6,
  123383. 8,
  123384. };
  123385. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  123386. _vq_quantthresh__8c0_s_p4_0,
  123387. _vq_quantmap__8c0_s_p4_0,
  123388. 9,
  123389. 9
  123390. };
  123391. static static_codebook _8c0_s_p4_0 = {
  123392. 2, 81,
  123393. _vq_lengthlist__8c0_s_p4_0,
  123394. 1, -531628032, 1611661312, 4, 0,
  123395. _vq_quantlist__8c0_s_p4_0,
  123396. NULL,
  123397. &_vq_auxt__8c0_s_p4_0,
  123398. NULL,
  123399. 0
  123400. };
  123401. static long _vq_quantlist__8c0_s_p5_0[] = {
  123402. 4,
  123403. 3,
  123404. 5,
  123405. 2,
  123406. 6,
  123407. 1,
  123408. 7,
  123409. 0,
  123410. 8,
  123411. };
  123412. static long _vq_lengthlist__8c0_s_p5_0[] = {
  123413. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123414. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  123415. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  123416. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  123417. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123418. 10,
  123419. };
  123420. static float _vq_quantthresh__8c0_s_p5_0[] = {
  123421. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123422. };
  123423. static long _vq_quantmap__8c0_s_p5_0[] = {
  123424. 7, 5, 3, 1, 0, 2, 4, 6,
  123425. 8,
  123426. };
  123427. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  123428. _vq_quantthresh__8c0_s_p5_0,
  123429. _vq_quantmap__8c0_s_p5_0,
  123430. 9,
  123431. 9
  123432. };
  123433. static static_codebook _8c0_s_p5_0 = {
  123434. 2, 81,
  123435. _vq_lengthlist__8c0_s_p5_0,
  123436. 1, -531628032, 1611661312, 4, 0,
  123437. _vq_quantlist__8c0_s_p5_0,
  123438. NULL,
  123439. &_vq_auxt__8c0_s_p5_0,
  123440. NULL,
  123441. 0
  123442. };
  123443. static long _vq_quantlist__8c0_s_p6_0[] = {
  123444. 8,
  123445. 7,
  123446. 9,
  123447. 6,
  123448. 10,
  123449. 5,
  123450. 11,
  123451. 4,
  123452. 12,
  123453. 3,
  123454. 13,
  123455. 2,
  123456. 14,
  123457. 1,
  123458. 15,
  123459. 0,
  123460. 16,
  123461. };
  123462. static long _vq_lengthlist__8c0_s_p6_0[] = {
  123463. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  123464. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  123465. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  123466. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  123467. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  123468. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  123469. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  123470. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  123471. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  123472. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123473. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  123474. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  123475. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  123476. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  123477. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  123478. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  123479. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  123480. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  123481. 14,
  123482. };
  123483. static float _vq_quantthresh__8c0_s_p6_0[] = {
  123484. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123485. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123486. };
  123487. static long _vq_quantmap__8c0_s_p6_0[] = {
  123488. 15, 13, 11, 9, 7, 5, 3, 1,
  123489. 0, 2, 4, 6, 8, 10, 12, 14,
  123490. 16,
  123491. };
  123492. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  123493. _vq_quantthresh__8c0_s_p6_0,
  123494. _vq_quantmap__8c0_s_p6_0,
  123495. 17,
  123496. 17
  123497. };
  123498. static static_codebook _8c0_s_p6_0 = {
  123499. 2, 289,
  123500. _vq_lengthlist__8c0_s_p6_0,
  123501. 1, -529530880, 1611661312, 5, 0,
  123502. _vq_quantlist__8c0_s_p6_0,
  123503. NULL,
  123504. &_vq_auxt__8c0_s_p6_0,
  123505. NULL,
  123506. 0
  123507. };
  123508. static long _vq_quantlist__8c0_s_p7_0[] = {
  123509. 1,
  123510. 0,
  123511. 2,
  123512. };
  123513. static long _vq_lengthlist__8c0_s_p7_0[] = {
  123514. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  123515. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  123516. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  123517. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  123518. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  123519. 10,
  123520. };
  123521. static float _vq_quantthresh__8c0_s_p7_0[] = {
  123522. -5.5, 5.5,
  123523. };
  123524. static long _vq_quantmap__8c0_s_p7_0[] = {
  123525. 1, 0, 2,
  123526. };
  123527. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  123528. _vq_quantthresh__8c0_s_p7_0,
  123529. _vq_quantmap__8c0_s_p7_0,
  123530. 3,
  123531. 3
  123532. };
  123533. static static_codebook _8c0_s_p7_0 = {
  123534. 4, 81,
  123535. _vq_lengthlist__8c0_s_p7_0,
  123536. 1, -529137664, 1618345984, 2, 0,
  123537. _vq_quantlist__8c0_s_p7_0,
  123538. NULL,
  123539. &_vq_auxt__8c0_s_p7_0,
  123540. NULL,
  123541. 0
  123542. };
  123543. static long _vq_quantlist__8c0_s_p7_1[] = {
  123544. 5,
  123545. 4,
  123546. 6,
  123547. 3,
  123548. 7,
  123549. 2,
  123550. 8,
  123551. 1,
  123552. 9,
  123553. 0,
  123554. 10,
  123555. };
  123556. static long _vq_lengthlist__8c0_s_p7_1[] = {
  123557. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  123558. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  123559. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  123560. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  123561. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  123562. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  123563. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  123564. 10,10,10, 9, 9, 9,10,10,10,
  123565. };
  123566. static float _vq_quantthresh__8c0_s_p7_1[] = {
  123567. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123568. 3.5, 4.5,
  123569. };
  123570. static long _vq_quantmap__8c0_s_p7_1[] = {
  123571. 9, 7, 5, 3, 1, 0, 2, 4,
  123572. 6, 8, 10,
  123573. };
  123574. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  123575. _vq_quantthresh__8c0_s_p7_1,
  123576. _vq_quantmap__8c0_s_p7_1,
  123577. 11,
  123578. 11
  123579. };
  123580. static static_codebook _8c0_s_p7_1 = {
  123581. 2, 121,
  123582. _vq_lengthlist__8c0_s_p7_1,
  123583. 1, -531365888, 1611661312, 4, 0,
  123584. _vq_quantlist__8c0_s_p7_1,
  123585. NULL,
  123586. &_vq_auxt__8c0_s_p7_1,
  123587. NULL,
  123588. 0
  123589. };
  123590. static long _vq_quantlist__8c0_s_p8_0[] = {
  123591. 6,
  123592. 5,
  123593. 7,
  123594. 4,
  123595. 8,
  123596. 3,
  123597. 9,
  123598. 2,
  123599. 10,
  123600. 1,
  123601. 11,
  123602. 0,
  123603. 12,
  123604. };
  123605. static long _vq_lengthlist__8c0_s_p8_0[] = {
  123606. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  123607. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  123608. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  123609. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  123610. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  123611. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  123612. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  123613. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  123614. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  123615. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  123616. 0, 0,13,13,11,13,13,11,12,
  123617. };
  123618. static float _vq_quantthresh__8c0_s_p8_0[] = {
  123619. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123620. 12.5, 17.5, 22.5, 27.5,
  123621. };
  123622. static long _vq_quantmap__8c0_s_p8_0[] = {
  123623. 11, 9, 7, 5, 3, 1, 0, 2,
  123624. 4, 6, 8, 10, 12,
  123625. };
  123626. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  123627. _vq_quantthresh__8c0_s_p8_0,
  123628. _vq_quantmap__8c0_s_p8_0,
  123629. 13,
  123630. 13
  123631. };
  123632. static static_codebook _8c0_s_p8_0 = {
  123633. 2, 169,
  123634. _vq_lengthlist__8c0_s_p8_0,
  123635. 1, -526516224, 1616117760, 4, 0,
  123636. _vq_quantlist__8c0_s_p8_0,
  123637. NULL,
  123638. &_vq_auxt__8c0_s_p8_0,
  123639. NULL,
  123640. 0
  123641. };
  123642. static long _vq_quantlist__8c0_s_p8_1[] = {
  123643. 2,
  123644. 1,
  123645. 3,
  123646. 0,
  123647. 4,
  123648. };
  123649. static long _vq_lengthlist__8c0_s_p8_1[] = {
  123650. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  123651. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  123652. };
  123653. static float _vq_quantthresh__8c0_s_p8_1[] = {
  123654. -1.5, -0.5, 0.5, 1.5,
  123655. };
  123656. static long _vq_quantmap__8c0_s_p8_1[] = {
  123657. 3, 1, 0, 2, 4,
  123658. };
  123659. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  123660. _vq_quantthresh__8c0_s_p8_1,
  123661. _vq_quantmap__8c0_s_p8_1,
  123662. 5,
  123663. 5
  123664. };
  123665. static static_codebook _8c0_s_p8_1 = {
  123666. 2, 25,
  123667. _vq_lengthlist__8c0_s_p8_1,
  123668. 1, -533725184, 1611661312, 3, 0,
  123669. _vq_quantlist__8c0_s_p8_1,
  123670. NULL,
  123671. &_vq_auxt__8c0_s_p8_1,
  123672. NULL,
  123673. 0
  123674. };
  123675. static long _vq_quantlist__8c0_s_p9_0[] = {
  123676. 1,
  123677. 0,
  123678. 2,
  123679. };
  123680. static long _vq_lengthlist__8c0_s_p9_0[] = {
  123681. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123682. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123683. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123684. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123685. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123686. 7,
  123687. };
  123688. static float _vq_quantthresh__8c0_s_p9_0[] = {
  123689. -157.5, 157.5,
  123690. };
  123691. static long _vq_quantmap__8c0_s_p9_0[] = {
  123692. 1, 0, 2,
  123693. };
  123694. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  123695. _vq_quantthresh__8c0_s_p9_0,
  123696. _vq_quantmap__8c0_s_p9_0,
  123697. 3,
  123698. 3
  123699. };
  123700. static static_codebook _8c0_s_p9_0 = {
  123701. 4, 81,
  123702. _vq_lengthlist__8c0_s_p9_0,
  123703. 1, -518803456, 1628680192, 2, 0,
  123704. _vq_quantlist__8c0_s_p9_0,
  123705. NULL,
  123706. &_vq_auxt__8c0_s_p9_0,
  123707. NULL,
  123708. 0
  123709. };
  123710. static long _vq_quantlist__8c0_s_p9_1[] = {
  123711. 7,
  123712. 6,
  123713. 8,
  123714. 5,
  123715. 9,
  123716. 4,
  123717. 10,
  123718. 3,
  123719. 11,
  123720. 2,
  123721. 12,
  123722. 1,
  123723. 13,
  123724. 0,
  123725. 14,
  123726. };
  123727. static long _vq_lengthlist__8c0_s_p9_1[] = {
  123728. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  123729. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  123730. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  123731. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  123732. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  123733. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  123734. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123735. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123736. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123737. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123738. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123739. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123740. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123741. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123742. 11,
  123743. };
  123744. static float _vq_quantthresh__8c0_s_p9_1[] = {
  123745. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123746. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123747. };
  123748. static long _vq_quantmap__8c0_s_p9_1[] = {
  123749. 13, 11, 9, 7, 5, 3, 1, 0,
  123750. 2, 4, 6, 8, 10, 12, 14,
  123751. };
  123752. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  123753. _vq_quantthresh__8c0_s_p9_1,
  123754. _vq_quantmap__8c0_s_p9_1,
  123755. 15,
  123756. 15
  123757. };
  123758. static static_codebook _8c0_s_p9_1 = {
  123759. 2, 225,
  123760. _vq_lengthlist__8c0_s_p9_1,
  123761. 1, -520986624, 1620377600, 4, 0,
  123762. _vq_quantlist__8c0_s_p9_1,
  123763. NULL,
  123764. &_vq_auxt__8c0_s_p9_1,
  123765. NULL,
  123766. 0
  123767. };
  123768. static long _vq_quantlist__8c0_s_p9_2[] = {
  123769. 10,
  123770. 9,
  123771. 11,
  123772. 8,
  123773. 12,
  123774. 7,
  123775. 13,
  123776. 6,
  123777. 14,
  123778. 5,
  123779. 15,
  123780. 4,
  123781. 16,
  123782. 3,
  123783. 17,
  123784. 2,
  123785. 18,
  123786. 1,
  123787. 19,
  123788. 0,
  123789. 20,
  123790. };
  123791. static long _vq_lengthlist__8c0_s_p9_2[] = {
  123792. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  123793. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  123794. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  123795. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  123796. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  123797. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  123798. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  123799. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  123800. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  123801. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  123802. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  123803. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  123804. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  123805. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  123806. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  123807. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  123808. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  123809. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  123810. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  123811. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  123812. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  123813. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  123814. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  123815. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  123816. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  123817. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  123818. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  123819. 10,11, 9,11,10, 9,10, 9,10,
  123820. };
  123821. static float _vq_quantthresh__8c0_s_p9_2[] = {
  123822. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123823. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123824. 6.5, 7.5, 8.5, 9.5,
  123825. };
  123826. static long _vq_quantmap__8c0_s_p9_2[] = {
  123827. 19, 17, 15, 13, 11, 9, 7, 5,
  123828. 3, 1, 0, 2, 4, 6, 8, 10,
  123829. 12, 14, 16, 18, 20,
  123830. };
  123831. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  123832. _vq_quantthresh__8c0_s_p9_2,
  123833. _vq_quantmap__8c0_s_p9_2,
  123834. 21,
  123835. 21
  123836. };
  123837. static static_codebook _8c0_s_p9_2 = {
  123838. 2, 441,
  123839. _vq_lengthlist__8c0_s_p9_2,
  123840. 1, -529268736, 1611661312, 5, 0,
  123841. _vq_quantlist__8c0_s_p9_2,
  123842. NULL,
  123843. &_vq_auxt__8c0_s_p9_2,
  123844. NULL,
  123845. 0
  123846. };
  123847. static long _huff_lengthlist__8c0_s_single[] = {
  123848. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  123849. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  123850. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  123851. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  123852. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  123853. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  123854. 17,16,17,17,
  123855. };
  123856. static static_codebook _huff_book__8c0_s_single = {
  123857. 2, 100,
  123858. _huff_lengthlist__8c0_s_single,
  123859. 0, 0, 0, 0, 0,
  123860. NULL,
  123861. NULL,
  123862. NULL,
  123863. NULL,
  123864. 0
  123865. };
  123866. static long _vq_quantlist__8c1_s_p1_0[] = {
  123867. 1,
  123868. 0,
  123869. 2,
  123870. };
  123871. static long _vq_lengthlist__8c1_s_p1_0[] = {
  123872. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123873. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123875. 0, 0, 0, 0, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  123878. 0, 0, 0, 7, 8, 9, 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, 0,
  123880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123882. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  123883. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  123918. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  123919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123923. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  123924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123928. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  123929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123963. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  123964. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123968. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  123969. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  123970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123973. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  123974. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  123975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  124123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124282. 0,
  124283. };
  124284. static float _vq_quantthresh__8c1_s_p1_0[] = {
  124285. -0.5, 0.5,
  124286. };
  124287. static long _vq_quantmap__8c1_s_p1_0[] = {
  124288. 1, 0, 2,
  124289. };
  124290. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  124291. _vq_quantthresh__8c1_s_p1_0,
  124292. _vq_quantmap__8c1_s_p1_0,
  124293. 3,
  124294. 3
  124295. };
  124296. static static_codebook _8c1_s_p1_0 = {
  124297. 8, 6561,
  124298. _vq_lengthlist__8c1_s_p1_0,
  124299. 1, -535822336, 1611661312, 2, 0,
  124300. _vq_quantlist__8c1_s_p1_0,
  124301. NULL,
  124302. &_vq_auxt__8c1_s_p1_0,
  124303. NULL,
  124304. 0
  124305. };
  124306. static long _vq_quantlist__8c1_s_p2_0[] = {
  124307. 2,
  124308. 1,
  124309. 3,
  124310. 0,
  124311. 4,
  124312. };
  124313. static long _vq_lengthlist__8c1_s_p2_0[] = {
  124314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124353. 0,
  124354. };
  124355. static float _vq_quantthresh__8c1_s_p2_0[] = {
  124356. -1.5, -0.5, 0.5, 1.5,
  124357. };
  124358. static long _vq_quantmap__8c1_s_p2_0[] = {
  124359. 3, 1, 0, 2, 4,
  124360. };
  124361. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  124362. _vq_quantthresh__8c1_s_p2_0,
  124363. _vq_quantmap__8c1_s_p2_0,
  124364. 5,
  124365. 5
  124366. };
  124367. static static_codebook _8c1_s_p2_0 = {
  124368. 4, 625,
  124369. _vq_lengthlist__8c1_s_p2_0,
  124370. 1, -533725184, 1611661312, 3, 0,
  124371. _vq_quantlist__8c1_s_p2_0,
  124372. NULL,
  124373. &_vq_auxt__8c1_s_p2_0,
  124374. NULL,
  124375. 0
  124376. };
  124377. static long _vq_quantlist__8c1_s_p3_0[] = {
  124378. 2,
  124379. 1,
  124380. 3,
  124381. 0,
  124382. 4,
  124383. };
  124384. static long _vq_lengthlist__8c1_s_p3_0[] = {
  124385. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  124387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124388. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  124390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124391. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  124392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124424. 0,
  124425. };
  124426. static float _vq_quantthresh__8c1_s_p3_0[] = {
  124427. -1.5, -0.5, 0.5, 1.5,
  124428. };
  124429. static long _vq_quantmap__8c1_s_p3_0[] = {
  124430. 3, 1, 0, 2, 4,
  124431. };
  124432. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  124433. _vq_quantthresh__8c1_s_p3_0,
  124434. _vq_quantmap__8c1_s_p3_0,
  124435. 5,
  124436. 5
  124437. };
  124438. static static_codebook _8c1_s_p3_0 = {
  124439. 4, 625,
  124440. _vq_lengthlist__8c1_s_p3_0,
  124441. 1, -533725184, 1611661312, 3, 0,
  124442. _vq_quantlist__8c1_s_p3_0,
  124443. NULL,
  124444. &_vq_auxt__8c1_s_p3_0,
  124445. NULL,
  124446. 0
  124447. };
  124448. static long _vq_quantlist__8c1_s_p4_0[] = {
  124449. 4,
  124450. 3,
  124451. 5,
  124452. 2,
  124453. 6,
  124454. 1,
  124455. 7,
  124456. 0,
  124457. 8,
  124458. };
  124459. static long _vq_lengthlist__8c1_s_p4_0[] = {
  124460. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  124461. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  124462. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  124463. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  124464. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124465. 0,
  124466. };
  124467. static float _vq_quantthresh__8c1_s_p4_0[] = {
  124468. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124469. };
  124470. static long _vq_quantmap__8c1_s_p4_0[] = {
  124471. 7, 5, 3, 1, 0, 2, 4, 6,
  124472. 8,
  124473. };
  124474. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  124475. _vq_quantthresh__8c1_s_p4_0,
  124476. _vq_quantmap__8c1_s_p4_0,
  124477. 9,
  124478. 9
  124479. };
  124480. static static_codebook _8c1_s_p4_0 = {
  124481. 2, 81,
  124482. _vq_lengthlist__8c1_s_p4_0,
  124483. 1, -531628032, 1611661312, 4, 0,
  124484. _vq_quantlist__8c1_s_p4_0,
  124485. NULL,
  124486. &_vq_auxt__8c1_s_p4_0,
  124487. NULL,
  124488. 0
  124489. };
  124490. static long _vq_quantlist__8c1_s_p5_0[] = {
  124491. 4,
  124492. 3,
  124493. 5,
  124494. 2,
  124495. 6,
  124496. 1,
  124497. 7,
  124498. 0,
  124499. 8,
  124500. };
  124501. static long _vq_lengthlist__8c1_s_p5_0[] = {
  124502. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  124503. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  124504. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  124505. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  124506. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  124507. 10,
  124508. };
  124509. static float _vq_quantthresh__8c1_s_p5_0[] = {
  124510. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124511. };
  124512. static long _vq_quantmap__8c1_s_p5_0[] = {
  124513. 7, 5, 3, 1, 0, 2, 4, 6,
  124514. 8,
  124515. };
  124516. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  124517. _vq_quantthresh__8c1_s_p5_0,
  124518. _vq_quantmap__8c1_s_p5_0,
  124519. 9,
  124520. 9
  124521. };
  124522. static static_codebook _8c1_s_p5_0 = {
  124523. 2, 81,
  124524. _vq_lengthlist__8c1_s_p5_0,
  124525. 1, -531628032, 1611661312, 4, 0,
  124526. _vq_quantlist__8c1_s_p5_0,
  124527. NULL,
  124528. &_vq_auxt__8c1_s_p5_0,
  124529. NULL,
  124530. 0
  124531. };
  124532. static long _vq_quantlist__8c1_s_p6_0[] = {
  124533. 8,
  124534. 7,
  124535. 9,
  124536. 6,
  124537. 10,
  124538. 5,
  124539. 11,
  124540. 4,
  124541. 12,
  124542. 3,
  124543. 13,
  124544. 2,
  124545. 14,
  124546. 1,
  124547. 15,
  124548. 0,
  124549. 16,
  124550. };
  124551. static long _vq_lengthlist__8c1_s_p6_0[] = {
  124552. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  124553. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124554. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  124555. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  124556. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  124557. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  124558. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  124559. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  124560. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  124561. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  124562. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  124563. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  124564. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  124565. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  124566. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  124567. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  124568. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  124569. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  124570. 14,
  124571. };
  124572. static float _vq_quantthresh__8c1_s_p6_0[] = {
  124573. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124574. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124575. };
  124576. static long _vq_quantmap__8c1_s_p6_0[] = {
  124577. 15, 13, 11, 9, 7, 5, 3, 1,
  124578. 0, 2, 4, 6, 8, 10, 12, 14,
  124579. 16,
  124580. };
  124581. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  124582. _vq_quantthresh__8c1_s_p6_0,
  124583. _vq_quantmap__8c1_s_p6_0,
  124584. 17,
  124585. 17
  124586. };
  124587. static static_codebook _8c1_s_p6_0 = {
  124588. 2, 289,
  124589. _vq_lengthlist__8c1_s_p6_0,
  124590. 1, -529530880, 1611661312, 5, 0,
  124591. _vq_quantlist__8c1_s_p6_0,
  124592. NULL,
  124593. &_vq_auxt__8c1_s_p6_0,
  124594. NULL,
  124595. 0
  124596. };
  124597. static long _vq_quantlist__8c1_s_p7_0[] = {
  124598. 1,
  124599. 0,
  124600. 2,
  124601. };
  124602. static long _vq_lengthlist__8c1_s_p7_0[] = {
  124603. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  124604. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  124605. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  124606. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  124607. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  124608. 9,
  124609. };
  124610. static float _vq_quantthresh__8c1_s_p7_0[] = {
  124611. -5.5, 5.5,
  124612. };
  124613. static long _vq_quantmap__8c1_s_p7_0[] = {
  124614. 1, 0, 2,
  124615. };
  124616. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  124617. _vq_quantthresh__8c1_s_p7_0,
  124618. _vq_quantmap__8c1_s_p7_0,
  124619. 3,
  124620. 3
  124621. };
  124622. static static_codebook _8c1_s_p7_0 = {
  124623. 4, 81,
  124624. _vq_lengthlist__8c1_s_p7_0,
  124625. 1, -529137664, 1618345984, 2, 0,
  124626. _vq_quantlist__8c1_s_p7_0,
  124627. NULL,
  124628. &_vq_auxt__8c1_s_p7_0,
  124629. NULL,
  124630. 0
  124631. };
  124632. static long _vq_quantlist__8c1_s_p7_1[] = {
  124633. 5,
  124634. 4,
  124635. 6,
  124636. 3,
  124637. 7,
  124638. 2,
  124639. 8,
  124640. 1,
  124641. 9,
  124642. 0,
  124643. 10,
  124644. };
  124645. static long _vq_lengthlist__8c1_s_p7_1[] = {
  124646. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  124647. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  124648. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124649. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  124650. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  124651. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  124652. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  124653. 10,10,10, 8, 8, 8, 8, 8, 8,
  124654. };
  124655. static float _vq_quantthresh__8c1_s_p7_1[] = {
  124656. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124657. 3.5, 4.5,
  124658. };
  124659. static long _vq_quantmap__8c1_s_p7_1[] = {
  124660. 9, 7, 5, 3, 1, 0, 2, 4,
  124661. 6, 8, 10,
  124662. };
  124663. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  124664. _vq_quantthresh__8c1_s_p7_1,
  124665. _vq_quantmap__8c1_s_p7_1,
  124666. 11,
  124667. 11
  124668. };
  124669. static static_codebook _8c1_s_p7_1 = {
  124670. 2, 121,
  124671. _vq_lengthlist__8c1_s_p7_1,
  124672. 1, -531365888, 1611661312, 4, 0,
  124673. _vq_quantlist__8c1_s_p7_1,
  124674. NULL,
  124675. &_vq_auxt__8c1_s_p7_1,
  124676. NULL,
  124677. 0
  124678. };
  124679. static long _vq_quantlist__8c1_s_p8_0[] = {
  124680. 6,
  124681. 5,
  124682. 7,
  124683. 4,
  124684. 8,
  124685. 3,
  124686. 9,
  124687. 2,
  124688. 10,
  124689. 1,
  124690. 11,
  124691. 0,
  124692. 12,
  124693. };
  124694. static long _vq_lengthlist__8c1_s_p8_0[] = {
  124695. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  124696. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  124697. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  124698. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  124699. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  124700. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  124701. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  124702. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  124703. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  124704. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  124705. 0,12,12,11,10,12,11,13,12,
  124706. };
  124707. static float _vq_quantthresh__8c1_s_p8_0[] = {
  124708. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124709. 12.5, 17.5, 22.5, 27.5,
  124710. };
  124711. static long _vq_quantmap__8c1_s_p8_0[] = {
  124712. 11, 9, 7, 5, 3, 1, 0, 2,
  124713. 4, 6, 8, 10, 12,
  124714. };
  124715. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  124716. _vq_quantthresh__8c1_s_p8_0,
  124717. _vq_quantmap__8c1_s_p8_0,
  124718. 13,
  124719. 13
  124720. };
  124721. static static_codebook _8c1_s_p8_0 = {
  124722. 2, 169,
  124723. _vq_lengthlist__8c1_s_p8_0,
  124724. 1, -526516224, 1616117760, 4, 0,
  124725. _vq_quantlist__8c1_s_p8_0,
  124726. NULL,
  124727. &_vq_auxt__8c1_s_p8_0,
  124728. NULL,
  124729. 0
  124730. };
  124731. static long _vq_quantlist__8c1_s_p8_1[] = {
  124732. 2,
  124733. 1,
  124734. 3,
  124735. 0,
  124736. 4,
  124737. };
  124738. static long _vq_lengthlist__8c1_s_p8_1[] = {
  124739. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124740. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124741. };
  124742. static float _vq_quantthresh__8c1_s_p8_1[] = {
  124743. -1.5, -0.5, 0.5, 1.5,
  124744. };
  124745. static long _vq_quantmap__8c1_s_p8_1[] = {
  124746. 3, 1, 0, 2, 4,
  124747. };
  124748. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  124749. _vq_quantthresh__8c1_s_p8_1,
  124750. _vq_quantmap__8c1_s_p8_1,
  124751. 5,
  124752. 5
  124753. };
  124754. static static_codebook _8c1_s_p8_1 = {
  124755. 2, 25,
  124756. _vq_lengthlist__8c1_s_p8_1,
  124757. 1, -533725184, 1611661312, 3, 0,
  124758. _vq_quantlist__8c1_s_p8_1,
  124759. NULL,
  124760. &_vq_auxt__8c1_s_p8_1,
  124761. NULL,
  124762. 0
  124763. };
  124764. static long _vq_quantlist__8c1_s_p9_0[] = {
  124765. 6,
  124766. 5,
  124767. 7,
  124768. 4,
  124769. 8,
  124770. 3,
  124771. 9,
  124772. 2,
  124773. 10,
  124774. 1,
  124775. 11,
  124776. 0,
  124777. 12,
  124778. };
  124779. static long _vq_lengthlist__8c1_s_p9_0[] = {
  124780. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  124781. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  124782. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124783. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124784. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124785. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124786. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124787. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124788. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124789. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124790. 10,10,10,10,10, 9, 9, 9, 9,
  124791. };
  124792. static float _vq_quantthresh__8c1_s_p9_0[] = {
  124793. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124794. 787.5, 1102.5, 1417.5, 1732.5,
  124795. };
  124796. static long _vq_quantmap__8c1_s_p9_0[] = {
  124797. 11, 9, 7, 5, 3, 1, 0, 2,
  124798. 4, 6, 8, 10, 12,
  124799. };
  124800. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  124801. _vq_quantthresh__8c1_s_p9_0,
  124802. _vq_quantmap__8c1_s_p9_0,
  124803. 13,
  124804. 13
  124805. };
  124806. static static_codebook _8c1_s_p9_0 = {
  124807. 2, 169,
  124808. _vq_lengthlist__8c1_s_p9_0,
  124809. 1, -513964032, 1628680192, 4, 0,
  124810. _vq_quantlist__8c1_s_p9_0,
  124811. NULL,
  124812. &_vq_auxt__8c1_s_p9_0,
  124813. NULL,
  124814. 0
  124815. };
  124816. static long _vq_quantlist__8c1_s_p9_1[] = {
  124817. 7,
  124818. 6,
  124819. 8,
  124820. 5,
  124821. 9,
  124822. 4,
  124823. 10,
  124824. 3,
  124825. 11,
  124826. 2,
  124827. 12,
  124828. 1,
  124829. 13,
  124830. 0,
  124831. 14,
  124832. };
  124833. static long _vq_lengthlist__8c1_s_p9_1[] = {
  124834. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  124835. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  124836. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  124837. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  124838. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  124839. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  124840. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  124841. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  124842. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  124843. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  124844. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  124845. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  124846. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  124847. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  124848. 15,
  124849. };
  124850. static float _vq_quantthresh__8c1_s_p9_1[] = {
  124851. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124852. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124853. };
  124854. static long _vq_quantmap__8c1_s_p9_1[] = {
  124855. 13, 11, 9, 7, 5, 3, 1, 0,
  124856. 2, 4, 6, 8, 10, 12, 14,
  124857. };
  124858. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  124859. _vq_quantthresh__8c1_s_p9_1,
  124860. _vq_quantmap__8c1_s_p9_1,
  124861. 15,
  124862. 15
  124863. };
  124864. static static_codebook _8c1_s_p9_1 = {
  124865. 2, 225,
  124866. _vq_lengthlist__8c1_s_p9_1,
  124867. 1, -520986624, 1620377600, 4, 0,
  124868. _vq_quantlist__8c1_s_p9_1,
  124869. NULL,
  124870. &_vq_auxt__8c1_s_p9_1,
  124871. NULL,
  124872. 0
  124873. };
  124874. static long _vq_quantlist__8c1_s_p9_2[] = {
  124875. 10,
  124876. 9,
  124877. 11,
  124878. 8,
  124879. 12,
  124880. 7,
  124881. 13,
  124882. 6,
  124883. 14,
  124884. 5,
  124885. 15,
  124886. 4,
  124887. 16,
  124888. 3,
  124889. 17,
  124890. 2,
  124891. 18,
  124892. 1,
  124893. 19,
  124894. 0,
  124895. 20,
  124896. };
  124897. static long _vq_lengthlist__8c1_s_p9_2[] = {
  124898. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  124899. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  124900. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  124901. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  124902. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  124903. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  124904. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  124905. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  124906. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  124907. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  124908. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  124909. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  124910. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  124911. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  124912. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  124913. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  124914. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124915. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  124916. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  124917. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  124918. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124919. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  124920. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  124921. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  124922. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  124923. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  124924. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  124925. 10,10,10,10,10,10,10,10,10,
  124926. };
  124927. static float _vq_quantthresh__8c1_s_p9_2[] = {
  124928. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124929. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124930. 6.5, 7.5, 8.5, 9.5,
  124931. };
  124932. static long _vq_quantmap__8c1_s_p9_2[] = {
  124933. 19, 17, 15, 13, 11, 9, 7, 5,
  124934. 3, 1, 0, 2, 4, 6, 8, 10,
  124935. 12, 14, 16, 18, 20,
  124936. };
  124937. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  124938. _vq_quantthresh__8c1_s_p9_2,
  124939. _vq_quantmap__8c1_s_p9_2,
  124940. 21,
  124941. 21
  124942. };
  124943. static static_codebook _8c1_s_p9_2 = {
  124944. 2, 441,
  124945. _vq_lengthlist__8c1_s_p9_2,
  124946. 1, -529268736, 1611661312, 5, 0,
  124947. _vq_quantlist__8c1_s_p9_2,
  124948. NULL,
  124949. &_vq_auxt__8c1_s_p9_2,
  124950. NULL,
  124951. 0
  124952. };
  124953. static long _huff_lengthlist__8c1_s_single[] = {
  124954. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  124955. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  124956. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  124957. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  124958. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  124959. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  124960. 9, 7, 7, 8,
  124961. };
  124962. static static_codebook _huff_book__8c1_s_single = {
  124963. 2, 100,
  124964. _huff_lengthlist__8c1_s_single,
  124965. 0, 0, 0, 0, 0,
  124966. NULL,
  124967. NULL,
  124968. NULL,
  124969. NULL,
  124970. 0
  124971. };
  124972. static long _huff_lengthlist__44c2_s_long[] = {
  124973. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  124974. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  124975. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  124976. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  124977. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  124978. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  124979. 10, 8, 8, 9,
  124980. };
  124981. static static_codebook _huff_book__44c2_s_long = {
  124982. 2, 100,
  124983. _huff_lengthlist__44c2_s_long,
  124984. 0, 0, 0, 0, 0,
  124985. NULL,
  124986. NULL,
  124987. NULL,
  124988. NULL,
  124989. 0
  124990. };
  124991. static long _vq_quantlist__44c2_s_p1_0[] = {
  124992. 1,
  124993. 0,
  124994. 2,
  124995. };
  124996. static long _vq_lengthlist__44c2_s_p1_0[] = {
  124997. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  124998. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  125003. 0, 0, 0, 6, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  125008. 0, 0, 0, 0, 7, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125043. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  125044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  125048. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  125049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  125053. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  125054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  125089. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  125094. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  125099. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125407. 0,
  125408. };
  125409. static float _vq_quantthresh__44c2_s_p1_0[] = {
  125410. -0.5, 0.5,
  125411. };
  125412. static long _vq_quantmap__44c2_s_p1_0[] = {
  125413. 1, 0, 2,
  125414. };
  125415. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  125416. _vq_quantthresh__44c2_s_p1_0,
  125417. _vq_quantmap__44c2_s_p1_0,
  125418. 3,
  125419. 3
  125420. };
  125421. static static_codebook _44c2_s_p1_0 = {
  125422. 8, 6561,
  125423. _vq_lengthlist__44c2_s_p1_0,
  125424. 1, -535822336, 1611661312, 2, 0,
  125425. _vq_quantlist__44c2_s_p1_0,
  125426. NULL,
  125427. &_vq_auxt__44c2_s_p1_0,
  125428. NULL,
  125429. 0
  125430. };
  125431. static long _vq_quantlist__44c2_s_p2_0[] = {
  125432. 2,
  125433. 1,
  125434. 3,
  125435. 0,
  125436. 4,
  125437. };
  125438. static long _vq_lengthlist__44c2_s_p2_0[] = {
  125439. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  125440. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  125441. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  125442. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  125443. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125448. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  125449. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  125450. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  125451. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125456. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  125457. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  125458. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  125459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125464. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  125465. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  125466. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  125467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125478. 0,
  125479. };
  125480. static float _vq_quantthresh__44c2_s_p2_0[] = {
  125481. -1.5, -0.5, 0.5, 1.5,
  125482. };
  125483. static long _vq_quantmap__44c2_s_p2_0[] = {
  125484. 3, 1, 0, 2, 4,
  125485. };
  125486. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  125487. _vq_quantthresh__44c2_s_p2_0,
  125488. _vq_quantmap__44c2_s_p2_0,
  125489. 5,
  125490. 5
  125491. };
  125492. static static_codebook _44c2_s_p2_0 = {
  125493. 4, 625,
  125494. _vq_lengthlist__44c2_s_p2_0,
  125495. 1, -533725184, 1611661312, 3, 0,
  125496. _vq_quantlist__44c2_s_p2_0,
  125497. NULL,
  125498. &_vq_auxt__44c2_s_p2_0,
  125499. NULL,
  125500. 0
  125501. };
  125502. static long _vq_quantlist__44c2_s_p3_0[] = {
  125503. 2,
  125504. 1,
  125505. 3,
  125506. 0,
  125507. 4,
  125508. };
  125509. static long _vq_lengthlist__44c2_s_p3_0[] = {
  125510. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  125512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125513. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  125515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125516. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  125517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125549. 0,
  125550. };
  125551. static float _vq_quantthresh__44c2_s_p3_0[] = {
  125552. -1.5, -0.5, 0.5, 1.5,
  125553. };
  125554. static long _vq_quantmap__44c2_s_p3_0[] = {
  125555. 3, 1, 0, 2, 4,
  125556. };
  125557. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  125558. _vq_quantthresh__44c2_s_p3_0,
  125559. _vq_quantmap__44c2_s_p3_0,
  125560. 5,
  125561. 5
  125562. };
  125563. static static_codebook _44c2_s_p3_0 = {
  125564. 4, 625,
  125565. _vq_lengthlist__44c2_s_p3_0,
  125566. 1, -533725184, 1611661312, 3, 0,
  125567. _vq_quantlist__44c2_s_p3_0,
  125568. NULL,
  125569. &_vq_auxt__44c2_s_p3_0,
  125570. NULL,
  125571. 0
  125572. };
  125573. static long _vq_quantlist__44c2_s_p4_0[] = {
  125574. 4,
  125575. 3,
  125576. 5,
  125577. 2,
  125578. 6,
  125579. 1,
  125580. 7,
  125581. 0,
  125582. 8,
  125583. };
  125584. static long _vq_lengthlist__44c2_s_p4_0[] = {
  125585. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  125586. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  125587. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  125588. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  125589. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125590. 0,
  125591. };
  125592. static float _vq_quantthresh__44c2_s_p4_0[] = {
  125593. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125594. };
  125595. static long _vq_quantmap__44c2_s_p4_0[] = {
  125596. 7, 5, 3, 1, 0, 2, 4, 6,
  125597. 8,
  125598. };
  125599. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  125600. _vq_quantthresh__44c2_s_p4_0,
  125601. _vq_quantmap__44c2_s_p4_0,
  125602. 9,
  125603. 9
  125604. };
  125605. static static_codebook _44c2_s_p4_0 = {
  125606. 2, 81,
  125607. _vq_lengthlist__44c2_s_p4_0,
  125608. 1, -531628032, 1611661312, 4, 0,
  125609. _vq_quantlist__44c2_s_p4_0,
  125610. NULL,
  125611. &_vq_auxt__44c2_s_p4_0,
  125612. NULL,
  125613. 0
  125614. };
  125615. static long _vq_quantlist__44c2_s_p5_0[] = {
  125616. 4,
  125617. 3,
  125618. 5,
  125619. 2,
  125620. 6,
  125621. 1,
  125622. 7,
  125623. 0,
  125624. 8,
  125625. };
  125626. static long _vq_lengthlist__44c2_s_p5_0[] = {
  125627. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  125628. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  125629. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  125630. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  125631. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  125632. 11,
  125633. };
  125634. static float _vq_quantthresh__44c2_s_p5_0[] = {
  125635. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125636. };
  125637. static long _vq_quantmap__44c2_s_p5_0[] = {
  125638. 7, 5, 3, 1, 0, 2, 4, 6,
  125639. 8,
  125640. };
  125641. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  125642. _vq_quantthresh__44c2_s_p5_0,
  125643. _vq_quantmap__44c2_s_p5_0,
  125644. 9,
  125645. 9
  125646. };
  125647. static static_codebook _44c2_s_p5_0 = {
  125648. 2, 81,
  125649. _vq_lengthlist__44c2_s_p5_0,
  125650. 1, -531628032, 1611661312, 4, 0,
  125651. _vq_quantlist__44c2_s_p5_0,
  125652. NULL,
  125653. &_vq_auxt__44c2_s_p5_0,
  125654. NULL,
  125655. 0
  125656. };
  125657. static long _vq_quantlist__44c2_s_p6_0[] = {
  125658. 8,
  125659. 7,
  125660. 9,
  125661. 6,
  125662. 10,
  125663. 5,
  125664. 11,
  125665. 4,
  125666. 12,
  125667. 3,
  125668. 13,
  125669. 2,
  125670. 14,
  125671. 1,
  125672. 15,
  125673. 0,
  125674. 16,
  125675. };
  125676. static long _vq_lengthlist__44c2_s_p6_0[] = {
  125677. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  125678. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  125679. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  125680. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  125681. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  125682. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  125683. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  125684. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  125685. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  125686. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  125687. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  125688. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  125689. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  125690. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  125691. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  125692. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  125693. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  125694. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  125695. 14,
  125696. };
  125697. static float _vq_quantthresh__44c2_s_p6_0[] = {
  125698. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125699. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125700. };
  125701. static long _vq_quantmap__44c2_s_p6_0[] = {
  125702. 15, 13, 11, 9, 7, 5, 3, 1,
  125703. 0, 2, 4, 6, 8, 10, 12, 14,
  125704. 16,
  125705. };
  125706. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  125707. _vq_quantthresh__44c2_s_p6_0,
  125708. _vq_quantmap__44c2_s_p6_0,
  125709. 17,
  125710. 17
  125711. };
  125712. static static_codebook _44c2_s_p6_0 = {
  125713. 2, 289,
  125714. _vq_lengthlist__44c2_s_p6_0,
  125715. 1, -529530880, 1611661312, 5, 0,
  125716. _vq_quantlist__44c2_s_p6_0,
  125717. NULL,
  125718. &_vq_auxt__44c2_s_p6_0,
  125719. NULL,
  125720. 0
  125721. };
  125722. static long _vq_quantlist__44c2_s_p7_0[] = {
  125723. 1,
  125724. 0,
  125725. 2,
  125726. };
  125727. static long _vq_lengthlist__44c2_s_p7_0[] = {
  125728. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  125729. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  125730. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  125731. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  125732. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  125733. 11,
  125734. };
  125735. static float _vq_quantthresh__44c2_s_p7_0[] = {
  125736. -5.5, 5.5,
  125737. };
  125738. static long _vq_quantmap__44c2_s_p7_0[] = {
  125739. 1, 0, 2,
  125740. };
  125741. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  125742. _vq_quantthresh__44c2_s_p7_0,
  125743. _vq_quantmap__44c2_s_p7_0,
  125744. 3,
  125745. 3
  125746. };
  125747. static static_codebook _44c2_s_p7_0 = {
  125748. 4, 81,
  125749. _vq_lengthlist__44c2_s_p7_0,
  125750. 1, -529137664, 1618345984, 2, 0,
  125751. _vq_quantlist__44c2_s_p7_0,
  125752. NULL,
  125753. &_vq_auxt__44c2_s_p7_0,
  125754. NULL,
  125755. 0
  125756. };
  125757. static long _vq_quantlist__44c2_s_p7_1[] = {
  125758. 5,
  125759. 4,
  125760. 6,
  125761. 3,
  125762. 7,
  125763. 2,
  125764. 8,
  125765. 1,
  125766. 9,
  125767. 0,
  125768. 10,
  125769. };
  125770. static long _vq_lengthlist__44c2_s_p7_1[] = {
  125771. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  125772. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  125773. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  125774. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  125775. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  125776. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  125777. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  125778. 10,10,10, 8, 8, 8, 8, 8, 8,
  125779. };
  125780. static float _vq_quantthresh__44c2_s_p7_1[] = {
  125781. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125782. 3.5, 4.5,
  125783. };
  125784. static long _vq_quantmap__44c2_s_p7_1[] = {
  125785. 9, 7, 5, 3, 1, 0, 2, 4,
  125786. 6, 8, 10,
  125787. };
  125788. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  125789. _vq_quantthresh__44c2_s_p7_1,
  125790. _vq_quantmap__44c2_s_p7_1,
  125791. 11,
  125792. 11
  125793. };
  125794. static static_codebook _44c2_s_p7_1 = {
  125795. 2, 121,
  125796. _vq_lengthlist__44c2_s_p7_1,
  125797. 1, -531365888, 1611661312, 4, 0,
  125798. _vq_quantlist__44c2_s_p7_1,
  125799. NULL,
  125800. &_vq_auxt__44c2_s_p7_1,
  125801. NULL,
  125802. 0
  125803. };
  125804. static long _vq_quantlist__44c2_s_p8_0[] = {
  125805. 6,
  125806. 5,
  125807. 7,
  125808. 4,
  125809. 8,
  125810. 3,
  125811. 9,
  125812. 2,
  125813. 10,
  125814. 1,
  125815. 11,
  125816. 0,
  125817. 12,
  125818. };
  125819. static long _vq_lengthlist__44c2_s_p8_0[] = {
  125820. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  125821. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  125822. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  125823. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  125824. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  125825. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  125826. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  125827. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  125828. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  125829. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  125830. 0,12,12,12,12,13,12,14,14,
  125831. };
  125832. static float _vq_quantthresh__44c2_s_p8_0[] = {
  125833. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125834. 12.5, 17.5, 22.5, 27.5,
  125835. };
  125836. static long _vq_quantmap__44c2_s_p8_0[] = {
  125837. 11, 9, 7, 5, 3, 1, 0, 2,
  125838. 4, 6, 8, 10, 12,
  125839. };
  125840. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  125841. _vq_quantthresh__44c2_s_p8_0,
  125842. _vq_quantmap__44c2_s_p8_0,
  125843. 13,
  125844. 13
  125845. };
  125846. static static_codebook _44c2_s_p8_0 = {
  125847. 2, 169,
  125848. _vq_lengthlist__44c2_s_p8_0,
  125849. 1, -526516224, 1616117760, 4, 0,
  125850. _vq_quantlist__44c2_s_p8_0,
  125851. NULL,
  125852. &_vq_auxt__44c2_s_p8_0,
  125853. NULL,
  125854. 0
  125855. };
  125856. static long _vq_quantlist__44c2_s_p8_1[] = {
  125857. 2,
  125858. 1,
  125859. 3,
  125860. 0,
  125861. 4,
  125862. };
  125863. static long _vq_lengthlist__44c2_s_p8_1[] = {
  125864. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  125865. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  125866. };
  125867. static float _vq_quantthresh__44c2_s_p8_1[] = {
  125868. -1.5, -0.5, 0.5, 1.5,
  125869. };
  125870. static long _vq_quantmap__44c2_s_p8_1[] = {
  125871. 3, 1, 0, 2, 4,
  125872. };
  125873. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  125874. _vq_quantthresh__44c2_s_p8_1,
  125875. _vq_quantmap__44c2_s_p8_1,
  125876. 5,
  125877. 5
  125878. };
  125879. static static_codebook _44c2_s_p8_1 = {
  125880. 2, 25,
  125881. _vq_lengthlist__44c2_s_p8_1,
  125882. 1, -533725184, 1611661312, 3, 0,
  125883. _vq_quantlist__44c2_s_p8_1,
  125884. NULL,
  125885. &_vq_auxt__44c2_s_p8_1,
  125886. NULL,
  125887. 0
  125888. };
  125889. static long _vq_quantlist__44c2_s_p9_0[] = {
  125890. 6,
  125891. 5,
  125892. 7,
  125893. 4,
  125894. 8,
  125895. 3,
  125896. 9,
  125897. 2,
  125898. 10,
  125899. 1,
  125900. 11,
  125901. 0,
  125902. 12,
  125903. };
  125904. static long _vq_lengthlist__44c2_s_p9_0[] = {
  125905. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  125906. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  125907. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125908. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  125909. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125910. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125911. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125912. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125913. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125914. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125915. 11,11,11,11,11,11,11,11,11,
  125916. };
  125917. static float _vq_quantthresh__44c2_s_p9_0[] = {
  125918. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  125919. 552.5, 773.5, 994.5, 1215.5,
  125920. };
  125921. static long _vq_quantmap__44c2_s_p9_0[] = {
  125922. 11, 9, 7, 5, 3, 1, 0, 2,
  125923. 4, 6, 8, 10, 12,
  125924. };
  125925. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  125926. _vq_quantthresh__44c2_s_p9_0,
  125927. _vq_quantmap__44c2_s_p9_0,
  125928. 13,
  125929. 13
  125930. };
  125931. static static_codebook _44c2_s_p9_0 = {
  125932. 2, 169,
  125933. _vq_lengthlist__44c2_s_p9_0,
  125934. 1, -514541568, 1627103232, 4, 0,
  125935. _vq_quantlist__44c2_s_p9_0,
  125936. NULL,
  125937. &_vq_auxt__44c2_s_p9_0,
  125938. NULL,
  125939. 0
  125940. };
  125941. static long _vq_quantlist__44c2_s_p9_1[] = {
  125942. 6,
  125943. 5,
  125944. 7,
  125945. 4,
  125946. 8,
  125947. 3,
  125948. 9,
  125949. 2,
  125950. 10,
  125951. 1,
  125952. 11,
  125953. 0,
  125954. 12,
  125955. };
  125956. static long _vq_lengthlist__44c2_s_p9_1[] = {
  125957. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  125958. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  125959. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  125960. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  125961. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  125962. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  125963. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  125964. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  125965. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  125966. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  125967. 17,13,12,12,10,13,11,14,14,
  125968. };
  125969. static float _vq_quantthresh__44c2_s_p9_1[] = {
  125970. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  125971. 42.5, 59.5, 76.5, 93.5,
  125972. };
  125973. static long _vq_quantmap__44c2_s_p9_1[] = {
  125974. 11, 9, 7, 5, 3, 1, 0, 2,
  125975. 4, 6, 8, 10, 12,
  125976. };
  125977. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  125978. _vq_quantthresh__44c2_s_p9_1,
  125979. _vq_quantmap__44c2_s_p9_1,
  125980. 13,
  125981. 13
  125982. };
  125983. static static_codebook _44c2_s_p9_1 = {
  125984. 2, 169,
  125985. _vq_lengthlist__44c2_s_p9_1,
  125986. 1, -522616832, 1620115456, 4, 0,
  125987. _vq_quantlist__44c2_s_p9_1,
  125988. NULL,
  125989. &_vq_auxt__44c2_s_p9_1,
  125990. NULL,
  125991. 0
  125992. };
  125993. static long _vq_quantlist__44c2_s_p9_2[] = {
  125994. 8,
  125995. 7,
  125996. 9,
  125997. 6,
  125998. 10,
  125999. 5,
  126000. 11,
  126001. 4,
  126002. 12,
  126003. 3,
  126004. 13,
  126005. 2,
  126006. 14,
  126007. 1,
  126008. 15,
  126009. 0,
  126010. 16,
  126011. };
  126012. static long _vq_lengthlist__44c2_s_p9_2[] = {
  126013. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  126014. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  126015. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  126016. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  126017. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  126018. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  126019. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  126020. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  126021. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  126022. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  126023. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  126024. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  126025. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  126026. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  126027. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  126028. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  126029. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  126030. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  126031. 10,
  126032. };
  126033. static float _vq_quantthresh__44c2_s_p9_2[] = {
  126034. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126035. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126036. };
  126037. static long _vq_quantmap__44c2_s_p9_2[] = {
  126038. 15, 13, 11, 9, 7, 5, 3, 1,
  126039. 0, 2, 4, 6, 8, 10, 12, 14,
  126040. 16,
  126041. };
  126042. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  126043. _vq_quantthresh__44c2_s_p9_2,
  126044. _vq_quantmap__44c2_s_p9_2,
  126045. 17,
  126046. 17
  126047. };
  126048. static static_codebook _44c2_s_p9_2 = {
  126049. 2, 289,
  126050. _vq_lengthlist__44c2_s_p9_2,
  126051. 1, -529530880, 1611661312, 5, 0,
  126052. _vq_quantlist__44c2_s_p9_2,
  126053. NULL,
  126054. &_vq_auxt__44c2_s_p9_2,
  126055. NULL,
  126056. 0
  126057. };
  126058. static long _huff_lengthlist__44c2_s_short[] = {
  126059. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  126060. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  126061. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  126062. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  126063. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  126064. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  126065. 6, 8, 9,12,
  126066. };
  126067. static static_codebook _huff_book__44c2_s_short = {
  126068. 2, 100,
  126069. _huff_lengthlist__44c2_s_short,
  126070. 0, 0, 0, 0, 0,
  126071. NULL,
  126072. NULL,
  126073. NULL,
  126074. NULL,
  126075. 0
  126076. };
  126077. static long _huff_lengthlist__44c3_s_long[] = {
  126078. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  126079. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  126080. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  126081. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  126082. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  126083. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  126084. 9, 8, 8, 8,
  126085. };
  126086. static static_codebook _huff_book__44c3_s_long = {
  126087. 2, 100,
  126088. _huff_lengthlist__44c3_s_long,
  126089. 0, 0, 0, 0, 0,
  126090. NULL,
  126091. NULL,
  126092. NULL,
  126093. NULL,
  126094. 0
  126095. };
  126096. static long _vq_quantlist__44c3_s_p1_0[] = {
  126097. 1,
  126098. 0,
  126099. 2,
  126100. };
  126101. static long _vq_lengthlist__44c3_s_p1_0[] = {
  126102. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  126103. 0, 0, 5, 6, 6, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  126108. 0, 0, 0, 6, 7, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  126113. 0, 0, 0, 0, 7, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126148. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  126149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7, 8, 8, 0, 0, 0,
  126153. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  126158. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126193. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  126194. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126198. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  126199. 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  126200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126203. 0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  126204. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  126205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126512. 0,
  126513. };
  126514. static float _vq_quantthresh__44c3_s_p1_0[] = {
  126515. -0.5, 0.5,
  126516. };
  126517. static long _vq_quantmap__44c3_s_p1_0[] = {
  126518. 1, 0, 2,
  126519. };
  126520. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  126521. _vq_quantthresh__44c3_s_p1_0,
  126522. _vq_quantmap__44c3_s_p1_0,
  126523. 3,
  126524. 3
  126525. };
  126526. static static_codebook _44c3_s_p1_0 = {
  126527. 8, 6561,
  126528. _vq_lengthlist__44c3_s_p1_0,
  126529. 1, -535822336, 1611661312, 2, 0,
  126530. _vq_quantlist__44c3_s_p1_0,
  126531. NULL,
  126532. &_vq_auxt__44c3_s_p1_0,
  126533. NULL,
  126534. 0
  126535. };
  126536. static long _vq_quantlist__44c3_s_p2_0[] = {
  126537. 2,
  126538. 1,
  126539. 3,
  126540. 0,
  126541. 4,
  126542. };
  126543. static long _vq_lengthlist__44c3_s_p2_0[] = {
  126544. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  126545. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  126546. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  126547. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  126548. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126553. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  126554. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  126555. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  126556. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126561. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  126562. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  126563. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  126564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126569. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  126570. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  126571. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  126572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126583. 0,
  126584. };
  126585. static float _vq_quantthresh__44c3_s_p2_0[] = {
  126586. -1.5, -0.5, 0.5, 1.5,
  126587. };
  126588. static long _vq_quantmap__44c3_s_p2_0[] = {
  126589. 3, 1, 0, 2, 4,
  126590. };
  126591. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  126592. _vq_quantthresh__44c3_s_p2_0,
  126593. _vq_quantmap__44c3_s_p2_0,
  126594. 5,
  126595. 5
  126596. };
  126597. static static_codebook _44c3_s_p2_0 = {
  126598. 4, 625,
  126599. _vq_lengthlist__44c3_s_p2_0,
  126600. 1, -533725184, 1611661312, 3, 0,
  126601. _vq_quantlist__44c3_s_p2_0,
  126602. NULL,
  126603. &_vq_auxt__44c3_s_p2_0,
  126604. NULL,
  126605. 0
  126606. };
  126607. static long _vq_quantlist__44c3_s_p3_0[] = {
  126608. 2,
  126609. 1,
  126610. 3,
  126611. 0,
  126612. 4,
  126613. };
  126614. static long _vq_lengthlist__44c3_s_p3_0[] = {
  126615. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  126617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126618. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  126620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126621. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  126622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126654. 0,
  126655. };
  126656. static float _vq_quantthresh__44c3_s_p3_0[] = {
  126657. -1.5, -0.5, 0.5, 1.5,
  126658. };
  126659. static long _vq_quantmap__44c3_s_p3_0[] = {
  126660. 3, 1, 0, 2, 4,
  126661. };
  126662. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  126663. _vq_quantthresh__44c3_s_p3_0,
  126664. _vq_quantmap__44c3_s_p3_0,
  126665. 5,
  126666. 5
  126667. };
  126668. static static_codebook _44c3_s_p3_0 = {
  126669. 4, 625,
  126670. _vq_lengthlist__44c3_s_p3_0,
  126671. 1, -533725184, 1611661312, 3, 0,
  126672. _vq_quantlist__44c3_s_p3_0,
  126673. NULL,
  126674. &_vq_auxt__44c3_s_p3_0,
  126675. NULL,
  126676. 0
  126677. };
  126678. static long _vq_quantlist__44c3_s_p4_0[] = {
  126679. 4,
  126680. 3,
  126681. 5,
  126682. 2,
  126683. 6,
  126684. 1,
  126685. 7,
  126686. 0,
  126687. 8,
  126688. };
  126689. static long _vq_lengthlist__44c3_s_p4_0[] = {
  126690. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  126691. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  126692. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  126693. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  126694. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126695. 0,
  126696. };
  126697. static float _vq_quantthresh__44c3_s_p4_0[] = {
  126698. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126699. };
  126700. static long _vq_quantmap__44c3_s_p4_0[] = {
  126701. 7, 5, 3, 1, 0, 2, 4, 6,
  126702. 8,
  126703. };
  126704. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  126705. _vq_quantthresh__44c3_s_p4_0,
  126706. _vq_quantmap__44c3_s_p4_0,
  126707. 9,
  126708. 9
  126709. };
  126710. static static_codebook _44c3_s_p4_0 = {
  126711. 2, 81,
  126712. _vq_lengthlist__44c3_s_p4_0,
  126713. 1, -531628032, 1611661312, 4, 0,
  126714. _vq_quantlist__44c3_s_p4_0,
  126715. NULL,
  126716. &_vq_auxt__44c3_s_p4_0,
  126717. NULL,
  126718. 0
  126719. };
  126720. static long _vq_quantlist__44c3_s_p5_0[] = {
  126721. 4,
  126722. 3,
  126723. 5,
  126724. 2,
  126725. 6,
  126726. 1,
  126727. 7,
  126728. 0,
  126729. 8,
  126730. };
  126731. static long _vq_lengthlist__44c3_s_p5_0[] = {
  126732. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  126733. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  126734. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  126735. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  126736. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  126737. 11,
  126738. };
  126739. static float _vq_quantthresh__44c3_s_p5_0[] = {
  126740. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126741. };
  126742. static long _vq_quantmap__44c3_s_p5_0[] = {
  126743. 7, 5, 3, 1, 0, 2, 4, 6,
  126744. 8,
  126745. };
  126746. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  126747. _vq_quantthresh__44c3_s_p5_0,
  126748. _vq_quantmap__44c3_s_p5_0,
  126749. 9,
  126750. 9
  126751. };
  126752. static static_codebook _44c3_s_p5_0 = {
  126753. 2, 81,
  126754. _vq_lengthlist__44c3_s_p5_0,
  126755. 1, -531628032, 1611661312, 4, 0,
  126756. _vq_quantlist__44c3_s_p5_0,
  126757. NULL,
  126758. &_vq_auxt__44c3_s_p5_0,
  126759. NULL,
  126760. 0
  126761. };
  126762. static long _vq_quantlist__44c3_s_p6_0[] = {
  126763. 8,
  126764. 7,
  126765. 9,
  126766. 6,
  126767. 10,
  126768. 5,
  126769. 11,
  126770. 4,
  126771. 12,
  126772. 3,
  126773. 13,
  126774. 2,
  126775. 14,
  126776. 1,
  126777. 15,
  126778. 0,
  126779. 16,
  126780. };
  126781. static long _vq_lengthlist__44c3_s_p6_0[] = {
  126782. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  126783. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  126784. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  126785. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  126786. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  126787. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  126788. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  126789. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  126790. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  126791. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  126792. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  126793. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  126794. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  126795. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  126796. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  126797. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  126798. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  126799. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  126800. 13,
  126801. };
  126802. static float _vq_quantthresh__44c3_s_p6_0[] = {
  126803. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126804. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126805. };
  126806. static long _vq_quantmap__44c3_s_p6_0[] = {
  126807. 15, 13, 11, 9, 7, 5, 3, 1,
  126808. 0, 2, 4, 6, 8, 10, 12, 14,
  126809. 16,
  126810. };
  126811. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  126812. _vq_quantthresh__44c3_s_p6_0,
  126813. _vq_quantmap__44c3_s_p6_0,
  126814. 17,
  126815. 17
  126816. };
  126817. static static_codebook _44c3_s_p6_0 = {
  126818. 2, 289,
  126819. _vq_lengthlist__44c3_s_p6_0,
  126820. 1, -529530880, 1611661312, 5, 0,
  126821. _vq_quantlist__44c3_s_p6_0,
  126822. NULL,
  126823. &_vq_auxt__44c3_s_p6_0,
  126824. NULL,
  126825. 0
  126826. };
  126827. static long _vq_quantlist__44c3_s_p7_0[] = {
  126828. 1,
  126829. 0,
  126830. 2,
  126831. };
  126832. static long _vq_lengthlist__44c3_s_p7_0[] = {
  126833. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  126834. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  126835. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  126836. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  126837. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  126838. 10,
  126839. };
  126840. static float _vq_quantthresh__44c3_s_p7_0[] = {
  126841. -5.5, 5.5,
  126842. };
  126843. static long _vq_quantmap__44c3_s_p7_0[] = {
  126844. 1, 0, 2,
  126845. };
  126846. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  126847. _vq_quantthresh__44c3_s_p7_0,
  126848. _vq_quantmap__44c3_s_p7_0,
  126849. 3,
  126850. 3
  126851. };
  126852. static static_codebook _44c3_s_p7_0 = {
  126853. 4, 81,
  126854. _vq_lengthlist__44c3_s_p7_0,
  126855. 1, -529137664, 1618345984, 2, 0,
  126856. _vq_quantlist__44c3_s_p7_0,
  126857. NULL,
  126858. &_vq_auxt__44c3_s_p7_0,
  126859. NULL,
  126860. 0
  126861. };
  126862. static long _vq_quantlist__44c3_s_p7_1[] = {
  126863. 5,
  126864. 4,
  126865. 6,
  126866. 3,
  126867. 7,
  126868. 2,
  126869. 8,
  126870. 1,
  126871. 9,
  126872. 0,
  126873. 10,
  126874. };
  126875. static long _vq_lengthlist__44c3_s_p7_1[] = {
  126876. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  126877. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  126878. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  126879. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  126880. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  126881. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  126882. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  126883. 10,10,10, 8, 8, 8, 8, 8, 8,
  126884. };
  126885. static float _vq_quantthresh__44c3_s_p7_1[] = {
  126886. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126887. 3.5, 4.5,
  126888. };
  126889. static long _vq_quantmap__44c3_s_p7_1[] = {
  126890. 9, 7, 5, 3, 1, 0, 2, 4,
  126891. 6, 8, 10,
  126892. };
  126893. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  126894. _vq_quantthresh__44c3_s_p7_1,
  126895. _vq_quantmap__44c3_s_p7_1,
  126896. 11,
  126897. 11
  126898. };
  126899. static static_codebook _44c3_s_p7_1 = {
  126900. 2, 121,
  126901. _vq_lengthlist__44c3_s_p7_1,
  126902. 1, -531365888, 1611661312, 4, 0,
  126903. _vq_quantlist__44c3_s_p7_1,
  126904. NULL,
  126905. &_vq_auxt__44c3_s_p7_1,
  126906. NULL,
  126907. 0
  126908. };
  126909. static long _vq_quantlist__44c3_s_p8_0[] = {
  126910. 6,
  126911. 5,
  126912. 7,
  126913. 4,
  126914. 8,
  126915. 3,
  126916. 9,
  126917. 2,
  126918. 10,
  126919. 1,
  126920. 11,
  126921. 0,
  126922. 12,
  126923. };
  126924. static long _vq_lengthlist__44c3_s_p8_0[] = {
  126925. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  126926. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  126927. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  126928. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  126929. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  126930. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  126931. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  126932. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  126933. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  126934. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  126935. 0,13,13,12,12,13,12,14,13,
  126936. };
  126937. static float _vq_quantthresh__44c3_s_p8_0[] = {
  126938. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126939. 12.5, 17.5, 22.5, 27.5,
  126940. };
  126941. static long _vq_quantmap__44c3_s_p8_0[] = {
  126942. 11, 9, 7, 5, 3, 1, 0, 2,
  126943. 4, 6, 8, 10, 12,
  126944. };
  126945. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  126946. _vq_quantthresh__44c3_s_p8_0,
  126947. _vq_quantmap__44c3_s_p8_0,
  126948. 13,
  126949. 13
  126950. };
  126951. static static_codebook _44c3_s_p8_0 = {
  126952. 2, 169,
  126953. _vq_lengthlist__44c3_s_p8_0,
  126954. 1, -526516224, 1616117760, 4, 0,
  126955. _vq_quantlist__44c3_s_p8_0,
  126956. NULL,
  126957. &_vq_auxt__44c3_s_p8_0,
  126958. NULL,
  126959. 0
  126960. };
  126961. static long _vq_quantlist__44c3_s_p8_1[] = {
  126962. 2,
  126963. 1,
  126964. 3,
  126965. 0,
  126966. 4,
  126967. };
  126968. static long _vq_lengthlist__44c3_s_p8_1[] = {
  126969. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  126970. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  126971. };
  126972. static float _vq_quantthresh__44c3_s_p8_1[] = {
  126973. -1.5, -0.5, 0.5, 1.5,
  126974. };
  126975. static long _vq_quantmap__44c3_s_p8_1[] = {
  126976. 3, 1, 0, 2, 4,
  126977. };
  126978. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  126979. _vq_quantthresh__44c3_s_p8_1,
  126980. _vq_quantmap__44c3_s_p8_1,
  126981. 5,
  126982. 5
  126983. };
  126984. static static_codebook _44c3_s_p8_1 = {
  126985. 2, 25,
  126986. _vq_lengthlist__44c3_s_p8_1,
  126987. 1, -533725184, 1611661312, 3, 0,
  126988. _vq_quantlist__44c3_s_p8_1,
  126989. NULL,
  126990. &_vq_auxt__44c3_s_p8_1,
  126991. NULL,
  126992. 0
  126993. };
  126994. static long _vq_quantlist__44c3_s_p9_0[] = {
  126995. 6,
  126996. 5,
  126997. 7,
  126998. 4,
  126999. 8,
  127000. 3,
  127001. 9,
  127002. 2,
  127003. 10,
  127004. 1,
  127005. 11,
  127006. 0,
  127007. 12,
  127008. };
  127009. static long _vq_lengthlist__44c3_s_p9_0[] = {
  127010. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  127011. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  127012. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  127013. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  127014. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  127015. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  127016. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  127017. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  127018. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  127019. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127020. 11,11,11,11,11,11,11,11,11,
  127021. };
  127022. static float _vq_quantthresh__44c3_s_p9_0[] = {
  127023. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  127024. 637.5, 892.5, 1147.5, 1402.5,
  127025. };
  127026. static long _vq_quantmap__44c3_s_p9_0[] = {
  127027. 11, 9, 7, 5, 3, 1, 0, 2,
  127028. 4, 6, 8, 10, 12,
  127029. };
  127030. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  127031. _vq_quantthresh__44c3_s_p9_0,
  127032. _vq_quantmap__44c3_s_p9_0,
  127033. 13,
  127034. 13
  127035. };
  127036. static static_codebook _44c3_s_p9_0 = {
  127037. 2, 169,
  127038. _vq_lengthlist__44c3_s_p9_0,
  127039. 1, -514332672, 1627381760, 4, 0,
  127040. _vq_quantlist__44c3_s_p9_0,
  127041. NULL,
  127042. &_vq_auxt__44c3_s_p9_0,
  127043. NULL,
  127044. 0
  127045. };
  127046. static long _vq_quantlist__44c3_s_p9_1[] = {
  127047. 7,
  127048. 6,
  127049. 8,
  127050. 5,
  127051. 9,
  127052. 4,
  127053. 10,
  127054. 3,
  127055. 11,
  127056. 2,
  127057. 12,
  127058. 1,
  127059. 13,
  127060. 0,
  127061. 14,
  127062. };
  127063. static long _vq_lengthlist__44c3_s_p9_1[] = {
  127064. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  127065. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  127066. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  127067. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  127068. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  127069. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  127070. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  127071. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  127072. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  127073. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  127074. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  127075. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  127076. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  127077. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  127078. 15,
  127079. };
  127080. static float _vq_quantthresh__44c3_s_p9_1[] = {
  127081. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  127082. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  127083. };
  127084. static long _vq_quantmap__44c3_s_p9_1[] = {
  127085. 13, 11, 9, 7, 5, 3, 1, 0,
  127086. 2, 4, 6, 8, 10, 12, 14,
  127087. };
  127088. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  127089. _vq_quantthresh__44c3_s_p9_1,
  127090. _vq_quantmap__44c3_s_p9_1,
  127091. 15,
  127092. 15
  127093. };
  127094. static static_codebook _44c3_s_p9_1 = {
  127095. 2, 225,
  127096. _vq_lengthlist__44c3_s_p9_1,
  127097. 1, -522338304, 1620115456, 4, 0,
  127098. _vq_quantlist__44c3_s_p9_1,
  127099. NULL,
  127100. &_vq_auxt__44c3_s_p9_1,
  127101. NULL,
  127102. 0
  127103. };
  127104. static long _vq_quantlist__44c3_s_p9_2[] = {
  127105. 8,
  127106. 7,
  127107. 9,
  127108. 6,
  127109. 10,
  127110. 5,
  127111. 11,
  127112. 4,
  127113. 12,
  127114. 3,
  127115. 13,
  127116. 2,
  127117. 14,
  127118. 1,
  127119. 15,
  127120. 0,
  127121. 16,
  127122. };
  127123. static long _vq_lengthlist__44c3_s_p9_2[] = {
  127124. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  127125. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  127126. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127127. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  127128. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  127129. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  127130. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  127131. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  127132. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  127133. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  127134. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  127135. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  127136. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  127137. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  127138. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  127139. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  127140. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  127141. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  127142. 10,
  127143. };
  127144. static float _vq_quantthresh__44c3_s_p9_2[] = {
  127145. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127146. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127147. };
  127148. static long _vq_quantmap__44c3_s_p9_2[] = {
  127149. 15, 13, 11, 9, 7, 5, 3, 1,
  127150. 0, 2, 4, 6, 8, 10, 12, 14,
  127151. 16,
  127152. };
  127153. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  127154. _vq_quantthresh__44c3_s_p9_2,
  127155. _vq_quantmap__44c3_s_p9_2,
  127156. 17,
  127157. 17
  127158. };
  127159. static static_codebook _44c3_s_p9_2 = {
  127160. 2, 289,
  127161. _vq_lengthlist__44c3_s_p9_2,
  127162. 1, -529530880, 1611661312, 5, 0,
  127163. _vq_quantlist__44c3_s_p9_2,
  127164. NULL,
  127165. &_vq_auxt__44c3_s_p9_2,
  127166. NULL,
  127167. 0
  127168. };
  127169. static long _huff_lengthlist__44c3_s_short[] = {
  127170. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  127171. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  127172. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  127173. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  127174. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  127175. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  127176. 6, 8, 9,11,
  127177. };
  127178. static static_codebook _huff_book__44c3_s_short = {
  127179. 2, 100,
  127180. _huff_lengthlist__44c3_s_short,
  127181. 0, 0, 0, 0, 0,
  127182. NULL,
  127183. NULL,
  127184. NULL,
  127185. NULL,
  127186. 0
  127187. };
  127188. static long _huff_lengthlist__44c4_s_long[] = {
  127189. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  127190. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  127191. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  127192. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  127193. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  127194. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  127195. 9, 8, 7, 7,
  127196. };
  127197. static static_codebook _huff_book__44c4_s_long = {
  127198. 2, 100,
  127199. _huff_lengthlist__44c4_s_long,
  127200. 0, 0, 0, 0, 0,
  127201. NULL,
  127202. NULL,
  127203. NULL,
  127204. NULL,
  127205. 0
  127206. };
  127207. static long _vq_quantlist__44c4_s_p1_0[] = {
  127208. 1,
  127209. 0,
  127210. 2,
  127211. };
  127212. static long _vq_lengthlist__44c4_s_p1_0[] = {
  127213. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  127214. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127219. 0, 0, 0, 6, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  127224. 0, 0, 0, 0, 7, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  127259. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127264. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  127269. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127280. 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127288. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127304. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127305. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127310. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127315. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  127316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127623. 0,
  127624. };
  127625. static float _vq_quantthresh__44c4_s_p1_0[] = {
  127626. -0.5, 0.5,
  127627. };
  127628. static long _vq_quantmap__44c4_s_p1_0[] = {
  127629. 1, 0, 2,
  127630. };
  127631. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  127632. _vq_quantthresh__44c4_s_p1_0,
  127633. _vq_quantmap__44c4_s_p1_0,
  127634. 3,
  127635. 3
  127636. };
  127637. static static_codebook _44c4_s_p1_0 = {
  127638. 8, 6561,
  127639. _vq_lengthlist__44c4_s_p1_0,
  127640. 1, -535822336, 1611661312, 2, 0,
  127641. _vq_quantlist__44c4_s_p1_0,
  127642. NULL,
  127643. &_vq_auxt__44c4_s_p1_0,
  127644. NULL,
  127645. 0
  127646. };
  127647. static long _vq_quantlist__44c4_s_p2_0[] = {
  127648. 2,
  127649. 1,
  127650. 3,
  127651. 0,
  127652. 4,
  127653. };
  127654. static long _vq_lengthlist__44c4_s_p2_0[] = {
  127655. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  127656. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  127657. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  127658. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  127659. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127664. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  127665. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  127666. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  127667. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127672. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  127673. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  127674. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  127675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127680. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  127681. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  127682. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  127683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127694. 0,
  127695. };
  127696. static float _vq_quantthresh__44c4_s_p2_0[] = {
  127697. -1.5, -0.5, 0.5, 1.5,
  127698. };
  127699. static long _vq_quantmap__44c4_s_p2_0[] = {
  127700. 3, 1, 0, 2, 4,
  127701. };
  127702. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  127703. _vq_quantthresh__44c4_s_p2_0,
  127704. _vq_quantmap__44c4_s_p2_0,
  127705. 5,
  127706. 5
  127707. };
  127708. static static_codebook _44c4_s_p2_0 = {
  127709. 4, 625,
  127710. _vq_lengthlist__44c4_s_p2_0,
  127711. 1, -533725184, 1611661312, 3, 0,
  127712. _vq_quantlist__44c4_s_p2_0,
  127713. NULL,
  127714. &_vq_auxt__44c4_s_p2_0,
  127715. NULL,
  127716. 0
  127717. };
  127718. static long _vq_quantlist__44c4_s_p3_0[] = {
  127719. 2,
  127720. 1,
  127721. 3,
  127722. 0,
  127723. 4,
  127724. };
  127725. static long _vq_lengthlist__44c4_s_p3_0[] = {
  127726. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  127728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127729. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  127731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127732. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  127733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127765. 0,
  127766. };
  127767. static float _vq_quantthresh__44c4_s_p3_0[] = {
  127768. -1.5, -0.5, 0.5, 1.5,
  127769. };
  127770. static long _vq_quantmap__44c4_s_p3_0[] = {
  127771. 3, 1, 0, 2, 4,
  127772. };
  127773. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  127774. _vq_quantthresh__44c4_s_p3_0,
  127775. _vq_quantmap__44c4_s_p3_0,
  127776. 5,
  127777. 5
  127778. };
  127779. static static_codebook _44c4_s_p3_0 = {
  127780. 4, 625,
  127781. _vq_lengthlist__44c4_s_p3_0,
  127782. 1, -533725184, 1611661312, 3, 0,
  127783. _vq_quantlist__44c4_s_p3_0,
  127784. NULL,
  127785. &_vq_auxt__44c4_s_p3_0,
  127786. NULL,
  127787. 0
  127788. };
  127789. static long _vq_quantlist__44c4_s_p4_0[] = {
  127790. 4,
  127791. 3,
  127792. 5,
  127793. 2,
  127794. 6,
  127795. 1,
  127796. 7,
  127797. 0,
  127798. 8,
  127799. };
  127800. static long _vq_lengthlist__44c4_s_p4_0[] = {
  127801. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  127802. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  127803. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  127804. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  127805. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127806. 0,
  127807. };
  127808. static float _vq_quantthresh__44c4_s_p4_0[] = {
  127809. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127810. };
  127811. static long _vq_quantmap__44c4_s_p4_0[] = {
  127812. 7, 5, 3, 1, 0, 2, 4, 6,
  127813. 8,
  127814. };
  127815. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  127816. _vq_quantthresh__44c4_s_p4_0,
  127817. _vq_quantmap__44c4_s_p4_0,
  127818. 9,
  127819. 9
  127820. };
  127821. static static_codebook _44c4_s_p4_0 = {
  127822. 2, 81,
  127823. _vq_lengthlist__44c4_s_p4_0,
  127824. 1, -531628032, 1611661312, 4, 0,
  127825. _vq_quantlist__44c4_s_p4_0,
  127826. NULL,
  127827. &_vq_auxt__44c4_s_p4_0,
  127828. NULL,
  127829. 0
  127830. };
  127831. static long _vq_quantlist__44c4_s_p5_0[] = {
  127832. 4,
  127833. 3,
  127834. 5,
  127835. 2,
  127836. 6,
  127837. 1,
  127838. 7,
  127839. 0,
  127840. 8,
  127841. };
  127842. static long _vq_lengthlist__44c4_s_p5_0[] = {
  127843. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  127844. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  127845. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  127846. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  127847. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  127848. 10,
  127849. };
  127850. static float _vq_quantthresh__44c4_s_p5_0[] = {
  127851. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127852. };
  127853. static long _vq_quantmap__44c4_s_p5_0[] = {
  127854. 7, 5, 3, 1, 0, 2, 4, 6,
  127855. 8,
  127856. };
  127857. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  127858. _vq_quantthresh__44c4_s_p5_0,
  127859. _vq_quantmap__44c4_s_p5_0,
  127860. 9,
  127861. 9
  127862. };
  127863. static static_codebook _44c4_s_p5_0 = {
  127864. 2, 81,
  127865. _vq_lengthlist__44c4_s_p5_0,
  127866. 1, -531628032, 1611661312, 4, 0,
  127867. _vq_quantlist__44c4_s_p5_0,
  127868. NULL,
  127869. &_vq_auxt__44c4_s_p5_0,
  127870. NULL,
  127871. 0
  127872. };
  127873. static long _vq_quantlist__44c4_s_p6_0[] = {
  127874. 8,
  127875. 7,
  127876. 9,
  127877. 6,
  127878. 10,
  127879. 5,
  127880. 11,
  127881. 4,
  127882. 12,
  127883. 3,
  127884. 13,
  127885. 2,
  127886. 14,
  127887. 1,
  127888. 15,
  127889. 0,
  127890. 16,
  127891. };
  127892. static long _vq_lengthlist__44c4_s_p6_0[] = {
  127893. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  127894. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127895. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  127896. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  127897. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  127898. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127899. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  127900. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  127901. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  127902. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  127903. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  127904. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  127905. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  127906. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  127907. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  127908. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  127909. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  127910. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  127911. 13,
  127912. };
  127913. static float _vq_quantthresh__44c4_s_p6_0[] = {
  127914. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127915. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127916. };
  127917. static long _vq_quantmap__44c4_s_p6_0[] = {
  127918. 15, 13, 11, 9, 7, 5, 3, 1,
  127919. 0, 2, 4, 6, 8, 10, 12, 14,
  127920. 16,
  127921. };
  127922. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  127923. _vq_quantthresh__44c4_s_p6_0,
  127924. _vq_quantmap__44c4_s_p6_0,
  127925. 17,
  127926. 17
  127927. };
  127928. static static_codebook _44c4_s_p6_0 = {
  127929. 2, 289,
  127930. _vq_lengthlist__44c4_s_p6_0,
  127931. 1, -529530880, 1611661312, 5, 0,
  127932. _vq_quantlist__44c4_s_p6_0,
  127933. NULL,
  127934. &_vq_auxt__44c4_s_p6_0,
  127935. NULL,
  127936. 0
  127937. };
  127938. static long _vq_quantlist__44c4_s_p7_0[] = {
  127939. 1,
  127940. 0,
  127941. 2,
  127942. };
  127943. static long _vq_lengthlist__44c4_s_p7_0[] = {
  127944. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  127945. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  127946. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  127947. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  127948. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  127949. 10,
  127950. };
  127951. static float _vq_quantthresh__44c4_s_p7_0[] = {
  127952. -5.5, 5.5,
  127953. };
  127954. static long _vq_quantmap__44c4_s_p7_0[] = {
  127955. 1, 0, 2,
  127956. };
  127957. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  127958. _vq_quantthresh__44c4_s_p7_0,
  127959. _vq_quantmap__44c4_s_p7_0,
  127960. 3,
  127961. 3
  127962. };
  127963. static static_codebook _44c4_s_p7_0 = {
  127964. 4, 81,
  127965. _vq_lengthlist__44c4_s_p7_0,
  127966. 1, -529137664, 1618345984, 2, 0,
  127967. _vq_quantlist__44c4_s_p7_0,
  127968. NULL,
  127969. &_vq_auxt__44c4_s_p7_0,
  127970. NULL,
  127971. 0
  127972. };
  127973. static long _vq_quantlist__44c4_s_p7_1[] = {
  127974. 5,
  127975. 4,
  127976. 6,
  127977. 3,
  127978. 7,
  127979. 2,
  127980. 8,
  127981. 1,
  127982. 9,
  127983. 0,
  127984. 10,
  127985. };
  127986. static long _vq_lengthlist__44c4_s_p7_1[] = {
  127987. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  127988. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  127989. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  127990. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  127991. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  127992. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127993. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  127994. 10,10,10, 8, 8, 8, 8, 9, 9,
  127995. };
  127996. static float _vq_quantthresh__44c4_s_p7_1[] = {
  127997. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127998. 3.5, 4.5,
  127999. };
  128000. static long _vq_quantmap__44c4_s_p7_1[] = {
  128001. 9, 7, 5, 3, 1, 0, 2, 4,
  128002. 6, 8, 10,
  128003. };
  128004. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  128005. _vq_quantthresh__44c4_s_p7_1,
  128006. _vq_quantmap__44c4_s_p7_1,
  128007. 11,
  128008. 11
  128009. };
  128010. static static_codebook _44c4_s_p7_1 = {
  128011. 2, 121,
  128012. _vq_lengthlist__44c4_s_p7_1,
  128013. 1, -531365888, 1611661312, 4, 0,
  128014. _vq_quantlist__44c4_s_p7_1,
  128015. NULL,
  128016. &_vq_auxt__44c4_s_p7_1,
  128017. NULL,
  128018. 0
  128019. };
  128020. static long _vq_quantlist__44c4_s_p8_0[] = {
  128021. 6,
  128022. 5,
  128023. 7,
  128024. 4,
  128025. 8,
  128026. 3,
  128027. 9,
  128028. 2,
  128029. 10,
  128030. 1,
  128031. 11,
  128032. 0,
  128033. 12,
  128034. };
  128035. static long _vq_lengthlist__44c4_s_p8_0[] = {
  128036. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  128037. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  128038. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128039. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128040. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  128041. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  128042. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  128043. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  128044. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  128045. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  128046. 0,13,12,12,12,12,12,13,13,
  128047. };
  128048. static float _vq_quantthresh__44c4_s_p8_0[] = {
  128049. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128050. 12.5, 17.5, 22.5, 27.5,
  128051. };
  128052. static long _vq_quantmap__44c4_s_p8_0[] = {
  128053. 11, 9, 7, 5, 3, 1, 0, 2,
  128054. 4, 6, 8, 10, 12,
  128055. };
  128056. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  128057. _vq_quantthresh__44c4_s_p8_0,
  128058. _vq_quantmap__44c4_s_p8_0,
  128059. 13,
  128060. 13
  128061. };
  128062. static static_codebook _44c4_s_p8_0 = {
  128063. 2, 169,
  128064. _vq_lengthlist__44c4_s_p8_0,
  128065. 1, -526516224, 1616117760, 4, 0,
  128066. _vq_quantlist__44c4_s_p8_0,
  128067. NULL,
  128068. &_vq_auxt__44c4_s_p8_0,
  128069. NULL,
  128070. 0
  128071. };
  128072. static long _vq_quantlist__44c4_s_p8_1[] = {
  128073. 2,
  128074. 1,
  128075. 3,
  128076. 0,
  128077. 4,
  128078. };
  128079. static long _vq_lengthlist__44c4_s_p8_1[] = {
  128080. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  128081. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128082. };
  128083. static float _vq_quantthresh__44c4_s_p8_1[] = {
  128084. -1.5, -0.5, 0.5, 1.5,
  128085. };
  128086. static long _vq_quantmap__44c4_s_p8_1[] = {
  128087. 3, 1, 0, 2, 4,
  128088. };
  128089. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  128090. _vq_quantthresh__44c4_s_p8_1,
  128091. _vq_quantmap__44c4_s_p8_1,
  128092. 5,
  128093. 5
  128094. };
  128095. static static_codebook _44c4_s_p8_1 = {
  128096. 2, 25,
  128097. _vq_lengthlist__44c4_s_p8_1,
  128098. 1, -533725184, 1611661312, 3, 0,
  128099. _vq_quantlist__44c4_s_p8_1,
  128100. NULL,
  128101. &_vq_auxt__44c4_s_p8_1,
  128102. NULL,
  128103. 0
  128104. };
  128105. static long _vq_quantlist__44c4_s_p9_0[] = {
  128106. 6,
  128107. 5,
  128108. 7,
  128109. 4,
  128110. 8,
  128111. 3,
  128112. 9,
  128113. 2,
  128114. 10,
  128115. 1,
  128116. 11,
  128117. 0,
  128118. 12,
  128119. };
  128120. static long _vq_lengthlist__44c4_s_p9_0[] = {
  128121. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  128122. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  128123. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128124. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128125. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128126. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128127. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128128. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128129. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128130. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128131. 12,12,12,12,12,12,12,12,12,
  128132. };
  128133. static float _vq_quantthresh__44c4_s_p9_0[] = {
  128134. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  128135. 787.5, 1102.5, 1417.5, 1732.5,
  128136. };
  128137. static long _vq_quantmap__44c4_s_p9_0[] = {
  128138. 11, 9, 7, 5, 3, 1, 0, 2,
  128139. 4, 6, 8, 10, 12,
  128140. };
  128141. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  128142. _vq_quantthresh__44c4_s_p9_0,
  128143. _vq_quantmap__44c4_s_p9_0,
  128144. 13,
  128145. 13
  128146. };
  128147. static static_codebook _44c4_s_p9_0 = {
  128148. 2, 169,
  128149. _vq_lengthlist__44c4_s_p9_0,
  128150. 1, -513964032, 1628680192, 4, 0,
  128151. _vq_quantlist__44c4_s_p9_0,
  128152. NULL,
  128153. &_vq_auxt__44c4_s_p9_0,
  128154. NULL,
  128155. 0
  128156. };
  128157. static long _vq_quantlist__44c4_s_p9_1[] = {
  128158. 7,
  128159. 6,
  128160. 8,
  128161. 5,
  128162. 9,
  128163. 4,
  128164. 10,
  128165. 3,
  128166. 11,
  128167. 2,
  128168. 12,
  128169. 1,
  128170. 13,
  128171. 0,
  128172. 14,
  128173. };
  128174. static long _vq_lengthlist__44c4_s_p9_1[] = {
  128175. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  128176. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  128177. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  128178. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  128179. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  128180. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  128181. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  128182. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  128183. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  128184. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  128185. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  128186. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  128187. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  128188. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  128189. 15,
  128190. };
  128191. static float _vq_quantthresh__44c4_s_p9_1[] = {
  128192. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  128193. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  128194. };
  128195. static long _vq_quantmap__44c4_s_p9_1[] = {
  128196. 13, 11, 9, 7, 5, 3, 1, 0,
  128197. 2, 4, 6, 8, 10, 12, 14,
  128198. };
  128199. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  128200. _vq_quantthresh__44c4_s_p9_1,
  128201. _vq_quantmap__44c4_s_p9_1,
  128202. 15,
  128203. 15
  128204. };
  128205. static static_codebook _44c4_s_p9_1 = {
  128206. 2, 225,
  128207. _vq_lengthlist__44c4_s_p9_1,
  128208. 1, -520986624, 1620377600, 4, 0,
  128209. _vq_quantlist__44c4_s_p9_1,
  128210. NULL,
  128211. &_vq_auxt__44c4_s_p9_1,
  128212. NULL,
  128213. 0
  128214. };
  128215. static long _vq_quantlist__44c4_s_p9_2[] = {
  128216. 10,
  128217. 9,
  128218. 11,
  128219. 8,
  128220. 12,
  128221. 7,
  128222. 13,
  128223. 6,
  128224. 14,
  128225. 5,
  128226. 15,
  128227. 4,
  128228. 16,
  128229. 3,
  128230. 17,
  128231. 2,
  128232. 18,
  128233. 1,
  128234. 19,
  128235. 0,
  128236. 20,
  128237. };
  128238. static long _vq_lengthlist__44c4_s_p9_2[] = {
  128239. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  128240. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  128241. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  128242. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  128243. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  128244. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  128245. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  128246. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  128247. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  128248. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  128249. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  128250. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  128251. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  128252. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  128253. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  128254. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  128255. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  128256. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  128257. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  128258. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  128259. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128260. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  128261. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  128262. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  128263. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  128264. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  128265. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  128266. 10,10,10,10,10,10,10,10,10,
  128267. };
  128268. static float _vq_quantthresh__44c4_s_p9_2[] = {
  128269. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  128270. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  128271. 6.5, 7.5, 8.5, 9.5,
  128272. };
  128273. static long _vq_quantmap__44c4_s_p9_2[] = {
  128274. 19, 17, 15, 13, 11, 9, 7, 5,
  128275. 3, 1, 0, 2, 4, 6, 8, 10,
  128276. 12, 14, 16, 18, 20,
  128277. };
  128278. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  128279. _vq_quantthresh__44c4_s_p9_2,
  128280. _vq_quantmap__44c4_s_p9_2,
  128281. 21,
  128282. 21
  128283. };
  128284. static static_codebook _44c4_s_p9_2 = {
  128285. 2, 441,
  128286. _vq_lengthlist__44c4_s_p9_2,
  128287. 1, -529268736, 1611661312, 5, 0,
  128288. _vq_quantlist__44c4_s_p9_2,
  128289. NULL,
  128290. &_vq_auxt__44c4_s_p9_2,
  128291. NULL,
  128292. 0
  128293. };
  128294. static long _huff_lengthlist__44c4_s_short[] = {
  128295. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  128296. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  128297. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  128298. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  128299. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  128300. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  128301. 7, 9,12,17,
  128302. };
  128303. static static_codebook _huff_book__44c4_s_short = {
  128304. 2, 100,
  128305. _huff_lengthlist__44c4_s_short,
  128306. 0, 0, 0, 0, 0,
  128307. NULL,
  128308. NULL,
  128309. NULL,
  128310. NULL,
  128311. 0
  128312. };
  128313. static long _huff_lengthlist__44c5_s_long[] = {
  128314. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  128315. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  128316. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  128317. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  128318. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  128319. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  128320. 9, 8, 7, 7,
  128321. };
  128322. static static_codebook _huff_book__44c5_s_long = {
  128323. 2, 100,
  128324. _huff_lengthlist__44c5_s_long,
  128325. 0, 0, 0, 0, 0,
  128326. NULL,
  128327. NULL,
  128328. NULL,
  128329. NULL,
  128330. 0
  128331. };
  128332. static long _vq_quantlist__44c5_s_p1_0[] = {
  128333. 1,
  128334. 0,
  128335. 2,
  128336. };
  128337. static long _vq_lengthlist__44c5_s_p1_0[] = {
  128338. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  128339. 0, 0, 4, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  128344. 0, 0, 0, 7, 8, 9, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  128349. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  128384. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  128385. 0, 0, 0, 0, 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, 7, 9, 9, 0, 0, 0,
  128389. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  128390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  128394. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128429. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  128430. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128434. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  128435. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  128436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128439. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  128440. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  128441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128748. 0,
  128749. };
  128750. static float _vq_quantthresh__44c5_s_p1_0[] = {
  128751. -0.5, 0.5,
  128752. };
  128753. static long _vq_quantmap__44c5_s_p1_0[] = {
  128754. 1, 0, 2,
  128755. };
  128756. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  128757. _vq_quantthresh__44c5_s_p1_0,
  128758. _vq_quantmap__44c5_s_p1_0,
  128759. 3,
  128760. 3
  128761. };
  128762. static static_codebook _44c5_s_p1_0 = {
  128763. 8, 6561,
  128764. _vq_lengthlist__44c5_s_p1_0,
  128765. 1, -535822336, 1611661312, 2, 0,
  128766. _vq_quantlist__44c5_s_p1_0,
  128767. NULL,
  128768. &_vq_auxt__44c5_s_p1_0,
  128769. NULL,
  128770. 0
  128771. };
  128772. static long _vq_quantlist__44c5_s_p2_0[] = {
  128773. 2,
  128774. 1,
  128775. 3,
  128776. 0,
  128777. 4,
  128778. };
  128779. static long _vq_lengthlist__44c5_s_p2_0[] = {
  128780. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  128781. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  128782. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  128783. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  128784. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128789. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  128790. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  128791. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  128792. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128797. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  128798. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  128799. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  128800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128805. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  128806. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  128807. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  128808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128819. 0,
  128820. };
  128821. static float _vq_quantthresh__44c5_s_p2_0[] = {
  128822. -1.5, -0.5, 0.5, 1.5,
  128823. };
  128824. static long _vq_quantmap__44c5_s_p2_0[] = {
  128825. 3, 1, 0, 2, 4,
  128826. };
  128827. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  128828. _vq_quantthresh__44c5_s_p2_0,
  128829. _vq_quantmap__44c5_s_p2_0,
  128830. 5,
  128831. 5
  128832. };
  128833. static static_codebook _44c5_s_p2_0 = {
  128834. 4, 625,
  128835. _vq_lengthlist__44c5_s_p2_0,
  128836. 1, -533725184, 1611661312, 3, 0,
  128837. _vq_quantlist__44c5_s_p2_0,
  128838. NULL,
  128839. &_vq_auxt__44c5_s_p2_0,
  128840. NULL,
  128841. 0
  128842. };
  128843. static long _vq_quantlist__44c5_s_p3_0[] = {
  128844. 2,
  128845. 1,
  128846. 3,
  128847. 0,
  128848. 4,
  128849. };
  128850. static long _vq_lengthlist__44c5_s_p3_0[] = {
  128851. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  128853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128854. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  128856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128857. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  128858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128890. 0,
  128891. };
  128892. static float _vq_quantthresh__44c5_s_p3_0[] = {
  128893. -1.5, -0.5, 0.5, 1.5,
  128894. };
  128895. static long _vq_quantmap__44c5_s_p3_0[] = {
  128896. 3, 1, 0, 2, 4,
  128897. };
  128898. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  128899. _vq_quantthresh__44c5_s_p3_0,
  128900. _vq_quantmap__44c5_s_p3_0,
  128901. 5,
  128902. 5
  128903. };
  128904. static static_codebook _44c5_s_p3_0 = {
  128905. 4, 625,
  128906. _vq_lengthlist__44c5_s_p3_0,
  128907. 1, -533725184, 1611661312, 3, 0,
  128908. _vq_quantlist__44c5_s_p3_0,
  128909. NULL,
  128910. &_vq_auxt__44c5_s_p3_0,
  128911. NULL,
  128912. 0
  128913. };
  128914. static long _vq_quantlist__44c5_s_p4_0[] = {
  128915. 4,
  128916. 3,
  128917. 5,
  128918. 2,
  128919. 6,
  128920. 1,
  128921. 7,
  128922. 0,
  128923. 8,
  128924. };
  128925. static long _vq_lengthlist__44c5_s_p4_0[] = {
  128926. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  128927. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  128928. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  128929. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  128930. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128931. 0,
  128932. };
  128933. static float _vq_quantthresh__44c5_s_p4_0[] = {
  128934. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128935. };
  128936. static long _vq_quantmap__44c5_s_p4_0[] = {
  128937. 7, 5, 3, 1, 0, 2, 4, 6,
  128938. 8,
  128939. };
  128940. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  128941. _vq_quantthresh__44c5_s_p4_0,
  128942. _vq_quantmap__44c5_s_p4_0,
  128943. 9,
  128944. 9
  128945. };
  128946. static static_codebook _44c5_s_p4_0 = {
  128947. 2, 81,
  128948. _vq_lengthlist__44c5_s_p4_0,
  128949. 1, -531628032, 1611661312, 4, 0,
  128950. _vq_quantlist__44c5_s_p4_0,
  128951. NULL,
  128952. &_vq_auxt__44c5_s_p4_0,
  128953. NULL,
  128954. 0
  128955. };
  128956. static long _vq_quantlist__44c5_s_p5_0[] = {
  128957. 4,
  128958. 3,
  128959. 5,
  128960. 2,
  128961. 6,
  128962. 1,
  128963. 7,
  128964. 0,
  128965. 8,
  128966. };
  128967. static long _vq_lengthlist__44c5_s_p5_0[] = {
  128968. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  128969. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  128970. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  128971. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  128972. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  128973. 10,
  128974. };
  128975. static float _vq_quantthresh__44c5_s_p5_0[] = {
  128976. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128977. };
  128978. static long _vq_quantmap__44c5_s_p5_0[] = {
  128979. 7, 5, 3, 1, 0, 2, 4, 6,
  128980. 8,
  128981. };
  128982. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  128983. _vq_quantthresh__44c5_s_p5_0,
  128984. _vq_quantmap__44c5_s_p5_0,
  128985. 9,
  128986. 9
  128987. };
  128988. static static_codebook _44c5_s_p5_0 = {
  128989. 2, 81,
  128990. _vq_lengthlist__44c5_s_p5_0,
  128991. 1, -531628032, 1611661312, 4, 0,
  128992. _vq_quantlist__44c5_s_p5_0,
  128993. NULL,
  128994. &_vq_auxt__44c5_s_p5_0,
  128995. NULL,
  128996. 0
  128997. };
  128998. static long _vq_quantlist__44c5_s_p6_0[] = {
  128999. 8,
  129000. 7,
  129001. 9,
  129002. 6,
  129003. 10,
  129004. 5,
  129005. 11,
  129006. 4,
  129007. 12,
  129008. 3,
  129009. 13,
  129010. 2,
  129011. 14,
  129012. 1,
  129013. 15,
  129014. 0,
  129015. 16,
  129016. };
  129017. static long _vq_lengthlist__44c5_s_p6_0[] = {
  129018. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  129019. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  129020. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  129021. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129022. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129023. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  129024. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  129025. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  129026. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129027. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  129028. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  129029. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  129030. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  129031. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  129032. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  129033. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129034. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  129035. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  129036. 13,
  129037. };
  129038. static float _vq_quantthresh__44c5_s_p6_0[] = {
  129039. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129040. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129041. };
  129042. static long _vq_quantmap__44c5_s_p6_0[] = {
  129043. 15, 13, 11, 9, 7, 5, 3, 1,
  129044. 0, 2, 4, 6, 8, 10, 12, 14,
  129045. 16,
  129046. };
  129047. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  129048. _vq_quantthresh__44c5_s_p6_0,
  129049. _vq_quantmap__44c5_s_p6_0,
  129050. 17,
  129051. 17
  129052. };
  129053. static static_codebook _44c5_s_p6_0 = {
  129054. 2, 289,
  129055. _vq_lengthlist__44c5_s_p6_0,
  129056. 1, -529530880, 1611661312, 5, 0,
  129057. _vq_quantlist__44c5_s_p6_0,
  129058. NULL,
  129059. &_vq_auxt__44c5_s_p6_0,
  129060. NULL,
  129061. 0
  129062. };
  129063. static long _vq_quantlist__44c5_s_p7_0[] = {
  129064. 1,
  129065. 0,
  129066. 2,
  129067. };
  129068. static long _vq_lengthlist__44c5_s_p7_0[] = {
  129069. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129070. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129071. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129072. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  129073. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129074. 10,
  129075. };
  129076. static float _vq_quantthresh__44c5_s_p7_0[] = {
  129077. -5.5, 5.5,
  129078. };
  129079. static long _vq_quantmap__44c5_s_p7_0[] = {
  129080. 1, 0, 2,
  129081. };
  129082. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  129083. _vq_quantthresh__44c5_s_p7_0,
  129084. _vq_quantmap__44c5_s_p7_0,
  129085. 3,
  129086. 3
  129087. };
  129088. static static_codebook _44c5_s_p7_0 = {
  129089. 4, 81,
  129090. _vq_lengthlist__44c5_s_p7_0,
  129091. 1, -529137664, 1618345984, 2, 0,
  129092. _vq_quantlist__44c5_s_p7_0,
  129093. NULL,
  129094. &_vq_auxt__44c5_s_p7_0,
  129095. NULL,
  129096. 0
  129097. };
  129098. static long _vq_quantlist__44c5_s_p7_1[] = {
  129099. 5,
  129100. 4,
  129101. 6,
  129102. 3,
  129103. 7,
  129104. 2,
  129105. 8,
  129106. 1,
  129107. 9,
  129108. 0,
  129109. 10,
  129110. };
  129111. static long _vq_lengthlist__44c5_s_p7_1[] = {
  129112. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  129113. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129114. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129115. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  129116. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  129117. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  129118. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  129119. 10,10,10, 8, 8, 8, 8, 8, 8,
  129120. };
  129121. static float _vq_quantthresh__44c5_s_p7_1[] = {
  129122. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129123. 3.5, 4.5,
  129124. };
  129125. static long _vq_quantmap__44c5_s_p7_1[] = {
  129126. 9, 7, 5, 3, 1, 0, 2, 4,
  129127. 6, 8, 10,
  129128. };
  129129. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  129130. _vq_quantthresh__44c5_s_p7_1,
  129131. _vq_quantmap__44c5_s_p7_1,
  129132. 11,
  129133. 11
  129134. };
  129135. static static_codebook _44c5_s_p7_1 = {
  129136. 2, 121,
  129137. _vq_lengthlist__44c5_s_p7_1,
  129138. 1, -531365888, 1611661312, 4, 0,
  129139. _vq_quantlist__44c5_s_p7_1,
  129140. NULL,
  129141. &_vq_auxt__44c5_s_p7_1,
  129142. NULL,
  129143. 0
  129144. };
  129145. static long _vq_quantlist__44c5_s_p8_0[] = {
  129146. 6,
  129147. 5,
  129148. 7,
  129149. 4,
  129150. 8,
  129151. 3,
  129152. 9,
  129153. 2,
  129154. 10,
  129155. 1,
  129156. 11,
  129157. 0,
  129158. 12,
  129159. };
  129160. static long _vq_lengthlist__44c5_s_p8_0[] = {
  129161. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  129162. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  129163. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129164. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  129165. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  129166. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  129167. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  129168. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  129169. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  129170. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  129171. 0,12,12,12,12,12,12,13,13,
  129172. };
  129173. static float _vq_quantthresh__44c5_s_p8_0[] = {
  129174. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129175. 12.5, 17.5, 22.5, 27.5,
  129176. };
  129177. static long _vq_quantmap__44c5_s_p8_0[] = {
  129178. 11, 9, 7, 5, 3, 1, 0, 2,
  129179. 4, 6, 8, 10, 12,
  129180. };
  129181. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  129182. _vq_quantthresh__44c5_s_p8_0,
  129183. _vq_quantmap__44c5_s_p8_0,
  129184. 13,
  129185. 13
  129186. };
  129187. static static_codebook _44c5_s_p8_0 = {
  129188. 2, 169,
  129189. _vq_lengthlist__44c5_s_p8_0,
  129190. 1, -526516224, 1616117760, 4, 0,
  129191. _vq_quantlist__44c5_s_p8_0,
  129192. NULL,
  129193. &_vq_auxt__44c5_s_p8_0,
  129194. NULL,
  129195. 0
  129196. };
  129197. static long _vq_quantlist__44c5_s_p8_1[] = {
  129198. 2,
  129199. 1,
  129200. 3,
  129201. 0,
  129202. 4,
  129203. };
  129204. static long _vq_lengthlist__44c5_s_p8_1[] = {
  129205. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  129206. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129207. };
  129208. static float _vq_quantthresh__44c5_s_p8_1[] = {
  129209. -1.5, -0.5, 0.5, 1.5,
  129210. };
  129211. static long _vq_quantmap__44c5_s_p8_1[] = {
  129212. 3, 1, 0, 2, 4,
  129213. };
  129214. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  129215. _vq_quantthresh__44c5_s_p8_1,
  129216. _vq_quantmap__44c5_s_p8_1,
  129217. 5,
  129218. 5
  129219. };
  129220. static static_codebook _44c5_s_p8_1 = {
  129221. 2, 25,
  129222. _vq_lengthlist__44c5_s_p8_1,
  129223. 1, -533725184, 1611661312, 3, 0,
  129224. _vq_quantlist__44c5_s_p8_1,
  129225. NULL,
  129226. &_vq_auxt__44c5_s_p8_1,
  129227. NULL,
  129228. 0
  129229. };
  129230. static long _vq_quantlist__44c5_s_p9_0[] = {
  129231. 7,
  129232. 6,
  129233. 8,
  129234. 5,
  129235. 9,
  129236. 4,
  129237. 10,
  129238. 3,
  129239. 11,
  129240. 2,
  129241. 12,
  129242. 1,
  129243. 13,
  129244. 0,
  129245. 14,
  129246. };
  129247. static long _vq_lengthlist__44c5_s_p9_0[] = {
  129248. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  129249. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  129250. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  129251. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  129252. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  129253. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  129254. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  129255. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  129256. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  129257. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  129258. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  129259. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  129260. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  129261. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  129262. 12,
  129263. };
  129264. static float _vq_quantthresh__44c5_s_p9_0[] = {
  129265. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  129266. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  129267. };
  129268. static long _vq_quantmap__44c5_s_p9_0[] = {
  129269. 13, 11, 9, 7, 5, 3, 1, 0,
  129270. 2, 4, 6, 8, 10, 12, 14,
  129271. };
  129272. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  129273. _vq_quantthresh__44c5_s_p9_0,
  129274. _vq_quantmap__44c5_s_p9_0,
  129275. 15,
  129276. 15
  129277. };
  129278. static static_codebook _44c5_s_p9_0 = {
  129279. 2, 225,
  129280. _vq_lengthlist__44c5_s_p9_0,
  129281. 1, -512522752, 1628852224, 4, 0,
  129282. _vq_quantlist__44c5_s_p9_0,
  129283. NULL,
  129284. &_vq_auxt__44c5_s_p9_0,
  129285. NULL,
  129286. 0
  129287. };
  129288. static long _vq_quantlist__44c5_s_p9_1[] = {
  129289. 8,
  129290. 7,
  129291. 9,
  129292. 6,
  129293. 10,
  129294. 5,
  129295. 11,
  129296. 4,
  129297. 12,
  129298. 3,
  129299. 13,
  129300. 2,
  129301. 14,
  129302. 1,
  129303. 15,
  129304. 0,
  129305. 16,
  129306. };
  129307. static long _vq_lengthlist__44c5_s_p9_1[] = {
  129308. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  129309. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  129310. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  129311. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  129312. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  129313. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  129314. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  129315. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  129316. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  129317. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  129318. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  129319. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  129320. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  129321. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  129322. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  129323. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  129324. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  129325. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  129326. 15,
  129327. };
  129328. static float _vq_quantthresh__44c5_s_p9_1[] = {
  129329. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  129330. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  129331. };
  129332. static long _vq_quantmap__44c5_s_p9_1[] = {
  129333. 15, 13, 11, 9, 7, 5, 3, 1,
  129334. 0, 2, 4, 6, 8, 10, 12, 14,
  129335. 16,
  129336. };
  129337. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  129338. _vq_quantthresh__44c5_s_p9_1,
  129339. _vq_quantmap__44c5_s_p9_1,
  129340. 17,
  129341. 17
  129342. };
  129343. static static_codebook _44c5_s_p9_1 = {
  129344. 2, 289,
  129345. _vq_lengthlist__44c5_s_p9_1,
  129346. 1, -520814592, 1620377600, 5, 0,
  129347. _vq_quantlist__44c5_s_p9_1,
  129348. NULL,
  129349. &_vq_auxt__44c5_s_p9_1,
  129350. NULL,
  129351. 0
  129352. };
  129353. static long _vq_quantlist__44c5_s_p9_2[] = {
  129354. 10,
  129355. 9,
  129356. 11,
  129357. 8,
  129358. 12,
  129359. 7,
  129360. 13,
  129361. 6,
  129362. 14,
  129363. 5,
  129364. 15,
  129365. 4,
  129366. 16,
  129367. 3,
  129368. 17,
  129369. 2,
  129370. 18,
  129371. 1,
  129372. 19,
  129373. 0,
  129374. 20,
  129375. };
  129376. static long _vq_lengthlist__44c5_s_p9_2[] = {
  129377. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  129378. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  129379. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  129380. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  129381. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  129382. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  129383. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  129384. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  129385. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  129386. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129387. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  129388. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  129389. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  129390. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  129391. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  129392. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  129393. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  129394. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  129395. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  129396. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  129397. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129398. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  129399. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  129400. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  129401. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  129402. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  129403. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  129404. 10,10,10,10,10,10,10,10,10,
  129405. };
  129406. static float _vq_quantthresh__44c5_s_p9_2[] = {
  129407. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  129408. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  129409. 6.5, 7.5, 8.5, 9.5,
  129410. };
  129411. static long _vq_quantmap__44c5_s_p9_2[] = {
  129412. 19, 17, 15, 13, 11, 9, 7, 5,
  129413. 3, 1, 0, 2, 4, 6, 8, 10,
  129414. 12, 14, 16, 18, 20,
  129415. };
  129416. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  129417. _vq_quantthresh__44c5_s_p9_2,
  129418. _vq_quantmap__44c5_s_p9_2,
  129419. 21,
  129420. 21
  129421. };
  129422. static static_codebook _44c5_s_p9_2 = {
  129423. 2, 441,
  129424. _vq_lengthlist__44c5_s_p9_2,
  129425. 1, -529268736, 1611661312, 5, 0,
  129426. _vq_quantlist__44c5_s_p9_2,
  129427. NULL,
  129428. &_vq_auxt__44c5_s_p9_2,
  129429. NULL,
  129430. 0
  129431. };
  129432. static long _huff_lengthlist__44c5_s_short[] = {
  129433. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  129434. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  129435. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  129436. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  129437. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  129438. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  129439. 6, 8,11,16,
  129440. };
  129441. static static_codebook _huff_book__44c5_s_short = {
  129442. 2, 100,
  129443. _huff_lengthlist__44c5_s_short,
  129444. 0, 0, 0, 0, 0,
  129445. NULL,
  129446. NULL,
  129447. NULL,
  129448. NULL,
  129449. 0
  129450. };
  129451. static long _huff_lengthlist__44c6_s_long[] = {
  129452. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  129453. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  129454. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  129455. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  129456. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  129457. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  129458. 11,10,10,12,
  129459. };
  129460. static static_codebook _huff_book__44c6_s_long = {
  129461. 2, 100,
  129462. _huff_lengthlist__44c6_s_long,
  129463. 0, 0, 0, 0, 0,
  129464. NULL,
  129465. NULL,
  129466. NULL,
  129467. NULL,
  129468. 0
  129469. };
  129470. static long _vq_quantlist__44c6_s_p1_0[] = {
  129471. 1,
  129472. 0,
  129473. 2,
  129474. };
  129475. static long _vq_lengthlist__44c6_s_p1_0[] = {
  129476. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  129477. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  129478. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  129479. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  129480. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  129481. 8,
  129482. };
  129483. static float _vq_quantthresh__44c6_s_p1_0[] = {
  129484. -0.5, 0.5,
  129485. };
  129486. static long _vq_quantmap__44c6_s_p1_0[] = {
  129487. 1, 0, 2,
  129488. };
  129489. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  129490. _vq_quantthresh__44c6_s_p1_0,
  129491. _vq_quantmap__44c6_s_p1_0,
  129492. 3,
  129493. 3
  129494. };
  129495. static static_codebook _44c6_s_p1_0 = {
  129496. 4, 81,
  129497. _vq_lengthlist__44c6_s_p1_0,
  129498. 1, -535822336, 1611661312, 2, 0,
  129499. _vq_quantlist__44c6_s_p1_0,
  129500. NULL,
  129501. &_vq_auxt__44c6_s_p1_0,
  129502. NULL,
  129503. 0
  129504. };
  129505. static long _vq_quantlist__44c6_s_p2_0[] = {
  129506. 2,
  129507. 1,
  129508. 3,
  129509. 0,
  129510. 4,
  129511. };
  129512. static long _vq_lengthlist__44c6_s_p2_0[] = {
  129513. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  129514. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  129515. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  129516. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  129517. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  129518. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  129519. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  129520. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 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, 5, 8, 7,11,10, 0, 7, 7,10,10,
  129523. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  129524. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  129525. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  129526. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  129527. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  129528. 0,12,12,13,13, 0, 0, 0,13,13, 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, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  129531. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  129532. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  129533. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  129534. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  129535. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  129536. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129538. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  129539. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  129540. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  129541. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  129542. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  129543. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  129544. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  129549. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  129550. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  129551. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  129552. 13,
  129553. };
  129554. static float _vq_quantthresh__44c6_s_p2_0[] = {
  129555. -1.5, -0.5, 0.5, 1.5,
  129556. };
  129557. static long _vq_quantmap__44c6_s_p2_0[] = {
  129558. 3, 1, 0, 2, 4,
  129559. };
  129560. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  129561. _vq_quantthresh__44c6_s_p2_0,
  129562. _vq_quantmap__44c6_s_p2_0,
  129563. 5,
  129564. 5
  129565. };
  129566. static static_codebook _44c6_s_p2_0 = {
  129567. 4, 625,
  129568. _vq_lengthlist__44c6_s_p2_0,
  129569. 1, -533725184, 1611661312, 3, 0,
  129570. _vq_quantlist__44c6_s_p2_0,
  129571. NULL,
  129572. &_vq_auxt__44c6_s_p2_0,
  129573. NULL,
  129574. 0
  129575. };
  129576. static long _vq_quantlist__44c6_s_p3_0[] = {
  129577. 4,
  129578. 3,
  129579. 5,
  129580. 2,
  129581. 6,
  129582. 1,
  129583. 7,
  129584. 0,
  129585. 8,
  129586. };
  129587. static long _vq_lengthlist__44c6_s_p3_0[] = {
  129588. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  129589. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  129590. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  129591. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  129592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129593. 0,
  129594. };
  129595. static float _vq_quantthresh__44c6_s_p3_0[] = {
  129596. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129597. };
  129598. static long _vq_quantmap__44c6_s_p3_0[] = {
  129599. 7, 5, 3, 1, 0, 2, 4, 6,
  129600. 8,
  129601. };
  129602. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  129603. _vq_quantthresh__44c6_s_p3_0,
  129604. _vq_quantmap__44c6_s_p3_0,
  129605. 9,
  129606. 9
  129607. };
  129608. static static_codebook _44c6_s_p3_0 = {
  129609. 2, 81,
  129610. _vq_lengthlist__44c6_s_p3_0,
  129611. 1, -531628032, 1611661312, 4, 0,
  129612. _vq_quantlist__44c6_s_p3_0,
  129613. NULL,
  129614. &_vq_auxt__44c6_s_p3_0,
  129615. NULL,
  129616. 0
  129617. };
  129618. static long _vq_quantlist__44c6_s_p4_0[] = {
  129619. 8,
  129620. 7,
  129621. 9,
  129622. 6,
  129623. 10,
  129624. 5,
  129625. 11,
  129626. 4,
  129627. 12,
  129628. 3,
  129629. 13,
  129630. 2,
  129631. 14,
  129632. 1,
  129633. 15,
  129634. 0,
  129635. 16,
  129636. };
  129637. static long _vq_lengthlist__44c6_s_p4_0[] = {
  129638. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  129639. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  129640. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  129641. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129642. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129643. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  129644. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  129645. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  129646. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  129647. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  129648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129656. 0,
  129657. };
  129658. static float _vq_quantthresh__44c6_s_p4_0[] = {
  129659. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129660. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129661. };
  129662. static long _vq_quantmap__44c6_s_p4_0[] = {
  129663. 15, 13, 11, 9, 7, 5, 3, 1,
  129664. 0, 2, 4, 6, 8, 10, 12, 14,
  129665. 16,
  129666. };
  129667. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  129668. _vq_quantthresh__44c6_s_p4_0,
  129669. _vq_quantmap__44c6_s_p4_0,
  129670. 17,
  129671. 17
  129672. };
  129673. static static_codebook _44c6_s_p4_0 = {
  129674. 2, 289,
  129675. _vq_lengthlist__44c6_s_p4_0,
  129676. 1, -529530880, 1611661312, 5, 0,
  129677. _vq_quantlist__44c6_s_p4_0,
  129678. NULL,
  129679. &_vq_auxt__44c6_s_p4_0,
  129680. NULL,
  129681. 0
  129682. };
  129683. static long _vq_quantlist__44c6_s_p5_0[] = {
  129684. 1,
  129685. 0,
  129686. 2,
  129687. };
  129688. static long _vq_lengthlist__44c6_s_p5_0[] = {
  129689. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  129690. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  129691. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  129692. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  129693. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  129694. 12,
  129695. };
  129696. static float _vq_quantthresh__44c6_s_p5_0[] = {
  129697. -5.5, 5.5,
  129698. };
  129699. static long _vq_quantmap__44c6_s_p5_0[] = {
  129700. 1, 0, 2,
  129701. };
  129702. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  129703. _vq_quantthresh__44c6_s_p5_0,
  129704. _vq_quantmap__44c6_s_p5_0,
  129705. 3,
  129706. 3
  129707. };
  129708. static static_codebook _44c6_s_p5_0 = {
  129709. 4, 81,
  129710. _vq_lengthlist__44c6_s_p5_0,
  129711. 1, -529137664, 1618345984, 2, 0,
  129712. _vq_quantlist__44c6_s_p5_0,
  129713. NULL,
  129714. &_vq_auxt__44c6_s_p5_0,
  129715. NULL,
  129716. 0
  129717. };
  129718. static long _vq_quantlist__44c6_s_p5_1[] = {
  129719. 5,
  129720. 4,
  129721. 6,
  129722. 3,
  129723. 7,
  129724. 2,
  129725. 8,
  129726. 1,
  129727. 9,
  129728. 0,
  129729. 10,
  129730. };
  129731. static long _vq_lengthlist__44c6_s_p5_1[] = {
  129732. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  129733. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  129734. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  129735. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  129736. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  129737. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  129738. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  129739. 11,10,10, 7, 7, 8, 8, 8, 8,
  129740. };
  129741. static float _vq_quantthresh__44c6_s_p5_1[] = {
  129742. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129743. 3.5, 4.5,
  129744. };
  129745. static long _vq_quantmap__44c6_s_p5_1[] = {
  129746. 9, 7, 5, 3, 1, 0, 2, 4,
  129747. 6, 8, 10,
  129748. };
  129749. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  129750. _vq_quantthresh__44c6_s_p5_1,
  129751. _vq_quantmap__44c6_s_p5_1,
  129752. 11,
  129753. 11
  129754. };
  129755. static static_codebook _44c6_s_p5_1 = {
  129756. 2, 121,
  129757. _vq_lengthlist__44c6_s_p5_1,
  129758. 1, -531365888, 1611661312, 4, 0,
  129759. _vq_quantlist__44c6_s_p5_1,
  129760. NULL,
  129761. &_vq_auxt__44c6_s_p5_1,
  129762. NULL,
  129763. 0
  129764. };
  129765. static long _vq_quantlist__44c6_s_p6_0[] = {
  129766. 6,
  129767. 5,
  129768. 7,
  129769. 4,
  129770. 8,
  129771. 3,
  129772. 9,
  129773. 2,
  129774. 10,
  129775. 1,
  129776. 11,
  129777. 0,
  129778. 12,
  129779. };
  129780. static long _vq_lengthlist__44c6_s_p6_0[] = {
  129781. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  129782. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  129783. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  129784. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  129785. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  129786. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  129787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129791. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129792. };
  129793. static float _vq_quantthresh__44c6_s_p6_0[] = {
  129794. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129795. 12.5, 17.5, 22.5, 27.5,
  129796. };
  129797. static long _vq_quantmap__44c6_s_p6_0[] = {
  129798. 11, 9, 7, 5, 3, 1, 0, 2,
  129799. 4, 6, 8, 10, 12,
  129800. };
  129801. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  129802. _vq_quantthresh__44c6_s_p6_0,
  129803. _vq_quantmap__44c6_s_p6_0,
  129804. 13,
  129805. 13
  129806. };
  129807. static static_codebook _44c6_s_p6_0 = {
  129808. 2, 169,
  129809. _vq_lengthlist__44c6_s_p6_0,
  129810. 1, -526516224, 1616117760, 4, 0,
  129811. _vq_quantlist__44c6_s_p6_0,
  129812. NULL,
  129813. &_vq_auxt__44c6_s_p6_0,
  129814. NULL,
  129815. 0
  129816. };
  129817. static long _vq_quantlist__44c6_s_p6_1[] = {
  129818. 2,
  129819. 1,
  129820. 3,
  129821. 0,
  129822. 4,
  129823. };
  129824. static long _vq_lengthlist__44c6_s_p6_1[] = {
  129825. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  129826. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129827. };
  129828. static float _vq_quantthresh__44c6_s_p6_1[] = {
  129829. -1.5, -0.5, 0.5, 1.5,
  129830. };
  129831. static long _vq_quantmap__44c6_s_p6_1[] = {
  129832. 3, 1, 0, 2, 4,
  129833. };
  129834. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  129835. _vq_quantthresh__44c6_s_p6_1,
  129836. _vq_quantmap__44c6_s_p6_1,
  129837. 5,
  129838. 5
  129839. };
  129840. static static_codebook _44c6_s_p6_1 = {
  129841. 2, 25,
  129842. _vq_lengthlist__44c6_s_p6_1,
  129843. 1, -533725184, 1611661312, 3, 0,
  129844. _vq_quantlist__44c6_s_p6_1,
  129845. NULL,
  129846. &_vq_auxt__44c6_s_p6_1,
  129847. NULL,
  129848. 0
  129849. };
  129850. static long _vq_quantlist__44c6_s_p7_0[] = {
  129851. 6,
  129852. 5,
  129853. 7,
  129854. 4,
  129855. 8,
  129856. 3,
  129857. 9,
  129858. 2,
  129859. 10,
  129860. 1,
  129861. 11,
  129862. 0,
  129863. 12,
  129864. };
  129865. static long _vq_lengthlist__44c6_s_p7_0[] = {
  129866. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  129867. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  129868. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  129869. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  129870. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  129871. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  129872. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  129873. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  129874. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  129875. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  129876. 20,13,13,13,13,13,13,14,14,
  129877. };
  129878. static float _vq_quantthresh__44c6_s_p7_0[] = {
  129879. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  129880. 27.5, 38.5, 49.5, 60.5,
  129881. };
  129882. static long _vq_quantmap__44c6_s_p7_0[] = {
  129883. 11, 9, 7, 5, 3, 1, 0, 2,
  129884. 4, 6, 8, 10, 12,
  129885. };
  129886. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  129887. _vq_quantthresh__44c6_s_p7_0,
  129888. _vq_quantmap__44c6_s_p7_0,
  129889. 13,
  129890. 13
  129891. };
  129892. static static_codebook _44c6_s_p7_0 = {
  129893. 2, 169,
  129894. _vq_lengthlist__44c6_s_p7_0,
  129895. 1, -523206656, 1618345984, 4, 0,
  129896. _vq_quantlist__44c6_s_p7_0,
  129897. NULL,
  129898. &_vq_auxt__44c6_s_p7_0,
  129899. NULL,
  129900. 0
  129901. };
  129902. static long _vq_quantlist__44c6_s_p7_1[] = {
  129903. 5,
  129904. 4,
  129905. 6,
  129906. 3,
  129907. 7,
  129908. 2,
  129909. 8,
  129910. 1,
  129911. 9,
  129912. 0,
  129913. 10,
  129914. };
  129915. static long _vq_lengthlist__44c6_s_p7_1[] = {
  129916. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  129917. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  129918. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  129919. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  129920. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  129921. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  129922. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  129923. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  129924. };
  129925. static float _vq_quantthresh__44c6_s_p7_1[] = {
  129926. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129927. 3.5, 4.5,
  129928. };
  129929. static long _vq_quantmap__44c6_s_p7_1[] = {
  129930. 9, 7, 5, 3, 1, 0, 2, 4,
  129931. 6, 8, 10,
  129932. };
  129933. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  129934. _vq_quantthresh__44c6_s_p7_1,
  129935. _vq_quantmap__44c6_s_p7_1,
  129936. 11,
  129937. 11
  129938. };
  129939. static static_codebook _44c6_s_p7_1 = {
  129940. 2, 121,
  129941. _vq_lengthlist__44c6_s_p7_1,
  129942. 1, -531365888, 1611661312, 4, 0,
  129943. _vq_quantlist__44c6_s_p7_1,
  129944. NULL,
  129945. &_vq_auxt__44c6_s_p7_1,
  129946. NULL,
  129947. 0
  129948. };
  129949. static long _vq_quantlist__44c6_s_p8_0[] = {
  129950. 7,
  129951. 6,
  129952. 8,
  129953. 5,
  129954. 9,
  129955. 4,
  129956. 10,
  129957. 3,
  129958. 11,
  129959. 2,
  129960. 12,
  129961. 1,
  129962. 13,
  129963. 0,
  129964. 14,
  129965. };
  129966. static long _vq_lengthlist__44c6_s_p8_0[] = {
  129967. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  129968. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  129969. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  129970. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  129971. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  129972. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  129973. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  129974. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  129975. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  129976. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  129977. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  129978. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  129979. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  129980. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  129981. 14,
  129982. };
  129983. static float _vq_quantthresh__44c6_s_p8_0[] = {
  129984. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  129985. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  129986. };
  129987. static long _vq_quantmap__44c6_s_p8_0[] = {
  129988. 13, 11, 9, 7, 5, 3, 1, 0,
  129989. 2, 4, 6, 8, 10, 12, 14,
  129990. };
  129991. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  129992. _vq_quantthresh__44c6_s_p8_0,
  129993. _vq_quantmap__44c6_s_p8_0,
  129994. 15,
  129995. 15
  129996. };
  129997. static static_codebook _44c6_s_p8_0 = {
  129998. 2, 225,
  129999. _vq_lengthlist__44c6_s_p8_0,
  130000. 1, -520986624, 1620377600, 4, 0,
  130001. _vq_quantlist__44c6_s_p8_0,
  130002. NULL,
  130003. &_vq_auxt__44c6_s_p8_0,
  130004. NULL,
  130005. 0
  130006. };
  130007. static long _vq_quantlist__44c6_s_p8_1[] = {
  130008. 10,
  130009. 9,
  130010. 11,
  130011. 8,
  130012. 12,
  130013. 7,
  130014. 13,
  130015. 6,
  130016. 14,
  130017. 5,
  130018. 15,
  130019. 4,
  130020. 16,
  130021. 3,
  130022. 17,
  130023. 2,
  130024. 18,
  130025. 1,
  130026. 19,
  130027. 0,
  130028. 20,
  130029. };
  130030. static long _vq_lengthlist__44c6_s_p8_1[] = {
  130031. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  130032. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  130033. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  130034. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  130035. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130036. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  130037. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  130038. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  130039. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130040. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130041. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  130042. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  130043. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  130044. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  130045. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  130046. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  130047. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  130048. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  130049. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  130050. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  130051. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  130052. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  130053. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  130054. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  130055. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  130056. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  130057. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  130058. 10,10,10,10,10,10,10,10,10,
  130059. };
  130060. static float _vq_quantthresh__44c6_s_p8_1[] = {
  130061. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  130062. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  130063. 6.5, 7.5, 8.5, 9.5,
  130064. };
  130065. static long _vq_quantmap__44c6_s_p8_1[] = {
  130066. 19, 17, 15, 13, 11, 9, 7, 5,
  130067. 3, 1, 0, 2, 4, 6, 8, 10,
  130068. 12, 14, 16, 18, 20,
  130069. };
  130070. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  130071. _vq_quantthresh__44c6_s_p8_1,
  130072. _vq_quantmap__44c6_s_p8_1,
  130073. 21,
  130074. 21
  130075. };
  130076. static static_codebook _44c6_s_p8_1 = {
  130077. 2, 441,
  130078. _vq_lengthlist__44c6_s_p8_1,
  130079. 1, -529268736, 1611661312, 5, 0,
  130080. _vq_quantlist__44c6_s_p8_1,
  130081. NULL,
  130082. &_vq_auxt__44c6_s_p8_1,
  130083. NULL,
  130084. 0
  130085. };
  130086. static long _vq_quantlist__44c6_s_p9_0[] = {
  130087. 6,
  130088. 5,
  130089. 7,
  130090. 4,
  130091. 8,
  130092. 3,
  130093. 9,
  130094. 2,
  130095. 10,
  130096. 1,
  130097. 11,
  130098. 0,
  130099. 12,
  130100. };
  130101. static long _vq_lengthlist__44c6_s_p9_0[] = {
  130102. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  130103. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  130104. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130105. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  130106. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130107. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130108. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130109. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130110. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130111. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130112. 10,10,10,10,10,10,10,10,10,
  130113. };
  130114. static float _vq_quantthresh__44c6_s_p9_0[] = {
  130115. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  130116. 1592.5, 2229.5, 2866.5, 3503.5,
  130117. };
  130118. static long _vq_quantmap__44c6_s_p9_0[] = {
  130119. 11, 9, 7, 5, 3, 1, 0, 2,
  130120. 4, 6, 8, 10, 12,
  130121. };
  130122. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  130123. _vq_quantthresh__44c6_s_p9_0,
  130124. _vq_quantmap__44c6_s_p9_0,
  130125. 13,
  130126. 13
  130127. };
  130128. static static_codebook _44c6_s_p9_0 = {
  130129. 2, 169,
  130130. _vq_lengthlist__44c6_s_p9_0,
  130131. 1, -511845376, 1630791680, 4, 0,
  130132. _vq_quantlist__44c6_s_p9_0,
  130133. NULL,
  130134. &_vq_auxt__44c6_s_p9_0,
  130135. NULL,
  130136. 0
  130137. };
  130138. static long _vq_quantlist__44c6_s_p9_1[] = {
  130139. 6,
  130140. 5,
  130141. 7,
  130142. 4,
  130143. 8,
  130144. 3,
  130145. 9,
  130146. 2,
  130147. 10,
  130148. 1,
  130149. 11,
  130150. 0,
  130151. 12,
  130152. };
  130153. static long _vq_lengthlist__44c6_s_p9_1[] = {
  130154. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  130155. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  130156. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  130157. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  130158. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  130159. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  130160. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  130161. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  130162. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  130163. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  130164. 15,12,10,11,11,13,11,12,13,
  130165. };
  130166. static float _vq_quantthresh__44c6_s_p9_1[] = {
  130167. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  130168. 122.5, 171.5, 220.5, 269.5,
  130169. };
  130170. static long _vq_quantmap__44c6_s_p9_1[] = {
  130171. 11, 9, 7, 5, 3, 1, 0, 2,
  130172. 4, 6, 8, 10, 12,
  130173. };
  130174. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  130175. _vq_quantthresh__44c6_s_p9_1,
  130176. _vq_quantmap__44c6_s_p9_1,
  130177. 13,
  130178. 13
  130179. };
  130180. static static_codebook _44c6_s_p9_1 = {
  130181. 2, 169,
  130182. _vq_lengthlist__44c6_s_p9_1,
  130183. 1, -518889472, 1622704128, 4, 0,
  130184. _vq_quantlist__44c6_s_p9_1,
  130185. NULL,
  130186. &_vq_auxt__44c6_s_p9_1,
  130187. NULL,
  130188. 0
  130189. };
  130190. static long _vq_quantlist__44c6_s_p9_2[] = {
  130191. 24,
  130192. 23,
  130193. 25,
  130194. 22,
  130195. 26,
  130196. 21,
  130197. 27,
  130198. 20,
  130199. 28,
  130200. 19,
  130201. 29,
  130202. 18,
  130203. 30,
  130204. 17,
  130205. 31,
  130206. 16,
  130207. 32,
  130208. 15,
  130209. 33,
  130210. 14,
  130211. 34,
  130212. 13,
  130213. 35,
  130214. 12,
  130215. 36,
  130216. 11,
  130217. 37,
  130218. 10,
  130219. 38,
  130220. 9,
  130221. 39,
  130222. 8,
  130223. 40,
  130224. 7,
  130225. 41,
  130226. 6,
  130227. 42,
  130228. 5,
  130229. 43,
  130230. 4,
  130231. 44,
  130232. 3,
  130233. 45,
  130234. 2,
  130235. 46,
  130236. 1,
  130237. 47,
  130238. 0,
  130239. 48,
  130240. };
  130241. static long _vq_lengthlist__44c6_s_p9_2[] = {
  130242. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  130243. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  130244. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  130245. 7,
  130246. };
  130247. static float _vq_quantthresh__44c6_s_p9_2[] = {
  130248. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  130249. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  130250. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130251. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130252. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  130253. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  130254. };
  130255. static long _vq_quantmap__44c6_s_p9_2[] = {
  130256. 47, 45, 43, 41, 39, 37, 35, 33,
  130257. 31, 29, 27, 25, 23, 21, 19, 17,
  130258. 15, 13, 11, 9, 7, 5, 3, 1,
  130259. 0, 2, 4, 6, 8, 10, 12, 14,
  130260. 16, 18, 20, 22, 24, 26, 28, 30,
  130261. 32, 34, 36, 38, 40, 42, 44, 46,
  130262. 48,
  130263. };
  130264. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  130265. _vq_quantthresh__44c6_s_p9_2,
  130266. _vq_quantmap__44c6_s_p9_2,
  130267. 49,
  130268. 49
  130269. };
  130270. static static_codebook _44c6_s_p9_2 = {
  130271. 1, 49,
  130272. _vq_lengthlist__44c6_s_p9_2,
  130273. 1, -526909440, 1611661312, 6, 0,
  130274. _vq_quantlist__44c6_s_p9_2,
  130275. NULL,
  130276. &_vq_auxt__44c6_s_p9_2,
  130277. NULL,
  130278. 0
  130279. };
  130280. static long _huff_lengthlist__44c6_s_short[] = {
  130281. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  130282. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  130283. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  130284. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  130285. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  130286. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  130287. 9,10,17,18,
  130288. };
  130289. static static_codebook _huff_book__44c6_s_short = {
  130290. 2, 100,
  130291. _huff_lengthlist__44c6_s_short,
  130292. 0, 0, 0, 0, 0,
  130293. NULL,
  130294. NULL,
  130295. NULL,
  130296. NULL,
  130297. 0
  130298. };
  130299. static long _huff_lengthlist__44c7_s_long[] = {
  130300. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  130301. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  130302. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  130303. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  130304. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  130305. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  130306. 11,10,10,12,
  130307. };
  130308. static static_codebook _huff_book__44c7_s_long = {
  130309. 2, 100,
  130310. _huff_lengthlist__44c7_s_long,
  130311. 0, 0, 0, 0, 0,
  130312. NULL,
  130313. NULL,
  130314. NULL,
  130315. NULL,
  130316. 0
  130317. };
  130318. static long _vq_quantlist__44c7_s_p1_0[] = {
  130319. 1,
  130320. 0,
  130321. 2,
  130322. };
  130323. static long _vq_lengthlist__44c7_s_p1_0[] = {
  130324. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  130325. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  130326. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  130327. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  130328. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  130329. 8,
  130330. };
  130331. static float _vq_quantthresh__44c7_s_p1_0[] = {
  130332. -0.5, 0.5,
  130333. };
  130334. static long _vq_quantmap__44c7_s_p1_0[] = {
  130335. 1, 0, 2,
  130336. };
  130337. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  130338. _vq_quantthresh__44c7_s_p1_0,
  130339. _vq_quantmap__44c7_s_p1_0,
  130340. 3,
  130341. 3
  130342. };
  130343. static static_codebook _44c7_s_p1_0 = {
  130344. 4, 81,
  130345. _vq_lengthlist__44c7_s_p1_0,
  130346. 1, -535822336, 1611661312, 2, 0,
  130347. _vq_quantlist__44c7_s_p1_0,
  130348. NULL,
  130349. &_vq_auxt__44c7_s_p1_0,
  130350. NULL,
  130351. 0
  130352. };
  130353. static long _vq_quantlist__44c7_s_p2_0[] = {
  130354. 2,
  130355. 1,
  130356. 3,
  130357. 0,
  130358. 4,
  130359. };
  130360. static long _vq_lengthlist__44c7_s_p2_0[] = {
  130361. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  130362. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  130363. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  130364. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  130365. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  130366. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  130367. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  130368. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 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, 5, 8, 7,11,10, 0, 7, 7,10,10,
  130371. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  130372. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  130373. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  130374. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  130375. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  130376. 0,12,12,13,13, 0, 0, 0,13,13, 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, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  130379. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  130380. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  130381. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  130382. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  130383. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  130384. 13,13, 0, 0, 0,12,13, 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. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  130387. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  130388. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  130389. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  130390. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  130391. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  130392. 0, 0,13,13, 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, 9,
  130397. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  130398. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  130399. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  130400. 13,
  130401. };
  130402. static float _vq_quantthresh__44c7_s_p2_0[] = {
  130403. -1.5, -0.5, 0.5, 1.5,
  130404. };
  130405. static long _vq_quantmap__44c7_s_p2_0[] = {
  130406. 3, 1, 0, 2, 4,
  130407. };
  130408. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  130409. _vq_quantthresh__44c7_s_p2_0,
  130410. _vq_quantmap__44c7_s_p2_0,
  130411. 5,
  130412. 5
  130413. };
  130414. static static_codebook _44c7_s_p2_0 = {
  130415. 4, 625,
  130416. _vq_lengthlist__44c7_s_p2_0,
  130417. 1, -533725184, 1611661312, 3, 0,
  130418. _vq_quantlist__44c7_s_p2_0,
  130419. NULL,
  130420. &_vq_auxt__44c7_s_p2_0,
  130421. NULL,
  130422. 0
  130423. };
  130424. static long _vq_quantlist__44c7_s_p3_0[] = {
  130425. 4,
  130426. 3,
  130427. 5,
  130428. 2,
  130429. 6,
  130430. 1,
  130431. 7,
  130432. 0,
  130433. 8,
  130434. };
  130435. static long _vq_lengthlist__44c7_s_p3_0[] = {
  130436. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130437. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  130438. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  130439. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  130440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130441. 0,
  130442. };
  130443. static float _vq_quantthresh__44c7_s_p3_0[] = {
  130444. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130445. };
  130446. static long _vq_quantmap__44c7_s_p3_0[] = {
  130447. 7, 5, 3, 1, 0, 2, 4, 6,
  130448. 8,
  130449. };
  130450. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  130451. _vq_quantthresh__44c7_s_p3_0,
  130452. _vq_quantmap__44c7_s_p3_0,
  130453. 9,
  130454. 9
  130455. };
  130456. static static_codebook _44c7_s_p3_0 = {
  130457. 2, 81,
  130458. _vq_lengthlist__44c7_s_p3_0,
  130459. 1, -531628032, 1611661312, 4, 0,
  130460. _vq_quantlist__44c7_s_p3_0,
  130461. NULL,
  130462. &_vq_auxt__44c7_s_p3_0,
  130463. NULL,
  130464. 0
  130465. };
  130466. static long _vq_quantlist__44c7_s_p4_0[] = {
  130467. 8,
  130468. 7,
  130469. 9,
  130470. 6,
  130471. 10,
  130472. 5,
  130473. 11,
  130474. 4,
  130475. 12,
  130476. 3,
  130477. 13,
  130478. 2,
  130479. 14,
  130480. 1,
  130481. 15,
  130482. 0,
  130483. 16,
  130484. };
  130485. static long _vq_lengthlist__44c7_s_p4_0[] = {
  130486. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  130487. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  130488. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  130489. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  130490. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  130491. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  130492. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  130493. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  130494. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  130495. 9,10,10,11,11,12,12,13,13, 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,
  130505. };
  130506. static float _vq_quantthresh__44c7_s_p4_0[] = {
  130507. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130508. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130509. };
  130510. static long _vq_quantmap__44c7_s_p4_0[] = {
  130511. 15, 13, 11, 9, 7, 5, 3, 1,
  130512. 0, 2, 4, 6, 8, 10, 12, 14,
  130513. 16,
  130514. };
  130515. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  130516. _vq_quantthresh__44c7_s_p4_0,
  130517. _vq_quantmap__44c7_s_p4_0,
  130518. 17,
  130519. 17
  130520. };
  130521. static static_codebook _44c7_s_p4_0 = {
  130522. 2, 289,
  130523. _vq_lengthlist__44c7_s_p4_0,
  130524. 1, -529530880, 1611661312, 5, 0,
  130525. _vq_quantlist__44c7_s_p4_0,
  130526. NULL,
  130527. &_vq_auxt__44c7_s_p4_0,
  130528. NULL,
  130529. 0
  130530. };
  130531. static long _vq_quantlist__44c7_s_p5_0[] = {
  130532. 1,
  130533. 0,
  130534. 2,
  130535. };
  130536. static long _vq_lengthlist__44c7_s_p5_0[] = {
  130537. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  130538. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  130539. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  130540. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  130541. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  130542. 12,
  130543. };
  130544. static float _vq_quantthresh__44c7_s_p5_0[] = {
  130545. -5.5, 5.5,
  130546. };
  130547. static long _vq_quantmap__44c7_s_p5_0[] = {
  130548. 1, 0, 2,
  130549. };
  130550. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  130551. _vq_quantthresh__44c7_s_p5_0,
  130552. _vq_quantmap__44c7_s_p5_0,
  130553. 3,
  130554. 3
  130555. };
  130556. static static_codebook _44c7_s_p5_0 = {
  130557. 4, 81,
  130558. _vq_lengthlist__44c7_s_p5_0,
  130559. 1, -529137664, 1618345984, 2, 0,
  130560. _vq_quantlist__44c7_s_p5_0,
  130561. NULL,
  130562. &_vq_auxt__44c7_s_p5_0,
  130563. NULL,
  130564. 0
  130565. };
  130566. static long _vq_quantlist__44c7_s_p5_1[] = {
  130567. 5,
  130568. 4,
  130569. 6,
  130570. 3,
  130571. 7,
  130572. 2,
  130573. 8,
  130574. 1,
  130575. 9,
  130576. 0,
  130577. 10,
  130578. };
  130579. static long _vq_lengthlist__44c7_s_p5_1[] = {
  130580. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  130581. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  130582. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  130583. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  130584. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  130585. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  130586. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  130587. 11,11,11, 7, 7, 8, 8, 8, 8,
  130588. };
  130589. static float _vq_quantthresh__44c7_s_p5_1[] = {
  130590. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130591. 3.5, 4.5,
  130592. };
  130593. static long _vq_quantmap__44c7_s_p5_1[] = {
  130594. 9, 7, 5, 3, 1, 0, 2, 4,
  130595. 6, 8, 10,
  130596. };
  130597. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  130598. _vq_quantthresh__44c7_s_p5_1,
  130599. _vq_quantmap__44c7_s_p5_1,
  130600. 11,
  130601. 11
  130602. };
  130603. static static_codebook _44c7_s_p5_1 = {
  130604. 2, 121,
  130605. _vq_lengthlist__44c7_s_p5_1,
  130606. 1, -531365888, 1611661312, 4, 0,
  130607. _vq_quantlist__44c7_s_p5_1,
  130608. NULL,
  130609. &_vq_auxt__44c7_s_p5_1,
  130610. NULL,
  130611. 0
  130612. };
  130613. static long _vq_quantlist__44c7_s_p6_0[] = {
  130614. 6,
  130615. 5,
  130616. 7,
  130617. 4,
  130618. 8,
  130619. 3,
  130620. 9,
  130621. 2,
  130622. 10,
  130623. 1,
  130624. 11,
  130625. 0,
  130626. 12,
  130627. };
  130628. static long _vq_lengthlist__44c7_s_p6_0[] = {
  130629. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  130630. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  130631. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  130632. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  130633. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  130634. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  130635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  130640. };
  130641. static float _vq_quantthresh__44c7_s_p6_0[] = {
  130642. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130643. 12.5, 17.5, 22.5, 27.5,
  130644. };
  130645. static long _vq_quantmap__44c7_s_p6_0[] = {
  130646. 11, 9, 7, 5, 3, 1, 0, 2,
  130647. 4, 6, 8, 10, 12,
  130648. };
  130649. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  130650. _vq_quantthresh__44c7_s_p6_0,
  130651. _vq_quantmap__44c7_s_p6_0,
  130652. 13,
  130653. 13
  130654. };
  130655. static static_codebook _44c7_s_p6_0 = {
  130656. 2, 169,
  130657. _vq_lengthlist__44c7_s_p6_0,
  130658. 1, -526516224, 1616117760, 4, 0,
  130659. _vq_quantlist__44c7_s_p6_0,
  130660. NULL,
  130661. &_vq_auxt__44c7_s_p6_0,
  130662. NULL,
  130663. 0
  130664. };
  130665. static long _vq_quantlist__44c7_s_p6_1[] = {
  130666. 2,
  130667. 1,
  130668. 3,
  130669. 0,
  130670. 4,
  130671. };
  130672. static long _vq_lengthlist__44c7_s_p6_1[] = {
  130673. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  130674. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130675. };
  130676. static float _vq_quantthresh__44c7_s_p6_1[] = {
  130677. -1.5, -0.5, 0.5, 1.5,
  130678. };
  130679. static long _vq_quantmap__44c7_s_p6_1[] = {
  130680. 3, 1, 0, 2, 4,
  130681. };
  130682. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  130683. _vq_quantthresh__44c7_s_p6_1,
  130684. _vq_quantmap__44c7_s_p6_1,
  130685. 5,
  130686. 5
  130687. };
  130688. static static_codebook _44c7_s_p6_1 = {
  130689. 2, 25,
  130690. _vq_lengthlist__44c7_s_p6_1,
  130691. 1, -533725184, 1611661312, 3, 0,
  130692. _vq_quantlist__44c7_s_p6_1,
  130693. NULL,
  130694. &_vq_auxt__44c7_s_p6_1,
  130695. NULL,
  130696. 0
  130697. };
  130698. static long _vq_quantlist__44c7_s_p7_0[] = {
  130699. 6,
  130700. 5,
  130701. 7,
  130702. 4,
  130703. 8,
  130704. 3,
  130705. 9,
  130706. 2,
  130707. 10,
  130708. 1,
  130709. 11,
  130710. 0,
  130711. 12,
  130712. };
  130713. static long _vq_lengthlist__44c7_s_p7_0[] = {
  130714. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  130715. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  130716. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  130717. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  130718. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  130719. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  130720. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  130721. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  130722. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  130723. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  130724. 19,13,13,13,13,14,14,15,15,
  130725. };
  130726. static float _vq_quantthresh__44c7_s_p7_0[] = {
  130727. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  130728. 27.5, 38.5, 49.5, 60.5,
  130729. };
  130730. static long _vq_quantmap__44c7_s_p7_0[] = {
  130731. 11, 9, 7, 5, 3, 1, 0, 2,
  130732. 4, 6, 8, 10, 12,
  130733. };
  130734. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  130735. _vq_quantthresh__44c7_s_p7_0,
  130736. _vq_quantmap__44c7_s_p7_0,
  130737. 13,
  130738. 13
  130739. };
  130740. static static_codebook _44c7_s_p7_0 = {
  130741. 2, 169,
  130742. _vq_lengthlist__44c7_s_p7_0,
  130743. 1, -523206656, 1618345984, 4, 0,
  130744. _vq_quantlist__44c7_s_p7_0,
  130745. NULL,
  130746. &_vq_auxt__44c7_s_p7_0,
  130747. NULL,
  130748. 0
  130749. };
  130750. static long _vq_quantlist__44c7_s_p7_1[] = {
  130751. 5,
  130752. 4,
  130753. 6,
  130754. 3,
  130755. 7,
  130756. 2,
  130757. 8,
  130758. 1,
  130759. 9,
  130760. 0,
  130761. 10,
  130762. };
  130763. static long _vq_lengthlist__44c7_s_p7_1[] = {
  130764. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  130765. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  130766. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  130767. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  130768. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  130769. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  130770. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  130771. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  130772. };
  130773. static float _vq_quantthresh__44c7_s_p7_1[] = {
  130774. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130775. 3.5, 4.5,
  130776. };
  130777. static long _vq_quantmap__44c7_s_p7_1[] = {
  130778. 9, 7, 5, 3, 1, 0, 2, 4,
  130779. 6, 8, 10,
  130780. };
  130781. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  130782. _vq_quantthresh__44c7_s_p7_1,
  130783. _vq_quantmap__44c7_s_p7_1,
  130784. 11,
  130785. 11
  130786. };
  130787. static static_codebook _44c7_s_p7_1 = {
  130788. 2, 121,
  130789. _vq_lengthlist__44c7_s_p7_1,
  130790. 1, -531365888, 1611661312, 4, 0,
  130791. _vq_quantlist__44c7_s_p7_1,
  130792. NULL,
  130793. &_vq_auxt__44c7_s_p7_1,
  130794. NULL,
  130795. 0
  130796. };
  130797. static long _vq_quantlist__44c7_s_p8_0[] = {
  130798. 7,
  130799. 6,
  130800. 8,
  130801. 5,
  130802. 9,
  130803. 4,
  130804. 10,
  130805. 3,
  130806. 11,
  130807. 2,
  130808. 12,
  130809. 1,
  130810. 13,
  130811. 0,
  130812. 14,
  130813. };
  130814. static long _vq_lengthlist__44c7_s_p8_0[] = {
  130815. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  130816. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  130817. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  130818. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  130819. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  130820. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  130821. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  130822. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  130823. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  130824. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  130825. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  130826. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  130827. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  130828. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  130829. 14,
  130830. };
  130831. static float _vq_quantthresh__44c7_s_p8_0[] = {
  130832. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  130833. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  130834. };
  130835. static long _vq_quantmap__44c7_s_p8_0[] = {
  130836. 13, 11, 9, 7, 5, 3, 1, 0,
  130837. 2, 4, 6, 8, 10, 12, 14,
  130838. };
  130839. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  130840. _vq_quantthresh__44c7_s_p8_0,
  130841. _vq_quantmap__44c7_s_p8_0,
  130842. 15,
  130843. 15
  130844. };
  130845. static static_codebook _44c7_s_p8_0 = {
  130846. 2, 225,
  130847. _vq_lengthlist__44c7_s_p8_0,
  130848. 1, -520986624, 1620377600, 4, 0,
  130849. _vq_quantlist__44c7_s_p8_0,
  130850. NULL,
  130851. &_vq_auxt__44c7_s_p8_0,
  130852. NULL,
  130853. 0
  130854. };
  130855. static long _vq_quantlist__44c7_s_p8_1[] = {
  130856. 10,
  130857. 9,
  130858. 11,
  130859. 8,
  130860. 12,
  130861. 7,
  130862. 13,
  130863. 6,
  130864. 14,
  130865. 5,
  130866. 15,
  130867. 4,
  130868. 16,
  130869. 3,
  130870. 17,
  130871. 2,
  130872. 18,
  130873. 1,
  130874. 19,
  130875. 0,
  130876. 20,
  130877. };
  130878. static long _vq_lengthlist__44c7_s_p8_1[] = {
  130879. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  130880. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  130881. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  130882. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  130883. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130884. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  130885. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  130886. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  130887. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130888. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130889. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  130890. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  130891. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  130892. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  130893. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  130894. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  130895. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  130896. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  130897. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  130898. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  130899. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  130900. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  130901. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  130902. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  130903. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  130904. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  130905. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  130906. 10,10,10,10,10,10,10,10,10,
  130907. };
  130908. static float _vq_quantthresh__44c7_s_p8_1[] = {
  130909. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  130910. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  130911. 6.5, 7.5, 8.5, 9.5,
  130912. };
  130913. static long _vq_quantmap__44c7_s_p8_1[] = {
  130914. 19, 17, 15, 13, 11, 9, 7, 5,
  130915. 3, 1, 0, 2, 4, 6, 8, 10,
  130916. 12, 14, 16, 18, 20,
  130917. };
  130918. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  130919. _vq_quantthresh__44c7_s_p8_1,
  130920. _vq_quantmap__44c7_s_p8_1,
  130921. 21,
  130922. 21
  130923. };
  130924. static static_codebook _44c7_s_p8_1 = {
  130925. 2, 441,
  130926. _vq_lengthlist__44c7_s_p8_1,
  130927. 1, -529268736, 1611661312, 5, 0,
  130928. _vq_quantlist__44c7_s_p8_1,
  130929. NULL,
  130930. &_vq_auxt__44c7_s_p8_1,
  130931. NULL,
  130932. 0
  130933. };
  130934. static long _vq_quantlist__44c7_s_p9_0[] = {
  130935. 6,
  130936. 5,
  130937. 7,
  130938. 4,
  130939. 8,
  130940. 3,
  130941. 9,
  130942. 2,
  130943. 10,
  130944. 1,
  130945. 11,
  130946. 0,
  130947. 12,
  130948. };
  130949. static long _vq_lengthlist__44c7_s_p9_0[] = {
  130950. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  130951. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  130952. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130953. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130954. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130955. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130956. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130957. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130958. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130959. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130960. 11,11,11,11,11,11,11,11,11,
  130961. };
  130962. static float _vq_quantthresh__44c7_s_p9_0[] = {
  130963. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  130964. 1592.5, 2229.5, 2866.5, 3503.5,
  130965. };
  130966. static long _vq_quantmap__44c7_s_p9_0[] = {
  130967. 11, 9, 7, 5, 3, 1, 0, 2,
  130968. 4, 6, 8, 10, 12,
  130969. };
  130970. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  130971. _vq_quantthresh__44c7_s_p9_0,
  130972. _vq_quantmap__44c7_s_p9_0,
  130973. 13,
  130974. 13
  130975. };
  130976. static static_codebook _44c7_s_p9_0 = {
  130977. 2, 169,
  130978. _vq_lengthlist__44c7_s_p9_0,
  130979. 1, -511845376, 1630791680, 4, 0,
  130980. _vq_quantlist__44c7_s_p9_0,
  130981. NULL,
  130982. &_vq_auxt__44c7_s_p9_0,
  130983. NULL,
  130984. 0
  130985. };
  130986. static long _vq_quantlist__44c7_s_p9_1[] = {
  130987. 6,
  130988. 5,
  130989. 7,
  130990. 4,
  130991. 8,
  130992. 3,
  130993. 9,
  130994. 2,
  130995. 10,
  130996. 1,
  130997. 11,
  130998. 0,
  130999. 12,
  131000. };
  131001. static long _vq_lengthlist__44c7_s_p9_1[] = {
  131002. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  131003. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  131004. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  131005. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  131006. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  131007. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  131008. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  131009. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  131010. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  131011. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  131012. 15,11,11,10,10,12,12,12,12,
  131013. };
  131014. static float _vq_quantthresh__44c7_s_p9_1[] = {
  131015. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  131016. 122.5, 171.5, 220.5, 269.5,
  131017. };
  131018. static long _vq_quantmap__44c7_s_p9_1[] = {
  131019. 11, 9, 7, 5, 3, 1, 0, 2,
  131020. 4, 6, 8, 10, 12,
  131021. };
  131022. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  131023. _vq_quantthresh__44c7_s_p9_1,
  131024. _vq_quantmap__44c7_s_p9_1,
  131025. 13,
  131026. 13
  131027. };
  131028. static static_codebook _44c7_s_p9_1 = {
  131029. 2, 169,
  131030. _vq_lengthlist__44c7_s_p9_1,
  131031. 1, -518889472, 1622704128, 4, 0,
  131032. _vq_quantlist__44c7_s_p9_1,
  131033. NULL,
  131034. &_vq_auxt__44c7_s_p9_1,
  131035. NULL,
  131036. 0
  131037. };
  131038. static long _vq_quantlist__44c7_s_p9_2[] = {
  131039. 24,
  131040. 23,
  131041. 25,
  131042. 22,
  131043. 26,
  131044. 21,
  131045. 27,
  131046. 20,
  131047. 28,
  131048. 19,
  131049. 29,
  131050. 18,
  131051. 30,
  131052. 17,
  131053. 31,
  131054. 16,
  131055. 32,
  131056. 15,
  131057. 33,
  131058. 14,
  131059. 34,
  131060. 13,
  131061. 35,
  131062. 12,
  131063. 36,
  131064. 11,
  131065. 37,
  131066. 10,
  131067. 38,
  131068. 9,
  131069. 39,
  131070. 8,
  131071. 40,
  131072. 7,
  131073. 41,
  131074. 6,
  131075. 42,
  131076. 5,
  131077. 43,
  131078. 4,
  131079. 44,
  131080. 3,
  131081. 45,
  131082. 2,
  131083. 46,
  131084. 1,
  131085. 47,
  131086. 0,
  131087. 48,
  131088. };
  131089. static long _vq_lengthlist__44c7_s_p9_2[] = {
  131090. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  131091. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  131092. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  131093. 7,
  131094. };
  131095. static float _vq_quantthresh__44c7_s_p9_2[] = {
  131096. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  131097. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  131098. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131099. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131100. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  131101. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  131102. };
  131103. static long _vq_quantmap__44c7_s_p9_2[] = {
  131104. 47, 45, 43, 41, 39, 37, 35, 33,
  131105. 31, 29, 27, 25, 23, 21, 19, 17,
  131106. 15, 13, 11, 9, 7, 5, 3, 1,
  131107. 0, 2, 4, 6, 8, 10, 12, 14,
  131108. 16, 18, 20, 22, 24, 26, 28, 30,
  131109. 32, 34, 36, 38, 40, 42, 44, 46,
  131110. 48,
  131111. };
  131112. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  131113. _vq_quantthresh__44c7_s_p9_2,
  131114. _vq_quantmap__44c7_s_p9_2,
  131115. 49,
  131116. 49
  131117. };
  131118. static static_codebook _44c7_s_p9_2 = {
  131119. 1, 49,
  131120. _vq_lengthlist__44c7_s_p9_2,
  131121. 1, -526909440, 1611661312, 6, 0,
  131122. _vq_quantlist__44c7_s_p9_2,
  131123. NULL,
  131124. &_vq_auxt__44c7_s_p9_2,
  131125. NULL,
  131126. 0
  131127. };
  131128. static long _huff_lengthlist__44c7_s_short[] = {
  131129. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  131130. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  131131. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  131132. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  131133. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  131134. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  131135. 10, 9,11,14,
  131136. };
  131137. static static_codebook _huff_book__44c7_s_short = {
  131138. 2, 100,
  131139. _huff_lengthlist__44c7_s_short,
  131140. 0, 0, 0, 0, 0,
  131141. NULL,
  131142. NULL,
  131143. NULL,
  131144. NULL,
  131145. 0
  131146. };
  131147. static long _huff_lengthlist__44c8_s_long[] = {
  131148. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  131149. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  131150. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  131151. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  131152. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  131153. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  131154. 11, 9, 9,10,
  131155. };
  131156. static static_codebook _huff_book__44c8_s_long = {
  131157. 2, 100,
  131158. _huff_lengthlist__44c8_s_long,
  131159. 0, 0, 0, 0, 0,
  131160. NULL,
  131161. NULL,
  131162. NULL,
  131163. NULL,
  131164. 0
  131165. };
  131166. static long _vq_quantlist__44c8_s_p1_0[] = {
  131167. 1,
  131168. 0,
  131169. 2,
  131170. };
  131171. static long _vq_lengthlist__44c8_s_p1_0[] = {
  131172. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  131173. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  131174. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  131175. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  131176. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  131177. 8,
  131178. };
  131179. static float _vq_quantthresh__44c8_s_p1_0[] = {
  131180. -0.5, 0.5,
  131181. };
  131182. static long _vq_quantmap__44c8_s_p1_0[] = {
  131183. 1, 0, 2,
  131184. };
  131185. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  131186. _vq_quantthresh__44c8_s_p1_0,
  131187. _vq_quantmap__44c8_s_p1_0,
  131188. 3,
  131189. 3
  131190. };
  131191. static static_codebook _44c8_s_p1_0 = {
  131192. 4, 81,
  131193. _vq_lengthlist__44c8_s_p1_0,
  131194. 1, -535822336, 1611661312, 2, 0,
  131195. _vq_quantlist__44c8_s_p1_0,
  131196. NULL,
  131197. &_vq_auxt__44c8_s_p1_0,
  131198. NULL,
  131199. 0
  131200. };
  131201. static long _vq_quantlist__44c8_s_p2_0[] = {
  131202. 2,
  131203. 1,
  131204. 3,
  131205. 0,
  131206. 4,
  131207. };
  131208. static long _vq_lengthlist__44c8_s_p2_0[] = {
  131209. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  131210. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  131211. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  131212. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  131213. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  131214. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  131215. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  131216. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  131217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131218. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  131219. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  131220. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  131221. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  131222. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  131223. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  131224. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  131225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131226. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  131227. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  131228. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  131229. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  131230. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  131231. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  131232. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131234. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  131235. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  131236. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  131237. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  131238. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  131239. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  131240. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  131245. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  131246. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  131247. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  131248. 13,
  131249. };
  131250. static float _vq_quantthresh__44c8_s_p2_0[] = {
  131251. -1.5, -0.5, 0.5, 1.5,
  131252. };
  131253. static long _vq_quantmap__44c8_s_p2_0[] = {
  131254. 3, 1, 0, 2, 4,
  131255. };
  131256. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  131257. _vq_quantthresh__44c8_s_p2_0,
  131258. _vq_quantmap__44c8_s_p2_0,
  131259. 5,
  131260. 5
  131261. };
  131262. static static_codebook _44c8_s_p2_0 = {
  131263. 4, 625,
  131264. _vq_lengthlist__44c8_s_p2_0,
  131265. 1, -533725184, 1611661312, 3, 0,
  131266. _vq_quantlist__44c8_s_p2_0,
  131267. NULL,
  131268. &_vq_auxt__44c8_s_p2_0,
  131269. NULL,
  131270. 0
  131271. };
  131272. static long _vq_quantlist__44c8_s_p3_0[] = {
  131273. 4,
  131274. 3,
  131275. 5,
  131276. 2,
  131277. 6,
  131278. 1,
  131279. 7,
  131280. 0,
  131281. 8,
  131282. };
  131283. static long _vq_lengthlist__44c8_s_p3_0[] = {
  131284. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131285. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  131286. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  131287. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  131288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131289. 0,
  131290. };
  131291. static float _vq_quantthresh__44c8_s_p3_0[] = {
  131292. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131293. };
  131294. static long _vq_quantmap__44c8_s_p3_0[] = {
  131295. 7, 5, 3, 1, 0, 2, 4, 6,
  131296. 8,
  131297. };
  131298. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  131299. _vq_quantthresh__44c8_s_p3_0,
  131300. _vq_quantmap__44c8_s_p3_0,
  131301. 9,
  131302. 9
  131303. };
  131304. static static_codebook _44c8_s_p3_0 = {
  131305. 2, 81,
  131306. _vq_lengthlist__44c8_s_p3_0,
  131307. 1, -531628032, 1611661312, 4, 0,
  131308. _vq_quantlist__44c8_s_p3_0,
  131309. NULL,
  131310. &_vq_auxt__44c8_s_p3_0,
  131311. NULL,
  131312. 0
  131313. };
  131314. static long _vq_quantlist__44c8_s_p4_0[] = {
  131315. 8,
  131316. 7,
  131317. 9,
  131318. 6,
  131319. 10,
  131320. 5,
  131321. 11,
  131322. 4,
  131323. 12,
  131324. 3,
  131325. 13,
  131326. 2,
  131327. 14,
  131328. 1,
  131329. 15,
  131330. 0,
  131331. 16,
  131332. };
  131333. static long _vq_lengthlist__44c8_s_p4_0[] = {
  131334. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  131335. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  131336. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  131337. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  131338. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  131339. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  131340. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  131341. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  131342. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  131343. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  131344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131352. 0,
  131353. };
  131354. static float _vq_quantthresh__44c8_s_p4_0[] = {
  131355. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131356. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131357. };
  131358. static long _vq_quantmap__44c8_s_p4_0[] = {
  131359. 15, 13, 11, 9, 7, 5, 3, 1,
  131360. 0, 2, 4, 6, 8, 10, 12, 14,
  131361. 16,
  131362. };
  131363. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  131364. _vq_quantthresh__44c8_s_p4_0,
  131365. _vq_quantmap__44c8_s_p4_0,
  131366. 17,
  131367. 17
  131368. };
  131369. static static_codebook _44c8_s_p4_0 = {
  131370. 2, 289,
  131371. _vq_lengthlist__44c8_s_p4_0,
  131372. 1, -529530880, 1611661312, 5, 0,
  131373. _vq_quantlist__44c8_s_p4_0,
  131374. NULL,
  131375. &_vq_auxt__44c8_s_p4_0,
  131376. NULL,
  131377. 0
  131378. };
  131379. static long _vq_quantlist__44c8_s_p5_0[] = {
  131380. 1,
  131381. 0,
  131382. 2,
  131383. };
  131384. static long _vq_lengthlist__44c8_s_p5_0[] = {
  131385. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  131386. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  131387. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  131388. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  131389. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  131390. 12,
  131391. };
  131392. static float _vq_quantthresh__44c8_s_p5_0[] = {
  131393. -5.5, 5.5,
  131394. };
  131395. static long _vq_quantmap__44c8_s_p5_0[] = {
  131396. 1, 0, 2,
  131397. };
  131398. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  131399. _vq_quantthresh__44c8_s_p5_0,
  131400. _vq_quantmap__44c8_s_p5_0,
  131401. 3,
  131402. 3
  131403. };
  131404. static static_codebook _44c8_s_p5_0 = {
  131405. 4, 81,
  131406. _vq_lengthlist__44c8_s_p5_0,
  131407. 1, -529137664, 1618345984, 2, 0,
  131408. _vq_quantlist__44c8_s_p5_0,
  131409. NULL,
  131410. &_vq_auxt__44c8_s_p5_0,
  131411. NULL,
  131412. 0
  131413. };
  131414. static long _vq_quantlist__44c8_s_p5_1[] = {
  131415. 5,
  131416. 4,
  131417. 6,
  131418. 3,
  131419. 7,
  131420. 2,
  131421. 8,
  131422. 1,
  131423. 9,
  131424. 0,
  131425. 10,
  131426. };
  131427. static long _vq_lengthlist__44c8_s_p5_1[] = {
  131428. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  131429. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131430. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  131431. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  131432. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  131433. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  131434. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  131435. 11,11,11, 7, 7, 7, 7, 8, 8,
  131436. };
  131437. static float _vq_quantthresh__44c8_s_p5_1[] = {
  131438. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131439. 3.5, 4.5,
  131440. };
  131441. static long _vq_quantmap__44c8_s_p5_1[] = {
  131442. 9, 7, 5, 3, 1, 0, 2, 4,
  131443. 6, 8, 10,
  131444. };
  131445. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  131446. _vq_quantthresh__44c8_s_p5_1,
  131447. _vq_quantmap__44c8_s_p5_1,
  131448. 11,
  131449. 11
  131450. };
  131451. static static_codebook _44c8_s_p5_1 = {
  131452. 2, 121,
  131453. _vq_lengthlist__44c8_s_p5_1,
  131454. 1, -531365888, 1611661312, 4, 0,
  131455. _vq_quantlist__44c8_s_p5_1,
  131456. NULL,
  131457. &_vq_auxt__44c8_s_p5_1,
  131458. NULL,
  131459. 0
  131460. };
  131461. static long _vq_quantlist__44c8_s_p6_0[] = {
  131462. 6,
  131463. 5,
  131464. 7,
  131465. 4,
  131466. 8,
  131467. 3,
  131468. 9,
  131469. 2,
  131470. 10,
  131471. 1,
  131472. 11,
  131473. 0,
  131474. 12,
  131475. };
  131476. static long _vq_lengthlist__44c8_s_p6_0[] = {
  131477. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  131478. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  131479. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  131480. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  131481. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  131482. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  131483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  131488. };
  131489. static float _vq_quantthresh__44c8_s_p6_0[] = {
  131490. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131491. 12.5, 17.5, 22.5, 27.5,
  131492. };
  131493. static long _vq_quantmap__44c8_s_p6_0[] = {
  131494. 11, 9, 7, 5, 3, 1, 0, 2,
  131495. 4, 6, 8, 10, 12,
  131496. };
  131497. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  131498. _vq_quantthresh__44c8_s_p6_0,
  131499. _vq_quantmap__44c8_s_p6_0,
  131500. 13,
  131501. 13
  131502. };
  131503. static static_codebook _44c8_s_p6_0 = {
  131504. 2, 169,
  131505. _vq_lengthlist__44c8_s_p6_0,
  131506. 1, -526516224, 1616117760, 4, 0,
  131507. _vq_quantlist__44c8_s_p6_0,
  131508. NULL,
  131509. &_vq_auxt__44c8_s_p6_0,
  131510. NULL,
  131511. 0
  131512. };
  131513. static long _vq_quantlist__44c8_s_p6_1[] = {
  131514. 2,
  131515. 1,
  131516. 3,
  131517. 0,
  131518. 4,
  131519. };
  131520. static long _vq_lengthlist__44c8_s_p6_1[] = {
  131521. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  131522. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131523. };
  131524. static float _vq_quantthresh__44c8_s_p6_1[] = {
  131525. -1.5, -0.5, 0.5, 1.5,
  131526. };
  131527. static long _vq_quantmap__44c8_s_p6_1[] = {
  131528. 3, 1, 0, 2, 4,
  131529. };
  131530. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  131531. _vq_quantthresh__44c8_s_p6_1,
  131532. _vq_quantmap__44c8_s_p6_1,
  131533. 5,
  131534. 5
  131535. };
  131536. static static_codebook _44c8_s_p6_1 = {
  131537. 2, 25,
  131538. _vq_lengthlist__44c8_s_p6_1,
  131539. 1, -533725184, 1611661312, 3, 0,
  131540. _vq_quantlist__44c8_s_p6_1,
  131541. NULL,
  131542. &_vq_auxt__44c8_s_p6_1,
  131543. NULL,
  131544. 0
  131545. };
  131546. static long _vq_quantlist__44c8_s_p7_0[] = {
  131547. 6,
  131548. 5,
  131549. 7,
  131550. 4,
  131551. 8,
  131552. 3,
  131553. 9,
  131554. 2,
  131555. 10,
  131556. 1,
  131557. 11,
  131558. 0,
  131559. 12,
  131560. };
  131561. static long _vq_lengthlist__44c8_s_p7_0[] = {
  131562. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  131563. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  131564. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  131565. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  131566. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  131567. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  131568. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  131569. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  131570. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  131571. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  131572. 20,13,13,13,13,14,13,15,15,
  131573. };
  131574. static float _vq_quantthresh__44c8_s_p7_0[] = {
  131575. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  131576. 27.5, 38.5, 49.5, 60.5,
  131577. };
  131578. static long _vq_quantmap__44c8_s_p7_0[] = {
  131579. 11, 9, 7, 5, 3, 1, 0, 2,
  131580. 4, 6, 8, 10, 12,
  131581. };
  131582. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  131583. _vq_quantthresh__44c8_s_p7_0,
  131584. _vq_quantmap__44c8_s_p7_0,
  131585. 13,
  131586. 13
  131587. };
  131588. static static_codebook _44c8_s_p7_0 = {
  131589. 2, 169,
  131590. _vq_lengthlist__44c8_s_p7_0,
  131591. 1, -523206656, 1618345984, 4, 0,
  131592. _vq_quantlist__44c8_s_p7_0,
  131593. NULL,
  131594. &_vq_auxt__44c8_s_p7_0,
  131595. NULL,
  131596. 0
  131597. };
  131598. static long _vq_quantlist__44c8_s_p7_1[] = {
  131599. 5,
  131600. 4,
  131601. 6,
  131602. 3,
  131603. 7,
  131604. 2,
  131605. 8,
  131606. 1,
  131607. 9,
  131608. 0,
  131609. 10,
  131610. };
  131611. static long _vq_lengthlist__44c8_s_p7_1[] = {
  131612. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  131613. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  131614. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  131615. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  131616. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  131617. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  131618. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  131619. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  131620. };
  131621. static float _vq_quantthresh__44c8_s_p7_1[] = {
  131622. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131623. 3.5, 4.5,
  131624. };
  131625. static long _vq_quantmap__44c8_s_p7_1[] = {
  131626. 9, 7, 5, 3, 1, 0, 2, 4,
  131627. 6, 8, 10,
  131628. };
  131629. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  131630. _vq_quantthresh__44c8_s_p7_1,
  131631. _vq_quantmap__44c8_s_p7_1,
  131632. 11,
  131633. 11
  131634. };
  131635. static static_codebook _44c8_s_p7_1 = {
  131636. 2, 121,
  131637. _vq_lengthlist__44c8_s_p7_1,
  131638. 1, -531365888, 1611661312, 4, 0,
  131639. _vq_quantlist__44c8_s_p7_1,
  131640. NULL,
  131641. &_vq_auxt__44c8_s_p7_1,
  131642. NULL,
  131643. 0
  131644. };
  131645. static long _vq_quantlist__44c8_s_p8_0[] = {
  131646. 7,
  131647. 6,
  131648. 8,
  131649. 5,
  131650. 9,
  131651. 4,
  131652. 10,
  131653. 3,
  131654. 11,
  131655. 2,
  131656. 12,
  131657. 1,
  131658. 13,
  131659. 0,
  131660. 14,
  131661. };
  131662. static long _vq_lengthlist__44c8_s_p8_0[] = {
  131663. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  131664. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  131665. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  131666. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  131667. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  131668. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  131669. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  131670. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  131671. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  131672. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  131673. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  131674. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  131675. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  131676. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  131677. 15,
  131678. };
  131679. static float _vq_quantthresh__44c8_s_p8_0[] = {
  131680. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  131681. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  131682. };
  131683. static long _vq_quantmap__44c8_s_p8_0[] = {
  131684. 13, 11, 9, 7, 5, 3, 1, 0,
  131685. 2, 4, 6, 8, 10, 12, 14,
  131686. };
  131687. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  131688. _vq_quantthresh__44c8_s_p8_0,
  131689. _vq_quantmap__44c8_s_p8_0,
  131690. 15,
  131691. 15
  131692. };
  131693. static static_codebook _44c8_s_p8_0 = {
  131694. 2, 225,
  131695. _vq_lengthlist__44c8_s_p8_0,
  131696. 1, -520986624, 1620377600, 4, 0,
  131697. _vq_quantlist__44c8_s_p8_0,
  131698. NULL,
  131699. &_vq_auxt__44c8_s_p8_0,
  131700. NULL,
  131701. 0
  131702. };
  131703. static long _vq_quantlist__44c8_s_p8_1[] = {
  131704. 10,
  131705. 9,
  131706. 11,
  131707. 8,
  131708. 12,
  131709. 7,
  131710. 13,
  131711. 6,
  131712. 14,
  131713. 5,
  131714. 15,
  131715. 4,
  131716. 16,
  131717. 3,
  131718. 17,
  131719. 2,
  131720. 18,
  131721. 1,
  131722. 19,
  131723. 0,
  131724. 20,
  131725. };
  131726. static long _vq_lengthlist__44c8_s_p8_1[] = {
  131727. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  131728. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  131729. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  131730. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  131731. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131732. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  131733. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  131734. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  131735. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131736. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131737. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  131738. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131739. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  131740. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131741. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  131742. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  131743. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  131744. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  131745. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  131746. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  131747. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  131748. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  131749. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  131750. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  131751. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  131752. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  131753. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  131754. 10, 9, 9,10,10, 9,10, 9, 9,
  131755. };
  131756. static float _vq_quantthresh__44c8_s_p8_1[] = {
  131757. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131758. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131759. 6.5, 7.5, 8.5, 9.5,
  131760. };
  131761. static long _vq_quantmap__44c8_s_p8_1[] = {
  131762. 19, 17, 15, 13, 11, 9, 7, 5,
  131763. 3, 1, 0, 2, 4, 6, 8, 10,
  131764. 12, 14, 16, 18, 20,
  131765. };
  131766. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  131767. _vq_quantthresh__44c8_s_p8_1,
  131768. _vq_quantmap__44c8_s_p8_1,
  131769. 21,
  131770. 21
  131771. };
  131772. static static_codebook _44c8_s_p8_1 = {
  131773. 2, 441,
  131774. _vq_lengthlist__44c8_s_p8_1,
  131775. 1, -529268736, 1611661312, 5, 0,
  131776. _vq_quantlist__44c8_s_p8_1,
  131777. NULL,
  131778. &_vq_auxt__44c8_s_p8_1,
  131779. NULL,
  131780. 0
  131781. };
  131782. static long _vq_quantlist__44c8_s_p9_0[] = {
  131783. 8,
  131784. 7,
  131785. 9,
  131786. 6,
  131787. 10,
  131788. 5,
  131789. 11,
  131790. 4,
  131791. 12,
  131792. 3,
  131793. 13,
  131794. 2,
  131795. 14,
  131796. 1,
  131797. 15,
  131798. 0,
  131799. 16,
  131800. };
  131801. static long _vq_lengthlist__44c8_s_p9_0[] = {
  131802. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131803. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  131804. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  131805. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131806. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131807. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131808. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131809. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131810. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131811. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131812. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131813. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131814. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131815. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131816. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131817. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131818. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131819. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131820. 10,
  131821. };
  131822. static float _vq_quantthresh__44c8_s_p9_0[] = {
  131823. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  131824. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  131825. };
  131826. static long _vq_quantmap__44c8_s_p9_0[] = {
  131827. 15, 13, 11, 9, 7, 5, 3, 1,
  131828. 0, 2, 4, 6, 8, 10, 12, 14,
  131829. 16,
  131830. };
  131831. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  131832. _vq_quantthresh__44c8_s_p9_0,
  131833. _vq_quantmap__44c8_s_p9_0,
  131834. 17,
  131835. 17
  131836. };
  131837. static static_codebook _44c8_s_p9_0 = {
  131838. 2, 289,
  131839. _vq_lengthlist__44c8_s_p9_0,
  131840. 1, -509798400, 1631393792, 5, 0,
  131841. _vq_quantlist__44c8_s_p9_0,
  131842. NULL,
  131843. &_vq_auxt__44c8_s_p9_0,
  131844. NULL,
  131845. 0
  131846. };
  131847. static long _vq_quantlist__44c8_s_p9_1[] = {
  131848. 9,
  131849. 8,
  131850. 10,
  131851. 7,
  131852. 11,
  131853. 6,
  131854. 12,
  131855. 5,
  131856. 13,
  131857. 4,
  131858. 14,
  131859. 3,
  131860. 15,
  131861. 2,
  131862. 16,
  131863. 1,
  131864. 17,
  131865. 0,
  131866. 18,
  131867. };
  131868. static long _vq_lengthlist__44c8_s_p9_1[] = {
  131869. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  131870. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  131871. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  131872. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  131873. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  131874. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  131875. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  131876. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  131877. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  131878. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  131879. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  131880. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  131881. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  131882. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  131883. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  131884. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  131885. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  131886. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  131887. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  131888. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  131889. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  131890. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  131891. 14,13,13,14,14,15,14,15,14,
  131892. };
  131893. static float _vq_quantthresh__44c8_s_p9_1[] = {
  131894. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  131895. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  131896. 367.5, 416.5,
  131897. };
  131898. static long _vq_quantmap__44c8_s_p9_1[] = {
  131899. 17, 15, 13, 11, 9, 7, 5, 3,
  131900. 1, 0, 2, 4, 6, 8, 10, 12,
  131901. 14, 16, 18,
  131902. };
  131903. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  131904. _vq_quantthresh__44c8_s_p9_1,
  131905. _vq_quantmap__44c8_s_p9_1,
  131906. 19,
  131907. 19
  131908. };
  131909. static static_codebook _44c8_s_p9_1 = {
  131910. 2, 361,
  131911. _vq_lengthlist__44c8_s_p9_1,
  131912. 1, -518287360, 1622704128, 5, 0,
  131913. _vq_quantlist__44c8_s_p9_1,
  131914. NULL,
  131915. &_vq_auxt__44c8_s_p9_1,
  131916. NULL,
  131917. 0
  131918. };
  131919. static long _vq_quantlist__44c8_s_p9_2[] = {
  131920. 24,
  131921. 23,
  131922. 25,
  131923. 22,
  131924. 26,
  131925. 21,
  131926. 27,
  131927. 20,
  131928. 28,
  131929. 19,
  131930. 29,
  131931. 18,
  131932. 30,
  131933. 17,
  131934. 31,
  131935. 16,
  131936. 32,
  131937. 15,
  131938. 33,
  131939. 14,
  131940. 34,
  131941. 13,
  131942. 35,
  131943. 12,
  131944. 36,
  131945. 11,
  131946. 37,
  131947. 10,
  131948. 38,
  131949. 9,
  131950. 39,
  131951. 8,
  131952. 40,
  131953. 7,
  131954. 41,
  131955. 6,
  131956. 42,
  131957. 5,
  131958. 43,
  131959. 4,
  131960. 44,
  131961. 3,
  131962. 45,
  131963. 2,
  131964. 46,
  131965. 1,
  131966. 47,
  131967. 0,
  131968. 48,
  131969. };
  131970. static long _vq_lengthlist__44c8_s_p9_2[] = {
  131971. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  131972. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  131973. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  131974. 7,
  131975. };
  131976. static float _vq_quantthresh__44c8_s_p9_2[] = {
  131977. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  131978. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  131979. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131980. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131981. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  131982. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  131983. };
  131984. static long _vq_quantmap__44c8_s_p9_2[] = {
  131985. 47, 45, 43, 41, 39, 37, 35, 33,
  131986. 31, 29, 27, 25, 23, 21, 19, 17,
  131987. 15, 13, 11, 9, 7, 5, 3, 1,
  131988. 0, 2, 4, 6, 8, 10, 12, 14,
  131989. 16, 18, 20, 22, 24, 26, 28, 30,
  131990. 32, 34, 36, 38, 40, 42, 44, 46,
  131991. 48,
  131992. };
  131993. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  131994. _vq_quantthresh__44c8_s_p9_2,
  131995. _vq_quantmap__44c8_s_p9_2,
  131996. 49,
  131997. 49
  131998. };
  131999. static static_codebook _44c8_s_p9_2 = {
  132000. 1, 49,
  132001. _vq_lengthlist__44c8_s_p9_2,
  132002. 1, -526909440, 1611661312, 6, 0,
  132003. _vq_quantlist__44c8_s_p9_2,
  132004. NULL,
  132005. &_vq_auxt__44c8_s_p9_2,
  132006. NULL,
  132007. 0
  132008. };
  132009. static long _huff_lengthlist__44c8_s_short[] = {
  132010. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  132011. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  132012. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  132013. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  132014. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  132015. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  132016. 10, 9,11,14,
  132017. };
  132018. static static_codebook _huff_book__44c8_s_short = {
  132019. 2, 100,
  132020. _huff_lengthlist__44c8_s_short,
  132021. 0, 0, 0, 0, 0,
  132022. NULL,
  132023. NULL,
  132024. NULL,
  132025. NULL,
  132026. 0
  132027. };
  132028. static long _huff_lengthlist__44c9_s_long[] = {
  132029. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  132030. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  132031. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  132032. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  132033. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  132034. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  132035. 10, 9, 8, 9,
  132036. };
  132037. static static_codebook _huff_book__44c9_s_long = {
  132038. 2, 100,
  132039. _huff_lengthlist__44c9_s_long,
  132040. 0, 0, 0, 0, 0,
  132041. NULL,
  132042. NULL,
  132043. NULL,
  132044. NULL,
  132045. 0
  132046. };
  132047. static long _vq_quantlist__44c9_s_p1_0[] = {
  132048. 1,
  132049. 0,
  132050. 2,
  132051. };
  132052. static long _vq_lengthlist__44c9_s_p1_0[] = {
  132053. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  132054. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132055. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  132056. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132057. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  132058. 7,
  132059. };
  132060. static float _vq_quantthresh__44c9_s_p1_0[] = {
  132061. -0.5, 0.5,
  132062. };
  132063. static long _vq_quantmap__44c9_s_p1_0[] = {
  132064. 1, 0, 2,
  132065. };
  132066. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  132067. _vq_quantthresh__44c9_s_p1_0,
  132068. _vq_quantmap__44c9_s_p1_0,
  132069. 3,
  132070. 3
  132071. };
  132072. static static_codebook _44c9_s_p1_0 = {
  132073. 4, 81,
  132074. _vq_lengthlist__44c9_s_p1_0,
  132075. 1, -535822336, 1611661312, 2, 0,
  132076. _vq_quantlist__44c9_s_p1_0,
  132077. NULL,
  132078. &_vq_auxt__44c9_s_p1_0,
  132079. NULL,
  132080. 0
  132081. };
  132082. static long _vq_quantlist__44c9_s_p2_0[] = {
  132083. 2,
  132084. 1,
  132085. 3,
  132086. 0,
  132087. 4,
  132088. };
  132089. static long _vq_lengthlist__44c9_s_p2_0[] = {
  132090. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132091. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  132092. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  132093. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  132094. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  132095. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  132096. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  132097. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  132098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132099. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  132100. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  132101. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  132102. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  132103. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  132104. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  132105. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  132106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132107. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  132108. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  132109. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  132110. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  132111. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  132112. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  132113. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132115. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  132116. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  132117. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  132118. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  132119. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  132120. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  132121. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132126. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  132127. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  132128. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  132129. 12,
  132130. };
  132131. static float _vq_quantthresh__44c9_s_p2_0[] = {
  132132. -1.5, -0.5, 0.5, 1.5,
  132133. };
  132134. static long _vq_quantmap__44c9_s_p2_0[] = {
  132135. 3, 1, 0, 2, 4,
  132136. };
  132137. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  132138. _vq_quantthresh__44c9_s_p2_0,
  132139. _vq_quantmap__44c9_s_p2_0,
  132140. 5,
  132141. 5
  132142. };
  132143. static static_codebook _44c9_s_p2_0 = {
  132144. 4, 625,
  132145. _vq_lengthlist__44c9_s_p2_0,
  132146. 1, -533725184, 1611661312, 3, 0,
  132147. _vq_quantlist__44c9_s_p2_0,
  132148. NULL,
  132149. &_vq_auxt__44c9_s_p2_0,
  132150. NULL,
  132151. 0
  132152. };
  132153. static long _vq_quantlist__44c9_s_p3_0[] = {
  132154. 4,
  132155. 3,
  132156. 5,
  132157. 2,
  132158. 6,
  132159. 1,
  132160. 7,
  132161. 0,
  132162. 8,
  132163. };
  132164. static long _vq_lengthlist__44c9_s_p3_0[] = {
  132165. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  132166. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  132167. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  132168. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  132169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132170. 0,
  132171. };
  132172. static float _vq_quantthresh__44c9_s_p3_0[] = {
  132173. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132174. };
  132175. static long _vq_quantmap__44c9_s_p3_0[] = {
  132176. 7, 5, 3, 1, 0, 2, 4, 6,
  132177. 8,
  132178. };
  132179. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  132180. _vq_quantthresh__44c9_s_p3_0,
  132181. _vq_quantmap__44c9_s_p3_0,
  132182. 9,
  132183. 9
  132184. };
  132185. static static_codebook _44c9_s_p3_0 = {
  132186. 2, 81,
  132187. _vq_lengthlist__44c9_s_p3_0,
  132188. 1, -531628032, 1611661312, 4, 0,
  132189. _vq_quantlist__44c9_s_p3_0,
  132190. NULL,
  132191. &_vq_auxt__44c9_s_p3_0,
  132192. NULL,
  132193. 0
  132194. };
  132195. static long _vq_quantlist__44c9_s_p4_0[] = {
  132196. 8,
  132197. 7,
  132198. 9,
  132199. 6,
  132200. 10,
  132201. 5,
  132202. 11,
  132203. 4,
  132204. 12,
  132205. 3,
  132206. 13,
  132207. 2,
  132208. 14,
  132209. 1,
  132210. 15,
  132211. 0,
  132212. 16,
  132213. };
  132214. static long _vq_lengthlist__44c9_s_p4_0[] = {
  132215. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  132216. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  132217. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  132218. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  132219. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  132220. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  132221. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  132222. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132223. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  132224. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  132225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132229. 0, 0, 0, 0, 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,
  132234. };
  132235. static float _vq_quantthresh__44c9_s_p4_0[] = {
  132236. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132237. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132238. };
  132239. static long _vq_quantmap__44c9_s_p4_0[] = {
  132240. 15, 13, 11, 9, 7, 5, 3, 1,
  132241. 0, 2, 4, 6, 8, 10, 12, 14,
  132242. 16,
  132243. };
  132244. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  132245. _vq_quantthresh__44c9_s_p4_0,
  132246. _vq_quantmap__44c9_s_p4_0,
  132247. 17,
  132248. 17
  132249. };
  132250. static static_codebook _44c9_s_p4_0 = {
  132251. 2, 289,
  132252. _vq_lengthlist__44c9_s_p4_0,
  132253. 1, -529530880, 1611661312, 5, 0,
  132254. _vq_quantlist__44c9_s_p4_0,
  132255. NULL,
  132256. &_vq_auxt__44c9_s_p4_0,
  132257. NULL,
  132258. 0
  132259. };
  132260. static long _vq_quantlist__44c9_s_p5_0[] = {
  132261. 1,
  132262. 0,
  132263. 2,
  132264. };
  132265. static long _vq_lengthlist__44c9_s_p5_0[] = {
  132266. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  132267. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  132268. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  132269. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  132270. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  132271. 12,
  132272. };
  132273. static float _vq_quantthresh__44c9_s_p5_0[] = {
  132274. -5.5, 5.5,
  132275. };
  132276. static long _vq_quantmap__44c9_s_p5_0[] = {
  132277. 1, 0, 2,
  132278. };
  132279. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  132280. _vq_quantthresh__44c9_s_p5_0,
  132281. _vq_quantmap__44c9_s_p5_0,
  132282. 3,
  132283. 3
  132284. };
  132285. static static_codebook _44c9_s_p5_0 = {
  132286. 4, 81,
  132287. _vq_lengthlist__44c9_s_p5_0,
  132288. 1, -529137664, 1618345984, 2, 0,
  132289. _vq_quantlist__44c9_s_p5_0,
  132290. NULL,
  132291. &_vq_auxt__44c9_s_p5_0,
  132292. NULL,
  132293. 0
  132294. };
  132295. static long _vq_quantlist__44c9_s_p5_1[] = {
  132296. 5,
  132297. 4,
  132298. 6,
  132299. 3,
  132300. 7,
  132301. 2,
  132302. 8,
  132303. 1,
  132304. 9,
  132305. 0,
  132306. 10,
  132307. };
  132308. static long _vq_lengthlist__44c9_s_p5_1[] = {
  132309. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  132310. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  132311. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  132312. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  132313. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  132314. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  132315. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  132316. 11,11,11, 7, 7, 7, 7, 7, 7,
  132317. };
  132318. static float _vq_quantthresh__44c9_s_p5_1[] = {
  132319. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132320. 3.5, 4.5,
  132321. };
  132322. static long _vq_quantmap__44c9_s_p5_1[] = {
  132323. 9, 7, 5, 3, 1, 0, 2, 4,
  132324. 6, 8, 10,
  132325. };
  132326. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  132327. _vq_quantthresh__44c9_s_p5_1,
  132328. _vq_quantmap__44c9_s_p5_1,
  132329. 11,
  132330. 11
  132331. };
  132332. static static_codebook _44c9_s_p5_1 = {
  132333. 2, 121,
  132334. _vq_lengthlist__44c9_s_p5_1,
  132335. 1, -531365888, 1611661312, 4, 0,
  132336. _vq_quantlist__44c9_s_p5_1,
  132337. NULL,
  132338. &_vq_auxt__44c9_s_p5_1,
  132339. NULL,
  132340. 0
  132341. };
  132342. static long _vq_quantlist__44c9_s_p6_0[] = {
  132343. 6,
  132344. 5,
  132345. 7,
  132346. 4,
  132347. 8,
  132348. 3,
  132349. 9,
  132350. 2,
  132351. 10,
  132352. 1,
  132353. 11,
  132354. 0,
  132355. 12,
  132356. };
  132357. static long _vq_lengthlist__44c9_s_p6_0[] = {
  132358. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  132359. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  132360. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  132361. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  132362. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  132363. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  132364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132368. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132369. };
  132370. static float _vq_quantthresh__44c9_s_p6_0[] = {
  132371. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132372. 12.5, 17.5, 22.5, 27.5,
  132373. };
  132374. static long _vq_quantmap__44c9_s_p6_0[] = {
  132375. 11, 9, 7, 5, 3, 1, 0, 2,
  132376. 4, 6, 8, 10, 12,
  132377. };
  132378. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  132379. _vq_quantthresh__44c9_s_p6_0,
  132380. _vq_quantmap__44c9_s_p6_0,
  132381. 13,
  132382. 13
  132383. };
  132384. static static_codebook _44c9_s_p6_0 = {
  132385. 2, 169,
  132386. _vq_lengthlist__44c9_s_p6_0,
  132387. 1, -526516224, 1616117760, 4, 0,
  132388. _vq_quantlist__44c9_s_p6_0,
  132389. NULL,
  132390. &_vq_auxt__44c9_s_p6_0,
  132391. NULL,
  132392. 0
  132393. };
  132394. static long _vq_quantlist__44c9_s_p6_1[] = {
  132395. 2,
  132396. 1,
  132397. 3,
  132398. 0,
  132399. 4,
  132400. };
  132401. static long _vq_lengthlist__44c9_s_p6_1[] = {
  132402. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  132403. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  132404. };
  132405. static float _vq_quantthresh__44c9_s_p6_1[] = {
  132406. -1.5, -0.5, 0.5, 1.5,
  132407. };
  132408. static long _vq_quantmap__44c9_s_p6_1[] = {
  132409. 3, 1, 0, 2, 4,
  132410. };
  132411. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  132412. _vq_quantthresh__44c9_s_p6_1,
  132413. _vq_quantmap__44c9_s_p6_1,
  132414. 5,
  132415. 5
  132416. };
  132417. static static_codebook _44c9_s_p6_1 = {
  132418. 2, 25,
  132419. _vq_lengthlist__44c9_s_p6_1,
  132420. 1, -533725184, 1611661312, 3, 0,
  132421. _vq_quantlist__44c9_s_p6_1,
  132422. NULL,
  132423. &_vq_auxt__44c9_s_p6_1,
  132424. NULL,
  132425. 0
  132426. };
  132427. static long _vq_quantlist__44c9_s_p7_0[] = {
  132428. 6,
  132429. 5,
  132430. 7,
  132431. 4,
  132432. 8,
  132433. 3,
  132434. 9,
  132435. 2,
  132436. 10,
  132437. 1,
  132438. 11,
  132439. 0,
  132440. 12,
  132441. };
  132442. static long _vq_lengthlist__44c9_s_p7_0[] = {
  132443. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  132444. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  132445. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  132446. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  132447. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  132448. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  132449. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  132450. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  132451. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  132452. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  132453. 19,12,12,12,12,13,13,14,14,
  132454. };
  132455. static float _vq_quantthresh__44c9_s_p7_0[] = {
  132456. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132457. 27.5, 38.5, 49.5, 60.5,
  132458. };
  132459. static long _vq_quantmap__44c9_s_p7_0[] = {
  132460. 11, 9, 7, 5, 3, 1, 0, 2,
  132461. 4, 6, 8, 10, 12,
  132462. };
  132463. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  132464. _vq_quantthresh__44c9_s_p7_0,
  132465. _vq_quantmap__44c9_s_p7_0,
  132466. 13,
  132467. 13
  132468. };
  132469. static static_codebook _44c9_s_p7_0 = {
  132470. 2, 169,
  132471. _vq_lengthlist__44c9_s_p7_0,
  132472. 1, -523206656, 1618345984, 4, 0,
  132473. _vq_quantlist__44c9_s_p7_0,
  132474. NULL,
  132475. &_vq_auxt__44c9_s_p7_0,
  132476. NULL,
  132477. 0
  132478. };
  132479. static long _vq_quantlist__44c9_s_p7_1[] = {
  132480. 5,
  132481. 4,
  132482. 6,
  132483. 3,
  132484. 7,
  132485. 2,
  132486. 8,
  132487. 1,
  132488. 9,
  132489. 0,
  132490. 10,
  132491. };
  132492. static long _vq_lengthlist__44c9_s_p7_1[] = {
  132493. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  132494. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  132495. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  132496. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  132497. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  132498. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  132499. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  132500. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  132501. };
  132502. static float _vq_quantthresh__44c9_s_p7_1[] = {
  132503. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132504. 3.5, 4.5,
  132505. };
  132506. static long _vq_quantmap__44c9_s_p7_1[] = {
  132507. 9, 7, 5, 3, 1, 0, 2, 4,
  132508. 6, 8, 10,
  132509. };
  132510. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  132511. _vq_quantthresh__44c9_s_p7_1,
  132512. _vq_quantmap__44c9_s_p7_1,
  132513. 11,
  132514. 11
  132515. };
  132516. static static_codebook _44c9_s_p7_1 = {
  132517. 2, 121,
  132518. _vq_lengthlist__44c9_s_p7_1,
  132519. 1, -531365888, 1611661312, 4, 0,
  132520. _vq_quantlist__44c9_s_p7_1,
  132521. NULL,
  132522. &_vq_auxt__44c9_s_p7_1,
  132523. NULL,
  132524. 0
  132525. };
  132526. static long _vq_quantlist__44c9_s_p8_0[] = {
  132527. 7,
  132528. 6,
  132529. 8,
  132530. 5,
  132531. 9,
  132532. 4,
  132533. 10,
  132534. 3,
  132535. 11,
  132536. 2,
  132537. 12,
  132538. 1,
  132539. 13,
  132540. 0,
  132541. 14,
  132542. };
  132543. static long _vq_lengthlist__44c9_s_p8_0[] = {
  132544. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  132545. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  132546. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  132547. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  132548. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  132549. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  132550. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  132551. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  132552. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  132553. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  132554. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  132555. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  132556. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  132557. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  132558. 14,
  132559. };
  132560. static float _vq_quantthresh__44c9_s_p8_0[] = {
  132561. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  132562. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  132563. };
  132564. static long _vq_quantmap__44c9_s_p8_0[] = {
  132565. 13, 11, 9, 7, 5, 3, 1, 0,
  132566. 2, 4, 6, 8, 10, 12, 14,
  132567. };
  132568. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  132569. _vq_quantthresh__44c9_s_p8_0,
  132570. _vq_quantmap__44c9_s_p8_0,
  132571. 15,
  132572. 15
  132573. };
  132574. static static_codebook _44c9_s_p8_0 = {
  132575. 2, 225,
  132576. _vq_lengthlist__44c9_s_p8_0,
  132577. 1, -520986624, 1620377600, 4, 0,
  132578. _vq_quantlist__44c9_s_p8_0,
  132579. NULL,
  132580. &_vq_auxt__44c9_s_p8_0,
  132581. NULL,
  132582. 0
  132583. };
  132584. static long _vq_quantlist__44c9_s_p8_1[] = {
  132585. 10,
  132586. 9,
  132587. 11,
  132588. 8,
  132589. 12,
  132590. 7,
  132591. 13,
  132592. 6,
  132593. 14,
  132594. 5,
  132595. 15,
  132596. 4,
  132597. 16,
  132598. 3,
  132599. 17,
  132600. 2,
  132601. 18,
  132602. 1,
  132603. 19,
  132604. 0,
  132605. 20,
  132606. };
  132607. static long _vq_lengthlist__44c9_s_p8_1[] = {
  132608. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  132609. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  132610. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  132611. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  132612. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132613. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  132614. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  132615. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  132616. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132617. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132618. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  132619. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  132620. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132621. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132622. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  132623. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  132624. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  132625. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  132626. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  132627. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  132628. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  132629. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  132630. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  132631. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  132632. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  132633. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  132634. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  132635. 9, 9, 9,10, 9, 9, 9, 9, 9,
  132636. };
  132637. static float _vq_quantthresh__44c9_s_p8_1[] = {
  132638. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132639. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132640. 6.5, 7.5, 8.5, 9.5,
  132641. };
  132642. static long _vq_quantmap__44c9_s_p8_1[] = {
  132643. 19, 17, 15, 13, 11, 9, 7, 5,
  132644. 3, 1, 0, 2, 4, 6, 8, 10,
  132645. 12, 14, 16, 18, 20,
  132646. };
  132647. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  132648. _vq_quantthresh__44c9_s_p8_1,
  132649. _vq_quantmap__44c9_s_p8_1,
  132650. 21,
  132651. 21
  132652. };
  132653. static static_codebook _44c9_s_p8_1 = {
  132654. 2, 441,
  132655. _vq_lengthlist__44c9_s_p8_1,
  132656. 1, -529268736, 1611661312, 5, 0,
  132657. _vq_quantlist__44c9_s_p8_1,
  132658. NULL,
  132659. &_vq_auxt__44c9_s_p8_1,
  132660. NULL,
  132661. 0
  132662. };
  132663. static long _vq_quantlist__44c9_s_p9_0[] = {
  132664. 9,
  132665. 8,
  132666. 10,
  132667. 7,
  132668. 11,
  132669. 6,
  132670. 12,
  132671. 5,
  132672. 13,
  132673. 4,
  132674. 14,
  132675. 3,
  132676. 15,
  132677. 2,
  132678. 16,
  132679. 1,
  132680. 17,
  132681. 0,
  132682. 18,
  132683. };
  132684. static long _vq_lengthlist__44c9_s_p9_0[] = {
  132685. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132686. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  132687. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  132688. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  132689. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132690. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132691. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132692. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132693. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132694. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132695. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132696. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132697. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132698. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132699. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132700. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132701. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  132702. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132703. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132704. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132705. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132706. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132707. 11,11,11,11,11,11,11,11,11,
  132708. };
  132709. static float _vq_quantthresh__44c9_s_p9_0[] = {
  132710. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  132711. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  132712. 6982.5, 7913.5,
  132713. };
  132714. static long _vq_quantmap__44c9_s_p9_0[] = {
  132715. 17, 15, 13, 11, 9, 7, 5, 3,
  132716. 1, 0, 2, 4, 6, 8, 10, 12,
  132717. 14, 16, 18,
  132718. };
  132719. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  132720. _vq_quantthresh__44c9_s_p9_0,
  132721. _vq_quantmap__44c9_s_p9_0,
  132722. 19,
  132723. 19
  132724. };
  132725. static static_codebook _44c9_s_p9_0 = {
  132726. 2, 361,
  132727. _vq_lengthlist__44c9_s_p9_0,
  132728. 1, -508535424, 1631393792, 5, 0,
  132729. _vq_quantlist__44c9_s_p9_0,
  132730. NULL,
  132731. &_vq_auxt__44c9_s_p9_0,
  132732. NULL,
  132733. 0
  132734. };
  132735. static long _vq_quantlist__44c9_s_p9_1[] = {
  132736. 9,
  132737. 8,
  132738. 10,
  132739. 7,
  132740. 11,
  132741. 6,
  132742. 12,
  132743. 5,
  132744. 13,
  132745. 4,
  132746. 14,
  132747. 3,
  132748. 15,
  132749. 2,
  132750. 16,
  132751. 1,
  132752. 17,
  132753. 0,
  132754. 18,
  132755. };
  132756. static long _vq_lengthlist__44c9_s_p9_1[] = {
  132757. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  132758. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  132759. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  132760. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  132761. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  132762. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  132763. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  132764. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  132765. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  132766. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  132767. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  132768. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  132769. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  132770. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  132771. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  132772. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  132773. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  132774. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  132775. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  132776. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  132777. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  132778. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  132779. 13,13,13,14,13,14,15,15,15,
  132780. };
  132781. static float _vq_quantthresh__44c9_s_p9_1[] = {
  132782. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  132783. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  132784. 367.5, 416.5,
  132785. };
  132786. static long _vq_quantmap__44c9_s_p9_1[] = {
  132787. 17, 15, 13, 11, 9, 7, 5, 3,
  132788. 1, 0, 2, 4, 6, 8, 10, 12,
  132789. 14, 16, 18,
  132790. };
  132791. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  132792. _vq_quantthresh__44c9_s_p9_1,
  132793. _vq_quantmap__44c9_s_p9_1,
  132794. 19,
  132795. 19
  132796. };
  132797. static static_codebook _44c9_s_p9_1 = {
  132798. 2, 361,
  132799. _vq_lengthlist__44c9_s_p9_1,
  132800. 1, -518287360, 1622704128, 5, 0,
  132801. _vq_quantlist__44c9_s_p9_1,
  132802. NULL,
  132803. &_vq_auxt__44c9_s_p9_1,
  132804. NULL,
  132805. 0
  132806. };
  132807. static long _vq_quantlist__44c9_s_p9_2[] = {
  132808. 24,
  132809. 23,
  132810. 25,
  132811. 22,
  132812. 26,
  132813. 21,
  132814. 27,
  132815. 20,
  132816. 28,
  132817. 19,
  132818. 29,
  132819. 18,
  132820. 30,
  132821. 17,
  132822. 31,
  132823. 16,
  132824. 32,
  132825. 15,
  132826. 33,
  132827. 14,
  132828. 34,
  132829. 13,
  132830. 35,
  132831. 12,
  132832. 36,
  132833. 11,
  132834. 37,
  132835. 10,
  132836. 38,
  132837. 9,
  132838. 39,
  132839. 8,
  132840. 40,
  132841. 7,
  132842. 41,
  132843. 6,
  132844. 42,
  132845. 5,
  132846. 43,
  132847. 4,
  132848. 44,
  132849. 3,
  132850. 45,
  132851. 2,
  132852. 46,
  132853. 1,
  132854. 47,
  132855. 0,
  132856. 48,
  132857. };
  132858. static long _vq_lengthlist__44c9_s_p9_2[] = {
  132859. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  132860. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  132861. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132862. 7,
  132863. };
  132864. static float _vq_quantthresh__44c9_s_p9_2[] = {
  132865. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  132866. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  132867. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132868. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132869. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  132870. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  132871. };
  132872. static long _vq_quantmap__44c9_s_p9_2[] = {
  132873. 47, 45, 43, 41, 39, 37, 35, 33,
  132874. 31, 29, 27, 25, 23, 21, 19, 17,
  132875. 15, 13, 11, 9, 7, 5, 3, 1,
  132876. 0, 2, 4, 6, 8, 10, 12, 14,
  132877. 16, 18, 20, 22, 24, 26, 28, 30,
  132878. 32, 34, 36, 38, 40, 42, 44, 46,
  132879. 48,
  132880. };
  132881. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  132882. _vq_quantthresh__44c9_s_p9_2,
  132883. _vq_quantmap__44c9_s_p9_2,
  132884. 49,
  132885. 49
  132886. };
  132887. static static_codebook _44c9_s_p9_2 = {
  132888. 1, 49,
  132889. _vq_lengthlist__44c9_s_p9_2,
  132890. 1, -526909440, 1611661312, 6, 0,
  132891. _vq_quantlist__44c9_s_p9_2,
  132892. NULL,
  132893. &_vq_auxt__44c9_s_p9_2,
  132894. NULL,
  132895. 0
  132896. };
  132897. static long _huff_lengthlist__44c9_s_short[] = {
  132898. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  132899. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  132900. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  132901. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  132902. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  132903. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  132904. 9, 8,10,13,
  132905. };
  132906. static static_codebook _huff_book__44c9_s_short = {
  132907. 2, 100,
  132908. _huff_lengthlist__44c9_s_short,
  132909. 0, 0, 0, 0, 0,
  132910. NULL,
  132911. NULL,
  132912. NULL,
  132913. NULL,
  132914. 0
  132915. };
  132916. static long _huff_lengthlist__44c0_s_long[] = {
  132917. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  132918. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  132919. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  132920. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  132921. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  132922. 12,
  132923. };
  132924. static static_codebook _huff_book__44c0_s_long = {
  132925. 2, 81,
  132926. _huff_lengthlist__44c0_s_long,
  132927. 0, 0, 0, 0, 0,
  132928. NULL,
  132929. NULL,
  132930. NULL,
  132931. NULL,
  132932. 0
  132933. };
  132934. static long _vq_quantlist__44c0_s_p1_0[] = {
  132935. 1,
  132936. 0,
  132937. 2,
  132938. };
  132939. static long _vq_lengthlist__44c0_s_p1_0[] = {
  132940. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  132941. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132945. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  132946. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132950. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  132951. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  132986. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  132987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  132991. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  132992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  132996. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  132997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133031. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  133032. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133036. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  133037. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  133038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133041. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  133042. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  133043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133069. 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133077. 0, 0, 0, 0, 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, 0,
  133082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  133325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133350. 0,
  133351. };
  133352. static float _vq_quantthresh__44c0_s_p1_0[] = {
  133353. -0.5, 0.5,
  133354. };
  133355. static long _vq_quantmap__44c0_s_p1_0[] = {
  133356. 1, 0, 2,
  133357. };
  133358. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  133359. _vq_quantthresh__44c0_s_p1_0,
  133360. _vq_quantmap__44c0_s_p1_0,
  133361. 3,
  133362. 3
  133363. };
  133364. static static_codebook _44c0_s_p1_0 = {
  133365. 8, 6561,
  133366. _vq_lengthlist__44c0_s_p1_0,
  133367. 1, -535822336, 1611661312, 2, 0,
  133368. _vq_quantlist__44c0_s_p1_0,
  133369. NULL,
  133370. &_vq_auxt__44c0_s_p1_0,
  133371. NULL,
  133372. 0
  133373. };
  133374. static long _vq_quantlist__44c0_s_p2_0[] = {
  133375. 2,
  133376. 1,
  133377. 3,
  133378. 0,
  133379. 4,
  133380. };
  133381. static long _vq_lengthlist__44c0_s_p2_0[] = {
  133382. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  133384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133385. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  133387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133388. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  133389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133421. 0,
  133422. };
  133423. static float _vq_quantthresh__44c0_s_p2_0[] = {
  133424. -1.5, -0.5, 0.5, 1.5,
  133425. };
  133426. static long _vq_quantmap__44c0_s_p2_0[] = {
  133427. 3, 1, 0, 2, 4,
  133428. };
  133429. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  133430. _vq_quantthresh__44c0_s_p2_0,
  133431. _vq_quantmap__44c0_s_p2_0,
  133432. 5,
  133433. 5
  133434. };
  133435. static static_codebook _44c0_s_p2_0 = {
  133436. 4, 625,
  133437. _vq_lengthlist__44c0_s_p2_0,
  133438. 1, -533725184, 1611661312, 3, 0,
  133439. _vq_quantlist__44c0_s_p2_0,
  133440. NULL,
  133441. &_vq_auxt__44c0_s_p2_0,
  133442. NULL,
  133443. 0
  133444. };
  133445. static long _vq_quantlist__44c0_s_p3_0[] = {
  133446. 4,
  133447. 3,
  133448. 5,
  133449. 2,
  133450. 6,
  133451. 1,
  133452. 7,
  133453. 0,
  133454. 8,
  133455. };
  133456. static long _vq_lengthlist__44c0_s_p3_0[] = {
  133457. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  133458. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  133459. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  133460. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  133461. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133462. 0,
  133463. };
  133464. static float _vq_quantthresh__44c0_s_p3_0[] = {
  133465. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133466. };
  133467. static long _vq_quantmap__44c0_s_p3_0[] = {
  133468. 7, 5, 3, 1, 0, 2, 4, 6,
  133469. 8,
  133470. };
  133471. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  133472. _vq_quantthresh__44c0_s_p3_0,
  133473. _vq_quantmap__44c0_s_p3_0,
  133474. 9,
  133475. 9
  133476. };
  133477. static static_codebook _44c0_s_p3_0 = {
  133478. 2, 81,
  133479. _vq_lengthlist__44c0_s_p3_0,
  133480. 1, -531628032, 1611661312, 4, 0,
  133481. _vq_quantlist__44c0_s_p3_0,
  133482. NULL,
  133483. &_vq_auxt__44c0_s_p3_0,
  133484. NULL,
  133485. 0
  133486. };
  133487. static long _vq_quantlist__44c0_s_p4_0[] = {
  133488. 4,
  133489. 3,
  133490. 5,
  133491. 2,
  133492. 6,
  133493. 1,
  133494. 7,
  133495. 0,
  133496. 8,
  133497. };
  133498. static long _vq_lengthlist__44c0_s_p4_0[] = {
  133499. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  133500. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  133501. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  133502. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  133503. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  133504. 10,
  133505. };
  133506. static float _vq_quantthresh__44c0_s_p4_0[] = {
  133507. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133508. };
  133509. static long _vq_quantmap__44c0_s_p4_0[] = {
  133510. 7, 5, 3, 1, 0, 2, 4, 6,
  133511. 8,
  133512. };
  133513. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  133514. _vq_quantthresh__44c0_s_p4_0,
  133515. _vq_quantmap__44c0_s_p4_0,
  133516. 9,
  133517. 9
  133518. };
  133519. static static_codebook _44c0_s_p4_0 = {
  133520. 2, 81,
  133521. _vq_lengthlist__44c0_s_p4_0,
  133522. 1, -531628032, 1611661312, 4, 0,
  133523. _vq_quantlist__44c0_s_p4_0,
  133524. NULL,
  133525. &_vq_auxt__44c0_s_p4_0,
  133526. NULL,
  133527. 0
  133528. };
  133529. static long _vq_quantlist__44c0_s_p5_0[] = {
  133530. 8,
  133531. 7,
  133532. 9,
  133533. 6,
  133534. 10,
  133535. 5,
  133536. 11,
  133537. 4,
  133538. 12,
  133539. 3,
  133540. 13,
  133541. 2,
  133542. 14,
  133543. 1,
  133544. 15,
  133545. 0,
  133546. 16,
  133547. };
  133548. static long _vq_lengthlist__44c0_s_p5_0[] = {
  133549. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133550. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  133551. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  133552. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  133553. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  133554. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  133555. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  133556. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  133557. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  133558. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  133559. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  133560. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  133561. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  133562. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  133563. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  133564. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  133565. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  133566. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  133567. 14,
  133568. };
  133569. static float _vq_quantthresh__44c0_s_p5_0[] = {
  133570. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133571. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133572. };
  133573. static long _vq_quantmap__44c0_s_p5_0[] = {
  133574. 15, 13, 11, 9, 7, 5, 3, 1,
  133575. 0, 2, 4, 6, 8, 10, 12, 14,
  133576. 16,
  133577. };
  133578. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  133579. _vq_quantthresh__44c0_s_p5_0,
  133580. _vq_quantmap__44c0_s_p5_0,
  133581. 17,
  133582. 17
  133583. };
  133584. static static_codebook _44c0_s_p5_0 = {
  133585. 2, 289,
  133586. _vq_lengthlist__44c0_s_p5_0,
  133587. 1, -529530880, 1611661312, 5, 0,
  133588. _vq_quantlist__44c0_s_p5_0,
  133589. NULL,
  133590. &_vq_auxt__44c0_s_p5_0,
  133591. NULL,
  133592. 0
  133593. };
  133594. static long _vq_quantlist__44c0_s_p6_0[] = {
  133595. 1,
  133596. 0,
  133597. 2,
  133598. };
  133599. static long _vq_lengthlist__44c0_s_p6_0[] = {
  133600. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  133601. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  133602. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  133603. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  133604. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  133605. 10,
  133606. };
  133607. static float _vq_quantthresh__44c0_s_p6_0[] = {
  133608. -5.5, 5.5,
  133609. };
  133610. static long _vq_quantmap__44c0_s_p6_0[] = {
  133611. 1, 0, 2,
  133612. };
  133613. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  133614. _vq_quantthresh__44c0_s_p6_0,
  133615. _vq_quantmap__44c0_s_p6_0,
  133616. 3,
  133617. 3
  133618. };
  133619. static static_codebook _44c0_s_p6_0 = {
  133620. 4, 81,
  133621. _vq_lengthlist__44c0_s_p6_0,
  133622. 1, -529137664, 1618345984, 2, 0,
  133623. _vq_quantlist__44c0_s_p6_0,
  133624. NULL,
  133625. &_vq_auxt__44c0_s_p6_0,
  133626. NULL,
  133627. 0
  133628. };
  133629. static long _vq_quantlist__44c0_s_p6_1[] = {
  133630. 5,
  133631. 4,
  133632. 6,
  133633. 3,
  133634. 7,
  133635. 2,
  133636. 8,
  133637. 1,
  133638. 9,
  133639. 0,
  133640. 10,
  133641. };
  133642. static long _vq_lengthlist__44c0_s_p6_1[] = {
  133643. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  133644. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  133645. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  133646. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  133647. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  133648. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  133649. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  133650. 10,10,10, 8, 8, 8, 8, 8, 8,
  133651. };
  133652. static float _vq_quantthresh__44c0_s_p6_1[] = {
  133653. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133654. 3.5, 4.5,
  133655. };
  133656. static long _vq_quantmap__44c0_s_p6_1[] = {
  133657. 9, 7, 5, 3, 1, 0, 2, 4,
  133658. 6, 8, 10,
  133659. };
  133660. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  133661. _vq_quantthresh__44c0_s_p6_1,
  133662. _vq_quantmap__44c0_s_p6_1,
  133663. 11,
  133664. 11
  133665. };
  133666. static static_codebook _44c0_s_p6_1 = {
  133667. 2, 121,
  133668. _vq_lengthlist__44c0_s_p6_1,
  133669. 1, -531365888, 1611661312, 4, 0,
  133670. _vq_quantlist__44c0_s_p6_1,
  133671. NULL,
  133672. &_vq_auxt__44c0_s_p6_1,
  133673. NULL,
  133674. 0
  133675. };
  133676. static long _vq_quantlist__44c0_s_p7_0[] = {
  133677. 6,
  133678. 5,
  133679. 7,
  133680. 4,
  133681. 8,
  133682. 3,
  133683. 9,
  133684. 2,
  133685. 10,
  133686. 1,
  133687. 11,
  133688. 0,
  133689. 12,
  133690. };
  133691. static long _vq_lengthlist__44c0_s_p7_0[] = {
  133692. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  133693. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  133694. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  133695. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  133696. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  133697. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  133698. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  133699. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  133700. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  133701. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  133702. 0,12,12,11,11,12,12,13,13,
  133703. };
  133704. static float _vq_quantthresh__44c0_s_p7_0[] = {
  133705. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133706. 12.5, 17.5, 22.5, 27.5,
  133707. };
  133708. static long _vq_quantmap__44c0_s_p7_0[] = {
  133709. 11, 9, 7, 5, 3, 1, 0, 2,
  133710. 4, 6, 8, 10, 12,
  133711. };
  133712. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  133713. _vq_quantthresh__44c0_s_p7_0,
  133714. _vq_quantmap__44c0_s_p7_0,
  133715. 13,
  133716. 13
  133717. };
  133718. static static_codebook _44c0_s_p7_0 = {
  133719. 2, 169,
  133720. _vq_lengthlist__44c0_s_p7_0,
  133721. 1, -526516224, 1616117760, 4, 0,
  133722. _vq_quantlist__44c0_s_p7_0,
  133723. NULL,
  133724. &_vq_auxt__44c0_s_p7_0,
  133725. NULL,
  133726. 0
  133727. };
  133728. static long _vq_quantlist__44c0_s_p7_1[] = {
  133729. 2,
  133730. 1,
  133731. 3,
  133732. 0,
  133733. 4,
  133734. };
  133735. static long _vq_lengthlist__44c0_s_p7_1[] = {
  133736. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  133737. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  133738. };
  133739. static float _vq_quantthresh__44c0_s_p7_1[] = {
  133740. -1.5, -0.5, 0.5, 1.5,
  133741. };
  133742. static long _vq_quantmap__44c0_s_p7_1[] = {
  133743. 3, 1, 0, 2, 4,
  133744. };
  133745. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  133746. _vq_quantthresh__44c0_s_p7_1,
  133747. _vq_quantmap__44c0_s_p7_1,
  133748. 5,
  133749. 5
  133750. };
  133751. static static_codebook _44c0_s_p7_1 = {
  133752. 2, 25,
  133753. _vq_lengthlist__44c0_s_p7_1,
  133754. 1, -533725184, 1611661312, 3, 0,
  133755. _vq_quantlist__44c0_s_p7_1,
  133756. NULL,
  133757. &_vq_auxt__44c0_s_p7_1,
  133758. NULL,
  133759. 0
  133760. };
  133761. static long _vq_quantlist__44c0_s_p8_0[] = {
  133762. 2,
  133763. 1,
  133764. 3,
  133765. 0,
  133766. 4,
  133767. };
  133768. static long _vq_lengthlist__44c0_s_p8_0[] = {
  133769. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  133770. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133771. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133772. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133773. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133774. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133775. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133776. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  133777. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133778. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133779. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133780. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133781. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  133782. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133783. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133784. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  133785. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133786. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133787. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133788. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133789. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133790. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133791. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133792. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133793. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133794. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133795. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133796. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133797. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133798. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133799. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133800. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133801. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133802. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133803. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133804. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133805. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133806. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133807. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133808. 11,
  133809. };
  133810. static float _vq_quantthresh__44c0_s_p8_0[] = {
  133811. -331.5, -110.5, 110.5, 331.5,
  133812. };
  133813. static long _vq_quantmap__44c0_s_p8_0[] = {
  133814. 3, 1, 0, 2, 4,
  133815. };
  133816. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  133817. _vq_quantthresh__44c0_s_p8_0,
  133818. _vq_quantmap__44c0_s_p8_0,
  133819. 5,
  133820. 5
  133821. };
  133822. static static_codebook _44c0_s_p8_0 = {
  133823. 4, 625,
  133824. _vq_lengthlist__44c0_s_p8_0,
  133825. 1, -518283264, 1627103232, 3, 0,
  133826. _vq_quantlist__44c0_s_p8_0,
  133827. NULL,
  133828. &_vq_auxt__44c0_s_p8_0,
  133829. NULL,
  133830. 0
  133831. };
  133832. static long _vq_quantlist__44c0_s_p8_1[] = {
  133833. 6,
  133834. 5,
  133835. 7,
  133836. 4,
  133837. 8,
  133838. 3,
  133839. 9,
  133840. 2,
  133841. 10,
  133842. 1,
  133843. 11,
  133844. 0,
  133845. 12,
  133846. };
  133847. static long _vq_lengthlist__44c0_s_p8_1[] = {
  133848. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  133849. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  133850. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  133851. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  133852. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  133853. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  133854. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  133855. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  133856. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  133857. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  133858. 16,13,13,12,12,14,14,15,13,
  133859. };
  133860. static float _vq_quantthresh__44c0_s_p8_1[] = {
  133861. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  133862. 42.5, 59.5, 76.5, 93.5,
  133863. };
  133864. static long _vq_quantmap__44c0_s_p8_1[] = {
  133865. 11, 9, 7, 5, 3, 1, 0, 2,
  133866. 4, 6, 8, 10, 12,
  133867. };
  133868. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  133869. _vq_quantthresh__44c0_s_p8_1,
  133870. _vq_quantmap__44c0_s_p8_1,
  133871. 13,
  133872. 13
  133873. };
  133874. static static_codebook _44c0_s_p8_1 = {
  133875. 2, 169,
  133876. _vq_lengthlist__44c0_s_p8_1,
  133877. 1, -522616832, 1620115456, 4, 0,
  133878. _vq_quantlist__44c0_s_p8_1,
  133879. NULL,
  133880. &_vq_auxt__44c0_s_p8_1,
  133881. NULL,
  133882. 0
  133883. };
  133884. static long _vq_quantlist__44c0_s_p8_2[] = {
  133885. 8,
  133886. 7,
  133887. 9,
  133888. 6,
  133889. 10,
  133890. 5,
  133891. 11,
  133892. 4,
  133893. 12,
  133894. 3,
  133895. 13,
  133896. 2,
  133897. 14,
  133898. 1,
  133899. 15,
  133900. 0,
  133901. 16,
  133902. };
  133903. static long _vq_lengthlist__44c0_s_p8_2[] = {
  133904. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  133905. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  133906. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  133907. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  133908. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  133909. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  133910. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  133911. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  133912. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  133913. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  133914. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  133915. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  133916. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  133917. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  133918. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  133919. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  133920. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  133921. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  133922. 10,
  133923. };
  133924. static float _vq_quantthresh__44c0_s_p8_2[] = {
  133925. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133926. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133927. };
  133928. static long _vq_quantmap__44c0_s_p8_2[] = {
  133929. 15, 13, 11, 9, 7, 5, 3, 1,
  133930. 0, 2, 4, 6, 8, 10, 12, 14,
  133931. 16,
  133932. };
  133933. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  133934. _vq_quantthresh__44c0_s_p8_2,
  133935. _vq_quantmap__44c0_s_p8_2,
  133936. 17,
  133937. 17
  133938. };
  133939. static static_codebook _44c0_s_p8_2 = {
  133940. 2, 289,
  133941. _vq_lengthlist__44c0_s_p8_2,
  133942. 1, -529530880, 1611661312, 5, 0,
  133943. _vq_quantlist__44c0_s_p8_2,
  133944. NULL,
  133945. &_vq_auxt__44c0_s_p8_2,
  133946. NULL,
  133947. 0
  133948. };
  133949. static long _huff_lengthlist__44c0_s_short[] = {
  133950. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  133951. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  133952. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  133953. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  133954. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  133955. 12,
  133956. };
  133957. static static_codebook _huff_book__44c0_s_short = {
  133958. 2, 81,
  133959. _huff_lengthlist__44c0_s_short,
  133960. 0, 0, 0, 0, 0,
  133961. NULL,
  133962. NULL,
  133963. NULL,
  133964. NULL,
  133965. 0
  133966. };
  133967. static long _huff_lengthlist__44c0_sm_long[] = {
  133968. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  133969. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  133970. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  133971. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  133972. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  133973. 13,
  133974. };
  133975. static static_codebook _huff_book__44c0_sm_long = {
  133976. 2, 81,
  133977. _huff_lengthlist__44c0_sm_long,
  133978. 0, 0, 0, 0, 0,
  133979. NULL,
  133980. NULL,
  133981. NULL,
  133982. NULL,
  133983. 0
  133984. };
  133985. static long _vq_quantlist__44c0_sm_p1_0[] = {
  133986. 1,
  133987. 0,
  133988. 2,
  133989. };
  133990. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  133991. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  133992. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133996. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  133997. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134001. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  134002. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  134037. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  134038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  134042. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  134043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  134047. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  134048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134082. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  134083. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134087. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  134088. 0, 0, 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  134089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134092. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  134093. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  134094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  134206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134401. 0,
  134402. };
  134403. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  134404. -0.5, 0.5,
  134405. };
  134406. static long _vq_quantmap__44c0_sm_p1_0[] = {
  134407. 1, 0, 2,
  134408. };
  134409. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  134410. _vq_quantthresh__44c0_sm_p1_0,
  134411. _vq_quantmap__44c0_sm_p1_0,
  134412. 3,
  134413. 3
  134414. };
  134415. static static_codebook _44c0_sm_p1_0 = {
  134416. 8, 6561,
  134417. _vq_lengthlist__44c0_sm_p1_0,
  134418. 1, -535822336, 1611661312, 2, 0,
  134419. _vq_quantlist__44c0_sm_p1_0,
  134420. NULL,
  134421. &_vq_auxt__44c0_sm_p1_0,
  134422. NULL,
  134423. 0
  134424. };
  134425. static long _vq_quantlist__44c0_sm_p2_0[] = {
  134426. 2,
  134427. 1,
  134428. 3,
  134429. 0,
  134430. 4,
  134431. };
  134432. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  134433. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  134435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134436. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  134438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134439. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  134440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134472. 0,
  134473. };
  134474. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  134475. -1.5, -0.5, 0.5, 1.5,
  134476. };
  134477. static long _vq_quantmap__44c0_sm_p2_0[] = {
  134478. 3, 1, 0, 2, 4,
  134479. };
  134480. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  134481. _vq_quantthresh__44c0_sm_p2_0,
  134482. _vq_quantmap__44c0_sm_p2_0,
  134483. 5,
  134484. 5
  134485. };
  134486. static static_codebook _44c0_sm_p2_0 = {
  134487. 4, 625,
  134488. _vq_lengthlist__44c0_sm_p2_0,
  134489. 1, -533725184, 1611661312, 3, 0,
  134490. _vq_quantlist__44c0_sm_p2_0,
  134491. NULL,
  134492. &_vq_auxt__44c0_sm_p2_0,
  134493. NULL,
  134494. 0
  134495. };
  134496. static long _vq_quantlist__44c0_sm_p3_0[] = {
  134497. 4,
  134498. 3,
  134499. 5,
  134500. 2,
  134501. 6,
  134502. 1,
  134503. 7,
  134504. 0,
  134505. 8,
  134506. };
  134507. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  134508. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  134509. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  134510. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  134511. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  134512. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134513. 0,
  134514. };
  134515. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  134516. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134517. };
  134518. static long _vq_quantmap__44c0_sm_p3_0[] = {
  134519. 7, 5, 3, 1, 0, 2, 4, 6,
  134520. 8,
  134521. };
  134522. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  134523. _vq_quantthresh__44c0_sm_p3_0,
  134524. _vq_quantmap__44c0_sm_p3_0,
  134525. 9,
  134526. 9
  134527. };
  134528. static static_codebook _44c0_sm_p3_0 = {
  134529. 2, 81,
  134530. _vq_lengthlist__44c0_sm_p3_0,
  134531. 1, -531628032, 1611661312, 4, 0,
  134532. _vq_quantlist__44c0_sm_p3_0,
  134533. NULL,
  134534. &_vq_auxt__44c0_sm_p3_0,
  134535. NULL,
  134536. 0
  134537. };
  134538. static long _vq_quantlist__44c0_sm_p4_0[] = {
  134539. 4,
  134540. 3,
  134541. 5,
  134542. 2,
  134543. 6,
  134544. 1,
  134545. 7,
  134546. 0,
  134547. 8,
  134548. };
  134549. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  134550. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  134551. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  134552. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  134553. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  134554. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  134555. 11,
  134556. };
  134557. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  134558. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134559. };
  134560. static long _vq_quantmap__44c0_sm_p4_0[] = {
  134561. 7, 5, 3, 1, 0, 2, 4, 6,
  134562. 8,
  134563. };
  134564. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  134565. _vq_quantthresh__44c0_sm_p4_0,
  134566. _vq_quantmap__44c0_sm_p4_0,
  134567. 9,
  134568. 9
  134569. };
  134570. static static_codebook _44c0_sm_p4_0 = {
  134571. 2, 81,
  134572. _vq_lengthlist__44c0_sm_p4_0,
  134573. 1, -531628032, 1611661312, 4, 0,
  134574. _vq_quantlist__44c0_sm_p4_0,
  134575. NULL,
  134576. &_vq_auxt__44c0_sm_p4_0,
  134577. NULL,
  134578. 0
  134579. };
  134580. static long _vq_quantlist__44c0_sm_p5_0[] = {
  134581. 8,
  134582. 7,
  134583. 9,
  134584. 6,
  134585. 10,
  134586. 5,
  134587. 11,
  134588. 4,
  134589. 12,
  134590. 3,
  134591. 13,
  134592. 2,
  134593. 14,
  134594. 1,
  134595. 15,
  134596. 0,
  134597. 16,
  134598. };
  134599. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  134600. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  134601. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  134602. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  134603. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  134604. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  134605. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  134606. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  134607. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  134608. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  134609. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  134610. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  134611. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  134612. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  134613. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  134614. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  134615. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  134616. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  134617. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  134618. 14,
  134619. };
  134620. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  134621. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134622. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134623. };
  134624. static long _vq_quantmap__44c0_sm_p5_0[] = {
  134625. 15, 13, 11, 9, 7, 5, 3, 1,
  134626. 0, 2, 4, 6, 8, 10, 12, 14,
  134627. 16,
  134628. };
  134629. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  134630. _vq_quantthresh__44c0_sm_p5_0,
  134631. _vq_quantmap__44c0_sm_p5_0,
  134632. 17,
  134633. 17
  134634. };
  134635. static static_codebook _44c0_sm_p5_0 = {
  134636. 2, 289,
  134637. _vq_lengthlist__44c0_sm_p5_0,
  134638. 1, -529530880, 1611661312, 5, 0,
  134639. _vq_quantlist__44c0_sm_p5_0,
  134640. NULL,
  134641. &_vq_auxt__44c0_sm_p5_0,
  134642. NULL,
  134643. 0
  134644. };
  134645. static long _vq_quantlist__44c0_sm_p6_0[] = {
  134646. 1,
  134647. 0,
  134648. 2,
  134649. };
  134650. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  134651. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  134652. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  134653. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  134654. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  134655. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  134656. 11,
  134657. };
  134658. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  134659. -5.5, 5.5,
  134660. };
  134661. static long _vq_quantmap__44c0_sm_p6_0[] = {
  134662. 1, 0, 2,
  134663. };
  134664. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  134665. _vq_quantthresh__44c0_sm_p6_0,
  134666. _vq_quantmap__44c0_sm_p6_0,
  134667. 3,
  134668. 3
  134669. };
  134670. static static_codebook _44c0_sm_p6_0 = {
  134671. 4, 81,
  134672. _vq_lengthlist__44c0_sm_p6_0,
  134673. 1, -529137664, 1618345984, 2, 0,
  134674. _vq_quantlist__44c0_sm_p6_0,
  134675. NULL,
  134676. &_vq_auxt__44c0_sm_p6_0,
  134677. NULL,
  134678. 0
  134679. };
  134680. static long _vq_quantlist__44c0_sm_p6_1[] = {
  134681. 5,
  134682. 4,
  134683. 6,
  134684. 3,
  134685. 7,
  134686. 2,
  134687. 8,
  134688. 1,
  134689. 9,
  134690. 0,
  134691. 10,
  134692. };
  134693. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  134694. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  134695. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  134696. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  134697. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  134698. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  134699. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  134700. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  134701. 10,10,10, 8, 8, 8, 8, 8, 8,
  134702. };
  134703. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  134704. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134705. 3.5, 4.5,
  134706. };
  134707. static long _vq_quantmap__44c0_sm_p6_1[] = {
  134708. 9, 7, 5, 3, 1, 0, 2, 4,
  134709. 6, 8, 10,
  134710. };
  134711. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  134712. _vq_quantthresh__44c0_sm_p6_1,
  134713. _vq_quantmap__44c0_sm_p6_1,
  134714. 11,
  134715. 11
  134716. };
  134717. static static_codebook _44c0_sm_p6_1 = {
  134718. 2, 121,
  134719. _vq_lengthlist__44c0_sm_p6_1,
  134720. 1, -531365888, 1611661312, 4, 0,
  134721. _vq_quantlist__44c0_sm_p6_1,
  134722. NULL,
  134723. &_vq_auxt__44c0_sm_p6_1,
  134724. NULL,
  134725. 0
  134726. };
  134727. static long _vq_quantlist__44c0_sm_p7_0[] = {
  134728. 6,
  134729. 5,
  134730. 7,
  134731. 4,
  134732. 8,
  134733. 3,
  134734. 9,
  134735. 2,
  134736. 10,
  134737. 1,
  134738. 11,
  134739. 0,
  134740. 12,
  134741. };
  134742. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  134743. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  134744. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  134745. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  134746. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  134747. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  134748. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  134749. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  134750. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  134751. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  134752. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  134753. 0,12,12,11,11,13,12,14,14,
  134754. };
  134755. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  134756. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134757. 12.5, 17.5, 22.5, 27.5,
  134758. };
  134759. static long _vq_quantmap__44c0_sm_p7_0[] = {
  134760. 11, 9, 7, 5, 3, 1, 0, 2,
  134761. 4, 6, 8, 10, 12,
  134762. };
  134763. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  134764. _vq_quantthresh__44c0_sm_p7_0,
  134765. _vq_quantmap__44c0_sm_p7_0,
  134766. 13,
  134767. 13
  134768. };
  134769. static static_codebook _44c0_sm_p7_0 = {
  134770. 2, 169,
  134771. _vq_lengthlist__44c0_sm_p7_0,
  134772. 1, -526516224, 1616117760, 4, 0,
  134773. _vq_quantlist__44c0_sm_p7_0,
  134774. NULL,
  134775. &_vq_auxt__44c0_sm_p7_0,
  134776. NULL,
  134777. 0
  134778. };
  134779. static long _vq_quantlist__44c0_sm_p7_1[] = {
  134780. 2,
  134781. 1,
  134782. 3,
  134783. 0,
  134784. 4,
  134785. };
  134786. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  134787. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  134788. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  134789. };
  134790. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  134791. -1.5, -0.5, 0.5, 1.5,
  134792. };
  134793. static long _vq_quantmap__44c0_sm_p7_1[] = {
  134794. 3, 1, 0, 2, 4,
  134795. };
  134796. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  134797. _vq_quantthresh__44c0_sm_p7_1,
  134798. _vq_quantmap__44c0_sm_p7_1,
  134799. 5,
  134800. 5
  134801. };
  134802. static static_codebook _44c0_sm_p7_1 = {
  134803. 2, 25,
  134804. _vq_lengthlist__44c0_sm_p7_1,
  134805. 1, -533725184, 1611661312, 3, 0,
  134806. _vq_quantlist__44c0_sm_p7_1,
  134807. NULL,
  134808. &_vq_auxt__44c0_sm_p7_1,
  134809. NULL,
  134810. 0
  134811. };
  134812. static long _vq_quantlist__44c0_sm_p8_0[] = {
  134813. 4,
  134814. 3,
  134815. 5,
  134816. 2,
  134817. 6,
  134818. 1,
  134819. 7,
  134820. 0,
  134821. 8,
  134822. };
  134823. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  134824. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  134825. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  134826. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134827. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134828. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134829. 12,
  134830. };
  134831. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  134832. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  134833. };
  134834. static long _vq_quantmap__44c0_sm_p8_0[] = {
  134835. 7, 5, 3, 1, 0, 2, 4, 6,
  134836. 8,
  134837. };
  134838. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  134839. _vq_quantthresh__44c0_sm_p8_0,
  134840. _vq_quantmap__44c0_sm_p8_0,
  134841. 9,
  134842. 9
  134843. };
  134844. static static_codebook _44c0_sm_p8_0 = {
  134845. 2, 81,
  134846. _vq_lengthlist__44c0_sm_p8_0,
  134847. 1, -516186112, 1627103232, 4, 0,
  134848. _vq_quantlist__44c0_sm_p8_0,
  134849. NULL,
  134850. &_vq_auxt__44c0_sm_p8_0,
  134851. NULL,
  134852. 0
  134853. };
  134854. static long _vq_quantlist__44c0_sm_p8_1[] = {
  134855. 6,
  134856. 5,
  134857. 7,
  134858. 4,
  134859. 8,
  134860. 3,
  134861. 9,
  134862. 2,
  134863. 10,
  134864. 1,
  134865. 11,
  134866. 0,
  134867. 12,
  134868. };
  134869. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  134870. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  134871. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  134872. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  134873. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  134874. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  134875. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  134876. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  134877. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  134878. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  134879. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  134880. 20,13,13,12,12,16,13,15,13,
  134881. };
  134882. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  134883. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  134884. 42.5, 59.5, 76.5, 93.5,
  134885. };
  134886. static long _vq_quantmap__44c0_sm_p8_1[] = {
  134887. 11, 9, 7, 5, 3, 1, 0, 2,
  134888. 4, 6, 8, 10, 12,
  134889. };
  134890. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  134891. _vq_quantthresh__44c0_sm_p8_1,
  134892. _vq_quantmap__44c0_sm_p8_1,
  134893. 13,
  134894. 13
  134895. };
  134896. static static_codebook _44c0_sm_p8_1 = {
  134897. 2, 169,
  134898. _vq_lengthlist__44c0_sm_p8_1,
  134899. 1, -522616832, 1620115456, 4, 0,
  134900. _vq_quantlist__44c0_sm_p8_1,
  134901. NULL,
  134902. &_vq_auxt__44c0_sm_p8_1,
  134903. NULL,
  134904. 0
  134905. };
  134906. static long _vq_quantlist__44c0_sm_p8_2[] = {
  134907. 8,
  134908. 7,
  134909. 9,
  134910. 6,
  134911. 10,
  134912. 5,
  134913. 11,
  134914. 4,
  134915. 12,
  134916. 3,
  134917. 13,
  134918. 2,
  134919. 14,
  134920. 1,
  134921. 15,
  134922. 0,
  134923. 16,
  134924. };
  134925. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  134926. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  134927. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  134928. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  134929. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  134930. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  134931. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  134932. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  134933. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  134934. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  134935. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  134936. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  134937. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  134938. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  134939. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  134940. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  134941. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  134942. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  134943. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  134944. 9,
  134945. };
  134946. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  134947. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134948. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134949. };
  134950. static long _vq_quantmap__44c0_sm_p8_2[] = {
  134951. 15, 13, 11, 9, 7, 5, 3, 1,
  134952. 0, 2, 4, 6, 8, 10, 12, 14,
  134953. 16,
  134954. };
  134955. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  134956. _vq_quantthresh__44c0_sm_p8_2,
  134957. _vq_quantmap__44c0_sm_p8_2,
  134958. 17,
  134959. 17
  134960. };
  134961. static static_codebook _44c0_sm_p8_2 = {
  134962. 2, 289,
  134963. _vq_lengthlist__44c0_sm_p8_2,
  134964. 1, -529530880, 1611661312, 5, 0,
  134965. _vq_quantlist__44c0_sm_p8_2,
  134966. NULL,
  134967. &_vq_auxt__44c0_sm_p8_2,
  134968. NULL,
  134969. 0
  134970. };
  134971. static long _huff_lengthlist__44c0_sm_short[] = {
  134972. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  134973. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  134974. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  134975. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  134976. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  134977. 12,
  134978. };
  134979. static static_codebook _huff_book__44c0_sm_short = {
  134980. 2, 81,
  134981. _huff_lengthlist__44c0_sm_short,
  134982. 0, 0, 0, 0, 0,
  134983. NULL,
  134984. NULL,
  134985. NULL,
  134986. NULL,
  134987. 0
  134988. };
  134989. static long _huff_lengthlist__44c1_s_long[] = {
  134990. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  134991. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  134992. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  134993. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  134994. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  134995. 11,
  134996. };
  134997. static static_codebook _huff_book__44c1_s_long = {
  134998. 2, 81,
  134999. _huff_lengthlist__44c1_s_long,
  135000. 0, 0, 0, 0, 0,
  135001. NULL,
  135002. NULL,
  135003. NULL,
  135004. NULL,
  135005. 0
  135006. };
  135007. static long _vq_quantlist__44c1_s_p1_0[] = {
  135008. 1,
  135009. 0,
  135010. 2,
  135011. };
  135012. static long _vq_lengthlist__44c1_s_p1_0[] = {
  135013. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  135014. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  135019. 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  135024. 0, 0, 0, 0, 7, 8, 8, 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, 4, 7, 7, 0, 0, 0, 0,
  135059. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  135064. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  135069. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  135105. 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  135110. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  135115. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135423. 0,
  135424. };
  135425. static float _vq_quantthresh__44c1_s_p1_0[] = {
  135426. -0.5, 0.5,
  135427. };
  135428. static long _vq_quantmap__44c1_s_p1_0[] = {
  135429. 1, 0, 2,
  135430. };
  135431. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  135432. _vq_quantthresh__44c1_s_p1_0,
  135433. _vq_quantmap__44c1_s_p1_0,
  135434. 3,
  135435. 3
  135436. };
  135437. static static_codebook _44c1_s_p1_0 = {
  135438. 8, 6561,
  135439. _vq_lengthlist__44c1_s_p1_0,
  135440. 1, -535822336, 1611661312, 2, 0,
  135441. _vq_quantlist__44c1_s_p1_0,
  135442. NULL,
  135443. &_vq_auxt__44c1_s_p1_0,
  135444. NULL,
  135445. 0
  135446. };
  135447. static long _vq_quantlist__44c1_s_p2_0[] = {
  135448. 2,
  135449. 1,
  135450. 3,
  135451. 0,
  135452. 4,
  135453. };
  135454. static long _vq_lengthlist__44c1_s_p2_0[] = {
  135455. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  135457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135458. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  135460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135461. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  135462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135494. 0,
  135495. };
  135496. static float _vq_quantthresh__44c1_s_p2_0[] = {
  135497. -1.5, -0.5, 0.5, 1.5,
  135498. };
  135499. static long _vq_quantmap__44c1_s_p2_0[] = {
  135500. 3, 1, 0, 2, 4,
  135501. };
  135502. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  135503. _vq_quantthresh__44c1_s_p2_0,
  135504. _vq_quantmap__44c1_s_p2_0,
  135505. 5,
  135506. 5
  135507. };
  135508. static static_codebook _44c1_s_p2_0 = {
  135509. 4, 625,
  135510. _vq_lengthlist__44c1_s_p2_0,
  135511. 1, -533725184, 1611661312, 3, 0,
  135512. _vq_quantlist__44c1_s_p2_0,
  135513. NULL,
  135514. &_vq_auxt__44c1_s_p2_0,
  135515. NULL,
  135516. 0
  135517. };
  135518. static long _vq_quantlist__44c1_s_p3_0[] = {
  135519. 4,
  135520. 3,
  135521. 5,
  135522. 2,
  135523. 6,
  135524. 1,
  135525. 7,
  135526. 0,
  135527. 8,
  135528. };
  135529. static long _vq_lengthlist__44c1_s_p3_0[] = {
  135530. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  135531. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  135532. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  135533. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  135534. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135535. 0,
  135536. };
  135537. static float _vq_quantthresh__44c1_s_p3_0[] = {
  135538. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135539. };
  135540. static long _vq_quantmap__44c1_s_p3_0[] = {
  135541. 7, 5, 3, 1, 0, 2, 4, 6,
  135542. 8,
  135543. };
  135544. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  135545. _vq_quantthresh__44c1_s_p3_0,
  135546. _vq_quantmap__44c1_s_p3_0,
  135547. 9,
  135548. 9
  135549. };
  135550. static static_codebook _44c1_s_p3_0 = {
  135551. 2, 81,
  135552. _vq_lengthlist__44c1_s_p3_0,
  135553. 1, -531628032, 1611661312, 4, 0,
  135554. _vq_quantlist__44c1_s_p3_0,
  135555. NULL,
  135556. &_vq_auxt__44c1_s_p3_0,
  135557. NULL,
  135558. 0
  135559. };
  135560. static long _vq_quantlist__44c1_s_p4_0[] = {
  135561. 4,
  135562. 3,
  135563. 5,
  135564. 2,
  135565. 6,
  135566. 1,
  135567. 7,
  135568. 0,
  135569. 8,
  135570. };
  135571. static long _vq_lengthlist__44c1_s_p4_0[] = {
  135572. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  135573. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  135574. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  135575. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  135576. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  135577. 11,
  135578. };
  135579. static float _vq_quantthresh__44c1_s_p4_0[] = {
  135580. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135581. };
  135582. static long _vq_quantmap__44c1_s_p4_0[] = {
  135583. 7, 5, 3, 1, 0, 2, 4, 6,
  135584. 8,
  135585. };
  135586. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  135587. _vq_quantthresh__44c1_s_p4_0,
  135588. _vq_quantmap__44c1_s_p4_0,
  135589. 9,
  135590. 9
  135591. };
  135592. static static_codebook _44c1_s_p4_0 = {
  135593. 2, 81,
  135594. _vq_lengthlist__44c1_s_p4_0,
  135595. 1, -531628032, 1611661312, 4, 0,
  135596. _vq_quantlist__44c1_s_p4_0,
  135597. NULL,
  135598. &_vq_auxt__44c1_s_p4_0,
  135599. NULL,
  135600. 0
  135601. };
  135602. static long _vq_quantlist__44c1_s_p5_0[] = {
  135603. 8,
  135604. 7,
  135605. 9,
  135606. 6,
  135607. 10,
  135608. 5,
  135609. 11,
  135610. 4,
  135611. 12,
  135612. 3,
  135613. 13,
  135614. 2,
  135615. 14,
  135616. 1,
  135617. 15,
  135618. 0,
  135619. 16,
  135620. };
  135621. static long _vq_lengthlist__44c1_s_p5_0[] = {
  135622. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  135623. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  135624. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  135625. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  135626. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  135627. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  135628. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  135629. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  135630. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  135631. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  135632. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  135633. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  135634. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  135635. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  135636. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  135637. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  135638. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  135639. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  135640. 14,
  135641. };
  135642. static float _vq_quantthresh__44c1_s_p5_0[] = {
  135643. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135644. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135645. };
  135646. static long _vq_quantmap__44c1_s_p5_0[] = {
  135647. 15, 13, 11, 9, 7, 5, 3, 1,
  135648. 0, 2, 4, 6, 8, 10, 12, 14,
  135649. 16,
  135650. };
  135651. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  135652. _vq_quantthresh__44c1_s_p5_0,
  135653. _vq_quantmap__44c1_s_p5_0,
  135654. 17,
  135655. 17
  135656. };
  135657. static static_codebook _44c1_s_p5_0 = {
  135658. 2, 289,
  135659. _vq_lengthlist__44c1_s_p5_0,
  135660. 1, -529530880, 1611661312, 5, 0,
  135661. _vq_quantlist__44c1_s_p5_0,
  135662. NULL,
  135663. &_vq_auxt__44c1_s_p5_0,
  135664. NULL,
  135665. 0
  135666. };
  135667. static long _vq_quantlist__44c1_s_p6_0[] = {
  135668. 1,
  135669. 0,
  135670. 2,
  135671. };
  135672. static long _vq_lengthlist__44c1_s_p6_0[] = {
  135673. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  135674. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  135675. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  135676. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  135677. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  135678. 11,
  135679. };
  135680. static float _vq_quantthresh__44c1_s_p6_0[] = {
  135681. -5.5, 5.5,
  135682. };
  135683. static long _vq_quantmap__44c1_s_p6_0[] = {
  135684. 1, 0, 2,
  135685. };
  135686. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  135687. _vq_quantthresh__44c1_s_p6_0,
  135688. _vq_quantmap__44c1_s_p6_0,
  135689. 3,
  135690. 3
  135691. };
  135692. static static_codebook _44c1_s_p6_0 = {
  135693. 4, 81,
  135694. _vq_lengthlist__44c1_s_p6_0,
  135695. 1, -529137664, 1618345984, 2, 0,
  135696. _vq_quantlist__44c1_s_p6_0,
  135697. NULL,
  135698. &_vq_auxt__44c1_s_p6_0,
  135699. NULL,
  135700. 0
  135701. };
  135702. static long _vq_quantlist__44c1_s_p6_1[] = {
  135703. 5,
  135704. 4,
  135705. 6,
  135706. 3,
  135707. 7,
  135708. 2,
  135709. 8,
  135710. 1,
  135711. 9,
  135712. 0,
  135713. 10,
  135714. };
  135715. static long _vq_lengthlist__44c1_s_p6_1[] = {
  135716. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  135717. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  135718. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  135719. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  135720. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  135721. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  135722. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  135723. 10,10,10, 8, 8, 8, 8, 8, 8,
  135724. };
  135725. static float _vq_quantthresh__44c1_s_p6_1[] = {
  135726. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135727. 3.5, 4.5,
  135728. };
  135729. static long _vq_quantmap__44c1_s_p6_1[] = {
  135730. 9, 7, 5, 3, 1, 0, 2, 4,
  135731. 6, 8, 10,
  135732. };
  135733. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  135734. _vq_quantthresh__44c1_s_p6_1,
  135735. _vq_quantmap__44c1_s_p6_1,
  135736. 11,
  135737. 11
  135738. };
  135739. static static_codebook _44c1_s_p6_1 = {
  135740. 2, 121,
  135741. _vq_lengthlist__44c1_s_p6_1,
  135742. 1, -531365888, 1611661312, 4, 0,
  135743. _vq_quantlist__44c1_s_p6_1,
  135744. NULL,
  135745. &_vq_auxt__44c1_s_p6_1,
  135746. NULL,
  135747. 0
  135748. };
  135749. static long _vq_quantlist__44c1_s_p7_0[] = {
  135750. 6,
  135751. 5,
  135752. 7,
  135753. 4,
  135754. 8,
  135755. 3,
  135756. 9,
  135757. 2,
  135758. 10,
  135759. 1,
  135760. 11,
  135761. 0,
  135762. 12,
  135763. };
  135764. static long _vq_lengthlist__44c1_s_p7_0[] = {
  135765. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  135766. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  135767. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  135768. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  135769. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  135770. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  135771. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  135772. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  135773. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  135774. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  135775. 0,12,11,11,11,13,10,14,13,
  135776. };
  135777. static float _vq_quantthresh__44c1_s_p7_0[] = {
  135778. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135779. 12.5, 17.5, 22.5, 27.5,
  135780. };
  135781. static long _vq_quantmap__44c1_s_p7_0[] = {
  135782. 11, 9, 7, 5, 3, 1, 0, 2,
  135783. 4, 6, 8, 10, 12,
  135784. };
  135785. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  135786. _vq_quantthresh__44c1_s_p7_0,
  135787. _vq_quantmap__44c1_s_p7_0,
  135788. 13,
  135789. 13
  135790. };
  135791. static static_codebook _44c1_s_p7_0 = {
  135792. 2, 169,
  135793. _vq_lengthlist__44c1_s_p7_0,
  135794. 1, -526516224, 1616117760, 4, 0,
  135795. _vq_quantlist__44c1_s_p7_0,
  135796. NULL,
  135797. &_vq_auxt__44c1_s_p7_0,
  135798. NULL,
  135799. 0
  135800. };
  135801. static long _vq_quantlist__44c1_s_p7_1[] = {
  135802. 2,
  135803. 1,
  135804. 3,
  135805. 0,
  135806. 4,
  135807. };
  135808. static long _vq_lengthlist__44c1_s_p7_1[] = {
  135809. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  135810. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  135811. };
  135812. static float _vq_quantthresh__44c1_s_p7_1[] = {
  135813. -1.5, -0.5, 0.5, 1.5,
  135814. };
  135815. static long _vq_quantmap__44c1_s_p7_1[] = {
  135816. 3, 1, 0, 2, 4,
  135817. };
  135818. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  135819. _vq_quantthresh__44c1_s_p7_1,
  135820. _vq_quantmap__44c1_s_p7_1,
  135821. 5,
  135822. 5
  135823. };
  135824. static static_codebook _44c1_s_p7_1 = {
  135825. 2, 25,
  135826. _vq_lengthlist__44c1_s_p7_1,
  135827. 1, -533725184, 1611661312, 3, 0,
  135828. _vq_quantlist__44c1_s_p7_1,
  135829. NULL,
  135830. &_vq_auxt__44c1_s_p7_1,
  135831. NULL,
  135832. 0
  135833. };
  135834. static long _vq_quantlist__44c1_s_p8_0[] = {
  135835. 6,
  135836. 5,
  135837. 7,
  135838. 4,
  135839. 8,
  135840. 3,
  135841. 9,
  135842. 2,
  135843. 10,
  135844. 1,
  135845. 11,
  135846. 0,
  135847. 12,
  135848. };
  135849. static long _vq_lengthlist__44c1_s_p8_0[] = {
  135850. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  135851. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  135852. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135853. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135854. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135855. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135856. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135857. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135858. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135859. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135860. 10,10,10,10,10,10,10,10,10,
  135861. };
  135862. static float _vq_quantthresh__44c1_s_p8_0[] = {
  135863. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  135864. 552.5, 773.5, 994.5, 1215.5,
  135865. };
  135866. static long _vq_quantmap__44c1_s_p8_0[] = {
  135867. 11, 9, 7, 5, 3, 1, 0, 2,
  135868. 4, 6, 8, 10, 12,
  135869. };
  135870. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  135871. _vq_quantthresh__44c1_s_p8_0,
  135872. _vq_quantmap__44c1_s_p8_0,
  135873. 13,
  135874. 13
  135875. };
  135876. static static_codebook _44c1_s_p8_0 = {
  135877. 2, 169,
  135878. _vq_lengthlist__44c1_s_p8_0,
  135879. 1, -514541568, 1627103232, 4, 0,
  135880. _vq_quantlist__44c1_s_p8_0,
  135881. NULL,
  135882. &_vq_auxt__44c1_s_p8_0,
  135883. NULL,
  135884. 0
  135885. };
  135886. static long _vq_quantlist__44c1_s_p8_1[] = {
  135887. 6,
  135888. 5,
  135889. 7,
  135890. 4,
  135891. 8,
  135892. 3,
  135893. 9,
  135894. 2,
  135895. 10,
  135896. 1,
  135897. 11,
  135898. 0,
  135899. 12,
  135900. };
  135901. static long _vq_lengthlist__44c1_s_p8_1[] = {
  135902. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  135903. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  135904. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  135905. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  135906. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  135907. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  135908. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  135909. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  135910. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  135911. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  135912. 16,13,12,12,11,14,12,15,13,
  135913. };
  135914. static float _vq_quantthresh__44c1_s_p8_1[] = {
  135915. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  135916. 42.5, 59.5, 76.5, 93.5,
  135917. };
  135918. static long _vq_quantmap__44c1_s_p8_1[] = {
  135919. 11, 9, 7, 5, 3, 1, 0, 2,
  135920. 4, 6, 8, 10, 12,
  135921. };
  135922. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  135923. _vq_quantthresh__44c1_s_p8_1,
  135924. _vq_quantmap__44c1_s_p8_1,
  135925. 13,
  135926. 13
  135927. };
  135928. static static_codebook _44c1_s_p8_1 = {
  135929. 2, 169,
  135930. _vq_lengthlist__44c1_s_p8_1,
  135931. 1, -522616832, 1620115456, 4, 0,
  135932. _vq_quantlist__44c1_s_p8_1,
  135933. NULL,
  135934. &_vq_auxt__44c1_s_p8_1,
  135935. NULL,
  135936. 0
  135937. };
  135938. static long _vq_quantlist__44c1_s_p8_2[] = {
  135939. 8,
  135940. 7,
  135941. 9,
  135942. 6,
  135943. 10,
  135944. 5,
  135945. 11,
  135946. 4,
  135947. 12,
  135948. 3,
  135949. 13,
  135950. 2,
  135951. 14,
  135952. 1,
  135953. 15,
  135954. 0,
  135955. 16,
  135956. };
  135957. static long _vq_lengthlist__44c1_s_p8_2[] = {
  135958. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  135959. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  135960. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  135961. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  135962. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  135963. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  135964. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  135965. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  135966. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  135967. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  135968. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  135969. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  135970. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  135971. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  135972. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  135973. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  135974. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  135975. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  135976. 9,
  135977. };
  135978. static float _vq_quantthresh__44c1_s_p8_2[] = {
  135979. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135980. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135981. };
  135982. static long _vq_quantmap__44c1_s_p8_2[] = {
  135983. 15, 13, 11, 9, 7, 5, 3, 1,
  135984. 0, 2, 4, 6, 8, 10, 12, 14,
  135985. 16,
  135986. };
  135987. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  135988. _vq_quantthresh__44c1_s_p8_2,
  135989. _vq_quantmap__44c1_s_p8_2,
  135990. 17,
  135991. 17
  135992. };
  135993. static static_codebook _44c1_s_p8_2 = {
  135994. 2, 289,
  135995. _vq_lengthlist__44c1_s_p8_2,
  135996. 1, -529530880, 1611661312, 5, 0,
  135997. _vq_quantlist__44c1_s_p8_2,
  135998. NULL,
  135999. &_vq_auxt__44c1_s_p8_2,
  136000. NULL,
  136001. 0
  136002. };
  136003. static long _huff_lengthlist__44c1_s_short[] = {
  136004. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  136005. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  136006. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  136007. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  136008. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  136009. 11,
  136010. };
  136011. static static_codebook _huff_book__44c1_s_short = {
  136012. 2, 81,
  136013. _huff_lengthlist__44c1_s_short,
  136014. 0, 0, 0, 0, 0,
  136015. NULL,
  136016. NULL,
  136017. NULL,
  136018. NULL,
  136019. 0
  136020. };
  136021. static long _huff_lengthlist__44c1_sm_long[] = {
  136022. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  136023. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  136024. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  136025. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  136026. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  136027. 11,
  136028. };
  136029. static static_codebook _huff_book__44c1_sm_long = {
  136030. 2, 81,
  136031. _huff_lengthlist__44c1_sm_long,
  136032. 0, 0, 0, 0, 0,
  136033. NULL,
  136034. NULL,
  136035. NULL,
  136036. NULL,
  136037. 0
  136038. };
  136039. static long _vq_quantlist__44c1_sm_p1_0[] = {
  136040. 1,
  136041. 0,
  136042. 2,
  136043. };
  136044. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  136045. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136046. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136051. 0, 0, 0, 7, 8, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  136056. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 7, 0, 0, 0, 0,
  136091. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  136096. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  136101. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  136137. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136142. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136147. 0, 0, 0, 0, 0, 0, 9,10, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136455. 0,
  136456. };
  136457. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  136458. -0.5, 0.5,
  136459. };
  136460. static long _vq_quantmap__44c1_sm_p1_0[] = {
  136461. 1, 0, 2,
  136462. };
  136463. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  136464. _vq_quantthresh__44c1_sm_p1_0,
  136465. _vq_quantmap__44c1_sm_p1_0,
  136466. 3,
  136467. 3
  136468. };
  136469. static static_codebook _44c1_sm_p1_0 = {
  136470. 8, 6561,
  136471. _vq_lengthlist__44c1_sm_p1_0,
  136472. 1, -535822336, 1611661312, 2, 0,
  136473. _vq_quantlist__44c1_sm_p1_0,
  136474. NULL,
  136475. &_vq_auxt__44c1_sm_p1_0,
  136476. NULL,
  136477. 0
  136478. };
  136479. static long _vq_quantlist__44c1_sm_p2_0[] = {
  136480. 2,
  136481. 1,
  136482. 3,
  136483. 0,
  136484. 4,
  136485. };
  136486. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  136487. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  136489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136490. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  136492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136493. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136526. 0,
  136527. };
  136528. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  136529. -1.5, -0.5, 0.5, 1.5,
  136530. };
  136531. static long _vq_quantmap__44c1_sm_p2_0[] = {
  136532. 3, 1, 0, 2, 4,
  136533. };
  136534. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  136535. _vq_quantthresh__44c1_sm_p2_0,
  136536. _vq_quantmap__44c1_sm_p2_0,
  136537. 5,
  136538. 5
  136539. };
  136540. static static_codebook _44c1_sm_p2_0 = {
  136541. 4, 625,
  136542. _vq_lengthlist__44c1_sm_p2_0,
  136543. 1, -533725184, 1611661312, 3, 0,
  136544. _vq_quantlist__44c1_sm_p2_0,
  136545. NULL,
  136546. &_vq_auxt__44c1_sm_p2_0,
  136547. NULL,
  136548. 0
  136549. };
  136550. static long _vq_quantlist__44c1_sm_p3_0[] = {
  136551. 4,
  136552. 3,
  136553. 5,
  136554. 2,
  136555. 6,
  136556. 1,
  136557. 7,
  136558. 0,
  136559. 8,
  136560. };
  136561. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  136562. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  136563. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  136564. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136565. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136566. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136567. 0,
  136568. };
  136569. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  136570. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136571. };
  136572. static long _vq_quantmap__44c1_sm_p3_0[] = {
  136573. 7, 5, 3, 1, 0, 2, 4, 6,
  136574. 8,
  136575. };
  136576. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  136577. _vq_quantthresh__44c1_sm_p3_0,
  136578. _vq_quantmap__44c1_sm_p3_0,
  136579. 9,
  136580. 9
  136581. };
  136582. static static_codebook _44c1_sm_p3_0 = {
  136583. 2, 81,
  136584. _vq_lengthlist__44c1_sm_p3_0,
  136585. 1, -531628032, 1611661312, 4, 0,
  136586. _vq_quantlist__44c1_sm_p3_0,
  136587. NULL,
  136588. &_vq_auxt__44c1_sm_p3_0,
  136589. NULL,
  136590. 0
  136591. };
  136592. static long _vq_quantlist__44c1_sm_p4_0[] = {
  136593. 4,
  136594. 3,
  136595. 5,
  136596. 2,
  136597. 6,
  136598. 1,
  136599. 7,
  136600. 0,
  136601. 8,
  136602. };
  136603. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  136604. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  136605. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  136606. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  136607. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  136608. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  136609. 11,
  136610. };
  136611. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  136612. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136613. };
  136614. static long _vq_quantmap__44c1_sm_p4_0[] = {
  136615. 7, 5, 3, 1, 0, 2, 4, 6,
  136616. 8,
  136617. };
  136618. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  136619. _vq_quantthresh__44c1_sm_p4_0,
  136620. _vq_quantmap__44c1_sm_p4_0,
  136621. 9,
  136622. 9
  136623. };
  136624. static static_codebook _44c1_sm_p4_0 = {
  136625. 2, 81,
  136626. _vq_lengthlist__44c1_sm_p4_0,
  136627. 1, -531628032, 1611661312, 4, 0,
  136628. _vq_quantlist__44c1_sm_p4_0,
  136629. NULL,
  136630. &_vq_auxt__44c1_sm_p4_0,
  136631. NULL,
  136632. 0
  136633. };
  136634. static long _vq_quantlist__44c1_sm_p5_0[] = {
  136635. 8,
  136636. 7,
  136637. 9,
  136638. 6,
  136639. 10,
  136640. 5,
  136641. 11,
  136642. 4,
  136643. 12,
  136644. 3,
  136645. 13,
  136646. 2,
  136647. 14,
  136648. 1,
  136649. 15,
  136650. 0,
  136651. 16,
  136652. };
  136653. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  136654. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  136655. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  136656. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  136657. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136658. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136659. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  136660. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  136661. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136662. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136663. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  136664. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136665. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136666. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  136667. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  136668. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  136669. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  136670. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  136671. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136672. 14,
  136673. };
  136674. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  136675. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136676. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136677. };
  136678. static long _vq_quantmap__44c1_sm_p5_0[] = {
  136679. 15, 13, 11, 9, 7, 5, 3, 1,
  136680. 0, 2, 4, 6, 8, 10, 12, 14,
  136681. 16,
  136682. };
  136683. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  136684. _vq_quantthresh__44c1_sm_p5_0,
  136685. _vq_quantmap__44c1_sm_p5_0,
  136686. 17,
  136687. 17
  136688. };
  136689. static static_codebook _44c1_sm_p5_0 = {
  136690. 2, 289,
  136691. _vq_lengthlist__44c1_sm_p5_0,
  136692. 1, -529530880, 1611661312, 5, 0,
  136693. _vq_quantlist__44c1_sm_p5_0,
  136694. NULL,
  136695. &_vq_auxt__44c1_sm_p5_0,
  136696. NULL,
  136697. 0
  136698. };
  136699. static long _vq_quantlist__44c1_sm_p6_0[] = {
  136700. 1,
  136701. 0,
  136702. 2,
  136703. };
  136704. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  136705. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  136706. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  136707. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  136708. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  136709. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  136710. 11,
  136711. };
  136712. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  136713. -5.5, 5.5,
  136714. };
  136715. static long _vq_quantmap__44c1_sm_p6_0[] = {
  136716. 1, 0, 2,
  136717. };
  136718. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  136719. _vq_quantthresh__44c1_sm_p6_0,
  136720. _vq_quantmap__44c1_sm_p6_0,
  136721. 3,
  136722. 3
  136723. };
  136724. static static_codebook _44c1_sm_p6_0 = {
  136725. 4, 81,
  136726. _vq_lengthlist__44c1_sm_p6_0,
  136727. 1, -529137664, 1618345984, 2, 0,
  136728. _vq_quantlist__44c1_sm_p6_0,
  136729. NULL,
  136730. &_vq_auxt__44c1_sm_p6_0,
  136731. NULL,
  136732. 0
  136733. };
  136734. static long _vq_quantlist__44c1_sm_p6_1[] = {
  136735. 5,
  136736. 4,
  136737. 6,
  136738. 3,
  136739. 7,
  136740. 2,
  136741. 8,
  136742. 1,
  136743. 9,
  136744. 0,
  136745. 10,
  136746. };
  136747. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  136748. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  136749. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  136750. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  136751. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  136752. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  136753. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  136754. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136755. 10,10,10, 8, 8, 8, 8, 8, 8,
  136756. };
  136757. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  136758. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136759. 3.5, 4.5,
  136760. };
  136761. static long _vq_quantmap__44c1_sm_p6_1[] = {
  136762. 9, 7, 5, 3, 1, 0, 2, 4,
  136763. 6, 8, 10,
  136764. };
  136765. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  136766. _vq_quantthresh__44c1_sm_p6_1,
  136767. _vq_quantmap__44c1_sm_p6_1,
  136768. 11,
  136769. 11
  136770. };
  136771. static static_codebook _44c1_sm_p6_1 = {
  136772. 2, 121,
  136773. _vq_lengthlist__44c1_sm_p6_1,
  136774. 1, -531365888, 1611661312, 4, 0,
  136775. _vq_quantlist__44c1_sm_p6_1,
  136776. NULL,
  136777. &_vq_auxt__44c1_sm_p6_1,
  136778. NULL,
  136779. 0
  136780. };
  136781. static long _vq_quantlist__44c1_sm_p7_0[] = {
  136782. 6,
  136783. 5,
  136784. 7,
  136785. 4,
  136786. 8,
  136787. 3,
  136788. 9,
  136789. 2,
  136790. 10,
  136791. 1,
  136792. 11,
  136793. 0,
  136794. 12,
  136795. };
  136796. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  136797. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136798. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136799. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136800. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136801. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136802. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  136803. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  136804. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136805. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136806. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  136807. 0,12,12,11,11,13,12,14,13,
  136808. };
  136809. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  136810. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136811. 12.5, 17.5, 22.5, 27.5,
  136812. };
  136813. static long _vq_quantmap__44c1_sm_p7_0[] = {
  136814. 11, 9, 7, 5, 3, 1, 0, 2,
  136815. 4, 6, 8, 10, 12,
  136816. };
  136817. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  136818. _vq_quantthresh__44c1_sm_p7_0,
  136819. _vq_quantmap__44c1_sm_p7_0,
  136820. 13,
  136821. 13
  136822. };
  136823. static static_codebook _44c1_sm_p7_0 = {
  136824. 2, 169,
  136825. _vq_lengthlist__44c1_sm_p7_0,
  136826. 1, -526516224, 1616117760, 4, 0,
  136827. _vq_quantlist__44c1_sm_p7_0,
  136828. NULL,
  136829. &_vq_auxt__44c1_sm_p7_0,
  136830. NULL,
  136831. 0
  136832. };
  136833. static long _vq_quantlist__44c1_sm_p7_1[] = {
  136834. 2,
  136835. 1,
  136836. 3,
  136837. 0,
  136838. 4,
  136839. };
  136840. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  136841. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  136842. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  136843. };
  136844. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  136845. -1.5, -0.5, 0.5, 1.5,
  136846. };
  136847. static long _vq_quantmap__44c1_sm_p7_1[] = {
  136848. 3, 1, 0, 2, 4,
  136849. };
  136850. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  136851. _vq_quantthresh__44c1_sm_p7_1,
  136852. _vq_quantmap__44c1_sm_p7_1,
  136853. 5,
  136854. 5
  136855. };
  136856. static static_codebook _44c1_sm_p7_1 = {
  136857. 2, 25,
  136858. _vq_lengthlist__44c1_sm_p7_1,
  136859. 1, -533725184, 1611661312, 3, 0,
  136860. _vq_quantlist__44c1_sm_p7_1,
  136861. NULL,
  136862. &_vq_auxt__44c1_sm_p7_1,
  136863. NULL,
  136864. 0
  136865. };
  136866. static long _vq_quantlist__44c1_sm_p8_0[] = {
  136867. 6,
  136868. 5,
  136869. 7,
  136870. 4,
  136871. 8,
  136872. 3,
  136873. 9,
  136874. 2,
  136875. 10,
  136876. 1,
  136877. 11,
  136878. 0,
  136879. 12,
  136880. };
  136881. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  136882. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  136883. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  136884. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136885. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136886. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136887. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136888. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136889. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136890. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136891. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136892. 13,13,13,13,13,13,13,13,13,
  136893. };
  136894. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  136895. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  136896. 552.5, 773.5, 994.5, 1215.5,
  136897. };
  136898. static long _vq_quantmap__44c1_sm_p8_0[] = {
  136899. 11, 9, 7, 5, 3, 1, 0, 2,
  136900. 4, 6, 8, 10, 12,
  136901. };
  136902. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  136903. _vq_quantthresh__44c1_sm_p8_0,
  136904. _vq_quantmap__44c1_sm_p8_0,
  136905. 13,
  136906. 13
  136907. };
  136908. static static_codebook _44c1_sm_p8_0 = {
  136909. 2, 169,
  136910. _vq_lengthlist__44c1_sm_p8_0,
  136911. 1, -514541568, 1627103232, 4, 0,
  136912. _vq_quantlist__44c1_sm_p8_0,
  136913. NULL,
  136914. &_vq_auxt__44c1_sm_p8_0,
  136915. NULL,
  136916. 0
  136917. };
  136918. static long _vq_quantlist__44c1_sm_p8_1[] = {
  136919. 6,
  136920. 5,
  136921. 7,
  136922. 4,
  136923. 8,
  136924. 3,
  136925. 9,
  136926. 2,
  136927. 10,
  136928. 1,
  136929. 11,
  136930. 0,
  136931. 12,
  136932. };
  136933. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  136934. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  136935. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  136936. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  136937. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  136938. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  136939. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  136940. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  136941. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  136942. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  136943. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  136944. 20,13,12,12,12,14,12,14,13,
  136945. };
  136946. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  136947. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136948. 42.5, 59.5, 76.5, 93.5,
  136949. };
  136950. static long _vq_quantmap__44c1_sm_p8_1[] = {
  136951. 11, 9, 7, 5, 3, 1, 0, 2,
  136952. 4, 6, 8, 10, 12,
  136953. };
  136954. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  136955. _vq_quantthresh__44c1_sm_p8_1,
  136956. _vq_quantmap__44c1_sm_p8_1,
  136957. 13,
  136958. 13
  136959. };
  136960. static static_codebook _44c1_sm_p8_1 = {
  136961. 2, 169,
  136962. _vq_lengthlist__44c1_sm_p8_1,
  136963. 1, -522616832, 1620115456, 4, 0,
  136964. _vq_quantlist__44c1_sm_p8_1,
  136965. NULL,
  136966. &_vq_auxt__44c1_sm_p8_1,
  136967. NULL,
  136968. 0
  136969. };
  136970. static long _vq_quantlist__44c1_sm_p8_2[] = {
  136971. 8,
  136972. 7,
  136973. 9,
  136974. 6,
  136975. 10,
  136976. 5,
  136977. 11,
  136978. 4,
  136979. 12,
  136980. 3,
  136981. 13,
  136982. 2,
  136983. 14,
  136984. 1,
  136985. 15,
  136986. 0,
  136987. 16,
  136988. };
  136989. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  136990. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136991. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  136992. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  136993. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  136994. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136995. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  136996. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  136997. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  136998. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  136999. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  137000. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  137001. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  137002. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  137003. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  137004. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  137005. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  137006. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  137007. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  137008. 9,
  137009. };
  137010. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  137011. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137012. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137013. };
  137014. static long _vq_quantmap__44c1_sm_p8_2[] = {
  137015. 15, 13, 11, 9, 7, 5, 3, 1,
  137016. 0, 2, 4, 6, 8, 10, 12, 14,
  137017. 16,
  137018. };
  137019. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  137020. _vq_quantthresh__44c1_sm_p8_2,
  137021. _vq_quantmap__44c1_sm_p8_2,
  137022. 17,
  137023. 17
  137024. };
  137025. static static_codebook _44c1_sm_p8_2 = {
  137026. 2, 289,
  137027. _vq_lengthlist__44c1_sm_p8_2,
  137028. 1, -529530880, 1611661312, 5, 0,
  137029. _vq_quantlist__44c1_sm_p8_2,
  137030. NULL,
  137031. &_vq_auxt__44c1_sm_p8_2,
  137032. NULL,
  137033. 0
  137034. };
  137035. static long _huff_lengthlist__44c1_sm_short[] = {
  137036. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  137037. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  137038. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  137039. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  137040. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  137041. 11,
  137042. };
  137043. static static_codebook _huff_book__44c1_sm_short = {
  137044. 2, 81,
  137045. _huff_lengthlist__44c1_sm_short,
  137046. 0, 0, 0, 0, 0,
  137047. NULL,
  137048. NULL,
  137049. NULL,
  137050. NULL,
  137051. 0
  137052. };
  137053. static long _huff_lengthlist__44cn1_s_long[] = {
  137054. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  137055. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  137056. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  137057. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  137058. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  137059. 20,
  137060. };
  137061. static static_codebook _huff_book__44cn1_s_long = {
  137062. 2, 81,
  137063. _huff_lengthlist__44cn1_s_long,
  137064. 0, 0, 0, 0, 0,
  137065. NULL,
  137066. NULL,
  137067. NULL,
  137068. NULL,
  137069. 0
  137070. };
  137071. static long _vq_quantlist__44cn1_s_p1_0[] = {
  137072. 1,
  137073. 0,
  137074. 2,
  137075. };
  137076. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  137077. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  137078. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  137083. 0, 0, 0, 7, 9,10, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  137088. 0, 0, 0, 0, 8,10, 9, 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, 5, 8, 8, 0, 0, 0, 0,
  137123. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 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, 7,10,10, 0, 0, 0,
  137128. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 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, 7,10,10, 0, 0,
  137133. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  137169. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  137174. 0, 0, 0, 0, 0, 9, 9,11, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  137179. 0, 0, 0, 0, 0, 0, 9,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137487. 0,
  137488. };
  137489. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  137490. -0.5, 0.5,
  137491. };
  137492. static long _vq_quantmap__44cn1_s_p1_0[] = {
  137493. 1, 0, 2,
  137494. };
  137495. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  137496. _vq_quantthresh__44cn1_s_p1_0,
  137497. _vq_quantmap__44cn1_s_p1_0,
  137498. 3,
  137499. 3
  137500. };
  137501. static static_codebook _44cn1_s_p1_0 = {
  137502. 8, 6561,
  137503. _vq_lengthlist__44cn1_s_p1_0,
  137504. 1, -535822336, 1611661312, 2, 0,
  137505. _vq_quantlist__44cn1_s_p1_0,
  137506. NULL,
  137507. &_vq_auxt__44cn1_s_p1_0,
  137508. NULL,
  137509. 0
  137510. };
  137511. static long _vq_quantlist__44cn1_s_p2_0[] = {
  137512. 2,
  137513. 1,
  137514. 3,
  137515. 0,
  137516. 4,
  137517. };
  137518. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  137519. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137522. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137525. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137558. 0,
  137559. };
  137560. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  137561. -1.5, -0.5, 0.5, 1.5,
  137562. };
  137563. static long _vq_quantmap__44cn1_s_p2_0[] = {
  137564. 3, 1, 0, 2, 4,
  137565. };
  137566. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  137567. _vq_quantthresh__44cn1_s_p2_0,
  137568. _vq_quantmap__44cn1_s_p2_0,
  137569. 5,
  137570. 5
  137571. };
  137572. static static_codebook _44cn1_s_p2_0 = {
  137573. 4, 625,
  137574. _vq_lengthlist__44cn1_s_p2_0,
  137575. 1, -533725184, 1611661312, 3, 0,
  137576. _vq_quantlist__44cn1_s_p2_0,
  137577. NULL,
  137578. &_vq_auxt__44cn1_s_p2_0,
  137579. NULL,
  137580. 0
  137581. };
  137582. static long _vq_quantlist__44cn1_s_p3_0[] = {
  137583. 4,
  137584. 3,
  137585. 5,
  137586. 2,
  137587. 6,
  137588. 1,
  137589. 7,
  137590. 0,
  137591. 8,
  137592. };
  137593. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  137594. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  137595. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  137596. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  137597. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  137598. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137599. 0,
  137600. };
  137601. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  137602. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137603. };
  137604. static long _vq_quantmap__44cn1_s_p3_0[] = {
  137605. 7, 5, 3, 1, 0, 2, 4, 6,
  137606. 8,
  137607. };
  137608. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  137609. _vq_quantthresh__44cn1_s_p3_0,
  137610. _vq_quantmap__44cn1_s_p3_0,
  137611. 9,
  137612. 9
  137613. };
  137614. static static_codebook _44cn1_s_p3_0 = {
  137615. 2, 81,
  137616. _vq_lengthlist__44cn1_s_p3_0,
  137617. 1, -531628032, 1611661312, 4, 0,
  137618. _vq_quantlist__44cn1_s_p3_0,
  137619. NULL,
  137620. &_vq_auxt__44cn1_s_p3_0,
  137621. NULL,
  137622. 0
  137623. };
  137624. static long _vq_quantlist__44cn1_s_p4_0[] = {
  137625. 4,
  137626. 3,
  137627. 5,
  137628. 2,
  137629. 6,
  137630. 1,
  137631. 7,
  137632. 0,
  137633. 8,
  137634. };
  137635. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  137636. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  137637. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  137638. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  137639. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  137640. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  137641. 11,
  137642. };
  137643. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  137644. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137645. };
  137646. static long _vq_quantmap__44cn1_s_p4_0[] = {
  137647. 7, 5, 3, 1, 0, 2, 4, 6,
  137648. 8,
  137649. };
  137650. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  137651. _vq_quantthresh__44cn1_s_p4_0,
  137652. _vq_quantmap__44cn1_s_p4_0,
  137653. 9,
  137654. 9
  137655. };
  137656. static static_codebook _44cn1_s_p4_0 = {
  137657. 2, 81,
  137658. _vq_lengthlist__44cn1_s_p4_0,
  137659. 1, -531628032, 1611661312, 4, 0,
  137660. _vq_quantlist__44cn1_s_p4_0,
  137661. NULL,
  137662. &_vq_auxt__44cn1_s_p4_0,
  137663. NULL,
  137664. 0
  137665. };
  137666. static long _vq_quantlist__44cn1_s_p5_0[] = {
  137667. 8,
  137668. 7,
  137669. 9,
  137670. 6,
  137671. 10,
  137672. 5,
  137673. 11,
  137674. 4,
  137675. 12,
  137676. 3,
  137677. 13,
  137678. 2,
  137679. 14,
  137680. 1,
  137681. 15,
  137682. 0,
  137683. 16,
  137684. };
  137685. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  137686. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  137687. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  137688. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137689. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  137690. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  137691. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  137692. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  137693. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  137694. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  137695. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  137696. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137697. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137698. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  137699. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  137700. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  137701. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  137702. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  137703. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  137704. 14,
  137705. };
  137706. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  137707. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137708. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137709. };
  137710. static long _vq_quantmap__44cn1_s_p5_0[] = {
  137711. 15, 13, 11, 9, 7, 5, 3, 1,
  137712. 0, 2, 4, 6, 8, 10, 12, 14,
  137713. 16,
  137714. };
  137715. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  137716. _vq_quantthresh__44cn1_s_p5_0,
  137717. _vq_quantmap__44cn1_s_p5_0,
  137718. 17,
  137719. 17
  137720. };
  137721. static static_codebook _44cn1_s_p5_0 = {
  137722. 2, 289,
  137723. _vq_lengthlist__44cn1_s_p5_0,
  137724. 1, -529530880, 1611661312, 5, 0,
  137725. _vq_quantlist__44cn1_s_p5_0,
  137726. NULL,
  137727. &_vq_auxt__44cn1_s_p5_0,
  137728. NULL,
  137729. 0
  137730. };
  137731. static long _vq_quantlist__44cn1_s_p6_0[] = {
  137732. 1,
  137733. 0,
  137734. 2,
  137735. };
  137736. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  137737. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  137738. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  137739. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  137740. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  137741. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  137742. 10,
  137743. };
  137744. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  137745. -5.5, 5.5,
  137746. };
  137747. static long _vq_quantmap__44cn1_s_p6_0[] = {
  137748. 1, 0, 2,
  137749. };
  137750. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  137751. _vq_quantthresh__44cn1_s_p6_0,
  137752. _vq_quantmap__44cn1_s_p6_0,
  137753. 3,
  137754. 3
  137755. };
  137756. static static_codebook _44cn1_s_p6_0 = {
  137757. 4, 81,
  137758. _vq_lengthlist__44cn1_s_p6_0,
  137759. 1, -529137664, 1618345984, 2, 0,
  137760. _vq_quantlist__44cn1_s_p6_0,
  137761. NULL,
  137762. &_vq_auxt__44cn1_s_p6_0,
  137763. NULL,
  137764. 0
  137765. };
  137766. static long _vq_quantlist__44cn1_s_p6_1[] = {
  137767. 5,
  137768. 4,
  137769. 6,
  137770. 3,
  137771. 7,
  137772. 2,
  137773. 8,
  137774. 1,
  137775. 9,
  137776. 0,
  137777. 10,
  137778. };
  137779. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  137780. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  137781. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  137782. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  137783. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  137784. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  137785. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  137786. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  137787. 10,10,10, 9, 9, 9, 9, 9, 9,
  137788. };
  137789. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  137790. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137791. 3.5, 4.5,
  137792. };
  137793. static long _vq_quantmap__44cn1_s_p6_1[] = {
  137794. 9, 7, 5, 3, 1, 0, 2, 4,
  137795. 6, 8, 10,
  137796. };
  137797. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  137798. _vq_quantthresh__44cn1_s_p6_1,
  137799. _vq_quantmap__44cn1_s_p6_1,
  137800. 11,
  137801. 11
  137802. };
  137803. static static_codebook _44cn1_s_p6_1 = {
  137804. 2, 121,
  137805. _vq_lengthlist__44cn1_s_p6_1,
  137806. 1, -531365888, 1611661312, 4, 0,
  137807. _vq_quantlist__44cn1_s_p6_1,
  137808. NULL,
  137809. &_vq_auxt__44cn1_s_p6_1,
  137810. NULL,
  137811. 0
  137812. };
  137813. static long _vq_quantlist__44cn1_s_p7_0[] = {
  137814. 6,
  137815. 5,
  137816. 7,
  137817. 4,
  137818. 8,
  137819. 3,
  137820. 9,
  137821. 2,
  137822. 10,
  137823. 1,
  137824. 11,
  137825. 0,
  137826. 12,
  137827. };
  137828. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  137829. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  137830. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  137831. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137832. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137833. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  137834. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  137835. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  137836. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  137837. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  137838. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  137839. 0,13,13,12,12,13,13,13,14,
  137840. };
  137841. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  137842. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137843. 12.5, 17.5, 22.5, 27.5,
  137844. };
  137845. static long _vq_quantmap__44cn1_s_p7_0[] = {
  137846. 11, 9, 7, 5, 3, 1, 0, 2,
  137847. 4, 6, 8, 10, 12,
  137848. };
  137849. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  137850. _vq_quantthresh__44cn1_s_p7_0,
  137851. _vq_quantmap__44cn1_s_p7_0,
  137852. 13,
  137853. 13
  137854. };
  137855. static static_codebook _44cn1_s_p7_0 = {
  137856. 2, 169,
  137857. _vq_lengthlist__44cn1_s_p7_0,
  137858. 1, -526516224, 1616117760, 4, 0,
  137859. _vq_quantlist__44cn1_s_p7_0,
  137860. NULL,
  137861. &_vq_auxt__44cn1_s_p7_0,
  137862. NULL,
  137863. 0
  137864. };
  137865. static long _vq_quantlist__44cn1_s_p7_1[] = {
  137866. 2,
  137867. 1,
  137868. 3,
  137869. 0,
  137870. 4,
  137871. };
  137872. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  137873. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  137874. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137875. };
  137876. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  137877. -1.5, -0.5, 0.5, 1.5,
  137878. };
  137879. static long _vq_quantmap__44cn1_s_p7_1[] = {
  137880. 3, 1, 0, 2, 4,
  137881. };
  137882. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  137883. _vq_quantthresh__44cn1_s_p7_1,
  137884. _vq_quantmap__44cn1_s_p7_1,
  137885. 5,
  137886. 5
  137887. };
  137888. static static_codebook _44cn1_s_p7_1 = {
  137889. 2, 25,
  137890. _vq_lengthlist__44cn1_s_p7_1,
  137891. 1, -533725184, 1611661312, 3, 0,
  137892. _vq_quantlist__44cn1_s_p7_1,
  137893. NULL,
  137894. &_vq_auxt__44cn1_s_p7_1,
  137895. NULL,
  137896. 0
  137897. };
  137898. static long _vq_quantlist__44cn1_s_p8_0[] = {
  137899. 2,
  137900. 1,
  137901. 3,
  137902. 0,
  137903. 4,
  137904. };
  137905. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  137906. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  137907. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  137908. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137909. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  137910. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137911. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137912. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137913. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  137914. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137915. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  137916. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  137917. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137918. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137919. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137920. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137921. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  137922. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137923. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137924. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137925. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137926. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137927. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137928. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137929. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137930. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137931. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137932. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137933. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137934. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137935. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137936. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137937. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137938. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137939. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  137940. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137941. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137942. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137943. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137944. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137945. 12,
  137946. };
  137947. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  137948. -331.5, -110.5, 110.5, 331.5,
  137949. };
  137950. static long _vq_quantmap__44cn1_s_p8_0[] = {
  137951. 3, 1, 0, 2, 4,
  137952. };
  137953. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  137954. _vq_quantthresh__44cn1_s_p8_0,
  137955. _vq_quantmap__44cn1_s_p8_0,
  137956. 5,
  137957. 5
  137958. };
  137959. static static_codebook _44cn1_s_p8_0 = {
  137960. 4, 625,
  137961. _vq_lengthlist__44cn1_s_p8_0,
  137962. 1, -518283264, 1627103232, 3, 0,
  137963. _vq_quantlist__44cn1_s_p8_0,
  137964. NULL,
  137965. &_vq_auxt__44cn1_s_p8_0,
  137966. NULL,
  137967. 0
  137968. };
  137969. static long _vq_quantlist__44cn1_s_p8_1[] = {
  137970. 6,
  137971. 5,
  137972. 7,
  137973. 4,
  137974. 8,
  137975. 3,
  137976. 9,
  137977. 2,
  137978. 10,
  137979. 1,
  137980. 11,
  137981. 0,
  137982. 12,
  137983. };
  137984. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  137985. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  137986. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  137987. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  137988. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  137989. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  137990. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  137991. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  137992. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  137993. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  137994. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  137995. 15,12,12,11,11,14,12,13,14,
  137996. };
  137997. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  137998. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137999. 42.5, 59.5, 76.5, 93.5,
  138000. };
  138001. static long _vq_quantmap__44cn1_s_p8_1[] = {
  138002. 11, 9, 7, 5, 3, 1, 0, 2,
  138003. 4, 6, 8, 10, 12,
  138004. };
  138005. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  138006. _vq_quantthresh__44cn1_s_p8_1,
  138007. _vq_quantmap__44cn1_s_p8_1,
  138008. 13,
  138009. 13
  138010. };
  138011. static static_codebook _44cn1_s_p8_1 = {
  138012. 2, 169,
  138013. _vq_lengthlist__44cn1_s_p8_1,
  138014. 1, -522616832, 1620115456, 4, 0,
  138015. _vq_quantlist__44cn1_s_p8_1,
  138016. NULL,
  138017. &_vq_auxt__44cn1_s_p8_1,
  138018. NULL,
  138019. 0
  138020. };
  138021. static long _vq_quantlist__44cn1_s_p8_2[] = {
  138022. 8,
  138023. 7,
  138024. 9,
  138025. 6,
  138026. 10,
  138027. 5,
  138028. 11,
  138029. 4,
  138030. 12,
  138031. 3,
  138032. 13,
  138033. 2,
  138034. 14,
  138035. 1,
  138036. 15,
  138037. 0,
  138038. 16,
  138039. };
  138040. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  138041. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  138042. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138043. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  138044. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  138045. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  138046. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  138047. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  138048. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  138049. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  138050. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  138051. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  138052. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  138053. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  138054. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  138055. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  138056. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  138057. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  138058. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  138059. 9,
  138060. };
  138061. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  138062. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138063. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138064. };
  138065. static long _vq_quantmap__44cn1_s_p8_2[] = {
  138066. 15, 13, 11, 9, 7, 5, 3, 1,
  138067. 0, 2, 4, 6, 8, 10, 12, 14,
  138068. 16,
  138069. };
  138070. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  138071. _vq_quantthresh__44cn1_s_p8_2,
  138072. _vq_quantmap__44cn1_s_p8_2,
  138073. 17,
  138074. 17
  138075. };
  138076. static static_codebook _44cn1_s_p8_2 = {
  138077. 2, 289,
  138078. _vq_lengthlist__44cn1_s_p8_2,
  138079. 1, -529530880, 1611661312, 5, 0,
  138080. _vq_quantlist__44cn1_s_p8_2,
  138081. NULL,
  138082. &_vq_auxt__44cn1_s_p8_2,
  138083. NULL,
  138084. 0
  138085. };
  138086. static long _huff_lengthlist__44cn1_s_short[] = {
  138087. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  138088. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  138089. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  138090. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  138091. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  138092. 10,
  138093. };
  138094. static static_codebook _huff_book__44cn1_s_short = {
  138095. 2, 81,
  138096. _huff_lengthlist__44cn1_s_short,
  138097. 0, 0, 0, 0, 0,
  138098. NULL,
  138099. NULL,
  138100. NULL,
  138101. NULL,
  138102. 0
  138103. };
  138104. static long _huff_lengthlist__44cn1_sm_long[] = {
  138105. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  138106. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  138107. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  138108. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  138109. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  138110. 17,
  138111. };
  138112. static static_codebook _huff_book__44cn1_sm_long = {
  138113. 2, 81,
  138114. _huff_lengthlist__44cn1_sm_long,
  138115. 0, 0, 0, 0, 0,
  138116. NULL,
  138117. NULL,
  138118. NULL,
  138119. NULL,
  138120. 0
  138121. };
  138122. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  138123. 1,
  138124. 0,
  138125. 2,
  138126. };
  138127. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  138128. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  138129. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  138134. 0, 0, 0, 7, 8, 9, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  138139. 0, 0, 0, 0, 8, 9, 9, 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, 5, 8, 8, 0, 0, 0, 0,
  138174. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  138179. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  138184. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138220. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138225. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  138230. 0, 0, 0, 0, 0, 0, 9,10, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138538. 0,
  138539. };
  138540. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  138541. -0.5, 0.5,
  138542. };
  138543. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  138544. 1, 0, 2,
  138545. };
  138546. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  138547. _vq_quantthresh__44cn1_sm_p1_0,
  138548. _vq_quantmap__44cn1_sm_p1_0,
  138549. 3,
  138550. 3
  138551. };
  138552. static static_codebook _44cn1_sm_p1_0 = {
  138553. 8, 6561,
  138554. _vq_lengthlist__44cn1_sm_p1_0,
  138555. 1, -535822336, 1611661312, 2, 0,
  138556. _vq_quantlist__44cn1_sm_p1_0,
  138557. NULL,
  138558. &_vq_auxt__44cn1_sm_p1_0,
  138559. NULL,
  138560. 0
  138561. };
  138562. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  138563. 2,
  138564. 1,
  138565. 3,
  138566. 0,
  138567. 4,
  138568. };
  138569. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  138570. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  138572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138573. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  138575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138576. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  138577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138609. 0,
  138610. };
  138611. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  138612. -1.5, -0.5, 0.5, 1.5,
  138613. };
  138614. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  138615. 3, 1, 0, 2, 4,
  138616. };
  138617. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  138618. _vq_quantthresh__44cn1_sm_p2_0,
  138619. _vq_quantmap__44cn1_sm_p2_0,
  138620. 5,
  138621. 5
  138622. };
  138623. static static_codebook _44cn1_sm_p2_0 = {
  138624. 4, 625,
  138625. _vq_lengthlist__44cn1_sm_p2_0,
  138626. 1, -533725184, 1611661312, 3, 0,
  138627. _vq_quantlist__44cn1_sm_p2_0,
  138628. NULL,
  138629. &_vq_auxt__44cn1_sm_p2_0,
  138630. NULL,
  138631. 0
  138632. };
  138633. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  138634. 4,
  138635. 3,
  138636. 5,
  138637. 2,
  138638. 6,
  138639. 1,
  138640. 7,
  138641. 0,
  138642. 8,
  138643. };
  138644. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  138645. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  138646. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  138647. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  138648. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  138649. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138650. 0,
  138651. };
  138652. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  138653. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138654. };
  138655. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  138656. 7, 5, 3, 1, 0, 2, 4, 6,
  138657. 8,
  138658. };
  138659. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  138660. _vq_quantthresh__44cn1_sm_p3_0,
  138661. _vq_quantmap__44cn1_sm_p3_0,
  138662. 9,
  138663. 9
  138664. };
  138665. static static_codebook _44cn1_sm_p3_0 = {
  138666. 2, 81,
  138667. _vq_lengthlist__44cn1_sm_p3_0,
  138668. 1, -531628032, 1611661312, 4, 0,
  138669. _vq_quantlist__44cn1_sm_p3_0,
  138670. NULL,
  138671. &_vq_auxt__44cn1_sm_p3_0,
  138672. NULL,
  138673. 0
  138674. };
  138675. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  138676. 4,
  138677. 3,
  138678. 5,
  138679. 2,
  138680. 6,
  138681. 1,
  138682. 7,
  138683. 0,
  138684. 8,
  138685. };
  138686. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  138687. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  138688. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  138689. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  138690. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  138691. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  138692. 11,
  138693. };
  138694. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  138695. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138696. };
  138697. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  138698. 7, 5, 3, 1, 0, 2, 4, 6,
  138699. 8,
  138700. };
  138701. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  138702. _vq_quantthresh__44cn1_sm_p4_0,
  138703. _vq_quantmap__44cn1_sm_p4_0,
  138704. 9,
  138705. 9
  138706. };
  138707. static static_codebook _44cn1_sm_p4_0 = {
  138708. 2, 81,
  138709. _vq_lengthlist__44cn1_sm_p4_0,
  138710. 1, -531628032, 1611661312, 4, 0,
  138711. _vq_quantlist__44cn1_sm_p4_0,
  138712. NULL,
  138713. &_vq_auxt__44cn1_sm_p4_0,
  138714. NULL,
  138715. 0
  138716. };
  138717. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  138718. 8,
  138719. 7,
  138720. 9,
  138721. 6,
  138722. 10,
  138723. 5,
  138724. 11,
  138725. 4,
  138726. 12,
  138727. 3,
  138728. 13,
  138729. 2,
  138730. 14,
  138731. 1,
  138732. 15,
  138733. 0,
  138734. 16,
  138735. };
  138736. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  138737. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  138738. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  138739. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  138740. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138741. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  138742. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  138743. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  138744. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138745. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  138746. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  138747. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  138748. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  138749. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  138750. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  138751. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  138752. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  138753. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  138754. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  138755. 14,
  138756. };
  138757. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  138758. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138759. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138760. };
  138761. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  138762. 15, 13, 11, 9, 7, 5, 3, 1,
  138763. 0, 2, 4, 6, 8, 10, 12, 14,
  138764. 16,
  138765. };
  138766. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  138767. _vq_quantthresh__44cn1_sm_p5_0,
  138768. _vq_quantmap__44cn1_sm_p5_0,
  138769. 17,
  138770. 17
  138771. };
  138772. static static_codebook _44cn1_sm_p5_0 = {
  138773. 2, 289,
  138774. _vq_lengthlist__44cn1_sm_p5_0,
  138775. 1, -529530880, 1611661312, 5, 0,
  138776. _vq_quantlist__44cn1_sm_p5_0,
  138777. NULL,
  138778. &_vq_auxt__44cn1_sm_p5_0,
  138779. NULL,
  138780. 0
  138781. };
  138782. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  138783. 1,
  138784. 0,
  138785. 2,
  138786. };
  138787. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  138788. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  138789. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  138790. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  138791. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  138792. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  138793. 10,
  138794. };
  138795. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  138796. -5.5, 5.5,
  138797. };
  138798. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  138799. 1, 0, 2,
  138800. };
  138801. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  138802. _vq_quantthresh__44cn1_sm_p6_0,
  138803. _vq_quantmap__44cn1_sm_p6_0,
  138804. 3,
  138805. 3
  138806. };
  138807. static static_codebook _44cn1_sm_p6_0 = {
  138808. 4, 81,
  138809. _vq_lengthlist__44cn1_sm_p6_0,
  138810. 1, -529137664, 1618345984, 2, 0,
  138811. _vq_quantlist__44cn1_sm_p6_0,
  138812. NULL,
  138813. &_vq_auxt__44cn1_sm_p6_0,
  138814. NULL,
  138815. 0
  138816. };
  138817. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  138818. 5,
  138819. 4,
  138820. 6,
  138821. 3,
  138822. 7,
  138823. 2,
  138824. 8,
  138825. 1,
  138826. 9,
  138827. 0,
  138828. 10,
  138829. };
  138830. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  138831. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  138832. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  138833. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  138834. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  138835. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  138836. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  138837. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  138838. 10,10,10, 8, 9, 8, 8, 9, 8,
  138839. };
  138840. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  138841. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138842. 3.5, 4.5,
  138843. };
  138844. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  138845. 9, 7, 5, 3, 1, 0, 2, 4,
  138846. 6, 8, 10,
  138847. };
  138848. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  138849. _vq_quantthresh__44cn1_sm_p6_1,
  138850. _vq_quantmap__44cn1_sm_p6_1,
  138851. 11,
  138852. 11
  138853. };
  138854. static static_codebook _44cn1_sm_p6_1 = {
  138855. 2, 121,
  138856. _vq_lengthlist__44cn1_sm_p6_1,
  138857. 1, -531365888, 1611661312, 4, 0,
  138858. _vq_quantlist__44cn1_sm_p6_1,
  138859. NULL,
  138860. &_vq_auxt__44cn1_sm_p6_1,
  138861. NULL,
  138862. 0
  138863. };
  138864. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  138865. 6,
  138866. 5,
  138867. 7,
  138868. 4,
  138869. 8,
  138870. 3,
  138871. 9,
  138872. 2,
  138873. 10,
  138874. 1,
  138875. 11,
  138876. 0,
  138877. 12,
  138878. };
  138879. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  138880. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  138881. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  138882. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138883. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138884. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  138885. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  138886. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  138887. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  138888. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  138889. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  138890. 0,13,12,12,12,13,13,13,14,
  138891. };
  138892. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  138893. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138894. 12.5, 17.5, 22.5, 27.5,
  138895. };
  138896. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  138897. 11, 9, 7, 5, 3, 1, 0, 2,
  138898. 4, 6, 8, 10, 12,
  138899. };
  138900. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  138901. _vq_quantthresh__44cn1_sm_p7_0,
  138902. _vq_quantmap__44cn1_sm_p7_0,
  138903. 13,
  138904. 13
  138905. };
  138906. static static_codebook _44cn1_sm_p7_0 = {
  138907. 2, 169,
  138908. _vq_lengthlist__44cn1_sm_p7_0,
  138909. 1, -526516224, 1616117760, 4, 0,
  138910. _vq_quantlist__44cn1_sm_p7_0,
  138911. NULL,
  138912. &_vq_auxt__44cn1_sm_p7_0,
  138913. NULL,
  138914. 0
  138915. };
  138916. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  138917. 2,
  138918. 1,
  138919. 3,
  138920. 0,
  138921. 4,
  138922. };
  138923. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  138924. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  138925. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  138926. };
  138927. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  138928. -1.5, -0.5, 0.5, 1.5,
  138929. };
  138930. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  138931. 3, 1, 0, 2, 4,
  138932. };
  138933. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  138934. _vq_quantthresh__44cn1_sm_p7_1,
  138935. _vq_quantmap__44cn1_sm_p7_1,
  138936. 5,
  138937. 5
  138938. };
  138939. static static_codebook _44cn1_sm_p7_1 = {
  138940. 2, 25,
  138941. _vq_lengthlist__44cn1_sm_p7_1,
  138942. 1, -533725184, 1611661312, 3, 0,
  138943. _vq_quantlist__44cn1_sm_p7_1,
  138944. NULL,
  138945. &_vq_auxt__44cn1_sm_p7_1,
  138946. NULL,
  138947. 0
  138948. };
  138949. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  138950. 4,
  138951. 3,
  138952. 5,
  138953. 2,
  138954. 6,
  138955. 1,
  138956. 7,
  138957. 0,
  138958. 8,
  138959. };
  138960. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  138961. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  138962. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  138963. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  138964. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  138965. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  138966. 14,
  138967. };
  138968. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  138969. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  138970. };
  138971. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  138972. 7, 5, 3, 1, 0, 2, 4, 6,
  138973. 8,
  138974. };
  138975. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  138976. _vq_quantthresh__44cn1_sm_p8_0,
  138977. _vq_quantmap__44cn1_sm_p8_0,
  138978. 9,
  138979. 9
  138980. };
  138981. static static_codebook _44cn1_sm_p8_0 = {
  138982. 2, 81,
  138983. _vq_lengthlist__44cn1_sm_p8_0,
  138984. 1, -516186112, 1627103232, 4, 0,
  138985. _vq_quantlist__44cn1_sm_p8_0,
  138986. NULL,
  138987. &_vq_auxt__44cn1_sm_p8_0,
  138988. NULL,
  138989. 0
  138990. };
  138991. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  138992. 6,
  138993. 5,
  138994. 7,
  138995. 4,
  138996. 8,
  138997. 3,
  138998. 9,
  138999. 2,
  139000. 10,
  139001. 1,
  139002. 11,
  139003. 0,
  139004. 12,
  139005. };
  139006. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  139007. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  139008. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  139009. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  139010. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  139011. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  139012. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  139013. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  139014. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  139015. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  139016. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  139017. 17,12,12,11,10,13,11,13,13,
  139018. };
  139019. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  139020. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139021. 42.5, 59.5, 76.5, 93.5,
  139022. };
  139023. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  139024. 11, 9, 7, 5, 3, 1, 0, 2,
  139025. 4, 6, 8, 10, 12,
  139026. };
  139027. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  139028. _vq_quantthresh__44cn1_sm_p8_1,
  139029. _vq_quantmap__44cn1_sm_p8_1,
  139030. 13,
  139031. 13
  139032. };
  139033. static static_codebook _44cn1_sm_p8_1 = {
  139034. 2, 169,
  139035. _vq_lengthlist__44cn1_sm_p8_1,
  139036. 1, -522616832, 1620115456, 4, 0,
  139037. _vq_quantlist__44cn1_sm_p8_1,
  139038. NULL,
  139039. &_vq_auxt__44cn1_sm_p8_1,
  139040. NULL,
  139041. 0
  139042. };
  139043. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  139044. 8,
  139045. 7,
  139046. 9,
  139047. 6,
  139048. 10,
  139049. 5,
  139050. 11,
  139051. 4,
  139052. 12,
  139053. 3,
  139054. 13,
  139055. 2,
  139056. 14,
  139057. 1,
  139058. 15,
  139059. 0,
  139060. 16,
  139061. };
  139062. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  139063. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  139064. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  139065. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  139066. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  139067. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  139068. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  139069. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  139070. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  139071. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  139072. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  139073. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  139074. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  139075. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  139076. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  139077. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  139078. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  139079. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  139080. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  139081. 9,
  139082. };
  139083. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  139084. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139085. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139086. };
  139087. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  139088. 15, 13, 11, 9, 7, 5, 3, 1,
  139089. 0, 2, 4, 6, 8, 10, 12, 14,
  139090. 16,
  139091. };
  139092. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  139093. _vq_quantthresh__44cn1_sm_p8_2,
  139094. _vq_quantmap__44cn1_sm_p8_2,
  139095. 17,
  139096. 17
  139097. };
  139098. static static_codebook _44cn1_sm_p8_2 = {
  139099. 2, 289,
  139100. _vq_lengthlist__44cn1_sm_p8_2,
  139101. 1, -529530880, 1611661312, 5, 0,
  139102. _vq_quantlist__44cn1_sm_p8_2,
  139103. NULL,
  139104. &_vq_auxt__44cn1_sm_p8_2,
  139105. NULL,
  139106. 0
  139107. };
  139108. static long _huff_lengthlist__44cn1_sm_short[] = {
  139109. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  139110. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  139111. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  139112. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  139113. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  139114. 9,
  139115. };
  139116. static static_codebook _huff_book__44cn1_sm_short = {
  139117. 2, 81,
  139118. _huff_lengthlist__44cn1_sm_short,
  139119. 0, 0, 0, 0, 0,
  139120. NULL,
  139121. NULL,
  139122. NULL,
  139123. NULL,
  139124. 0
  139125. };
  139126. /*** End of inlined file: res_books_stereo.h ***/
  139127. /***** residue backends *********************************************/
  139128. static vorbis_info_residue0 _residue_44_low={
  139129. 0,-1, -1, 9,-1,
  139130. /* 0 1 2 3 4 5 6 7 */
  139131. {0},
  139132. {-1},
  139133. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  139134. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  139135. };
  139136. static vorbis_info_residue0 _residue_44_mid={
  139137. 0,-1, -1, 10,-1,
  139138. /* 0 1 2 3 4 5 6 7 8 */
  139139. {0},
  139140. {-1},
  139141. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  139142. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  139143. };
  139144. static vorbis_info_residue0 _residue_44_high={
  139145. 0,-1, -1, 10,-1,
  139146. /* 0 1 2 3 4 5 6 7 8 */
  139147. {0},
  139148. {-1},
  139149. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  139150. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  139151. };
  139152. static static_bookblock _resbook_44s_n1={
  139153. {
  139154. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  139155. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  139156. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  139157. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  139158. }
  139159. };
  139160. static static_bookblock _resbook_44sm_n1={
  139161. {
  139162. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  139163. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  139164. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  139165. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  139166. }
  139167. };
  139168. static static_bookblock _resbook_44s_0={
  139169. {
  139170. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  139171. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  139172. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  139173. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  139174. }
  139175. };
  139176. static static_bookblock _resbook_44sm_0={
  139177. {
  139178. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  139179. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  139180. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  139181. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  139182. }
  139183. };
  139184. static static_bookblock _resbook_44s_1={
  139185. {
  139186. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  139187. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  139188. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  139189. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  139190. }
  139191. };
  139192. static static_bookblock _resbook_44sm_1={
  139193. {
  139194. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  139195. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  139196. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  139197. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  139198. }
  139199. };
  139200. static static_bookblock _resbook_44s_2={
  139201. {
  139202. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  139203. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  139204. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  139205. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  139206. }
  139207. };
  139208. static static_bookblock _resbook_44s_3={
  139209. {
  139210. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  139211. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  139212. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  139213. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  139214. }
  139215. };
  139216. static static_bookblock _resbook_44s_4={
  139217. {
  139218. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  139219. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  139220. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  139221. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  139222. }
  139223. };
  139224. static static_bookblock _resbook_44s_5={
  139225. {
  139226. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  139227. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  139228. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  139229. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  139230. }
  139231. };
  139232. static static_bookblock _resbook_44s_6={
  139233. {
  139234. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  139235. {0,0,&_44c6_s_p4_0},
  139236. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  139237. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  139238. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  139239. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  139240. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  139241. }
  139242. };
  139243. static static_bookblock _resbook_44s_7={
  139244. {
  139245. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  139246. {0,0,&_44c7_s_p4_0},
  139247. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  139248. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  139249. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  139250. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  139251. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  139252. }
  139253. };
  139254. static static_bookblock _resbook_44s_8={
  139255. {
  139256. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  139257. {0,0,&_44c8_s_p4_0},
  139258. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  139259. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  139260. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  139261. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  139262. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  139263. }
  139264. };
  139265. static static_bookblock _resbook_44s_9={
  139266. {
  139267. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  139268. {0,0,&_44c9_s_p4_0},
  139269. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  139270. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  139271. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  139272. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  139273. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  139274. }
  139275. };
  139276. static vorbis_residue_template _res_44s_n1[]={
  139277. {2,0, &_residue_44_low,
  139278. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  139279. &_resbook_44s_n1,&_resbook_44sm_n1},
  139280. {2,0, &_residue_44_low,
  139281. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  139282. &_resbook_44s_n1,&_resbook_44sm_n1}
  139283. };
  139284. static vorbis_residue_template _res_44s_0[]={
  139285. {2,0, &_residue_44_low,
  139286. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  139287. &_resbook_44s_0,&_resbook_44sm_0},
  139288. {2,0, &_residue_44_low,
  139289. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  139290. &_resbook_44s_0,&_resbook_44sm_0}
  139291. };
  139292. static vorbis_residue_template _res_44s_1[]={
  139293. {2,0, &_residue_44_low,
  139294. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  139295. &_resbook_44s_1,&_resbook_44sm_1},
  139296. {2,0, &_residue_44_low,
  139297. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  139298. &_resbook_44s_1,&_resbook_44sm_1}
  139299. };
  139300. static vorbis_residue_template _res_44s_2[]={
  139301. {2,0, &_residue_44_mid,
  139302. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  139303. &_resbook_44s_2,&_resbook_44s_2},
  139304. {2,0, &_residue_44_mid,
  139305. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  139306. &_resbook_44s_2,&_resbook_44s_2}
  139307. };
  139308. static vorbis_residue_template _res_44s_3[]={
  139309. {2,0, &_residue_44_mid,
  139310. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  139311. &_resbook_44s_3,&_resbook_44s_3},
  139312. {2,0, &_residue_44_mid,
  139313. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  139314. &_resbook_44s_3,&_resbook_44s_3}
  139315. };
  139316. static vorbis_residue_template _res_44s_4[]={
  139317. {2,0, &_residue_44_mid,
  139318. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  139319. &_resbook_44s_4,&_resbook_44s_4},
  139320. {2,0, &_residue_44_mid,
  139321. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  139322. &_resbook_44s_4,&_resbook_44s_4}
  139323. };
  139324. static vorbis_residue_template _res_44s_5[]={
  139325. {2,0, &_residue_44_mid,
  139326. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  139327. &_resbook_44s_5,&_resbook_44s_5},
  139328. {2,0, &_residue_44_mid,
  139329. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  139330. &_resbook_44s_5,&_resbook_44s_5}
  139331. };
  139332. static vorbis_residue_template _res_44s_6[]={
  139333. {2,0, &_residue_44_high,
  139334. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  139335. &_resbook_44s_6,&_resbook_44s_6},
  139336. {2,0, &_residue_44_high,
  139337. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  139338. &_resbook_44s_6,&_resbook_44s_6}
  139339. };
  139340. static vorbis_residue_template _res_44s_7[]={
  139341. {2,0, &_residue_44_high,
  139342. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  139343. &_resbook_44s_7,&_resbook_44s_7},
  139344. {2,0, &_residue_44_high,
  139345. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  139346. &_resbook_44s_7,&_resbook_44s_7}
  139347. };
  139348. static vorbis_residue_template _res_44s_8[]={
  139349. {2,0, &_residue_44_high,
  139350. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  139351. &_resbook_44s_8,&_resbook_44s_8},
  139352. {2,0, &_residue_44_high,
  139353. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  139354. &_resbook_44s_8,&_resbook_44s_8}
  139355. };
  139356. static vorbis_residue_template _res_44s_9[]={
  139357. {2,0, &_residue_44_high,
  139358. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  139359. &_resbook_44s_9,&_resbook_44s_9},
  139360. {2,0, &_residue_44_high,
  139361. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  139362. &_resbook_44s_9,&_resbook_44s_9}
  139363. };
  139364. static vorbis_mapping_template _mapres_template_44_stereo[]={
  139365. { _map_nominal, _res_44s_n1 }, /* -1 */
  139366. { _map_nominal, _res_44s_0 }, /* 0 */
  139367. { _map_nominal, _res_44s_1 }, /* 1 */
  139368. { _map_nominal, _res_44s_2 }, /* 2 */
  139369. { _map_nominal, _res_44s_3 }, /* 3 */
  139370. { _map_nominal, _res_44s_4 }, /* 4 */
  139371. { _map_nominal, _res_44s_5 }, /* 5 */
  139372. { _map_nominal, _res_44s_6 }, /* 6 */
  139373. { _map_nominal, _res_44s_7 }, /* 7 */
  139374. { _map_nominal, _res_44s_8 }, /* 8 */
  139375. { _map_nominal, _res_44s_9 }, /* 9 */
  139376. };
  139377. /*** End of inlined file: residue_44.h ***/
  139378. /*** Start of inlined file: psych_44.h ***/
  139379. /* preecho trigger settings *****************************************/
  139380. static vorbis_info_psy_global _psy_global_44[5]={
  139381. {8, /* lines per eighth octave */
  139382. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  139383. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  139384. -6.f,
  139385. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  139386. },
  139387. {8, /* lines per eighth octave */
  139388. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  139389. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  139390. -6.f,
  139391. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  139392. },
  139393. {8, /* lines per eighth octave */
  139394. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  139395. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  139396. -6.f,
  139397. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  139398. },
  139399. {8, /* lines per eighth octave */
  139400. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  139401. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  139402. -6.f,
  139403. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  139404. },
  139405. {8, /* lines per eighth octave */
  139406. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  139407. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  139408. -6.f,
  139409. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  139410. },
  139411. };
  139412. /* noise compander lookups * low, mid, high quality ****************/
  139413. static compandblock _psy_compand_44[6]={
  139414. /* sub-mode Z short */
  139415. {{
  139416. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  139417. 8, 9,10,11,12,13,14, 15, /* 15dB */
  139418. 16,17,18,19,20,21,22, 23, /* 23dB */
  139419. 24,25,26,27,28,29,30, 31, /* 31dB */
  139420. 32,33,34,35,36,37,38, 39, /* 39dB */
  139421. }},
  139422. /* mode_Z nominal short */
  139423. {{
  139424. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  139425. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  139426. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  139427. 15,16,17,17,17,18,18, 19, /* 31dB */
  139428. 19,19,20,21,22,23,24, 25, /* 39dB */
  139429. }},
  139430. /* mode A short */
  139431. {{
  139432. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  139433. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  139434. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  139435. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  139436. 11,12,13,14,15,16,17, 18, /* 39dB */
  139437. }},
  139438. /* sub-mode Z long */
  139439. {{
  139440. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  139441. 8, 9,10,11,12,13,14, 15, /* 15dB */
  139442. 16,17,18,19,20,21,22, 23, /* 23dB */
  139443. 24,25,26,27,28,29,30, 31, /* 31dB */
  139444. 32,33,34,35,36,37,38, 39, /* 39dB */
  139445. }},
  139446. /* mode_Z nominal long */
  139447. {{
  139448. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  139449. 8, 9,10,11,12,12,13, 13, /* 15dB */
  139450. 13,14,14,14,15,15,15, 15, /* 23dB */
  139451. 16,16,17,17,17,18,18, 19, /* 31dB */
  139452. 19,19,20,21,22,23,24, 25, /* 39dB */
  139453. }},
  139454. /* mode A long */
  139455. {{
  139456. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  139457. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  139458. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  139459. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  139460. 11,12,13,14,15,16,17, 18, /* 39dB */
  139461. }}
  139462. };
  139463. /* tonal masking curve level adjustments *************************/
  139464. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  139465. /* 63 125 250 500 1 2 4 8 16 */
  139466. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  139467. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  139468. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  139469. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  139470. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  139471. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  139472. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  139473. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  139474. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  139475. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  139476. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  139477. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  139478. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  139479. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  139480. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  139481. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  139482. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  139483. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  139484. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  139485. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  139486. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  139487. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  139488. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  139489. };
  139490. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  139491. /* 63 125 250 500 1 2 4 8 16 */
  139492. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  139493. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  139494. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  139495. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  139496. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  139497. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  139498. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  139499. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  139500. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  139501. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  139502. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  139503. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  139504. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  139505. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  139506. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  139507. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  139508. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  139509. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  139510. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  139511. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  139512. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  139513. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  139514. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  139515. };
  139516. /* noise bias (transition block) */
  139517. static noise3 _psy_noisebias_trans[12]={
  139518. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  139519. /* -1 */
  139520. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  139521. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  139522. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  139523. /* 0
  139524. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  139525. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  139526. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  139527. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  139528. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  139529. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  139530. /* 1
  139531. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  139532. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  139533. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  139534. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  139535. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  139536. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  139537. /* 2
  139538. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  139539. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  139540. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  139541. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  139542. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  139543. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  139544. /* 3
  139545. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  139546. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  139547. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  139548. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  139549. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  139550. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  139551. /* 4
  139552. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  139553. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  139554. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  139555. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  139556. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  139557. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  139558. /* 5
  139559. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  139560. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  139561. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  139562. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  139563. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  139564. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  139565. /* 6
  139566. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  139567. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  139568. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  139569. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  139570. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  139571. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  139572. /* 7
  139573. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  139574. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  139575. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  139576. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  139577. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  139578. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  139579. /* 8
  139580. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  139581. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  139582. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  139583. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  139584. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  139585. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  139586. /* 9
  139587. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  139588. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  139589. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  139590. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  139591. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  139592. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  139593. /* 10 */
  139594. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  139595. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  139596. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  139597. };
  139598. /* noise bias (long block) */
  139599. static noise3 _psy_noisebias_long[12]={
  139600. /*63 125 250 500 1k 2k 4k 8k 16k*/
  139601. /* -1 */
  139602. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  139603. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  139604. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  139605. /* 0 */
  139606. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  139607. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  139608. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  139609. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  139610. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  139611. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  139612. /* 1 */
  139613. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  139614. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  139615. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  139616. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  139617. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  139618. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  139619. /* 2 */
  139620. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  139621. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  139622. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  139623. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  139624. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  139625. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  139626. /* 3 */
  139627. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  139628. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  139629. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  139630. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  139631. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  139632. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  139633. /* 4 */
  139634. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  139635. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  139636. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  139637. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  139638. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  139639. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  139640. /* 5 */
  139641. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  139642. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  139643. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  139644. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  139645. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  139646. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  139647. /* 6 */
  139648. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  139649. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  139650. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  139651. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  139652. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  139653. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  139654. /* 7 */
  139655. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  139656. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  139657. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  139658. /* 8 */
  139659. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  139660. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  139661. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  139662. /* 9 */
  139663. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  139664. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  139665. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  139666. /* 10 */
  139667. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  139668. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  139669. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  139670. };
  139671. /* noise bias (impulse block) */
  139672. static noise3 _psy_noisebias_impulse[12]={
  139673. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  139674. /* -1 */
  139675. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  139676. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  139677. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  139678. /* 0 */
  139679. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  139680. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  139681. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  139682. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  139683. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  139684. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  139685. /* 1 */
  139686. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  139687. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  139688. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  139689. /* 2 */
  139690. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  139691. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  139692. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  139693. /* 3 */
  139694. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  139695. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  139696. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  139697. /* 4 */
  139698. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  139699. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  139700. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  139701. /* 5 */
  139702. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  139703. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  139704. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  139705. /* 6
  139706. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  139707. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  139708. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  139709. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  139710. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  139711. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  139712. /* 7 */
  139713. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  139714. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  139715. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  139716. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  139717. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  139718. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  139719. /* 8 */
  139720. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  139721. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  139722. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  139723. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  139724. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  139725. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  139726. /* 9 */
  139727. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  139728. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  139729. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  139730. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  139731. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  139732. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  139733. /* 10 */
  139734. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  139735. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  139736. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  139737. };
  139738. /* noise bias (padding block) */
  139739. static noise3 _psy_noisebias_padding[12]={
  139740. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  139741. /* -1 */
  139742. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  139743. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  139744. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  139745. /* 0 */
  139746. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  139747. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  139748. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  139749. /* 1 */
  139750. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  139751. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  139752. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  139753. /* 2 */
  139754. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  139755. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  139756. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  139757. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  139758. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  139759. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  139760. /* 3 */
  139761. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  139762. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  139763. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  139764. /* 4 */
  139765. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  139766. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  139767. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  139768. /* 5 */
  139769. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  139770. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  139771. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  139772. /* 6 */
  139773. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  139774. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  139775. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  139776. /* 7 */
  139777. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  139778. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  139779. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  139780. /* 8 */
  139781. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  139782. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  139783. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  139784. /* 9 */
  139785. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  139786. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  139787. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  139788. /* 10 */
  139789. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  139790. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  139791. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  139792. };
  139793. static noiseguard _psy_noiseguards_44[4]={
  139794. {3,3,15},
  139795. {3,3,15},
  139796. {10,10,100},
  139797. {10,10,100},
  139798. };
  139799. static int _psy_tone_suppress[12]={
  139800. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  139801. };
  139802. static int _psy_tone_0dB[12]={
  139803. 90,90,95,95,95,95,105,105,105,105,105,105,
  139804. };
  139805. static int _psy_noise_suppress[12]={
  139806. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  139807. };
  139808. static vorbis_info_psy _psy_info_template={
  139809. /* blockflag */
  139810. -1,
  139811. /* ath_adjatt, ath_maxatt */
  139812. -140.,-140.,
  139813. /* tonemask att boost/decay,suppr,curves */
  139814. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  139815. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  139816. 1, -0.f, .5f, .5f, 0,0,0,
  139817. /* noiseoffset*3, noisecompand, max_curve_dB */
  139818. {{-1},{-1},{-1}},{-1},105.f,
  139819. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  139820. 0,0,-1,-1,0.,
  139821. };
  139822. /* ath ****************/
  139823. static int _psy_ath_floater[12]={
  139824. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  139825. };
  139826. static int _psy_ath_abs[12]={
  139827. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  139828. };
  139829. /* stereo setup. These don't map directly to quality level, there's
  139830. an additional indirection as several of the below may be used in a
  139831. single bitmanaged stream
  139832. ****************/
  139833. /* various stereo possibilities */
  139834. /* stereo mode by base quality level */
  139835. static adj_stereo _psy_stereo_modes_44[12]={
  139836. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  139837. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  139838. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  139839. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  139840. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  139841. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  139842. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  139843. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  139844. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  139845. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  139846. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  139847. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  139848. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  139849. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  139850. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  139851. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  139852. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  139853. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  139854. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139855. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  139856. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  139857. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  139858. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  139859. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  139860. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  139861. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  139862. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  139863. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139864. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  139865. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  139866. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  139867. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  139868. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139869. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  139870. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139871. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  139872. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  139873. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139874. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  139875. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139876. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  139877. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  139878. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  139879. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139880. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  139881. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  139882. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139883. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  139884. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139885. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139886. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  139887. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  139888. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139889. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139890. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  139891. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139892. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  139893. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139894. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139895. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  139896. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  139897. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139898. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139899. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  139900. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139901. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  139902. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139903. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139904. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  139905. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  139906. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139907. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139908. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  139909. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139910. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  139911. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139912. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139913. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  139914. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139915. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  139916. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139917. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139918. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  139919. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139920. };
  139921. /* tone master attenuation by base quality mode and bitrate tweak */
  139922. static att3 _psy_tone_masteratt_44[12]={
  139923. {{ 35, 21, 9}, 0, 0}, /* -1 */
  139924. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  139925. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  139926. {{ 25, 12, 2}, 0, 0}, /* 1 */
  139927. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  139928. {{ 20, 9, -3}, 0, 0}, /* 2 */
  139929. {{ 20, 9, -4}, 0, 0}, /* 3 */
  139930. {{ 20, 9, -4}, 0, 0}, /* 4 */
  139931. {{ 20, 6, -6}, 0, 0}, /* 5 */
  139932. {{ 20, 3, -10}, 0, 0}, /* 6 */
  139933. {{ 18, 1, -14}, 0, 0}, /* 7 */
  139934. {{ 18, 0, -16}, 0, 0}, /* 8 */
  139935. {{ 18, -2, -16}, 0, 0}, /* 9 */
  139936. {{ 12, -2, -20}, 0, 0}, /* 10 */
  139937. };
  139938. /* lowpass by mode **************/
  139939. static double _psy_lowpass_44[12]={
  139940. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  139941. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  139942. };
  139943. /* noise normalization **********/
  139944. static int _noise_start_short_44[11]={
  139945. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  139946. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  139947. };
  139948. static int _noise_start_long_44[11]={
  139949. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  139950. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  139951. };
  139952. static int _noise_part_short_44[11]={
  139953. 8,8,8,8,8,8,8,8,8,8,8
  139954. };
  139955. static int _noise_part_long_44[11]={
  139956. 32,32,32,32,32,32,32,32,32,32,32
  139957. };
  139958. static double _noise_thresh_44[11]={
  139959. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  139960. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  139961. };
  139962. static double _noise_thresh_5only[2]={
  139963. .5,.5,
  139964. };
  139965. /*** End of inlined file: psych_44.h ***/
  139966. static double rate_mapping_44_stereo[12]={
  139967. 22500.,32000.,40000.,48000.,56000.,64000.,
  139968. 80000.,96000.,112000.,128000.,160000.,250001.
  139969. };
  139970. static double quality_mapping_44[12]={
  139971. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  139972. };
  139973. static int blocksize_short_44[11]={
  139974. 512,256,256,256,256,256,256,256,256,256,256
  139975. };
  139976. static int blocksize_long_44[11]={
  139977. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  139978. };
  139979. static double _psy_compand_short_mapping[12]={
  139980. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  139981. };
  139982. static double _psy_compand_long_mapping[12]={
  139983. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  139984. };
  139985. static double _global_mapping_44[12]={
  139986. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  139987. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  139988. };
  139989. static int _floor_short_mapping_44[11]={
  139990. 1,0,0,2,2,4,5,5,5,5,5
  139991. };
  139992. static int _floor_long_mapping_44[11]={
  139993. 8,7,7,7,7,7,7,7,7,7,7
  139994. };
  139995. ve_setup_data_template ve_setup_44_stereo={
  139996. 11,
  139997. rate_mapping_44_stereo,
  139998. quality_mapping_44,
  139999. 2,
  140000. 40000,
  140001. 50000,
  140002. blocksize_short_44,
  140003. blocksize_long_44,
  140004. _psy_tone_masteratt_44,
  140005. _psy_tone_0dB,
  140006. _psy_tone_suppress,
  140007. _vp_tonemask_adj_otherblock,
  140008. _vp_tonemask_adj_longblock,
  140009. _vp_tonemask_adj_otherblock,
  140010. _psy_noiseguards_44,
  140011. _psy_noisebias_impulse,
  140012. _psy_noisebias_padding,
  140013. _psy_noisebias_trans,
  140014. _psy_noisebias_long,
  140015. _psy_noise_suppress,
  140016. _psy_compand_44,
  140017. _psy_compand_short_mapping,
  140018. _psy_compand_long_mapping,
  140019. {_noise_start_short_44,_noise_start_long_44},
  140020. {_noise_part_short_44,_noise_part_long_44},
  140021. _noise_thresh_44,
  140022. _psy_ath_floater,
  140023. _psy_ath_abs,
  140024. _psy_lowpass_44,
  140025. _psy_global_44,
  140026. _global_mapping_44,
  140027. _psy_stereo_modes_44,
  140028. _floor_books,
  140029. _floor,
  140030. _floor_short_mapping_44,
  140031. _floor_long_mapping_44,
  140032. _mapres_template_44_stereo
  140033. };
  140034. /*** End of inlined file: setup_44.h ***/
  140035. /*** Start of inlined file: setup_44u.h ***/
  140036. /*** Start of inlined file: residue_44u.h ***/
  140037. /*** Start of inlined file: res_books_uncoupled.h ***/
  140038. static long _vq_quantlist__16u0__p1_0[] = {
  140039. 1,
  140040. 0,
  140041. 2,
  140042. };
  140043. static long _vq_lengthlist__16u0__p1_0[] = {
  140044. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  140045. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  140046. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  140047. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  140048. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  140049. 12,
  140050. };
  140051. static float _vq_quantthresh__16u0__p1_0[] = {
  140052. -0.5, 0.5,
  140053. };
  140054. static long _vq_quantmap__16u0__p1_0[] = {
  140055. 1, 0, 2,
  140056. };
  140057. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  140058. _vq_quantthresh__16u0__p1_0,
  140059. _vq_quantmap__16u0__p1_0,
  140060. 3,
  140061. 3
  140062. };
  140063. static static_codebook _16u0__p1_0 = {
  140064. 4, 81,
  140065. _vq_lengthlist__16u0__p1_0,
  140066. 1, -535822336, 1611661312, 2, 0,
  140067. _vq_quantlist__16u0__p1_0,
  140068. NULL,
  140069. &_vq_auxt__16u0__p1_0,
  140070. NULL,
  140071. 0
  140072. };
  140073. static long _vq_quantlist__16u0__p2_0[] = {
  140074. 1,
  140075. 0,
  140076. 2,
  140077. };
  140078. static long _vq_lengthlist__16u0__p2_0[] = {
  140079. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  140080. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  140081. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  140082. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  140083. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  140084. 8,
  140085. };
  140086. static float _vq_quantthresh__16u0__p2_0[] = {
  140087. -0.5, 0.5,
  140088. };
  140089. static long _vq_quantmap__16u0__p2_0[] = {
  140090. 1, 0, 2,
  140091. };
  140092. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  140093. _vq_quantthresh__16u0__p2_0,
  140094. _vq_quantmap__16u0__p2_0,
  140095. 3,
  140096. 3
  140097. };
  140098. static static_codebook _16u0__p2_0 = {
  140099. 4, 81,
  140100. _vq_lengthlist__16u0__p2_0,
  140101. 1, -535822336, 1611661312, 2, 0,
  140102. _vq_quantlist__16u0__p2_0,
  140103. NULL,
  140104. &_vq_auxt__16u0__p2_0,
  140105. NULL,
  140106. 0
  140107. };
  140108. static long _vq_quantlist__16u0__p3_0[] = {
  140109. 2,
  140110. 1,
  140111. 3,
  140112. 0,
  140113. 4,
  140114. };
  140115. static long _vq_lengthlist__16u0__p3_0[] = {
  140116. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  140117. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  140118. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  140119. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  140120. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  140121. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  140122. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  140123. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  140124. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  140125. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  140126. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  140127. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  140128. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  140129. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  140130. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  140131. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  140132. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  140133. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  140134. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  140135. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  140136. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  140137. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  140138. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  140139. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  140140. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  140141. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  140142. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  140143. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  140144. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  140145. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  140146. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  140147. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  140148. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  140149. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  140150. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  140151. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  140152. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  140153. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  140154. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  140155. 18,
  140156. };
  140157. static float _vq_quantthresh__16u0__p3_0[] = {
  140158. -1.5, -0.5, 0.5, 1.5,
  140159. };
  140160. static long _vq_quantmap__16u0__p3_0[] = {
  140161. 3, 1, 0, 2, 4,
  140162. };
  140163. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  140164. _vq_quantthresh__16u0__p3_0,
  140165. _vq_quantmap__16u0__p3_0,
  140166. 5,
  140167. 5
  140168. };
  140169. static static_codebook _16u0__p3_0 = {
  140170. 4, 625,
  140171. _vq_lengthlist__16u0__p3_0,
  140172. 1, -533725184, 1611661312, 3, 0,
  140173. _vq_quantlist__16u0__p3_0,
  140174. NULL,
  140175. &_vq_auxt__16u0__p3_0,
  140176. NULL,
  140177. 0
  140178. };
  140179. static long _vq_quantlist__16u0__p4_0[] = {
  140180. 2,
  140181. 1,
  140182. 3,
  140183. 0,
  140184. 4,
  140185. };
  140186. static long _vq_lengthlist__16u0__p4_0[] = {
  140187. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  140188. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  140189. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  140190. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  140191. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  140192. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  140193. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  140194. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  140195. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  140196. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  140197. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  140198. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  140199. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  140200. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  140201. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  140202. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  140203. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  140204. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  140205. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  140206. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  140207. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  140208. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  140209. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  140210. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  140211. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  140212. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  140213. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  140214. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  140215. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  140216. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  140217. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  140218. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  140219. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  140220. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  140221. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  140222. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  140223. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  140224. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  140225. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  140226. 11,
  140227. };
  140228. static float _vq_quantthresh__16u0__p4_0[] = {
  140229. -1.5, -0.5, 0.5, 1.5,
  140230. };
  140231. static long _vq_quantmap__16u0__p4_0[] = {
  140232. 3, 1, 0, 2, 4,
  140233. };
  140234. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  140235. _vq_quantthresh__16u0__p4_0,
  140236. _vq_quantmap__16u0__p4_0,
  140237. 5,
  140238. 5
  140239. };
  140240. static static_codebook _16u0__p4_0 = {
  140241. 4, 625,
  140242. _vq_lengthlist__16u0__p4_0,
  140243. 1, -533725184, 1611661312, 3, 0,
  140244. _vq_quantlist__16u0__p4_0,
  140245. NULL,
  140246. &_vq_auxt__16u0__p4_0,
  140247. NULL,
  140248. 0
  140249. };
  140250. static long _vq_quantlist__16u0__p5_0[] = {
  140251. 4,
  140252. 3,
  140253. 5,
  140254. 2,
  140255. 6,
  140256. 1,
  140257. 7,
  140258. 0,
  140259. 8,
  140260. };
  140261. static long _vq_lengthlist__16u0__p5_0[] = {
  140262. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  140263. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  140264. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  140265. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  140266. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  140267. 12,
  140268. };
  140269. static float _vq_quantthresh__16u0__p5_0[] = {
  140270. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140271. };
  140272. static long _vq_quantmap__16u0__p5_0[] = {
  140273. 7, 5, 3, 1, 0, 2, 4, 6,
  140274. 8,
  140275. };
  140276. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  140277. _vq_quantthresh__16u0__p5_0,
  140278. _vq_quantmap__16u0__p5_0,
  140279. 9,
  140280. 9
  140281. };
  140282. static static_codebook _16u0__p5_0 = {
  140283. 2, 81,
  140284. _vq_lengthlist__16u0__p5_0,
  140285. 1, -531628032, 1611661312, 4, 0,
  140286. _vq_quantlist__16u0__p5_0,
  140287. NULL,
  140288. &_vq_auxt__16u0__p5_0,
  140289. NULL,
  140290. 0
  140291. };
  140292. static long _vq_quantlist__16u0__p6_0[] = {
  140293. 6,
  140294. 5,
  140295. 7,
  140296. 4,
  140297. 8,
  140298. 3,
  140299. 9,
  140300. 2,
  140301. 10,
  140302. 1,
  140303. 11,
  140304. 0,
  140305. 12,
  140306. };
  140307. static long _vq_lengthlist__16u0__p6_0[] = {
  140308. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  140309. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  140310. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  140311. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  140312. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  140313. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  140314. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  140315. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  140316. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  140317. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  140318. 18, 0,19, 0, 0, 0, 0, 0, 0,
  140319. };
  140320. static float _vq_quantthresh__16u0__p6_0[] = {
  140321. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140322. 12.5, 17.5, 22.5, 27.5,
  140323. };
  140324. static long _vq_quantmap__16u0__p6_0[] = {
  140325. 11, 9, 7, 5, 3, 1, 0, 2,
  140326. 4, 6, 8, 10, 12,
  140327. };
  140328. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  140329. _vq_quantthresh__16u0__p6_0,
  140330. _vq_quantmap__16u0__p6_0,
  140331. 13,
  140332. 13
  140333. };
  140334. static static_codebook _16u0__p6_0 = {
  140335. 2, 169,
  140336. _vq_lengthlist__16u0__p6_0,
  140337. 1, -526516224, 1616117760, 4, 0,
  140338. _vq_quantlist__16u0__p6_0,
  140339. NULL,
  140340. &_vq_auxt__16u0__p6_0,
  140341. NULL,
  140342. 0
  140343. };
  140344. static long _vq_quantlist__16u0__p6_1[] = {
  140345. 2,
  140346. 1,
  140347. 3,
  140348. 0,
  140349. 4,
  140350. };
  140351. static long _vq_lengthlist__16u0__p6_1[] = {
  140352. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  140353. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  140354. };
  140355. static float _vq_quantthresh__16u0__p6_1[] = {
  140356. -1.5, -0.5, 0.5, 1.5,
  140357. };
  140358. static long _vq_quantmap__16u0__p6_1[] = {
  140359. 3, 1, 0, 2, 4,
  140360. };
  140361. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  140362. _vq_quantthresh__16u0__p6_1,
  140363. _vq_quantmap__16u0__p6_1,
  140364. 5,
  140365. 5
  140366. };
  140367. static static_codebook _16u0__p6_1 = {
  140368. 2, 25,
  140369. _vq_lengthlist__16u0__p6_1,
  140370. 1, -533725184, 1611661312, 3, 0,
  140371. _vq_quantlist__16u0__p6_1,
  140372. NULL,
  140373. &_vq_auxt__16u0__p6_1,
  140374. NULL,
  140375. 0
  140376. };
  140377. static long _vq_quantlist__16u0__p7_0[] = {
  140378. 1,
  140379. 0,
  140380. 2,
  140381. };
  140382. static long _vq_lengthlist__16u0__p7_0[] = {
  140383. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  140384. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  140385. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  140386. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  140387. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  140388. 7,
  140389. };
  140390. static float _vq_quantthresh__16u0__p7_0[] = {
  140391. -157.5, 157.5,
  140392. };
  140393. static long _vq_quantmap__16u0__p7_0[] = {
  140394. 1, 0, 2,
  140395. };
  140396. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  140397. _vq_quantthresh__16u0__p7_0,
  140398. _vq_quantmap__16u0__p7_0,
  140399. 3,
  140400. 3
  140401. };
  140402. static static_codebook _16u0__p7_0 = {
  140403. 4, 81,
  140404. _vq_lengthlist__16u0__p7_0,
  140405. 1, -518803456, 1628680192, 2, 0,
  140406. _vq_quantlist__16u0__p7_0,
  140407. NULL,
  140408. &_vq_auxt__16u0__p7_0,
  140409. NULL,
  140410. 0
  140411. };
  140412. static long _vq_quantlist__16u0__p7_1[] = {
  140413. 7,
  140414. 6,
  140415. 8,
  140416. 5,
  140417. 9,
  140418. 4,
  140419. 10,
  140420. 3,
  140421. 11,
  140422. 2,
  140423. 12,
  140424. 1,
  140425. 13,
  140426. 0,
  140427. 14,
  140428. };
  140429. static long _vq_lengthlist__16u0__p7_1[] = {
  140430. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  140431. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  140432. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  140433. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  140434. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  140435. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  140436. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140437. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140438. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140439. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140440. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140441. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140442. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140443. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140444. 10,
  140445. };
  140446. static float _vq_quantthresh__16u0__p7_1[] = {
  140447. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  140448. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  140449. };
  140450. static long _vq_quantmap__16u0__p7_1[] = {
  140451. 13, 11, 9, 7, 5, 3, 1, 0,
  140452. 2, 4, 6, 8, 10, 12, 14,
  140453. };
  140454. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  140455. _vq_quantthresh__16u0__p7_1,
  140456. _vq_quantmap__16u0__p7_1,
  140457. 15,
  140458. 15
  140459. };
  140460. static static_codebook _16u0__p7_1 = {
  140461. 2, 225,
  140462. _vq_lengthlist__16u0__p7_1,
  140463. 1, -520986624, 1620377600, 4, 0,
  140464. _vq_quantlist__16u0__p7_1,
  140465. NULL,
  140466. &_vq_auxt__16u0__p7_1,
  140467. NULL,
  140468. 0
  140469. };
  140470. static long _vq_quantlist__16u0__p7_2[] = {
  140471. 10,
  140472. 9,
  140473. 11,
  140474. 8,
  140475. 12,
  140476. 7,
  140477. 13,
  140478. 6,
  140479. 14,
  140480. 5,
  140481. 15,
  140482. 4,
  140483. 16,
  140484. 3,
  140485. 17,
  140486. 2,
  140487. 18,
  140488. 1,
  140489. 19,
  140490. 0,
  140491. 20,
  140492. };
  140493. static long _vq_lengthlist__16u0__p7_2[] = {
  140494. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  140495. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  140496. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  140497. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  140498. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  140499. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  140500. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  140501. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  140502. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  140503. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  140504. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  140505. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  140506. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  140507. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  140508. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  140509. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  140510. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  140511. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  140512. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  140513. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  140514. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  140515. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  140516. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  140517. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  140518. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  140519. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  140520. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  140521. 10,10,12,11,10,11,11,11,10,
  140522. };
  140523. static float _vq_quantthresh__16u0__p7_2[] = {
  140524. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  140525. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  140526. 6.5, 7.5, 8.5, 9.5,
  140527. };
  140528. static long _vq_quantmap__16u0__p7_2[] = {
  140529. 19, 17, 15, 13, 11, 9, 7, 5,
  140530. 3, 1, 0, 2, 4, 6, 8, 10,
  140531. 12, 14, 16, 18, 20,
  140532. };
  140533. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  140534. _vq_quantthresh__16u0__p7_2,
  140535. _vq_quantmap__16u0__p7_2,
  140536. 21,
  140537. 21
  140538. };
  140539. static static_codebook _16u0__p7_2 = {
  140540. 2, 441,
  140541. _vq_lengthlist__16u0__p7_2,
  140542. 1, -529268736, 1611661312, 5, 0,
  140543. _vq_quantlist__16u0__p7_2,
  140544. NULL,
  140545. &_vq_auxt__16u0__p7_2,
  140546. NULL,
  140547. 0
  140548. };
  140549. static long _huff_lengthlist__16u0__single[] = {
  140550. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  140551. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  140552. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  140553. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  140554. };
  140555. static static_codebook _huff_book__16u0__single = {
  140556. 2, 64,
  140557. _huff_lengthlist__16u0__single,
  140558. 0, 0, 0, 0, 0,
  140559. NULL,
  140560. NULL,
  140561. NULL,
  140562. NULL,
  140563. 0
  140564. };
  140565. static long _huff_lengthlist__16u1__long[] = {
  140566. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  140567. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  140568. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  140569. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  140570. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  140571. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  140572. 16,13,16,18,
  140573. };
  140574. static static_codebook _huff_book__16u1__long = {
  140575. 2, 100,
  140576. _huff_lengthlist__16u1__long,
  140577. 0, 0, 0, 0, 0,
  140578. NULL,
  140579. NULL,
  140580. NULL,
  140581. NULL,
  140582. 0
  140583. };
  140584. static long _vq_quantlist__16u1__p1_0[] = {
  140585. 1,
  140586. 0,
  140587. 2,
  140588. };
  140589. static long _vq_lengthlist__16u1__p1_0[] = {
  140590. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  140591. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  140592. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  140593. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  140594. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  140595. 11,
  140596. };
  140597. static float _vq_quantthresh__16u1__p1_0[] = {
  140598. -0.5, 0.5,
  140599. };
  140600. static long _vq_quantmap__16u1__p1_0[] = {
  140601. 1, 0, 2,
  140602. };
  140603. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  140604. _vq_quantthresh__16u1__p1_0,
  140605. _vq_quantmap__16u1__p1_0,
  140606. 3,
  140607. 3
  140608. };
  140609. static static_codebook _16u1__p1_0 = {
  140610. 4, 81,
  140611. _vq_lengthlist__16u1__p1_0,
  140612. 1, -535822336, 1611661312, 2, 0,
  140613. _vq_quantlist__16u1__p1_0,
  140614. NULL,
  140615. &_vq_auxt__16u1__p1_0,
  140616. NULL,
  140617. 0
  140618. };
  140619. static long _vq_quantlist__16u1__p2_0[] = {
  140620. 1,
  140621. 0,
  140622. 2,
  140623. };
  140624. static long _vq_lengthlist__16u1__p2_0[] = {
  140625. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  140626. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  140627. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  140628. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  140629. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  140630. 8,
  140631. };
  140632. static float _vq_quantthresh__16u1__p2_0[] = {
  140633. -0.5, 0.5,
  140634. };
  140635. static long _vq_quantmap__16u1__p2_0[] = {
  140636. 1, 0, 2,
  140637. };
  140638. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  140639. _vq_quantthresh__16u1__p2_0,
  140640. _vq_quantmap__16u1__p2_0,
  140641. 3,
  140642. 3
  140643. };
  140644. static static_codebook _16u1__p2_0 = {
  140645. 4, 81,
  140646. _vq_lengthlist__16u1__p2_0,
  140647. 1, -535822336, 1611661312, 2, 0,
  140648. _vq_quantlist__16u1__p2_0,
  140649. NULL,
  140650. &_vq_auxt__16u1__p2_0,
  140651. NULL,
  140652. 0
  140653. };
  140654. static long _vq_quantlist__16u1__p3_0[] = {
  140655. 2,
  140656. 1,
  140657. 3,
  140658. 0,
  140659. 4,
  140660. };
  140661. static long _vq_lengthlist__16u1__p3_0[] = {
  140662. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  140663. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  140664. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  140665. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  140666. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  140667. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  140668. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  140669. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  140670. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  140671. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  140672. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  140673. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  140674. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  140675. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  140676. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  140677. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  140678. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  140679. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  140680. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  140681. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  140682. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  140683. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  140684. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  140685. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  140686. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  140687. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  140688. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  140689. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  140690. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  140691. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  140692. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  140693. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  140694. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  140695. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  140696. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  140697. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  140698. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  140699. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  140700. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  140701. 16,
  140702. };
  140703. static float _vq_quantthresh__16u1__p3_0[] = {
  140704. -1.5, -0.5, 0.5, 1.5,
  140705. };
  140706. static long _vq_quantmap__16u1__p3_0[] = {
  140707. 3, 1, 0, 2, 4,
  140708. };
  140709. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  140710. _vq_quantthresh__16u1__p3_0,
  140711. _vq_quantmap__16u1__p3_0,
  140712. 5,
  140713. 5
  140714. };
  140715. static static_codebook _16u1__p3_0 = {
  140716. 4, 625,
  140717. _vq_lengthlist__16u1__p3_0,
  140718. 1, -533725184, 1611661312, 3, 0,
  140719. _vq_quantlist__16u1__p3_0,
  140720. NULL,
  140721. &_vq_auxt__16u1__p3_0,
  140722. NULL,
  140723. 0
  140724. };
  140725. static long _vq_quantlist__16u1__p4_0[] = {
  140726. 2,
  140727. 1,
  140728. 3,
  140729. 0,
  140730. 4,
  140731. };
  140732. static long _vq_lengthlist__16u1__p4_0[] = {
  140733. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  140734. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  140735. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  140736. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  140737. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  140738. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  140739. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  140740. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  140741. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  140742. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  140743. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  140744. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  140745. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  140746. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  140747. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  140748. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  140749. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  140750. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  140751. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  140752. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  140753. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  140754. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  140755. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  140756. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  140757. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  140758. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  140759. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  140760. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  140761. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  140762. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  140763. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  140764. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  140765. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  140766. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  140767. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  140768. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  140769. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  140770. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  140771. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  140772. 11,
  140773. };
  140774. static float _vq_quantthresh__16u1__p4_0[] = {
  140775. -1.5, -0.5, 0.5, 1.5,
  140776. };
  140777. static long _vq_quantmap__16u1__p4_0[] = {
  140778. 3, 1, 0, 2, 4,
  140779. };
  140780. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  140781. _vq_quantthresh__16u1__p4_0,
  140782. _vq_quantmap__16u1__p4_0,
  140783. 5,
  140784. 5
  140785. };
  140786. static static_codebook _16u1__p4_0 = {
  140787. 4, 625,
  140788. _vq_lengthlist__16u1__p4_0,
  140789. 1, -533725184, 1611661312, 3, 0,
  140790. _vq_quantlist__16u1__p4_0,
  140791. NULL,
  140792. &_vq_auxt__16u1__p4_0,
  140793. NULL,
  140794. 0
  140795. };
  140796. static long _vq_quantlist__16u1__p5_0[] = {
  140797. 4,
  140798. 3,
  140799. 5,
  140800. 2,
  140801. 6,
  140802. 1,
  140803. 7,
  140804. 0,
  140805. 8,
  140806. };
  140807. static long _vq_lengthlist__16u1__p5_0[] = {
  140808. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  140809. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  140810. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  140811. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  140812. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  140813. 13,
  140814. };
  140815. static float _vq_quantthresh__16u1__p5_0[] = {
  140816. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140817. };
  140818. static long _vq_quantmap__16u1__p5_0[] = {
  140819. 7, 5, 3, 1, 0, 2, 4, 6,
  140820. 8,
  140821. };
  140822. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  140823. _vq_quantthresh__16u1__p5_0,
  140824. _vq_quantmap__16u1__p5_0,
  140825. 9,
  140826. 9
  140827. };
  140828. static static_codebook _16u1__p5_0 = {
  140829. 2, 81,
  140830. _vq_lengthlist__16u1__p5_0,
  140831. 1, -531628032, 1611661312, 4, 0,
  140832. _vq_quantlist__16u1__p5_0,
  140833. NULL,
  140834. &_vq_auxt__16u1__p5_0,
  140835. NULL,
  140836. 0
  140837. };
  140838. static long _vq_quantlist__16u1__p6_0[] = {
  140839. 4,
  140840. 3,
  140841. 5,
  140842. 2,
  140843. 6,
  140844. 1,
  140845. 7,
  140846. 0,
  140847. 8,
  140848. };
  140849. static long _vq_lengthlist__16u1__p6_0[] = {
  140850. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  140851. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  140852. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  140853. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  140854. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  140855. 11,
  140856. };
  140857. static float _vq_quantthresh__16u1__p6_0[] = {
  140858. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140859. };
  140860. static long _vq_quantmap__16u1__p6_0[] = {
  140861. 7, 5, 3, 1, 0, 2, 4, 6,
  140862. 8,
  140863. };
  140864. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  140865. _vq_quantthresh__16u1__p6_0,
  140866. _vq_quantmap__16u1__p6_0,
  140867. 9,
  140868. 9
  140869. };
  140870. static static_codebook _16u1__p6_0 = {
  140871. 2, 81,
  140872. _vq_lengthlist__16u1__p6_0,
  140873. 1, -531628032, 1611661312, 4, 0,
  140874. _vq_quantlist__16u1__p6_0,
  140875. NULL,
  140876. &_vq_auxt__16u1__p6_0,
  140877. NULL,
  140878. 0
  140879. };
  140880. static long _vq_quantlist__16u1__p7_0[] = {
  140881. 1,
  140882. 0,
  140883. 2,
  140884. };
  140885. static long _vq_lengthlist__16u1__p7_0[] = {
  140886. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  140887. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  140888. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  140889. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  140890. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  140891. 13,
  140892. };
  140893. static float _vq_quantthresh__16u1__p7_0[] = {
  140894. -5.5, 5.5,
  140895. };
  140896. static long _vq_quantmap__16u1__p7_0[] = {
  140897. 1, 0, 2,
  140898. };
  140899. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  140900. _vq_quantthresh__16u1__p7_0,
  140901. _vq_quantmap__16u1__p7_0,
  140902. 3,
  140903. 3
  140904. };
  140905. static static_codebook _16u1__p7_0 = {
  140906. 4, 81,
  140907. _vq_lengthlist__16u1__p7_0,
  140908. 1, -529137664, 1618345984, 2, 0,
  140909. _vq_quantlist__16u1__p7_0,
  140910. NULL,
  140911. &_vq_auxt__16u1__p7_0,
  140912. NULL,
  140913. 0
  140914. };
  140915. static long _vq_quantlist__16u1__p7_1[] = {
  140916. 5,
  140917. 4,
  140918. 6,
  140919. 3,
  140920. 7,
  140921. 2,
  140922. 8,
  140923. 1,
  140924. 9,
  140925. 0,
  140926. 10,
  140927. };
  140928. static long _vq_lengthlist__16u1__p7_1[] = {
  140929. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  140930. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  140931. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  140932. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  140933. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  140934. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  140935. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  140936. 8, 9, 9,10,10,10,10,10,10,
  140937. };
  140938. static float _vq_quantthresh__16u1__p7_1[] = {
  140939. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140940. 3.5, 4.5,
  140941. };
  140942. static long _vq_quantmap__16u1__p7_1[] = {
  140943. 9, 7, 5, 3, 1, 0, 2, 4,
  140944. 6, 8, 10,
  140945. };
  140946. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  140947. _vq_quantthresh__16u1__p7_1,
  140948. _vq_quantmap__16u1__p7_1,
  140949. 11,
  140950. 11
  140951. };
  140952. static static_codebook _16u1__p7_1 = {
  140953. 2, 121,
  140954. _vq_lengthlist__16u1__p7_1,
  140955. 1, -531365888, 1611661312, 4, 0,
  140956. _vq_quantlist__16u1__p7_1,
  140957. NULL,
  140958. &_vq_auxt__16u1__p7_1,
  140959. NULL,
  140960. 0
  140961. };
  140962. static long _vq_quantlist__16u1__p8_0[] = {
  140963. 5,
  140964. 4,
  140965. 6,
  140966. 3,
  140967. 7,
  140968. 2,
  140969. 8,
  140970. 1,
  140971. 9,
  140972. 0,
  140973. 10,
  140974. };
  140975. static long _vq_lengthlist__16u1__p8_0[] = {
  140976. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  140977. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  140978. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  140979. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  140980. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  140981. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  140982. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  140983. 13,14,14,15,15,16,16,15,16,
  140984. };
  140985. static float _vq_quantthresh__16u1__p8_0[] = {
  140986. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  140987. 38.5, 49.5,
  140988. };
  140989. static long _vq_quantmap__16u1__p8_0[] = {
  140990. 9, 7, 5, 3, 1, 0, 2, 4,
  140991. 6, 8, 10,
  140992. };
  140993. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  140994. _vq_quantthresh__16u1__p8_0,
  140995. _vq_quantmap__16u1__p8_0,
  140996. 11,
  140997. 11
  140998. };
  140999. static static_codebook _16u1__p8_0 = {
  141000. 2, 121,
  141001. _vq_lengthlist__16u1__p8_0,
  141002. 1, -524582912, 1618345984, 4, 0,
  141003. _vq_quantlist__16u1__p8_0,
  141004. NULL,
  141005. &_vq_auxt__16u1__p8_0,
  141006. NULL,
  141007. 0
  141008. };
  141009. static long _vq_quantlist__16u1__p8_1[] = {
  141010. 5,
  141011. 4,
  141012. 6,
  141013. 3,
  141014. 7,
  141015. 2,
  141016. 8,
  141017. 1,
  141018. 9,
  141019. 0,
  141020. 10,
  141021. };
  141022. static long _vq_lengthlist__16u1__p8_1[] = {
  141023. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  141024. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  141025. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  141026. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  141027. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  141028. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  141029. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  141030. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  141031. };
  141032. static float _vq_quantthresh__16u1__p8_1[] = {
  141033. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141034. 3.5, 4.5,
  141035. };
  141036. static long _vq_quantmap__16u1__p8_1[] = {
  141037. 9, 7, 5, 3, 1, 0, 2, 4,
  141038. 6, 8, 10,
  141039. };
  141040. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  141041. _vq_quantthresh__16u1__p8_1,
  141042. _vq_quantmap__16u1__p8_1,
  141043. 11,
  141044. 11
  141045. };
  141046. static static_codebook _16u1__p8_1 = {
  141047. 2, 121,
  141048. _vq_lengthlist__16u1__p8_1,
  141049. 1, -531365888, 1611661312, 4, 0,
  141050. _vq_quantlist__16u1__p8_1,
  141051. NULL,
  141052. &_vq_auxt__16u1__p8_1,
  141053. NULL,
  141054. 0
  141055. };
  141056. static long _vq_quantlist__16u1__p9_0[] = {
  141057. 7,
  141058. 6,
  141059. 8,
  141060. 5,
  141061. 9,
  141062. 4,
  141063. 10,
  141064. 3,
  141065. 11,
  141066. 2,
  141067. 12,
  141068. 1,
  141069. 13,
  141070. 0,
  141071. 14,
  141072. };
  141073. static long _vq_lengthlist__16u1__p9_0[] = {
  141074. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141075. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141076. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141077. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141078. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141079. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141080. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141081. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141082. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141083. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141084. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141085. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141086. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  141087. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  141088. 8,
  141089. };
  141090. static float _vq_quantthresh__16u1__p9_0[] = {
  141091. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  141092. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  141093. };
  141094. static long _vq_quantmap__16u1__p9_0[] = {
  141095. 13, 11, 9, 7, 5, 3, 1, 0,
  141096. 2, 4, 6, 8, 10, 12, 14,
  141097. };
  141098. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  141099. _vq_quantthresh__16u1__p9_0,
  141100. _vq_quantmap__16u1__p9_0,
  141101. 15,
  141102. 15
  141103. };
  141104. static static_codebook _16u1__p9_0 = {
  141105. 2, 225,
  141106. _vq_lengthlist__16u1__p9_0,
  141107. 1, -514071552, 1627381760, 4, 0,
  141108. _vq_quantlist__16u1__p9_0,
  141109. NULL,
  141110. &_vq_auxt__16u1__p9_0,
  141111. NULL,
  141112. 0
  141113. };
  141114. static long _vq_quantlist__16u1__p9_1[] = {
  141115. 7,
  141116. 6,
  141117. 8,
  141118. 5,
  141119. 9,
  141120. 4,
  141121. 10,
  141122. 3,
  141123. 11,
  141124. 2,
  141125. 12,
  141126. 1,
  141127. 13,
  141128. 0,
  141129. 14,
  141130. };
  141131. static long _vq_lengthlist__16u1__p9_1[] = {
  141132. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  141133. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  141134. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  141135. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  141136. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  141137. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  141138. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  141139. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  141140. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  141141. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141142. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141143. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141144. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141145. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141146. 9,
  141147. };
  141148. static float _vq_quantthresh__16u1__p9_1[] = {
  141149. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  141150. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  141151. };
  141152. static long _vq_quantmap__16u1__p9_1[] = {
  141153. 13, 11, 9, 7, 5, 3, 1, 0,
  141154. 2, 4, 6, 8, 10, 12, 14,
  141155. };
  141156. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  141157. _vq_quantthresh__16u1__p9_1,
  141158. _vq_quantmap__16u1__p9_1,
  141159. 15,
  141160. 15
  141161. };
  141162. static static_codebook _16u1__p9_1 = {
  141163. 2, 225,
  141164. _vq_lengthlist__16u1__p9_1,
  141165. 1, -522338304, 1620115456, 4, 0,
  141166. _vq_quantlist__16u1__p9_1,
  141167. NULL,
  141168. &_vq_auxt__16u1__p9_1,
  141169. NULL,
  141170. 0
  141171. };
  141172. static long _vq_quantlist__16u1__p9_2[] = {
  141173. 8,
  141174. 7,
  141175. 9,
  141176. 6,
  141177. 10,
  141178. 5,
  141179. 11,
  141180. 4,
  141181. 12,
  141182. 3,
  141183. 13,
  141184. 2,
  141185. 14,
  141186. 1,
  141187. 15,
  141188. 0,
  141189. 16,
  141190. };
  141191. static long _vq_lengthlist__16u1__p9_2[] = {
  141192. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  141193. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  141194. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  141195. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  141196. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  141197. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  141198. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  141199. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  141200. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  141201. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  141202. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  141203. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  141204. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  141205. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  141206. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  141207. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  141208. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  141209. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  141210. 10,
  141211. };
  141212. static float _vq_quantthresh__16u1__p9_2[] = {
  141213. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141214. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141215. };
  141216. static long _vq_quantmap__16u1__p9_2[] = {
  141217. 15, 13, 11, 9, 7, 5, 3, 1,
  141218. 0, 2, 4, 6, 8, 10, 12, 14,
  141219. 16,
  141220. };
  141221. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  141222. _vq_quantthresh__16u1__p9_2,
  141223. _vq_quantmap__16u1__p9_2,
  141224. 17,
  141225. 17
  141226. };
  141227. static static_codebook _16u1__p9_2 = {
  141228. 2, 289,
  141229. _vq_lengthlist__16u1__p9_2,
  141230. 1, -529530880, 1611661312, 5, 0,
  141231. _vq_quantlist__16u1__p9_2,
  141232. NULL,
  141233. &_vq_auxt__16u1__p9_2,
  141234. NULL,
  141235. 0
  141236. };
  141237. static long _huff_lengthlist__16u1__short[] = {
  141238. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  141239. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  141240. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  141241. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  141242. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  141243. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  141244. 16,16,16,16,
  141245. };
  141246. static static_codebook _huff_book__16u1__short = {
  141247. 2, 100,
  141248. _huff_lengthlist__16u1__short,
  141249. 0, 0, 0, 0, 0,
  141250. NULL,
  141251. NULL,
  141252. NULL,
  141253. NULL,
  141254. 0
  141255. };
  141256. static long _huff_lengthlist__16u2__long[] = {
  141257. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  141258. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  141259. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  141260. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  141261. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  141262. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  141263. 13,14,18,18,
  141264. };
  141265. static static_codebook _huff_book__16u2__long = {
  141266. 2, 100,
  141267. _huff_lengthlist__16u2__long,
  141268. 0, 0, 0, 0, 0,
  141269. NULL,
  141270. NULL,
  141271. NULL,
  141272. NULL,
  141273. 0
  141274. };
  141275. static long _huff_lengthlist__16u2__short[] = {
  141276. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  141277. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  141278. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  141279. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  141280. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  141281. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  141282. 16,16,16,16,
  141283. };
  141284. static static_codebook _huff_book__16u2__short = {
  141285. 2, 100,
  141286. _huff_lengthlist__16u2__short,
  141287. 0, 0, 0, 0, 0,
  141288. NULL,
  141289. NULL,
  141290. NULL,
  141291. NULL,
  141292. 0
  141293. };
  141294. static long _vq_quantlist__16u2_p1_0[] = {
  141295. 1,
  141296. 0,
  141297. 2,
  141298. };
  141299. static long _vq_lengthlist__16u2_p1_0[] = {
  141300. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  141301. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  141302. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  141303. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  141304. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  141305. 10,
  141306. };
  141307. static float _vq_quantthresh__16u2_p1_0[] = {
  141308. -0.5, 0.5,
  141309. };
  141310. static long _vq_quantmap__16u2_p1_0[] = {
  141311. 1, 0, 2,
  141312. };
  141313. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  141314. _vq_quantthresh__16u2_p1_0,
  141315. _vq_quantmap__16u2_p1_0,
  141316. 3,
  141317. 3
  141318. };
  141319. static static_codebook _16u2_p1_0 = {
  141320. 4, 81,
  141321. _vq_lengthlist__16u2_p1_0,
  141322. 1, -535822336, 1611661312, 2, 0,
  141323. _vq_quantlist__16u2_p1_0,
  141324. NULL,
  141325. &_vq_auxt__16u2_p1_0,
  141326. NULL,
  141327. 0
  141328. };
  141329. static long _vq_quantlist__16u2_p2_0[] = {
  141330. 2,
  141331. 1,
  141332. 3,
  141333. 0,
  141334. 4,
  141335. };
  141336. static long _vq_lengthlist__16u2_p2_0[] = {
  141337. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  141338. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  141339. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  141340. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  141341. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  141342. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  141343. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  141344. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  141345. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  141346. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  141347. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  141348. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  141349. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  141350. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  141351. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  141352. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  141353. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  141354. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  141355. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  141356. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  141357. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  141358. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  141359. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  141360. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  141361. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  141362. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  141363. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  141364. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  141365. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  141366. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  141367. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  141368. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  141369. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  141370. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  141371. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  141372. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  141373. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  141374. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  141375. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  141376. 13,
  141377. };
  141378. static float _vq_quantthresh__16u2_p2_0[] = {
  141379. -1.5, -0.5, 0.5, 1.5,
  141380. };
  141381. static long _vq_quantmap__16u2_p2_0[] = {
  141382. 3, 1, 0, 2, 4,
  141383. };
  141384. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  141385. _vq_quantthresh__16u2_p2_0,
  141386. _vq_quantmap__16u2_p2_0,
  141387. 5,
  141388. 5
  141389. };
  141390. static static_codebook _16u2_p2_0 = {
  141391. 4, 625,
  141392. _vq_lengthlist__16u2_p2_0,
  141393. 1, -533725184, 1611661312, 3, 0,
  141394. _vq_quantlist__16u2_p2_0,
  141395. NULL,
  141396. &_vq_auxt__16u2_p2_0,
  141397. NULL,
  141398. 0
  141399. };
  141400. static long _vq_quantlist__16u2_p3_0[] = {
  141401. 4,
  141402. 3,
  141403. 5,
  141404. 2,
  141405. 6,
  141406. 1,
  141407. 7,
  141408. 0,
  141409. 8,
  141410. };
  141411. static long _vq_lengthlist__16u2_p3_0[] = {
  141412. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  141413. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  141414. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  141415. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  141416. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  141417. 11,
  141418. };
  141419. static float _vq_quantthresh__16u2_p3_0[] = {
  141420. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141421. };
  141422. static long _vq_quantmap__16u2_p3_0[] = {
  141423. 7, 5, 3, 1, 0, 2, 4, 6,
  141424. 8,
  141425. };
  141426. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  141427. _vq_quantthresh__16u2_p3_0,
  141428. _vq_quantmap__16u2_p3_0,
  141429. 9,
  141430. 9
  141431. };
  141432. static static_codebook _16u2_p3_0 = {
  141433. 2, 81,
  141434. _vq_lengthlist__16u2_p3_0,
  141435. 1, -531628032, 1611661312, 4, 0,
  141436. _vq_quantlist__16u2_p3_0,
  141437. NULL,
  141438. &_vq_auxt__16u2_p3_0,
  141439. NULL,
  141440. 0
  141441. };
  141442. static long _vq_quantlist__16u2_p4_0[] = {
  141443. 8,
  141444. 7,
  141445. 9,
  141446. 6,
  141447. 10,
  141448. 5,
  141449. 11,
  141450. 4,
  141451. 12,
  141452. 3,
  141453. 13,
  141454. 2,
  141455. 14,
  141456. 1,
  141457. 15,
  141458. 0,
  141459. 16,
  141460. };
  141461. static long _vq_lengthlist__16u2_p4_0[] = {
  141462. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  141463. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  141464. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  141465. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  141466. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  141467. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  141468. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  141469. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  141470. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  141471. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  141472. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  141473. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  141474. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  141475. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  141476. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  141477. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  141478. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  141479. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  141480. 14,
  141481. };
  141482. static float _vq_quantthresh__16u2_p4_0[] = {
  141483. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141484. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141485. };
  141486. static long _vq_quantmap__16u2_p4_0[] = {
  141487. 15, 13, 11, 9, 7, 5, 3, 1,
  141488. 0, 2, 4, 6, 8, 10, 12, 14,
  141489. 16,
  141490. };
  141491. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  141492. _vq_quantthresh__16u2_p4_0,
  141493. _vq_quantmap__16u2_p4_0,
  141494. 17,
  141495. 17
  141496. };
  141497. static static_codebook _16u2_p4_0 = {
  141498. 2, 289,
  141499. _vq_lengthlist__16u2_p4_0,
  141500. 1, -529530880, 1611661312, 5, 0,
  141501. _vq_quantlist__16u2_p4_0,
  141502. NULL,
  141503. &_vq_auxt__16u2_p4_0,
  141504. NULL,
  141505. 0
  141506. };
  141507. static long _vq_quantlist__16u2_p5_0[] = {
  141508. 1,
  141509. 0,
  141510. 2,
  141511. };
  141512. static long _vq_lengthlist__16u2_p5_0[] = {
  141513. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  141514. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  141515. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  141516. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  141517. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  141518. 10,
  141519. };
  141520. static float _vq_quantthresh__16u2_p5_0[] = {
  141521. -5.5, 5.5,
  141522. };
  141523. static long _vq_quantmap__16u2_p5_0[] = {
  141524. 1, 0, 2,
  141525. };
  141526. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  141527. _vq_quantthresh__16u2_p5_0,
  141528. _vq_quantmap__16u2_p5_0,
  141529. 3,
  141530. 3
  141531. };
  141532. static static_codebook _16u2_p5_0 = {
  141533. 4, 81,
  141534. _vq_lengthlist__16u2_p5_0,
  141535. 1, -529137664, 1618345984, 2, 0,
  141536. _vq_quantlist__16u2_p5_0,
  141537. NULL,
  141538. &_vq_auxt__16u2_p5_0,
  141539. NULL,
  141540. 0
  141541. };
  141542. static long _vq_quantlist__16u2_p5_1[] = {
  141543. 5,
  141544. 4,
  141545. 6,
  141546. 3,
  141547. 7,
  141548. 2,
  141549. 8,
  141550. 1,
  141551. 9,
  141552. 0,
  141553. 10,
  141554. };
  141555. static long _vq_lengthlist__16u2_p5_1[] = {
  141556. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  141557. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  141558. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  141559. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  141560. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  141561. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  141562. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  141563. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  141564. };
  141565. static float _vq_quantthresh__16u2_p5_1[] = {
  141566. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141567. 3.5, 4.5,
  141568. };
  141569. static long _vq_quantmap__16u2_p5_1[] = {
  141570. 9, 7, 5, 3, 1, 0, 2, 4,
  141571. 6, 8, 10,
  141572. };
  141573. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  141574. _vq_quantthresh__16u2_p5_1,
  141575. _vq_quantmap__16u2_p5_1,
  141576. 11,
  141577. 11
  141578. };
  141579. static static_codebook _16u2_p5_1 = {
  141580. 2, 121,
  141581. _vq_lengthlist__16u2_p5_1,
  141582. 1, -531365888, 1611661312, 4, 0,
  141583. _vq_quantlist__16u2_p5_1,
  141584. NULL,
  141585. &_vq_auxt__16u2_p5_1,
  141586. NULL,
  141587. 0
  141588. };
  141589. static long _vq_quantlist__16u2_p6_0[] = {
  141590. 6,
  141591. 5,
  141592. 7,
  141593. 4,
  141594. 8,
  141595. 3,
  141596. 9,
  141597. 2,
  141598. 10,
  141599. 1,
  141600. 11,
  141601. 0,
  141602. 12,
  141603. };
  141604. static long _vq_lengthlist__16u2_p6_0[] = {
  141605. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  141606. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  141607. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  141608. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  141609. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  141610. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  141611. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  141612. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  141613. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  141614. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  141615. 12,13,13,14,14,14,14,15,15,
  141616. };
  141617. static float _vq_quantthresh__16u2_p6_0[] = {
  141618. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141619. 12.5, 17.5, 22.5, 27.5,
  141620. };
  141621. static long _vq_quantmap__16u2_p6_0[] = {
  141622. 11, 9, 7, 5, 3, 1, 0, 2,
  141623. 4, 6, 8, 10, 12,
  141624. };
  141625. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  141626. _vq_quantthresh__16u2_p6_0,
  141627. _vq_quantmap__16u2_p6_0,
  141628. 13,
  141629. 13
  141630. };
  141631. static static_codebook _16u2_p6_0 = {
  141632. 2, 169,
  141633. _vq_lengthlist__16u2_p6_0,
  141634. 1, -526516224, 1616117760, 4, 0,
  141635. _vq_quantlist__16u2_p6_0,
  141636. NULL,
  141637. &_vq_auxt__16u2_p6_0,
  141638. NULL,
  141639. 0
  141640. };
  141641. static long _vq_quantlist__16u2_p6_1[] = {
  141642. 2,
  141643. 1,
  141644. 3,
  141645. 0,
  141646. 4,
  141647. };
  141648. static long _vq_lengthlist__16u2_p6_1[] = {
  141649. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  141650. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  141651. };
  141652. static float _vq_quantthresh__16u2_p6_1[] = {
  141653. -1.5, -0.5, 0.5, 1.5,
  141654. };
  141655. static long _vq_quantmap__16u2_p6_1[] = {
  141656. 3, 1, 0, 2, 4,
  141657. };
  141658. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  141659. _vq_quantthresh__16u2_p6_1,
  141660. _vq_quantmap__16u2_p6_1,
  141661. 5,
  141662. 5
  141663. };
  141664. static static_codebook _16u2_p6_1 = {
  141665. 2, 25,
  141666. _vq_lengthlist__16u2_p6_1,
  141667. 1, -533725184, 1611661312, 3, 0,
  141668. _vq_quantlist__16u2_p6_1,
  141669. NULL,
  141670. &_vq_auxt__16u2_p6_1,
  141671. NULL,
  141672. 0
  141673. };
  141674. static long _vq_quantlist__16u2_p7_0[] = {
  141675. 6,
  141676. 5,
  141677. 7,
  141678. 4,
  141679. 8,
  141680. 3,
  141681. 9,
  141682. 2,
  141683. 10,
  141684. 1,
  141685. 11,
  141686. 0,
  141687. 12,
  141688. };
  141689. static long _vq_lengthlist__16u2_p7_0[] = {
  141690. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  141691. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  141692. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  141693. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  141694. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  141695. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  141696. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  141697. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  141698. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  141699. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  141700. 12,13,13,13,14,14,14,15,14,
  141701. };
  141702. static float _vq_quantthresh__16u2_p7_0[] = {
  141703. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  141704. 27.5, 38.5, 49.5, 60.5,
  141705. };
  141706. static long _vq_quantmap__16u2_p7_0[] = {
  141707. 11, 9, 7, 5, 3, 1, 0, 2,
  141708. 4, 6, 8, 10, 12,
  141709. };
  141710. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  141711. _vq_quantthresh__16u2_p7_0,
  141712. _vq_quantmap__16u2_p7_0,
  141713. 13,
  141714. 13
  141715. };
  141716. static static_codebook _16u2_p7_0 = {
  141717. 2, 169,
  141718. _vq_lengthlist__16u2_p7_0,
  141719. 1, -523206656, 1618345984, 4, 0,
  141720. _vq_quantlist__16u2_p7_0,
  141721. NULL,
  141722. &_vq_auxt__16u2_p7_0,
  141723. NULL,
  141724. 0
  141725. };
  141726. static long _vq_quantlist__16u2_p7_1[] = {
  141727. 5,
  141728. 4,
  141729. 6,
  141730. 3,
  141731. 7,
  141732. 2,
  141733. 8,
  141734. 1,
  141735. 9,
  141736. 0,
  141737. 10,
  141738. };
  141739. static long _vq_lengthlist__16u2_p7_1[] = {
  141740. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  141741. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  141742. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  141743. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  141744. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  141745. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  141746. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  141747. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  141748. };
  141749. static float _vq_quantthresh__16u2_p7_1[] = {
  141750. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141751. 3.5, 4.5,
  141752. };
  141753. static long _vq_quantmap__16u2_p7_1[] = {
  141754. 9, 7, 5, 3, 1, 0, 2, 4,
  141755. 6, 8, 10,
  141756. };
  141757. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  141758. _vq_quantthresh__16u2_p7_1,
  141759. _vq_quantmap__16u2_p7_1,
  141760. 11,
  141761. 11
  141762. };
  141763. static static_codebook _16u2_p7_1 = {
  141764. 2, 121,
  141765. _vq_lengthlist__16u2_p7_1,
  141766. 1, -531365888, 1611661312, 4, 0,
  141767. _vq_quantlist__16u2_p7_1,
  141768. NULL,
  141769. &_vq_auxt__16u2_p7_1,
  141770. NULL,
  141771. 0
  141772. };
  141773. static long _vq_quantlist__16u2_p8_0[] = {
  141774. 7,
  141775. 6,
  141776. 8,
  141777. 5,
  141778. 9,
  141779. 4,
  141780. 10,
  141781. 3,
  141782. 11,
  141783. 2,
  141784. 12,
  141785. 1,
  141786. 13,
  141787. 0,
  141788. 14,
  141789. };
  141790. static long _vq_lengthlist__16u2_p8_0[] = {
  141791. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  141792. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  141793. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  141794. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  141795. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  141796. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  141797. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  141798. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  141799. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  141800. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  141801. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  141802. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  141803. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  141804. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  141805. 14,
  141806. };
  141807. static float _vq_quantthresh__16u2_p8_0[] = {
  141808. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  141809. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  141810. };
  141811. static long _vq_quantmap__16u2_p8_0[] = {
  141812. 13, 11, 9, 7, 5, 3, 1, 0,
  141813. 2, 4, 6, 8, 10, 12, 14,
  141814. };
  141815. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  141816. _vq_quantthresh__16u2_p8_0,
  141817. _vq_quantmap__16u2_p8_0,
  141818. 15,
  141819. 15
  141820. };
  141821. static static_codebook _16u2_p8_0 = {
  141822. 2, 225,
  141823. _vq_lengthlist__16u2_p8_0,
  141824. 1, -520986624, 1620377600, 4, 0,
  141825. _vq_quantlist__16u2_p8_0,
  141826. NULL,
  141827. &_vq_auxt__16u2_p8_0,
  141828. NULL,
  141829. 0
  141830. };
  141831. static long _vq_quantlist__16u2_p8_1[] = {
  141832. 10,
  141833. 9,
  141834. 11,
  141835. 8,
  141836. 12,
  141837. 7,
  141838. 13,
  141839. 6,
  141840. 14,
  141841. 5,
  141842. 15,
  141843. 4,
  141844. 16,
  141845. 3,
  141846. 17,
  141847. 2,
  141848. 18,
  141849. 1,
  141850. 19,
  141851. 0,
  141852. 20,
  141853. };
  141854. static long _vq_lengthlist__16u2_p8_1[] = {
  141855. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  141856. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  141857. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  141858. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  141859. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  141860. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  141861. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  141862. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  141863. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  141864. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  141865. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  141866. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  141867. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  141868. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  141869. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  141870. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  141871. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  141872. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  141873. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  141874. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  141875. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  141876. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  141877. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  141878. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  141879. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  141880. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  141881. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  141882. 11,11,10,11,11,11,10,11,11,
  141883. };
  141884. static float _vq_quantthresh__16u2_p8_1[] = {
  141885. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  141886. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  141887. 6.5, 7.5, 8.5, 9.5,
  141888. };
  141889. static long _vq_quantmap__16u2_p8_1[] = {
  141890. 19, 17, 15, 13, 11, 9, 7, 5,
  141891. 3, 1, 0, 2, 4, 6, 8, 10,
  141892. 12, 14, 16, 18, 20,
  141893. };
  141894. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  141895. _vq_quantthresh__16u2_p8_1,
  141896. _vq_quantmap__16u2_p8_1,
  141897. 21,
  141898. 21
  141899. };
  141900. static static_codebook _16u2_p8_1 = {
  141901. 2, 441,
  141902. _vq_lengthlist__16u2_p8_1,
  141903. 1, -529268736, 1611661312, 5, 0,
  141904. _vq_quantlist__16u2_p8_1,
  141905. NULL,
  141906. &_vq_auxt__16u2_p8_1,
  141907. NULL,
  141908. 0
  141909. };
  141910. static long _vq_quantlist__16u2_p9_0[] = {
  141911. 5586,
  141912. 4655,
  141913. 6517,
  141914. 3724,
  141915. 7448,
  141916. 2793,
  141917. 8379,
  141918. 1862,
  141919. 9310,
  141920. 931,
  141921. 10241,
  141922. 0,
  141923. 11172,
  141924. 5521,
  141925. 5651,
  141926. };
  141927. static long _vq_lengthlist__16u2_p9_0[] = {
  141928. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  141929. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141930. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141931. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141932. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141933. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141934. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141935. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141936. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141937. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141938. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141939. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141940. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  141941. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  141942. 5,
  141943. };
  141944. static float _vq_quantthresh__16u2_p9_0[] = {
  141945. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  141946. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  141947. };
  141948. static long _vq_quantmap__16u2_p9_0[] = {
  141949. 11, 9, 7, 5, 3, 1, 13, 0,
  141950. 14, 2, 4, 6, 8, 10, 12,
  141951. };
  141952. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  141953. _vq_quantthresh__16u2_p9_0,
  141954. _vq_quantmap__16u2_p9_0,
  141955. 15,
  141956. 15
  141957. };
  141958. static static_codebook _16u2_p9_0 = {
  141959. 2, 225,
  141960. _vq_lengthlist__16u2_p9_0,
  141961. 1, -510275072, 1611661312, 14, 0,
  141962. _vq_quantlist__16u2_p9_0,
  141963. NULL,
  141964. &_vq_auxt__16u2_p9_0,
  141965. NULL,
  141966. 0
  141967. };
  141968. static long _vq_quantlist__16u2_p9_1[] = {
  141969. 392,
  141970. 343,
  141971. 441,
  141972. 294,
  141973. 490,
  141974. 245,
  141975. 539,
  141976. 196,
  141977. 588,
  141978. 147,
  141979. 637,
  141980. 98,
  141981. 686,
  141982. 49,
  141983. 735,
  141984. 0,
  141985. 784,
  141986. 388,
  141987. 396,
  141988. };
  141989. static long _vq_lengthlist__16u2_p9_1[] = {
  141990. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  141991. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  141992. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  141993. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  141994. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  141995. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  141996. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141997. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  141998. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  141999. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  142000. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  142001. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  142002. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  142003. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  142004. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  142005. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142006. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142007. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142008. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142009. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142010. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  142011. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  142012. 11,11,11,11,11,11,11, 5, 4,
  142013. };
  142014. static float _vq_quantthresh__16u2_p9_1[] = {
  142015. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  142016. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  142017. 318.5, 367.5,
  142018. };
  142019. static long _vq_quantmap__16u2_p9_1[] = {
  142020. 15, 13, 11, 9, 7, 5, 3, 1,
  142021. 17, 0, 18, 2, 4, 6, 8, 10,
  142022. 12, 14, 16,
  142023. };
  142024. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  142025. _vq_quantthresh__16u2_p9_1,
  142026. _vq_quantmap__16u2_p9_1,
  142027. 19,
  142028. 19
  142029. };
  142030. static static_codebook _16u2_p9_1 = {
  142031. 2, 361,
  142032. _vq_lengthlist__16u2_p9_1,
  142033. 1, -518488064, 1611661312, 10, 0,
  142034. _vq_quantlist__16u2_p9_1,
  142035. NULL,
  142036. &_vq_auxt__16u2_p9_1,
  142037. NULL,
  142038. 0
  142039. };
  142040. static long _vq_quantlist__16u2_p9_2[] = {
  142041. 24,
  142042. 23,
  142043. 25,
  142044. 22,
  142045. 26,
  142046. 21,
  142047. 27,
  142048. 20,
  142049. 28,
  142050. 19,
  142051. 29,
  142052. 18,
  142053. 30,
  142054. 17,
  142055. 31,
  142056. 16,
  142057. 32,
  142058. 15,
  142059. 33,
  142060. 14,
  142061. 34,
  142062. 13,
  142063. 35,
  142064. 12,
  142065. 36,
  142066. 11,
  142067. 37,
  142068. 10,
  142069. 38,
  142070. 9,
  142071. 39,
  142072. 8,
  142073. 40,
  142074. 7,
  142075. 41,
  142076. 6,
  142077. 42,
  142078. 5,
  142079. 43,
  142080. 4,
  142081. 44,
  142082. 3,
  142083. 45,
  142084. 2,
  142085. 46,
  142086. 1,
  142087. 47,
  142088. 0,
  142089. 48,
  142090. };
  142091. static long _vq_lengthlist__16u2_p9_2[] = {
  142092. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  142093. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  142094. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  142095. 11,
  142096. };
  142097. static float _vq_quantthresh__16u2_p9_2[] = {
  142098. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  142099. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  142100. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  142101. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  142102. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  142103. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  142104. };
  142105. static long _vq_quantmap__16u2_p9_2[] = {
  142106. 47, 45, 43, 41, 39, 37, 35, 33,
  142107. 31, 29, 27, 25, 23, 21, 19, 17,
  142108. 15, 13, 11, 9, 7, 5, 3, 1,
  142109. 0, 2, 4, 6, 8, 10, 12, 14,
  142110. 16, 18, 20, 22, 24, 26, 28, 30,
  142111. 32, 34, 36, 38, 40, 42, 44, 46,
  142112. 48,
  142113. };
  142114. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  142115. _vq_quantthresh__16u2_p9_2,
  142116. _vq_quantmap__16u2_p9_2,
  142117. 49,
  142118. 49
  142119. };
  142120. static static_codebook _16u2_p9_2 = {
  142121. 1, 49,
  142122. _vq_lengthlist__16u2_p9_2,
  142123. 1, -526909440, 1611661312, 6, 0,
  142124. _vq_quantlist__16u2_p9_2,
  142125. NULL,
  142126. &_vq_auxt__16u2_p9_2,
  142127. NULL,
  142128. 0
  142129. };
  142130. static long _vq_quantlist__8u0__p1_0[] = {
  142131. 1,
  142132. 0,
  142133. 2,
  142134. };
  142135. static long _vq_lengthlist__8u0__p1_0[] = {
  142136. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  142137. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  142138. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  142139. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  142140. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  142141. 11,
  142142. };
  142143. static float _vq_quantthresh__8u0__p1_0[] = {
  142144. -0.5, 0.5,
  142145. };
  142146. static long _vq_quantmap__8u0__p1_0[] = {
  142147. 1, 0, 2,
  142148. };
  142149. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  142150. _vq_quantthresh__8u0__p1_0,
  142151. _vq_quantmap__8u0__p1_0,
  142152. 3,
  142153. 3
  142154. };
  142155. static static_codebook _8u0__p1_0 = {
  142156. 4, 81,
  142157. _vq_lengthlist__8u0__p1_0,
  142158. 1, -535822336, 1611661312, 2, 0,
  142159. _vq_quantlist__8u0__p1_0,
  142160. NULL,
  142161. &_vq_auxt__8u0__p1_0,
  142162. NULL,
  142163. 0
  142164. };
  142165. static long _vq_quantlist__8u0__p2_0[] = {
  142166. 1,
  142167. 0,
  142168. 2,
  142169. };
  142170. static long _vq_lengthlist__8u0__p2_0[] = {
  142171. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  142172. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  142173. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  142174. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  142175. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  142176. 8,
  142177. };
  142178. static float _vq_quantthresh__8u0__p2_0[] = {
  142179. -0.5, 0.5,
  142180. };
  142181. static long _vq_quantmap__8u0__p2_0[] = {
  142182. 1, 0, 2,
  142183. };
  142184. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  142185. _vq_quantthresh__8u0__p2_0,
  142186. _vq_quantmap__8u0__p2_0,
  142187. 3,
  142188. 3
  142189. };
  142190. static static_codebook _8u0__p2_0 = {
  142191. 4, 81,
  142192. _vq_lengthlist__8u0__p2_0,
  142193. 1, -535822336, 1611661312, 2, 0,
  142194. _vq_quantlist__8u0__p2_0,
  142195. NULL,
  142196. &_vq_auxt__8u0__p2_0,
  142197. NULL,
  142198. 0
  142199. };
  142200. static long _vq_quantlist__8u0__p3_0[] = {
  142201. 2,
  142202. 1,
  142203. 3,
  142204. 0,
  142205. 4,
  142206. };
  142207. static long _vq_lengthlist__8u0__p3_0[] = {
  142208. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  142209. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  142210. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  142211. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  142212. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  142213. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  142214. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  142215. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  142216. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  142217. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  142218. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  142219. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  142220. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  142221. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  142222. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  142223. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  142224. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  142225. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  142226. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  142227. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  142228. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  142229. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  142230. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  142231. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  142232. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  142233. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  142234. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  142235. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  142236. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  142237. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  142238. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  142239. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  142240. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  142241. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  142242. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  142243. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  142244. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  142245. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  142246. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  142247. 16,
  142248. };
  142249. static float _vq_quantthresh__8u0__p3_0[] = {
  142250. -1.5, -0.5, 0.5, 1.5,
  142251. };
  142252. static long _vq_quantmap__8u0__p3_0[] = {
  142253. 3, 1, 0, 2, 4,
  142254. };
  142255. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  142256. _vq_quantthresh__8u0__p3_0,
  142257. _vq_quantmap__8u0__p3_0,
  142258. 5,
  142259. 5
  142260. };
  142261. static static_codebook _8u0__p3_0 = {
  142262. 4, 625,
  142263. _vq_lengthlist__8u0__p3_0,
  142264. 1, -533725184, 1611661312, 3, 0,
  142265. _vq_quantlist__8u0__p3_0,
  142266. NULL,
  142267. &_vq_auxt__8u0__p3_0,
  142268. NULL,
  142269. 0
  142270. };
  142271. static long _vq_quantlist__8u0__p4_0[] = {
  142272. 2,
  142273. 1,
  142274. 3,
  142275. 0,
  142276. 4,
  142277. };
  142278. static long _vq_lengthlist__8u0__p4_0[] = {
  142279. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  142280. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  142281. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  142282. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  142283. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  142284. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  142285. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  142286. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  142287. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  142288. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  142289. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  142290. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  142291. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  142292. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  142293. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  142294. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  142295. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  142296. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  142297. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  142298. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  142299. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  142300. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  142301. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  142302. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  142303. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  142304. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  142305. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  142306. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  142307. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  142308. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  142309. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  142310. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  142311. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  142312. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  142313. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  142314. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  142315. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  142316. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  142317. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  142318. 12,
  142319. };
  142320. static float _vq_quantthresh__8u0__p4_0[] = {
  142321. -1.5, -0.5, 0.5, 1.5,
  142322. };
  142323. static long _vq_quantmap__8u0__p4_0[] = {
  142324. 3, 1, 0, 2, 4,
  142325. };
  142326. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  142327. _vq_quantthresh__8u0__p4_0,
  142328. _vq_quantmap__8u0__p4_0,
  142329. 5,
  142330. 5
  142331. };
  142332. static static_codebook _8u0__p4_0 = {
  142333. 4, 625,
  142334. _vq_lengthlist__8u0__p4_0,
  142335. 1, -533725184, 1611661312, 3, 0,
  142336. _vq_quantlist__8u0__p4_0,
  142337. NULL,
  142338. &_vq_auxt__8u0__p4_0,
  142339. NULL,
  142340. 0
  142341. };
  142342. static long _vq_quantlist__8u0__p5_0[] = {
  142343. 4,
  142344. 3,
  142345. 5,
  142346. 2,
  142347. 6,
  142348. 1,
  142349. 7,
  142350. 0,
  142351. 8,
  142352. };
  142353. static long _vq_lengthlist__8u0__p5_0[] = {
  142354. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  142355. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  142356. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  142357. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142358. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  142359. 12,
  142360. };
  142361. static float _vq_quantthresh__8u0__p5_0[] = {
  142362. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142363. };
  142364. static long _vq_quantmap__8u0__p5_0[] = {
  142365. 7, 5, 3, 1, 0, 2, 4, 6,
  142366. 8,
  142367. };
  142368. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  142369. _vq_quantthresh__8u0__p5_0,
  142370. _vq_quantmap__8u0__p5_0,
  142371. 9,
  142372. 9
  142373. };
  142374. static static_codebook _8u0__p5_0 = {
  142375. 2, 81,
  142376. _vq_lengthlist__8u0__p5_0,
  142377. 1, -531628032, 1611661312, 4, 0,
  142378. _vq_quantlist__8u0__p5_0,
  142379. NULL,
  142380. &_vq_auxt__8u0__p5_0,
  142381. NULL,
  142382. 0
  142383. };
  142384. static long _vq_quantlist__8u0__p6_0[] = {
  142385. 6,
  142386. 5,
  142387. 7,
  142388. 4,
  142389. 8,
  142390. 3,
  142391. 9,
  142392. 2,
  142393. 10,
  142394. 1,
  142395. 11,
  142396. 0,
  142397. 12,
  142398. };
  142399. static long _vq_lengthlist__8u0__p6_0[] = {
  142400. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  142401. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  142402. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  142403. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  142404. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  142405. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  142406. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  142407. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  142408. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  142409. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  142410. 16, 0,15, 0,17, 0, 0, 0, 0,
  142411. };
  142412. static float _vq_quantthresh__8u0__p6_0[] = {
  142413. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142414. 12.5, 17.5, 22.5, 27.5,
  142415. };
  142416. static long _vq_quantmap__8u0__p6_0[] = {
  142417. 11, 9, 7, 5, 3, 1, 0, 2,
  142418. 4, 6, 8, 10, 12,
  142419. };
  142420. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  142421. _vq_quantthresh__8u0__p6_0,
  142422. _vq_quantmap__8u0__p6_0,
  142423. 13,
  142424. 13
  142425. };
  142426. static static_codebook _8u0__p6_0 = {
  142427. 2, 169,
  142428. _vq_lengthlist__8u0__p6_0,
  142429. 1, -526516224, 1616117760, 4, 0,
  142430. _vq_quantlist__8u0__p6_0,
  142431. NULL,
  142432. &_vq_auxt__8u0__p6_0,
  142433. NULL,
  142434. 0
  142435. };
  142436. static long _vq_quantlist__8u0__p6_1[] = {
  142437. 2,
  142438. 1,
  142439. 3,
  142440. 0,
  142441. 4,
  142442. };
  142443. static long _vq_lengthlist__8u0__p6_1[] = {
  142444. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  142445. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  142446. };
  142447. static float _vq_quantthresh__8u0__p6_1[] = {
  142448. -1.5, -0.5, 0.5, 1.5,
  142449. };
  142450. static long _vq_quantmap__8u0__p6_1[] = {
  142451. 3, 1, 0, 2, 4,
  142452. };
  142453. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  142454. _vq_quantthresh__8u0__p6_1,
  142455. _vq_quantmap__8u0__p6_1,
  142456. 5,
  142457. 5
  142458. };
  142459. static static_codebook _8u0__p6_1 = {
  142460. 2, 25,
  142461. _vq_lengthlist__8u0__p6_1,
  142462. 1, -533725184, 1611661312, 3, 0,
  142463. _vq_quantlist__8u0__p6_1,
  142464. NULL,
  142465. &_vq_auxt__8u0__p6_1,
  142466. NULL,
  142467. 0
  142468. };
  142469. static long _vq_quantlist__8u0__p7_0[] = {
  142470. 1,
  142471. 0,
  142472. 2,
  142473. };
  142474. static long _vq_lengthlist__8u0__p7_0[] = {
  142475. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142476. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142477. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142478. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142479. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142480. 7,
  142481. };
  142482. static float _vq_quantthresh__8u0__p7_0[] = {
  142483. -157.5, 157.5,
  142484. };
  142485. static long _vq_quantmap__8u0__p7_0[] = {
  142486. 1, 0, 2,
  142487. };
  142488. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  142489. _vq_quantthresh__8u0__p7_0,
  142490. _vq_quantmap__8u0__p7_0,
  142491. 3,
  142492. 3
  142493. };
  142494. static static_codebook _8u0__p7_0 = {
  142495. 4, 81,
  142496. _vq_lengthlist__8u0__p7_0,
  142497. 1, -518803456, 1628680192, 2, 0,
  142498. _vq_quantlist__8u0__p7_0,
  142499. NULL,
  142500. &_vq_auxt__8u0__p7_0,
  142501. NULL,
  142502. 0
  142503. };
  142504. static long _vq_quantlist__8u0__p7_1[] = {
  142505. 7,
  142506. 6,
  142507. 8,
  142508. 5,
  142509. 9,
  142510. 4,
  142511. 10,
  142512. 3,
  142513. 11,
  142514. 2,
  142515. 12,
  142516. 1,
  142517. 13,
  142518. 0,
  142519. 14,
  142520. };
  142521. static long _vq_lengthlist__8u0__p7_1[] = {
  142522. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  142523. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  142524. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  142525. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  142526. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  142527. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  142528. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142529. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142530. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142531. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142532. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142533. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142534. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  142535. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142536. 10,
  142537. };
  142538. static float _vq_quantthresh__8u0__p7_1[] = {
  142539. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  142540. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  142541. };
  142542. static long _vq_quantmap__8u0__p7_1[] = {
  142543. 13, 11, 9, 7, 5, 3, 1, 0,
  142544. 2, 4, 6, 8, 10, 12, 14,
  142545. };
  142546. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  142547. _vq_quantthresh__8u0__p7_1,
  142548. _vq_quantmap__8u0__p7_1,
  142549. 15,
  142550. 15
  142551. };
  142552. static static_codebook _8u0__p7_1 = {
  142553. 2, 225,
  142554. _vq_lengthlist__8u0__p7_1,
  142555. 1, -520986624, 1620377600, 4, 0,
  142556. _vq_quantlist__8u0__p7_1,
  142557. NULL,
  142558. &_vq_auxt__8u0__p7_1,
  142559. NULL,
  142560. 0
  142561. };
  142562. static long _vq_quantlist__8u0__p7_2[] = {
  142563. 10,
  142564. 9,
  142565. 11,
  142566. 8,
  142567. 12,
  142568. 7,
  142569. 13,
  142570. 6,
  142571. 14,
  142572. 5,
  142573. 15,
  142574. 4,
  142575. 16,
  142576. 3,
  142577. 17,
  142578. 2,
  142579. 18,
  142580. 1,
  142581. 19,
  142582. 0,
  142583. 20,
  142584. };
  142585. static long _vq_lengthlist__8u0__p7_2[] = {
  142586. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  142587. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  142588. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  142589. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  142590. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  142591. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  142592. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  142593. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  142594. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  142595. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  142596. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  142597. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  142598. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  142599. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  142600. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  142601. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  142602. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  142603. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  142604. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  142605. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  142606. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  142607. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  142608. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  142609. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  142610. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  142611. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  142612. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  142613. 11,12,11,11,11,10,10,11,11,
  142614. };
  142615. static float _vq_quantthresh__8u0__p7_2[] = {
  142616. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  142617. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  142618. 6.5, 7.5, 8.5, 9.5,
  142619. };
  142620. static long _vq_quantmap__8u0__p7_2[] = {
  142621. 19, 17, 15, 13, 11, 9, 7, 5,
  142622. 3, 1, 0, 2, 4, 6, 8, 10,
  142623. 12, 14, 16, 18, 20,
  142624. };
  142625. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  142626. _vq_quantthresh__8u0__p7_2,
  142627. _vq_quantmap__8u0__p7_2,
  142628. 21,
  142629. 21
  142630. };
  142631. static static_codebook _8u0__p7_2 = {
  142632. 2, 441,
  142633. _vq_lengthlist__8u0__p7_2,
  142634. 1, -529268736, 1611661312, 5, 0,
  142635. _vq_quantlist__8u0__p7_2,
  142636. NULL,
  142637. &_vq_auxt__8u0__p7_2,
  142638. NULL,
  142639. 0
  142640. };
  142641. static long _huff_lengthlist__8u0__single[] = {
  142642. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  142643. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  142644. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  142645. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  142646. };
  142647. static static_codebook _huff_book__8u0__single = {
  142648. 2, 64,
  142649. _huff_lengthlist__8u0__single,
  142650. 0, 0, 0, 0, 0,
  142651. NULL,
  142652. NULL,
  142653. NULL,
  142654. NULL,
  142655. 0
  142656. };
  142657. static long _vq_quantlist__8u1__p1_0[] = {
  142658. 1,
  142659. 0,
  142660. 2,
  142661. };
  142662. static long _vq_lengthlist__8u1__p1_0[] = {
  142663. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  142664. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  142665. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  142666. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  142667. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  142668. 10,
  142669. };
  142670. static float _vq_quantthresh__8u1__p1_0[] = {
  142671. -0.5, 0.5,
  142672. };
  142673. static long _vq_quantmap__8u1__p1_0[] = {
  142674. 1, 0, 2,
  142675. };
  142676. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  142677. _vq_quantthresh__8u1__p1_0,
  142678. _vq_quantmap__8u1__p1_0,
  142679. 3,
  142680. 3
  142681. };
  142682. static static_codebook _8u1__p1_0 = {
  142683. 4, 81,
  142684. _vq_lengthlist__8u1__p1_0,
  142685. 1, -535822336, 1611661312, 2, 0,
  142686. _vq_quantlist__8u1__p1_0,
  142687. NULL,
  142688. &_vq_auxt__8u1__p1_0,
  142689. NULL,
  142690. 0
  142691. };
  142692. static long _vq_quantlist__8u1__p2_0[] = {
  142693. 1,
  142694. 0,
  142695. 2,
  142696. };
  142697. static long _vq_lengthlist__8u1__p2_0[] = {
  142698. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  142699. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  142700. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  142701. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  142702. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  142703. 7,
  142704. };
  142705. static float _vq_quantthresh__8u1__p2_0[] = {
  142706. -0.5, 0.5,
  142707. };
  142708. static long _vq_quantmap__8u1__p2_0[] = {
  142709. 1, 0, 2,
  142710. };
  142711. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  142712. _vq_quantthresh__8u1__p2_0,
  142713. _vq_quantmap__8u1__p2_0,
  142714. 3,
  142715. 3
  142716. };
  142717. static static_codebook _8u1__p2_0 = {
  142718. 4, 81,
  142719. _vq_lengthlist__8u1__p2_0,
  142720. 1, -535822336, 1611661312, 2, 0,
  142721. _vq_quantlist__8u1__p2_0,
  142722. NULL,
  142723. &_vq_auxt__8u1__p2_0,
  142724. NULL,
  142725. 0
  142726. };
  142727. static long _vq_quantlist__8u1__p3_0[] = {
  142728. 2,
  142729. 1,
  142730. 3,
  142731. 0,
  142732. 4,
  142733. };
  142734. static long _vq_lengthlist__8u1__p3_0[] = {
  142735. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  142736. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  142737. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  142738. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  142739. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  142740. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  142741. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  142742. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  142743. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  142744. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  142745. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  142746. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  142747. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  142748. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  142749. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  142750. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  142751. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  142752. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  142753. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  142754. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  142755. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  142756. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  142757. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  142758. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  142759. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  142760. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  142761. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  142762. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  142763. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  142764. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  142765. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  142766. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  142767. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  142768. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  142769. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  142770. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  142771. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  142772. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  142773. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  142774. 16,
  142775. };
  142776. static float _vq_quantthresh__8u1__p3_0[] = {
  142777. -1.5, -0.5, 0.5, 1.5,
  142778. };
  142779. static long _vq_quantmap__8u1__p3_0[] = {
  142780. 3, 1, 0, 2, 4,
  142781. };
  142782. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  142783. _vq_quantthresh__8u1__p3_0,
  142784. _vq_quantmap__8u1__p3_0,
  142785. 5,
  142786. 5
  142787. };
  142788. static static_codebook _8u1__p3_0 = {
  142789. 4, 625,
  142790. _vq_lengthlist__8u1__p3_0,
  142791. 1, -533725184, 1611661312, 3, 0,
  142792. _vq_quantlist__8u1__p3_0,
  142793. NULL,
  142794. &_vq_auxt__8u1__p3_0,
  142795. NULL,
  142796. 0
  142797. };
  142798. static long _vq_quantlist__8u1__p4_0[] = {
  142799. 2,
  142800. 1,
  142801. 3,
  142802. 0,
  142803. 4,
  142804. };
  142805. static long _vq_lengthlist__8u1__p4_0[] = {
  142806. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  142807. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  142808. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  142809. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  142810. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  142811. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  142812. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  142813. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  142814. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  142815. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  142816. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  142817. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  142818. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  142819. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  142820. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  142821. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  142822. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  142823. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  142824. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  142825. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  142826. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  142827. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  142828. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  142829. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  142830. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  142831. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  142832. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  142833. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  142834. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  142835. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  142836. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  142837. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  142838. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  142839. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  142840. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  142841. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  142842. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  142843. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  142844. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  142845. 10,
  142846. };
  142847. static float _vq_quantthresh__8u1__p4_0[] = {
  142848. -1.5, -0.5, 0.5, 1.5,
  142849. };
  142850. static long _vq_quantmap__8u1__p4_0[] = {
  142851. 3, 1, 0, 2, 4,
  142852. };
  142853. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  142854. _vq_quantthresh__8u1__p4_0,
  142855. _vq_quantmap__8u1__p4_0,
  142856. 5,
  142857. 5
  142858. };
  142859. static static_codebook _8u1__p4_0 = {
  142860. 4, 625,
  142861. _vq_lengthlist__8u1__p4_0,
  142862. 1, -533725184, 1611661312, 3, 0,
  142863. _vq_quantlist__8u1__p4_0,
  142864. NULL,
  142865. &_vq_auxt__8u1__p4_0,
  142866. NULL,
  142867. 0
  142868. };
  142869. static long _vq_quantlist__8u1__p5_0[] = {
  142870. 4,
  142871. 3,
  142872. 5,
  142873. 2,
  142874. 6,
  142875. 1,
  142876. 7,
  142877. 0,
  142878. 8,
  142879. };
  142880. static long _vq_lengthlist__8u1__p5_0[] = {
  142881. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  142882. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  142883. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  142884. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  142885. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  142886. 13,
  142887. };
  142888. static float _vq_quantthresh__8u1__p5_0[] = {
  142889. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142890. };
  142891. static long _vq_quantmap__8u1__p5_0[] = {
  142892. 7, 5, 3, 1, 0, 2, 4, 6,
  142893. 8,
  142894. };
  142895. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  142896. _vq_quantthresh__8u1__p5_0,
  142897. _vq_quantmap__8u1__p5_0,
  142898. 9,
  142899. 9
  142900. };
  142901. static static_codebook _8u1__p5_0 = {
  142902. 2, 81,
  142903. _vq_lengthlist__8u1__p5_0,
  142904. 1, -531628032, 1611661312, 4, 0,
  142905. _vq_quantlist__8u1__p5_0,
  142906. NULL,
  142907. &_vq_auxt__8u1__p5_0,
  142908. NULL,
  142909. 0
  142910. };
  142911. static long _vq_quantlist__8u1__p6_0[] = {
  142912. 4,
  142913. 3,
  142914. 5,
  142915. 2,
  142916. 6,
  142917. 1,
  142918. 7,
  142919. 0,
  142920. 8,
  142921. };
  142922. static long _vq_lengthlist__8u1__p6_0[] = {
  142923. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  142924. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  142925. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  142926. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  142927. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  142928. 10,
  142929. };
  142930. static float _vq_quantthresh__8u1__p6_0[] = {
  142931. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142932. };
  142933. static long _vq_quantmap__8u1__p6_0[] = {
  142934. 7, 5, 3, 1, 0, 2, 4, 6,
  142935. 8,
  142936. };
  142937. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  142938. _vq_quantthresh__8u1__p6_0,
  142939. _vq_quantmap__8u1__p6_0,
  142940. 9,
  142941. 9
  142942. };
  142943. static static_codebook _8u1__p6_0 = {
  142944. 2, 81,
  142945. _vq_lengthlist__8u1__p6_0,
  142946. 1, -531628032, 1611661312, 4, 0,
  142947. _vq_quantlist__8u1__p6_0,
  142948. NULL,
  142949. &_vq_auxt__8u1__p6_0,
  142950. NULL,
  142951. 0
  142952. };
  142953. static long _vq_quantlist__8u1__p7_0[] = {
  142954. 1,
  142955. 0,
  142956. 2,
  142957. };
  142958. static long _vq_lengthlist__8u1__p7_0[] = {
  142959. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  142960. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  142961. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  142962. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  142963. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  142964. 11,
  142965. };
  142966. static float _vq_quantthresh__8u1__p7_0[] = {
  142967. -5.5, 5.5,
  142968. };
  142969. static long _vq_quantmap__8u1__p7_0[] = {
  142970. 1, 0, 2,
  142971. };
  142972. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  142973. _vq_quantthresh__8u1__p7_0,
  142974. _vq_quantmap__8u1__p7_0,
  142975. 3,
  142976. 3
  142977. };
  142978. static static_codebook _8u1__p7_0 = {
  142979. 4, 81,
  142980. _vq_lengthlist__8u1__p7_0,
  142981. 1, -529137664, 1618345984, 2, 0,
  142982. _vq_quantlist__8u1__p7_0,
  142983. NULL,
  142984. &_vq_auxt__8u1__p7_0,
  142985. NULL,
  142986. 0
  142987. };
  142988. static long _vq_quantlist__8u1__p7_1[] = {
  142989. 5,
  142990. 4,
  142991. 6,
  142992. 3,
  142993. 7,
  142994. 2,
  142995. 8,
  142996. 1,
  142997. 9,
  142998. 0,
  142999. 10,
  143000. };
  143001. static long _vq_lengthlist__8u1__p7_1[] = {
  143002. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  143003. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  143004. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  143005. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  143006. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  143007. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  143008. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  143009. 9, 9, 9, 9, 9,10,10,10,10,
  143010. };
  143011. static float _vq_quantthresh__8u1__p7_1[] = {
  143012. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143013. 3.5, 4.5,
  143014. };
  143015. static long _vq_quantmap__8u1__p7_1[] = {
  143016. 9, 7, 5, 3, 1, 0, 2, 4,
  143017. 6, 8, 10,
  143018. };
  143019. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  143020. _vq_quantthresh__8u1__p7_1,
  143021. _vq_quantmap__8u1__p7_1,
  143022. 11,
  143023. 11
  143024. };
  143025. static static_codebook _8u1__p7_1 = {
  143026. 2, 121,
  143027. _vq_lengthlist__8u1__p7_1,
  143028. 1, -531365888, 1611661312, 4, 0,
  143029. _vq_quantlist__8u1__p7_1,
  143030. NULL,
  143031. &_vq_auxt__8u1__p7_1,
  143032. NULL,
  143033. 0
  143034. };
  143035. static long _vq_quantlist__8u1__p8_0[] = {
  143036. 5,
  143037. 4,
  143038. 6,
  143039. 3,
  143040. 7,
  143041. 2,
  143042. 8,
  143043. 1,
  143044. 9,
  143045. 0,
  143046. 10,
  143047. };
  143048. static long _vq_lengthlist__8u1__p8_0[] = {
  143049. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  143050. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  143051. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  143052. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  143053. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  143054. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  143055. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  143056. 12,13,13,14,14,15,15,15,15,
  143057. };
  143058. static float _vq_quantthresh__8u1__p8_0[] = {
  143059. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  143060. 38.5, 49.5,
  143061. };
  143062. static long _vq_quantmap__8u1__p8_0[] = {
  143063. 9, 7, 5, 3, 1, 0, 2, 4,
  143064. 6, 8, 10,
  143065. };
  143066. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  143067. _vq_quantthresh__8u1__p8_0,
  143068. _vq_quantmap__8u1__p8_0,
  143069. 11,
  143070. 11
  143071. };
  143072. static static_codebook _8u1__p8_0 = {
  143073. 2, 121,
  143074. _vq_lengthlist__8u1__p8_0,
  143075. 1, -524582912, 1618345984, 4, 0,
  143076. _vq_quantlist__8u1__p8_0,
  143077. NULL,
  143078. &_vq_auxt__8u1__p8_0,
  143079. NULL,
  143080. 0
  143081. };
  143082. static long _vq_quantlist__8u1__p8_1[] = {
  143083. 5,
  143084. 4,
  143085. 6,
  143086. 3,
  143087. 7,
  143088. 2,
  143089. 8,
  143090. 1,
  143091. 9,
  143092. 0,
  143093. 10,
  143094. };
  143095. static long _vq_lengthlist__8u1__p8_1[] = {
  143096. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  143097. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  143098. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  143099. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  143100. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143101. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  143102. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  143103. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  143104. };
  143105. static float _vq_quantthresh__8u1__p8_1[] = {
  143106. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143107. 3.5, 4.5,
  143108. };
  143109. static long _vq_quantmap__8u1__p8_1[] = {
  143110. 9, 7, 5, 3, 1, 0, 2, 4,
  143111. 6, 8, 10,
  143112. };
  143113. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  143114. _vq_quantthresh__8u1__p8_1,
  143115. _vq_quantmap__8u1__p8_1,
  143116. 11,
  143117. 11
  143118. };
  143119. static static_codebook _8u1__p8_1 = {
  143120. 2, 121,
  143121. _vq_lengthlist__8u1__p8_1,
  143122. 1, -531365888, 1611661312, 4, 0,
  143123. _vq_quantlist__8u1__p8_1,
  143124. NULL,
  143125. &_vq_auxt__8u1__p8_1,
  143126. NULL,
  143127. 0
  143128. };
  143129. static long _vq_quantlist__8u1__p9_0[] = {
  143130. 7,
  143131. 6,
  143132. 8,
  143133. 5,
  143134. 9,
  143135. 4,
  143136. 10,
  143137. 3,
  143138. 11,
  143139. 2,
  143140. 12,
  143141. 1,
  143142. 13,
  143143. 0,
  143144. 14,
  143145. };
  143146. static long _vq_lengthlist__8u1__p9_0[] = {
  143147. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  143148. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  143149. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143150. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143151. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143152. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143153. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143154. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143155. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143156. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143157. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143158. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143159. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  143160. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143161. 10,
  143162. };
  143163. static float _vq_quantthresh__8u1__p9_0[] = {
  143164. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  143165. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  143166. };
  143167. static long _vq_quantmap__8u1__p9_0[] = {
  143168. 13, 11, 9, 7, 5, 3, 1, 0,
  143169. 2, 4, 6, 8, 10, 12, 14,
  143170. };
  143171. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  143172. _vq_quantthresh__8u1__p9_0,
  143173. _vq_quantmap__8u1__p9_0,
  143174. 15,
  143175. 15
  143176. };
  143177. static static_codebook _8u1__p9_0 = {
  143178. 2, 225,
  143179. _vq_lengthlist__8u1__p9_0,
  143180. 1, -514071552, 1627381760, 4, 0,
  143181. _vq_quantlist__8u1__p9_0,
  143182. NULL,
  143183. &_vq_auxt__8u1__p9_0,
  143184. NULL,
  143185. 0
  143186. };
  143187. static long _vq_quantlist__8u1__p9_1[] = {
  143188. 7,
  143189. 6,
  143190. 8,
  143191. 5,
  143192. 9,
  143193. 4,
  143194. 10,
  143195. 3,
  143196. 11,
  143197. 2,
  143198. 12,
  143199. 1,
  143200. 13,
  143201. 0,
  143202. 14,
  143203. };
  143204. static long _vq_lengthlist__8u1__p9_1[] = {
  143205. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  143206. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  143207. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  143208. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  143209. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  143210. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  143211. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  143212. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  143213. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  143214. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  143215. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  143216. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  143217. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  143218. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  143219. 13,
  143220. };
  143221. static float _vq_quantthresh__8u1__p9_1[] = {
  143222. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143223. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143224. };
  143225. static long _vq_quantmap__8u1__p9_1[] = {
  143226. 13, 11, 9, 7, 5, 3, 1, 0,
  143227. 2, 4, 6, 8, 10, 12, 14,
  143228. };
  143229. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  143230. _vq_quantthresh__8u1__p9_1,
  143231. _vq_quantmap__8u1__p9_1,
  143232. 15,
  143233. 15
  143234. };
  143235. static static_codebook _8u1__p9_1 = {
  143236. 2, 225,
  143237. _vq_lengthlist__8u1__p9_1,
  143238. 1, -522338304, 1620115456, 4, 0,
  143239. _vq_quantlist__8u1__p9_1,
  143240. NULL,
  143241. &_vq_auxt__8u1__p9_1,
  143242. NULL,
  143243. 0
  143244. };
  143245. static long _vq_quantlist__8u1__p9_2[] = {
  143246. 8,
  143247. 7,
  143248. 9,
  143249. 6,
  143250. 10,
  143251. 5,
  143252. 11,
  143253. 4,
  143254. 12,
  143255. 3,
  143256. 13,
  143257. 2,
  143258. 14,
  143259. 1,
  143260. 15,
  143261. 0,
  143262. 16,
  143263. };
  143264. static long _vq_lengthlist__8u1__p9_2[] = {
  143265. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143266. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  143267. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143268. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  143269. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  143270. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  143271. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  143272. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  143273. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  143274. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  143275. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  143276. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  143277. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  143278. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  143279. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  143280. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  143281. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143282. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143283. 10,
  143284. };
  143285. static float _vq_quantthresh__8u1__p9_2[] = {
  143286. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143287. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143288. };
  143289. static long _vq_quantmap__8u1__p9_2[] = {
  143290. 15, 13, 11, 9, 7, 5, 3, 1,
  143291. 0, 2, 4, 6, 8, 10, 12, 14,
  143292. 16,
  143293. };
  143294. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  143295. _vq_quantthresh__8u1__p9_2,
  143296. _vq_quantmap__8u1__p9_2,
  143297. 17,
  143298. 17
  143299. };
  143300. static static_codebook _8u1__p9_2 = {
  143301. 2, 289,
  143302. _vq_lengthlist__8u1__p9_2,
  143303. 1, -529530880, 1611661312, 5, 0,
  143304. _vq_quantlist__8u1__p9_2,
  143305. NULL,
  143306. &_vq_auxt__8u1__p9_2,
  143307. NULL,
  143308. 0
  143309. };
  143310. static long _huff_lengthlist__8u1__single[] = {
  143311. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  143312. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  143313. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  143314. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  143315. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  143316. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  143317. 13, 8, 8,15,
  143318. };
  143319. static static_codebook _huff_book__8u1__single = {
  143320. 2, 100,
  143321. _huff_lengthlist__8u1__single,
  143322. 0, 0, 0, 0, 0,
  143323. NULL,
  143324. NULL,
  143325. NULL,
  143326. NULL,
  143327. 0
  143328. };
  143329. static long _huff_lengthlist__44u0__long[] = {
  143330. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  143331. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  143332. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  143333. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  143334. };
  143335. static static_codebook _huff_book__44u0__long = {
  143336. 2, 64,
  143337. _huff_lengthlist__44u0__long,
  143338. 0, 0, 0, 0, 0,
  143339. NULL,
  143340. NULL,
  143341. NULL,
  143342. NULL,
  143343. 0
  143344. };
  143345. static long _vq_quantlist__44u0__p1_0[] = {
  143346. 1,
  143347. 0,
  143348. 2,
  143349. };
  143350. static long _vq_lengthlist__44u0__p1_0[] = {
  143351. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  143352. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  143353. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  143354. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  143355. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  143356. 13,
  143357. };
  143358. static float _vq_quantthresh__44u0__p1_0[] = {
  143359. -0.5, 0.5,
  143360. };
  143361. static long _vq_quantmap__44u0__p1_0[] = {
  143362. 1, 0, 2,
  143363. };
  143364. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  143365. _vq_quantthresh__44u0__p1_0,
  143366. _vq_quantmap__44u0__p1_0,
  143367. 3,
  143368. 3
  143369. };
  143370. static static_codebook _44u0__p1_0 = {
  143371. 4, 81,
  143372. _vq_lengthlist__44u0__p1_0,
  143373. 1, -535822336, 1611661312, 2, 0,
  143374. _vq_quantlist__44u0__p1_0,
  143375. NULL,
  143376. &_vq_auxt__44u0__p1_0,
  143377. NULL,
  143378. 0
  143379. };
  143380. static long _vq_quantlist__44u0__p2_0[] = {
  143381. 1,
  143382. 0,
  143383. 2,
  143384. };
  143385. static long _vq_lengthlist__44u0__p2_0[] = {
  143386. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  143387. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  143388. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  143389. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  143390. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  143391. 9,
  143392. };
  143393. static float _vq_quantthresh__44u0__p2_0[] = {
  143394. -0.5, 0.5,
  143395. };
  143396. static long _vq_quantmap__44u0__p2_0[] = {
  143397. 1, 0, 2,
  143398. };
  143399. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  143400. _vq_quantthresh__44u0__p2_0,
  143401. _vq_quantmap__44u0__p2_0,
  143402. 3,
  143403. 3
  143404. };
  143405. static static_codebook _44u0__p2_0 = {
  143406. 4, 81,
  143407. _vq_lengthlist__44u0__p2_0,
  143408. 1, -535822336, 1611661312, 2, 0,
  143409. _vq_quantlist__44u0__p2_0,
  143410. NULL,
  143411. &_vq_auxt__44u0__p2_0,
  143412. NULL,
  143413. 0
  143414. };
  143415. static long _vq_quantlist__44u0__p3_0[] = {
  143416. 2,
  143417. 1,
  143418. 3,
  143419. 0,
  143420. 4,
  143421. };
  143422. static long _vq_lengthlist__44u0__p3_0[] = {
  143423. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  143424. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  143425. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  143426. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  143427. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  143428. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  143429. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  143430. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  143431. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  143432. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  143433. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  143434. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  143435. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  143436. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  143437. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  143438. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  143439. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  143440. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  143441. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  143442. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  143443. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  143444. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  143445. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  143446. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  143447. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  143448. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  143449. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  143450. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  143451. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  143452. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  143453. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  143454. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  143455. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  143456. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  143457. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  143458. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  143459. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  143460. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  143461. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  143462. 19,
  143463. };
  143464. static float _vq_quantthresh__44u0__p3_0[] = {
  143465. -1.5, -0.5, 0.5, 1.5,
  143466. };
  143467. static long _vq_quantmap__44u0__p3_0[] = {
  143468. 3, 1, 0, 2, 4,
  143469. };
  143470. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  143471. _vq_quantthresh__44u0__p3_0,
  143472. _vq_quantmap__44u0__p3_0,
  143473. 5,
  143474. 5
  143475. };
  143476. static static_codebook _44u0__p3_0 = {
  143477. 4, 625,
  143478. _vq_lengthlist__44u0__p3_0,
  143479. 1, -533725184, 1611661312, 3, 0,
  143480. _vq_quantlist__44u0__p3_0,
  143481. NULL,
  143482. &_vq_auxt__44u0__p3_0,
  143483. NULL,
  143484. 0
  143485. };
  143486. static long _vq_quantlist__44u0__p4_0[] = {
  143487. 2,
  143488. 1,
  143489. 3,
  143490. 0,
  143491. 4,
  143492. };
  143493. static long _vq_lengthlist__44u0__p4_0[] = {
  143494. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  143495. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  143496. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  143497. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  143498. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  143499. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  143500. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  143501. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  143502. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  143503. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  143504. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  143505. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143506. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  143507. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  143508. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  143509. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  143510. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  143511. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  143512. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  143513. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  143514. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  143515. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  143516. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  143517. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  143518. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  143519. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  143520. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  143521. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  143522. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  143523. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  143524. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  143525. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  143526. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  143527. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  143528. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  143529. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  143530. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  143531. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  143532. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  143533. 12,
  143534. };
  143535. static float _vq_quantthresh__44u0__p4_0[] = {
  143536. -1.5, -0.5, 0.5, 1.5,
  143537. };
  143538. static long _vq_quantmap__44u0__p4_0[] = {
  143539. 3, 1, 0, 2, 4,
  143540. };
  143541. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  143542. _vq_quantthresh__44u0__p4_0,
  143543. _vq_quantmap__44u0__p4_0,
  143544. 5,
  143545. 5
  143546. };
  143547. static static_codebook _44u0__p4_0 = {
  143548. 4, 625,
  143549. _vq_lengthlist__44u0__p4_0,
  143550. 1, -533725184, 1611661312, 3, 0,
  143551. _vq_quantlist__44u0__p4_0,
  143552. NULL,
  143553. &_vq_auxt__44u0__p4_0,
  143554. NULL,
  143555. 0
  143556. };
  143557. static long _vq_quantlist__44u0__p5_0[] = {
  143558. 4,
  143559. 3,
  143560. 5,
  143561. 2,
  143562. 6,
  143563. 1,
  143564. 7,
  143565. 0,
  143566. 8,
  143567. };
  143568. static long _vq_lengthlist__44u0__p5_0[] = {
  143569. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143570. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  143571. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  143572. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143573. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  143574. 12,
  143575. };
  143576. static float _vq_quantthresh__44u0__p5_0[] = {
  143577. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143578. };
  143579. static long _vq_quantmap__44u0__p5_0[] = {
  143580. 7, 5, 3, 1, 0, 2, 4, 6,
  143581. 8,
  143582. };
  143583. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  143584. _vq_quantthresh__44u0__p5_0,
  143585. _vq_quantmap__44u0__p5_0,
  143586. 9,
  143587. 9
  143588. };
  143589. static static_codebook _44u0__p5_0 = {
  143590. 2, 81,
  143591. _vq_lengthlist__44u0__p5_0,
  143592. 1, -531628032, 1611661312, 4, 0,
  143593. _vq_quantlist__44u0__p5_0,
  143594. NULL,
  143595. &_vq_auxt__44u0__p5_0,
  143596. NULL,
  143597. 0
  143598. };
  143599. static long _vq_quantlist__44u0__p6_0[] = {
  143600. 6,
  143601. 5,
  143602. 7,
  143603. 4,
  143604. 8,
  143605. 3,
  143606. 9,
  143607. 2,
  143608. 10,
  143609. 1,
  143610. 11,
  143611. 0,
  143612. 12,
  143613. };
  143614. static long _vq_lengthlist__44u0__p6_0[] = {
  143615. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  143616. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  143617. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  143618. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  143619. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  143620. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  143621. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  143622. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  143623. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  143624. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  143625. 15,17,16,17,18,17,17,18, 0,
  143626. };
  143627. static float _vq_quantthresh__44u0__p6_0[] = {
  143628. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143629. 12.5, 17.5, 22.5, 27.5,
  143630. };
  143631. static long _vq_quantmap__44u0__p6_0[] = {
  143632. 11, 9, 7, 5, 3, 1, 0, 2,
  143633. 4, 6, 8, 10, 12,
  143634. };
  143635. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  143636. _vq_quantthresh__44u0__p6_0,
  143637. _vq_quantmap__44u0__p6_0,
  143638. 13,
  143639. 13
  143640. };
  143641. static static_codebook _44u0__p6_0 = {
  143642. 2, 169,
  143643. _vq_lengthlist__44u0__p6_0,
  143644. 1, -526516224, 1616117760, 4, 0,
  143645. _vq_quantlist__44u0__p6_0,
  143646. NULL,
  143647. &_vq_auxt__44u0__p6_0,
  143648. NULL,
  143649. 0
  143650. };
  143651. static long _vq_quantlist__44u0__p6_1[] = {
  143652. 2,
  143653. 1,
  143654. 3,
  143655. 0,
  143656. 4,
  143657. };
  143658. static long _vq_lengthlist__44u0__p6_1[] = {
  143659. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  143660. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  143661. };
  143662. static float _vq_quantthresh__44u0__p6_1[] = {
  143663. -1.5, -0.5, 0.5, 1.5,
  143664. };
  143665. static long _vq_quantmap__44u0__p6_1[] = {
  143666. 3, 1, 0, 2, 4,
  143667. };
  143668. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  143669. _vq_quantthresh__44u0__p6_1,
  143670. _vq_quantmap__44u0__p6_1,
  143671. 5,
  143672. 5
  143673. };
  143674. static static_codebook _44u0__p6_1 = {
  143675. 2, 25,
  143676. _vq_lengthlist__44u0__p6_1,
  143677. 1, -533725184, 1611661312, 3, 0,
  143678. _vq_quantlist__44u0__p6_1,
  143679. NULL,
  143680. &_vq_auxt__44u0__p6_1,
  143681. NULL,
  143682. 0
  143683. };
  143684. static long _vq_quantlist__44u0__p7_0[] = {
  143685. 2,
  143686. 1,
  143687. 3,
  143688. 0,
  143689. 4,
  143690. };
  143691. static long _vq_lengthlist__44u0__p7_0[] = {
  143692. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  143693. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143694. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143695. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143696. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143697. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143698. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143699. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  143700. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143701. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143702. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143703. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143704. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143705. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143706. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143707. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143708. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143709. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143710. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143711. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143712. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143713. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143714. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143715. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143716. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143717. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143718. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143719. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143720. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143721. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143722. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  143723. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143724. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143725. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143726. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143727. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143728. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143729. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143730. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143731. 10,
  143732. };
  143733. static float _vq_quantthresh__44u0__p7_0[] = {
  143734. -253.5, -84.5, 84.5, 253.5,
  143735. };
  143736. static long _vq_quantmap__44u0__p7_0[] = {
  143737. 3, 1, 0, 2, 4,
  143738. };
  143739. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  143740. _vq_quantthresh__44u0__p7_0,
  143741. _vq_quantmap__44u0__p7_0,
  143742. 5,
  143743. 5
  143744. };
  143745. static static_codebook _44u0__p7_0 = {
  143746. 4, 625,
  143747. _vq_lengthlist__44u0__p7_0,
  143748. 1, -518709248, 1626677248, 3, 0,
  143749. _vq_quantlist__44u0__p7_0,
  143750. NULL,
  143751. &_vq_auxt__44u0__p7_0,
  143752. NULL,
  143753. 0
  143754. };
  143755. static long _vq_quantlist__44u0__p7_1[] = {
  143756. 6,
  143757. 5,
  143758. 7,
  143759. 4,
  143760. 8,
  143761. 3,
  143762. 9,
  143763. 2,
  143764. 10,
  143765. 1,
  143766. 11,
  143767. 0,
  143768. 12,
  143769. };
  143770. static long _vq_lengthlist__44u0__p7_1[] = {
  143771. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  143772. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  143773. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  143774. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  143775. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  143776. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  143777. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  143778. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  143779. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  143780. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  143781. 15,15,15,15,15,15,15,15,15,
  143782. };
  143783. static float _vq_quantthresh__44u0__p7_1[] = {
  143784. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  143785. 32.5, 45.5, 58.5, 71.5,
  143786. };
  143787. static long _vq_quantmap__44u0__p7_1[] = {
  143788. 11, 9, 7, 5, 3, 1, 0, 2,
  143789. 4, 6, 8, 10, 12,
  143790. };
  143791. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  143792. _vq_quantthresh__44u0__p7_1,
  143793. _vq_quantmap__44u0__p7_1,
  143794. 13,
  143795. 13
  143796. };
  143797. static static_codebook _44u0__p7_1 = {
  143798. 2, 169,
  143799. _vq_lengthlist__44u0__p7_1,
  143800. 1, -523010048, 1618608128, 4, 0,
  143801. _vq_quantlist__44u0__p7_1,
  143802. NULL,
  143803. &_vq_auxt__44u0__p7_1,
  143804. NULL,
  143805. 0
  143806. };
  143807. static long _vq_quantlist__44u0__p7_2[] = {
  143808. 6,
  143809. 5,
  143810. 7,
  143811. 4,
  143812. 8,
  143813. 3,
  143814. 9,
  143815. 2,
  143816. 10,
  143817. 1,
  143818. 11,
  143819. 0,
  143820. 12,
  143821. };
  143822. static long _vq_lengthlist__44u0__p7_2[] = {
  143823. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  143824. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  143825. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  143826. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  143827. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  143828. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  143829. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  143830. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143831. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143832. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  143833. 9, 9, 9,10, 9, 9,10,10, 9,
  143834. };
  143835. static float _vq_quantthresh__44u0__p7_2[] = {
  143836. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  143837. 2.5, 3.5, 4.5, 5.5,
  143838. };
  143839. static long _vq_quantmap__44u0__p7_2[] = {
  143840. 11, 9, 7, 5, 3, 1, 0, 2,
  143841. 4, 6, 8, 10, 12,
  143842. };
  143843. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  143844. _vq_quantthresh__44u0__p7_2,
  143845. _vq_quantmap__44u0__p7_2,
  143846. 13,
  143847. 13
  143848. };
  143849. static static_codebook _44u0__p7_2 = {
  143850. 2, 169,
  143851. _vq_lengthlist__44u0__p7_2,
  143852. 1, -531103744, 1611661312, 4, 0,
  143853. _vq_quantlist__44u0__p7_2,
  143854. NULL,
  143855. &_vq_auxt__44u0__p7_2,
  143856. NULL,
  143857. 0
  143858. };
  143859. static long _huff_lengthlist__44u0__short[] = {
  143860. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  143861. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  143862. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  143863. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  143864. };
  143865. static static_codebook _huff_book__44u0__short = {
  143866. 2, 64,
  143867. _huff_lengthlist__44u0__short,
  143868. 0, 0, 0, 0, 0,
  143869. NULL,
  143870. NULL,
  143871. NULL,
  143872. NULL,
  143873. 0
  143874. };
  143875. static long _huff_lengthlist__44u1__long[] = {
  143876. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  143877. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  143878. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  143879. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  143880. };
  143881. static static_codebook _huff_book__44u1__long = {
  143882. 2, 64,
  143883. _huff_lengthlist__44u1__long,
  143884. 0, 0, 0, 0, 0,
  143885. NULL,
  143886. NULL,
  143887. NULL,
  143888. NULL,
  143889. 0
  143890. };
  143891. static long _vq_quantlist__44u1__p1_0[] = {
  143892. 1,
  143893. 0,
  143894. 2,
  143895. };
  143896. static long _vq_lengthlist__44u1__p1_0[] = {
  143897. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  143898. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  143899. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  143900. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  143901. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  143902. 13,
  143903. };
  143904. static float _vq_quantthresh__44u1__p1_0[] = {
  143905. -0.5, 0.5,
  143906. };
  143907. static long _vq_quantmap__44u1__p1_0[] = {
  143908. 1, 0, 2,
  143909. };
  143910. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  143911. _vq_quantthresh__44u1__p1_0,
  143912. _vq_quantmap__44u1__p1_0,
  143913. 3,
  143914. 3
  143915. };
  143916. static static_codebook _44u1__p1_0 = {
  143917. 4, 81,
  143918. _vq_lengthlist__44u1__p1_0,
  143919. 1, -535822336, 1611661312, 2, 0,
  143920. _vq_quantlist__44u1__p1_0,
  143921. NULL,
  143922. &_vq_auxt__44u1__p1_0,
  143923. NULL,
  143924. 0
  143925. };
  143926. static long _vq_quantlist__44u1__p2_0[] = {
  143927. 1,
  143928. 0,
  143929. 2,
  143930. };
  143931. static long _vq_lengthlist__44u1__p2_0[] = {
  143932. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  143933. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  143934. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  143935. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  143936. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  143937. 9,
  143938. };
  143939. static float _vq_quantthresh__44u1__p2_0[] = {
  143940. -0.5, 0.5,
  143941. };
  143942. static long _vq_quantmap__44u1__p2_0[] = {
  143943. 1, 0, 2,
  143944. };
  143945. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  143946. _vq_quantthresh__44u1__p2_0,
  143947. _vq_quantmap__44u1__p2_0,
  143948. 3,
  143949. 3
  143950. };
  143951. static static_codebook _44u1__p2_0 = {
  143952. 4, 81,
  143953. _vq_lengthlist__44u1__p2_0,
  143954. 1, -535822336, 1611661312, 2, 0,
  143955. _vq_quantlist__44u1__p2_0,
  143956. NULL,
  143957. &_vq_auxt__44u1__p2_0,
  143958. NULL,
  143959. 0
  143960. };
  143961. static long _vq_quantlist__44u1__p3_0[] = {
  143962. 2,
  143963. 1,
  143964. 3,
  143965. 0,
  143966. 4,
  143967. };
  143968. static long _vq_lengthlist__44u1__p3_0[] = {
  143969. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  143970. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  143971. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  143972. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  143973. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  143974. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  143975. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  143976. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  143977. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  143978. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  143979. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  143980. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  143981. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  143982. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  143983. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  143984. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  143985. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  143986. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  143987. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  143988. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  143989. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  143990. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  143991. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  143992. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  143993. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  143994. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  143995. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  143996. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  143997. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  143998. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  143999. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  144000. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  144001. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  144002. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  144003. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  144004. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  144005. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  144006. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  144007. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  144008. 19,
  144009. };
  144010. static float _vq_quantthresh__44u1__p3_0[] = {
  144011. -1.5, -0.5, 0.5, 1.5,
  144012. };
  144013. static long _vq_quantmap__44u1__p3_0[] = {
  144014. 3, 1, 0, 2, 4,
  144015. };
  144016. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  144017. _vq_quantthresh__44u1__p3_0,
  144018. _vq_quantmap__44u1__p3_0,
  144019. 5,
  144020. 5
  144021. };
  144022. static static_codebook _44u1__p3_0 = {
  144023. 4, 625,
  144024. _vq_lengthlist__44u1__p3_0,
  144025. 1, -533725184, 1611661312, 3, 0,
  144026. _vq_quantlist__44u1__p3_0,
  144027. NULL,
  144028. &_vq_auxt__44u1__p3_0,
  144029. NULL,
  144030. 0
  144031. };
  144032. static long _vq_quantlist__44u1__p4_0[] = {
  144033. 2,
  144034. 1,
  144035. 3,
  144036. 0,
  144037. 4,
  144038. };
  144039. static long _vq_lengthlist__44u1__p4_0[] = {
  144040. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  144041. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  144042. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  144043. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  144044. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  144045. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  144046. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  144047. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  144048. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  144049. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  144050. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  144051. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144052. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  144053. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  144054. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  144055. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  144056. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  144057. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  144058. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  144059. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  144060. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  144061. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  144062. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  144063. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  144064. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  144065. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  144066. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  144067. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  144068. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  144069. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  144070. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  144071. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  144072. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  144073. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  144074. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  144075. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  144076. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  144077. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  144078. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  144079. 12,
  144080. };
  144081. static float _vq_quantthresh__44u1__p4_0[] = {
  144082. -1.5, -0.5, 0.5, 1.5,
  144083. };
  144084. static long _vq_quantmap__44u1__p4_0[] = {
  144085. 3, 1, 0, 2, 4,
  144086. };
  144087. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  144088. _vq_quantthresh__44u1__p4_0,
  144089. _vq_quantmap__44u1__p4_0,
  144090. 5,
  144091. 5
  144092. };
  144093. static static_codebook _44u1__p4_0 = {
  144094. 4, 625,
  144095. _vq_lengthlist__44u1__p4_0,
  144096. 1, -533725184, 1611661312, 3, 0,
  144097. _vq_quantlist__44u1__p4_0,
  144098. NULL,
  144099. &_vq_auxt__44u1__p4_0,
  144100. NULL,
  144101. 0
  144102. };
  144103. static long _vq_quantlist__44u1__p5_0[] = {
  144104. 4,
  144105. 3,
  144106. 5,
  144107. 2,
  144108. 6,
  144109. 1,
  144110. 7,
  144111. 0,
  144112. 8,
  144113. };
  144114. static long _vq_lengthlist__44u1__p5_0[] = {
  144115. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  144116. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  144117. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  144118. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  144119. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  144120. 12,
  144121. };
  144122. static float _vq_quantthresh__44u1__p5_0[] = {
  144123. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144124. };
  144125. static long _vq_quantmap__44u1__p5_0[] = {
  144126. 7, 5, 3, 1, 0, 2, 4, 6,
  144127. 8,
  144128. };
  144129. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  144130. _vq_quantthresh__44u1__p5_0,
  144131. _vq_quantmap__44u1__p5_0,
  144132. 9,
  144133. 9
  144134. };
  144135. static static_codebook _44u1__p5_0 = {
  144136. 2, 81,
  144137. _vq_lengthlist__44u1__p5_0,
  144138. 1, -531628032, 1611661312, 4, 0,
  144139. _vq_quantlist__44u1__p5_0,
  144140. NULL,
  144141. &_vq_auxt__44u1__p5_0,
  144142. NULL,
  144143. 0
  144144. };
  144145. static long _vq_quantlist__44u1__p6_0[] = {
  144146. 6,
  144147. 5,
  144148. 7,
  144149. 4,
  144150. 8,
  144151. 3,
  144152. 9,
  144153. 2,
  144154. 10,
  144155. 1,
  144156. 11,
  144157. 0,
  144158. 12,
  144159. };
  144160. static long _vq_lengthlist__44u1__p6_0[] = {
  144161. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  144162. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  144163. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  144164. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  144165. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  144166. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  144167. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  144168. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  144169. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  144170. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  144171. 15,17,16,17,18,17,17,18, 0,
  144172. };
  144173. static float _vq_quantthresh__44u1__p6_0[] = {
  144174. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144175. 12.5, 17.5, 22.5, 27.5,
  144176. };
  144177. static long _vq_quantmap__44u1__p6_0[] = {
  144178. 11, 9, 7, 5, 3, 1, 0, 2,
  144179. 4, 6, 8, 10, 12,
  144180. };
  144181. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  144182. _vq_quantthresh__44u1__p6_0,
  144183. _vq_quantmap__44u1__p6_0,
  144184. 13,
  144185. 13
  144186. };
  144187. static static_codebook _44u1__p6_0 = {
  144188. 2, 169,
  144189. _vq_lengthlist__44u1__p6_0,
  144190. 1, -526516224, 1616117760, 4, 0,
  144191. _vq_quantlist__44u1__p6_0,
  144192. NULL,
  144193. &_vq_auxt__44u1__p6_0,
  144194. NULL,
  144195. 0
  144196. };
  144197. static long _vq_quantlist__44u1__p6_1[] = {
  144198. 2,
  144199. 1,
  144200. 3,
  144201. 0,
  144202. 4,
  144203. };
  144204. static long _vq_lengthlist__44u1__p6_1[] = {
  144205. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  144206. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  144207. };
  144208. static float _vq_quantthresh__44u1__p6_1[] = {
  144209. -1.5, -0.5, 0.5, 1.5,
  144210. };
  144211. static long _vq_quantmap__44u1__p6_1[] = {
  144212. 3, 1, 0, 2, 4,
  144213. };
  144214. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  144215. _vq_quantthresh__44u1__p6_1,
  144216. _vq_quantmap__44u1__p6_1,
  144217. 5,
  144218. 5
  144219. };
  144220. static static_codebook _44u1__p6_1 = {
  144221. 2, 25,
  144222. _vq_lengthlist__44u1__p6_1,
  144223. 1, -533725184, 1611661312, 3, 0,
  144224. _vq_quantlist__44u1__p6_1,
  144225. NULL,
  144226. &_vq_auxt__44u1__p6_1,
  144227. NULL,
  144228. 0
  144229. };
  144230. static long _vq_quantlist__44u1__p7_0[] = {
  144231. 3,
  144232. 2,
  144233. 4,
  144234. 1,
  144235. 5,
  144236. 0,
  144237. 6,
  144238. };
  144239. static long _vq_lengthlist__44u1__p7_0[] = {
  144240. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144241. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144242. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144243. 8,
  144244. };
  144245. static float _vq_quantthresh__44u1__p7_0[] = {
  144246. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  144247. };
  144248. static long _vq_quantmap__44u1__p7_0[] = {
  144249. 5, 3, 1, 0, 2, 4, 6,
  144250. };
  144251. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  144252. _vq_quantthresh__44u1__p7_0,
  144253. _vq_quantmap__44u1__p7_0,
  144254. 7,
  144255. 7
  144256. };
  144257. static static_codebook _44u1__p7_0 = {
  144258. 2, 49,
  144259. _vq_lengthlist__44u1__p7_0,
  144260. 1, -518017024, 1626677248, 3, 0,
  144261. _vq_quantlist__44u1__p7_0,
  144262. NULL,
  144263. &_vq_auxt__44u1__p7_0,
  144264. NULL,
  144265. 0
  144266. };
  144267. static long _vq_quantlist__44u1__p7_1[] = {
  144268. 6,
  144269. 5,
  144270. 7,
  144271. 4,
  144272. 8,
  144273. 3,
  144274. 9,
  144275. 2,
  144276. 10,
  144277. 1,
  144278. 11,
  144279. 0,
  144280. 12,
  144281. };
  144282. static long _vq_lengthlist__44u1__p7_1[] = {
  144283. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  144284. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  144285. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  144286. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  144287. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  144288. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  144289. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  144290. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  144291. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  144292. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  144293. 15,15,15,15,15,15,15,15,15,
  144294. };
  144295. static float _vq_quantthresh__44u1__p7_1[] = {
  144296. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  144297. 32.5, 45.5, 58.5, 71.5,
  144298. };
  144299. static long _vq_quantmap__44u1__p7_1[] = {
  144300. 11, 9, 7, 5, 3, 1, 0, 2,
  144301. 4, 6, 8, 10, 12,
  144302. };
  144303. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  144304. _vq_quantthresh__44u1__p7_1,
  144305. _vq_quantmap__44u1__p7_1,
  144306. 13,
  144307. 13
  144308. };
  144309. static static_codebook _44u1__p7_1 = {
  144310. 2, 169,
  144311. _vq_lengthlist__44u1__p7_1,
  144312. 1, -523010048, 1618608128, 4, 0,
  144313. _vq_quantlist__44u1__p7_1,
  144314. NULL,
  144315. &_vq_auxt__44u1__p7_1,
  144316. NULL,
  144317. 0
  144318. };
  144319. static long _vq_quantlist__44u1__p7_2[] = {
  144320. 6,
  144321. 5,
  144322. 7,
  144323. 4,
  144324. 8,
  144325. 3,
  144326. 9,
  144327. 2,
  144328. 10,
  144329. 1,
  144330. 11,
  144331. 0,
  144332. 12,
  144333. };
  144334. static long _vq_lengthlist__44u1__p7_2[] = {
  144335. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  144336. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  144337. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  144338. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  144339. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  144340. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  144341. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  144342. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144343. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144344. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  144345. 9, 9, 9,10, 9, 9,10,10, 9,
  144346. };
  144347. static float _vq_quantthresh__44u1__p7_2[] = {
  144348. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  144349. 2.5, 3.5, 4.5, 5.5,
  144350. };
  144351. static long _vq_quantmap__44u1__p7_2[] = {
  144352. 11, 9, 7, 5, 3, 1, 0, 2,
  144353. 4, 6, 8, 10, 12,
  144354. };
  144355. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  144356. _vq_quantthresh__44u1__p7_2,
  144357. _vq_quantmap__44u1__p7_2,
  144358. 13,
  144359. 13
  144360. };
  144361. static static_codebook _44u1__p7_2 = {
  144362. 2, 169,
  144363. _vq_lengthlist__44u1__p7_2,
  144364. 1, -531103744, 1611661312, 4, 0,
  144365. _vq_quantlist__44u1__p7_2,
  144366. NULL,
  144367. &_vq_auxt__44u1__p7_2,
  144368. NULL,
  144369. 0
  144370. };
  144371. static long _huff_lengthlist__44u1__short[] = {
  144372. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  144373. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  144374. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  144375. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  144376. };
  144377. static static_codebook _huff_book__44u1__short = {
  144378. 2, 64,
  144379. _huff_lengthlist__44u1__short,
  144380. 0, 0, 0, 0, 0,
  144381. NULL,
  144382. NULL,
  144383. NULL,
  144384. NULL,
  144385. 0
  144386. };
  144387. static long _huff_lengthlist__44u2__long[] = {
  144388. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  144389. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  144390. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  144391. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  144392. };
  144393. static static_codebook _huff_book__44u2__long = {
  144394. 2, 64,
  144395. _huff_lengthlist__44u2__long,
  144396. 0, 0, 0, 0, 0,
  144397. NULL,
  144398. NULL,
  144399. NULL,
  144400. NULL,
  144401. 0
  144402. };
  144403. static long _vq_quantlist__44u2__p1_0[] = {
  144404. 1,
  144405. 0,
  144406. 2,
  144407. };
  144408. static long _vq_lengthlist__44u2__p1_0[] = {
  144409. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  144410. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  144411. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  144412. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  144413. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  144414. 13,
  144415. };
  144416. static float _vq_quantthresh__44u2__p1_0[] = {
  144417. -0.5, 0.5,
  144418. };
  144419. static long _vq_quantmap__44u2__p1_0[] = {
  144420. 1, 0, 2,
  144421. };
  144422. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  144423. _vq_quantthresh__44u2__p1_0,
  144424. _vq_quantmap__44u2__p1_0,
  144425. 3,
  144426. 3
  144427. };
  144428. static static_codebook _44u2__p1_0 = {
  144429. 4, 81,
  144430. _vq_lengthlist__44u2__p1_0,
  144431. 1, -535822336, 1611661312, 2, 0,
  144432. _vq_quantlist__44u2__p1_0,
  144433. NULL,
  144434. &_vq_auxt__44u2__p1_0,
  144435. NULL,
  144436. 0
  144437. };
  144438. static long _vq_quantlist__44u2__p2_0[] = {
  144439. 1,
  144440. 0,
  144441. 2,
  144442. };
  144443. static long _vq_lengthlist__44u2__p2_0[] = {
  144444. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  144445. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  144446. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  144447. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  144448. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  144449. 9,
  144450. };
  144451. static float _vq_quantthresh__44u2__p2_0[] = {
  144452. -0.5, 0.5,
  144453. };
  144454. static long _vq_quantmap__44u2__p2_0[] = {
  144455. 1, 0, 2,
  144456. };
  144457. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  144458. _vq_quantthresh__44u2__p2_0,
  144459. _vq_quantmap__44u2__p2_0,
  144460. 3,
  144461. 3
  144462. };
  144463. static static_codebook _44u2__p2_0 = {
  144464. 4, 81,
  144465. _vq_lengthlist__44u2__p2_0,
  144466. 1, -535822336, 1611661312, 2, 0,
  144467. _vq_quantlist__44u2__p2_0,
  144468. NULL,
  144469. &_vq_auxt__44u2__p2_0,
  144470. NULL,
  144471. 0
  144472. };
  144473. static long _vq_quantlist__44u2__p3_0[] = {
  144474. 2,
  144475. 1,
  144476. 3,
  144477. 0,
  144478. 4,
  144479. };
  144480. static long _vq_lengthlist__44u2__p3_0[] = {
  144481. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  144482. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  144483. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  144484. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  144485. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  144486. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  144487. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  144488. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  144489. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  144490. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  144491. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  144492. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  144493. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  144494. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  144495. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  144496. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  144497. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  144498. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  144499. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  144500. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  144501. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  144502. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  144503. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  144504. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  144505. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  144506. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  144507. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  144508. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  144509. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  144510. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  144511. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  144512. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  144513. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  144514. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  144515. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  144516. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  144517. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  144518. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  144519. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  144520. 0,
  144521. };
  144522. static float _vq_quantthresh__44u2__p3_0[] = {
  144523. -1.5, -0.5, 0.5, 1.5,
  144524. };
  144525. static long _vq_quantmap__44u2__p3_0[] = {
  144526. 3, 1, 0, 2, 4,
  144527. };
  144528. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  144529. _vq_quantthresh__44u2__p3_0,
  144530. _vq_quantmap__44u2__p3_0,
  144531. 5,
  144532. 5
  144533. };
  144534. static static_codebook _44u2__p3_0 = {
  144535. 4, 625,
  144536. _vq_lengthlist__44u2__p3_0,
  144537. 1, -533725184, 1611661312, 3, 0,
  144538. _vq_quantlist__44u2__p3_0,
  144539. NULL,
  144540. &_vq_auxt__44u2__p3_0,
  144541. NULL,
  144542. 0
  144543. };
  144544. static long _vq_quantlist__44u2__p4_0[] = {
  144545. 2,
  144546. 1,
  144547. 3,
  144548. 0,
  144549. 4,
  144550. };
  144551. static long _vq_lengthlist__44u2__p4_0[] = {
  144552. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  144553. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144554. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  144555. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  144556. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  144557. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  144558. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  144559. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  144560. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  144561. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  144562. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  144563. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144564. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  144565. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  144566. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  144567. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  144568. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  144569. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  144570. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  144571. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  144572. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  144573. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  144574. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  144575. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  144576. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  144577. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  144578. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  144579. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  144580. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  144581. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  144582. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  144583. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  144584. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  144585. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  144586. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  144587. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  144588. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  144589. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  144590. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  144591. 13,
  144592. };
  144593. static float _vq_quantthresh__44u2__p4_0[] = {
  144594. -1.5, -0.5, 0.5, 1.5,
  144595. };
  144596. static long _vq_quantmap__44u2__p4_0[] = {
  144597. 3, 1, 0, 2, 4,
  144598. };
  144599. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  144600. _vq_quantthresh__44u2__p4_0,
  144601. _vq_quantmap__44u2__p4_0,
  144602. 5,
  144603. 5
  144604. };
  144605. static static_codebook _44u2__p4_0 = {
  144606. 4, 625,
  144607. _vq_lengthlist__44u2__p4_0,
  144608. 1, -533725184, 1611661312, 3, 0,
  144609. _vq_quantlist__44u2__p4_0,
  144610. NULL,
  144611. &_vq_auxt__44u2__p4_0,
  144612. NULL,
  144613. 0
  144614. };
  144615. static long _vq_quantlist__44u2__p5_0[] = {
  144616. 4,
  144617. 3,
  144618. 5,
  144619. 2,
  144620. 6,
  144621. 1,
  144622. 7,
  144623. 0,
  144624. 8,
  144625. };
  144626. static long _vq_lengthlist__44u2__p5_0[] = {
  144627. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  144628. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  144629. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  144630. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  144631. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  144632. 13,
  144633. };
  144634. static float _vq_quantthresh__44u2__p5_0[] = {
  144635. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144636. };
  144637. static long _vq_quantmap__44u2__p5_0[] = {
  144638. 7, 5, 3, 1, 0, 2, 4, 6,
  144639. 8,
  144640. };
  144641. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  144642. _vq_quantthresh__44u2__p5_0,
  144643. _vq_quantmap__44u2__p5_0,
  144644. 9,
  144645. 9
  144646. };
  144647. static static_codebook _44u2__p5_0 = {
  144648. 2, 81,
  144649. _vq_lengthlist__44u2__p5_0,
  144650. 1, -531628032, 1611661312, 4, 0,
  144651. _vq_quantlist__44u2__p5_0,
  144652. NULL,
  144653. &_vq_auxt__44u2__p5_0,
  144654. NULL,
  144655. 0
  144656. };
  144657. static long _vq_quantlist__44u2__p6_0[] = {
  144658. 6,
  144659. 5,
  144660. 7,
  144661. 4,
  144662. 8,
  144663. 3,
  144664. 9,
  144665. 2,
  144666. 10,
  144667. 1,
  144668. 11,
  144669. 0,
  144670. 12,
  144671. };
  144672. static long _vq_lengthlist__44u2__p6_0[] = {
  144673. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  144674. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  144675. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  144676. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  144677. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  144678. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  144679. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  144680. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  144681. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  144682. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  144683. 15,17,17,16,18,17,18, 0, 0,
  144684. };
  144685. static float _vq_quantthresh__44u2__p6_0[] = {
  144686. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144687. 12.5, 17.5, 22.5, 27.5,
  144688. };
  144689. static long _vq_quantmap__44u2__p6_0[] = {
  144690. 11, 9, 7, 5, 3, 1, 0, 2,
  144691. 4, 6, 8, 10, 12,
  144692. };
  144693. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  144694. _vq_quantthresh__44u2__p6_0,
  144695. _vq_quantmap__44u2__p6_0,
  144696. 13,
  144697. 13
  144698. };
  144699. static static_codebook _44u2__p6_0 = {
  144700. 2, 169,
  144701. _vq_lengthlist__44u2__p6_0,
  144702. 1, -526516224, 1616117760, 4, 0,
  144703. _vq_quantlist__44u2__p6_0,
  144704. NULL,
  144705. &_vq_auxt__44u2__p6_0,
  144706. NULL,
  144707. 0
  144708. };
  144709. static long _vq_quantlist__44u2__p6_1[] = {
  144710. 2,
  144711. 1,
  144712. 3,
  144713. 0,
  144714. 4,
  144715. };
  144716. static long _vq_lengthlist__44u2__p6_1[] = {
  144717. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  144718. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  144719. };
  144720. static float _vq_quantthresh__44u2__p6_1[] = {
  144721. -1.5, -0.5, 0.5, 1.5,
  144722. };
  144723. static long _vq_quantmap__44u2__p6_1[] = {
  144724. 3, 1, 0, 2, 4,
  144725. };
  144726. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  144727. _vq_quantthresh__44u2__p6_1,
  144728. _vq_quantmap__44u2__p6_1,
  144729. 5,
  144730. 5
  144731. };
  144732. static static_codebook _44u2__p6_1 = {
  144733. 2, 25,
  144734. _vq_lengthlist__44u2__p6_1,
  144735. 1, -533725184, 1611661312, 3, 0,
  144736. _vq_quantlist__44u2__p6_1,
  144737. NULL,
  144738. &_vq_auxt__44u2__p6_1,
  144739. NULL,
  144740. 0
  144741. };
  144742. static long _vq_quantlist__44u2__p7_0[] = {
  144743. 4,
  144744. 3,
  144745. 5,
  144746. 2,
  144747. 6,
  144748. 1,
  144749. 7,
  144750. 0,
  144751. 8,
  144752. };
  144753. static long _vq_lengthlist__44u2__p7_0[] = {
  144754. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  144755. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  144756. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144757. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144758. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144759. 11,
  144760. };
  144761. static float _vq_quantthresh__44u2__p7_0[] = {
  144762. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  144763. };
  144764. static long _vq_quantmap__44u2__p7_0[] = {
  144765. 7, 5, 3, 1, 0, 2, 4, 6,
  144766. 8,
  144767. };
  144768. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  144769. _vq_quantthresh__44u2__p7_0,
  144770. _vq_quantmap__44u2__p7_0,
  144771. 9,
  144772. 9
  144773. };
  144774. static static_codebook _44u2__p7_0 = {
  144775. 2, 81,
  144776. _vq_lengthlist__44u2__p7_0,
  144777. 1, -516612096, 1626677248, 4, 0,
  144778. _vq_quantlist__44u2__p7_0,
  144779. NULL,
  144780. &_vq_auxt__44u2__p7_0,
  144781. NULL,
  144782. 0
  144783. };
  144784. static long _vq_quantlist__44u2__p7_1[] = {
  144785. 6,
  144786. 5,
  144787. 7,
  144788. 4,
  144789. 8,
  144790. 3,
  144791. 9,
  144792. 2,
  144793. 10,
  144794. 1,
  144795. 11,
  144796. 0,
  144797. 12,
  144798. };
  144799. static long _vq_lengthlist__44u2__p7_1[] = {
  144800. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  144801. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  144802. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  144803. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  144804. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  144805. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  144806. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  144807. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  144808. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  144809. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  144810. 14,14,14,17,15,17,17,17,17,
  144811. };
  144812. static float _vq_quantthresh__44u2__p7_1[] = {
  144813. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  144814. 32.5, 45.5, 58.5, 71.5,
  144815. };
  144816. static long _vq_quantmap__44u2__p7_1[] = {
  144817. 11, 9, 7, 5, 3, 1, 0, 2,
  144818. 4, 6, 8, 10, 12,
  144819. };
  144820. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  144821. _vq_quantthresh__44u2__p7_1,
  144822. _vq_quantmap__44u2__p7_1,
  144823. 13,
  144824. 13
  144825. };
  144826. static static_codebook _44u2__p7_1 = {
  144827. 2, 169,
  144828. _vq_lengthlist__44u2__p7_1,
  144829. 1, -523010048, 1618608128, 4, 0,
  144830. _vq_quantlist__44u2__p7_1,
  144831. NULL,
  144832. &_vq_auxt__44u2__p7_1,
  144833. NULL,
  144834. 0
  144835. };
  144836. static long _vq_quantlist__44u2__p7_2[] = {
  144837. 6,
  144838. 5,
  144839. 7,
  144840. 4,
  144841. 8,
  144842. 3,
  144843. 9,
  144844. 2,
  144845. 10,
  144846. 1,
  144847. 11,
  144848. 0,
  144849. 12,
  144850. };
  144851. static long _vq_lengthlist__44u2__p7_2[] = {
  144852. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  144853. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  144854. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  144855. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  144856. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  144857. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  144858. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  144859. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144860. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  144861. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  144862. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144863. };
  144864. static float _vq_quantthresh__44u2__p7_2[] = {
  144865. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  144866. 2.5, 3.5, 4.5, 5.5,
  144867. };
  144868. static long _vq_quantmap__44u2__p7_2[] = {
  144869. 11, 9, 7, 5, 3, 1, 0, 2,
  144870. 4, 6, 8, 10, 12,
  144871. };
  144872. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  144873. _vq_quantthresh__44u2__p7_2,
  144874. _vq_quantmap__44u2__p7_2,
  144875. 13,
  144876. 13
  144877. };
  144878. static static_codebook _44u2__p7_2 = {
  144879. 2, 169,
  144880. _vq_lengthlist__44u2__p7_2,
  144881. 1, -531103744, 1611661312, 4, 0,
  144882. _vq_quantlist__44u2__p7_2,
  144883. NULL,
  144884. &_vq_auxt__44u2__p7_2,
  144885. NULL,
  144886. 0
  144887. };
  144888. static long _huff_lengthlist__44u2__short[] = {
  144889. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  144890. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  144891. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  144892. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  144893. };
  144894. static static_codebook _huff_book__44u2__short = {
  144895. 2, 64,
  144896. _huff_lengthlist__44u2__short,
  144897. 0, 0, 0, 0, 0,
  144898. NULL,
  144899. NULL,
  144900. NULL,
  144901. NULL,
  144902. 0
  144903. };
  144904. static long _huff_lengthlist__44u3__long[] = {
  144905. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  144906. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  144907. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  144908. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  144909. };
  144910. static static_codebook _huff_book__44u3__long = {
  144911. 2, 64,
  144912. _huff_lengthlist__44u3__long,
  144913. 0, 0, 0, 0, 0,
  144914. NULL,
  144915. NULL,
  144916. NULL,
  144917. NULL,
  144918. 0
  144919. };
  144920. static long _vq_quantlist__44u3__p1_0[] = {
  144921. 1,
  144922. 0,
  144923. 2,
  144924. };
  144925. static long _vq_lengthlist__44u3__p1_0[] = {
  144926. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  144927. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  144928. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  144929. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  144930. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  144931. 13,
  144932. };
  144933. static float _vq_quantthresh__44u3__p1_0[] = {
  144934. -0.5, 0.5,
  144935. };
  144936. static long _vq_quantmap__44u3__p1_0[] = {
  144937. 1, 0, 2,
  144938. };
  144939. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  144940. _vq_quantthresh__44u3__p1_0,
  144941. _vq_quantmap__44u3__p1_0,
  144942. 3,
  144943. 3
  144944. };
  144945. static static_codebook _44u3__p1_0 = {
  144946. 4, 81,
  144947. _vq_lengthlist__44u3__p1_0,
  144948. 1, -535822336, 1611661312, 2, 0,
  144949. _vq_quantlist__44u3__p1_0,
  144950. NULL,
  144951. &_vq_auxt__44u3__p1_0,
  144952. NULL,
  144953. 0
  144954. };
  144955. static long _vq_quantlist__44u3__p2_0[] = {
  144956. 1,
  144957. 0,
  144958. 2,
  144959. };
  144960. static long _vq_lengthlist__44u3__p2_0[] = {
  144961. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  144962. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  144963. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  144964. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  144965. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  144966. 9,
  144967. };
  144968. static float _vq_quantthresh__44u3__p2_0[] = {
  144969. -0.5, 0.5,
  144970. };
  144971. static long _vq_quantmap__44u3__p2_0[] = {
  144972. 1, 0, 2,
  144973. };
  144974. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  144975. _vq_quantthresh__44u3__p2_0,
  144976. _vq_quantmap__44u3__p2_0,
  144977. 3,
  144978. 3
  144979. };
  144980. static static_codebook _44u3__p2_0 = {
  144981. 4, 81,
  144982. _vq_lengthlist__44u3__p2_0,
  144983. 1, -535822336, 1611661312, 2, 0,
  144984. _vq_quantlist__44u3__p2_0,
  144985. NULL,
  144986. &_vq_auxt__44u3__p2_0,
  144987. NULL,
  144988. 0
  144989. };
  144990. static long _vq_quantlist__44u3__p3_0[] = {
  144991. 2,
  144992. 1,
  144993. 3,
  144994. 0,
  144995. 4,
  144996. };
  144997. static long _vq_lengthlist__44u3__p3_0[] = {
  144998. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  144999. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  145000. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  145001. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  145002. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  145003. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  145004. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  145005. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  145006. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  145007. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  145008. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  145009. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  145010. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  145011. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  145012. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  145013. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  145014. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  145015. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  145016. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  145017. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  145018. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  145019. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  145020. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  145021. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  145022. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  145023. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  145024. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  145025. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  145026. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  145027. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  145028. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  145029. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  145030. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  145031. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  145032. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  145033. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  145034. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  145035. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  145036. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  145037. 0,
  145038. };
  145039. static float _vq_quantthresh__44u3__p3_0[] = {
  145040. -1.5, -0.5, 0.5, 1.5,
  145041. };
  145042. static long _vq_quantmap__44u3__p3_0[] = {
  145043. 3, 1, 0, 2, 4,
  145044. };
  145045. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  145046. _vq_quantthresh__44u3__p3_0,
  145047. _vq_quantmap__44u3__p3_0,
  145048. 5,
  145049. 5
  145050. };
  145051. static static_codebook _44u3__p3_0 = {
  145052. 4, 625,
  145053. _vq_lengthlist__44u3__p3_0,
  145054. 1, -533725184, 1611661312, 3, 0,
  145055. _vq_quantlist__44u3__p3_0,
  145056. NULL,
  145057. &_vq_auxt__44u3__p3_0,
  145058. NULL,
  145059. 0
  145060. };
  145061. static long _vq_quantlist__44u3__p4_0[] = {
  145062. 2,
  145063. 1,
  145064. 3,
  145065. 0,
  145066. 4,
  145067. };
  145068. static long _vq_lengthlist__44u3__p4_0[] = {
  145069. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  145070. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  145071. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  145072. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  145073. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  145074. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  145075. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  145076. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  145077. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  145078. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  145079. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  145080. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  145081. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  145082. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  145083. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  145084. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  145085. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  145086. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  145087. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  145088. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  145089. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  145090. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  145091. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  145092. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  145093. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  145094. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  145095. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  145096. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  145097. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  145098. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  145099. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  145100. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  145101. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  145102. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  145103. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  145104. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  145105. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  145106. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  145107. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  145108. 13,
  145109. };
  145110. static float _vq_quantthresh__44u3__p4_0[] = {
  145111. -1.5, -0.5, 0.5, 1.5,
  145112. };
  145113. static long _vq_quantmap__44u3__p4_0[] = {
  145114. 3, 1, 0, 2, 4,
  145115. };
  145116. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  145117. _vq_quantthresh__44u3__p4_0,
  145118. _vq_quantmap__44u3__p4_0,
  145119. 5,
  145120. 5
  145121. };
  145122. static static_codebook _44u3__p4_0 = {
  145123. 4, 625,
  145124. _vq_lengthlist__44u3__p4_0,
  145125. 1, -533725184, 1611661312, 3, 0,
  145126. _vq_quantlist__44u3__p4_0,
  145127. NULL,
  145128. &_vq_auxt__44u3__p4_0,
  145129. NULL,
  145130. 0
  145131. };
  145132. static long _vq_quantlist__44u3__p5_0[] = {
  145133. 4,
  145134. 3,
  145135. 5,
  145136. 2,
  145137. 6,
  145138. 1,
  145139. 7,
  145140. 0,
  145141. 8,
  145142. };
  145143. static long _vq_lengthlist__44u3__p5_0[] = {
  145144. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  145145. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  145146. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  145147. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145148. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  145149. 12,
  145150. };
  145151. static float _vq_quantthresh__44u3__p5_0[] = {
  145152. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145153. };
  145154. static long _vq_quantmap__44u3__p5_0[] = {
  145155. 7, 5, 3, 1, 0, 2, 4, 6,
  145156. 8,
  145157. };
  145158. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  145159. _vq_quantthresh__44u3__p5_0,
  145160. _vq_quantmap__44u3__p5_0,
  145161. 9,
  145162. 9
  145163. };
  145164. static static_codebook _44u3__p5_0 = {
  145165. 2, 81,
  145166. _vq_lengthlist__44u3__p5_0,
  145167. 1, -531628032, 1611661312, 4, 0,
  145168. _vq_quantlist__44u3__p5_0,
  145169. NULL,
  145170. &_vq_auxt__44u3__p5_0,
  145171. NULL,
  145172. 0
  145173. };
  145174. static long _vq_quantlist__44u3__p6_0[] = {
  145175. 6,
  145176. 5,
  145177. 7,
  145178. 4,
  145179. 8,
  145180. 3,
  145181. 9,
  145182. 2,
  145183. 10,
  145184. 1,
  145185. 11,
  145186. 0,
  145187. 12,
  145188. };
  145189. static long _vq_lengthlist__44u3__p6_0[] = {
  145190. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  145191. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  145192. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  145193. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  145194. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  145195. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  145196. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  145197. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  145198. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  145199. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  145200. 15,16,16,16,17,18,16,20,18,
  145201. };
  145202. static float _vq_quantthresh__44u3__p6_0[] = {
  145203. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145204. 12.5, 17.5, 22.5, 27.5,
  145205. };
  145206. static long _vq_quantmap__44u3__p6_0[] = {
  145207. 11, 9, 7, 5, 3, 1, 0, 2,
  145208. 4, 6, 8, 10, 12,
  145209. };
  145210. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  145211. _vq_quantthresh__44u3__p6_0,
  145212. _vq_quantmap__44u3__p6_0,
  145213. 13,
  145214. 13
  145215. };
  145216. static static_codebook _44u3__p6_0 = {
  145217. 2, 169,
  145218. _vq_lengthlist__44u3__p6_0,
  145219. 1, -526516224, 1616117760, 4, 0,
  145220. _vq_quantlist__44u3__p6_0,
  145221. NULL,
  145222. &_vq_auxt__44u3__p6_0,
  145223. NULL,
  145224. 0
  145225. };
  145226. static long _vq_quantlist__44u3__p6_1[] = {
  145227. 2,
  145228. 1,
  145229. 3,
  145230. 0,
  145231. 4,
  145232. };
  145233. static long _vq_lengthlist__44u3__p6_1[] = {
  145234. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  145235. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  145236. };
  145237. static float _vq_quantthresh__44u3__p6_1[] = {
  145238. -1.5, -0.5, 0.5, 1.5,
  145239. };
  145240. static long _vq_quantmap__44u3__p6_1[] = {
  145241. 3, 1, 0, 2, 4,
  145242. };
  145243. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  145244. _vq_quantthresh__44u3__p6_1,
  145245. _vq_quantmap__44u3__p6_1,
  145246. 5,
  145247. 5
  145248. };
  145249. static static_codebook _44u3__p6_1 = {
  145250. 2, 25,
  145251. _vq_lengthlist__44u3__p6_1,
  145252. 1, -533725184, 1611661312, 3, 0,
  145253. _vq_quantlist__44u3__p6_1,
  145254. NULL,
  145255. &_vq_auxt__44u3__p6_1,
  145256. NULL,
  145257. 0
  145258. };
  145259. static long _vq_quantlist__44u3__p7_0[] = {
  145260. 4,
  145261. 3,
  145262. 5,
  145263. 2,
  145264. 6,
  145265. 1,
  145266. 7,
  145267. 0,
  145268. 8,
  145269. };
  145270. static long _vq_lengthlist__44u3__p7_0[] = {
  145271. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  145272. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  145273. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145274. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145275. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145276. 9,
  145277. };
  145278. static float _vq_quantthresh__44u3__p7_0[] = {
  145279. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  145280. };
  145281. static long _vq_quantmap__44u3__p7_0[] = {
  145282. 7, 5, 3, 1, 0, 2, 4, 6,
  145283. 8,
  145284. };
  145285. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  145286. _vq_quantthresh__44u3__p7_0,
  145287. _vq_quantmap__44u3__p7_0,
  145288. 9,
  145289. 9
  145290. };
  145291. static static_codebook _44u3__p7_0 = {
  145292. 2, 81,
  145293. _vq_lengthlist__44u3__p7_0,
  145294. 1, -515907584, 1627381760, 4, 0,
  145295. _vq_quantlist__44u3__p7_0,
  145296. NULL,
  145297. &_vq_auxt__44u3__p7_0,
  145298. NULL,
  145299. 0
  145300. };
  145301. static long _vq_quantlist__44u3__p7_1[] = {
  145302. 7,
  145303. 6,
  145304. 8,
  145305. 5,
  145306. 9,
  145307. 4,
  145308. 10,
  145309. 3,
  145310. 11,
  145311. 2,
  145312. 12,
  145313. 1,
  145314. 13,
  145315. 0,
  145316. 14,
  145317. };
  145318. static long _vq_lengthlist__44u3__p7_1[] = {
  145319. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  145320. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  145321. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  145322. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  145323. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  145324. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  145325. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  145326. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  145327. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  145328. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  145329. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  145330. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  145331. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  145332. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  145333. 17,
  145334. };
  145335. static float _vq_quantthresh__44u3__p7_1[] = {
  145336. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  145337. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  145338. };
  145339. static long _vq_quantmap__44u3__p7_1[] = {
  145340. 13, 11, 9, 7, 5, 3, 1, 0,
  145341. 2, 4, 6, 8, 10, 12, 14,
  145342. };
  145343. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  145344. _vq_quantthresh__44u3__p7_1,
  145345. _vq_quantmap__44u3__p7_1,
  145346. 15,
  145347. 15
  145348. };
  145349. static static_codebook _44u3__p7_1 = {
  145350. 2, 225,
  145351. _vq_lengthlist__44u3__p7_1,
  145352. 1, -522338304, 1620115456, 4, 0,
  145353. _vq_quantlist__44u3__p7_1,
  145354. NULL,
  145355. &_vq_auxt__44u3__p7_1,
  145356. NULL,
  145357. 0
  145358. };
  145359. static long _vq_quantlist__44u3__p7_2[] = {
  145360. 8,
  145361. 7,
  145362. 9,
  145363. 6,
  145364. 10,
  145365. 5,
  145366. 11,
  145367. 4,
  145368. 12,
  145369. 3,
  145370. 13,
  145371. 2,
  145372. 14,
  145373. 1,
  145374. 15,
  145375. 0,
  145376. 16,
  145377. };
  145378. static long _vq_lengthlist__44u3__p7_2[] = {
  145379. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145380. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145381. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  145382. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145383. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  145384. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145385. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  145386. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145387. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  145388. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  145389. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  145390. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  145391. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  145392. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  145393. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  145394. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  145395. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145396. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  145397. 11,
  145398. };
  145399. static float _vq_quantthresh__44u3__p7_2[] = {
  145400. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145401. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145402. };
  145403. static long _vq_quantmap__44u3__p7_2[] = {
  145404. 15, 13, 11, 9, 7, 5, 3, 1,
  145405. 0, 2, 4, 6, 8, 10, 12, 14,
  145406. 16,
  145407. };
  145408. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  145409. _vq_quantthresh__44u3__p7_2,
  145410. _vq_quantmap__44u3__p7_2,
  145411. 17,
  145412. 17
  145413. };
  145414. static static_codebook _44u3__p7_2 = {
  145415. 2, 289,
  145416. _vq_lengthlist__44u3__p7_2,
  145417. 1, -529530880, 1611661312, 5, 0,
  145418. _vq_quantlist__44u3__p7_2,
  145419. NULL,
  145420. &_vq_auxt__44u3__p7_2,
  145421. NULL,
  145422. 0
  145423. };
  145424. static long _huff_lengthlist__44u3__short[] = {
  145425. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  145426. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  145427. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  145428. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  145429. };
  145430. static static_codebook _huff_book__44u3__short = {
  145431. 2, 64,
  145432. _huff_lengthlist__44u3__short,
  145433. 0, 0, 0, 0, 0,
  145434. NULL,
  145435. NULL,
  145436. NULL,
  145437. NULL,
  145438. 0
  145439. };
  145440. static long _huff_lengthlist__44u4__long[] = {
  145441. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  145442. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  145443. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  145444. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  145445. };
  145446. static static_codebook _huff_book__44u4__long = {
  145447. 2, 64,
  145448. _huff_lengthlist__44u4__long,
  145449. 0, 0, 0, 0, 0,
  145450. NULL,
  145451. NULL,
  145452. NULL,
  145453. NULL,
  145454. 0
  145455. };
  145456. static long _vq_quantlist__44u4__p1_0[] = {
  145457. 1,
  145458. 0,
  145459. 2,
  145460. };
  145461. static long _vq_lengthlist__44u4__p1_0[] = {
  145462. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  145463. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  145464. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  145465. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  145466. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  145467. 13,
  145468. };
  145469. static float _vq_quantthresh__44u4__p1_0[] = {
  145470. -0.5, 0.5,
  145471. };
  145472. static long _vq_quantmap__44u4__p1_0[] = {
  145473. 1, 0, 2,
  145474. };
  145475. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  145476. _vq_quantthresh__44u4__p1_0,
  145477. _vq_quantmap__44u4__p1_0,
  145478. 3,
  145479. 3
  145480. };
  145481. static static_codebook _44u4__p1_0 = {
  145482. 4, 81,
  145483. _vq_lengthlist__44u4__p1_0,
  145484. 1, -535822336, 1611661312, 2, 0,
  145485. _vq_quantlist__44u4__p1_0,
  145486. NULL,
  145487. &_vq_auxt__44u4__p1_0,
  145488. NULL,
  145489. 0
  145490. };
  145491. static long _vq_quantlist__44u4__p2_0[] = {
  145492. 1,
  145493. 0,
  145494. 2,
  145495. };
  145496. static long _vq_lengthlist__44u4__p2_0[] = {
  145497. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  145498. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  145499. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  145500. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  145501. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  145502. 9,
  145503. };
  145504. static float _vq_quantthresh__44u4__p2_0[] = {
  145505. -0.5, 0.5,
  145506. };
  145507. static long _vq_quantmap__44u4__p2_0[] = {
  145508. 1, 0, 2,
  145509. };
  145510. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  145511. _vq_quantthresh__44u4__p2_0,
  145512. _vq_quantmap__44u4__p2_0,
  145513. 3,
  145514. 3
  145515. };
  145516. static static_codebook _44u4__p2_0 = {
  145517. 4, 81,
  145518. _vq_lengthlist__44u4__p2_0,
  145519. 1, -535822336, 1611661312, 2, 0,
  145520. _vq_quantlist__44u4__p2_0,
  145521. NULL,
  145522. &_vq_auxt__44u4__p2_0,
  145523. NULL,
  145524. 0
  145525. };
  145526. static long _vq_quantlist__44u4__p3_0[] = {
  145527. 2,
  145528. 1,
  145529. 3,
  145530. 0,
  145531. 4,
  145532. };
  145533. static long _vq_lengthlist__44u4__p3_0[] = {
  145534. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  145535. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  145536. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  145537. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  145538. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  145539. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  145540. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  145541. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  145542. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  145543. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  145544. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  145545. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  145546. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  145547. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  145548. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  145549. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  145550. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  145551. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  145552. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  145553. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  145554. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  145555. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  145556. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  145557. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  145558. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  145559. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  145560. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  145561. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  145562. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  145563. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  145564. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  145565. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  145566. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  145567. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  145568. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  145569. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  145570. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  145571. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  145572. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  145573. 0,
  145574. };
  145575. static float _vq_quantthresh__44u4__p3_0[] = {
  145576. -1.5, -0.5, 0.5, 1.5,
  145577. };
  145578. static long _vq_quantmap__44u4__p3_0[] = {
  145579. 3, 1, 0, 2, 4,
  145580. };
  145581. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  145582. _vq_quantthresh__44u4__p3_0,
  145583. _vq_quantmap__44u4__p3_0,
  145584. 5,
  145585. 5
  145586. };
  145587. static static_codebook _44u4__p3_0 = {
  145588. 4, 625,
  145589. _vq_lengthlist__44u4__p3_0,
  145590. 1, -533725184, 1611661312, 3, 0,
  145591. _vq_quantlist__44u4__p3_0,
  145592. NULL,
  145593. &_vq_auxt__44u4__p3_0,
  145594. NULL,
  145595. 0
  145596. };
  145597. static long _vq_quantlist__44u4__p4_0[] = {
  145598. 2,
  145599. 1,
  145600. 3,
  145601. 0,
  145602. 4,
  145603. };
  145604. static long _vq_lengthlist__44u4__p4_0[] = {
  145605. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  145606. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  145607. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  145608. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  145609. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  145610. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  145611. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  145612. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  145613. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  145614. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  145615. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  145616. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  145617. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  145618. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  145619. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  145620. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  145621. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  145622. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  145623. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  145624. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  145625. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  145626. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  145627. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  145628. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  145629. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  145630. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  145631. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  145632. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  145633. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  145634. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  145635. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  145636. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  145637. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  145638. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  145639. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  145640. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  145641. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  145642. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  145643. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  145644. 13,
  145645. };
  145646. static float _vq_quantthresh__44u4__p4_0[] = {
  145647. -1.5, -0.5, 0.5, 1.5,
  145648. };
  145649. static long _vq_quantmap__44u4__p4_0[] = {
  145650. 3, 1, 0, 2, 4,
  145651. };
  145652. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  145653. _vq_quantthresh__44u4__p4_0,
  145654. _vq_quantmap__44u4__p4_0,
  145655. 5,
  145656. 5
  145657. };
  145658. static static_codebook _44u4__p4_0 = {
  145659. 4, 625,
  145660. _vq_lengthlist__44u4__p4_0,
  145661. 1, -533725184, 1611661312, 3, 0,
  145662. _vq_quantlist__44u4__p4_0,
  145663. NULL,
  145664. &_vq_auxt__44u4__p4_0,
  145665. NULL,
  145666. 0
  145667. };
  145668. static long _vq_quantlist__44u4__p5_0[] = {
  145669. 4,
  145670. 3,
  145671. 5,
  145672. 2,
  145673. 6,
  145674. 1,
  145675. 7,
  145676. 0,
  145677. 8,
  145678. };
  145679. static long _vq_lengthlist__44u4__p5_0[] = {
  145680. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  145681. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  145682. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  145683. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145684. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  145685. 12,
  145686. };
  145687. static float _vq_quantthresh__44u4__p5_0[] = {
  145688. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145689. };
  145690. static long _vq_quantmap__44u4__p5_0[] = {
  145691. 7, 5, 3, 1, 0, 2, 4, 6,
  145692. 8,
  145693. };
  145694. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  145695. _vq_quantthresh__44u4__p5_0,
  145696. _vq_quantmap__44u4__p5_0,
  145697. 9,
  145698. 9
  145699. };
  145700. static static_codebook _44u4__p5_0 = {
  145701. 2, 81,
  145702. _vq_lengthlist__44u4__p5_0,
  145703. 1, -531628032, 1611661312, 4, 0,
  145704. _vq_quantlist__44u4__p5_0,
  145705. NULL,
  145706. &_vq_auxt__44u4__p5_0,
  145707. NULL,
  145708. 0
  145709. };
  145710. static long _vq_quantlist__44u4__p6_0[] = {
  145711. 6,
  145712. 5,
  145713. 7,
  145714. 4,
  145715. 8,
  145716. 3,
  145717. 9,
  145718. 2,
  145719. 10,
  145720. 1,
  145721. 11,
  145722. 0,
  145723. 12,
  145724. };
  145725. static long _vq_lengthlist__44u4__p6_0[] = {
  145726. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  145727. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  145728. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  145729. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  145730. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  145731. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  145732. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  145733. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  145734. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  145735. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  145736. 16,16,16,17,17,18,17,20,21,
  145737. };
  145738. static float _vq_quantthresh__44u4__p6_0[] = {
  145739. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145740. 12.5, 17.5, 22.5, 27.5,
  145741. };
  145742. static long _vq_quantmap__44u4__p6_0[] = {
  145743. 11, 9, 7, 5, 3, 1, 0, 2,
  145744. 4, 6, 8, 10, 12,
  145745. };
  145746. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  145747. _vq_quantthresh__44u4__p6_0,
  145748. _vq_quantmap__44u4__p6_0,
  145749. 13,
  145750. 13
  145751. };
  145752. static static_codebook _44u4__p6_0 = {
  145753. 2, 169,
  145754. _vq_lengthlist__44u4__p6_0,
  145755. 1, -526516224, 1616117760, 4, 0,
  145756. _vq_quantlist__44u4__p6_0,
  145757. NULL,
  145758. &_vq_auxt__44u4__p6_0,
  145759. NULL,
  145760. 0
  145761. };
  145762. static long _vq_quantlist__44u4__p6_1[] = {
  145763. 2,
  145764. 1,
  145765. 3,
  145766. 0,
  145767. 4,
  145768. };
  145769. static long _vq_lengthlist__44u4__p6_1[] = {
  145770. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  145771. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  145772. };
  145773. static float _vq_quantthresh__44u4__p6_1[] = {
  145774. -1.5, -0.5, 0.5, 1.5,
  145775. };
  145776. static long _vq_quantmap__44u4__p6_1[] = {
  145777. 3, 1, 0, 2, 4,
  145778. };
  145779. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  145780. _vq_quantthresh__44u4__p6_1,
  145781. _vq_quantmap__44u4__p6_1,
  145782. 5,
  145783. 5
  145784. };
  145785. static static_codebook _44u4__p6_1 = {
  145786. 2, 25,
  145787. _vq_lengthlist__44u4__p6_1,
  145788. 1, -533725184, 1611661312, 3, 0,
  145789. _vq_quantlist__44u4__p6_1,
  145790. NULL,
  145791. &_vq_auxt__44u4__p6_1,
  145792. NULL,
  145793. 0
  145794. };
  145795. static long _vq_quantlist__44u4__p7_0[] = {
  145796. 6,
  145797. 5,
  145798. 7,
  145799. 4,
  145800. 8,
  145801. 3,
  145802. 9,
  145803. 2,
  145804. 10,
  145805. 1,
  145806. 11,
  145807. 0,
  145808. 12,
  145809. };
  145810. static long _vq_lengthlist__44u4__p7_0[] = {
  145811. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  145812. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  145813. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145814. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145815. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145816. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145817. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145818. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145819. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145820. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145821. 11,11,11,11,11,11,11,11,11,
  145822. };
  145823. static float _vq_quantthresh__44u4__p7_0[] = {
  145824. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  145825. 637.5, 892.5, 1147.5, 1402.5,
  145826. };
  145827. static long _vq_quantmap__44u4__p7_0[] = {
  145828. 11, 9, 7, 5, 3, 1, 0, 2,
  145829. 4, 6, 8, 10, 12,
  145830. };
  145831. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  145832. _vq_quantthresh__44u4__p7_0,
  145833. _vq_quantmap__44u4__p7_0,
  145834. 13,
  145835. 13
  145836. };
  145837. static static_codebook _44u4__p7_0 = {
  145838. 2, 169,
  145839. _vq_lengthlist__44u4__p7_0,
  145840. 1, -514332672, 1627381760, 4, 0,
  145841. _vq_quantlist__44u4__p7_0,
  145842. NULL,
  145843. &_vq_auxt__44u4__p7_0,
  145844. NULL,
  145845. 0
  145846. };
  145847. static long _vq_quantlist__44u4__p7_1[] = {
  145848. 7,
  145849. 6,
  145850. 8,
  145851. 5,
  145852. 9,
  145853. 4,
  145854. 10,
  145855. 3,
  145856. 11,
  145857. 2,
  145858. 12,
  145859. 1,
  145860. 13,
  145861. 0,
  145862. 14,
  145863. };
  145864. static long _vq_lengthlist__44u4__p7_1[] = {
  145865. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  145866. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  145867. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  145868. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  145869. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  145870. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  145871. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  145872. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  145873. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  145874. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  145875. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  145876. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  145877. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  145878. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  145879. 16,
  145880. };
  145881. static float _vq_quantthresh__44u4__p7_1[] = {
  145882. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  145883. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  145884. };
  145885. static long _vq_quantmap__44u4__p7_1[] = {
  145886. 13, 11, 9, 7, 5, 3, 1, 0,
  145887. 2, 4, 6, 8, 10, 12, 14,
  145888. };
  145889. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  145890. _vq_quantthresh__44u4__p7_1,
  145891. _vq_quantmap__44u4__p7_1,
  145892. 15,
  145893. 15
  145894. };
  145895. static static_codebook _44u4__p7_1 = {
  145896. 2, 225,
  145897. _vq_lengthlist__44u4__p7_1,
  145898. 1, -522338304, 1620115456, 4, 0,
  145899. _vq_quantlist__44u4__p7_1,
  145900. NULL,
  145901. &_vq_auxt__44u4__p7_1,
  145902. NULL,
  145903. 0
  145904. };
  145905. static long _vq_quantlist__44u4__p7_2[] = {
  145906. 8,
  145907. 7,
  145908. 9,
  145909. 6,
  145910. 10,
  145911. 5,
  145912. 11,
  145913. 4,
  145914. 12,
  145915. 3,
  145916. 13,
  145917. 2,
  145918. 14,
  145919. 1,
  145920. 15,
  145921. 0,
  145922. 16,
  145923. };
  145924. static long _vq_lengthlist__44u4__p7_2[] = {
  145925. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145926. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145927. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145928. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145929. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  145930. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145931. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145932. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  145933. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  145934. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  145935. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  145936. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  145937. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  145938. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  145939. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  145940. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  145941. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145942. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  145943. 10,
  145944. };
  145945. static float _vq_quantthresh__44u4__p7_2[] = {
  145946. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145947. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145948. };
  145949. static long _vq_quantmap__44u4__p7_2[] = {
  145950. 15, 13, 11, 9, 7, 5, 3, 1,
  145951. 0, 2, 4, 6, 8, 10, 12, 14,
  145952. 16,
  145953. };
  145954. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  145955. _vq_quantthresh__44u4__p7_2,
  145956. _vq_quantmap__44u4__p7_2,
  145957. 17,
  145958. 17
  145959. };
  145960. static static_codebook _44u4__p7_2 = {
  145961. 2, 289,
  145962. _vq_lengthlist__44u4__p7_2,
  145963. 1, -529530880, 1611661312, 5, 0,
  145964. _vq_quantlist__44u4__p7_2,
  145965. NULL,
  145966. &_vq_auxt__44u4__p7_2,
  145967. NULL,
  145968. 0
  145969. };
  145970. static long _huff_lengthlist__44u4__short[] = {
  145971. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  145972. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  145973. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  145974. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  145975. };
  145976. static static_codebook _huff_book__44u4__short = {
  145977. 2, 64,
  145978. _huff_lengthlist__44u4__short,
  145979. 0, 0, 0, 0, 0,
  145980. NULL,
  145981. NULL,
  145982. NULL,
  145983. NULL,
  145984. 0
  145985. };
  145986. static long _huff_lengthlist__44u5__long[] = {
  145987. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  145988. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  145989. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  145990. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  145991. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  145992. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  145993. 14, 8, 7, 8,
  145994. };
  145995. static static_codebook _huff_book__44u5__long = {
  145996. 2, 100,
  145997. _huff_lengthlist__44u5__long,
  145998. 0, 0, 0, 0, 0,
  145999. NULL,
  146000. NULL,
  146001. NULL,
  146002. NULL,
  146003. 0
  146004. };
  146005. static long _vq_quantlist__44u5__p1_0[] = {
  146006. 1,
  146007. 0,
  146008. 2,
  146009. };
  146010. static long _vq_lengthlist__44u5__p1_0[] = {
  146011. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  146012. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  146013. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  146014. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  146015. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  146016. 12,
  146017. };
  146018. static float _vq_quantthresh__44u5__p1_0[] = {
  146019. -0.5, 0.5,
  146020. };
  146021. static long _vq_quantmap__44u5__p1_0[] = {
  146022. 1, 0, 2,
  146023. };
  146024. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  146025. _vq_quantthresh__44u5__p1_0,
  146026. _vq_quantmap__44u5__p1_0,
  146027. 3,
  146028. 3
  146029. };
  146030. static static_codebook _44u5__p1_0 = {
  146031. 4, 81,
  146032. _vq_lengthlist__44u5__p1_0,
  146033. 1, -535822336, 1611661312, 2, 0,
  146034. _vq_quantlist__44u5__p1_0,
  146035. NULL,
  146036. &_vq_auxt__44u5__p1_0,
  146037. NULL,
  146038. 0
  146039. };
  146040. static long _vq_quantlist__44u5__p2_0[] = {
  146041. 1,
  146042. 0,
  146043. 2,
  146044. };
  146045. static long _vq_lengthlist__44u5__p2_0[] = {
  146046. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  146047. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  146048. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  146049. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  146050. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  146051. 9,
  146052. };
  146053. static float _vq_quantthresh__44u5__p2_0[] = {
  146054. -0.5, 0.5,
  146055. };
  146056. static long _vq_quantmap__44u5__p2_0[] = {
  146057. 1, 0, 2,
  146058. };
  146059. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  146060. _vq_quantthresh__44u5__p2_0,
  146061. _vq_quantmap__44u5__p2_0,
  146062. 3,
  146063. 3
  146064. };
  146065. static static_codebook _44u5__p2_0 = {
  146066. 4, 81,
  146067. _vq_lengthlist__44u5__p2_0,
  146068. 1, -535822336, 1611661312, 2, 0,
  146069. _vq_quantlist__44u5__p2_0,
  146070. NULL,
  146071. &_vq_auxt__44u5__p2_0,
  146072. NULL,
  146073. 0
  146074. };
  146075. static long _vq_quantlist__44u5__p3_0[] = {
  146076. 2,
  146077. 1,
  146078. 3,
  146079. 0,
  146080. 4,
  146081. };
  146082. static long _vq_lengthlist__44u5__p3_0[] = {
  146083. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  146084. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  146085. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  146086. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  146087. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  146088. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  146089. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  146090. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  146091. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  146092. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  146093. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  146094. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  146095. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  146096. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  146097. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  146098. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  146099. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  146100. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  146101. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  146102. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  146103. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  146104. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  146105. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  146106. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  146107. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  146108. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  146109. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  146110. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  146111. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  146112. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  146113. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  146114. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  146115. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  146116. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  146117. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  146118. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  146119. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  146120. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  146121. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  146122. 0,
  146123. };
  146124. static float _vq_quantthresh__44u5__p3_0[] = {
  146125. -1.5, -0.5, 0.5, 1.5,
  146126. };
  146127. static long _vq_quantmap__44u5__p3_0[] = {
  146128. 3, 1, 0, 2, 4,
  146129. };
  146130. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  146131. _vq_quantthresh__44u5__p3_0,
  146132. _vq_quantmap__44u5__p3_0,
  146133. 5,
  146134. 5
  146135. };
  146136. static static_codebook _44u5__p3_0 = {
  146137. 4, 625,
  146138. _vq_lengthlist__44u5__p3_0,
  146139. 1, -533725184, 1611661312, 3, 0,
  146140. _vq_quantlist__44u5__p3_0,
  146141. NULL,
  146142. &_vq_auxt__44u5__p3_0,
  146143. NULL,
  146144. 0
  146145. };
  146146. static long _vq_quantlist__44u5__p4_0[] = {
  146147. 2,
  146148. 1,
  146149. 3,
  146150. 0,
  146151. 4,
  146152. };
  146153. static long _vq_lengthlist__44u5__p4_0[] = {
  146154. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  146155. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  146156. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  146157. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  146158. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  146159. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  146160. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  146161. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  146162. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  146163. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  146164. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  146165. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146166. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  146167. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  146168. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  146169. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  146170. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  146171. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  146172. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  146173. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  146174. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  146175. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  146176. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  146177. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  146178. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  146179. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  146180. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  146181. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  146182. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  146183. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  146184. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  146185. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  146186. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  146187. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  146188. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  146189. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  146190. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  146191. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  146192. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  146193. 12,
  146194. };
  146195. static float _vq_quantthresh__44u5__p4_0[] = {
  146196. -1.5, -0.5, 0.5, 1.5,
  146197. };
  146198. static long _vq_quantmap__44u5__p4_0[] = {
  146199. 3, 1, 0, 2, 4,
  146200. };
  146201. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  146202. _vq_quantthresh__44u5__p4_0,
  146203. _vq_quantmap__44u5__p4_0,
  146204. 5,
  146205. 5
  146206. };
  146207. static static_codebook _44u5__p4_0 = {
  146208. 4, 625,
  146209. _vq_lengthlist__44u5__p4_0,
  146210. 1, -533725184, 1611661312, 3, 0,
  146211. _vq_quantlist__44u5__p4_0,
  146212. NULL,
  146213. &_vq_auxt__44u5__p4_0,
  146214. NULL,
  146215. 0
  146216. };
  146217. static long _vq_quantlist__44u5__p5_0[] = {
  146218. 4,
  146219. 3,
  146220. 5,
  146221. 2,
  146222. 6,
  146223. 1,
  146224. 7,
  146225. 0,
  146226. 8,
  146227. };
  146228. static long _vq_lengthlist__44u5__p5_0[] = {
  146229. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  146230. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  146231. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  146232. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  146233. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  146234. 14,
  146235. };
  146236. static float _vq_quantthresh__44u5__p5_0[] = {
  146237. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146238. };
  146239. static long _vq_quantmap__44u5__p5_0[] = {
  146240. 7, 5, 3, 1, 0, 2, 4, 6,
  146241. 8,
  146242. };
  146243. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  146244. _vq_quantthresh__44u5__p5_0,
  146245. _vq_quantmap__44u5__p5_0,
  146246. 9,
  146247. 9
  146248. };
  146249. static static_codebook _44u5__p5_0 = {
  146250. 2, 81,
  146251. _vq_lengthlist__44u5__p5_0,
  146252. 1, -531628032, 1611661312, 4, 0,
  146253. _vq_quantlist__44u5__p5_0,
  146254. NULL,
  146255. &_vq_auxt__44u5__p5_0,
  146256. NULL,
  146257. 0
  146258. };
  146259. static long _vq_quantlist__44u5__p6_0[] = {
  146260. 4,
  146261. 3,
  146262. 5,
  146263. 2,
  146264. 6,
  146265. 1,
  146266. 7,
  146267. 0,
  146268. 8,
  146269. };
  146270. static long _vq_lengthlist__44u5__p6_0[] = {
  146271. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  146272. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  146273. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  146274. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  146275. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  146276. 11,
  146277. };
  146278. static float _vq_quantthresh__44u5__p6_0[] = {
  146279. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146280. };
  146281. static long _vq_quantmap__44u5__p6_0[] = {
  146282. 7, 5, 3, 1, 0, 2, 4, 6,
  146283. 8,
  146284. };
  146285. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  146286. _vq_quantthresh__44u5__p6_0,
  146287. _vq_quantmap__44u5__p6_0,
  146288. 9,
  146289. 9
  146290. };
  146291. static static_codebook _44u5__p6_0 = {
  146292. 2, 81,
  146293. _vq_lengthlist__44u5__p6_0,
  146294. 1, -531628032, 1611661312, 4, 0,
  146295. _vq_quantlist__44u5__p6_0,
  146296. NULL,
  146297. &_vq_auxt__44u5__p6_0,
  146298. NULL,
  146299. 0
  146300. };
  146301. static long _vq_quantlist__44u5__p7_0[] = {
  146302. 1,
  146303. 0,
  146304. 2,
  146305. };
  146306. static long _vq_lengthlist__44u5__p7_0[] = {
  146307. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  146308. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  146309. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  146310. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  146311. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  146312. 12,
  146313. };
  146314. static float _vq_quantthresh__44u5__p7_0[] = {
  146315. -5.5, 5.5,
  146316. };
  146317. static long _vq_quantmap__44u5__p7_0[] = {
  146318. 1, 0, 2,
  146319. };
  146320. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  146321. _vq_quantthresh__44u5__p7_0,
  146322. _vq_quantmap__44u5__p7_0,
  146323. 3,
  146324. 3
  146325. };
  146326. static static_codebook _44u5__p7_0 = {
  146327. 4, 81,
  146328. _vq_lengthlist__44u5__p7_0,
  146329. 1, -529137664, 1618345984, 2, 0,
  146330. _vq_quantlist__44u5__p7_0,
  146331. NULL,
  146332. &_vq_auxt__44u5__p7_0,
  146333. NULL,
  146334. 0
  146335. };
  146336. static long _vq_quantlist__44u5__p7_1[] = {
  146337. 5,
  146338. 4,
  146339. 6,
  146340. 3,
  146341. 7,
  146342. 2,
  146343. 8,
  146344. 1,
  146345. 9,
  146346. 0,
  146347. 10,
  146348. };
  146349. static long _vq_lengthlist__44u5__p7_1[] = {
  146350. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  146351. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  146352. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  146353. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  146354. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  146355. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  146356. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  146357. 9, 9, 9, 9, 9,10,10,10,10,
  146358. };
  146359. static float _vq_quantthresh__44u5__p7_1[] = {
  146360. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146361. 3.5, 4.5,
  146362. };
  146363. static long _vq_quantmap__44u5__p7_1[] = {
  146364. 9, 7, 5, 3, 1, 0, 2, 4,
  146365. 6, 8, 10,
  146366. };
  146367. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  146368. _vq_quantthresh__44u5__p7_1,
  146369. _vq_quantmap__44u5__p7_1,
  146370. 11,
  146371. 11
  146372. };
  146373. static static_codebook _44u5__p7_1 = {
  146374. 2, 121,
  146375. _vq_lengthlist__44u5__p7_1,
  146376. 1, -531365888, 1611661312, 4, 0,
  146377. _vq_quantlist__44u5__p7_1,
  146378. NULL,
  146379. &_vq_auxt__44u5__p7_1,
  146380. NULL,
  146381. 0
  146382. };
  146383. static long _vq_quantlist__44u5__p8_0[] = {
  146384. 5,
  146385. 4,
  146386. 6,
  146387. 3,
  146388. 7,
  146389. 2,
  146390. 8,
  146391. 1,
  146392. 9,
  146393. 0,
  146394. 10,
  146395. };
  146396. static long _vq_lengthlist__44u5__p8_0[] = {
  146397. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  146398. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  146399. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  146400. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  146401. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  146402. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  146403. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  146404. 12,13,13,14,14,14,14,15,15,
  146405. };
  146406. static float _vq_quantthresh__44u5__p8_0[] = {
  146407. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  146408. 38.5, 49.5,
  146409. };
  146410. static long _vq_quantmap__44u5__p8_0[] = {
  146411. 9, 7, 5, 3, 1, 0, 2, 4,
  146412. 6, 8, 10,
  146413. };
  146414. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  146415. _vq_quantthresh__44u5__p8_0,
  146416. _vq_quantmap__44u5__p8_0,
  146417. 11,
  146418. 11
  146419. };
  146420. static static_codebook _44u5__p8_0 = {
  146421. 2, 121,
  146422. _vq_lengthlist__44u5__p8_0,
  146423. 1, -524582912, 1618345984, 4, 0,
  146424. _vq_quantlist__44u5__p8_0,
  146425. NULL,
  146426. &_vq_auxt__44u5__p8_0,
  146427. NULL,
  146428. 0
  146429. };
  146430. static long _vq_quantlist__44u5__p8_1[] = {
  146431. 5,
  146432. 4,
  146433. 6,
  146434. 3,
  146435. 7,
  146436. 2,
  146437. 8,
  146438. 1,
  146439. 9,
  146440. 0,
  146441. 10,
  146442. };
  146443. static long _vq_lengthlist__44u5__p8_1[] = {
  146444. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  146445. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  146446. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  146447. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  146448. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  146449. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  146450. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146451. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146452. };
  146453. static float _vq_quantthresh__44u5__p8_1[] = {
  146454. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146455. 3.5, 4.5,
  146456. };
  146457. static long _vq_quantmap__44u5__p8_1[] = {
  146458. 9, 7, 5, 3, 1, 0, 2, 4,
  146459. 6, 8, 10,
  146460. };
  146461. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  146462. _vq_quantthresh__44u5__p8_1,
  146463. _vq_quantmap__44u5__p8_1,
  146464. 11,
  146465. 11
  146466. };
  146467. static static_codebook _44u5__p8_1 = {
  146468. 2, 121,
  146469. _vq_lengthlist__44u5__p8_1,
  146470. 1, -531365888, 1611661312, 4, 0,
  146471. _vq_quantlist__44u5__p8_1,
  146472. NULL,
  146473. &_vq_auxt__44u5__p8_1,
  146474. NULL,
  146475. 0
  146476. };
  146477. static long _vq_quantlist__44u5__p9_0[] = {
  146478. 6,
  146479. 5,
  146480. 7,
  146481. 4,
  146482. 8,
  146483. 3,
  146484. 9,
  146485. 2,
  146486. 10,
  146487. 1,
  146488. 11,
  146489. 0,
  146490. 12,
  146491. };
  146492. static long _vq_lengthlist__44u5__p9_0[] = {
  146493. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  146494. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  146495. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  146496. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  146497. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  146498. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  146499. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  146500. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  146501. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  146502. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  146503. 12,12,12,12,12,12,12,12,12,
  146504. };
  146505. static float _vq_quantthresh__44u5__p9_0[] = {
  146506. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  146507. 637.5, 892.5, 1147.5, 1402.5,
  146508. };
  146509. static long _vq_quantmap__44u5__p9_0[] = {
  146510. 11, 9, 7, 5, 3, 1, 0, 2,
  146511. 4, 6, 8, 10, 12,
  146512. };
  146513. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  146514. _vq_quantthresh__44u5__p9_0,
  146515. _vq_quantmap__44u5__p9_0,
  146516. 13,
  146517. 13
  146518. };
  146519. static static_codebook _44u5__p9_0 = {
  146520. 2, 169,
  146521. _vq_lengthlist__44u5__p9_0,
  146522. 1, -514332672, 1627381760, 4, 0,
  146523. _vq_quantlist__44u5__p9_0,
  146524. NULL,
  146525. &_vq_auxt__44u5__p9_0,
  146526. NULL,
  146527. 0
  146528. };
  146529. static long _vq_quantlist__44u5__p9_1[] = {
  146530. 7,
  146531. 6,
  146532. 8,
  146533. 5,
  146534. 9,
  146535. 4,
  146536. 10,
  146537. 3,
  146538. 11,
  146539. 2,
  146540. 12,
  146541. 1,
  146542. 13,
  146543. 0,
  146544. 14,
  146545. };
  146546. static long _vq_lengthlist__44u5__p9_1[] = {
  146547. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  146548. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  146549. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  146550. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  146551. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  146552. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  146553. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  146554. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  146555. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  146556. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  146557. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  146558. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  146559. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  146560. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  146561. 14,
  146562. };
  146563. static float _vq_quantthresh__44u5__p9_1[] = {
  146564. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  146565. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  146566. };
  146567. static long _vq_quantmap__44u5__p9_1[] = {
  146568. 13, 11, 9, 7, 5, 3, 1, 0,
  146569. 2, 4, 6, 8, 10, 12, 14,
  146570. };
  146571. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  146572. _vq_quantthresh__44u5__p9_1,
  146573. _vq_quantmap__44u5__p9_1,
  146574. 15,
  146575. 15
  146576. };
  146577. static static_codebook _44u5__p9_1 = {
  146578. 2, 225,
  146579. _vq_lengthlist__44u5__p9_1,
  146580. 1, -522338304, 1620115456, 4, 0,
  146581. _vq_quantlist__44u5__p9_1,
  146582. NULL,
  146583. &_vq_auxt__44u5__p9_1,
  146584. NULL,
  146585. 0
  146586. };
  146587. static long _vq_quantlist__44u5__p9_2[] = {
  146588. 8,
  146589. 7,
  146590. 9,
  146591. 6,
  146592. 10,
  146593. 5,
  146594. 11,
  146595. 4,
  146596. 12,
  146597. 3,
  146598. 13,
  146599. 2,
  146600. 14,
  146601. 1,
  146602. 15,
  146603. 0,
  146604. 16,
  146605. };
  146606. static long _vq_lengthlist__44u5__p9_2[] = {
  146607. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  146608. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  146609. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  146610. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  146611. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  146612. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146613. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  146614. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  146615. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  146616. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  146617. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  146618. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  146619. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  146620. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  146621. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  146622. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  146623. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  146624. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  146625. 10,
  146626. };
  146627. static float _vq_quantthresh__44u5__p9_2[] = {
  146628. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146629. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146630. };
  146631. static long _vq_quantmap__44u5__p9_2[] = {
  146632. 15, 13, 11, 9, 7, 5, 3, 1,
  146633. 0, 2, 4, 6, 8, 10, 12, 14,
  146634. 16,
  146635. };
  146636. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  146637. _vq_quantthresh__44u5__p9_2,
  146638. _vq_quantmap__44u5__p9_2,
  146639. 17,
  146640. 17
  146641. };
  146642. static static_codebook _44u5__p9_2 = {
  146643. 2, 289,
  146644. _vq_lengthlist__44u5__p9_2,
  146645. 1, -529530880, 1611661312, 5, 0,
  146646. _vq_quantlist__44u5__p9_2,
  146647. NULL,
  146648. &_vq_auxt__44u5__p9_2,
  146649. NULL,
  146650. 0
  146651. };
  146652. static long _huff_lengthlist__44u5__short[] = {
  146653. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  146654. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  146655. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  146656. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  146657. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  146658. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  146659. 6, 8,15,17,
  146660. };
  146661. static static_codebook _huff_book__44u5__short = {
  146662. 2, 100,
  146663. _huff_lengthlist__44u5__short,
  146664. 0, 0, 0, 0, 0,
  146665. NULL,
  146666. NULL,
  146667. NULL,
  146668. NULL,
  146669. 0
  146670. };
  146671. static long _huff_lengthlist__44u6__long[] = {
  146672. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  146673. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  146674. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  146675. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  146676. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  146677. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  146678. 13, 8, 7, 7,
  146679. };
  146680. static static_codebook _huff_book__44u6__long = {
  146681. 2, 100,
  146682. _huff_lengthlist__44u6__long,
  146683. 0, 0, 0, 0, 0,
  146684. NULL,
  146685. NULL,
  146686. NULL,
  146687. NULL,
  146688. 0
  146689. };
  146690. static long _vq_quantlist__44u6__p1_0[] = {
  146691. 1,
  146692. 0,
  146693. 2,
  146694. };
  146695. static long _vq_lengthlist__44u6__p1_0[] = {
  146696. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  146697. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  146698. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  146699. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  146700. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  146701. 12,
  146702. };
  146703. static float _vq_quantthresh__44u6__p1_0[] = {
  146704. -0.5, 0.5,
  146705. };
  146706. static long _vq_quantmap__44u6__p1_0[] = {
  146707. 1, 0, 2,
  146708. };
  146709. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  146710. _vq_quantthresh__44u6__p1_0,
  146711. _vq_quantmap__44u6__p1_0,
  146712. 3,
  146713. 3
  146714. };
  146715. static static_codebook _44u6__p1_0 = {
  146716. 4, 81,
  146717. _vq_lengthlist__44u6__p1_0,
  146718. 1, -535822336, 1611661312, 2, 0,
  146719. _vq_quantlist__44u6__p1_0,
  146720. NULL,
  146721. &_vq_auxt__44u6__p1_0,
  146722. NULL,
  146723. 0
  146724. };
  146725. static long _vq_quantlist__44u6__p2_0[] = {
  146726. 1,
  146727. 0,
  146728. 2,
  146729. };
  146730. static long _vq_lengthlist__44u6__p2_0[] = {
  146731. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  146732. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  146733. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  146734. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  146735. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  146736. 9,
  146737. };
  146738. static float _vq_quantthresh__44u6__p2_0[] = {
  146739. -0.5, 0.5,
  146740. };
  146741. static long _vq_quantmap__44u6__p2_0[] = {
  146742. 1, 0, 2,
  146743. };
  146744. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  146745. _vq_quantthresh__44u6__p2_0,
  146746. _vq_quantmap__44u6__p2_0,
  146747. 3,
  146748. 3
  146749. };
  146750. static static_codebook _44u6__p2_0 = {
  146751. 4, 81,
  146752. _vq_lengthlist__44u6__p2_0,
  146753. 1, -535822336, 1611661312, 2, 0,
  146754. _vq_quantlist__44u6__p2_0,
  146755. NULL,
  146756. &_vq_auxt__44u6__p2_0,
  146757. NULL,
  146758. 0
  146759. };
  146760. static long _vq_quantlist__44u6__p3_0[] = {
  146761. 2,
  146762. 1,
  146763. 3,
  146764. 0,
  146765. 4,
  146766. };
  146767. static long _vq_lengthlist__44u6__p3_0[] = {
  146768. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  146769. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  146770. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  146771. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  146772. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  146773. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  146774. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  146775. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  146776. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  146777. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  146778. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  146779. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  146780. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  146781. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  146782. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  146783. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  146784. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  146785. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  146786. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  146787. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  146788. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  146789. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  146790. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  146791. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  146792. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  146793. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  146794. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  146795. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  146796. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  146797. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  146798. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  146799. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  146800. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  146801. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  146802. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  146803. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  146804. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  146805. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  146806. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  146807. 19,
  146808. };
  146809. static float _vq_quantthresh__44u6__p3_0[] = {
  146810. -1.5, -0.5, 0.5, 1.5,
  146811. };
  146812. static long _vq_quantmap__44u6__p3_0[] = {
  146813. 3, 1, 0, 2, 4,
  146814. };
  146815. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  146816. _vq_quantthresh__44u6__p3_0,
  146817. _vq_quantmap__44u6__p3_0,
  146818. 5,
  146819. 5
  146820. };
  146821. static static_codebook _44u6__p3_0 = {
  146822. 4, 625,
  146823. _vq_lengthlist__44u6__p3_0,
  146824. 1, -533725184, 1611661312, 3, 0,
  146825. _vq_quantlist__44u6__p3_0,
  146826. NULL,
  146827. &_vq_auxt__44u6__p3_0,
  146828. NULL,
  146829. 0
  146830. };
  146831. static long _vq_quantlist__44u6__p4_0[] = {
  146832. 2,
  146833. 1,
  146834. 3,
  146835. 0,
  146836. 4,
  146837. };
  146838. static long _vq_lengthlist__44u6__p4_0[] = {
  146839. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  146840. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  146841. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  146842. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  146843. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  146844. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  146845. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  146846. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  146847. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  146848. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  146849. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  146850. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  146851. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  146852. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  146853. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  146854. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  146855. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  146856. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  146857. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  146858. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  146859. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  146860. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  146861. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  146862. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  146863. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  146864. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  146865. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  146866. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  146867. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  146868. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  146869. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  146870. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  146871. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  146872. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  146873. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  146874. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  146875. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  146876. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  146877. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  146878. 13,
  146879. };
  146880. static float _vq_quantthresh__44u6__p4_0[] = {
  146881. -1.5, -0.5, 0.5, 1.5,
  146882. };
  146883. static long _vq_quantmap__44u6__p4_0[] = {
  146884. 3, 1, 0, 2, 4,
  146885. };
  146886. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  146887. _vq_quantthresh__44u6__p4_0,
  146888. _vq_quantmap__44u6__p4_0,
  146889. 5,
  146890. 5
  146891. };
  146892. static static_codebook _44u6__p4_0 = {
  146893. 4, 625,
  146894. _vq_lengthlist__44u6__p4_0,
  146895. 1, -533725184, 1611661312, 3, 0,
  146896. _vq_quantlist__44u6__p4_0,
  146897. NULL,
  146898. &_vq_auxt__44u6__p4_0,
  146899. NULL,
  146900. 0
  146901. };
  146902. static long _vq_quantlist__44u6__p5_0[] = {
  146903. 4,
  146904. 3,
  146905. 5,
  146906. 2,
  146907. 6,
  146908. 1,
  146909. 7,
  146910. 0,
  146911. 8,
  146912. };
  146913. static long _vq_lengthlist__44u6__p5_0[] = {
  146914. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  146915. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  146916. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  146917. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  146918. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  146919. 14,
  146920. };
  146921. static float _vq_quantthresh__44u6__p5_0[] = {
  146922. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146923. };
  146924. static long _vq_quantmap__44u6__p5_0[] = {
  146925. 7, 5, 3, 1, 0, 2, 4, 6,
  146926. 8,
  146927. };
  146928. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  146929. _vq_quantthresh__44u6__p5_0,
  146930. _vq_quantmap__44u6__p5_0,
  146931. 9,
  146932. 9
  146933. };
  146934. static static_codebook _44u6__p5_0 = {
  146935. 2, 81,
  146936. _vq_lengthlist__44u6__p5_0,
  146937. 1, -531628032, 1611661312, 4, 0,
  146938. _vq_quantlist__44u6__p5_0,
  146939. NULL,
  146940. &_vq_auxt__44u6__p5_0,
  146941. NULL,
  146942. 0
  146943. };
  146944. static long _vq_quantlist__44u6__p6_0[] = {
  146945. 4,
  146946. 3,
  146947. 5,
  146948. 2,
  146949. 6,
  146950. 1,
  146951. 7,
  146952. 0,
  146953. 8,
  146954. };
  146955. static long _vq_lengthlist__44u6__p6_0[] = {
  146956. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  146957. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  146958. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  146959. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  146960. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  146961. 12,
  146962. };
  146963. static float _vq_quantthresh__44u6__p6_0[] = {
  146964. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146965. };
  146966. static long _vq_quantmap__44u6__p6_0[] = {
  146967. 7, 5, 3, 1, 0, 2, 4, 6,
  146968. 8,
  146969. };
  146970. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  146971. _vq_quantthresh__44u6__p6_0,
  146972. _vq_quantmap__44u6__p6_0,
  146973. 9,
  146974. 9
  146975. };
  146976. static static_codebook _44u6__p6_0 = {
  146977. 2, 81,
  146978. _vq_lengthlist__44u6__p6_0,
  146979. 1, -531628032, 1611661312, 4, 0,
  146980. _vq_quantlist__44u6__p6_0,
  146981. NULL,
  146982. &_vq_auxt__44u6__p6_0,
  146983. NULL,
  146984. 0
  146985. };
  146986. static long _vq_quantlist__44u6__p7_0[] = {
  146987. 1,
  146988. 0,
  146989. 2,
  146990. };
  146991. static long _vq_lengthlist__44u6__p7_0[] = {
  146992. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  146993. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  146994. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  146995. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  146996. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  146997. 10,
  146998. };
  146999. static float _vq_quantthresh__44u6__p7_0[] = {
  147000. -5.5, 5.5,
  147001. };
  147002. static long _vq_quantmap__44u6__p7_0[] = {
  147003. 1, 0, 2,
  147004. };
  147005. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  147006. _vq_quantthresh__44u6__p7_0,
  147007. _vq_quantmap__44u6__p7_0,
  147008. 3,
  147009. 3
  147010. };
  147011. static static_codebook _44u6__p7_0 = {
  147012. 4, 81,
  147013. _vq_lengthlist__44u6__p7_0,
  147014. 1, -529137664, 1618345984, 2, 0,
  147015. _vq_quantlist__44u6__p7_0,
  147016. NULL,
  147017. &_vq_auxt__44u6__p7_0,
  147018. NULL,
  147019. 0
  147020. };
  147021. static long _vq_quantlist__44u6__p7_1[] = {
  147022. 5,
  147023. 4,
  147024. 6,
  147025. 3,
  147026. 7,
  147027. 2,
  147028. 8,
  147029. 1,
  147030. 9,
  147031. 0,
  147032. 10,
  147033. };
  147034. static long _vq_lengthlist__44u6__p7_1[] = {
  147035. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  147036. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  147037. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  147038. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  147039. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  147040. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  147041. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  147042. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147043. };
  147044. static float _vq_quantthresh__44u6__p7_1[] = {
  147045. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  147046. 3.5, 4.5,
  147047. };
  147048. static long _vq_quantmap__44u6__p7_1[] = {
  147049. 9, 7, 5, 3, 1, 0, 2, 4,
  147050. 6, 8, 10,
  147051. };
  147052. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  147053. _vq_quantthresh__44u6__p7_1,
  147054. _vq_quantmap__44u6__p7_1,
  147055. 11,
  147056. 11
  147057. };
  147058. static static_codebook _44u6__p7_1 = {
  147059. 2, 121,
  147060. _vq_lengthlist__44u6__p7_1,
  147061. 1, -531365888, 1611661312, 4, 0,
  147062. _vq_quantlist__44u6__p7_1,
  147063. NULL,
  147064. &_vq_auxt__44u6__p7_1,
  147065. NULL,
  147066. 0
  147067. };
  147068. static long _vq_quantlist__44u6__p8_0[] = {
  147069. 5,
  147070. 4,
  147071. 6,
  147072. 3,
  147073. 7,
  147074. 2,
  147075. 8,
  147076. 1,
  147077. 9,
  147078. 0,
  147079. 10,
  147080. };
  147081. static long _vq_lengthlist__44u6__p8_0[] = {
  147082. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  147083. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  147084. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  147085. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  147086. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  147087. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  147088. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  147089. 12,13,13,14,14,14,15,15,15,
  147090. };
  147091. static float _vq_quantthresh__44u6__p8_0[] = {
  147092. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  147093. 38.5, 49.5,
  147094. };
  147095. static long _vq_quantmap__44u6__p8_0[] = {
  147096. 9, 7, 5, 3, 1, 0, 2, 4,
  147097. 6, 8, 10,
  147098. };
  147099. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  147100. _vq_quantthresh__44u6__p8_0,
  147101. _vq_quantmap__44u6__p8_0,
  147102. 11,
  147103. 11
  147104. };
  147105. static static_codebook _44u6__p8_0 = {
  147106. 2, 121,
  147107. _vq_lengthlist__44u6__p8_0,
  147108. 1, -524582912, 1618345984, 4, 0,
  147109. _vq_quantlist__44u6__p8_0,
  147110. NULL,
  147111. &_vq_auxt__44u6__p8_0,
  147112. NULL,
  147113. 0
  147114. };
  147115. static long _vq_quantlist__44u6__p8_1[] = {
  147116. 5,
  147117. 4,
  147118. 6,
  147119. 3,
  147120. 7,
  147121. 2,
  147122. 8,
  147123. 1,
  147124. 9,
  147125. 0,
  147126. 10,
  147127. };
  147128. static long _vq_lengthlist__44u6__p8_1[] = {
  147129. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  147130. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  147131. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  147132. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  147133. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  147134. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  147135. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  147136. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  147137. };
  147138. static float _vq_quantthresh__44u6__p8_1[] = {
  147139. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  147140. 3.5, 4.5,
  147141. };
  147142. static long _vq_quantmap__44u6__p8_1[] = {
  147143. 9, 7, 5, 3, 1, 0, 2, 4,
  147144. 6, 8, 10,
  147145. };
  147146. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  147147. _vq_quantthresh__44u6__p8_1,
  147148. _vq_quantmap__44u6__p8_1,
  147149. 11,
  147150. 11
  147151. };
  147152. static static_codebook _44u6__p8_1 = {
  147153. 2, 121,
  147154. _vq_lengthlist__44u6__p8_1,
  147155. 1, -531365888, 1611661312, 4, 0,
  147156. _vq_quantlist__44u6__p8_1,
  147157. NULL,
  147158. &_vq_auxt__44u6__p8_1,
  147159. NULL,
  147160. 0
  147161. };
  147162. static long _vq_quantlist__44u6__p9_0[] = {
  147163. 7,
  147164. 6,
  147165. 8,
  147166. 5,
  147167. 9,
  147168. 4,
  147169. 10,
  147170. 3,
  147171. 11,
  147172. 2,
  147173. 12,
  147174. 1,
  147175. 13,
  147176. 0,
  147177. 14,
  147178. };
  147179. static long _vq_lengthlist__44u6__p9_0[] = {
  147180. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  147181. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  147182. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  147183. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  147184. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  147185. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  147186. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  147187. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  147188. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  147189. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  147190. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  147191. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  147192. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  147193. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  147194. 14,
  147195. };
  147196. static float _vq_quantthresh__44u6__p9_0[] = {
  147197. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  147198. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  147199. };
  147200. static long _vq_quantmap__44u6__p9_0[] = {
  147201. 13, 11, 9, 7, 5, 3, 1, 0,
  147202. 2, 4, 6, 8, 10, 12, 14,
  147203. };
  147204. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  147205. _vq_quantthresh__44u6__p9_0,
  147206. _vq_quantmap__44u6__p9_0,
  147207. 15,
  147208. 15
  147209. };
  147210. static static_codebook _44u6__p9_0 = {
  147211. 2, 225,
  147212. _vq_lengthlist__44u6__p9_0,
  147213. 1, -514071552, 1627381760, 4, 0,
  147214. _vq_quantlist__44u6__p9_0,
  147215. NULL,
  147216. &_vq_auxt__44u6__p9_0,
  147217. NULL,
  147218. 0
  147219. };
  147220. static long _vq_quantlist__44u6__p9_1[] = {
  147221. 7,
  147222. 6,
  147223. 8,
  147224. 5,
  147225. 9,
  147226. 4,
  147227. 10,
  147228. 3,
  147229. 11,
  147230. 2,
  147231. 12,
  147232. 1,
  147233. 13,
  147234. 0,
  147235. 14,
  147236. };
  147237. static long _vq_lengthlist__44u6__p9_1[] = {
  147238. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  147239. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  147240. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  147241. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  147242. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  147243. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  147244. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  147245. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  147246. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  147247. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  147248. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  147249. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  147250. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  147251. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  147252. 13,
  147253. };
  147254. static float _vq_quantthresh__44u6__p9_1[] = {
  147255. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  147256. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  147257. };
  147258. static long _vq_quantmap__44u6__p9_1[] = {
  147259. 13, 11, 9, 7, 5, 3, 1, 0,
  147260. 2, 4, 6, 8, 10, 12, 14,
  147261. };
  147262. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  147263. _vq_quantthresh__44u6__p9_1,
  147264. _vq_quantmap__44u6__p9_1,
  147265. 15,
  147266. 15
  147267. };
  147268. static static_codebook _44u6__p9_1 = {
  147269. 2, 225,
  147270. _vq_lengthlist__44u6__p9_1,
  147271. 1, -522338304, 1620115456, 4, 0,
  147272. _vq_quantlist__44u6__p9_1,
  147273. NULL,
  147274. &_vq_auxt__44u6__p9_1,
  147275. NULL,
  147276. 0
  147277. };
  147278. static long _vq_quantlist__44u6__p9_2[] = {
  147279. 8,
  147280. 7,
  147281. 9,
  147282. 6,
  147283. 10,
  147284. 5,
  147285. 11,
  147286. 4,
  147287. 12,
  147288. 3,
  147289. 13,
  147290. 2,
  147291. 14,
  147292. 1,
  147293. 15,
  147294. 0,
  147295. 16,
  147296. };
  147297. static long _vq_lengthlist__44u6__p9_2[] = {
  147298. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  147299. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  147300. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  147301. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147302. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147303. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147304. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147305. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147306. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147307. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  147308. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  147309. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147310. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  147311. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  147312. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  147313. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  147314. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  147315. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  147316. 10,
  147317. };
  147318. static float _vq_quantthresh__44u6__p9_2[] = {
  147319. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147320. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147321. };
  147322. static long _vq_quantmap__44u6__p9_2[] = {
  147323. 15, 13, 11, 9, 7, 5, 3, 1,
  147324. 0, 2, 4, 6, 8, 10, 12, 14,
  147325. 16,
  147326. };
  147327. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  147328. _vq_quantthresh__44u6__p9_2,
  147329. _vq_quantmap__44u6__p9_2,
  147330. 17,
  147331. 17
  147332. };
  147333. static static_codebook _44u6__p9_2 = {
  147334. 2, 289,
  147335. _vq_lengthlist__44u6__p9_2,
  147336. 1, -529530880, 1611661312, 5, 0,
  147337. _vq_quantlist__44u6__p9_2,
  147338. NULL,
  147339. &_vq_auxt__44u6__p9_2,
  147340. NULL,
  147341. 0
  147342. };
  147343. static long _huff_lengthlist__44u6__short[] = {
  147344. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  147345. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  147346. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  147347. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  147348. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  147349. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  147350. 7, 6, 9,16,
  147351. };
  147352. static static_codebook _huff_book__44u6__short = {
  147353. 2, 100,
  147354. _huff_lengthlist__44u6__short,
  147355. 0, 0, 0, 0, 0,
  147356. NULL,
  147357. NULL,
  147358. NULL,
  147359. NULL,
  147360. 0
  147361. };
  147362. static long _huff_lengthlist__44u7__long[] = {
  147363. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  147364. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  147365. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  147366. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  147367. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  147368. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  147369. 12, 8, 6, 7,
  147370. };
  147371. static static_codebook _huff_book__44u7__long = {
  147372. 2, 100,
  147373. _huff_lengthlist__44u7__long,
  147374. 0, 0, 0, 0, 0,
  147375. NULL,
  147376. NULL,
  147377. NULL,
  147378. NULL,
  147379. 0
  147380. };
  147381. static long _vq_quantlist__44u7__p1_0[] = {
  147382. 1,
  147383. 0,
  147384. 2,
  147385. };
  147386. static long _vq_lengthlist__44u7__p1_0[] = {
  147387. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  147388. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  147389. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  147390. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  147391. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  147392. 12,
  147393. };
  147394. static float _vq_quantthresh__44u7__p1_0[] = {
  147395. -0.5, 0.5,
  147396. };
  147397. static long _vq_quantmap__44u7__p1_0[] = {
  147398. 1, 0, 2,
  147399. };
  147400. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  147401. _vq_quantthresh__44u7__p1_0,
  147402. _vq_quantmap__44u7__p1_0,
  147403. 3,
  147404. 3
  147405. };
  147406. static static_codebook _44u7__p1_0 = {
  147407. 4, 81,
  147408. _vq_lengthlist__44u7__p1_0,
  147409. 1, -535822336, 1611661312, 2, 0,
  147410. _vq_quantlist__44u7__p1_0,
  147411. NULL,
  147412. &_vq_auxt__44u7__p1_0,
  147413. NULL,
  147414. 0
  147415. };
  147416. static long _vq_quantlist__44u7__p2_0[] = {
  147417. 1,
  147418. 0,
  147419. 2,
  147420. };
  147421. static long _vq_lengthlist__44u7__p2_0[] = {
  147422. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  147423. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  147424. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  147425. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  147426. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  147427. 9,
  147428. };
  147429. static float _vq_quantthresh__44u7__p2_0[] = {
  147430. -0.5, 0.5,
  147431. };
  147432. static long _vq_quantmap__44u7__p2_0[] = {
  147433. 1, 0, 2,
  147434. };
  147435. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  147436. _vq_quantthresh__44u7__p2_0,
  147437. _vq_quantmap__44u7__p2_0,
  147438. 3,
  147439. 3
  147440. };
  147441. static static_codebook _44u7__p2_0 = {
  147442. 4, 81,
  147443. _vq_lengthlist__44u7__p2_0,
  147444. 1, -535822336, 1611661312, 2, 0,
  147445. _vq_quantlist__44u7__p2_0,
  147446. NULL,
  147447. &_vq_auxt__44u7__p2_0,
  147448. NULL,
  147449. 0
  147450. };
  147451. static long _vq_quantlist__44u7__p3_0[] = {
  147452. 2,
  147453. 1,
  147454. 3,
  147455. 0,
  147456. 4,
  147457. };
  147458. static long _vq_lengthlist__44u7__p3_0[] = {
  147459. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  147460. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  147461. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  147462. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  147463. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  147464. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  147465. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  147466. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  147467. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  147468. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147469. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  147470. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147471. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  147472. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  147473. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  147474. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  147475. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  147476. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  147477. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  147478. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  147479. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  147480. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  147481. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  147482. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  147483. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  147484. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  147485. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  147486. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  147487. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  147488. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  147489. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  147490. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  147491. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  147492. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  147493. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  147494. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  147495. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  147496. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  147497. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  147498. 0,
  147499. };
  147500. static float _vq_quantthresh__44u7__p3_0[] = {
  147501. -1.5, -0.5, 0.5, 1.5,
  147502. };
  147503. static long _vq_quantmap__44u7__p3_0[] = {
  147504. 3, 1, 0, 2, 4,
  147505. };
  147506. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  147507. _vq_quantthresh__44u7__p3_0,
  147508. _vq_quantmap__44u7__p3_0,
  147509. 5,
  147510. 5
  147511. };
  147512. static static_codebook _44u7__p3_0 = {
  147513. 4, 625,
  147514. _vq_lengthlist__44u7__p3_0,
  147515. 1, -533725184, 1611661312, 3, 0,
  147516. _vq_quantlist__44u7__p3_0,
  147517. NULL,
  147518. &_vq_auxt__44u7__p3_0,
  147519. NULL,
  147520. 0
  147521. };
  147522. static long _vq_quantlist__44u7__p4_0[] = {
  147523. 2,
  147524. 1,
  147525. 3,
  147526. 0,
  147527. 4,
  147528. };
  147529. static long _vq_lengthlist__44u7__p4_0[] = {
  147530. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  147531. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  147532. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  147533. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  147534. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  147535. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  147536. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  147537. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  147538. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  147539. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  147540. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  147541. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  147542. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  147543. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  147544. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  147545. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  147546. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  147547. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  147548. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  147549. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  147550. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  147551. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  147552. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  147553. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  147554. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  147555. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  147556. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  147557. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  147558. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  147559. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  147560. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  147561. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  147562. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  147563. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  147564. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  147565. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  147566. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  147567. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  147568. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  147569. 14,
  147570. };
  147571. static float _vq_quantthresh__44u7__p4_0[] = {
  147572. -1.5, -0.5, 0.5, 1.5,
  147573. };
  147574. static long _vq_quantmap__44u7__p4_0[] = {
  147575. 3, 1, 0, 2, 4,
  147576. };
  147577. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  147578. _vq_quantthresh__44u7__p4_0,
  147579. _vq_quantmap__44u7__p4_0,
  147580. 5,
  147581. 5
  147582. };
  147583. static static_codebook _44u7__p4_0 = {
  147584. 4, 625,
  147585. _vq_lengthlist__44u7__p4_0,
  147586. 1, -533725184, 1611661312, 3, 0,
  147587. _vq_quantlist__44u7__p4_0,
  147588. NULL,
  147589. &_vq_auxt__44u7__p4_0,
  147590. NULL,
  147591. 0
  147592. };
  147593. static long _vq_quantlist__44u7__p5_0[] = {
  147594. 4,
  147595. 3,
  147596. 5,
  147597. 2,
  147598. 6,
  147599. 1,
  147600. 7,
  147601. 0,
  147602. 8,
  147603. };
  147604. static long _vq_lengthlist__44u7__p5_0[] = {
  147605. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  147606. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  147607. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  147608. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  147609. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  147610. 14,
  147611. };
  147612. static float _vq_quantthresh__44u7__p5_0[] = {
  147613. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147614. };
  147615. static long _vq_quantmap__44u7__p5_0[] = {
  147616. 7, 5, 3, 1, 0, 2, 4, 6,
  147617. 8,
  147618. };
  147619. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  147620. _vq_quantthresh__44u7__p5_0,
  147621. _vq_quantmap__44u7__p5_0,
  147622. 9,
  147623. 9
  147624. };
  147625. static static_codebook _44u7__p5_0 = {
  147626. 2, 81,
  147627. _vq_lengthlist__44u7__p5_0,
  147628. 1, -531628032, 1611661312, 4, 0,
  147629. _vq_quantlist__44u7__p5_0,
  147630. NULL,
  147631. &_vq_auxt__44u7__p5_0,
  147632. NULL,
  147633. 0
  147634. };
  147635. static long _vq_quantlist__44u7__p6_0[] = {
  147636. 4,
  147637. 3,
  147638. 5,
  147639. 2,
  147640. 6,
  147641. 1,
  147642. 7,
  147643. 0,
  147644. 8,
  147645. };
  147646. static long _vq_lengthlist__44u7__p6_0[] = {
  147647. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  147648. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  147649. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  147650. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  147651. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  147652. 12,
  147653. };
  147654. static float _vq_quantthresh__44u7__p6_0[] = {
  147655. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147656. };
  147657. static long _vq_quantmap__44u7__p6_0[] = {
  147658. 7, 5, 3, 1, 0, 2, 4, 6,
  147659. 8,
  147660. };
  147661. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  147662. _vq_quantthresh__44u7__p6_0,
  147663. _vq_quantmap__44u7__p6_0,
  147664. 9,
  147665. 9
  147666. };
  147667. static static_codebook _44u7__p6_0 = {
  147668. 2, 81,
  147669. _vq_lengthlist__44u7__p6_0,
  147670. 1, -531628032, 1611661312, 4, 0,
  147671. _vq_quantlist__44u7__p6_0,
  147672. NULL,
  147673. &_vq_auxt__44u7__p6_0,
  147674. NULL,
  147675. 0
  147676. };
  147677. static long _vq_quantlist__44u7__p7_0[] = {
  147678. 1,
  147679. 0,
  147680. 2,
  147681. };
  147682. static long _vq_lengthlist__44u7__p7_0[] = {
  147683. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  147684. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  147685. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  147686. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  147687. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  147688. 10,
  147689. };
  147690. static float _vq_quantthresh__44u7__p7_0[] = {
  147691. -5.5, 5.5,
  147692. };
  147693. static long _vq_quantmap__44u7__p7_0[] = {
  147694. 1, 0, 2,
  147695. };
  147696. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  147697. _vq_quantthresh__44u7__p7_0,
  147698. _vq_quantmap__44u7__p7_0,
  147699. 3,
  147700. 3
  147701. };
  147702. static static_codebook _44u7__p7_0 = {
  147703. 4, 81,
  147704. _vq_lengthlist__44u7__p7_0,
  147705. 1, -529137664, 1618345984, 2, 0,
  147706. _vq_quantlist__44u7__p7_0,
  147707. NULL,
  147708. &_vq_auxt__44u7__p7_0,
  147709. NULL,
  147710. 0
  147711. };
  147712. static long _vq_quantlist__44u7__p7_1[] = {
  147713. 5,
  147714. 4,
  147715. 6,
  147716. 3,
  147717. 7,
  147718. 2,
  147719. 8,
  147720. 1,
  147721. 9,
  147722. 0,
  147723. 10,
  147724. };
  147725. static long _vq_lengthlist__44u7__p7_1[] = {
  147726. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  147727. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  147728. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  147729. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  147730. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  147731. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147732. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  147733. 8, 9, 9, 9, 9, 9,10,10,10,
  147734. };
  147735. static float _vq_quantthresh__44u7__p7_1[] = {
  147736. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  147737. 3.5, 4.5,
  147738. };
  147739. static long _vq_quantmap__44u7__p7_1[] = {
  147740. 9, 7, 5, 3, 1, 0, 2, 4,
  147741. 6, 8, 10,
  147742. };
  147743. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  147744. _vq_quantthresh__44u7__p7_1,
  147745. _vq_quantmap__44u7__p7_1,
  147746. 11,
  147747. 11
  147748. };
  147749. static static_codebook _44u7__p7_1 = {
  147750. 2, 121,
  147751. _vq_lengthlist__44u7__p7_1,
  147752. 1, -531365888, 1611661312, 4, 0,
  147753. _vq_quantlist__44u7__p7_1,
  147754. NULL,
  147755. &_vq_auxt__44u7__p7_1,
  147756. NULL,
  147757. 0
  147758. };
  147759. static long _vq_quantlist__44u7__p8_0[] = {
  147760. 5,
  147761. 4,
  147762. 6,
  147763. 3,
  147764. 7,
  147765. 2,
  147766. 8,
  147767. 1,
  147768. 9,
  147769. 0,
  147770. 10,
  147771. };
  147772. static long _vq_lengthlist__44u7__p8_0[] = {
  147773. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  147774. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  147775. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  147776. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  147777. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  147778. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  147779. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  147780. 12,13,13,14,14,15,15,15,16,
  147781. };
  147782. static float _vq_quantthresh__44u7__p8_0[] = {
  147783. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  147784. 38.5, 49.5,
  147785. };
  147786. static long _vq_quantmap__44u7__p8_0[] = {
  147787. 9, 7, 5, 3, 1, 0, 2, 4,
  147788. 6, 8, 10,
  147789. };
  147790. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  147791. _vq_quantthresh__44u7__p8_0,
  147792. _vq_quantmap__44u7__p8_0,
  147793. 11,
  147794. 11
  147795. };
  147796. static static_codebook _44u7__p8_0 = {
  147797. 2, 121,
  147798. _vq_lengthlist__44u7__p8_0,
  147799. 1, -524582912, 1618345984, 4, 0,
  147800. _vq_quantlist__44u7__p8_0,
  147801. NULL,
  147802. &_vq_auxt__44u7__p8_0,
  147803. NULL,
  147804. 0
  147805. };
  147806. static long _vq_quantlist__44u7__p8_1[] = {
  147807. 5,
  147808. 4,
  147809. 6,
  147810. 3,
  147811. 7,
  147812. 2,
  147813. 8,
  147814. 1,
  147815. 9,
  147816. 0,
  147817. 10,
  147818. };
  147819. static long _vq_lengthlist__44u7__p8_1[] = {
  147820. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  147821. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  147822. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  147823. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  147824. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  147825. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  147826. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  147827. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  147828. };
  147829. static float _vq_quantthresh__44u7__p8_1[] = {
  147830. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  147831. 3.5, 4.5,
  147832. };
  147833. static long _vq_quantmap__44u7__p8_1[] = {
  147834. 9, 7, 5, 3, 1, 0, 2, 4,
  147835. 6, 8, 10,
  147836. };
  147837. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  147838. _vq_quantthresh__44u7__p8_1,
  147839. _vq_quantmap__44u7__p8_1,
  147840. 11,
  147841. 11
  147842. };
  147843. static static_codebook _44u7__p8_1 = {
  147844. 2, 121,
  147845. _vq_lengthlist__44u7__p8_1,
  147846. 1, -531365888, 1611661312, 4, 0,
  147847. _vq_quantlist__44u7__p8_1,
  147848. NULL,
  147849. &_vq_auxt__44u7__p8_1,
  147850. NULL,
  147851. 0
  147852. };
  147853. static long _vq_quantlist__44u7__p9_0[] = {
  147854. 5,
  147855. 4,
  147856. 6,
  147857. 3,
  147858. 7,
  147859. 2,
  147860. 8,
  147861. 1,
  147862. 9,
  147863. 0,
  147864. 10,
  147865. };
  147866. static long _vq_lengthlist__44u7__p9_0[] = {
  147867. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  147868. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  147869. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147870. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147871. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147872. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147873. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  147874. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147875. };
  147876. static float _vq_quantthresh__44u7__p9_0[] = {
  147877. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  147878. 2229.5, 2866.5,
  147879. };
  147880. static long _vq_quantmap__44u7__p9_0[] = {
  147881. 9, 7, 5, 3, 1, 0, 2, 4,
  147882. 6, 8, 10,
  147883. };
  147884. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  147885. _vq_quantthresh__44u7__p9_0,
  147886. _vq_quantmap__44u7__p9_0,
  147887. 11,
  147888. 11
  147889. };
  147890. static static_codebook _44u7__p9_0 = {
  147891. 2, 121,
  147892. _vq_lengthlist__44u7__p9_0,
  147893. 1, -512171520, 1630791680, 4, 0,
  147894. _vq_quantlist__44u7__p9_0,
  147895. NULL,
  147896. &_vq_auxt__44u7__p9_0,
  147897. NULL,
  147898. 0
  147899. };
  147900. static long _vq_quantlist__44u7__p9_1[] = {
  147901. 6,
  147902. 5,
  147903. 7,
  147904. 4,
  147905. 8,
  147906. 3,
  147907. 9,
  147908. 2,
  147909. 10,
  147910. 1,
  147911. 11,
  147912. 0,
  147913. 12,
  147914. };
  147915. static long _vq_lengthlist__44u7__p9_1[] = {
  147916. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  147917. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  147918. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  147919. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  147920. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  147921. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  147922. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  147923. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  147924. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  147925. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  147926. 15,15,15,15,17,17,16,17,16,
  147927. };
  147928. static float _vq_quantthresh__44u7__p9_1[] = {
  147929. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  147930. 122.5, 171.5, 220.5, 269.5,
  147931. };
  147932. static long _vq_quantmap__44u7__p9_1[] = {
  147933. 11, 9, 7, 5, 3, 1, 0, 2,
  147934. 4, 6, 8, 10, 12,
  147935. };
  147936. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  147937. _vq_quantthresh__44u7__p9_1,
  147938. _vq_quantmap__44u7__p9_1,
  147939. 13,
  147940. 13
  147941. };
  147942. static static_codebook _44u7__p9_1 = {
  147943. 2, 169,
  147944. _vq_lengthlist__44u7__p9_1,
  147945. 1, -518889472, 1622704128, 4, 0,
  147946. _vq_quantlist__44u7__p9_1,
  147947. NULL,
  147948. &_vq_auxt__44u7__p9_1,
  147949. NULL,
  147950. 0
  147951. };
  147952. static long _vq_quantlist__44u7__p9_2[] = {
  147953. 24,
  147954. 23,
  147955. 25,
  147956. 22,
  147957. 26,
  147958. 21,
  147959. 27,
  147960. 20,
  147961. 28,
  147962. 19,
  147963. 29,
  147964. 18,
  147965. 30,
  147966. 17,
  147967. 31,
  147968. 16,
  147969. 32,
  147970. 15,
  147971. 33,
  147972. 14,
  147973. 34,
  147974. 13,
  147975. 35,
  147976. 12,
  147977. 36,
  147978. 11,
  147979. 37,
  147980. 10,
  147981. 38,
  147982. 9,
  147983. 39,
  147984. 8,
  147985. 40,
  147986. 7,
  147987. 41,
  147988. 6,
  147989. 42,
  147990. 5,
  147991. 43,
  147992. 4,
  147993. 44,
  147994. 3,
  147995. 45,
  147996. 2,
  147997. 46,
  147998. 1,
  147999. 47,
  148000. 0,
  148001. 48,
  148002. };
  148003. static long _vq_lengthlist__44u7__p9_2[] = {
  148004. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  148005. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  148006. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  148007. 8,
  148008. };
  148009. static float _vq_quantthresh__44u7__p9_2[] = {
  148010. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  148011. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  148012. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148013. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148014. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  148015. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  148016. };
  148017. static long _vq_quantmap__44u7__p9_2[] = {
  148018. 47, 45, 43, 41, 39, 37, 35, 33,
  148019. 31, 29, 27, 25, 23, 21, 19, 17,
  148020. 15, 13, 11, 9, 7, 5, 3, 1,
  148021. 0, 2, 4, 6, 8, 10, 12, 14,
  148022. 16, 18, 20, 22, 24, 26, 28, 30,
  148023. 32, 34, 36, 38, 40, 42, 44, 46,
  148024. 48,
  148025. };
  148026. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  148027. _vq_quantthresh__44u7__p9_2,
  148028. _vq_quantmap__44u7__p9_2,
  148029. 49,
  148030. 49
  148031. };
  148032. static static_codebook _44u7__p9_2 = {
  148033. 1, 49,
  148034. _vq_lengthlist__44u7__p9_2,
  148035. 1, -526909440, 1611661312, 6, 0,
  148036. _vq_quantlist__44u7__p9_2,
  148037. NULL,
  148038. &_vq_auxt__44u7__p9_2,
  148039. NULL,
  148040. 0
  148041. };
  148042. static long _huff_lengthlist__44u7__short[] = {
  148043. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  148044. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  148045. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  148046. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  148047. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  148048. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  148049. 6, 8, 5, 9,
  148050. };
  148051. static static_codebook _huff_book__44u7__short = {
  148052. 2, 100,
  148053. _huff_lengthlist__44u7__short,
  148054. 0, 0, 0, 0, 0,
  148055. NULL,
  148056. NULL,
  148057. NULL,
  148058. NULL,
  148059. 0
  148060. };
  148061. static long _huff_lengthlist__44u8__long[] = {
  148062. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  148063. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  148064. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  148065. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  148066. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  148067. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  148068. 10, 8, 8, 9,
  148069. };
  148070. static static_codebook _huff_book__44u8__long = {
  148071. 2, 100,
  148072. _huff_lengthlist__44u8__long,
  148073. 0, 0, 0, 0, 0,
  148074. NULL,
  148075. NULL,
  148076. NULL,
  148077. NULL,
  148078. 0
  148079. };
  148080. static long _huff_lengthlist__44u8__short[] = {
  148081. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  148082. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  148083. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  148084. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  148085. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  148086. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  148087. 10,10,15,17,
  148088. };
  148089. static static_codebook _huff_book__44u8__short = {
  148090. 2, 100,
  148091. _huff_lengthlist__44u8__short,
  148092. 0, 0, 0, 0, 0,
  148093. NULL,
  148094. NULL,
  148095. NULL,
  148096. NULL,
  148097. 0
  148098. };
  148099. static long _vq_quantlist__44u8_p1_0[] = {
  148100. 1,
  148101. 0,
  148102. 2,
  148103. };
  148104. static long _vq_lengthlist__44u8_p1_0[] = {
  148105. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  148106. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  148107. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  148108. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  148109. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  148110. 10,
  148111. };
  148112. static float _vq_quantthresh__44u8_p1_0[] = {
  148113. -0.5, 0.5,
  148114. };
  148115. static long _vq_quantmap__44u8_p1_0[] = {
  148116. 1, 0, 2,
  148117. };
  148118. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  148119. _vq_quantthresh__44u8_p1_0,
  148120. _vq_quantmap__44u8_p1_0,
  148121. 3,
  148122. 3
  148123. };
  148124. static static_codebook _44u8_p1_0 = {
  148125. 4, 81,
  148126. _vq_lengthlist__44u8_p1_0,
  148127. 1, -535822336, 1611661312, 2, 0,
  148128. _vq_quantlist__44u8_p1_0,
  148129. NULL,
  148130. &_vq_auxt__44u8_p1_0,
  148131. NULL,
  148132. 0
  148133. };
  148134. static long _vq_quantlist__44u8_p2_0[] = {
  148135. 2,
  148136. 1,
  148137. 3,
  148138. 0,
  148139. 4,
  148140. };
  148141. static long _vq_lengthlist__44u8_p2_0[] = {
  148142. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  148143. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148144. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  148145. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148146. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  148147. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  148148. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  148149. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  148150. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  148151. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  148152. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  148153. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148154. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  148155. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  148156. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  148157. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  148158. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  148159. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  148160. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  148161. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  148162. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  148163. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  148164. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  148165. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  148166. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  148167. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  148168. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  148169. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  148170. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  148171. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  148172. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  148173. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  148174. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  148175. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  148176. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  148177. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  148178. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  148179. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  148180. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  148181. 14,
  148182. };
  148183. static float _vq_quantthresh__44u8_p2_0[] = {
  148184. -1.5, -0.5, 0.5, 1.5,
  148185. };
  148186. static long _vq_quantmap__44u8_p2_0[] = {
  148187. 3, 1, 0, 2, 4,
  148188. };
  148189. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  148190. _vq_quantthresh__44u8_p2_0,
  148191. _vq_quantmap__44u8_p2_0,
  148192. 5,
  148193. 5
  148194. };
  148195. static static_codebook _44u8_p2_0 = {
  148196. 4, 625,
  148197. _vq_lengthlist__44u8_p2_0,
  148198. 1, -533725184, 1611661312, 3, 0,
  148199. _vq_quantlist__44u8_p2_0,
  148200. NULL,
  148201. &_vq_auxt__44u8_p2_0,
  148202. NULL,
  148203. 0
  148204. };
  148205. static long _vq_quantlist__44u8_p3_0[] = {
  148206. 4,
  148207. 3,
  148208. 5,
  148209. 2,
  148210. 6,
  148211. 1,
  148212. 7,
  148213. 0,
  148214. 8,
  148215. };
  148216. static long _vq_lengthlist__44u8_p3_0[] = {
  148217. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  148218. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  148219. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  148220. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  148221. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  148222. 12,
  148223. };
  148224. static float _vq_quantthresh__44u8_p3_0[] = {
  148225. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148226. };
  148227. static long _vq_quantmap__44u8_p3_0[] = {
  148228. 7, 5, 3, 1, 0, 2, 4, 6,
  148229. 8,
  148230. };
  148231. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  148232. _vq_quantthresh__44u8_p3_0,
  148233. _vq_quantmap__44u8_p3_0,
  148234. 9,
  148235. 9
  148236. };
  148237. static static_codebook _44u8_p3_0 = {
  148238. 2, 81,
  148239. _vq_lengthlist__44u8_p3_0,
  148240. 1, -531628032, 1611661312, 4, 0,
  148241. _vq_quantlist__44u8_p3_0,
  148242. NULL,
  148243. &_vq_auxt__44u8_p3_0,
  148244. NULL,
  148245. 0
  148246. };
  148247. static long _vq_quantlist__44u8_p4_0[] = {
  148248. 8,
  148249. 7,
  148250. 9,
  148251. 6,
  148252. 10,
  148253. 5,
  148254. 11,
  148255. 4,
  148256. 12,
  148257. 3,
  148258. 13,
  148259. 2,
  148260. 14,
  148261. 1,
  148262. 15,
  148263. 0,
  148264. 16,
  148265. };
  148266. static long _vq_lengthlist__44u8_p4_0[] = {
  148267. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  148268. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  148269. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  148270. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  148271. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  148272. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  148273. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  148274. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  148275. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  148276. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  148277. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  148278. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  148279. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  148280. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  148281. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  148282. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  148283. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  148284. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  148285. 14,
  148286. };
  148287. static float _vq_quantthresh__44u8_p4_0[] = {
  148288. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148289. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148290. };
  148291. static long _vq_quantmap__44u8_p4_0[] = {
  148292. 15, 13, 11, 9, 7, 5, 3, 1,
  148293. 0, 2, 4, 6, 8, 10, 12, 14,
  148294. 16,
  148295. };
  148296. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  148297. _vq_quantthresh__44u8_p4_0,
  148298. _vq_quantmap__44u8_p4_0,
  148299. 17,
  148300. 17
  148301. };
  148302. static static_codebook _44u8_p4_0 = {
  148303. 2, 289,
  148304. _vq_lengthlist__44u8_p4_0,
  148305. 1, -529530880, 1611661312, 5, 0,
  148306. _vq_quantlist__44u8_p4_0,
  148307. NULL,
  148308. &_vq_auxt__44u8_p4_0,
  148309. NULL,
  148310. 0
  148311. };
  148312. static long _vq_quantlist__44u8_p5_0[] = {
  148313. 1,
  148314. 0,
  148315. 2,
  148316. };
  148317. static long _vq_lengthlist__44u8_p5_0[] = {
  148318. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  148319. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  148320. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  148321. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  148322. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  148323. 10,
  148324. };
  148325. static float _vq_quantthresh__44u8_p5_0[] = {
  148326. -5.5, 5.5,
  148327. };
  148328. static long _vq_quantmap__44u8_p5_0[] = {
  148329. 1, 0, 2,
  148330. };
  148331. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  148332. _vq_quantthresh__44u8_p5_0,
  148333. _vq_quantmap__44u8_p5_0,
  148334. 3,
  148335. 3
  148336. };
  148337. static static_codebook _44u8_p5_0 = {
  148338. 4, 81,
  148339. _vq_lengthlist__44u8_p5_0,
  148340. 1, -529137664, 1618345984, 2, 0,
  148341. _vq_quantlist__44u8_p5_0,
  148342. NULL,
  148343. &_vq_auxt__44u8_p5_0,
  148344. NULL,
  148345. 0
  148346. };
  148347. static long _vq_quantlist__44u8_p5_1[] = {
  148348. 5,
  148349. 4,
  148350. 6,
  148351. 3,
  148352. 7,
  148353. 2,
  148354. 8,
  148355. 1,
  148356. 9,
  148357. 0,
  148358. 10,
  148359. };
  148360. static long _vq_lengthlist__44u8_p5_1[] = {
  148361. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  148362. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  148363. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  148364. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  148365. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  148366. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  148367. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  148368. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  148369. };
  148370. static float _vq_quantthresh__44u8_p5_1[] = {
  148371. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148372. 3.5, 4.5,
  148373. };
  148374. static long _vq_quantmap__44u8_p5_1[] = {
  148375. 9, 7, 5, 3, 1, 0, 2, 4,
  148376. 6, 8, 10,
  148377. };
  148378. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  148379. _vq_quantthresh__44u8_p5_1,
  148380. _vq_quantmap__44u8_p5_1,
  148381. 11,
  148382. 11
  148383. };
  148384. static static_codebook _44u8_p5_1 = {
  148385. 2, 121,
  148386. _vq_lengthlist__44u8_p5_1,
  148387. 1, -531365888, 1611661312, 4, 0,
  148388. _vq_quantlist__44u8_p5_1,
  148389. NULL,
  148390. &_vq_auxt__44u8_p5_1,
  148391. NULL,
  148392. 0
  148393. };
  148394. static long _vq_quantlist__44u8_p6_0[] = {
  148395. 6,
  148396. 5,
  148397. 7,
  148398. 4,
  148399. 8,
  148400. 3,
  148401. 9,
  148402. 2,
  148403. 10,
  148404. 1,
  148405. 11,
  148406. 0,
  148407. 12,
  148408. };
  148409. static long _vq_lengthlist__44u8_p6_0[] = {
  148410. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  148411. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  148412. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  148413. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  148414. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  148415. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  148416. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  148417. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  148418. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  148419. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  148420. 11,11,11,11,11,12,11,12,12,
  148421. };
  148422. static float _vq_quantthresh__44u8_p6_0[] = {
  148423. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148424. 12.5, 17.5, 22.5, 27.5,
  148425. };
  148426. static long _vq_quantmap__44u8_p6_0[] = {
  148427. 11, 9, 7, 5, 3, 1, 0, 2,
  148428. 4, 6, 8, 10, 12,
  148429. };
  148430. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  148431. _vq_quantthresh__44u8_p6_0,
  148432. _vq_quantmap__44u8_p6_0,
  148433. 13,
  148434. 13
  148435. };
  148436. static static_codebook _44u8_p6_0 = {
  148437. 2, 169,
  148438. _vq_lengthlist__44u8_p6_0,
  148439. 1, -526516224, 1616117760, 4, 0,
  148440. _vq_quantlist__44u8_p6_0,
  148441. NULL,
  148442. &_vq_auxt__44u8_p6_0,
  148443. NULL,
  148444. 0
  148445. };
  148446. static long _vq_quantlist__44u8_p6_1[] = {
  148447. 2,
  148448. 1,
  148449. 3,
  148450. 0,
  148451. 4,
  148452. };
  148453. static long _vq_lengthlist__44u8_p6_1[] = {
  148454. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  148455. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  148456. };
  148457. static float _vq_quantthresh__44u8_p6_1[] = {
  148458. -1.5, -0.5, 0.5, 1.5,
  148459. };
  148460. static long _vq_quantmap__44u8_p6_1[] = {
  148461. 3, 1, 0, 2, 4,
  148462. };
  148463. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  148464. _vq_quantthresh__44u8_p6_1,
  148465. _vq_quantmap__44u8_p6_1,
  148466. 5,
  148467. 5
  148468. };
  148469. static static_codebook _44u8_p6_1 = {
  148470. 2, 25,
  148471. _vq_lengthlist__44u8_p6_1,
  148472. 1, -533725184, 1611661312, 3, 0,
  148473. _vq_quantlist__44u8_p6_1,
  148474. NULL,
  148475. &_vq_auxt__44u8_p6_1,
  148476. NULL,
  148477. 0
  148478. };
  148479. static long _vq_quantlist__44u8_p7_0[] = {
  148480. 6,
  148481. 5,
  148482. 7,
  148483. 4,
  148484. 8,
  148485. 3,
  148486. 9,
  148487. 2,
  148488. 10,
  148489. 1,
  148490. 11,
  148491. 0,
  148492. 12,
  148493. };
  148494. static long _vq_lengthlist__44u8_p7_0[] = {
  148495. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  148496. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  148497. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  148498. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  148499. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  148500. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  148501. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  148502. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  148503. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  148504. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  148505. 13,13,14,14,14,15,15,15,16,
  148506. };
  148507. static float _vq_quantthresh__44u8_p7_0[] = {
  148508. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  148509. 27.5, 38.5, 49.5, 60.5,
  148510. };
  148511. static long _vq_quantmap__44u8_p7_0[] = {
  148512. 11, 9, 7, 5, 3, 1, 0, 2,
  148513. 4, 6, 8, 10, 12,
  148514. };
  148515. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  148516. _vq_quantthresh__44u8_p7_0,
  148517. _vq_quantmap__44u8_p7_0,
  148518. 13,
  148519. 13
  148520. };
  148521. static static_codebook _44u8_p7_0 = {
  148522. 2, 169,
  148523. _vq_lengthlist__44u8_p7_0,
  148524. 1, -523206656, 1618345984, 4, 0,
  148525. _vq_quantlist__44u8_p7_0,
  148526. NULL,
  148527. &_vq_auxt__44u8_p7_0,
  148528. NULL,
  148529. 0
  148530. };
  148531. static long _vq_quantlist__44u8_p7_1[] = {
  148532. 5,
  148533. 4,
  148534. 6,
  148535. 3,
  148536. 7,
  148537. 2,
  148538. 8,
  148539. 1,
  148540. 9,
  148541. 0,
  148542. 10,
  148543. };
  148544. static long _vq_lengthlist__44u8_p7_1[] = {
  148545. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  148546. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  148547. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  148548. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  148549. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  148550. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  148551. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  148552. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  148553. };
  148554. static float _vq_quantthresh__44u8_p7_1[] = {
  148555. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148556. 3.5, 4.5,
  148557. };
  148558. static long _vq_quantmap__44u8_p7_1[] = {
  148559. 9, 7, 5, 3, 1, 0, 2, 4,
  148560. 6, 8, 10,
  148561. };
  148562. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  148563. _vq_quantthresh__44u8_p7_1,
  148564. _vq_quantmap__44u8_p7_1,
  148565. 11,
  148566. 11
  148567. };
  148568. static static_codebook _44u8_p7_1 = {
  148569. 2, 121,
  148570. _vq_lengthlist__44u8_p7_1,
  148571. 1, -531365888, 1611661312, 4, 0,
  148572. _vq_quantlist__44u8_p7_1,
  148573. NULL,
  148574. &_vq_auxt__44u8_p7_1,
  148575. NULL,
  148576. 0
  148577. };
  148578. static long _vq_quantlist__44u8_p8_0[] = {
  148579. 7,
  148580. 6,
  148581. 8,
  148582. 5,
  148583. 9,
  148584. 4,
  148585. 10,
  148586. 3,
  148587. 11,
  148588. 2,
  148589. 12,
  148590. 1,
  148591. 13,
  148592. 0,
  148593. 14,
  148594. };
  148595. static long _vq_lengthlist__44u8_p8_0[] = {
  148596. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  148597. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  148598. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  148599. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  148600. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  148601. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  148602. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  148603. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  148604. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  148605. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  148606. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  148607. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  148608. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  148609. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  148610. 17,
  148611. };
  148612. static float _vq_quantthresh__44u8_p8_0[] = {
  148613. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  148614. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  148615. };
  148616. static long _vq_quantmap__44u8_p8_0[] = {
  148617. 13, 11, 9, 7, 5, 3, 1, 0,
  148618. 2, 4, 6, 8, 10, 12, 14,
  148619. };
  148620. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  148621. _vq_quantthresh__44u8_p8_0,
  148622. _vq_quantmap__44u8_p8_0,
  148623. 15,
  148624. 15
  148625. };
  148626. static static_codebook _44u8_p8_0 = {
  148627. 2, 225,
  148628. _vq_lengthlist__44u8_p8_0,
  148629. 1, -520986624, 1620377600, 4, 0,
  148630. _vq_quantlist__44u8_p8_0,
  148631. NULL,
  148632. &_vq_auxt__44u8_p8_0,
  148633. NULL,
  148634. 0
  148635. };
  148636. static long _vq_quantlist__44u8_p8_1[] = {
  148637. 10,
  148638. 9,
  148639. 11,
  148640. 8,
  148641. 12,
  148642. 7,
  148643. 13,
  148644. 6,
  148645. 14,
  148646. 5,
  148647. 15,
  148648. 4,
  148649. 16,
  148650. 3,
  148651. 17,
  148652. 2,
  148653. 18,
  148654. 1,
  148655. 19,
  148656. 0,
  148657. 20,
  148658. };
  148659. static long _vq_lengthlist__44u8_p8_1[] = {
  148660. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  148661. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  148662. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  148663. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  148664. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148665. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148666. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  148667. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  148668. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  148669. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  148670. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  148671. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  148672. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  148673. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  148674. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  148675. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148676. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  148677. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  148678. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  148679. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  148680. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148681. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  148682. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  148683. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148684. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148685. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  148686. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  148687. 10,10,10,10,10,10,10,10,10,
  148688. };
  148689. static float _vq_quantthresh__44u8_p8_1[] = {
  148690. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  148691. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  148692. 6.5, 7.5, 8.5, 9.5,
  148693. };
  148694. static long _vq_quantmap__44u8_p8_1[] = {
  148695. 19, 17, 15, 13, 11, 9, 7, 5,
  148696. 3, 1, 0, 2, 4, 6, 8, 10,
  148697. 12, 14, 16, 18, 20,
  148698. };
  148699. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  148700. _vq_quantthresh__44u8_p8_1,
  148701. _vq_quantmap__44u8_p8_1,
  148702. 21,
  148703. 21
  148704. };
  148705. static static_codebook _44u8_p8_1 = {
  148706. 2, 441,
  148707. _vq_lengthlist__44u8_p8_1,
  148708. 1, -529268736, 1611661312, 5, 0,
  148709. _vq_quantlist__44u8_p8_1,
  148710. NULL,
  148711. &_vq_auxt__44u8_p8_1,
  148712. NULL,
  148713. 0
  148714. };
  148715. static long _vq_quantlist__44u8_p9_0[] = {
  148716. 4,
  148717. 3,
  148718. 5,
  148719. 2,
  148720. 6,
  148721. 1,
  148722. 7,
  148723. 0,
  148724. 8,
  148725. };
  148726. static long _vq_lengthlist__44u8_p9_0[] = {
  148727. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  148728. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148729. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148730. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148731. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  148732. 8,
  148733. };
  148734. static float _vq_quantthresh__44u8_p9_0[] = {
  148735. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  148736. };
  148737. static long _vq_quantmap__44u8_p9_0[] = {
  148738. 7, 5, 3, 1, 0, 2, 4, 6,
  148739. 8,
  148740. };
  148741. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  148742. _vq_quantthresh__44u8_p9_0,
  148743. _vq_quantmap__44u8_p9_0,
  148744. 9,
  148745. 9
  148746. };
  148747. static static_codebook _44u8_p9_0 = {
  148748. 2, 81,
  148749. _vq_lengthlist__44u8_p9_0,
  148750. 1, -511895552, 1631393792, 4, 0,
  148751. _vq_quantlist__44u8_p9_0,
  148752. NULL,
  148753. &_vq_auxt__44u8_p9_0,
  148754. NULL,
  148755. 0
  148756. };
  148757. static long _vq_quantlist__44u8_p9_1[] = {
  148758. 9,
  148759. 8,
  148760. 10,
  148761. 7,
  148762. 11,
  148763. 6,
  148764. 12,
  148765. 5,
  148766. 13,
  148767. 4,
  148768. 14,
  148769. 3,
  148770. 15,
  148771. 2,
  148772. 16,
  148773. 1,
  148774. 17,
  148775. 0,
  148776. 18,
  148777. };
  148778. static long _vq_lengthlist__44u8_p9_1[] = {
  148779. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  148780. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  148781. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  148782. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  148783. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  148784. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  148785. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  148786. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  148787. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  148788. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  148789. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  148790. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  148791. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  148792. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  148793. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  148794. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  148795. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  148796. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  148797. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  148798. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  148799. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  148800. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  148801. 16,15,16,16,16,16,16,16,16,
  148802. };
  148803. static float _vq_quantthresh__44u8_p9_1[] = {
  148804. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  148805. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  148806. 367.5, 416.5,
  148807. };
  148808. static long _vq_quantmap__44u8_p9_1[] = {
  148809. 17, 15, 13, 11, 9, 7, 5, 3,
  148810. 1, 0, 2, 4, 6, 8, 10, 12,
  148811. 14, 16, 18,
  148812. };
  148813. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  148814. _vq_quantthresh__44u8_p9_1,
  148815. _vq_quantmap__44u8_p9_1,
  148816. 19,
  148817. 19
  148818. };
  148819. static static_codebook _44u8_p9_1 = {
  148820. 2, 361,
  148821. _vq_lengthlist__44u8_p9_1,
  148822. 1, -518287360, 1622704128, 5, 0,
  148823. _vq_quantlist__44u8_p9_1,
  148824. NULL,
  148825. &_vq_auxt__44u8_p9_1,
  148826. NULL,
  148827. 0
  148828. };
  148829. static long _vq_quantlist__44u8_p9_2[] = {
  148830. 24,
  148831. 23,
  148832. 25,
  148833. 22,
  148834. 26,
  148835. 21,
  148836. 27,
  148837. 20,
  148838. 28,
  148839. 19,
  148840. 29,
  148841. 18,
  148842. 30,
  148843. 17,
  148844. 31,
  148845. 16,
  148846. 32,
  148847. 15,
  148848. 33,
  148849. 14,
  148850. 34,
  148851. 13,
  148852. 35,
  148853. 12,
  148854. 36,
  148855. 11,
  148856. 37,
  148857. 10,
  148858. 38,
  148859. 9,
  148860. 39,
  148861. 8,
  148862. 40,
  148863. 7,
  148864. 41,
  148865. 6,
  148866. 42,
  148867. 5,
  148868. 43,
  148869. 4,
  148870. 44,
  148871. 3,
  148872. 45,
  148873. 2,
  148874. 46,
  148875. 1,
  148876. 47,
  148877. 0,
  148878. 48,
  148879. };
  148880. static long _vq_lengthlist__44u8_p9_2[] = {
  148881. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  148882. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  148883. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  148884. 7,
  148885. };
  148886. static float _vq_quantthresh__44u8_p9_2[] = {
  148887. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  148888. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  148889. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148890. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148891. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  148892. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  148893. };
  148894. static long _vq_quantmap__44u8_p9_2[] = {
  148895. 47, 45, 43, 41, 39, 37, 35, 33,
  148896. 31, 29, 27, 25, 23, 21, 19, 17,
  148897. 15, 13, 11, 9, 7, 5, 3, 1,
  148898. 0, 2, 4, 6, 8, 10, 12, 14,
  148899. 16, 18, 20, 22, 24, 26, 28, 30,
  148900. 32, 34, 36, 38, 40, 42, 44, 46,
  148901. 48,
  148902. };
  148903. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  148904. _vq_quantthresh__44u8_p9_2,
  148905. _vq_quantmap__44u8_p9_2,
  148906. 49,
  148907. 49
  148908. };
  148909. static static_codebook _44u8_p9_2 = {
  148910. 1, 49,
  148911. _vq_lengthlist__44u8_p9_2,
  148912. 1, -526909440, 1611661312, 6, 0,
  148913. _vq_quantlist__44u8_p9_2,
  148914. NULL,
  148915. &_vq_auxt__44u8_p9_2,
  148916. NULL,
  148917. 0
  148918. };
  148919. static long _huff_lengthlist__44u9__long[] = {
  148920. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  148921. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  148922. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  148923. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  148924. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  148925. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  148926. 10, 8, 8, 9,
  148927. };
  148928. static static_codebook _huff_book__44u9__long = {
  148929. 2, 100,
  148930. _huff_lengthlist__44u9__long,
  148931. 0, 0, 0, 0, 0,
  148932. NULL,
  148933. NULL,
  148934. NULL,
  148935. NULL,
  148936. 0
  148937. };
  148938. static long _huff_lengthlist__44u9__short[] = {
  148939. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  148940. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  148941. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  148942. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  148943. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  148944. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  148945. 9, 9,12,15,
  148946. };
  148947. static static_codebook _huff_book__44u9__short = {
  148948. 2, 100,
  148949. _huff_lengthlist__44u9__short,
  148950. 0, 0, 0, 0, 0,
  148951. NULL,
  148952. NULL,
  148953. NULL,
  148954. NULL,
  148955. 0
  148956. };
  148957. static long _vq_quantlist__44u9_p1_0[] = {
  148958. 1,
  148959. 0,
  148960. 2,
  148961. };
  148962. static long _vq_lengthlist__44u9_p1_0[] = {
  148963. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  148964. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  148965. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  148966. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  148967. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  148968. 10,
  148969. };
  148970. static float _vq_quantthresh__44u9_p1_0[] = {
  148971. -0.5, 0.5,
  148972. };
  148973. static long _vq_quantmap__44u9_p1_0[] = {
  148974. 1, 0, 2,
  148975. };
  148976. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  148977. _vq_quantthresh__44u9_p1_0,
  148978. _vq_quantmap__44u9_p1_0,
  148979. 3,
  148980. 3
  148981. };
  148982. static static_codebook _44u9_p1_0 = {
  148983. 4, 81,
  148984. _vq_lengthlist__44u9_p1_0,
  148985. 1, -535822336, 1611661312, 2, 0,
  148986. _vq_quantlist__44u9_p1_0,
  148987. NULL,
  148988. &_vq_auxt__44u9_p1_0,
  148989. NULL,
  148990. 0
  148991. };
  148992. static long _vq_quantlist__44u9_p2_0[] = {
  148993. 2,
  148994. 1,
  148995. 3,
  148996. 0,
  148997. 4,
  148998. };
  148999. static long _vq_lengthlist__44u9_p2_0[] = {
  149000. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  149001. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149002. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  149003. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  149004. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  149005. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  149006. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  149007. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  149008. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  149009. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  149010. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  149011. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  149012. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  149013. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  149014. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  149015. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  149016. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  149017. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  149018. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  149019. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  149020. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  149021. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  149022. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  149023. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  149024. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  149025. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  149026. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  149027. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  149028. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  149029. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  149030. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  149031. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  149032. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  149033. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  149034. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  149035. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  149036. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  149037. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  149038. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  149039. 14,
  149040. };
  149041. static float _vq_quantthresh__44u9_p2_0[] = {
  149042. -1.5, -0.5, 0.5, 1.5,
  149043. };
  149044. static long _vq_quantmap__44u9_p2_0[] = {
  149045. 3, 1, 0, 2, 4,
  149046. };
  149047. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  149048. _vq_quantthresh__44u9_p2_0,
  149049. _vq_quantmap__44u9_p2_0,
  149050. 5,
  149051. 5
  149052. };
  149053. static static_codebook _44u9_p2_0 = {
  149054. 4, 625,
  149055. _vq_lengthlist__44u9_p2_0,
  149056. 1, -533725184, 1611661312, 3, 0,
  149057. _vq_quantlist__44u9_p2_0,
  149058. NULL,
  149059. &_vq_auxt__44u9_p2_0,
  149060. NULL,
  149061. 0
  149062. };
  149063. static long _vq_quantlist__44u9_p3_0[] = {
  149064. 4,
  149065. 3,
  149066. 5,
  149067. 2,
  149068. 6,
  149069. 1,
  149070. 7,
  149071. 0,
  149072. 8,
  149073. };
  149074. static long _vq_lengthlist__44u9_p3_0[] = {
  149075. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  149076. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  149077. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  149078. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  149079. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  149080. 11,
  149081. };
  149082. static float _vq_quantthresh__44u9_p3_0[] = {
  149083. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149084. };
  149085. static long _vq_quantmap__44u9_p3_0[] = {
  149086. 7, 5, 3, 1, 0, 2, 4, 6,
  149087. 8,
  149088. };
  149089. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  149090. _vq_quantthresh__44u9_p3_0,
  149091. _vq_quantmap__44u9_p3_0,
  149092. 9,
  149093. 9
  149094. };
  149095. static static_codebook _44u9_p3_0 = {
  149096. 2, 81,
  149097. _vq_lengthlist__44u9_p3_0,
  149098. 1, -531628032, 1611661312, 4, 0,
  149099. _vq_quantlist__44u9_p3_0,
  149100. NULL,
  149101. &_vq_auxt__44u9_p3_0,
  149102. NULL,
  149103. 0
  149104. };
  149105. static long _vq_quantlist__44u9_p4_0[] = {
  149106. 8,
  149107. 7,
  149108. 9,
  149109. 6,
  149110. 10,
  149111. 5,
  149112. 11,
  149113. 4,
  149114. 12,
  149115. 3,
  149116. 13,
  149117. 2,
  149118. 14,
  149119. 1,
  149120. 15,
  149121. 0,
  149122. 16,
  149123. };
  149124. static long _vq_lengthlist__44u9_p4_0[] = {
  149125. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  149126. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  149127. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  149128. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  149129. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  149130. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  149131. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  149132. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  149133. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  149134. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  149135. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  149136. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  149137. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  149138. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  149139. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  149140. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  149141. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  149142. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  149143. 14,
  149144. };
  149145. static float _vq_quantthresh__44u9_p4_0[] = {
  149146. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149147. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149148. };
  149149. static long _vq_quantmap__44u9_p4_0[] = {
  149150. 15, 13, 11, 9, 7, 5, 3, 1,
  149151. 0, 2, 4, 6, 8, 10, 12, 14,
  149152. 16,
  149153. };
  149154. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  149155. _vq_quantthresh__44u9_p4_0,
  149156. _vq_quantmap__44u9_p4_0,
  149157. 17,
  149158. 17
  149159. };
  149160. static static_codebook _44u9_p4_0 = {
  149161. 2, 289,
  149162. _vq_lengthlist__44u9_p4_0,
  149163. 1, -529530880, 1611661312, 5, 0,
  149164. _vq_quantlist__44u9_p4_0,
  149165. NULL,
  149166. &_vq_auxt__44u9_p4_0,
  149167. NULL,
  149168. 0
  149169. };
  149170. static long _vq_quantlist__44u9_p5_0[] = {
  149171. 1,
  149172. 0,
  149173. 2,
  149174. };
  149175. static long _vq_lengthlist__44u9_p5_0[] = {
  149176. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  149177. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  149178. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  149179. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  149180. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  149181. 10,
  149182. };
  149183. static float _vq_quantthresh__44u9_p5_0[] = {
  149184. -5.5, 5.5,
  149185. };
  149186. static long _vq_quantmap__44u9_p5_0[] = {
  149187. 1, 0, 2,
  149188. };
  149189. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  149190. _vq_quantthresh__44u9_p5_0,
  149191. _vq_quantmap__44u9_p5_0,
  149192. 3,
  149193. 3
  149194. };
  149195. static static_codebook _44u9_p5_0 = {
  149196. 4, 81,
  149197. _vq_lengthlist__44u9_p5_0,
  149198. 1, -529137664, 1618345984, 2, 0,
  149199. _vq_quantlist__44u9_p5_0,
  149200. NULL,
  149201. &_vq_auxt__44u9_p5_0,
  149202. NULL,
  149203. 0
  149204. };
  149205. static long _vq_quantlist__44u9_p5_1[] = {
  149206. 5,
  149207. 4,
  149208. 6,
  149209. 3,
  149210. 7,
  149211. 2,
  149212. 8,
  149213. 1,
  149214. 9,
  149215. 0,
  149216. 10,
  149217. };
  149218. static long _vq_lengthlist__44u9_p5_1[] = {
  149219. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  149220. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  149221. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  149222. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  149223. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  149224. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  149225. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  149226. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149227. };
  149228. static float _vq_quantthresh__44u9_p5_1[] = {
  149229. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149230. 3.5, 4.5,
  149231. };
  149232. static long _vq_quantmap__44u9_p5_1[] = {
  149233. 9, 7, 5, 3, 1, 0, 2, 4,
  149234. 6, 8, 10,
  149235. };
  149236. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  149237. _vq_quantthresh__44u9_p5_1,
  149238. _vq_quantmap__44u9_p5_1,
  149239. 11,
  149240. 11
  149241. };
  149242. static static_codebook _44u9_p5_1 = {
  149243. 2, 121,
  149244. _vq_lengthlist__44u9_p5_1,
  149245. 1, -531365888, 1611661312, 4, 0,
  149246. _vq_quantlist__44u9_p5_1,
  149247. NULL,
  149248. &_vq_auxt__44u9_p5_1,
  149249. NULL,
  149250. 0
  149251. };
  149252. static long _vq_quantlist__44u9_p6_0[] = {
  149253. 6,
  149254. 5,
  149255. 7,
  149256. 4,
  149257. 8,
  149258. 3,
  149259. 9,
  149260. 2,
  149261. 10,
  149262. 1,
  149263. 11,
  149264. 0,
  149265. 12,
  149266. };
  149267. static long _vq_lengthlist__44u9_p6_0[] = {
  149268. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  149269. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  149270. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  149271. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  149272. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  149273. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  149274. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  149275. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  149276. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  149277. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  149278. 10,11,11,11,11,12,11,12,12,
  149279. };
  149280. static float _vq_quantthresh__44u9_p6_0[] = {
  149281. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  149282. 12.5, 17.5, 22.5, 27.5,
  149283. };
  149284. static long _vq_quantmap__44u9_p6_0[] = {
  149285. 11, 9, 7, 5, 3, 1, 0, 2,
  149286. 4, 6, 8, 10, 12,
  149287. };
  149288. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  149289. _vq_quantthresh__44u9_p6_0,
  149290. _vq_quantmap__44u9_p6_0,
  149291. 13,
  149292. 13
  149293. };
  149294. static static_codebook _44u9_p6_0 = {
  149295. 2, 169,
  149296. _vq_lengthlist__44u9_p6_0,
  149297. 1, -526516224, 1616117760, 4, 0,
  149298. _vq_quantlist__44u9_p6_0,
  149299. NULL,
  149300. &_vq_auxt__44u9_p6_0,
  149301. NULL,
  149302. 0
  149303. };
  149304. static long _vq_quantlist__44u9_p6_1[] = {
  149305. 2,
  149306. 1,
  149307. 3,
  149308. 0,
  149309. 4,
  149310. };
  149311. static long _vq_lengthlist__44u9_p6_1[] = {
  149312. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  149313. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  149314. };
  149315. static float _vq_quantthresh__44u9_p6_1[] = {
  149316. -1.5, -0.5, 0.5, 1.5,
  149317. };
  149318. static long _vq_quantmap__44u9_p6_1[] = {
  149319. 3, 1, 0, 2, 4,
  149320. };
  149321. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  149322. _vq_quantthresh__44u9_p6_1,
  149323. _vq_quantmap__44u9_p6_1,
  149324. 5,
  149325. 5
  149326. };
  149327. static static_codebook _44u9_p6_1 = {
  149328. 2, 25,
  149329. _vq_lengthlist__44u9_p6_1,
  149330. 1, -533725184, 1611661312, 3, 0,
  149331. _vq_quantlist__44u9_p6_1,
  149332. NULL,
  149333. &_vq_auxt__44u9_p6_1,
  149334. NULL,
  149335. 0
  149336. };
  149337. static long _vq_quantlist__44u9_p7_0[] = {
  149338. 6,
  149339. 5,
  149340. 7,
  149341. 4,
  149342. 8,
  149343. 3,
  149344. 9,
  149345. 2,
  149346. 10,
  149347. 1,
  149348. 11,
  149349. 0,
  149350. 12,
  149351. };
  149352. static long _vq_lengthlist__44u9_p7_0[] = {
  149353. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  149354. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  149355. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  149356. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  149357. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  149358. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  149359. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  149360. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  149361. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  149362. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  149363. 12,13,13,14,14,14,15,15,15,
  149364. };
  149365. static float _vq_quantthresh__44u9_p7_0[] = {
  149366. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  149367. 27.5, 38.5, 49.5, 60.5,
  149368. };
  149369. static long _vq_quantmap__44u9_p7_0[] = {
  149370. 11, 9, 7, 5, 3, 1, 0, 2,
  149371. 4, 6, 8, 10, 12,
  149372. };
  149373. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  149374. _vq_quantthresh__44u9_p7_0,
  149375. _vq_quantmap__44u9_p7_0,
  149376. 13,
  149377. 13
  149378. };
  149379. static static_codebook _44u9_p7_0 = {
  149380. 2, 169,
  149381. _vq_lengthlist__44u9_p7_0,
  149382. 1, -523206656, 1618345984, 4, 0,
  149383. _vq_quantlist__44u9_p7_0,
  149384. NULL,
  149385. &_vq_auxt__44u9_p7_0,
  149386. NULL,
  149387. 0
  149388. };
  149389. static long _vq_quantlist__44u9_p7_1[] = {
  149390. 5,
  149391. 4,
  149392. 6,
  149393. 3,
  149394. 7,
  149395. 2,
  149396. 8,
  149397. 1,
  149398. 9,
  149399. 0,
  149400. 10,
  149401. };
  149402. static long _vq_lengthlist__44u9_p7_1[] = {
  149403. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  149404. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  149405. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  149406. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  149407. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  149408. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  149409. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  149410. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  149411. };
  149412. static float _vq_quantthresh__44u9_p7_1[] = {
  149413. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149414. 3.5, 4.5,
  149415. };
  149416. static long _vq_quantmap__44u9_p7_1[] = {
  149417. 9, 7, 5, 3, 1, 0, 2, 4,
  149418. 6, 8, 10,
  149419. };
  149420. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  149421. _vq_quantthresh__44u9_p7_1,
  149422. _vq_quantmap__44u9_p7_1,
  149423. 11,
  149424. 11
  149425. };
  149426. static static_codebook _44u9_p7_1 = {
  149427. 2, 121,
  149428. _vq_lengthlist__44u9_p7_1,
  149429. 1, -531365888, 1611661312, 4, 0,
  149430. _vq_quantlist__44u9_p7_1,
  149431. NULL,
  149432. &_vq_auxt__44u9_p7_1,
  149433. NULL,
  149434. 0
  149435. };
  149436. static long _vq_quantlist__44u9_p8_0[] = {
  149437. 7,
  149438. 6,
  149439. 8,
  149440. 5,
  149441. 9,
  149442. 4,
  149443. 10,
  149444. 3,
  149445. 11,
  149446. 2,
  149447. 12,
  149448. 1,
  149449. 13,
  149450. 0,
  149451. 14,
  149452. };
  149453. static long _vq_lengthlist__44u9_p8_0[] = {
  149454. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  149455. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  149456. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  149457. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  149458. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  149459. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  149460. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  149461. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  149462. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  149463. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  149464. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  149465. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  149466. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  149467. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  149468. 15,
  149469. };
  149470. static float _vq_quantthresh__44u9_p8_0[] = {
  149471. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  149472. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  149473. };
  149474. static long _vq_quantmap__44u9_p8_0[] = {
  149475. 13, 11, 9, 7, 5, 3, 1, 0,
  149476. 2, 4, 6, 8, 10, 12, 14,
  149477. };
  149478. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  149479. _vq_quantthresh__44u9_p8_0,
  149480. _vq_quantmap__44u9_p8_0,
  149481. 15,
  149482. 15
  149483. };
  149484. static static_codebook _44u9_p8_0 = {
  149485. 2, 225,
  149486. _vq_lengthlist__44u9_p8_0,
  149487. 1, -520986624, 1620377600, 4, 0,
  149488. _vq_quantlist__44u9_p8_0,
  149489. NULL,
  149490. &_vq_auxt__44u9_p8_0,
  149491. NULL,
  149492. 0
  149493. };
  149494. static long _vq_quantlist__44u9_p8_1[] = {
  149495. 10,
  149496. 9,
  149497. 11,
  149498. 8,
  149499. 12,
  149500. 7,
  149501. 13,
  149502. 6,
  149503. 14,
  149504. 5,
  149505. 15,
  149506. 4,
  149507. 16,
  149508. 3,
  149509. 17,
  149510. 2,
  149511. 18,
  149512. 1,
  149513. 19,
  149514. 0,
  149515. 20,
  149516. };
  149517. static long _vq_lengthlist__44u9_p8_1[] = {
  149518. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  149519. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  149520. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  149521. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  149522. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  149523. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149524. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  149525. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  149526. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  149527. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  149528. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  149529. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  149530. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  149531. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  149532. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  149533. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149534. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  149535. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  149536. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  149537. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  149538. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149539. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  149540. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  149541. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  149542. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149543. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  149544. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  149545. 10,10,10,10,10,10,10,10,10,
  149546. };
  149547. static float _vq_quantthresh__44u9_p8_1[] = {
  149548. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  149549. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  149550. 6.5, 7.5, 8.5, 9.5,
  149551. };
  149552. static long _vq_quantmap__44u9_p8_1[] = {
  149553. 19, 17, 15, 13, 11, 9, 7, 5,
  149554. 3, 1, 0, 2, 4, 6, 8, 10,
  149555. 12, 14, 16, 18, 20,
  149556. };
  149557. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  149558. _vq_quantthresh__44u9_p8_1,
  149559. _vq_quantmap__44u9_p8_1,
  149560. 21,
  149561. 21
  149562. };
  149563. static static_codebook _44u9_p8_1 = {
  149564. 2, 441,
  149565. _vq_lengthlist__44u9_p8_1,
  149566. 1, -529268736, 1611661312, 5, 0,
  149567. _vq_quantlist__44u9_p8_1,
  149568. NULL,
  149569. &_vq_auxt__44u9_p8_1,
  149570. NULL,
  149571. 0
  149572. };
  149573. static long _vq_quantlist__44u9_p9_0[] = {
  149574. 7,
  149575. 6,
  149576. 8,
  149577. 5,
  149578. 9,
  149579. 4,
  149580. 10,
  149581. 3,
  149582. 11,
  149583. 2,
  149584. 12,
  149585. 1,
  149586. 13,
  149587. 0,
  149588. 14,
  149589. };
  149590. static long _vq_lengthlist__44u9_p9_0[] = {
  149591. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  149592. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  149593. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149594. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149595. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149596. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149597. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149598. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149599. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149600. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149601. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149602. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149603. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149604. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149605. 10,
  149606. };
  149607. static float _vq_quantthresh__44u9_p9_0[] = {
  149608. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  149609. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  149610. };
  149611. static long _vq_quantmap__44u9_p9_0[] = {
  149612. 13, 11, 9, 7, 5, 3, 1, 0,
  149613. 2, 4, 6, 8, 10, 12, 14,
  149614. };
  149615. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  149616. _vq_quantthresh__44u9_p9_0,
  149617. _vq_quantmap__44u9_p9_0,
  149618. 15,
  149619. 15
  149620. };
  149621. static static_codebook _44u9_p9_0 = {
  149622. 2, 225,
  149623. _vq_lengthlist__44u9_p9_0,
  149624. 1, -510036736, 1631393792, 4, 0,
  149625. _vq_quantlist__44u9_p9_0,
  149626. NULL,
  149627. &_vq_auxt__44u9_p9_0,
  149628. NULL,
  149629. 0
  149630. };
  149631. static long _vq_quantlist__44u9_p9_1[] = {
  149632. 9,
  149633. 8,
  149634. 10,
  149635. 7,
  149636. 11,
  149637. 6,
  149638. 12,
  149639. 5,
  149640. 13,
  149641. 4,
  149642. 14,
  149643. 3,
  149644. 15,
  149645. 2,
  149646. 16,
  149647. 1,
  149648. 17,
  149649. 0,
  149650. 18,
  149651. };
  149652. static long _vq_lengthlist__44u9_p9_1[] = {
  149653. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  149654. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  149655. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  149656. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  149657. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  149658. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  149659. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  149660. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  149661. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  149662. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  149663. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  149664. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  149665. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  149666. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  149667. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  149668. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  149669. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  149670. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  149671. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  149672. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  149673. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  149674. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  149675. 17,17,15,17,15,17,16,16,17,
  149676. };
  149677. static float _vq_quantthresh__44u9_p9_1[] = {
  149678. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  149679. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  149680. 367.5, 416.5,
  149681. };
  149682. static long _vq_quantmap__44u9_p9_1[] = {
  149683. 17, 15, 13, 11, 9, 7, 5, 3,
  149684. 1, 0, 2, 4, 6, 8, 10, 12,
  149685. 14, 16, 18,
  149686. };
  149687. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  149688. _vq_quantthresh__44u9_p9_1,
  149689. _vq_quantmap__44u9_p9_1,
  149690. 19,
  149691. 19
  149692. };
  149693. static static_codebook _44u9_p9_1 = {
  149694. 2, 361,
  149695. _vq_lengthlist__44u9_p9_1,
  149696. 1, -518287360, 1622704128, 5, 0,
  149697. _vq_quantlist__44u9_p9_1,
  149698. NULL,
  149699. &_vq_auxt__44u9_p9_1,
  149700. NULL,
  149701. 0
  149702. };
  149703. static long _vq_quantlist__44u9_p9_2[] = {
  149704. 24,
  149705. 23,
  149706. 25,
  149707. 22,
  149708. 26,
  149709. 21,
  149710. 27,
  149711. 20,
  149712. 28,
  149713. 19,
  149714. 29,
  149715. 18,
  149716. 30,
  149717. 17,
  149718. 31,
  149719. 16,
  149720. 32,
  149721. 15,
  149722. 33,
  149723. 14,
  149724. 34,
  149725. 13,
  149726. 35,
  149727. 12,
  149728. 36,
  149729. 11,
  149730. 37,
  149731. 10,
  149732. 38,
  149733. 9,
  149734. 39,
  149735. 8,
  149736. 40,
  149737. 7,
  149738. 41,
  149739. 6,
  149740. 42,
  149741. 5,
  149742. 43,
  149743. 4,
  149744. 44,
  149745. 3,
  149746. 45,
  149747. 2,
  149748. 46,
  149749. 1,
  149750. 47,
  149751. 0,
  149752. 48,
  149753. };
  149754. static long _vq_lengthlist__44u9_p9_2[] = {
  149755. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  149756. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  149757. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  149758. 7,
  149759. };
  149760. static float _vq_quantthresh__44u9_p9_2[] = {
  149761. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  149762. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  149763. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149764. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149765. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  149766. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  149767. };
  149768. static long _vq_quantmap__44u9_p9_2[] = {
  149769. 47, 45, 43, 41, 39, 37, 35, 33,
  149770. 31, 29, 27, 25, 23, 21, 19, 17,
  149771. 15, 13, 11, 9, 7, 5, 3, 1,
  149772. 0, 2, 4, 6, 8, 10, 12, 14,
  149773. 16, 18, 20, 22, 24, 26, 28, 30,
  149774. 32, 34, 36, 38, 40, 42, 44, 46,
  149775. 48,
  149776. };
  149777. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  149778. _vq_quantthresh__44u9_p9_2,
  149779. _vq_quantmap__44u9_p9_2,
  149780. 49,
  149781. 49
  149782. };
  149783. static static_codebook _44u9_p9_2 = {
  149784. 1, 49,
  149785. _vq_lengthlist__44u9_p9_2,
  149786. 1, -526909440, 1611661312, 6, 0,
  149787. _vq_quantlist__44u9_p9_2,
  149788. NULL,
  149789. &_vq_auxt__44u9_p9_2,
  149790. NULL,
  149791. 0
  149792. };
  149793. static long _huff_lengthlist__44un1__long[] = {
  149794. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  149795. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  149796. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  149797. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  149798. };
  149799. static static_codebook _huff_book__44un1__long = {
  149800. 2, 64,
  149801. _huff_lengthlist__44un1__long,
  149802. 0, 0, 0, 0, 0,
  149803. NULL,
  149804. NULL,
  149805. NULL,
  149806. NULL,
  149807. 0
  149808. };
  149809. static long _vq_quantlist__44un1__p1_0[] = {
  149810. 1,
  149811. 0,
  149812. 2,
  149813. };
  149814. static long _vq_lengthlist__44un1__p1_0[] = {
  149815. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  149816. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  149817. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  149818. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  149819. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  149820. 12,
  149821. };
  149822. static float _vq_quantthresh__44un1__p1_0[] = {
  149823. -0.5, 0.5,
  149824. };
  149825. static long _vq_quantmap__44un1__p1_0[] = {
  149826. 1, 0, 2,
  149827. };
  149828. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  149829. _vq_quantthresh__44un1__p1_0,
  149830. _vq_quantmap__44un1__p1_0,
  149831. 3,
  149832. 3
  149833. };
  149834. static static_codebook _44un1__p1_0 = {
  149835. 4, 81,
  149836. _vq_lengthlist__44un1__p1_0,
  149837. 1, -535822336, 1611661312, 2, 0,
  149838. _vq_quantlist__44un1__p1_0,
  149839. NULL,
  149840. &_vq_auxt__44un1__p1_0,
  149841. NULL,
  149842. 0
  149843. };
  149844. static long _vq_quantlist__44un1__p2_0[] = {
  149845. 1,
  149846. 0,
  149847. 2,
  149848. };
  149849. static long _vq_lengthlist__44un1__p2_0[] = {
  149850. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  149851. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  149852. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  149853. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  149854. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  149855. 8,
  149856. };
  149857. static float _vq_quantthresh__44un1__p2_0[] = {
  149858. -0.5, 0.5,
  149859. };
  149860. static long _vq_quantmap__44un1__p2_0[] = {
  149861. 1, 0, 2,
  149862. };
  149863. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  149864. _vq_quantthresh__44un1__p2_0,
  149865. _vq_quantmap__44un1__p2_0,
  149866. 3,
  149867. 3
  149868. };
  149869. static static_codebook _44un1__p2_0 = {
  149870. 4, 81,
  149871. _vq_lengthlist__44un1__p2_0,
  149872. 1, -535822336, 1611661312, 2, 0,
  149873. _vq_quantlist__44un1__p2_0,
  149874. NULL,
  149875. &_vq_auxt__44un1__p2_0,
  149876. NULL,
  149877. 0
  149878. };
  149879. static long _vq_quantlist__44un1__p3_0[] = {
  149880. 2,
  149881. 1,
  149882. 3,
  149883. 0,
  149884. 4,
  149885. };
  149886. static long _vq_lengthlist__44un1__p3_0[] = {
  149887. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  149888. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  149889. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  149890. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  149891. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  149892. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  149893. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  149894. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  149895. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  149896. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  149897. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  149898. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  149899. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  149900. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  149901. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  149902. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  149903. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  149904. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  149905. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  149906. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  149907. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  149908. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  149909. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  149910. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  149911. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  149912. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  149913. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  149914. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  149915. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  149916. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  149917. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  149918. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  149919. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  149920. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  149921. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  149922. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  149923. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  149924. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  149925. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  149926. 17,
  149927. };
  149928. static float _vq_quantthresh__44un1__p3_0[] = {
  149929. -1.5, -0.5, 0.5, 1.5,
  149930. };
  149931. static long _vq_quantmap__44un1__p3_0[] = {
  149932. 3, 1, 0, 2, 4,
  149933. };
  149934. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  149935. _vq_quantthresh__44un1__p3_0,
  149936. _vq_quantmap__44un1__p3_0,
  149937. 5,
  149938. 5
  149939. };
  149940. static static_codebook _44un1__p3_0 = {
  149941. 4, 625,
  149942. _vq_lengthlist__44un1__p3_0,
  149943. 1, -533725184, 1611661312, 3, 0,
  149944. _vq_quantlist__44un1__p3_0,
  149945. NULL,
  149946. &_vq_auxt__44un1__p3_0,
  149947. NULL,
  149948. 0
  149949. };
  149950. static long _vq_quantlist__44un1__p4_0[] = {
  149951. 2,
  149952. 1,
  149953. 3,
  149954. 0,
  149955. 4,
  149956. };
  149957. static long _vq_lengthlist__44un1__p4_0[] = {
  149958. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  149959. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  149960. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  149961. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  149962. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  149963. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  149964. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  149965. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  149966. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  149967. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  149968. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  149969. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  149970. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  149971. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  149972. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  149973. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  149974. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  149975. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  149976. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  149977. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  149978. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  149979. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  149980. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  149981. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  149982. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  149983. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  149984. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  149985. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  149986. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  149987. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  149988. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  149989. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  149990. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  149991. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  149992. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  149993. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  149994. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  149995. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  149996. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  149997. 12,
  149998. };
  149999. static float _vq_quantthresh__44un1__p4_0[] = {
  150000. -1.5, -0.5, 0.5, 1.5,
  150001. };
  150002. static long _vq_quantmap__44un1__p4_0[] = {
  150003. 3, 1, 0, 2, 4,
  150004. };
  150005. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  150006. _vq_quantthresh__44un1__p4_0,
  150007. _vq_quantmap__44un1__p4_0,
  150008. 5,
  150009. 5
  150010. };
  150011. static static_codebook _44un1__p4_0 = {
  150012. 4, 625,
  150013. _vq_lengthlist__44un1__p4_0,
  150014. 1, -533725184, 1611661312, 3, 0,
  150015. _vq_quantlist__44un1__p4_0,
  150016. NULL,
  150017. &_vq_auxt__44un1__p4_0,
  150018. NULL,
  150019. 0
  150020. };
  150021. static long _vq_quantlist__44un1__p5_0[] = {
  150022. 4,
  150023. 3,
  150024. 5,
  150025. 2,
  150026. 6,
  150027. 1,
  150028. 7,
  150029. 0,
  150030. 8,
  150031. };
  150032. static long _vq_lengthlist__44un1__p5_0[] = {
  150033. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  150034. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  150035. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  150036. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  150037. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  150038. 12,
  150039. };
  150040. static float _vq_quantthresh__44un1__p5_0[] = {
  150041. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150042. };
  150043. static long _vq_quantmap__44un1__p5_0[] = {
  150044. 7, 5, 3, 1, 0, 2, 4, 6,
  150045. 8,
  150046. };
  150047. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  150048. _vq_quantthresh__44un1__p5_0,
  150049. _vq_quantmap__44un1__p5_0,
  150050. 9,
  150051. 9
  150052. };
  150053. static static_codebook _44un1__p5_0 = {
  150054. 2, 81,
  150055. _vq_lengthlist__44un1__p5_0,
  150056. 1, -531628032, 1611661312, 4, 0,
  150057. _vq_quantlist__44un1__p5_0,
  150058. NULL,
  150059. &_vq_auxt__44un1__p5_0,
  150060. NULL,
  150061. 0
  150062. };
  150063. static long _vq_quantlist__44un1__p6_0[] = {
  150064. 6,
  150065. 5,
  150066. 7,
  150067. 4,
  150068. 8,
  150069. 3,
  150070. 9,
  150071. 2,
  150072. 10,
  150073. 1,
  150074. 11,
  150075. 0,
  150076. 12,
  150077. };
  150078. static long _vq_lengthlist__44un1__p6_0[] = {
  150079. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  150080. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  150081. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  150082. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  150083. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  150084. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  150085. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  150086. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  150087. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  150088. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  150089. 16, 0,15,18,18, 0,16, 0, 0,
  150090. };
  150091. static float _vq_quantthresh__44un1__p6_0[] = {
  150092. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  150093. 12.5, 17.5, 22.5, 27.5,
  150094. };
  150095. static long _vq_quantmap__44un1__p6_0[] = {
  150096. 11, 9, 7, 5, 3, 1, 0, 2,
  150097. 4, 6, 8, 10, 12,
  150098. };
  150099. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  150100. _vq_quantthresh__44un1__p6_0,
  150101. _vq_quantmap__44un1__p6_0,
  150102. 13,
  150103. 13
  150104. };
  150105. static static_codebook _44un1__p6_0 = {
  150106. 2, 169,
  150107. _vq_lengthlist__44un1__p6_0,
  150108. 1, -526516224, 1616117760, 4, 0,
  150109. _vq_quantlist__44un1__p6_0,
  150110. NULL,
  150111. &_vq_auxt__44un1__p6_0,
  150112. NULL,
  150113. 0
  150114. };
  150115. static long _vq_quantlist__44un1__p6_1[] = {
  150116. 2,
  150117. 1,
  150118. 3,
  150119. 0,
  150120. 4,
  150121. };
  150122. static long _vq_lengthlist__44un1__p6_1[] = {
  150123. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  150124. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  150125. };
  150126. static float _vq_quantthresh__44un1__p6_1[] = {
  150127. -1.5, -0.5, 0.5, 1.5,
  150128. };
  150129. static long _vq_quantmap__44un1__p6_1[] = {
  150130. 3, 1, 0, 2, 4,
  150131. };
  150132. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  150133. _vq_quantthresh__44un1__p6_1,
  150134. _vq_quantmap__44un1__p6_1,
  150135. 5,
  150136. 5
  150137. };
  150138. static static_codebook _44un1__p6_1 = {
  150139. 2, 25,
  150140. _vq_lengthlist__44un1__p6_1,
  150141. 1, -533725184, 1611661312, 3, 0,
  150142. _vq_quantlist__44un1__p6_1,
  150143. NULL,
  150144. &_vq_auxt__44un1__p6_1,
  150145. NULL,
  150146. 0
  150147. };
  150148. static long _vq_quantlist__44un1__p7_0[] = {
  150149. 2,
  150150. 1,
  150151. 3,
  150152. 0,
  150153. 4,
  150154. };
  150155. static long _vq_lengthlist__44un1__p7_0[] = {
  150156. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  150157. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  150158. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150159. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150160. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150161. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150162. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150163. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  150164. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150165. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150166. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  150167. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150168. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150169. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150170. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150171. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  150172. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150173. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  150174. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150175. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150176. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150177. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150178. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150179. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150180. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150181. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150182. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150183. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150184. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150185. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150186. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150187. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150188. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150189. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150190. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150191. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  150192. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150193. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150194. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150195. 10,
  150196. };
  150197. static float _vq_quantthresh__44un1__p7_0[] = {
  150198. -253.5, -84.5, 84.5, 253.5,
  150199. };
  150200. static long _vq_quantmap__44un1__p7_0[] = {
  150201. 3, 1, 0, 2, 4,
  150202. };
  150203. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  150204. _vq_quantthresh__44un1__p7_0,
  150205. _vq_quantmap__44un1__p7_0,
  150206. 5,
  150207. 5
  150208. };
  150209. static static_codebook _44un1__p7_0 = {
  150210. 4, 625,
  150211. _vq_lengthlist__44un1__p7_0,
  150212. 1, -518709248, 1626677248, 3, 0,
  150213. _vq_quantlist__44un1__p7_0,
  150214. NULL,
  150215. &_vq_auxt__44un1__p7_0,
  150216. NULL,
  150217. 0
  150218. };
  150219. static long _vq_quantlist__44un1__p7_1[] = {
  150220. 6,
  150221. 5,
  150222. 7,
  150223. 4,
  150224. 8,
  150225. 3,
  150226. 9,
  150227. 2,
  150228. 10,
  150229. 1,
  150230. 11,
  150231. 0,
  150232. 12,
  150233. };
  150234. static long _vq_lengthlist__44un1__p7_1[] = {
  150235. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  150236. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  150237. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  150238. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  150239. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  150240. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  150241. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  150242. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  150243. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  150244. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  150245. 12,13,13,12,13,13,14,14,14,
  150246. };
  150247. static float _vq_quantthresh__44un1__p7_1[] = {
  150248. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  150249. 32.5, 45.5, 58.5, 71.5,
  150250. };
  150251. static long _vq_quantmap__44un1__p7_1[] = {
  150252. 11, 9, 7, 5, 3, 1, 0, 2,
  150253. 4, 6, 8, 10, 12,
  150254. };
  150255. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  150256. _vq_quantthresh__44un1__p7_1,
  150257. _vq_quantmap__44un1__p7_1,
  150258. 13,
  150259. 13
  150260. };
  150261. static static_codebook _44un1__p7_1 = {
  150262. 2, 169,
  150263. _vq_lengthlist__44un1__p7_1,
  150264. 1, -523010048, 1618608128, 4, 0,
  150265. _vq_quantlist__44un1__p7_1,
  150266. NULL,
  150267. &_vq_auxt__44un1__p7_1,
  150268. NULL,
  150269. 0
  150270. };
  150271. static long _vq_quantlist__44un1__p7_2[] = {
  150272. 6,
  150273. 5,
  150274. 7,
  150275. 4,
  150276. 8,
  150277. 3,
  150278. 9,
  150279. 2,
  150280. 10,
  150281. 1,
  150282. 11,
  150283. 0,
  150284. 12,
  150285. };
  150286. static long _vq_lengthlist__44un1__p7_2[] = {
  150287. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  150288. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  150289. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  150290. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  150291. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  150292. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  150293. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  150294. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  150295. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  150296. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  150297. 9, 9, 9,10,10,10,10,10,10,
  150298. };
  150299. static float _vq_quantthresh__44un1__p7_2[] = {
  150300. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  150301. 2.5, 3.5, 4.5, 5.5,
  150302. };
  150303. static long _vq_quantmap__44un1__p7_2[] = {
  150304. 11, 9, 7, 5, 3, 1, 0, 2,
  150305. 4, 6, 8, 10, 12,
  150306. };
  150307. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  150308. _vq_quantthresh__44un1__p7_2,
  150309. _vq_quantmap__44un1__p7_2,
  150310. 13,
  150311. 13
  150312. };
  150313. static static_codebook _44un1__p7_2 = {
  150314. 2, 169,
  150315. _vq_lengthlist__44un1__p7_2,
  150316. 1, -531103744, 1611661312, 4, 0,
  150317. _vq_quantlist__44un1__p7_2,
  150318. NULL,
  150319. &_vq_auxt__44un1__p7_2,
  150320. NULL,
  150321. 0
  150322. };
  150323. static long _huff_lengthlist__44un1__short[] = {
  150324. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  150325. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  150326. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  150327. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  150328. };
  150329. static static_codebook _huff_book__44un1__short = {
  150330. 2, 64,
  150331. _huff_lengthlist__44un1__short,
  150332. 0, 0, 0, 0, 0,
  150333. NULL,
  150334. NULL,
  150335. NULL,
  150336. NULL,
  150337. 0
  150338. };
  150339. /*** End of inlined file: res_books_uncoupled.h ***/
  150340. /***** residue backends *********************************************/
  150341. static vorbis_info_residue0 _residue_44_low_un={
  150342. 0,-1, -1, 8,-1,
  150343. {0},
  150344. {-1},
  150345. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  150346. { -1, 25, -1, 45, -1, -1, -1}
  150347. };
  150348. static vorbis_info_residue0 _residue_44_mid_un={
  150349. 0,-1, -1, 10,-1,
  150350. /* 0 1 2 3 4 5 6 7 8 9 */
  150351. {0},
  150352. {-1},
  150353. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  150354. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  150355. };
  150356. static vorbis_info_residue0 _residue_44_hi_un={
  150357. 0,-1, -1, 10,-1,
  150358. /* 0 1 2 3 4 5 6 7 8 9 */
  150359. {0},
  150360. {-1},
  150361. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  150362. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  150363. };
  150364. /* mapping conventions:
  150365. only one submap (this would change for efficient 5.1 support for example)*/
  150366. /* Four psychoacoustic profiles are used, one for each blocktype */
  150367. static vorbis_info_mapping0 _map_nominal_u[2]={
  150368. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  150369. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  150370. };
  150371. static static_bookblock _resbook_44u_n1={
  150372. {
  150373. {0},
  150374. {0,0,&_44un1__p1_0},
  150375. {0,0,&_44un1__p2_0},
  150376. {0,0,&_44un1__p3_0},
  150377. {0,0,&_44un1__p4_0},
  150378. {0,0,&_44un1__p5_0},
  150379. {&_44un1__p6_0,&_44un1__p6_1},
  150380. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  150381. }
  150382. };
  150383. static static_bookblock _resbook_44u_0={
  150384. {
  150385. {0},
  150386. {0,0,&_44u0__p1_0},
  150387. {0,0,&_44u0__p2_0},
  150388. {0,0,&_44u0__p3_0},
  150389. {0,0,&_44u0__p4_0},
  150390. {0,0,&_44u0__p5_0},
  150391. {&_44u0__p6_0,&_44u0__p6_1},
  150392. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  150393. }
  150394. };
  150395. static static_bookblock _resbook_44u_1={
  150396. {
  150397. {0},
  150398. {0,0,&_44u1__p1_0},
  150399. {0,0,&_44u1__p2_0},
  150400. {0,0,&_44u1__p3_0},
  150401. {0,0,&_44u1__p4_0},
  150402. {0,0,&_44u1__p5_0},
  150403. {&_44u1__p6_0,&_44u1__p6_1},
  150404. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  150405. }
  150406. };
  150407. static static_bookblock _resbook_44u_2={
  150408. {
  150409. {0},
  150410. {0,0,&_44u2__p1_0},
  150411. {0,0,&_44u2__p2_0},
  150412. {0,0,&_44u2__p3_0},
  150413. {0,0,&_44u2__p4_0},
  150414. {0,0,&_44u2__p5_0},
  150415. {&_44u2__p6_0,&_44u2__p6_1},
  150416. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  150417. }
  150418. };
  150419. static static_bookblock _resbook_44u_3={
  150420. {
  150421. {0},
  150422. {0,0,&_44u3__p1_0},
  150423. {0,0,&_44u3__p2_0},
  150424. {0,0,&_44u3__p3_0},
  150425. {0,0,&_44u3__p4_0},
  150426. {0,0,&_44u3__p5_0},
  150427. {&_44u3__p6_0,&_44u3__p6_1},
  150428. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  150429. }
  150430. };
  150431. static static_bookblock _resbook_44u_4={
  150432. {
  150433. {0},
  150434. {0,0,&_44u4__p1_0},
  150435. {0,0,&_44u4__p2_0},
  150436. {0,0,&_44u4__p3_0},
  150437. {0,0,&_44u4__p4_0},
  150438. {0,0,&_44u4__p5_0},
  150439. {&_44u4__p6_0,&_44u4__p6_1},
  150440. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  150441. }
  150442. };
  150443. static static_bookblock _resbook_44u_5={
  150444. {
  150445. {0},
  150446. {0,0,&_44u5__p1_0},
  150447. {0,0,&_44u5__p2_0},
  150448. {0,0,&_44u5__p3_0},
  150449. {0,0,&_44u5__p4_0},
  150450. {0,0,&_44u5__p5_0},
  150451. {0,0,&_44u5__p6_0},
  150452. {&_44u5__p7_0,&_44u5__p7_1},
  150453. {&_44u5__p8_0,&_44u5__p8_1},
  150454. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  150455. }
  150456. };
  150457. static static_bookblock _resbook_44u_6={
  150458. {
  150459. {0},
  150460. {0,0,&_44u6__p1_0},
  150461. {0,0,&_44u6__p2_0},
  150462. {0,0,&_44u6__p3_0},
  150463. {0,0,&_44u6__p4_0},
  150464. {0,0,&_44u6__p5_0},
  150465. {0,0,&_44u6__p6_0},
  150466. {&_44u6__p7_0,&_44u6__p7_1},
  150467. {&_44u6__p8_0,&_44u6__p8_1},
  150468. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  150469. }
  150470. };
  150471. static static_bookblock _resbook_44u_7={
  150472. {
  150473. {0},
  150474. {0,0,&_44u7__p1_0},
  150475. {0,0,&_44u7__p2_0},
  150476. {0,0,&_44u7__p3_0},
  150477. {0,0,&_44u7__p4_0},
  150478. {0,0,&_44u7__p5_0},
  150479. {0,0,&_44u7__p6_0},
  150480. {&_44u7__p7_0,&_44u7__p7_1},
  150481. {&_44u7__p8_0,&_44u7__p8_1},
  150482. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  150483. }
  150484. };
  150485. static static_bookblock _resbook_44u_8={
  150486. {
  150487. {0},
  150488. {0,0,&_44u8_p1_0},
  150489. {0,0,&_44u8_p2_0},
  150490. {0,0,&_44u8_p3_0},
  150491. {0,0,&_44u8_p4_0},
  150492. {&_44u8_p5_0,&_44u8_p5_1},
  150493. {&_44u8_p6_0,&_44u8_p6_1},
  150494. {&_44u8_p7_0,&_44u8_p7_1},
  150495. {&_44u8_p8_0,&_44u8_p8_1},
  150496. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  150497. }
  150498. };
  150499. static static_bookblock _resbook_44u_9={
  150500. {
  150501. {0},
  150502. {0,0,&_44u9_p1_0},
  150503. {0,0,&_44u9_p2_0},
  150504. {0,0,&_44u9_p3_0},
  150505. {0,0,&_44u9_p4_0},
  150506. {&_44u9_p5_0,&_44u9_p5_1},
  150507. {&_44u9_p6_0,&_44u9_p6_1},
  150508. {&_44u9_p7_0,&_44u9_p7_1},
  150509. {&_44u9_p8_0,&_44u9_p8_1},
  150510. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  150511. }
  150512. };
  150513. static vorbis_residue_template _res_44u_n1[]={
  150514. {1,0, &_residue_44_low_un,
  150515. &_huff_book__44un1__short,&_huff_book__44un1__short,
  150516. &_resbook_44u_n1,&_resbook_44u_n1},
  150517. {1,0, &_residue_44_low_un,
  150518. &_huff_book__44un1__long,&_huff_book__44un1__long,
  150519. &_resbook_44u_n1,&_resbook_44u_n1}
  150520. };
  150521. static vorbis_residue_template _res_44u_0[]={
  150522. {1,0, &_residue_44_low_un,
  150523. &_huff_book__44u0__short,&_huff_book__44u0__short,
  150524. &_resbook_44u_0,&_resbook_44u_0},
  150525. {1,0, &_residue_44_low_un,
  150526. &_huff_book__44u0__long,&_huff_book__44u0__long,
  150527. &_resbook_44u_0,&_resbook_44u_0}
  150528. };
  150529. static vorbis_residue_template _res_44u_1[]={
  150530. {1,0, &_residue_44_low_un,
  150531. &_huff_book__44u1__short,&_huff_book__44u1__short,
  150532. &_resbook_44u_1,&_resbook_44u_1},
  150533. {1,0, &_residue_44_low_un,
  150534. &_huff_book__44u1__long,&_huff_book__44u1__long,
  150535. &_resbook_44u_1,&_resbook_44u_1}
  150536. };
  150537. static vorbis_residue_template _res_44u_2[]={
  150538. {1,0, &_residue_44_low_un,
  150539. &_huff_book__44u2__short,&_huff_book__44u2__short,
  150540. &_resbook_44u_2,&_resbook_44u_2},
  150541. {1,0, &_residue_44_low_un,
  150542. &_huff_book__44u2__long,&_huff_book__44u2__long,
  150543. &_resbook_44u_2,&_resbook_44u_2}
  150544. };
  150545. static vorbis_residue_template _res_44u_3[]={
  150546. {1,0, &_residue_44_low_un,
  150547. &_huff_book__44u3__short,&_huff_book__44u3__short,
  150548. &_resbook_44u_3,&_resbook_44u_3},
  150549. {1,0, &_residue_44_low_un,
  150550. &_huff_book__44u3__long,&_huff_book__44u3__long,
  150551. &_resbook_44u_3,&_resbook_44u_3}
  150552. };
  150553. static vorbis_residue_template _res_44u_4[]={
  150554. {1,0, &_residue_44_low_un,
  150555. &_huff_book__44u4__short,&_huff_book__44u4__short,
  150556. &_resbook_44u_4,&_resbook_44u_4},
  150557. {1,0, &_residue_44_low_un,
  150558. &_huff_book__44u4__long,&_huff_book__44u4__long,
  150559. &_resbook_44u_4,&_resbook_44u_4}
  150560. };
  150561. static vorbis_residue_template _res_44u_5[]={
  150562. {1,0, &_residue_44_mid_un,
  150563. &_huff_book__44u5__short,&_huff_book__44u5__short,
  150564. &_resbook_44u_5,&_resbook_44u_5},
  150565. {1,0, &_residue_44_mid_un,
  150566. &_huff_book__44u5__long,&_huff_book__44u5__long,
  150567. &_resbook_44u_5,&_resbook_44u_5}
  150568. };
  150569. static vorbis_residue_template _res_44u_6[]={
  150570. {1,0, &_residue_44_mid_un,
  150571. &_huff_book__44u6__short,&_huff_book__44u6__short,
  150572. &_resbook_44u_6,&_resbook_44u_6},
  150573. {1,0, &_residue_44_mid_un,
  150574. &_huff_book__44u6__long,&_huff_book__44u6__long,
  150575. &_resbook_44u_6,&_resbook_44u_6}
  150576. };
  150577. static vorbis_residue_template _res_44u_7[]={
  150578. {1,0, &_residue_44_mid_un,
  150579. &_huff_book__44u7__short,&_huff_book__44u7__short,
  150580. &_resbook_44u_7,&_resbook_44u_7},
  150581. {1,0, &_residue_44_mid_un,
  150582. &_huff_book__44u7__long,&_huff_book__44u7__long,
  150583. &_resbook_44u_7,&_resbook_44u_7}
  150584. };
  150585. static vorbis_residue_template _res_44u_8[]={
  150586. {1,0, &_residue_44_hi_un,
  150587. &_huff_book__44u8__short,&_huff_book__44u8__short,
  150588. &_resbook_44u_8,&_resbook_44u_8},
  150589. {1,0, &_residue_44_hi_un,
  150590. &_huff_book__44u8__long,&_huff_book__44u8__long,
  150591. &_resbook_44u_8,&_resbook_44u_8}
  150592. };
  150593. static vorbis_residue_template _res_44u_9[]={
  150594. {1,0, &_residue_44_hi_un,
  150595. &_huff_book__44u9__short,&_huff_book__44u9__short,
  150596. &_resbook_44u_9,&_resbook_44u_9},
  150597. {1,0, &_residue_44_hi_un,
  150598. &_huff_book__44u9__long,&_huff_book__44u9__long,
  150599. &_resbook_44u_9,&_resbook_44u_9}
  150600. };
  150601. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  150602. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  150603. { _map_nominal_u, _res_44u_0 }, /* 0 */
  150604. { _map_nominal_u, _res_44u_1 }, /* 1 */
  150605. { _map_nominal_u, _res_44u_2 }, /* 2 */
  150606. { _map_nominal_u, _res_44u_3 }, /* 3 */
  150607. { _map_nominal_u, _res_44u_4 }, /* 4 */
  150608. { _map_nominal_u, _res_44u_5 }, /* 5 */
  150609. { _map_nominal_u, _res_44u_6 }, /* 6 */
  150610. { _map_nominal_u, _res_44u_7 }, /* 7 */
  150611. { _map_nominal_u, _res_44u_8 }, /* 8 */
  150612. { _map_nominal_u, _res_44u_9 }, /* 9 */
  150613. };
  150614. /*** End of inlined file: residue_44u.h ***/
  150615. static double rate_mapping_44_un[12]={
  150616. 32000.,48000.,60000.,70000.,80000.,86000.,
  150617. 96000.,110000.,120000.,140000.,160000.,240001.
  150618. };
  150619. ve_setup_data_template ve_setup_44_uncoupled={
  150620. 11,
  150621. rate_mapping_44_un,
  150622. quality_mapping_44,
  150623. -1,
  150624. 40000,
  150625. 50000,
  150626. blocksize_short_44,
  150627. blocksize_long_44,
  150628. _psy_tone_masteratt_44,
  150629. _psy_tone_0dB,
  150630. _psy_tone_suppress,
  150631. _vp_tonemask_adj_otherblock,
  150632. _vp_tonemask_adj_longblock,
  150633. _vp_tonemask_adj_otherblock,
  150634. _psy_noiseguards_44,
  150635. _psy_noisebias_impulse,
  150636. _psy_noisebias_padding,
  150637. _psy_noisebias_trans,
  150638. _psy_noisebias_long,
  150639. _psy_noise_suppress,
  150640. _psy_compand_44,
  150641. _psy_compand_short_mapping,
  150642. _psy_compand_long_mapping,
  150643. {_noise_start_short_44,_noise_start_long_44},
  150644. {_noise_part_short_44,_noise_part_long_44},
  150645. _noise_thresh_44,
  150646. _psy_ath_floater,
  150647. _psy_ath_abs,
  150648. _psy_lowpass_44,
  150649. _psy_global_44,
  150650. _global_mapping_44,
  150651. NULL,
  150652. _floor_books,
  150653. _floor,
  150654. _floor_short_mapping_44,
  150655. _floor_long_mapping_44,
  150656. _mapres_template_44_uncoupled
  150657. };
  150658. /*** End of inlined file: setup_44u.h ***/
  150659. /*** Start of inlined file: setup_32.h ***/
  150660. static double rate_mapping_32[12]={
  150661. 18000.,28000.,35000.,45000.,56000.,60000.,
  150662. 75000.,90000.,100000.,115000.,150000.,190000.,
  150663. };
  150664. static double rate_mapping_32_un[12]={
  150665. 30000.,42000.,52000.,64000.,72000.,78000.,
  150666. 86000.,92000.,110000.,120000.,140000.,190000.,
  150667. };
  150668. static double _psy_lowpass_32[12]={
  150669. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  150670. };
  150671. ve_setup_data_template ve_setup_32_stereo={
  150672. 11,
  150673. rate_mapping_32,
  150674. quality_mapping_44,
  150675. 2,
  150676. 26000,
  150677. 40000,
  150678. blocksize_short_44,
  150679. blocksize_long_44,
  150680. _psy_tone_masteratt_44,
  150681. _psy_tone_0dB,
  150682. _psy_tone_suppress,
  150683. _vp_tonemask_adj_otherblock,
  150684. _vp_tonemask_adj_longblock,
  150685. _vp_tonemask_adj_otherblock,
  150686. _psy_noiseguards_44,
  150687. _psy_noisebias_impulse,
  150688. _psy_noisebias_padding,
  150689. _psy_noisebias_trans,
  150690. _psy_noisebias_long,
  150691. _psy_noise_suppress,
  150692. _psy_compand_44,
  150693. _psy_compand_short_mapping,
  150694. _psy_compand_long_mapping,
  150695. {_noise_start_short_44,_noise_start_long_44},
  150696. {_noise_part_short_44,_noise_part_long_44},
  150697. _noise_thresh_44,
  150698. _psy_ath_floater,
  150699. _psy_ath_abs,
  150700. _psy_lowpass_32,
  150701. _psy_global_44,
  150702. _global_mapping_44,
  150703. _psy_stereo_modes_44,
  150704. _floor_books,
  150705. _floor,
  150706. _floor_short_mapping_44,
  150707. _floor_long_mapping_44,
  150708. _mapres_template_44_stereo
  150709. };
  150710. ve_setup_data_template ve_setup_32_uncoupled={
  150711. 11,
  150712. rate_mapping_32_un,
  150713. quality_mapping_44,
  150714. -1,
  150715. 26000,
  150716. 40000,
  150717. blocksize_short_44,
  150718. blocksize_long_44,
  150719. _psy_tone_masteratt_44,
  150720. _psy_tone_0dB,
  150721. _psy_tone_suppress,
  150722. _vp_tonemask_adj_otherblock,
  150723. _vp_tonemask_adj_longblock,
  150724. _vp_tonemask_adj_otherblock,
  150725. _psy_noiseguards_44,
  150726. _psy_noisebias_impulse,
  150727. _psy_noisebias_padding,
  150728. _psy_noisebias_trans,
  150729. _psy_noisebias_long,
  150730. _psy_noise_suppress,
  150731. _psy_compand_44,
  150732. _psy_compand_short_mapping,
  150733. _psy_compand_long_mapping,
  150734. {_noise_start_short_44,_noise_start_long_44},
  150735. {_noise_part_short_44,_noise_part_long_44},
  150736. _noise_thresh_44,
  150737. _psy_ath_floater,
  150738. _psy_ath_abs,
  150739. _psy_lowpass_32,
  150740. _psy_global_44,
  150741. _global_mapping_44,
  150742. NULL,
  150743. _floor_books,
  150744. _floor,
  150745. _floor_short_mapping_44,
  150746. _floor_long_mapping_44,
  150747. _mapres_template_44_uncoupled
  150748. };
  150749. /*** End of inlined file: setup_32.h ***/
  150750. /*** Start of inlined file: setup_8.h ***/
  150751. /*** Start of inlined file: psych_8.h ***/
  150752. static att3 _psy_tone_masteratt_8[3]={
  150753. {{ 32, 25, 12}, 0, 0}, /* 0 */
  150754. {{ 30, 25, 12}, 0, 0}, /* 0 */
  150755. {{ 20, 0, -14}, 0, 0}, /* 0 */
  150756. };
  150757. static vp_adjblock _vp_tonemask_adj_8[3]={
  150758. /* adjust for mode zero */
  150759. /* 63 125 250 500 1 2 4 8 16 */
  150760. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  150761. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  150762. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  150763. };
  150764. static noise3 _psy_noisebias_8[3]={
  150765. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  150766. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  150767. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  150768. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  150769. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  150770. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  150771. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  150772. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  150773. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  150774. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  150775. };
  150776. /* stereo mode by base quality level */
  150777. static adj_stereo _psy_stereo_modes_8[3]={
  150778. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  150779. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  150780. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  150781. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  150782. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  150783. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  150784. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  150785. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  150786. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  150787. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  150788. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  150789. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  150790. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  150791. };
  150792. static noiseguard _psy_noiseguards_8[2]={
  150793. {10,10,-1},
  150794. {10,10,-1},
  150795. };
  150796. static compandblock _psy_compand_8[2]={
  150797. {{
  150798. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  150799. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  150800. 12,12,13,13,14,14,15, 15, /* 23dB */
  150801. 16,16,17,17,17,18,18, 19, /* 31dB */
  150802. 19,19,20,21,22,23,24, 25, /* 39dB */
  150803. }},
  150804. {{
  150805. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  150806. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  150807. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  150808. 9,10,11,12,13,14,15, 16, /* 31dB */
  150809. 17,18,19,20,21,22,23, 24, /* 39dB */
  150810. }},
  150811. };
  150812. static double _psy_lowpass_8[3]={3.,4.,4.};
  150813. static int _noise_start_8[2]={
  150814. 64,64,
  150815. };
  150816. static int _noise_part_8[2]={
  150817. 8,8,
  150818. };
  150819. static int _psy_ath_floater_8[3]={
  150820. -100,-100,-105,
  150821. };
  150822. static int _psy_ath_abs_8[3]={
  150823. -130,-130,-140,
  150824. };
  150825. /*** End of inlined file: psych_8.h ***/
  150826. /*** Start of inlined file: residue_8.h ***/
  150827. /***** residue backends *********************************************/
  150828. static static_bookblock _resbook_8s_0={
  150829. {
  150830. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  150831. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  150832. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  150833. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  150834. }
  150835. };
  150836. static static_bookblock _resbook_8s_1={
  150837. {
  150838. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  150839. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  150840. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  150841. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  150842. }
  150843. };
  150844. static vorbis_residue_template _res_8s_0[]={
  150845. {2,0, &_residue_44_mid,
  150846. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  150847. &_resbook_8s_0,&_resbook_8s_0},
  150848. };
  150849. static vorbis_residue_template _res_8s_1[]={
  150850. {2,0, &_residue_44_mid,
  150851. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  150852. &_resbook_8s_1,&_resbook_8s_1},
  150853. };
  150854. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  150855. { _map_nominal, _res_8s_0 }, /* 0 */
  150856. { _map_nominal, _res_8s_1 }, /* 1 */
  150857. };
  150858. static static_bookblock _resbook_8u_0={
  150859. {
  150860. {0},
  150861. {0,0,&_8u0__p1_0},
  150862. {0,0,&_8u0__p2_0},
  150863. {0,0,&_8u0__p3_0},
  150864. {0,0,&_8u0__p4_0},
  150865. {0,0,&_8u0__p5_0},
  150866. {&_8u0__p6_0,&_8u0__p6_1},
  150867. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  150868. }
  150869. };
  150870. static static_bookblock _resbook_8u_1={
  150871. {
  150872. {0},
  150873. {0,0,&_8u1__p1_0},
  150874. {0,0,&_8u1__p2_0},
  150875. {0,0,&_8u1__p3_0},
  150876. {0,0,&_8u1__p4_0},
  150877. {0,0,&_8u1__p5_0},
  150878. {0,0,&_8u1__p6_0},
  150879. {&_8u1__p7_0,&_8u1__p7_1},
  150880. {&_8u1__p8_0,&_8u1__p8_1},
  150881. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  150882. }
  150883. };
  150884. static vorbis_residue_template _res_8u_0[]={
  150885. {1,0, &_residue_44_low_un,
  150886. &_huff_book__8u0__single,&_huff_book__8u0__single,
  150887. &_resbook_8u_0,&_resbook_8u_0},
  150888. };
  150889. static vorbis_residue_template _res_8u_1[]={
  150890. {1,0, &_residue_44_mid_un,
  150891. &_huff_book__8u1__single,&_huff_book__8u1__single,
  150892. &_resbook_8u_1,&_resbook_8u_1},
  150893. };
  150894. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  150895. { _map_nominal_u, _res_8u_0 }, /* 0 */
  150896. { _map_nominal_u, _res_8u_1 }, /* 1 */
  150897. };
  150898. /*** End of inlined file: residue_8.h ***/
  150899. static int blocksize_8[2]={
  150900. 512,512
  150901. };
  150902. static int _floor_mapping_8[2]={
  150903. 6,6,
  150904. };
  150905. static double rate_mapping_8[3]={
  150906. 6000.,9000.,32000.,
  150907. };
  150908. static double rate_mapping_8_uncoupled[3]={
  150909. 8000.,14000.,42000.,
  150910. };
  150911. static double quality_mapping_8[3]={
  150912. -.1,.0,1.
  150913. };
  150914. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  150915. static double _global_mapping_8[3]={ 1., 2., 3. };
  150916. ve_setup_data_template ve_setup_8_stereo={
  150917. 2,
  150918. rate_mapping_8,
  150919. quality_mapping_8,
  150920. 2,
  150921. 8000,
  150922. 9000,
  150923. blocksize_8,
  150924. blocksize_8,
  150925. _psy_tone_masteratt_8,
  150926. _psy_tone_0dB,
  150927. _psy_tone_suppress,
  150928. _vp_tonemask_adj_8,
  150929. NULL,
  150930. _vp_tonemask_adj_8,
  150931. _psy_noiseguards_8,
  150932. _psy_noisebias_8,
  150933. _psy_noisebias_8,
  150934. NULL,
  150935. NULL,
  150936. _psy_noise_suppress,
  150937. _psy_compand_8,
  150938. _psy_compand_8_mapping,
  150939. NULL,
  150940. {_noise_start_8,_noise_start_8},
  150941. {_noise_part_8,_noise_part_8},
  150942. _noise_thresh_5only,
  150943. _psy_ath_floater_8,
  150944. _psy_ath_abs_8,
  150945. _psy_lowpass_8,
  150946. _psy_global_44,
  150947. _global_mapping_8,
  150948. _psy_stereo_modes_8,
  150949. _floor_books,
  150950. _floor,
  150951. _floor_mapping_8,
  150952. NULL,
  150953. _mapres_template_8_stereo
  150954. };
  150955. ve_setup_data_template ve_setup_8_uncoupled={
  150956. 2,
  150957. rate_mapping_8_uncoupled,
  150958. quality_mapping_8,
  150959. -1,
  150960. 8000,
  150961. 9000,
  150962. blocksize_8,
  150963. blocksize_8,
  150964. _psy_tone_masteratt_8,
  150965. _psy_tone_0dB,
  150966. _psy_tone_suppress,
  150967. _vp_tonemask_adj_8,
  150968. NULL,
  150969. _vp_tonemask_adj_8,
  150970. _psy_noiseguards_8,
  150971. _psy_noisebias_8,
  150972. _psy_noisebias_8,
  150973. NULL,
  150974. NULL,
  150975. _psy_noise_suppress,
  150976. _psy_compand_8,
  150977. _psy_compand_8_mapping,
  150978. NULL,
  150979. {_noise_start_8,_noise_start_8},
  150980. {_noise_part_8,_noise_part_8},
  150981. _noise_thresh_5only,
  150982. _psy_ath_floater_8,
  150983. _psy_ath_abs_8,
  150984. _psy_lowpass_8,
  150985. _psy_global_44,
  150986. _global_mapping_8,
  150987. _psy_stereo_modes_8,
  150988. _floor_books,
  150989. _floor,
  150990. _floor_mapping_8,
  150991. NULL,
  150992. _mapres_template_8_uncoupled
  150993. };
  150994. /*** End of inlined file: setup_8.h ***/
  150995. /*** Start of inlined file: setup_11.h ***/
  150996. /*** Start of inlined file: psych_11.h ***/
  150997. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  150998. static att3 _psy_tone_masteratt_11[3]={
  150999. {{ 30, 25, 12}, 0, 0}, /* 0 */
  151000. {{ 30, 25, 12}, 0, 0}, /* 0 */
  151001. {{ 20, 0, -14}, 0, 0}, /* 0 */
  151002. };
  151003. static vp_adjblock _vp_tonemask_adj_11[3]={
  151004. /* adjust for mode zero */
  151005. /* 63 125 250 500 1 2 4 8 16 */
  151006. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  151007. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  151008. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  151009. };
  151010. static noise3 _psy_noisebias_11[3]={
  151011. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  151012. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  151013. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  151014. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  151015. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  151016. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  151017. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  151018. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  151019. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  151020. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  151021. };
  151022. static double _noise_thresh_11[3]={ .3,.5,.5 };
  151023. /*** End of inlined file: psych_11.h ***/
  151024. static int blocksize_11[2]={
  151025. 512,512
  151026. };
  151027. static int _floor_mapping_11[2]={
  151028. 6,6,
  151029. };
  151030. static double rate_mapping_11[3]={
  151031. 8000.,13000.,44000.,
  151032. };
  151033. static double rate_mapping_11_uncoupled[3]={
  151034. 12000.,20000.,50000.,
  151035. };
  151036. static double quality_mapping_11[3]={
  151037. -.1,.0,1.
  151038. };
  151039. ve_setup_data_template ve_setup_11_stereo={
  151040. 2,
  151041. rate_mapping_11,
  151042. quality_mapping_11,
  151043. 2,
  151044. 9000,
  151045. 15000,
  151046. blocksize_11,
  151047. blocksize_11,
  151048. _psy_tone_masteratt_11,
  151049. _psy_tone_0dB,
  151050. _psy_tone_suppress,
  151051. _vp_tonemask_adj_11,
  151052. NULL,
  151053. _vp_tonemask_adj_11,
  151054. _psy_noiseguards_8,
  151055. _psy_noisebias_11,
  151056. _psy_noisebias_11,
  151057. NULL,
  151058. NULL,
  151059. _psy_noise_suppress,
  151060. _psy_compand_8,
  151061. _psy_compand_8_mapping,
  151062. NULL,
  151063. {_noise_start_8,_noise_start_8},
  151064. {_noise_part_8,_noise_part_8},
  151065. _noise_thresh_11,
  151066. _psy_ath_floater_8,
  151067. _psy_ath_abs_8,
  151068. _psy_lowpass_11,
  151069. _psy_global_44,
  151070. _global_mapping_8,
  151071. _psy_stereo_modes_8,
  151072. _floor_books,
  151073. _floor,
  151074. _floor_mapping_11,
  151075. NULL,
  151076. _mapres_template_8_stereo
  151077. };
  151078. ve_setup_data_template ve_setup_11_uncoupled={
  151079. 2,
  151080. rate_mapping_11_uncoupled,
  151081. quality_mapping_11,
  151082. -1,
  151083. 9000,
  151084. 15000,
  151085. blocksize_11,
  151086. blocksize_11,
  151087. _psy_tone_masteratt_11,
  151088. _psy_tone_0dB,
  151089. _psy_tone_suppress,
  151090. _vp_tonemask_adj_11,
  151091. NULL,
  151092. _vp_tonemask_adj_11,
  151093. _psy_noiseguards_8,
  151094. _psy_noisebias_11,
  151095. _psy_noisebias_11,
  151096. NULL,
  151097. NULL,
  151098. _psy_noise_suppress,
  151099. _psy_compand_8,
  151100. _psy_compand_8_mapping,
  151101. NULL,
  151102. {_noise_start_8,_noise_start_8},
  151103. {_noise_part_8,_noise_part_8},
  151104. _noise_thresh_11,
  151105. _psy_ath_floater_8,
  151106. _psy_ath_abs_8,
  151107. _psy_lowpass_11,
  151108. _psy_global_44,
  151109. _global_mapping_8,
  151110. _psy_stereo_modes_8,
  151111. _floor_books,
  151112. _floor,
  151113. _floor_mapping_11,
  151114. NULL,
  151115. _mapres_template_8_uncoupled
  151116. };
  151117. /*** End of inlined file: setup_11.h ***/
  151118. /*** Start of inlined file: setup_16.h ***/
  151119. /*** Start of inlined file: psych_16.h ***/
  151120. /* stereo mode by base quality level */
  151121. static adj_stereo _psy_stereo_modes_16[4]={
  151122. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  151123. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  151124. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  151125. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  151126. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  151127. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  151128. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  151129. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  151130. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  151131. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  151132. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  151133. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  151134. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  151135. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  151136. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  151137. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  151138. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  151139. };
  151140. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  151141. static att3 _psy_tone_masteratt_16[4]={
  151142. {{ 30, 25, 12}, 0, 0}, /* 0 */
  151143. {{ 25, 22, 12}, 0, 0}, /* 0 */
  151144. {{ 20, 12, 0}, 0, 0}, /* 0 */
  151145. {{ 15, 0, -14}, 0, 0}, /* 0 */
  151146. };
  151147. static vp_adjblock _vp_tonemask_adj_16[4]={
  151148. /* adjust for mode zero */
  151149. /* 63 125 250 500 1 2 4 8 16 */
  151150. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  151151. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  151152. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  151153. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  151154. };
  151155. static noise3 _psy_noisebias_16_short[4]={
  151156. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  151157. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  151158. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  151159. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  151160. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  151161. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  151162. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  151163. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  151164. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  151165. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  151166. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  151167. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  151168. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  151169. };
  151170. static noise3 _psy_noisebias_16_impulse[4]={
  151171. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  151172. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  151173. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  151174. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  151175. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  151176. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  151177. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  151178. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  151179. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  151180. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  151181. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  151182. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  151183. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  151184. };
  151185. static noise3 _psy_noisebias_16[4]={
  151186. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  151187. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  151188. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  151189. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  151190. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  151191. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  151192. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  151193. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  151194. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  151195. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  151196. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  151197. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  151198. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  151199. };
  151200. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  151201. static int _noise_start_16[3]={ 256,256,9999 };
  151202. static int _noise_part_16[4]={ 8,8,8,8 };
  151203. static int _psy_ath_floater_16[4]={
  151204. -100,-100,-100,-105,
  151205. };
  151206. static int _psy_ath_abs_16[4]={
  151207. -130,-130,-130,-140,
  151208. };
  151209. /*** End of inlined file: psych_16.h ***/
  151210. /*** Start of inlined file: residue_16.h ***/
  151211. /***** residue backends *********************************************/
  151212. static static_bookblock _resbook_16s_0={
  151213. {
  151214. {0},
  151215. {0,0,&_16c0_s_p1_0},
  151216. {0,0,&_16c0_s_p2_0},
  151217. {0,0,&_16c0_s_p3_0},
  151218. {0,0,&_16c0_s_p4_0},
  151219. {0,0,&_16c0_s_p5_0},
  151220. {0,0,&_16c0_s_p6_0},
  151221. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  151222. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  151223. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  151224. }
  151225. };
  151226. static static_bookblock _resbook_16s_1={
  151227. {
  151228. {0},
  151229. {0,0,&_16c1_s_p1_0},
  151230. {0,0,&_16c1_s_p2_0},
  151231. {0,0,&_16c1_s_p3_0},
  151232. {0,0,&_16c1_s_p4_0},
  151233. {0,0,&_16c1_s_p5_0},
  151234. {0,0,&_16c1_s_p6_0},
  151235. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  151236. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  151237. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  151238. }
  151239. };
  151240. static static_bookblock _resbook_16s_2={
  151241. {
  151242. {0},
  151243. {0,0,&_16c2_s_p1_0},
  151244. {0,0,&_16c2_s_p2_0},
  151245. {0,0,&_16c2_s_p3_0},
  151246. {0,0,&_16c2_s_p4_0},
  151247. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  151248. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  151249. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  151250. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  151251. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  151252. }
  151253. };
  151254. static vorbis_residue_template _res_16s_0[]={
  151255. {2,0, &_residue_44_mid,
  151256. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  151257. &_resbook_16s_0,&_resbook_16s_0},
  151258. };
  151259. static vorbis_residue_template _res_16s_1[]={
  151260. {2,0, &_residue_44_mid,
  151261. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  151262. &_resbook_16s_1,&_resbook_16s_1},
  151263. {2,0, &_residue_44_mid,
  151264. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  151265. &_resbook_16s_1,&_resbook_16s_1}
  151266. };
  151267. static vorbis_residue_template _res_16s_2[]={
  151268. {2,0, &_residue_44_high,
  151269. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  151270. &_resbook_16s_2,&_resbook_16s_2},
  151271. {2,0, &_residue_44_high,
  151272. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  151273. &_resbook_16s_2,&_resbook_16s_2}
  151274. };
  151275. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  151276. { _map_nominal, _res_16s_0 }, /* 0 */
  151277. { _map_nominal, _res_16s_1 }, /* 1 */
  151278. { _map_nominal, _res_16s_2 }, /* 2 */
  151279. };
  151280. static static_bookblock _resbook_16u_0={
  151281. {
  151282. {0},
  151283. {0,0,&_16u0__p1_0},
  151284. {0,0,&_16u0__p2_0},
  151285. {0,0,&_16u0__p3_0},
  151286. {0,0,&_16u0__p4_0},
  151287. {0,0,&_16u0__p5_0},
  151288. {&_16u0__p6_0,&_16u0__p6_1},
  151289. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  151290. }
  151291. };
  151292. static static_bookblock _resbook_16u_1={
  151293. {
  151294. {0},
  151295. {0,0,&_16u1__p1_0},
  151296. {0,0,&_16u1__p2_0},
  151297. {0,0,&_16u1__p3_0},
  151298. {0,0,&_16u1__p4_0},
  151299. {0,0,&_16u1__p5_0},
  151300. {0,0,&_16u1__p6_0},
  151301. {&_16u1__p7_0,&_16u1__p7_1},
  151302. {&_16u1__p8_0,&_16u1__p8_1},
  151303. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  151304. }
  151305. };
  151306. static static_bookblock _resbook_16u_2={
  151307. {
  151308. {0},
  151309. {0,0,&_16u2_p1_0},
  151310. {0,0,&_16u2_p2_0},
  151311. {0,0,&_16u2_p3_0},
  151312. {0,0,&_16u2_p4_0},
  151313. {&_16u2_p5_0,&_16u2_p5_1},
  151314. {&_16u2_p6_0,&_16u2_p6_1},
  151315. {&_16u2_p7_0,&_16u2_p7_1},
  151316. {&_16u2_p8_0,&_16u2_p8_1},
  151317. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  151318. }
  151319. };
  151320. static vorbis_residue_template _res_16u_0[]={
  151321. {1,0, &_residue_44_low_un,
  151322. &_huff_book__16u0__single,&_huff_book__16u0__single,
  151323. &_resbook_16u_0,&_resbook_16u_0},
  151324. };
  151325. static vorbis_residue_template _res_16u_1[]={
  151326. {1,0, &_residue_44_mid_un,
  151327. &_huff_book__16u1__short,&_huff_book__16u1__short,
  151328. &_resbook_16u_1,&_resbook_16u_1},
  151329. {1,0, &_residue_44_mid_un,
  151330. &_huff_book__16u1__long,&_huff_book__16u1__long,
  151331. &_resbook_16u_1,&_resbook_16u_1}
  151332. };
  151333. static vorbis_residue_template _res_16u_2[]={
  151334. {1,0, &_residue_44_hi_un,
  151335. &_huff_book__16u2__short,&_huff_book__16u2__short,
  151336. &_resbook_16u_2,&_resbook_16u_2},
  151337. {1,0, &_residue_44_hi_un,
  151338. &_huff_book__16u2__long,&_huff_book__16u2__long,
  151339. &_resbook_16u_2,&_resbook_16u_2}
  151340. };
  151341. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  151342. { _map_nominal_u, _res_16u_0 }, /* 0 */
  151343. { _map_nominal_u, _res_16u_1 }, /* 1 */
  151344. { _map_nominal_u, _res_16u_2 }, /* 2 */
  151345. };
  151346. /*** End of inlined file: residue_16.h ***/
  151347. static int blocksize_16_short[3]={
  151348. 1024,512,512
  151349. };
  151350. static int blocksize_16_long[3]={
  151351. 1024,1024,1024
  151352. };
  151353. static int _floor_mapping_16_short[3]={
  151354. 9,3,3
  151355. };
  151356. static int _floor_mapping_16[3]={
  151357. 9,9,9
  151358. };
  151359. static double rate_mapping_16[4]={
  151360. 12000.,20000.,44000.,86000.
  151361. };
  151362. static double rate_mapping_16_uncoupled[4]={
  151363. 16000.,28000.,64000.,100000.
  151364. };
  151365. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  151366. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  151367. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  151368. ve_setup_data_template ve_setup_16_stereo={
  151369. 3,
  151370. rate_mapping_16,
  151371. quality_mapping_16,
  151372. 2,
  151373. 15000,
  151374. 19000,
  151375. blocksize_16_short,
  151376. blocksize_16_long,
  151377. _psy_tone_masteratt_16,
  151378. _psy_tone_0dB,
  151379. _psy_tone_suppress,
  151380. _vp_tonemask_adj_16,
  151381. _vp_tonemask_adj_16,
  151382. _vp_tonemask_adj_16,
  151383. _psy_noiseguards_8,
  151384. _psy_noisebias_16_impulse,
  151385. _psy_noisebias_16_short,
  151386. _psy_noisebias_16_short,
  151387. _psy_noisebias_16,
  151388. _psy_noise_suppress,
  151389. _psy_compand_8,
  151390. _psy_compand_16_mapping,
  151391. _psy_compand_16_mapping,
  151392. {_noise_start_16,_noise_start_16},
  151393. { _noise_part_16, _noise_part_16},
  151394. _noise_thresh_16,
  151395. _psy_ath_floater_16,
  151396. _psy_ath_abs_16,
  151397. _psy_lowpass_16,
  151398. _psy_global_44,
  151399. _global_mapping_16,
  151400. _psy_stereo_modes_16,
  151401. _floor_books,
  151402. _floor,
  151403. _floor_mapping_16_short,
  151404. _floor_mapping_16,
  151405. _mapres_template_16_stereo
  151406. };
  151407. ve_setup_data_template ve_setup_16_uncoupled={
  151408. 3,
  151409. rate_mapping_16_uncoupled,
  151410. quality_mapping_16,
  151411. -1,
  151412. 15000,
  151413. 19000,
  151414. blocksize_16_short,
  151415. blocksize_16_long,
  151416. _psy_tone_masteratt_16,
  151417. _psy_tone_0dB,
  151418. _psy_tone_suppress,
  151419. _vp_tonemask_adj_16,
  151420. _vp_tonemask_adj_16,
  151421. _vp_tonemask_adj_16,
  151422. _psy_noiseguards_8,
  151423. _psy_noisebias_16_impulse,
  151424. _psy_noisebias_16_short,
  151425. _psy_noisebias_16_short,
  151426. _psy_noisebias_16,
  151427. _psy_noise_suppress,
  151428. _psy_compand_8,
  151429. _psy_compand_16_mapping,
  151430. _psy_compand_16_mapping,
  151431. {_noise_start_16,_noise_start_16},
  151432. { _noise_part_16, _noise_part_16},
  151433. _noise_thresh_16,
  151434. _psy_ath_floater_16,
  151435. _psy_ath_abs_16,
  151436. _psy_lowpass_16,
  151437. _psy_global_44,
  151438. _global_mapping_16,
  151439. _psy_stereo_modes_16,
  151440. _floor_books,
  151441. _floor,
  151442. _floor_mapping_16_short,
  151443. _floor_mapping_16,
  151444. _mapres_template_16_uncoupled
  151445. };
  151446. /*** End of inlined file: setup_16.h ***/
  151447. /*** Start of inlined file: setup_22.h ***/
  151448. static double rate_mapping_22[4]={
  151449. 15000.,20000.,44000.,86000.
  151450. };
  151451. static double rate_mapping_22_uncoupled[4]={
  151452. 16000.,28000.,50000.,90000.
  151453. };
  151454. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  151455. ve_setup_data_template ve_setup_22_stereo={
  151456. 3,
  151457. rate_mapping_22,
  151458. quality_mapping_16,
  151459. 2,
  151460. 19000,
  151461. 26000,
  151462. blocksize_16_short,
  151463. blocksize_16_long,
  151464. _psy_tone_masteratt_16,
  151465. _psy_tone_0dB,
  151466. _psy_tone_suppress,
  151467. _vp_tonemask_adj_16,
  151468. _vp_tonemask_adj_16,
  151469. _vp_tonemask_adj_16,
  151470. _psy_noiseguards_8,
  151471. _psy_noisebias_16_impulse,
  151472. _psy_noisebias_16_short,
  151473. _psy_noisebias_16_short,
  151474. _psy_noisebias_16,
  151475. _psy_noise_suppress,
  151476. _psy_compand_8,
  151477. _psy_compand_8_mapping,
  151478. _psy_compand_8_mapping,
  151479. {_noise_start_16,_noise_start_16},
  151480. { _noise_part_16, _noise_part_16},
  151481. _noise_thresh_16,
  151482. _psy_ath_floater_16,
  151483. _psy_ath_abs_16,
  151484. _psy_lowpass_22,
  151485. _psy_global_44,
  151486. _global_mapping_16,
  151487. _psy_stereo_modes_16,
  151488. _floor_books,
  151489. _floor,
  151490. _floor_mapping_16_short,
  151491. _floor_mapping_16,
  151492. _mapres_template_16_stereo
  151493. };
  151494. ve_setup_data_template ve_setup_22_uncoupled={
  151495. 3,
  151496. rate_mapping_22_uncoupled,
  151497. quality_mapping_16,
  151498. -1,
  151499. 19000,
  151500. 26000,
  151501. blocksize_16_short,
  151502. blocksize_16_long,
  151503. _psy_tone_masteratt_16,
  151504. _psy_tone_0dB,
  151505. _psy_tone_suppress,
  151506. _vp_tonemask_adj_16,
  151507. _vp_tonemask_adj_16,
  151508. _vp_tonemask_adj_16,
  151509. _psy_noiseguards_8,
  151510. _psy_noisebias_16_impulse,
  151511. _psy_noisebias_16_short,
  151512. _psy_noisebias_16_short,
  151513. _psy_noisebias_16,
  151514. _psy_noise_suppress,
  151515. _psy_compand_8,
  151516. _psy_compand_8_mapping,
  151517. _psy_compand_8_mapping,
  151518. {_noise_start_16,_noise_start_16},
  151519. { _noise_part_16, _noise_part_16},
  151520. _noise_thresh_16,
  151521. _psy_ath_floater_16,
  151522. _psy_ath_abs_16,
  151523. _psy_lowpass_22,
  151524. _psy_global_44,
  151525. _global_mapping_16,
  151526. _psy_stereo_modes_16,
  151527. _floor_books,
  151528. _floor,
  151529. _floor_mapping_16_short,
  151530. _floor_mapping_16,
  151531. _mapres_template_16_uncoupled
  151532. };
  151533. /*** End of inlined file: setup_22.h ***/
  151534. /*** Start of inlined file: setup_X.h ***/
  151535. static double rate_mapping_X[12]={
  151536. -1.,-1.,-1.,-1.,-1.,-1.,
  151537. -1.,-1.,-1.,-1.,-1.,-1.
  151538. };
  151539. ve_setup_data_template ve_setup_X_stereo={
  151540. 11,
  151541. rate_mapping_X,
  151542. quality_mapping_44,
  151543. 2,
  151544. 50000,
  151545. 200000,
  151546. blocksize_short_44,
  151547. blocksize_long_44,
  151548. _psy_tone_masteratt_44,
  151549. _psy_tone_0dB,
  151550. _psy_tone_suppress,
  151551. _vp_tonemask_adj_otherblock,
  151552. _vp_tonemask_adj_longblock,
  151553. _vp_tonemask_adj_otherblock,
  151554. _psy_noiseguards_44,
  151555. _psy_noisebias_impulse,
  151556. _psy_noisebias_padding,
  151557. _psy_noisebias_trans,
  151558. _psy_noisebias_long,
  151559. _psy_noise_suppress,
  151560. _psy_compand_44,
  151561. _psy_compand_short_mapping,
  151562. _psy_compand_long_mapping,
  151563. {_noise_start_short_44,_noise_start_long_44},
  151564. {_noise_part_short_44,_noise_part_long_44},
  151565. _noise_thresh_44,
  151566. _psy_ath_floater,
  151567. _psy_ath_abs,
  151568. _psy_lowpass_44,
  151569. _psy_global_44,
  151570. _global_mapping_44,
  151571. _psy_stereo_modes_44,
  151572. _floor_books,
  151573. _floor,
  151574. _floor_short_mapping_44,
  151575. _floor_long_mapping_44,
  151576. _mapres_template_44_stereo
  151577. };
  151578. ve_setup_data_template ve_setup_X_uncoupled={
  151579. 11,
  151580. rate_mapping_X,
  151581. quality_mapping_44,
  151582. -1,
  151583. 50000,
  151584. 200000,
  151585. blocksize_short_44,
  151586. blocksize_long_44,
  151587. _psy_tone_masteratt_44,
  151588. _psy_tone_0dB,
  151589. _psy_tone_suppress,
  151590. _vp_tonemask_adj_otherblock,
  151591. _vp_tonemask_adj_longblock,
  151592. _vp_tonemask_adj_otherblock,
  151593. _psy_noiseguards_44,
  151594. _psy_noisebias_impulse,
  151595. _psy_noisebias_padding,
  151596. _psy_noisebias_trans,
  151597. _psy_noisebias_long,
  151598. _psy_noise_suppress,
  151599. _psy_compand_44,
  151600. _psy_compand_short_mapping,
  151601. _psy_compand_long_mapping,
  151602. {_noise_start_short_44,_noise_start_long_44},
  151603. {_noise_part_short_44,_noise_part_long_44},
  151604. _noise_thresh_44,
  151605. _psy_ath_floater,
  151606. _psy_ath_abs,
  151607. _psy_lowpass_44,
  151608. _psy_global_44,
  151609. _global_mapping_44,
  151610. NULL,
  151611. _floor_books,
  151612. _floor,
  151613. _floor_short_mapping_44,
  151614. _floor_long_mapping_44,
  151615. _mapres_template_44_uncoupled
  151616. };
  151617. ve_setup_data_template ve_setup_XX_stereo={
  151618. 2,
  151619. rate_mapping_X,
  151620. quality_mapping_8,
  151621. 2,
  151622. 0,
  151623. 8000,
  151624. blocksize_8,
  151625. blocksize_8,
  151626. _psy_tone_masteratt_8,
  151627. _psy_tone_0dB,
  151628. _psy_tone_suppress,
  151629. _vp_tonemask_adj_8,
  151630. NULL,
  151631. _vp_tonemask_adj_8,
  151632. _psy_noiseguards_8,
  151633. _psy_noisebias_8,
  151634. _psy_noisebias_8,
  151635. NULL,
  151636. NULL,
  151637. _psy_noise_suppress,
  151638. _psy_compand_8,
  151639. _psy_compand_8_mapping,
  151640. NULL,
  151641. {_noise_start_8,_noise_start_8},
  151642. {_noise_part_8,_noise_part_8},
  151643. _noise_thresh_5only,
  151644. _psy_ath_floater_8,
  151645. _psy_ath_abs_8,
  151646. _psy_lowpass_8,
  151647. _psy_global_44,
  151648. _global_mapping_8,
  151649. _psy_stereo_modes_8,
  151650. _floor_books,
  151651. _floor,
  151652. _floor_mapping_8,
  151653. NULL,
  151654. _mapres_template_8_stereo
  151655. };
  151656. ve_setup_data_template ve_setup_XX_uncoupled={
  151657. 2,
  151658. rate_mapping_X,
  151659. quality_mapping_8,
  151660. -1,
  151661. 0,
  151662. 8000,
  151663. blocksize_8,
  151664. blocksize_8,
  151665. _psy_tone_masteratt_8,
  151666. _psy_tone_0dB,
  151667. _psy_tone_suppress,
  151668. _vp_tonemask_adj_8,
  151669. NULL,
  151670. _vp_tonemask_adj_8,
  151671. _psy_noiseguards_8,
  151672. _psy_noisebias_8,
  151673. _psy_noisebias_8,
  151674. NULL,
  151675. NULL,
  151676. _psy_noise_suppress,
  151677. _psy_compand_8,
  151678. _psy_compand_8_mapping,
  151679. NULL,
  151680. {_noise_start_8,_noise_start_8},
  151681. {_noise_part_8,_noise_part_8},
  151682. _noise_thresh_5only,
  151683. _psy_ath_floater_8,
  151684. _psy_ath_abs_8,
  151685. _psy_lowpass_8,
  151686. _psy_global_44,
  151687. _global_mapping_8,
  151688. _psy_stereo_modes_8,
  151689. _floor_books,
  151690. _floor,
  151691. _floor_mapping_8,
  151692. NULL,
  151693. _mapres_template_8_uncoupled
  151694. };
  151695. /*** End of inlined file: setup_X.h ***/
  151696. static ve_setup_data_template *setup_list[]={
  151697. &ve_setup_44_stereo,
  151698. &ve_setup_44_uncoupled,
  151699. &ve_setup_32_stereo,
  151700. &ve_setup_32_uncoupled,
  151701. &ve_setup_22_stereo,
  151702. &ve_setup_22_uncoupled,
  151703. &ve_setup_16_stereo,
  151704. &ve_setup_16_uncoupled,
  151705. &ve_setup_11_stereo,
  151706. &ve_setup_11_uncoupled,
  151707. &ve_setup_8_stereo,
  151708. &ve_setup_8_uncoupled,
  151709. &ve_setup_X_stereo,
  151710. &ve_setup_X_uncoupled,
  151711. &ve_setup_XX_stereo,
  151712. &ve_setup_XX_uncoupled,
  151713. 0
  151714. };
  151715. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  151716. if(vi && vi->codec_setup){
  151717. vi->version=0;
  151718. vi->channels=ch;
  151719. vi->rate=rate;
  151720. return(0);
  151721. }
  151722. return(OV_EINVAL);
  151723. }
  151724. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  151725. static_codebook ***books,
  151726. vorbis_info_floor1 *in,
  151727. int *x){
  151728. int i,k,is=s;
  151729. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  151730. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151731. memcpy(f,in+x[is],sizeof(*f));
  151732. /* fill in the lowpass field, even if it's temporary */
  151733. f->n=ci->blocksizes[block]>>1;
  151734. /* books */
  151735. {
  151736. int partitions=f->partitions;
  151737. int maxclass=-1;
  151738. int maxbook=-1;
  151739. for(i=0;i<partitions;i++)
  151740. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  151741. for(i=0;i<=maxclass;i++){
  151742. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  151743. f->class_book[i]+=ci->books;
  151744. for(k=0;k<(1<<f->class_subs[i]);k++){
  151745. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  151746. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  151747. }
  151748. }
  151749. for(i=0;i<=maxbook;i++)
  151750. ci->book_param[ci->books++]=books[x[is]][i];
  151751. }
  151752. /* for now, we're only using floor 1 */
  151753. ci->floor_type[ci->floors]=1;
  151754. ci->floor_param[ci->floors]=f;
  151755. ci->floors++;
  151756. return;
  151757. }
  151758. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  151759. vorbis_info_psy_global *in,
  151760. double *x){
  151761. int i,is=s;
  151762. double ds=s-is;
  151763. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151764. vorbis_info_psy_global *g=&ci->psy_g_param;
  151765. memcpy(g,in+(int)x[is],sizeof(*g));
  151766. ds=x[is]*(1.-ds)+x[is+1]*ds;
  151767. is=(int)ds;
  151768. ds-=is;
  151769. if(ds==0 && is>0){
  151770. is--;
  151771. ds=1.;
  151772. }
  151773. /* interpolate the trigger threshholds */
  151774. for(i=0;i<4;i++){
  151775. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  151776. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  151777. }
  151778. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  151779. return;
  151780. }
  151781. static void vorbis_encode_global_stereo(vorbis_info *vi,
  151782. highlevel_encode_setup *hi,
  151783. adj_stereo *p){
  151784. float s=hi->stereo_point_setting;
  151785. int i,is=s;
  151786. double ds=s-is;
  151787. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151788. vorbis_info_psy_global *g=&ci->psy_g_param;
  151789. if(p){
  151790. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  151791. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  151792. if(hi->managed){
  151793. /* interpolate the kHz threshholds */
  151794. for(i=0;i<PACKETBLOBS;i++){
  151795. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  151796. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  151797. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  151798. g->coupling_pkHz[i]=kHz;
  151799. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  151800. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  151801. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  151802. }
  151803. }else{
  151804. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  151805. for(i=0;i<PACKETBLOBS;i++){
  151806. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  151807. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  151808. g->coupling_pkHz[i]=kHz;
  151809. }
  151810. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  151811. for(i=0;i<PACKETBLOBS;i++){
  151812. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  151813. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  151814. }
  151815. }
  151816. }else{
  151817. for(i=0;i<PACKETBLOBS;i++){
  151818. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  151819. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  151820. }
  151821. }
  151822. return;
  151823. }
  151824. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  151825. int *nn_start,
  151826. int *nn_partition,
  151827. double *nn_thresh,
  151828. int block){
  151829. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  151830. vorbis_info_psy *p=ci->psy_param[block];
  151831. highlevel_encode_setup *hi=&ci->hi;
  151832. int is=s;
  151833. if(block>=ci->psys)
  151834. ci->psys=block+1;
  151835. if(!p){
  151836. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  151837. ci->psy_param[block]=p;
  151838. }
  151839. memcpy(p,&_psy_info_template,sizeof(*p));
  151840. p->blockflag=block>>1;
  151841. if(hi->noise_normalize_p){
  151842. p->normal_channel_p=1;
  151843. p->normal_point_p=1;
  151844. p->normal_start=nn_start[is];
  151845. p->normal_partition=nn_partition[is];
  151846. p->normal_thresh=nn_thresh[is];
  151847. }
  151848. return;
  151849. }
  151850. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  151851. att3 *att,
  151852. int *max,
  151853. vp_adjblock *in){
  151854. int i,is=s;
  151855. double ds=s-is;
  151856. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  151857. vorbis_info_psy *p=ci->psy_param[block];
  151858. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  151859. filling the values in here */
  151860. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  151861. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  151862. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  151863. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  151864. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  151865. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  151866. for(i=0;i<P_BANDS;i++)
  151867. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  151868. return;
  151869. }
  151870. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  151871. compandblock *in, double *x){
  151872. int i,is=s;
  151873. double ds=s-is;
  151874. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151875. vorbis_info_psy *p=ci->psy_param[block];
  151876. ds=x[is]*(1.-ds)+x[is+1]*ds;
  151877. is=(int)ds;
  151878. ds-=is;
  151879. if(ds==0 && is>0){
  151880. is--;
  151881. ds=1.;
  151882. }
  151883. /* interpolate the compander settings */
  151884. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  151885. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  151886. return;
  151887. }
  151888. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  151889. int *suppress){
  151890. int is=s;
  151891. double ds=s-is;
  151892. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151893. vorbis_info_psy *p=ci->psy_param[block];
  151894. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  151895. return;
  151896. }
  151897. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  151898. int *suppress,
  151899. noise3 *in,
  151900. noiseguard *guard,
  151901. double userbias){
  151902. int i,is=s,j;
  151903. double ds=s-is;
  151904. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151905. vorbis_info_psy *p=ci->psy_param[block];
  151906. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  151907. p->noisewindowlomin=guard[block].lo;
  151908. p->noisewindowhimin=guard[block].hi;
  151909. p->noisewindowfixed=guard[block].fixed;
  151910. for(j=0;j<P_NOISECURVES;j++)
  151911. for(i=0;i<P_BANDS;i++)
  151912. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  151913. /* impulse blocks may take a user specified bias to boost the
  151914. nominal/high noise encoding depth */
  151915. for(j=0;j<P_NOISECURVES;j++){
  151916. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  151917. for(i=0;i<P_BANDS;i++){
  151918. p->noiseoff[j][i]+=userbias;
  151919. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  151920. }
  151921. }
  151922. return;
  151923. }
  151924. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  151925. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151926. vorbis_info_psy *p=ci->psy_param[block];
  151927. p->ath_adjatt=ci->hi.ath_floating_dB;
  151928. p->ath_maxatt=ci->hi.ath_absolute_dB;
  151929. return;
  151930. }
  151931. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  151932. int i;
  151933. for(i=0;i<ci->books;i++)
  151934. if(ci->book_param[i]==book)return(i);
  151935. return(ci->books++);
  151936. }
  151937. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  151938. int *shortb,int *longb){
  151939. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151940. int is=s;
  151941. int blockshort=shortb[is];
  151942. int blocklong=longb[is];
  151943. ci->blocksizes[0]=blockshort;
  151944. ci->blocksizes[1]=blocklong;
  151945. }
  151946. static void vorbis_encode_residue_setup(vorbis_info *vi,
  151947. int number, int block,
  151948. vorbis_residue_template *res){
  151949. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151950. int i,n;
  151951. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  151952. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  151953. memcpy(r,res->res,sizeof(*r));
  151954. if(ci->residues<=number)ci->residues=number+1;
  151955. switch(ci->blocksizes[block]){
  151956. case 64:case 128:case 256:
  151957. r->grouping=16;
  151958. break;
  151959. default:
  151960. r->grouping=32;
  151961. break;
  151962. }
  151963. ci->residue_type[number]=res->res_type;
  151964. /* to be adjusted by lowpass/pointlimit later */
  151965. n=r->end=ci->blocksizes[block]>>1;
  151966. if(res->res_type==2)
  151967. n=r->end*=vi->channels;
  151968. /* fill in all the books */
  151969. {
  151970. int booklist=0,k;
  151971. if(ci->hi.managed){
  151972. for(i=0;i<r->partitions;i++)
  151973. for(k=0;k<3;k++)
  151974. if(res->books_base_managed->books[i][k])
  151975. r->secondstages[i]|=(1<<k);
  151976. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  151977. ci->book_param[r->groupbook]=res->book_aux_managed;
  151978. for(i=0;i<r->partitions;i++){
  151979. for(k=0;k<3;k++){
  151980. if(res->books_base_managed->books[i][k]){
  151981. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  151982. r->booklist[booklist++]=bookid;
  151983. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  151984. }
  151985. }
  151986. }
  151987. }else{
  151988. for(i=0;i<r->partitions;i++)
  151989. for(k=0;k<3;k++)
  151990. if(res->books_base->books[i][k])
  151991. r->secondstages[i]|=(1<<k);
  151992. r->groupbook=book_dup_or_new(ci,res->book_aux);
  151993. ci->book_param[r->groupbook]=res->book_aux;
  151994. for(i=0;i<r->partitions;i++){
  151995. for(k=0;k<3;k++){
  151996. if(res->books_base->books[i][k]){
  151997. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  151998. r->booklist[booklist++]=bookid;
  151999. ci->book_param[bookid]=res->books_base->books[i][k];
  152000. }
  152001. }
  152002. }
  152003. }
  152004. }
  152005. /* lowpass setup/pointlimit */
  152006. {
  152007. double freq=ci->hi.lowpass_kHz*1000.;
  152008. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  152009. double nyq=vi->rate/2.;
  152010. long blocksize=ci->blocksizes[block]>>1;
  152011. /* lowpass needs to be set in the floor and the residue. */
  152012. if(freq>nyq)freq=nyq;
  152013. /* in the floor, the granularity can be very fine; it doesn't alter
  152014. the encoding structure, only the samples used to fit the floor
  152015. approximation */
  152016. f->n=freq/nyq*blocksize;
  152017. /* this res may by limited by the maximum pointlimit of the mode,
  152018. not the lowpass. the floor is always lowpass limited. */
  152019. if(res->limit_type){
  152020. if(ci->hi.managed)
  152021. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  152022. else
  152023. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  152024. if(freq>nyq)freq=nyq;
  152025. }
  152026. /* in the residue, we're constrained, physically, by partition
  152027. boundaries. We still lowpass 'wherever', but we have to round up
  152028. here to next boundary, or the vorbis spec will round it *down* to
  152029. previous boundary in encode/decode */
  152030. if(ci->residue_type[block]==2)
  152031. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  152032. r->grouping;
  152033. else
  152034. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  152035. r->grouping;
  152036. }
  152037. }
  152038. /* we assume two maps in this encoder */
  152039. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  152040. vorbis_mapping_template *maps){
  152041. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  152042. int i,j,is=s,modes=2;
  152043. vorbis_info_mapping0 *map=maps[is].map;
  152044. vorbis_info_mode *mode=_mode_template;
  152045. vorbis_residue_template *res=maps[is].res;
  152046. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  152047. for(i=0;i<modes;i++){
  152048. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  152049. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  152050. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  152051. if(i>=ci->modes)ci->modes=i+1;
  152052. ci->map_type[i]=0;
  152053. memcpy(ci->map_param[i],map+i,sizeof(*map));
  152054. if(i>=ci->maps)ci->maps=i+1;
  152055. for(j=0;j<map[i].submaps;j++)
  152056. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  152057. ,res+map[i].residuesubmap[j]);
  152058. }
  152059. }
  152060. static double setting_to_approx_bitrate(vorbis_info *vi){
  152061. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  152062. highlevel_encode_setup *hi=&ci->hi;
  152063. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  152064. int is=hi->base_setting;
  152065. double ds=hi->base_setting-is;
  152066. int ch=vi->channels;
  152067. double *r=setup->rate_mapping;
  152068. if(r==NULL)
  152069. return(-1);
  152070. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  152071. }
  152072. static void get_setup_template(vorbis_info *vi,
  152073. long ch,long srate,
  152074. double req,int q_or_bitrate){
  152075. int i=0,j;
  152076. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  152077. highlevel_encode_setup *hi=&ci->hi;
  152078. if(q_or_bitrate)req/=ch;
  152079. while(setup_list[i]){
  152080. if(setup_list[i]->coupling_restriction==-1 ||
  152081. setup_list[i]->coupling_restriction==ch){
  152082. if(srate>=setup_list[i]->samplerate_min_restriction &&
  152083. srate<=setup_list[i]->samplerate_max_restriction){
  152084. int mappings=setup_list[i]->mappings;
  152085. double *map=(q_or_bitrate?
  152086. setup_list[i]->rate_mapping:
  152087. setup_list[i]->quality_mapping);
  152088. /* the template matches. Does the requested quality mode
  152089. fall within this template's modes? */
  152090. if(req<map[0]){++i;continue;}
  152091. if(req>map[setup_list[i]->mappings]){++i;continue;}
  152092. for(j=0;j<mappings;j++)
  152093. if(req>=map[j] && req<map[j+1])break;
  152094. /* an all-points match */
  152095. hi->setup=setup_list[i];
  152096. if(j==mappings)
  152097. hi->base_setting=j-.001;
  152098. else{
  152099. float low=map[j];
  152100. float high=map[j+1];
  152101. float del=(req-low)/(high-low);
  152102. hi->base_setting=j+del;
  152103. }
  152104. return;
  152105. }
  152106. }
  152107. i++;
  152108. }
  152109. hi->setup=NULL;
  152110. }
  152111. /* encoders will need to use vorbis_info_init beforehand and call
  152112. vorbis_info clear when all done */
  152113. /* two interfaces; this, more detailed one, and later a convenience
  152114. layer on top */
  152115. /* the final setup call */
  152116. int vorbis_encode_setup_init(vorbis_info *vi){
  152117. int i0=0,singleblock=0;
  152118. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  152119. ve_setup_data_template *setup=NULL;
  152120. highlevel_encode_setup *hi=&ci->hi;
  152121. if(ci==NULL)return(OV_EINVAL);
  152122. if(!hi->impulse_block_p)i0=1;
  152123. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  152124. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  152125. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  152126. /* again, bound this to avoid the app shooting itself int he foot
  152127. too badly */
  152128. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  152129. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  152130. /* get the appropriate setup template; matches the fetch in previous
  152131. stages */
  152132. setup=(ve_setup_data_template *)hi->setup;
  152133. if(setup==NULL)return(OV_EINVAL);
  152134. hi->set_in_stone=1;
  152135. /* choose block sizes from configured sizes as well as paying
  152136. attention to long_block_p and short_block_p. If the configured
  152137. short and long blocks are the same length, we set long_block_p
  152138. and unset short_block_p */
  152139. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  152140. setup->blocksize_short,
  152141. setup->blocksize_long);
  152142. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  152143. /* floor setup; choose proper floor params. Allocated on the floor
  152144. stack in order; if we alloc only long floor, it's 0 */
  152145. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  152146. setup->floor_books,
  152147. setup->floor_params,
  152148. setup->floor_short_mapping);
  152149. if(!singleblock)
  152150. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  152151. setup->floor_books,
  152152. setup->floor_params,
  152153. setup->floor_long_mapping);
  152154. /* setup of [mostly] short block detection and stereo*/
  152155. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  152156. setup->global_params,
  152157. setup->global_mapping);
  152158. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  152159. /* basic psych setup and noise normalization */
  152160. vorbis_encode_psyset_setup(vi,hi->short_setting,
  152161. setup->psy_noise_normal_start[0],
  152162. setup->psy_noise_normal_partition[0],
  152163. setup->psy_noise_normal_thresh,
  152164. 0);
  152165. vorbis_encode_psyset_setup(vi,hi->short_setting,
  152166. setup->psy_noise_normal_start[0],
  152167. setup->psy_noise_normal_partition[0],
  152168. setup->psy_noise_normal_thresh,
  152169. 1);
  152170. if(!singleblock){
  152171. vorbis_encode_psyset_setup(vi,hi->long_setting,
  152172. setup->psy_noise_normal_start[1],
  152173. setup->psy_noise_normal_partition[1],
  152174. setup->psy_noise_normal_thresh,
  152175. 2);
  152176. vorbis_encode_psyset_setup(vi,hi->long_setting,
  152177. setup->psy_noise_normal_start[1],
  152178. setup->psy_noise_normal_partition[1],
  152179. setup->psy_noise_normal_thresh,
  152180. 3);
  152181. }
  152182. /* tone masking setup */
  152183. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  152184. setup->psy_tone_masteratt,
  152185. setup->psy_tone_0dB,
  152186. setup->psy_tone_adj_impulse);
  152187. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  152188. setup->psy_tone_masteratt,
  152189. setup->psy_tone_0dB,
  152190. setup->psy_tone_adj_other);
  152191. if(!singleblock){
  152192. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  152193. setup->psy_tone_masteratt,
  152194. setup->psy_tone_0dB,
  152195. setup->psy_tone_adj_other);
  152196. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  152197. setup->psy_tone_masteratt,
  152198. setup->psy_tone_0dB,
  152199. setup->psy_tone_adj_long);
  152200. }
  152201. /* noise companding setup */
  152202. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  152203. setup->psy_noise_compand,
  152204. setup->psy_noise_compand_short_mapping);
  152205. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  152206. setup->psy_noise_compand,
  152207. setup->psy_noise_compand_short_mapping);
  152208. if(!singleblock){
  152209. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  152210. setup->psy_noise_compand,
  152211. setup->psy_noise_compand_long_mapping);
  152212. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  152213. setup->psy_noise_compand,
  152214. setup->psy_noise_compand_long_mapping);
  152215. }
  152216. /* peak guarding setup */
  152217. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  152218. setup->psy_tone_dBsuppress);
  152219. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  152220. setup->psy_tone_dBsuppress);
  152221. if(!singleblock){
  152222. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  152223. setup->psy_tone_dBsuppress);
  152224. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  152225. setup->psy_tone_dBsuppress);
  152226. }
  152227. /* noise bias setup */
  152228. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  152229. setup->psy_noise_dBsuppress,
  152230. setup->psy_noise_bias_impulse,
  152231. setup->psy_noiseguards,
  152232. (i0==0?hi->impulse_noisetune:0.));
  152233. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  152234. setup->psy_noise_dBsuppress,
  152235. setup->psy_noise_bias_padding,
  152236. setup->psy_noiseguards,0.);
  152237. if(!singleblock){
  152238. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  152239. setup->psy_noise_dBsuppress,
  152240. setup->psy_noise_bias_trans,
  152241. setup->psy_noiseguards,0.);
  152242. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  152243. setup->psy_noise_dBsuppress,
  152244. setup->psy_noise_bias_long,
  152245. setup->psy_noiseguards,0.);
  152246. }
  152247. vorbis_encode_ath_setup(vi,0);
  152248. vorbis_encode_ath_setup(vi,1);
  152249. if(!singleblock){
  152250. vorbis_encode_ath_setup(vi,2);
  152251. vorbis_encode_ath_setup(vi,3);
  152252. }
  152253. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  152254. /* set bitrate readonlies and management */
  152255. if(hi->bitrate_av>0)
  152256. vi->bitrate_nominal=hi->bitrate_av;
  152257. else{
  152258. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  152259. }
  152260. vi->bitrate_lower=hi->bitrate_min;
  152261. vi->bitrate_upper=hi->bitrate_max;
  152262. if(hi->bitrate_av)
  152263. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  152264. else
  152265. vi->bitrate_window=0.;
  152266. if(hi->managed){
  152267. ci->bi.avg_rate=hi->bitrate_av;
  152268. ci->bi.min_rate=hi->bitrate_min;
  152269. ci->bi.max_rate=hi->bitrate_max;
  152270. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  152271. ci->bi.reservoir_bias=
  152272. hi->bitrate_reservoir_bias;
  152273. ci->bi.slew_damp=hi->bitrate_av_damp;
  152274. }
  152275. return(0);
  152276. }
  152277. static int vorbis_encode_setup_setting(vorbis_info *vi,
  152278. long channels,
  152279. long rate){
  152280. int ret=0,i,is;
  152281. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  152282. highlevel_encode_setup *hi=&ci->hi;
  152283. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  152284. double ds;
  152285. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  152286. if(ret)return(ret);
  152287. is=hi->base_setting;
  152288. ds=hi->base_setting-is;
  152289. hi->short_setting=hi->base_setting;
  152290. hi->long_setting=hi->base_setting;
  152291. hi->managed=0;
  152292. hi->impulse_block_p=1;
  152293. hi->noise_normalize_p=1;
  152294. hi->stereo_point_setting=hi->base_setting;
  152295. hi->lowpass_kHz=
  152296. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  152297. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  152298. setup->psy_ath_float[is+1]*ds;
  152299. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  152300. setup->psy_ath_abs[is+1]*ds;
  152301. hi->amplitude_track_dBpersec=-6.;
  152302. hi->trigger_setting=hi->base_setting;
  152303. for(i=0;i<4;i++){
  152304. hi->block[i].tone_mask_setting=hi->base_setting;
  152305. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  152306. hi->block[i].noise_bias_setting=hi->base_setting;
  152307. hi->block[i].noise_compand_setting=hi->base_setting;
  152308. }
  152309. return(ret);
  152310. }
  152311. int vorbis_encode_setup_vbr(vorbis_info *vi,
  152312. long channels,
  152313. long rate,
  152314. float quality){
  152315. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  152316. highlevel_encode_setup *hi=&ci->hi;
  152317. quality+=.0000001;
  152318. if(quality>=1.)quality=.9999;
  152319. get_setup_template(vi,channels,rate,quality,0);
  152320. if(!hi->setup)return OV_EIMPL;
  152321. return vorbis_encode_setup_setting(vi,channels,rate);
  152322. }
  152323. int vorbis_encode_init_vbr(vorbis_info *vi,
  152324. long channels,
  152325. long rate,
  152326. float base_quality /* 0. to 1. */
  152327. ){
  152328. int ret=0;
  152329. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  152330. if(ret){
  152331. vorbis_info_clear(vi);
  152332. return ret;
  152333. }
  152334. ret=vorbis_encode_setup_init(vi);
  152335. if(ret)
  152336. vorbis_info_clear(vi);
  152337. return(ret);
  152338. }
  152339. int vorbis_encode_setup_managed(vorbis_info *vi,
  152340. long channels,
  152341. long rate,
  152342. long max_bitrate,
  152343. long nominal_bitrate,
  152344. long min_bitrate){
  152345. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  152346. highlevel_encode_setup *hi=&ci->hi;
  152347. double tnominal=nominal_bitrate;
  152348. int ret=0;
  152349. if(nominal_bitrate<=0.){
  152350. if(max_bitrate>0.){
  152351. if(min_bitrate>0.)
  152352. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  152353. else
  152354. nominal_bitrate=max_bitrate*.875;
  152355. }else{
  152356. if(min_bitrate>0.){
  152357. nominal_bitrate=min_bitrate;
  152358. }else{
  152359. return(OV_EINVAL);
  152360. }
  152361. }
  152362. }
  152363. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  152364. if(!hi->setup)return OV_EIMPL;
  152365. ret=vorbis_encode_setup_setting(vi,channels,rate);
  152366. if(ret){
  152367. vorbis_info_clear(vi);
  152368. return ret;
  152369. }
  152370. /* initialize management with sane defaults */
  152371. hi->managed=1;
  152372. hi->bitrate_min=min_bitrate;
  152373. hi->bitrate_max=max_bitrate;
  152374. hi->bitrate_av=tnominal;
  152375. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  152376. hi->bitrate_reservoir=nominal_bitrate*2;
  152377. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  152378. return(ret);
  152379. }
  152380. int vorbis_encode_init(vorbis_info *vi,
  152381. long channels,
  152382. long rate,
  152383. long max_bitrate,
  152384. long nominal_bitrate,
  152385. long min_bitrate){
  152386. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  152387. max_bitrate,
  152388. nominal_bitrate,
  152389. min_bitrate);
  152390. if(ret){
  152391. vorbis_info_clear(vi);
  152392. return(ret);
  152393. }
  152394. ret=vorbis_encode_setup_init(vi);
  152395. if(ret)
  152396. vorbis_info_clear(vi);
  152397. return(ret);
  152398. }
  152399. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  152400. if(vi){
  152401. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  152402. highlevel_encode_setup *hi=&ci->hi;
  152403. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  152404. if(setp && hi->set_in_stone)return(OV_EINVAL);
  152405. switch(number){
  152406. /* now deprecated *****************/
  152407. case OV_ECTL_RATEMANAGE_GET:
  152408. {
  152409. struct ovectl_ratemanage_arg *ai=
  152410. (struct ovectl_ratemanage_arg *)arg;
  152411. ai->management_active=hi->managed;
  152412. ai->bitrate_hard_window=ai->bitrate_av_window=
  152413. (double)hi->bitrate_reservoir/vi->rate;
  152414. ai->bitrate_av_window_center=1.;
  152415. ai->bitrate_hard_min=hi->bitrate_min;
  152416. ai->bitrate_hard_max=hi->bitrate_max;
  152417. ai->bitrate_av_lo=hi->bitrate_av;
  152418. ai->bitrate_av_hi=hi->bitrate_av;
  152419. }
  152420. return(0);
  152421. /* now deprecated *****************/
  152422. case OV_ECTL_RATEMANAGE_SET:
  152423. {
  152424. struct ovectl_ratemanage_arg *ai=
  152425. (struct ovectl_ratemanage_arg *)arg;
  152426. if(ai==NULL){
  152427. hi->managed=0;
  152428. }else{
  152429. hi->managed=ai->management_active;
  152430. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  152431. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  152432. }
  152433. }
  152434. return 0;
  152435. /* now deprecated *****************/
  152436. case OV_ECTL_RATEMANAGE_AVG:
  152437. {
  152438. struct ovectl_ratemanage_arg *ai=
  152439. (struct ovectl_ratemanage_arg *)arg;
  152440. if(ai==NULL){
  152441. hi->bitrate_av=0;
  152442. }else{
  152443. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  152444. }
  152445. }
  152446. return(0);
  152447. /* now deprecated *****************/
  152448. case OV_ECTL_RATEMANAGE_HARD:
  152449. {
  152450. struct ovectl_ratemanage_arg *ai=
  152451. (struct ovectl_ratemanage_arg *)arg;
  152452. if(ai==NULL){
  152453. hi->bitrate_min=0;
  152454. hi->bitrate_max=0;
  152455. }else{
  152456. hi->bitrate_min=ai->bitrate_hard_min;
  152457. hi->bitrate_max=ai->bitrate_hard_max;
  152458. hi->bitrate_reservoir=ai->bitrate_hard_window*
  152459. (hi->bitrate_max+hi->bitrate_min)*.5;
  152460. }
  152461. if(hi->bitrate_reservoir<128.)
  152462. hi->bitrate_reservoir=128.;
  152463. }
  152464. return(0);
  152465. /* replacement ratemanage interface */
  152466. case OV_ECTL_RATEMANAGE2_GET:
  152467. {
  152468. struct ovectl_ratemanage2_arg *ai=
  152469. (struct ovectl_ratemanage2_arg *)arg;
  152470. if(ai==NULL)return OV_EINVAL;
  152471. ai->management_active=hi->managed;
  152472. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  152473. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  152474. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  152475. ai->bitrate_average_damping=hi->bitrate_av_damp;
  152476. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  152477. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  152478. }
  152479. return (0);
  152480. case OV_ECTL_RATEMANAGE2_SET:
  152481. {
  152482. struct ovectl_ratemanage2_arg *ai=
  152483. (struct ovectl_ratemanage2_arg *)arg;
  152484. if(ai==NULL){
  152485. hi->managed=0;
  152486. }else{
  152487. /* sanity check; only catch invariant violations */
  152488. if(ai->bitrate_limit_min_kbps>0 &&
  152489. ai->bitrate_average_kbps>0 &&
  152490. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  152491. return OV_EINVAL;
  152492. if(ai->bitrate_limit_max_kbps>0 &&
  152493. ai->bitrate_average_kbps>0 &&
  152494. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  152495. return OV_EINVAL;
  152496. if(ai->bitrate_limit_min_kbps>0 &&
  152497. ai->bitrate_limit_max_kbps>0 &&
  152498. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  152499. return OV_EINVAL;
  152500. if(ai->bitrate_average_damping <= 0.)
  152501. return OV_EINVAL;
  152502. if(ai->bitrate_limit_reservoir_bits < 0)
  152503. return OV_EINVAL;
  152504. if(ai->bitrate_limit_reservoir_bias < 0.)
  152505. return OV_EINVAL;
  152506. if(ai->bitrate_limit_reservoir_bias > 1.)
  152507. return OV_EINVAL;
  152508. hi->managed=ai->management_active;
  152509. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  152510. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  152511. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  152512. hi->bitrate_av_damp=ai->bitrate_average_damping;
  152513. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  152514. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  152515. }
  152516. }
  152517. return 0;
  152518. case OV_ECTL_LOWPASS_GET:
  152519. {
  152520. double *farg=(double *)arg;
  152521. *farg=hi->lowpass_kHz;
  152522. }
  152523. return(0);
  152524. case OV_ECTL_LOWPASS_SET:
  152525. {
  152526. double *farg=(double *)arg;
  152527. hi->lowpass_kHz=*farg;
  152528. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  152529. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  152530. }
  152531. return(0);
  152532. case OV_ECTL_IBLOCK_GET:
  152533. {
  152534. double *farg=(double *)arg;
  152535. *farg=hi->impulse_noisetune;
  152536. }
  152537. return(0);
  152538. case OV_ECTL_IBLOCK_SET:
  152539. {
  152540. double *farg=(double *)arg;
  152541. hi->impulse_noisetune=*farg;
  152542. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  152543. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  152544. }
  152545. return(0);
  152546. }
  152547. return(OV_EIMPL);
  152548. }
  152549. return(OV_EINVAL);
  152550. }
  152551. #endif
  152552. /*** End of inlined file: vorbisenc.c ***/
  152553. /*** Start of inlined file: vorbisfile.c ***/
  152554. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  152555. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  152556. // tasks..
  152557. #if JUCE_MSVC
  152558. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  152559. #endif
  152560. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  152561. #if JUCE_USE_OGGVORBIS
  152562. #include <stdlib.h>
  152563. #include <stdio.h>
  152564. #include <errno.h>
  152565. #include <string.h>
  152566. #include <math.h>
  152567. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  152568. one logical bitstream arranged end to end (the only form of Ogg
  152569. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  152570. multiplexing] is not allowed in Vorbis) */
  152571. /* A Vorbis file can be played beginning to end (streamed) without
  152572. worrying ahead of time about chaining (see decoder_example.c). If
  152573. we have the whole file, however, and want random access
  152574. (seeking/scrubbing) or desire to know the total length/time of a
  152575. file, we need to account for the possibility of chaining. */
  152576. /* We can handle things a number of ways; we can determine the entire
  152577. bitstream structure right off the bat, or find pieces on demand.
  152578. This example determines and caches structure for the entire
  152579. bitstream, but builds a virtual decoder on the fly when moving
  152580. between links in the chain. */
  152581. /* There are also different ways to implement seeking. Enough
  152582. information exists in an Ogg bitstream to seek to
  152583. sample-granularity positions in the output. Or, one can seek by
  152584. picking some portion of the stream roughly in the desired area if
  152585. we only want coarse navigation through the stream. */
  152586. /*************************************************************************
  152587. * Many, many internal helpers. The intention is not to be confusing;
  152588. * rampant duplication and monolithic function implementation would be
  152589. * harder to understand anyway. The high level functions are last. Begin
  152590. * grokking near the end of the file */
  152591. /* read a little more data from the file/pipe into the ogg_sync framer
  152592. */
  152593. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  152594. over 8k gets what they deserve */
  152595. static long _get_data(OggVorbis_File *vf){
  152596. errno=0;
  152597. if(vf->datasource){
  152598. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  152599. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  152600. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  152601. if(bytes==0 && errno)return(-1);
  152602. return(bytes);
  152603. }else
  152604. return(0);
  152605. }
  152606. /* save a tiny smidge of verbosity to make the code more readable */
  152607. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  152608. if(vf->datasource){
  152609. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  152610. vf->offset=offset;
  152611. ogg_sync_reset(&vf->oy);
  152612. }else{
  152613. /* shouldn't happen unless someone writes a broken callback */
  152614. return;
  152615. }
  152616. }
  152617. /* The read/seek functions track absolute position within the stream */
  152618. /* from the head of the stream, get the next page. boundary specifies
  152619. if the function is allowed to fetch more data from the stream (and
  152620. how much) or only use internally buffered data.
  152621. boundary: -1) unbounded search
  152622. 0) read no additional data; use cached only
  152623. n) search for a new page beginning for n bytes
  152624. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  152625. n) found a page at absolute offset n */
  152626. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  152627. ogg_int64_t boundary){
  152628. if(boundary>0)boundary+=vf->offset;
  152629. while(1){
  152630. long more;
  152631. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  152632. more=ogg_sync_pageseek(&vf->oy,og);
  152633. if(more<0){
  152634. /* skipped n bytes */
  152635. vf->offset-=more;
  152636. }else{
  152637. if(more==0){
  152638. /* send more paramedics */
  152639. if(!boundary)return(OV_FALSE);
  152640. {
  152641. long ret=_get_data(vf);
  152642. if(ret==0)return(OV_EOF);
  152643. if(ret<0)return(OV_EREAD);
  152644. }
  152645. }else{
  152646. /* got a page. Return the offset at the page beginning,
  152647. advance the internal offset past the page end */
  152648. ogg_int64_t ret=vf->offset;
  152649. vf->offset+=more;
  152650. return(ret);
  152651. }
  152652. }
  152653. }
  152654. }
  152655. /* find the latest page beginning before the current stream cursor
  152656. position. Much dirtier than the above as Ogg doesn't have any
  152657. backward search linkage. no 'readp' as it will certainly have to
  152658. read. */
  152659. /* returns offset or OV_EREAD, OV_FAULT */
  152660. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  152661. ogg_int64_t begin=vf->offset;
  152662. ogg_int64_t end=begin;
  152663. ogg_int64_t ret;
  152664. ogg_int64_t offset=-1;
  152665. while(offset==-1){
  152666. begin-=CHUNKSIZE;
  152667. if(begin<0)
  152668. begin=0;
  152669. _seek_helper(vf,begin);
  152670. while(vf->offset<end){
  152671. ret=_get_next_page(vf,og,end-vf->offset);
  152672. if(ret==OV_EREAD)return(OV_EREAD);
  152673. if(ret<0){
  152674. break;
  152675. }else{
  152676. offset=ret;
  152677. }
  152678. }
  152679. }
  152680. /* we have the offset. Actually snork and hold the page now */
  152681. _seek_helper(vf,offset);
  152682. ret=_get_next_page(vf,og,CHUNKSIZE);
  152683. if(ret<0)
  152684. /* this shouldn't be possible */
  152685. return(OV_EFAULT);
  152686. return(offset);
  152687. }
  152688. /* finds each bitstream link one at a time using a bisection search
  152689. (has to begin by knowing the offset of the lb's initial page).
  152690. Recurses for each link so it can alloc the link storage after
  152691. finding them all, then unroll and fill the cache at the same time */
  152692. static int _bisect_forward_serialno(OggVorbis_File *vf,
  152693. ogg_int64_t begin,
  152694. ogg_int64_t searched,
  152695. ogg_int64_t end,
  152696. long currentno,
  152697. long m){
  152698. ogg_int64_t endsearched=end;
  152699. ogg_int64_t next=end;
  152700. ogg_page og;
  152701. ogg_int64_t ret;
  152702. /* the below guards against garbage seperating the last and
  152703. first pages of two links. */
  152704. while(searched<endsearched){
  152705. ogg_int64_t bisect;
  152706. if(endsearched-searched<CHUNKSIZE){
  152707. bisect=searched;
  152708. }else{
  152709. bisect=(searched+endsearched)/2;
  152710. }
  152711. _seek_helper(vf,bisect);
  152712. ret=_get_next_page(vf,&og,-1);
  152713. if(ret==OV_EREAD)return(OV_EREAD);
  152714. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  152715. endsearched=bisect;
  152716. if(ret>=0)next=ret;
  152717. }else{
  152718. searched=ret+og.header_len+og.body_len;
  152719. }
  152720. }
  152721. _seek_helper(vf,next);
  152722. ret=_get_next_page(vf,&og,-1);
  152723. if(ret==OV_EREAD)return(OV_EREAD);
  152724. if(searched>=end || ret<0){
  152725. vf->links=m+1;
  152726. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  152727. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  152728. vf->offsets[m+1]=searched;
  152729. }else{
  152730. ret=_bisect_forward_serialno(vf,next,vf->offset,
  152731. end,ogg_page_serialno(&og),m+1);
  152732. if(ret==OV_EREAD)return(OV_EREAD);
  152733. }
  152734. vf->offsets[m]=begin;
  152735. vf->serialnos[m]=currentno;
  152736. return(0);
  152737. }
  152738. /* uses the local ogg_stream storage in vf; this is important for
  152739. non-streaming input sources */
  152740. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  152741. long *serialno,ogg_page *og_ptr){
  152742. ogg_page og;
  152743. ogg_packet op;
  152744. int i,ret;
  152745. if(!og_ptr){
  152746. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  152747. if(llret==OV_EREAD)return(OV_EREAD);
  152748. if(llret<0)return OV_ENOTVORBIS;
  152749. og_ptr=&og;
  152750. }
  152751. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  152752. if(serialno)*serialno=vf->os.serialno;
  152753. vf->ready_state=STREAMSET;
  152754. /* extract the initial header from the first page and verify that the
  152755. Ogg bitstream is in fact Vorbis data */
  152756. vorbis_info_init(vi);
  152757. vorbis_comment_init(vc);
  152758. i=0;
  152759. while(i<3){
  152760. ogg_stream_pagein(&vf->os,og_ptr);
  152761. while(i<3){
  152762. int result=ogg_stream_packetout(&vf->os,&op);
  152763. if(result==0)break;
  152764. if(result==-1){
  152765. ret=OV_EBADHEADER;
  152766. goto bail_header;
  152767. }
  152768. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  152769. goto bail_header;
  152770. }
  152771. i++;
  152772. }
  152773. if(i<3)
  152774. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  152775. ret=OV_EBADHEADER;
  152776. goto bail_header;
  152777. }
  152778. }
  152779. return 0;
  152780. bail_header:
  152781. vorbis_info_clear(vi);
  152782. vorbis_comment_clear(vc);
  152783. vf->ready_state=OPENED;
  152784. return ret;
  152785. }
  152786. /* last step of the OggVorbis_File initialization; get all the
  152787. vorbis_info structs and PCM positions. Only called by the seekable
  152788. initialization (local stream storage is hacked slightly; pay
  152789. attention to how that's done) */
  152790. /* this is void and does not propogate errors up because we want to be
  152791. able to open and use damaged bitstreams as well as we can. Just
  152792. watch out for missing information for links in the OggVorbis_File
  152793. struct */
  152794. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  152795. ogg_page og;
  152796. int i;
  152797. ogg_int64_t ret;
  152798. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  152799. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  152800. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  152801. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  152802. for(i=0;i<vf->links;i++){
  152803. if(i==0){
  152804. /* we already grabbed the initial header earlier. Just set the offset */
  152805. vf->dataoffsets[i]=dataoffset;
  152806. _seek_helper(vf,dataoffset);
  152807. }else{
  152808. /* seek to the location of the initial header */
  152809. _seek_helper(vf,vf->offsets[i]);
  152810. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  152811. vf->dataoffsets[i]=-1;
  152812. }else{
  152813. vf->dataoffsets[i]=vf->offset;
  152814. }
  152815. }
  152816. /* fetch beginning PCM offset */
  152817. if(vf->dataoffsets[i]!=-1){
  152818. ogg_int64_t accumulated=0;
  152819. long lastblock=-1;
  152820. int result;
  152821. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  152822. while(1){
  152823. ogg_packet op;
  152824. ret=_get_next_page(vf,&og,-1);
  152825. if(ret<0)
  152826. /* this should not be possible unless the file is
  152827. truncated/mangled */
  152828. break;
  152829. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  152830. break;
  152831. /* count blocksizes of all frames in the page */
  152832. ogg_stream_pagein(&vf->os,&og);
  152833. while((result=ogg_stream_packetout(&vf->os,&op))){
  152834. if(result>0){ /* ignore holes */
  152835. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  152836. if(lastblock!=-1)
  152837. accumulated+=(lastblock+thisblock)>>2;
  152838. lastblock=thisblock;
  152839. }
  152840. }
  152841. if(ogg_page_granulepos(&og)!=-1){
  152842. /* pcm offset of last packet on the first audio page */
  152843. accumulated= ogg_page_granulepos(&og)-accumulated;
  152844. break;
  152845. }
  152846. }
  152847. /* less than zero? This is a stream with samples trimmed off
  152848. the beginning, a normal occurrence; set the offset to zero */
  152849. if(accumulated<0)accumulated=0;
  152850. vf->pcmlengths[i*2]=accumulated;
  152851. }
  152852. /* get the PCM length of this link. To do this,
  152853. get the last page of the stream */
  152854. {
  152855. ogg_int64_t end=vf->offsets[i+1];
  152856. _seek_helper(vf,end);
  152857. while(1){
  152858. ret=_get_prev_page(vf,&og);
  152859. if(ret<0){
  152860. /* this should not be possible */
  152861. vorbis_info_clear(vf->vi+i);
  152862. vorbis_comment_clear(vf->vc+i);
  152863. break;
  152864. }
  152865. if(ogg_page_granulepos(&og)!=-1){
  152866. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  152867. break;
  152868. }
  152869. vf->offset=ret;
  152870. }
  152871. }
  152872. }
  152873. }
  152874. static int _make_decode_ready(OggVorbis_File *vf){
  152875. if(vf->ready_state>STREAMSET)return 0;
  152876. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  152877. if(vf->seekable){
  152878. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  152879. return OV_EBADLINK;
  152880. }else{
  152881. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  152882. return OV_EBADLINK;
  152883. }
  152884. vorbis_block_init(&vf->vd,&vf->vb);
  152885. vf->ready_state=INITSET;
  152886. vf->bittrack=0.f;
  152887. vf->samptrack=0.f;
  152888. return 0;
  152889. }
  152890. static int _open_seekable2(OggVorbis_File *vf){
  152891. long serialno=vf->current_serialno;
  152892. ogg_int64_t dataoffset=vf->offset, end;
  152893. ogg_page og;
  152894. /* we're partially open and have a first link header state in
  152895. storage in vf */
  152896. /* we can seek, so set out learning all about this file */
  152897. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  152898. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  152899. /* We get the offset for the last page of the physical bitstream.
  152900. Most OggVorbis files will contain a single logical bitstream */
  152901. end=_get_prev_page(vf,&og);
  152902. if(end<0)return(end);
  152903. /* more than one logical bitstream? */
  152904. if(ogg_page_serialno(&og)!=serialno){
  152905. /* Chained bitstream. Bisect-search each logical bitstream
  152906. section. Do so based on serial number only */
  152907. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  152908. }else{
  152909. /* Only one logical bitstream */
  152910. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  152911. }
  152912. /* the initial header memory is referenced by vf after; don't free it */
  152913. _prefetch_all_headers(vf,dataoffset);
  152914. return(ov_raw_seek(vf,0));
  152915. }
  152916. /* clear out the current logical bitstream decoder */
  152917. static void _decode_clear(OggVorbis_File *vf){
  152918. vorbis_dsp_clear(&vf->vd);
  152919. vorbis_block_clear(&vf->vb);
  152920. vf->ready_state=OPENED;
  152921. }
  152922. /* fetch and process a packet. Handles the case where we're at a
  152923. bitstream boundary and dumps the decoding machine. If the decoding
  152924. machine is unloaded, it loads it. It also keeps pcm_offset up to
  152925. date (seek and read both use this. seek uses a special hack with
  152926. readp).
  152927. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  152928. 0) need more data (only if readp==0)
  152929. 1) got a packet
  152930. */
  152931. static int _fetch_and_process_packet(OggVorbis_File *vf,
  152932. ogg_packet *op_in,
  152933. int readp,
  152934. int spanp){
  152935. ogg_page og;
  152936. /* handle one packet. Try to fetch it from current stream state */
  152937. /* extract packets from page */
  152938. while(1){
  152939. /* process a packet if we can. If the machine isn't loaded,
  152940. neither is a page */
  152941. if(vf->ready_state==INITSET){
  152942. while(1) {
  152943. ogg_packet op;
  152944. ogg_packet *op_ptr=(op_in?op_in:&op);
  152945. int result=ogg_stream_packetout(&vf->os,op_ptr);
  152946. ogg_int64_t granulepos;
  152947. op_in=NULL;
  152948. if(result==-1)return(OV_HOLE); /* hole in the data. */
  152949. if(result>0){
  152950. /* got a packet. process it */
  152951. granulepos=op_ptr->granulepos;
  152952. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  152953. header handling. The
  152954. header packets aren't
  152955. audio, so if/when we
  152956. submit them,
  152957. vorbis_synthesis will
  152958. reject them */
  152959. /* suck in the synthesis data and track bitrate */
  152960. {
  152961. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  152962. /* for proper use of libvorbis within libvorbisfile,
  152963. oldsamples will always be zero. */
  152964. if(oldsamples)return(OV_EFAULT);
  152965. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  152966. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  152967. vf->bittrack+=op_ptr->bytes*8;
  152968. }
  152969. /* update the pcm offset. */
  152970. if(granulepos!=-1 && !op_ptr->e_o_s){
  152971. int link=(vf->seekable?vf->current_link:0);
  152972. int i,samples;
  152973. /* this packet has a pcm_offset on it (the last packet
  152974. completed on a page carries the offset) After processing
  152975. (above), we know the pcm position of the *last* sample
  152976. ready to be returned. Find the offset of the *first*
  152977. As an aside, this trick is inaccurate if we begin
  152978. reading anew right at the last page; the end-of-stream
  152979. granulepos declares the last frame in the stream, and the
  152980. last packet of the last page may be a partial frame.
  152981. So, we need a previous granulepos from an in-sequence page
  152982. to have a reference point. Thus the !op_ptr->e_o_s clause
  152983. above */
  152984. if(vf->seekable && link>0)
  152985. granulepos-=vf->pcmlengths[link*2];
  152986. if(granulepos<0)granulepos=0; /* actually, this
  152987. shouldn't be possible
  152988. here unless the stream
  152989. is very broken */
  152990. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  152991. granulepos-=samples;
  152992. for(i=0;i<link;i++)
  152993. granulepos+=vf->pcmlengths[i*2+1];
  152994. vf->pcm_offset=granulepos;
  152995. }
  152996. return(1);
  152997. }
  152998. }
  152999. else
  153000. break;
  153001. }
  153002. }
  153003. if(vf->ready_state>=OPENED){
  153004. ogg_int64_t ret;
  153005. if(!readp)return(0);
  153006. if((ret=_get_next_page(vf,&og,-1))<0){
  153007. return(OV_EOF); /* eof.
  153008. leave unitialized */
  153009. }
  153010. /* bitrate tracking; add the header's bytes here, the body bytes
  153011. are done by packet above */
  153012. vf->bittrack+=og.header_len*8;
  153013. /* has our decoding just traversed a bitstream boundary? */
  153014. if(vf->ready_state==INITSET){
  153015. if(vf->current_serialno!=ogg_page_serialno(&og)){
  153016. if(!spanp)
  153017. return(OV_EOF);
  153018. _decode_clear(vf);
  153019. if(!vf->seekable){
  153020. vorbis_info_clear(vf->vi);
  153021. vorbis_comment_clear(vf->vc);
  153022. }
  153023. }
  153024. }
  153025. }
  153026. /* Do we need to load a new machine before submitting the page? */
  153027. /* This is different in the seekable and non-seekable cases.
  153028. In the seekable case, we already have all the header
  153029. information loaded and cached; we just initialize the machine
  153030. with it and continue on our merry way.
  153031. In the non-seekable (streaming) case, we'll only be at a
  153032. boundary if we just left the previous logical bitstream and
  153033. we're now nominally at the header of the next bitstream
  153034. */
  153035. if(vf->ready_state!=INITSET){
  153036. int link;
  153037. if(vf->ready_state<STREAMSET){
  153038. if(vf->seekable){
  153039. vf->current_serialno=ogg_page_serialno(&og);
  153040. /* match the serialno to bitstream section. We use this rather than
  153041. offset positions to avoid problems near logical bitstream
  153042. boundaries */
  153043. for(link=0;link<vf->links;link++)
  153044. if(vf->serialnos[link]==vf->current_serialno)break;
  153045. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  153046. stream. error out,
  153047. leave machine
  153048. uninitialized */
  153049. vf->current_link=link;
  153050. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  153051. vf->ready_state=STREAMSET;
  153052. }else{
  153053. /* we're streaming */
  153054. /* fetch the three header packets, build the info struct */
  153055. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  153056. if(ret)return(ret);
  153057. vf->current_link++;
  153058. link=0;
  153059. }
  153060. }
  153061. {
  153062. int ret=_make_decode_ready(vf);
  153063. if(ret<0)return ret;
  153064. }
  153065. }
  153066. ogg_stream_pagein(&vf->os,&og);
  153067. }
  153068. }
  153069. /* if, eg, 64 bit stdio is configured by default, this will build with
  153070. fseek64 */
  153071. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  153072. if(f==NULL)return(-1);
  153073. return fseek(f,off,whence);
  153074. }
  153075. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  153076. long ibytes, ov_callbacks callbacks){
  153077. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  153078. int ret;
  153079. memset(vf,0,sizeof(*vf));
  153080. vf->datasource=f;
  153081. vf->callbacks = callbacks;
  153082. /* init the framing state */
  153083. ogg_sync_init(&vf->oy);
  153084. /* perhaps some data was previously read into a buffer for testing
  153085. against other stream types. Allow initialization from this
  153086. previously read data (as we may be reading from a non-seekable
  153087. stream) */
  153088. if(initial){
  153089. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  153090. memcpy(buffer,initial,ibytes);
  153091. ogg_sync_wrote(&vf->oy,ibytes);
  153092. }
  153093. /* can we seek? Stevens suggests the seek test was portable */
  153094. if(offsettest!=-1)vf->seekable=1;
  153095. /* No seeking yet; Set up a 'single' (current) logical bitstream
  153096. entry for partial open */
  153097. vf->links=1;
  153098. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  153099. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  153100. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  153101. /* Try to fetch the headers, maintaining all the storage */
  153102. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  153103. vf->datasource=NULL;
  153104. ov_clear(vf);
  153105. }else
  153106. vf->ready_state=PARTOPEN;
  153107. return(ret);
  153108. }
  153109. static int _ov_open2(OggVorbis_File *vf){
  153110. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  153111. vf->ready_state=OPENED;
  153112. if(vf->seekable){
  153113. int ret=_open_seekable2(vf);
  153114. if(ret){
  153115. vf->datasource=NULL;
  153116. ov_clear(vf);
  153117. }
  153118. return(ret);
  153119. }else
  153120. vf->ready_state=STREAMSET;
  153121. return 0;
  153122. }
  153123. /* clear out the OggVorbis_File struct */
  153124. int ov_clear(OggVorbis_File *vf){
  153125. if(vf){
  153126. vorbis_block_clear(&vf->vb);
  153127. vorbis_dsp_clear(&vf->vd);
  153128. ogg_stream_clear(&vf->os);
  153129. if(vf->vi && vf->links){
  153130. int i;
  153131. for(i=0;i<vf->links;i++){
  153132. vorbis_info_clear(vf->vi+i);
  153133. vorbis_comment_clear(vf->vc+i);
  153134. }
  153135. _ogg_free(vf->vi);
  153136. _ogg_free(vf->vc);
  153137. }
  153138. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  153139. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  153140. if(vf->serialnos)_ogg_free(vf->serialnos);
  153141. if(vf->offsets)_ogg_free(vf->offsets);
  153142. ogg_sync_clear(&vf->oy);
  153143. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  153144. memset(vf,0,sizeof(*vf));
  153145. }
  153146. #ifdef DEBUG_LEAKS
  153147. _VDBG_dump();
  153148. #endif
  153149. return(0);
  153150. }
  153151. /* inspects the OggVorbis file and finds/documents all the logical
  153152. bitstreams contained in it. Tries to be tolerant of logical
  153153. bitstream sections that are truncated/woogie.
  153154. return: -1) error
  153155. 0) OK
  153156. */
  153157. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  153158. ov_callbacks callbacks){
  153159. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  153160. if(ret)return ret;
  153161. return _ov_open2(vf);
  153162. }
  153163. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  153164. ov_callbacks callbacks = {
  153165. (size_t (*)(void *, size_t, size_t, void *)) fread,
  153166. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  153167. (int (*)(void *)) fclose,
  153168. (long (*)(void *)) ftell
  153169. };
  153170. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  153171. }
  153172. /* cheap hack for game usage where downsampling is desirable; there's
  153173. no need for SRC as we can just do it cheaply in libvorbis. */
  153174. int ov_halfrate(OggVorbis_File *vf,int flag){
  153175. int i;
  153176. if(vf->vi==NULL)return OV_EINVAL;
  153177. if(!vf->seekable)return OV_EINVAL;
  153178. if(vf->ready_state>=STREAMSET)
  153179. _decode_clear(vf); /* clear out stream state; later on libvorbis
  153180. will be able to swap this on the fly, but
  153181. for now dumping the decode machine is needed
  153182. to reinit the MDCT lookups. 1.1 libvorbis
  153183. is planned to be able to switch on the fly */
  153184. for(i=0;i<vf->links;i++){
  153185. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  153186. ov_halfrate(vf,0);
  153187. return OV_EINVAL;
  153188. }
  153189. }
  153190. return 0;
  153191. }
  153192. int ov_halfrate_p(OggVorbis_File *vf){
  153193. if(vf->vi==NULL)return OV_EINVAL;
  153194. return vorbis_synthesis_halfrate_p(vf->vi);
  153195. }
  153196. /* Only partially open the vorbis file; test for Vorbisness, and load
  153197. the headers for the first chain. Do not seek (although test for
  153198. seekability). Use ov_test_open to finish opening the file, else
  153199. ov_clear to close/free it. Same return codes as open. */
  153200. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  153201. ov_callbacks callbacks)
  153202. {
  153203. return _ov_open1(f,vf,initial,ibytes,callbacks);
  153204. }
  153205. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  153206. ov_callbacks callbacks = {
  153207. (size_t (*)(void *, size_t, size_t, void *)) fread,
  153208. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  153209. (int (*)(void *)) fclose,
  153210. (long (*)(void *)) ftell
  153211. };
  153212. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  153213. }
  153214. int ov_test_open(OggVorbis_File *vf){
  153215. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  153216. return _ov_open2(vf);
  153217. }
  153218. /* How many logical bitstreams in this physical bitstream? */
  153219. long ov_streams(OggVorbis_File *vf){
  153220. return vf->links;
  153221. }
  153222. /* Is the FILE * associated with vf seekable? */
  153223. long ov_seekable(OggVorbis_File *vf){
  153224. return vf->seekable;
  153225. }
  153226. /* returns the bitrate for a given logical bitstream or the entire
  153227. physical bitstream. If the file is open for random access, it will
  153228. find the *actual* average bitrate. If the file is streaming, it
  153229. returns the nominal bitrate (if set) else the average of the
  153230. upper/lower bounds (if set) else -1 (unset).
  153231. If you want the actual bitrate field settings, get them from the
  153232. vorbis_info structs */
  153233. long ov_bitrate(OggVorbis_File *vf,int i){
  153234. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153235. if(i>=vf->links)return(OV_EINVAL);
  153236. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  153237. if(i<0){
  153238. ogg_int64_t bits=0;
  153239. int i;
  153240. float br;
  153241. for(i=0;i<vf->links;i++)
  153242. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  153243. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  153244. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  153245. * so this is slightly transformed to make it work.
  153246. */
  153247. br = bits/ov_time_total(vf,-1);
  153248. return(rint(br));
  153249. }else{
  153250. if(vf->seekable){
  153251. /* return the actual bitrate */
  153252. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  153253. }else{
  153254. /* return nominal if set */
  153255. if(vf->vi[i].bitrate_nominal>0){
  153256. return vf->vi[i].bitrate_nominal;
  153257. }else{
  153258. if(vf->vi[i].bitrate_upper>0){
  153259. if(vf->vi[i].bitrate_lower>0){
  153260. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  153261. }else{
  153262. return vf->vi[i].bitrate_upper;
  153263. }
  153264. }
  153265. return(OV_FALSE);
  153266. }
  153267. }
  153268. }
  153269. }
  153270. /* returns the actual bitrate since last call. returns -1 if no
  153271. additional data to offer since last call (or at beginning of stream),
  153272. EINVAL if stream is only partially open
  153273. */
  153274. long ov_bitrate_instant(OggVorbis_File *vf){
  153275. int link=(vf->seekable?vf->current_link:0);
  153276. long ret;
  153277. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153278. if(vf->samptrack==0)return(OV_FALSE);
  153279. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  153280. vf->bittrack=0.f;
  153281. vf->samptrack=0.f;
  153282. return(ret);
  153283. }
  153284. /* Guess */
  153285. long ov_serialnumber(OggVorbis_File *vf,int i){
  153286. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  153287. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  153288. if(i<0){
  153289. return(vf->current_serialno);
  153290. }else{
  153291. return(vf->serialnos[i]);
  153292. }
  153293. }
  153294. /* returns: total raw (compressed) length of content if i==-1
  153295. raw (compressed) length of that logical bitstream for i==0 to n
  153296. OV_EINVAL if the stream is not seekable (we can't know the length)
  153297. or if stream is only partially open
  153298. */
  153299. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  153300. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153301. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  153302. if(i<0){
  153303. ogg_int64_t acc=0;
  153304. int i;
  153305. for(i=0;i<vf->links;i++)
  153306. acc+=ov_raw_total(vf,i);
  153307. return(acc);
  153308. }else{
  153309. return(vf->offsets[i+1]-vf->offsets[i]);
  153310. }
  153311. }
  153312. /* returns: total PCM length (samples) of content if i==-1 PCM length
  153313. (samples) of that logical bitstream for i==0 to n
  153314. OV_EINVAL if the stream is not seekable (we can't know the
  153315. length) or only partially open
  153316. */
  153317. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  153318. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153319. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  153320. if(i<0){
  153321. ogg_int64_t acc=0;
  153322. int i;
  153323. for(i=0;i<vf->links;i++)
  153324. acc+=ov_pcm_total(vf,i);
  153325. return(acc);
  153326. }else{
  153327. return(vf->pcmlengths[i*2+1]);
  153328. }
  153329. }
  153330. /* returns: total seconds of content if i==-1
  153331. seconds in that logical bitstream for i==0 to n
  153332. OV_EINVAL if the stream is not seekable (we can't know the
  153333. length) or only partially open
  153334. */
  153335. double ov_time_total(OggVorbis_File *vf,int i){
  153336. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153337. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  153338. if(i<0){
  153339. double acc=0;
  153340. int i;
  153341. for(i=0;i<vf->links;i++)
  153342. acc+=ov_time_total(vf,i);
  153343. return(acc);
  153344. }else{
  153345. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  153346. }
  153347. }
  153348. /* seek to an offset relative to the *compressed* data. This also
  153349. scans packets to update the PCM cursor. It will cross a logical
  153350. bitstream boundary, but only if it can't get any packets out of the
  153351. tail of the bitstream we seek to (so no surprises).
  153352. returns zero on success, nonzero on failure */
  153353. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  153354. ogg_stream_state work_os;
  153355. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153356. if(!vf->seekable)
  153357. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  153358. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  153359. /* don't yet clear out decoding machine (if it's initialized), in
  153360. the case we're in the same link. Restart the decode lapping, and
  153361. let _fetch_and_process_packet deal with a potential bitstream
  153362. boundary */
  153363. vf->pcm_offset=-1;
  153364. ogg_stream_reset_serialno(&vf->os,
  153365. vf->current_serialno); /* must set serialno */
  153366. vorbis_synthesis_restart(&vf->vd);
  153367. _seek_helper(vf,pos);
  153368. /* we need to make sure the pcm_offset is set, but we don't want to
  153369. advance the raw cursor past good packets just to get to the first
  153370. with a granulepos. That's not equivalent behavior to beginning
  153371. decoding as immediately after the seek position as possible.
  153372. So, a hack. We use two stream states; a local scratch state and
  153373. the shared vf->os stream state. We use the local state to
  153374. scan, and the shared state as a buffer for later decode.
  153375. Unfortuantely, on the last page we still advance to last packet
  153376. because the granulepos on the last page is not necessarily on a
  153377. packet boundary, and we need to make sure the granpos is
  153378. correct.
  153379. */
  153380. {
  153381. ogg_page og;
  153382. ogg_packet op;
  153383. int lastblock=0;
  153384. int accblock=0;
  153385. int thisblock;
  153386. int eosflag;
  153387. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  153388. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  153389. return from not necessarily
  153390. starting from the beginning */
  153391. while(1){
  153392. if(vf->ready_state>=STREAMSET){
  153393. /* snarf/scan a packet if we can */
  153394. int result=ogg_stream_packetout(&work_os,&op);
  153395. if(result>0){
  153396. if(vf->vi[vf->current_link].codec_setup){
  153397. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  153398. if(thisblock<0){
  153399. ogg_stream_packetout(&vf->os,NULL);
  153400. thisblock=0;
  153401. }else{
  153402. if(eosflag)
  153403. ogg_stream_packetout(&vf->os,NULL);
  153404. else
  153405. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  153406. }
  153407. if(op.granulepos!=-1){
  153408. int i,link=vf->current_link;
  153409. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  153410. if(granulepos<0)granulepos=0;
  153411. for(i=0;i<link;i++)
  153412. granulepos+=vf->pcmlengths[i*2+1];
  153413. vf->pcm_offset=granulepos-accblock;
  153414. break;
  153415. }
  153416. lastblock=thisblock;
  153417. continue;
  153418. }else
  153419. ogg_stream_packetout(&vf->os,NULL);
  153420. }
  153421. }
  153422. if(!lastblock){
  153423. if(_get_next_page(vf,&og,-1)<0){
  153424. vf->pcm_offset=ov_pcm_total(vf,-1);
  153425. break;
  153426. }
  153427. }else{
  153428. /* huh? Bogus stream with packets but no granulepos */
  153429. vf->pcm_offset=-1;
  153430. break;
  153431. }
  153432. /* has our decoding just traversed a bitstream boundary? */
  153433. if(vf->ready_state>=STREAMSET)
  153434. if(vf->current_serialno!=ogg_page_serialno(&og)){
  153435. _decode_clear(vf); /* clear out stream state */
  153436. ogg_stream_clear(&work_os);
  153437. }
  153438. if(vf->ready_state<STREAMSET){
  153439. int link;
  153440. vf->current_serialno=ogg_page_serialno(&og);
  153441. for(link=0;link<vf->links;link++)
  153442. if(vf->serialnos[link]==vf->current_serialno)break;
  153443. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  153444. error out, leave
  153445. machine uninitialized */
  153446. vf->current_link=link;
  153447. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  153448. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  153449. vf->ready_state=STREAMSET;
  153450. }
  153451. ogg_stream_pagein(&vf->os,&og);
  153452. ogg_stream_pagein(&work_os,&og);
  153453. eosflag=ogg_page_eos(&og);
  153454. }
  153455. }
  153456. ogg_stream_clear(&work_os);
  153457. vf->bittrack=0.f;
  153458. vf->samptrack=0.f;
  153459. return(0);
  153460. seek_error:
  153461. /* dump the machine so we're in a known state */
  153462. vf->pcm_offset=-1;
  153463. ogg_stream_clear(&work_os);
  153464. _decode_clear(vf);
  153465. return OV_EBADLINK;
  153466. }
  153467. /* Page granularity seek (faster than sample granularity because we
  153468. don't do the last bit of decode to find a specific sample).
  153469. Seek to the last [granule marked] page preceeding the specified pos
  153470. location, such that decoding past the returned point will quickly
  153471. arrive at the requested position. */
  153472. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  153473. int link=-1;
  153474. ogg_int64_t result=0;
  153475. ogg_int64_t total=ov_pcm_total(vf,-1);
  153476. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153477. if(!vf->seekable)return(OV_ENOSEEK);
  153478. if(pos<0 || pos>total)return(OV_EINVAL);
  153479. /* which bitstream section does this pcm offset occur in? */
  153480. for(link=vf->links-1;link>=0;link--){
  153481. total-=vf->pcmlengths[link*2+1];
  153482. if(pos>=total)break;
  153483. }
  153484. /* search within the logical bitstream for the page with the highest
  153485. pcm_pos preceeding (or equal to) pos. There is a danger here;
  153486. missing pages or incorrect frame number information in the
  153487. bitstream could make our task impossible. Account for that (it
  153488. would be an error condition) */
  153489. /* new search algorithm by HB (Nicholas Vinen) */
  153490. {
  153491. ogg_int64_t end=vf->offsets[link+1];
  153492. ogg_int64_t begin=vf->offsets[link];
  153493. ogg_int64_t begintime = vf->pcmlengths[link*2];
  153494. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  153495. ogg_int64_t target=pos-total+begintime;
  153496. ogg_int64_t best=begin;
  153497. ogg_page og;
  153498. while(begin<end){
  153499. ogg_int64_t bisect;
  153500. if(end-begin<CHUNKSIZE){
  153501. bisect=begin;
  153502. }else{
  153503. /* take a (pretty decent) guess. */
  153504. bisect=begin +
  153505. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  153506. if(bisect<=begin)
  153507. bisect=begin+1;
  153508. }
  153509. _seek_helper(vf,bisect);
  153510. while(begin<end){
  153511. result=_get_next_page(vf,&og,end-vf->offset);
  153512. if(result==OV_EREAD) goto seek_error;
  153513. if(result<0){
  153514. if(bisect<=begin+1)
  153515. end=begin; /* found it */
  153516. else{
  153517. if(bisect==0) goto seek_error;
  153518. bisect-=CHUNKSIZE;
  153519. if(bisect<=begin)bisect=begin+1;
  153520. _seek_helper(vf,bisect);
  153521. }
  153522. }else{
  153523. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  153524. if(granulepos==-1)continue;
  153525. if(granulepos<target){
  153526. best=result; /* raw offset of packet with granulepos */
  153527. begin=vf->offset; /* raw offset of next page */
  153528. begintime=granulepos;
  153529. if(target-begintime>44100)break;
  153530. bisect=begin; /* *not* begin + 1 */
  153531. }else{
  153532. if(bisect<=begin+1)
  153533. end=begin; /* found it */
  153534. else{
  153535. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  153536. end=result;
  153537. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  153538. if(bisect<=begin)bisect=begin+1;
  153539. _seek_helper(vf,bisect);
  153540. }else{
  153541. end=result;
  153542. endtime=granulepos;
  153543. break;
  153544. }
  153545. }
  153546. }
  153547. }
  153548. }
  153549. }
  153550. /* found our page. seek to it, update pcm offset. Easier case than
  153551. raw_seek, don't keep packets preceeding granulepos. */
  153552. {
  153553. ogg_page og;
  153554. ogg_packet op;
  153555. /* seek */
  153556. _seek_helper(vf,best);
  153557. vf->pcm_offset=-1;
  153558. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  153559. if(link!=vf->current_link){
  153560. /* Different link; dump entire decode machine */
  153561. _decode_clear(vf);
  153562. vf->current_link=link;
  153563. vf->current_serialno=ogg_page_serialno(&og);
  153564. vf->ready_state=STREAMSET;
  153565. }else{
  153566. vorbis_synthesis_restart(&vf->vd);
  153567. }
  153568. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  153569. ogg_stream_pagein(&vf->os,&og);
  153570. /* pull out all but last packet; the one with granulepos */
  153571. while(1){
  153572. result=ogg_stream_packetpeek(&vf->os,&op);
  153573. if(result==0){
  153574. /* !!! the packet finishing this page originated on a
  153575. preceeding page. Keep fetching previous pages until we
  153576. get one with a granulepos or without the 'continued' flag
  153577. set. Then just use raw_seek for simplicity. */
  153578. _seek_helper(vf,best);
  153579. while(1){
  153580. result=_get_prev_page(vf,&og);
  153581. if(result<0) goto seek_error;
  153582. if(ogg_page_granulepos(&og)>-1 ||
  153583. !ogg_page_continued(&og)){
  153584. return ov_raw_seek(vf,result);
  153585. }
  153586. vf->offset=result;
  153587. }
  153588. }
  153589. if(result<0){
  153590. result = OV_EBADPACKET;
  153591. goto seek_error;
  153592. }
  153593. if(op.granulepos!=-1){
  153594. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  153595. if(vf->pcm_offset<0)vf->pcm_offset=0;
  153596. vf->pcm_offset+=total;
  153597. break;
  153598. }else
  153599. result=ogg_stream_packetout(&vf->os,NULL);
  153600. }
  153601. }
  153602. }
  153603. /* verify result */
  153604. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  153605. result=OV_EFAULT;
  153606. goto seek_error;
  153607. }
  153608. vf->bittrack=0.f;
  153609. vf->samptrack=0.f;
  153610. return(0);
  153611. seek_error:
  153612. /* dump machine so we're in a known state */
  153613. vf->pcm_offset=-1;
  153614. _decode_clear(vf);
  153615. return (int)result;
  153616. }
  153617. /* seek to a sample offset relative to the decompressed pcm stream
  153618. returns zero on success, nonzero on failure */
  153619. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  153620. int thisblock,lastblock=0;
  153621. int ret=ov_pcm_seek_page(vf,pos);
  153622. if(ret<0)return(ret);
  153623. if((ret=_make_decode_ready(vf)))return ret;
  153624. /* discard leading packets we don't need for the lapping of the
  153625. position we want; don't decode them */
  153626. while(1){
  153627. ogg_packet op;
  153628. ogg_page og;
  153629. int ret=ogg_stream_packetpeek(&vf->os,&op);
  153630. if(ret>0){
  153631. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  153632. if(thisblock<0){
  153633. ogg_stream_packetout(&vf->os,NULL);
  153634. continue; /* non audio packet */
  153635. }
  153636. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  153637. if(vf->pcm_offset+((thisblock+
  153638. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  153639. /* remove the packet from packet queue and track its granulepos */
  153640. ogg_stream_packetout(&vf->os,NULL);
  153641. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  153642. only tracking, no
  153643. pcm_decode */
  153644. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  153645. /* end of logical stream case is hard, especially with exact
  153646. length positioning. */
  153647. if(op.granulepos>-1){
  153648. int i;
  153649. /* always believe the stream markers */
  153650. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  153651. if(vf->pcm_offset<0)vf->pcm_offset=0;
  153652. for(i=0;i<vf->current_link;i++)
  153653. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  153654. }
  153655. lastblock=thisblock;
  153656. }else{
  153657. if(ret<0 && ret!=OV_HOLE)break;
  153658. /* suck in a new page */
  153659. if(_get_next_page(vf,&og,-1)<0)break;
  153660. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  153661. if(vf->ready_state<STREAMSET){
  153662. int link;
  153663. vf->current_serialno=ogg_page_serialno(&og);
  153664. for(link=0;link<vf->links;link++)
  153665. if(vf->serialnos[link]==vf->current_serialno)break;
  153666. if(link==vf->links)return(OV_EBADLINK);
  153667. vf->current_link=link;
  153668. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  153669. vf->ready_state=STREAMSET;
  153670. ret=_make_decode_ready(vf);
  153671. if(ret)return ret;
  153672. lastblock=0;
  153673. }
  153674. ogg_stream_pagein(&vf->os,&og);
  153675. }
  153676. }
  153677. vf->bittrack=0.f;
  153678. vf->samptrack=0.f;
  153679. /* discard samples until we reach the desired position. Crossing a
  153680. logical bitstream boundary with abandon is OK. */
  153681. while(vf->pcm_offset<pos){
  153682. ogg_int64_t target=pos-vf->pcm_offset;
  153683. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  153684. if(samples>target)samples=target;
  153685. vorbis_synthesis_read(&vf->vd,samples);
  153686. vf->pcm_offset+=samples;
  153687. if(samples<target)
  153688. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  153689. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  153690. }
  153691. return 0;
  153692. }
  153693. /* seek to a playback time relative to the decompressed pcm stream
  153694. returns zero on success, nonzero on failure */
  153695. int ov_time_seek(OggVorbis_File *vf,double seconds){
  153696. /* translate time to PCM position and call ov_pcm_seek */
  153697. int link=-1;
  153698. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  153699. double time_total=ov_time_total(vf,-1);
  153700. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153701. if(!vf->seekable)return(OV_ENOSEEK);
  153702. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  153703. /* which bitstream section does this time offset occur in? */
  153704. for(link=vf->links-1;link>=0;link--){
  153705. pcm_total-=vf->pcmlengths[link*2+1];
  153706. time_total-=ov_time_total(vf,link);
  153707. if(seconds>=time_total)break;
  153708. }
  153709. /* enough information to convert time offset to pcm offset */
  153710. {
  153711. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  153712. return(ov_pcm_seek(vf,target));
  153713. }
  153714. }
  153715. /* page-granularity version of ov_time_seek
  153716. returns zero on success, nonzero on failure */
  153717. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  153718. /* translate time to PCM position and call ov_pcm_seek */
  153719. int link=-1;
  153720. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  153721. double time_total=ov_time_total(vf,-1);
  153722. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153723. if(!vf->seekable)return(OV_ENOSEEK);
  153724. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  153725. /* which bitstream section does this time offset occur in? */
  153726. for(link=vf->links-1;link>=0;link--){
  153727. pcm_total-=vf->pcmlengths[link*2+1];
  153728. time_total-=ov_time_total(vf,link);
  153729. if(seconds>=time_total)break;
  153730. }
  153731. /* enough information to convert time offset to pcm offset */
  153732. {
  153733. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  153734. return(ov_pcm_seek_page(vf,target));
  153735. }
  153736. }
  153737. /* tell the current stream offset cursor. Note that seek followed by
  153738. tell will likely not give the set offset due to caching */
  153739. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  153740. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153741. return(vf->offset);
  153742. }
  153743. /* return PCM offset (sample) of next PCM sample to be read */
  153744. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  153745. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153746. return(vf->pcm_offset);
  153747. }
  153748. /* return time offset (seconds) of next PCM sample to be read */
  153749. double ov_time_tell(OggVorbis_File *vf){
  153750. int link=0;
  153751. ogg_int64_t pcm_total=0;
  153752. double time_total=0.f;
  153753. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153754. if(vf->seekable){
  153755. pcm_total=ov_pcm_total(vf,-1);
  153756. time_total=ov_time_total(vf,-1);
  153757. /* which bitstream section does this time offset occur in? */
  153758. for(link=vf->links-1;link>=0;link--){
  153759. pcm_total-=vf->pcmlengths[link*2+1];
  153760. time_total-=ov_time_total(vf,link);
  153761. if(vf->pcm_offset>=pcm_total)break;
  153762. }
  153763. }
  153764. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  153765. }
  153766. /* link: -1) return the vorbis_info struct for the bitstream section
  153767. currently being decoded
  153768. 0-n) to request information for a specific bitstream section
  153769. In the case of a non-seekable bitstream, any call returns the
  153770. current bitstream. NULL in the case that the machine is not
  153771. initialized */
  153772. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  153773. if(vf->seekable){
  153774. if(link<0)
  153775. if(vf->ready_state>=STREAMSET)
  153776. return vf->vi+vf->current_link;
  153777. else
  153778. return vf->vi;
  153779. else
  153780. if(link>=vf->links)
  153781. return NULL;
  153782. else
  153783. return vf->vi+link;
  153784. }else{
  153785. return vf->vi;
  153786. }
  153787. }
  153788. /* grr, strong typing, grr, no templates/inheritence, grr */
  153789. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  153790. if(vf->seekable){
  153791. if(link<0)
  153792. if(vf->ready_state>=STREAMSET)
  153793. return vf->vc+vf->current_link;
  153794. else
  153795. return vf->vc;
  153796. else
  153797. if(link>=vf->links)
  153798. return NULL;
  153799. else
  153800. return vf->vc+link;
  153801. }else{
  153802. return vf->vc;
  153803. }
  153804. }
  153805. static int host_is_big_endian() {
  153806. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  153807. unsigned char *bytewise = (unsigned char *)&pattern;
  153808. if (bytewise[0] == 0xfe) return 1;
  153809. return 0;
  153810. }
  153811. /* up to this point, everything could more or less hide the multiple
  153812. logical bitstream nature of chaining from the toplevel application
  153813. if the toplevel application didn't particularly care. However, at
  153814. the point that we actually read audio back, the multiple-section
  153815. nature must surface: Multiple bitstream sections do not necessarily
  153816. have to have the same number of channels or sampling rate.
  153817. ov_read returns the sequential logical bitstream number currently
  153818. being decoded along with the PCM data in order that the toplevel
  153819. application can take action on channel/sample rate changes. This
  153820. number will be incremented even for streamed (non-seekable) streams
  153821. (for seekable streams, it represents the actual logical bitstream
  153822. index within the physical bitstream. Note that the accessor
  153823. functions above are aware of this dichotomy).
  153824. input values: buffer) a buffer to hold packed PCM data for return
  153825. length) the byte length requested to be placed into buffer
  153826. bigendianp) should the data be packed LSB first (0) or
  153827. MSB first (1)
  153828. word) word size for output. currently 1 (byte) or
  153829. 2 (16 bit short)
  153830. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  153831. 0) EOF
  153832. n) number of bytes of PCM actually returned. The
  153833. below works on a packet-by-packet basis, so the
  153834. return length is not related to the 'length' passed
  153835. in, just guaranteed to fit.
  153836. *section) set to the logical bitstream number */
  153837. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  153838. int bigendianp,int word,int sgned,int *bitstream){
  153839. int i,j;
  153840. int host_endian = host_is_big_endian();
  153841. float **pcm;
  153842. long samples;
  153843. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153844. while(1){
  153845. if(vf->ready_state==INITSET){
  153846. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  153847. if(samples)break;
  153848. }
  153849. /* suck in another packet */
  153850. {
  153851. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  153852. if(ret==OV_EOF)
  153853. return(0);
  153854. if(ret<=0)
  153855. return(ret);
  153856. }
  153857. }
  153858. if(samples>0){
  153859. /* yay! proceed to pack data into the byte buffer */
  153860. long channels=ov_info(vf,-1)->channels;
  153861. long bytespersample=word * channels;
  153862. vorbis_fpu_control fpu;
  153863. (void) fpu; // (to avoid a warning about it being unused)
  153864. if(samples>length/bytespersample)samples=length/bytespersample;
  153865. if(samples <= 0)
  153866. return OV_EINVAL;
  153867. /* a tight loop to pack each size */
  153868. {
  153869. int val;
  153870. if(word==1){
  153871. int off=(sgned?0:128);
  153872. vorbis_fpu_setround(&fpu);
  153873. for(j=0;j<samples;j++)
  153874. for(i=0;i<channels;i++){
  153875. val=vorbis_ftoi(pcm[i][j]*128.f);
  153876. if(val>127)val=127;
  153877. else if(val<-128)val=-128;
  153878. *buffer++=val+off;
  153879. }
  153880. vorbis_fpu_restore(fpu);
  153881. }else{
  153882. int off=(sgned?0:32768);
  153883. if(host_endian==bigendianp){
  153884. if(sgned){
  153885. vorbis_fpu_setround(&fpu);
  153886. for(i=0;i<channels;i++) { /* It's faster in this order */
  153887. float *src=pcm[i];
  153888. short *dest=((short *)buffer)+i;
  153889. for(j=0;j<samples;j++) {
  153890. val=vorbis_ftoi(src[j]*32768.f);
  153891. if(val>32767)val=32767;
  153892. else if(val<-32768)val=-32768;
  153893. *dest=val;
  153894. dest+=channels;
  153895. }
  153896. }
  153897. vorbis_fpu_restore(fpu);
  153898. }else{
  153899. vorbis_fpu_setround(&fpu);
  153900. for(i=0;i<channels;i++) {
  153901. float *src=pcm[i];
  153902. short *dest=((short *)buffer)+i;
  153903. for(j=0;j<samples;j++) {
  153904. val=vorbis_ftoi(src[j]*32768.f);
  153905. if(val>32767)val=32767;
  153906. else if(val<-32768)val=-32768;
  153907. *dest=val+off;
  153908. dest+=channels;
  153909. }
  153910. }
  153911. vorbis_fpu_restore(fpu);
  153912. }
  153913. }else if(bigendianp){
  153914. vorbis_fpu_setround(&fpu);
  153915. for(j=0;j<samples;j++)
  153916. for(i=0;i<channels;i++){
  153917. val=vorbis_ftoi(pcm[i][j]*32768.f);
  153918. if(val>32767)val=32767;
  153919. else if(val<-32768)val=-32768;
  153920. val+=off;
  153921. *buffer++=(val>>8);
  153922. *buffer++=(val&0xff);
  153923. }
  153924. vorbis_fpu_restore(fpu);
  153925. }else{
  153926. int val;
  153927. vorbis_fpu_setround(&fpu);
  153928. for(j=0;j<samples;j++)
  153929. for(i=0;i<channels;i++){
  153930. val=vorbis_ftoi(pcm[i][j]*32768.f);
  153931. if(val>32767)val=32767;
  153932. else if(val<-32768)val=-32768;
  153933. val+=off;
  153934. *buffer++=(val&0xff);
  153935. *buffer++=(val>>8);
  153936. }
  153937. vorbis_fpu_restore(fpu);
  153938. }
  153939. }
  153940. }
  153941. vorbis_synthesis_read(&vf->vd,samples);
  153942. vf->pcm_offset+=samples;
  153943. if(bitstream)*bitstream=vf->current_link;
  153944. return(samples*bytespersample);
  153945. }else{
  153946. return(samples);
  153947. }
  153948. }
  153949. /* input values: pcm_channels) a float vector per channel of output
  153950. length) the sample length being read by the app
  153951. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  153952. 0) EOF
  153953. n) number of samples of PCM actually returned. The
  153954. below works on a packet-by-packet basis, so the
  153955. return length is not related to the 'length' passed
  153956. in, just guaranteed to fit.
  153957. *section) set to the logical bitstream number */
  153958. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  153959. int *bitstream){
  153960. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153961. while(1){
  153962. if(vf->ready_state==INITSET){
  153963. float **pcm;
  153964. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  153965. if(samples){
  153966. if(pcm_channels)*pcm_channels=pcm;
  153967. if(samples>length)samples=length;
  153968. vorbis_synthesis_read(&vf->vd,samples);
  153969. vf->pcm_offset+=samples;
  153970. if(bitstream)*bitstream=vf->current_link;
  153971. return samples;
  153972. }
  153973. }
  153974. /* suck in another packet */
  153975. {
  153976. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  153977. if(ret==OV_EOF)return(0);
  153978. if(ret<=0)return(ret);
  153979. }
  153980. }
  153981. }
  153982. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  153983. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  153984. ogg_int64_t off);
  153985. static void _ov_splice(float **pcm,float **lappcm,
  153986. int n1, int n2,
  153987. int ch1, int ch2,
  153988. float *w1, float *w2){
  153989. int i,j;
  153990. float *w=w1;
  153991. int n=n1;
  153992. if(n1>n2){
  153993. n=n2;
  153994. w=w2;
  153995. }
  153996. /* splice */
  153997. for(j=0;j<ch1 && j<ch2;j++){
  153998. float *s=lappcm[j];
  153999. float *d=pcm[j];
  154000. for(i=0;i<n;i++){
  154001. float wd=w[i]*w[i];
  154002. float ws=1.-wd;
  154003. d[i]=d[i]*wd + s[i]*ws;
  154004. }
  154005. }
  154006. /* window from zero */
  154007. for(;j<ch2;j++){
  154008. float *d=pcm[j];
  154009. for(i=0;i<n;i++){
  154010. float wd=w[i]*w[i];
  154011. d[i]=d[i]*wd;
  154012. }
  154013. }
  154014. }
  154015. /* make sure vf is INITSET */
  154016. static int _ov_initset(OggVorbis_File *vf){
  154017. while(1){
  154018. if(vf->ready_state==INITSET)break;
  154019. /* suck in another packet */
  154020. {
  154021. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  154022. if(ret<0 && ret!=OV_HOLE)return(ret);
  154023. }
  154024. }
  154025. return 0;
  154026. }
  154027. /* make sure vf is INITSET and that we have a primed buffer; if
  154028. we're crosslapping at a stream section boundary, this also makes
  154029. sure we're sanity checking against the right stream information */
  154030. static int _ov_initprime(OggVorbis_File *vf){
  154031. vorbis_dsp_state *vd=&vf->vd;
  154032. while(1){
  154033. if(vf->ready_state==INITSET)
  154034. if(vorbis_synthesis_pcmout(vd,NULL))break;
  154035. /* suck in another packet */
  154036. {
  154037. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  154038. if(ret<0 && ret!=OV_HOLE)return(ret);
  154039. }
  154040. }
  154041. return 0;
  154042. }
  154043. /* grab enough data for lapping from vf; this may be in the form of
  154044. unreturned, already-decoded pcm, remaining PCM we will need to
  154045. decode, or synthetic postextrapolation from last packets. */
  154046. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  154047. float **lappcm,int lapsize){
  154048. int lapcount=0,i;
  154049. float **pcm;
  154050. /* try first to decode the lapping data */
  154051. while(lapcount<lapsize){
  154052. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  154053. if(samples){
  154054. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  154055. for(i=0;i<vi->channels;i++)
  154056. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  154057. lapcount+=samples;
  154058. vorbis_synthesis_read(vd,samples);
  154059. }else{
  154060. /* suck in another packet */
  154061. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  154062. if(ret==OV_EOF)break;
  154063. }
  154064. }
  154065. if(lapcount<lapsize){
  154066. /* failed to get lapping data from normal decode; pry it from the
  154067. postextrapolation buffering, or the second half of the MDCT
  154068. from the last packet */
  154069. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  154070. if(samples==0){
  154071. for(i=0;i<vi->channels;i++)
  154072. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  154073. lapcount=lapsize;
  154074. }else{
  154075. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  154076. for(i=0;i<vi->channels;i++)
  154077. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  154078. lapcount+=samples;
  154079. }
  154080. }
  154081. }
  154082. /* this sets up crosslapping of a sample by using trailing data from
  154083. sample 1 and lapping it into the windowing buffer of sample 2 */
  154084. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  154085. vorbis_info *vi1,*vi2;
  154086. float **lappcm;
  154087. float **pcm;
  154088. float *w1,*w2;
  154089. int n1,n2,i,ret,hs1,hs2;
  154090. if(vf1==vf2)return(0); /* degenerate case */
  154091. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  154092. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  154093. /* the relevant overlap buffers must be pre-checked and pre-primed
  154094. before looking at settings in the event that priming would cross
  154095. a bitstream boundary. So, do it now */
  154096. ret=_ov_initset(vf1);
  154097. if(ret)return(ret);
  154098. ret=_ov_initprime(vf2);
  154099. if(ret)return(ret);
  154100. vi1=ov_info(vf1,-1);
  154101. vi2=ov_info(vf2,-1);
  154102. hs1=ov_halfrate_p(vf1);
  154103. hs2=ov_halfrate_p(vf2);
  154104. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  154105. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  154106. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  154107. w1=vorbis_window(&vf1->vd,0);
  154108. w2=vorbis_window(&vf2->vd,0);
  154109. for(i=0;i<vi1->channels;i++)
  154110. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  154111. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  154112. /* have a lapping buffer from vf1; now to splice it into the lapping
  154113. buffer of vf2 */
  154114. /* consolidate and expose the buffer. */
  154115. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  154116. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  154117. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  154118. /* splice */
  154119. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  154120. /* done */
  154121. return(0);
  154122. }
  154123. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  154124. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  154125. vorbis_info *vi;
  154126. float **lappcm;
  154127. float **pcm;
  154128. float *w1,*w2;
  154129. int n1,n2,ch1,ch2,hs;
  154130. int i,ret;
  154131. if(vf->ready_state<OPENED)return(OV_EINVAL);
  154132. ret=_ov_initset(vf);
  154133. if(ret)return(ret);
  154134. vi=ov_info(vf,-1);
  154135. hs=ov_halfrate_p(vf);
  154136. ch1=vi->channels;
  154137. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  154138. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  154139. persistent; even if the decode state
  154140. from this link gets dumped, this
  154141. window array continues to exist */
  154142. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  154143. for(i=0;i<ch1;i++)
  154144. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  154145. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  154146. /* have lapping data; seek and prime the buffer */
  154147. ret=localseek(vf,pos);
  154148. if(ret)return ret;
  154149. ret=_ov_initprime(vf);
  154150. if(ret)return(ret);
  154151. /* Guard against cross-link changes; they're perfectly legal */
  154152. vi=ov_info(vf,-1);
  154153. ch2=vi->channels;
  154154. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  154155. w2=vorbis_window(&vf->vd,0);
  154156. /* consolidate and expose the buffer. */
  154157. vorbis_synthesis_lapout(&vf->vd,&pcm);
  154158. /* splice */
  154159. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  154160. /* done */
  154161. return(0);
  154162. }
  154163. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  154164. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  154165. }
  154166. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  154167. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  154168. }
  154169. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  154170. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  154171. }
  154172. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  154173. int (*localseek)(OggVorbis_File *,double)){
  154174. vorbis_info *vi;
  154175. float **lappcm;
  154176. float **pcm;
  154177. float *w1,*w2;
  154178. int n1,n2,ch1,ch2,hs;
  154179. int i,ret;
  154180. if(vf->ready_state<OPENED)return(OV_EINVAL);
  154181. ret=_ov_initset(vf);
  154182. if(ret)return(ret);
  154183. vi=ov_info(vf,-1);
  154184. hs=ov_halfrate_p(vf);
  154185. ch1=vi->channels;
  154186. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  154187. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  154188. persistent; even if the decode state
  154189. from this link gets dumped, this
  154190. window array continues to exist */
  154191. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  154192. for(i=0;i<ch1;i++)
  154193. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  154194. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  154195. /* have lapping data; seek and prime the buffer */
  154196. ret=localseek(vf,pos);
  154197. if(ret)return ret;
  154198. ret=_ov_initprime(vf);
  154199. if(ret)return(ret);
  154200. /* Guard against cross-link changes; they're perfectly legal */
  154201. vi=ov_info(vf,-1);
  154202. ch2=vi->channels;
  154203. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  154204. w2=vorbis_window(&vf->vd,0);
  154205. /* consolidate and expose the buffer. */
  154206. vorbis_synthesis_lapout(&vf->vd,&pcm);
  154207. /* splice */
  154208. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  154209. /* done */
  154210. return(0);
  154211. }
  154212. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  154213. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  154214. }
  154215. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  154216. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  154217. }
  154218. #endif
  154219. /*** End of inlined file: vorbisfile.c ***/
  154220. /*** Start of inlined file: window.c ***/
  154221. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  154222. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  154223. // tasks..
  154224. #if JUCE_MSVC
  154225. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  154226. #endif
  154227. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  154228. #if JUCE_USE_OGGVORBIS
  154229. #include <stdlib.h>
  154230. #include <math.h>
  154231. static float vwin64[32] = {
  154232. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  154233. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  154234. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  154235. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  154236. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  154237. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  154238. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  154239. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  154240. };
  154241. static float vwin128[64] = {
  154242. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  154243. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  154244. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  154245. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  154246. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  154247. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  154248. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  154249. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  154250. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  154251. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  154252. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  154253. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  154254. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  154255. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  154256. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  154257. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  154258. };
  154259. static float vwin256[128] = {
  154260. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  154261. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  154262. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  154263. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  154264. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  154265. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  154266. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  154267. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  154268. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  154269. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  154270. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  154271. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  154272. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  154273. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  154274. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  154275. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  154276. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  154277. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  154278. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  154279. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  154280. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  154281. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  154282. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  154283. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  154284. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  154285. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  154286. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  154287. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  154288. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  154289. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  154290. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  154291. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  154292. };
  154293. static float vwin512[256] = {
  154294. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  154295. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  154296. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  154297. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  154298. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  154299. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  154300. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  154301. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  154302. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  154303. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  154304. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  154305. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  154306. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  154307. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  154308. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  154309. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  154310. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  154311. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  154312. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  154313. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  154314. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  154315. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  154316. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  154317. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  154318. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  154319. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  154320. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  154321. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  154322. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  154323. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  154324. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  154325. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  154326. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  154327. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  154328. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  154329. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  154330. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  154331. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  154332. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  154333. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  154334. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  154335. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  154336. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  154337. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  154338. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  154339. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  154340. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  154341. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  154342. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  154343. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  154344. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  154345. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  154346. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  154347. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  154348. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  154349. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  154350. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  154351. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  154352. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  154353. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  154354. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  154355. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  154356. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  154357. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  154358. };
  154359. static float vwin1024[512] = {
  154360. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  154361. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  154362. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  154363. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  154364. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  154365. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  154366. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  154367. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  154368. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  154369. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  154370. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  154371. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  154372. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  154373. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  154374. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  154375. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  154376. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  154377. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  154378. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  154379. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  154380. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  154381. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  154382. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  154383. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  154384. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  154385. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  154386. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  154387. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  154388. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  154389. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  154390. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  154391. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  154392. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  154393. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  154394. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  154395. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  154396. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  154397. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  154398. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  154399. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  154400. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  154401. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  154402. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  154403. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  154404. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  154405. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  154406. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  154407. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  154408. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  154409. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  154410. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  154411. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  154412. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  154413. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  154414. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  154415. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  154416. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  154417. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  154418. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  154419. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  154420. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  154421. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  154422. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  154423. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  154424. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  154425. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  154426. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  154427. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  154428. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  154429. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  154430. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  154431. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  154432. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  154433. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  154434. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  154435. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  154436. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  154437. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  154438. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  154439. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  154440. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  154441. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  154442. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  154443. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  154444. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  154445. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  154446. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  154447. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  154448. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  154449. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  154450. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  154451. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  154452. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  154453. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  154454. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  154455. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  154456. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  154457. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  154458. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  154459. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  154460. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  154461. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  154462. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  154463. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  154464. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  154465. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  154466. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  154467. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  154468. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  154469. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  154470. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  154471. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  154472. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  154473. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  154474. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  154475. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  154476. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  154477. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  154478. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  154479. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  154480. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  154481. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  154482. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  154483. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  154484. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  154485. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  154486. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  154487. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  154488. };
  154489. static float vwin2048[1024] = {
  154490. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  154491. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  154492. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  154493. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  154494. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  154495. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  154496. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  154497. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  154498. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  154499. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  154500. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  154501. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  154502. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  154503. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  154504. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  154505. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  154506. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  154507. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  154508. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  154509. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  154510. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  154511. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  154512. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  154513. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  154514. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  154515. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  154516. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  154517. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  154518. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  154519. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  154520. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  154521. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  154522. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  154523. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  154524. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  154525. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  154526. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  154527. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  154528. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  154529. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  154530. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  154531. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  154532. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  154533. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  154534. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  154535. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  154536. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  154537. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  154538. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  154539. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  154540. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  154541. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  154542. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  154543. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  154544. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  154545. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  154546. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  154547. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  154548. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  154549. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  154550. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  154551. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  154552. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  154553. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  154554. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  154555. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  154556. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  154557. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  154558. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  154559. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  154560. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  154561. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  154562. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  154563. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  154564. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  154565. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  154566. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  154567. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  154568. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  154569. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  154570. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  154571. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  154572. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  154573. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  154574. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  154575. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  154576. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  154577. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  154578. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  154579. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  154580. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  154581. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  154582. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  154583. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  154584. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  154585. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  154586. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  154587. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  154588. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  154589. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  154590. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  154591. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  154592. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  154593. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  154594. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  154595. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  154596. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  154597. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  154598. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  154599. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  154600. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  154601. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  154602. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  154603. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  154604. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  154605. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  154606. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  154607. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  154608. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  154609. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  154610. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  154611. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  154612. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  154613. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  154614. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  154615. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  154616. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  154617. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  154618. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  154619. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  154620. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  154621. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  154622. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  154623. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  154624. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  154625. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  154626. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  154627. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  154628. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  154629. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  154630. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  154631. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  154632. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  154633. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  154634. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  154635. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  154636. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  154637. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  154638. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  154639. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  154640. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  154641. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  154642. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  154643. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  154644. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  154645. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  154646. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  154647. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  154648. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  154649. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  154650. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  154651. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  154652. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  154653. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  154654. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  154655. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  154656. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  154657. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  154658. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  154659. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  154660. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  154661. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  154662. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  154663. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  154664. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  154665. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  154666. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  154667. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  154668. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  154669. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  154670. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  154671. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  154672. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  154673. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  154674. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  154675. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  154676. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  154677. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  154678. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  154679. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  154680. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  154681. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  154682. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  154683. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  154684. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  154685. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  154686. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  154687. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  154688. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  154689. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  154690. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  154691. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  154692. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  154693. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  154694. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  154695. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  154696. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  154697. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  154698. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  154699. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  154700. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  154701. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  154702. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  154703. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  154704. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  154705. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  154706. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  154707. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  154708. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  154709. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  154710. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  154711. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  154712. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  154713. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  154714. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  154715. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  154716. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  154717. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  154718. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  154719. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  154720. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  154721. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  154722. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  154723. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  154724. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  154725. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  154726. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  154727. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  154728. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  154729. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  154730. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  154731. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  154732. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  154733. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  154734. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  154735. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  154736. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  154737. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  154738. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  154739. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  154740. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  154741. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  154742. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  154743. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  154744. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  154745. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  154746. };
  154747. static float vwin4096[2048] = {
  154748. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  154749. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  154750. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  154751. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  154752. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  154753. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  154754. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  154755. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  154756. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  154757. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  154758. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  154759. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  154760. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  154761. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  154762. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  154763. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  154764. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  154765. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  154766. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  154767. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  154768. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  154769. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  154770. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  154771. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  154772. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  154773. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  154774. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  154775. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  154776. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  154777. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  154778. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  154779. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  154780. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  154781. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  154782. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  154783. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  154784. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  154785. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  154786. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  154787. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  154788. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  154789. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  154790. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  154791. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  154792. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  154793. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  154794. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  154795. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  154796. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  154797. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  154798. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  154799. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  154800. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  154801. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  154802. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  154803. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  154804. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  154805. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  154806. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  154807. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  154808. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  154809. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  154810. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  154811. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  154812. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  154813. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  154814. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  154815. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  154816. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  154817. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  154818. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  154819. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  154820. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  154821. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  154822. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  154823. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  154824. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  154825. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  154826. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  154827. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  154828. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  154829. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  154830. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  154831. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  154832. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  154833. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  154834. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  154835. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  154836. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  154837. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  154838. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  154839. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  154840. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  154841. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  154842. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  154843. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  154844. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  154845. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  154846. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  154847. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  154848. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  154849. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  154850. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  154851. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  154852. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  154853. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  154854. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  154855. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  154856. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  154857. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  154858. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  154859. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  154860. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  154861. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  154862. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  154863. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  154864. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  154865. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  154866. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  154867. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  154868. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  154869. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  154870. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  154871. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  154872. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  154873. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  154874. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  154875. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  154876. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  154877. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  154878. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  154879. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  154880. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  154881. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  154882. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  154883. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  154884. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  154885. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  154886. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  154887. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  154888. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  154889. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  154890. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  154891. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  154892. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  154893. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  154894. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  154895. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  154896. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  154897. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  154898. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  154899. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  154900. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  154901. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  154902. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  154903. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  154904. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  154905. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  154906. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  154907. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  154908. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  154909. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  154910. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  154911. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  154912. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  154913. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  154914. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  154915. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  154916. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  154917. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  154918. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  154919. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  154920. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  154921. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  154922. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  154923. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  154924. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  154925. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  154926. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  154927. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  154928. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  154929. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  154930. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  154931. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  154932. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  154933. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  154934. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  154935. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  154936. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  154937. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  154938. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  154939. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  154940. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  154941. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  154942. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  154943. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  154944. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  154945. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  154946. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  154947. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  154948. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  154949. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  154950. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  154951. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  154952. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  154953. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  154954. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  154955. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  154956. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  154957. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  154958. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  154959. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  154960. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  154961. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  154962. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  154963. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  154964. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  154965. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  154966. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  154967. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  154968. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  154969. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  154970. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  154971. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  154972. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  154973. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  154974. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  154975. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  154976. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  154977. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  154978. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  154979. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  154980. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  154981. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  154982. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  154983. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  154984. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  154985. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  154986. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  154987. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  154988. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  154989. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  154990. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  154991. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  154992. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  154993. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  154994. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  154995. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  154996. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  154997. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  154998. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  154999. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  155000. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  155001. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  155002. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  155003. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  155004. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  155005. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  155006. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  155007. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  155008. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  155009. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  155010. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  155011. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  155012. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  155013. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  155014. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  155015. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  155016. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  155017. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  155018. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  155019. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  155020. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  155021. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  155022. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  155023. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  155024. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  155025. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  155026. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  155027. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  155028. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  155029. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  155030. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  155031. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  155032. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  155033. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  155034. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  155035. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  155036. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  155037. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  155038. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  155039. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  155040. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  155041. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  155042. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  155043. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  155044. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  155045. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  155046. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  155047. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  155048. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  155049. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  155050. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  155051. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  155052. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  155053. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  155054. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  155055. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  155056. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  155057. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  155058. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  155059. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  155060. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  155061. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  155062. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  155063. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  155064. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  155065. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  155066. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  155067. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  155068. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  155069. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  155070. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  155071. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  155072. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  155073. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  155074. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  155075. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  155076. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  155077. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  155078. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  155079. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  155080. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  155081. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  155082. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  155083. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  155084. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  155085. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  155086. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  155087. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  155088. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  155089. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  155090. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  155091. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  155092. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  155093. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  155094. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  155095. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  155096. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  155097. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  155098. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  155099. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  155100. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  155101. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  155102. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  155103. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  155104. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  155105. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  155106. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  155107. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  155108. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  155109. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  155110. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  155111. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  155112. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  155113. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  155114. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  155115. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  155116. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  155117. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  155118. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  155119. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  155120. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  155121. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  155122. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  155123. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  155124. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  155125. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  155126. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  155127. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  155128. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  155129. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  155130. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  155131. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  155132. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  155133. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  155134. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  155135. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  155136. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  155137. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  155138. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  155139. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  155140. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  155141. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  155142. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  155143. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  155144. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  155145. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  155146. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  155147. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  155148. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  155149. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  155150. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  155151. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  155152. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  155153. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  155154. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  155155. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  155156. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  155157. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  155158. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  155159. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  155160. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  155161. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  155162. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  155163. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  155164. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  155165. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  155166. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  155167. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  155168. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  155169. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  155170. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  155171. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  155172. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  155173. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  155174. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  155175. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  155176. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  155177. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  155178. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  155179. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  155180. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  155181. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  155182. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  155183. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  155184. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  155185. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  155186. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  155187. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  155188. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  155189. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  155190. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  155191. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  155192. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  155193. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  155194. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  155195. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  155196. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  155197. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  155198. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  155199. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  155200. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  155201. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  155202. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  155203. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  155204. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  155205. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  155206. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  155207. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  155208. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  155209. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  155210. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  155211. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  155212. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  155213. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  155214. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  155215. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  155216. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  155217. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  155218. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  155219. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  155220. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  155221. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  155222. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  155223. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  155224. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  155225. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  155226. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  155227. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  155228. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  155229. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  155230. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  155231. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  155232. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  155233. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  155234. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  155235. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  155236. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  155237. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  155238. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  155239. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  155240. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  155241. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  155242. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  155243. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  155244. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  155245. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  155246. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  155247. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  155248. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  155249. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  155250. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  155251. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  155252. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  155253. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  155254. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  155255. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  155256. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  155257. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  155258. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  155259. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  155260. };
  155261. static float vwin8192[4096] = {
  155262. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  155263. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  155264. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  155265. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  155266. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  155267. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  155268. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  155269. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  155270. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  155271. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  155272. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  155273. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  155274. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  155275. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  155276. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  155277. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  155278. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  155279. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  155280. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  155281. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  155282. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  155283. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  155284. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  155285. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  155286. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  155287. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  155288. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  155289. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  155290. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  155291. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  155292. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  155293. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  155294. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  155295. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  155296. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  155297. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  155298. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  155299. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  155300. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  155301. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  155302. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  155303. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  155304. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  155305. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  155306. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  155307. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  155308. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  155309. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  155310. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  155311. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  155312. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  155313. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  155314. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  155315. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  155316. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  155317. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  155318. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  155319. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  155320. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  155321. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  155322. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  155323. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  155324. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  155325. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  155326. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  155327. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  155328. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  155329. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  155330. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  155331. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  155332. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  155333. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  155334. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  155335. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  155336. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  155337. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  155338. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  155339. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  155340. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  155341. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  155342. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  155343. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  155344. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  155345. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  155346. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  155347. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  155348. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  155349. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  155350. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  155351. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  155352. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  155353. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  155354. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  155355. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  155356. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  155357. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  155358. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  155359. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  155360. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  155361. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  155362. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  155363. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  155364. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  155365. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  155366. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  155367. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  155368. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  155369. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  155370. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  155371. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  155372. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  155373. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  155374. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  155375. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  155376. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  155377. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  155378. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  155379. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  155380. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  155381. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  155382. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  155383. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  155384. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  155385. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  155386. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  155387. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  155388. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  155389. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  155390. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  155391. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  155392. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  155393. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  155394. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  155395. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  155396. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  155397. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  155398. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  155399. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  155400. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  155401. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  155402. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  155403. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  155404. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  155405. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  155406. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  155407. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  155408. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  155409. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  155410. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  155411. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  155412. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  155413. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  155414. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  155415. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  155416. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  155417. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  155418. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  155419. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  155420. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  155421. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  155422. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  155423. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  155424. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  155425. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  155426. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  155427. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  155428. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  155429. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  155430. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  155431. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  155432. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  155433. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  155434. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  155435. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  155436. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  155437. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  155438. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  155439. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  155440. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  155441. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  155442. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  155443. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  155444. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  155445. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  155446. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  155447. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  155448. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  155449. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  155450. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  155451. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  155452. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  155453. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  155454. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  155455. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  155456. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  155457. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  155458. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  155459. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  155460. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  155461. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  155462. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  155463. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  155464. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  155465. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  155466. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  155467. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  155468. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  155469. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  155470. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  155471. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  155472. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  155473. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  155474. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  155475. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  155476. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  155477. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  155478. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  155479. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  155480. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  155481. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  155482. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  155483. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  155484. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  155485. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  155486. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  155487. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  155488. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  155489. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  155490. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  155491. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  155492. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  155493. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  155494. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  155495. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  155496. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  155497. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  155498. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  155499. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  155500. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  155501. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  155502. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  155503. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  155504. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  155505. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  155506. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  155507. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  155508. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  155509. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  155510. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  155511. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  155512. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  155513. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  155514. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  155515. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  155516. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  155517. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  155518. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  155519. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  155520. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  155521. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  155522. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  155523. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  155524. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  155525. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  155526. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  155527. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  155528. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  155529. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  155530. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  155531. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  155532. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  155533. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  155534. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  155535. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  155536. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  155537. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  155538. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  155539. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  155540. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  155541. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  155542. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  155543. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  155544. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  155545. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  155546. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  155547. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  155548. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  155549. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  155550. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  155551. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  155552. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  155553. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  155554. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  155555. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  155556. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  155557. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  155558. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  155559. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  155560. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  155561. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  155562. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  155563. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  155564. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  155565. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  155566. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  155567. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  155568. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  155569. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  155570. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  155571. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  155572. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  155573. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  155574. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  155575. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  155576. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  155577. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  155578. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  155579. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  155580. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  155581. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  155582. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  155583. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  155584. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  155585. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  155586. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  155587. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  155588. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  155589. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  155590. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  155591. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  155592. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  155593. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  155594. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  155595. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  155596. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  155597. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  155598. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  155599. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  155600. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  155601. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  155602. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  155603. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  155604. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  155605. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  155606. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  155607. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  155608. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  155609. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  155610. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  155611. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  155612. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  155613. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  155614. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  155615. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  155616. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  155617. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  155618. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  155619. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  155620. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  155621. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  155622. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  155623. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  155624. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  155625. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  155626. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  155627. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  155628. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  155629. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  155630. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  155631. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  155632. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  155633. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  155634. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  155635. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  155636. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  155637. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  155638. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  155639. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  155640. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  155641. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  155642. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  155643. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  155644. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  155645. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  155646. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  155647. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  155648. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  155649. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  155650. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  155651. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  155652. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  155653. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  155654. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  155655. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  155656. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  155657. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  155658. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  155659. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  155660. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  155661. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  155662. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  155663. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  155664. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  155665. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  155666. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  155667. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  155668. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  155669. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  155670. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  155671. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  155672. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  155673. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  155674. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  155675. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  155676. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  155677. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  155678. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  155679. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  155680. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  155681. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  155682. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  155683. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  155684. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  155685. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  155686. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  155687. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  155688. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  155689. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  155690. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  155691. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  155692. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  155693. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  155694. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  155695. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  155696. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  155697. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  155698. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  155699. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  155700. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  155701. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  155702. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  155703. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  155704. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  155705. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  155706. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  155707. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  155708. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  155709. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  155710. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  155711. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  155712. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  155713. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  155714. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  155715. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  155716. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  155717. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  155718. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  155719. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  155720. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  155721. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  155722. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  155723. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  155724. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  155725. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  155726. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  155727. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  155728. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  155729. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  155730. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  155731. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  155732. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  155733. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  155734. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  155735. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  155736. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  155737. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  155738. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  155739. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  155740. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  155741. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  155742. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  155743. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  155744. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  155745. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  155746. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  155747. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  155748. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  155749. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  155750. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  155751. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  155752. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  155753. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  155754. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  155755. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  155756. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  155757. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  155758. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  155759. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  155760. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  155761. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  155762. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  155763. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  155764. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  155765. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  155766. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  155767. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  155768. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  155769. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  155770. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  155771. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  155772. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  155773. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  155774. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  155775. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  155776. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  155777. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  155778. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  155779. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  155780. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  155781. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  155782. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  155783. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  155784. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  155785. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  155786. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  155787. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  155788. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  155789. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  155790. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  155791. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  155792. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  155793. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  155794. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  155795. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  155796. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  155797. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  155798. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  155799. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  155800. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  155801. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  155802. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  155803. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  155804. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  155805. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  155806. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  155807. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  155808. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  155809. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  155810. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  155811. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  155812. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  155813. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  155814. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  155815. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  155816. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  155817. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  155818. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  155819. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  155820. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  155821. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  155822. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  155823. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  155824. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  155825. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  155826. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  155827. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  155828. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  155829. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  155830. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  155831. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  155832. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  155833. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  155834. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  155835. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  155836. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  155837. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  155838. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  155839. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  155840. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  155841. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  155842. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  155843. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  155844. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  155845. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  155846. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  155847. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  155848. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  155849. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  155850. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  155851. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  155852. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  155853. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  155854. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  155855. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  155856. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  155857. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  155858. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  155859. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  155860. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  155861. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  155862. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  155863. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  155864. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  155865. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  155866. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  155867. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  155868. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  155869. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  155870. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  155871. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  155872. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  155873. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  155874. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  155875. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  155876. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  155877. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  155878. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  155879. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  155880. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  155881. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  155882. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  155883. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  155884. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  155885. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  155886. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  155887. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  155888. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  155889. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  155890. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  155891. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  155892. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  155893. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  155894. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  155895. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  155896. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  155897. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  155898. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  155899. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  155900. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  155901. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  155902. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  155903. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  155904. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  155905. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  155906. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  155907. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  155908. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  155909. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  155910. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  155911. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  155912. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  155913. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  155914. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  155915. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  155916. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  155917. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  155918. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  155919. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  155920. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  155921. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  155922. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  155923. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  155924. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  155925. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  155926. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  155927. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  155928. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  155929. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  155930. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  155931. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  155932. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  155933. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  155934. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  155935. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  155936. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  155937. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  155938. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  155939. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  155940. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  155941. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  155942. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  155943. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  155944. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  155945. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  155946. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  155947. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  155948. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  155949. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  155950. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  155951. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  155952. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  155953. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  155954. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  155955. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  155956. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  155957. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  155958. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  155959. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  155960. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  155961. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  155962. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  155963. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  155964. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  155965. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  155966. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  155967. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  155968. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  155969. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  155970. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  155971. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  155972. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  155973. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  155974. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  155975. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  155976. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  155977. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  155978. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  155979. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  155980. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  155981. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  155982. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  155983. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  155984. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  155985. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  155986. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  155987. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  155988. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  155989. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  155990. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  155991. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  155992. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  155993. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  155994. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  155995. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  155996. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  155997. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  155998. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  155999. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  156000. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  156001. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  156002. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  156003. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  156004. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  156005. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  156006. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  156007. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  156008. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  156009. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  156010. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  156011. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  156012. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  156013. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  156014. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  156015. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  156016. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  156017. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  156018. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  156019. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  156020. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  156021. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  156022. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  156023. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  156024. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  156025. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  156026. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  156027. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  156028. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  156029. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  156030. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  156031. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  156032. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  156033. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  156034. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  156035. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  156036. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  156037. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  156038. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  156039. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  156040. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  156041. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  156042. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  156043. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  156044. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  156045. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  156046. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  156047. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  156048. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  156049. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  156050. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  156051. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  156052. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  156053. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  156054. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  156055. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  156056. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  156057. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  156058. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  156059. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  156060. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  156061. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  156062. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  156063. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  156064. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  156065. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  156066. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  156067. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  156068. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  156069. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  156070. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  156071. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  156072. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  156073. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  156074. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  156075. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  156076. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  156077. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  156078. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  156079. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  156080. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  156081. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  156082. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  156083. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  156084. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  156085. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  156086. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  156087. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  156088. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  156089. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  156090. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  156091. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  156092. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  156093. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  156094. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  156095. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  156096. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  156097. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  156098. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  156099. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  156100. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  156101. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  156102. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  156103. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  156104. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  156105. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  156106. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  156107. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  156108. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  156109. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  156110. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  156111. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  156112. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  156113. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  156114. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  156115. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  156116. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  156117. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  156118. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  156119. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  156120. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  156121. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  156122. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  156123. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  156124. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  156125. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  156126. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  156127. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  156128. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  156129. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  156130. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  156131. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  156132. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  156133. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  156134. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  156135. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  156136. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  156137. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  156138. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  156139. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  156140. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  156141. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  156142. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  156143. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  156144. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  156145. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  156146. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  156147. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  156148. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  156149. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  156150. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  156151. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  156152. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  156153. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  156154. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  156155. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  156156. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  156157. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  156158. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  156159. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  156160. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  156161. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  156162. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  156163. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  156164. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  156165. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  156166. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  156167. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  156168. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  156169. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  156170. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  156171. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  156172. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  156173. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  156174. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  156175. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  156176. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  156177. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  156178. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  156179. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  156180. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  156181. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  156182. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  156183. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  156184. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  156185. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  156186. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  156187. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  156188. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  156189. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  156190. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  156191. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  156192. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  156193. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  156194. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  156195. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  156196. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  156197. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  156198. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  156199. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  156200. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  156201. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  156202. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  156203. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  156204. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  156205. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  156206. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  156207. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  156208. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  156209. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  156210. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  156211. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  156212. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  156213. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  156214. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  156215. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  156216. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  156217. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  156218. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  156219. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  156220. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  156221. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  156222. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  156223. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  156224. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  156225. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  156226. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  156227. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  156228. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  156229. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  156230. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  156231. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  156232. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  156233. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  156234. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  156235. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  156236. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  156237. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  156238. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  156239. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  156240. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  156241. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  156242. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  156243. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  156244. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  156245. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  156246. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  156247. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  156248. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  156249. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  156250. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  156251. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  156252. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  156253. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  156254. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  156255. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  156256. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  156257. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  156258. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  156259. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  156260. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  156261. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  156262. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  156263. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  156264. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  156265. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  156266. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  156267. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  156268. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  156269. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  156270. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  156271. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  156272. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  156273. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  156274. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  156275. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  156276. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  156277. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  156278. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  156279. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  156280. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  156281. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  156282. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  156283. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  156284. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  156285. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  156286. };
  156287. static float *vwin[8] = {
  156288. vwin64,
  156289. vwin128,
  156290. vwin256,
  156291. vwin512,
  156292. vwin1024,
  156293. vwin2048,
  156294. vwin4096,
  156295. vwin8192,
  156296. };
  156297. float *_vorbis_window_get(int n){
  156298. return vwin[n];
  156299. }
  156300. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  156301. int lW,int W,int nW){
  156302. lW=(W?lW:0);
  156303. nW=(W?nW:0);
  156304. {
  156305. float *windowLW=vwin[winno[lW]];
  156306. float *windowNW=vwin[winno[nW]];
  156307. long n=blocksizes[W];
  156308. long ln=blocksizes[lW];
  156309. long rn=blocksizes[nW];
  156310. long leftbegin=n/4-ln/4;
  156311. long leftend=leftbegin+ln/2;
  156312. long rightbegin=n/2+n/4-rn/4;
  156313. long rightend=rightbegin+rn/2;
  156314. int i,p;
  156315. for(i=0;i<leftbegin;i++)
  156316. d[i]=0.f;
  156317. for(p=0;i<leftend;i++,p++)
  156318. d[i]*=windowLW[p];
  156319. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  156320. d[i]*=windowNW[p];
  156321. for(;i<n;i++)
  156322. d[i]=0.f;
  156323. }
  156324. }
  156325. #endif
  156326. /*** End of inlined file: window.c ***/
  156327. #else
  156328. #include <vorbis/vorbisenc.h>
  156329. #include <vorbis/codec.h>
  156330. #include <vorbis/vorbisfile.h>
  156331. #endif
  156332. }
  156333. #undef max
  156334. #undef min
  156335. BEGIN_JUCE_NAMESPACE
  156336. static const char* const oggFormatName = "Ogg-Vorbis file";
  156337. static const char* const oggExtensions[] = { ".ogg", 0 };
  156338. class OggReader : public AudioFormatReader
  156339. {
  156340. OggVorbisNamespace::OggVorbis_File ovFile;
  156341. OggVorbisNamespace::ov_callbacks callbacks;
  156342. AudioSampleBuffer reservoir;
  156343. int reservoirStart, samplesInReservoir;
  156344. public:
  156345. OggReader (InputStream* const inp)
  156346. : AudioFormatReader (inp, TRANS (oggFormatName)),
  156347. reservoir (2, 4096),
  156348. reservoirStart (0),
  156349. samplesInReservoir (0)
  156350. {
  156351. using namespace OggVorbisNamespace;
  156352. sampleRate = 0;
  156353. usesFloatingPointData = true;
  156354. callbacks.read_func = &oggReadCallback;
  156355. callbacks.seek_func = &oggSeekCallback;
  156356. callbacks.close_func = &oggCloseCallback;
  156357. callbacks.tell_func = &oggTellCallback;
  156358. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  156359. if (err == 0)
  156360. {
  156361. vorbis_info* info = ov_info (&ovFile, -1);
  156362. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  156363. numChannels = info->channels;
  156364. bitsPerSample = 16;
  156365. sampleRate = info->rate;
  156366. reservoir.setSize (numChannels,
  156367. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  156368. }
  156369. }
  156370. ~OggReader()
  156371. {
  156372. OggVorbisNamespace::ov_clear (&ovFile);
  156373. }
  156374. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  156375. int64 startSampleInFile, int numSamples)
  156376. {
  156377. while (numSamples > 0)
  156378. {
  156379. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  156380. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  156381. {
  156382. // got a few samples overlapping, so use them before seeking..
  156383. const int numToUse = jmin (numSamples, numAvailable);
  156384. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  156385. if (destSamples[i] != 0)
  156386. memcpy (destSamples[i] + startOffsetInDestBuffer,
  156387. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  156388. sizeof (float) * numToUse);
  156389. startSampleInFile += numToUse;
  156390. numSamples -= numToUse;
  156391. startOffsetInDestBuffer += numToUse;
  156392. if (numSamples == 0)
  156393. break;
  156394. }
  156395. if (startSampleInFile < reservoirStart
  156396. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  156397. {
  156398. // buffer miss, so refill the reservoir
  156399. int bitStream = 0;
  156400. reservoirStart = jmax (0, (int) startSampleInFile);
  156401. samplesInReservoir = reservoir.getNumSamples();
  156402. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  156403. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  156404. int offset = 0;
  156405. int numToRead = samplesInReservoir;
  156406. while (numToRead > 0)
  156407. {
  156408. float** dataIn = 0;
  156409. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  156410. if (samps <= 0)
  156411. break;
  156412. jassert (samps <= numToRead);
  156413. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  156414. {
  156415. memcpy (reservoir.getSampleData (i, offset),
  156416. dataIn[i],
  156417. sizeof (float) * samps);
  156418. }
  156419. numToRead -= samps;
  156420. offset += samps;
  156421. }
  156422. if (numToRead > 0)
  156423. reservoir.clear (offset, numToRead);
  156424. }
  156425. }
  156426. if (numSamples > 0)
  156427. {
  156428. for (int i = numDestChannels; --i >= 0;)
  156429. if (destSamples[i] != 0)
  156430. zeromem (destSamples[i] + startOffsetInDestBuffer,
  156431. sizeof (int) * numSamples);
  156432. }
  156433. return true;
  156434. }
  156435. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  156436. {
  156437. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  156438. }
  156439. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  156440. {
  156441. InputStream* const in = static_cast <InputStream*> (datasource);
  156442. if (whence == SEEK_CUR)
  156443. offset += in->getPosition();
  156444. else if (whence == SEEK_END)
  156445. offset += in->getTotalLength();
  156446. in->setPosition (offset);
  156447. return 0;
  156448. }
  156449. static int oggCloseCallback (void*)
  156450. {
  156451. return 0;
  156452. }
  156453. static long oggTellCallback (void* datasource)
  156454. {
  156455. return (long) static_cast <InputStream*> (datasource)->getPosition();
  156456. }
  156457. juce_UseDebuggingNewOperator
  156458. };
  156459. class OggWriter : public AudioFormatWriter
  156460. {
  156461. OggVorbisNamespace::ogg_stream_state os;
  156462. OggVorbisNamespace::ogg_page og;
  156463. OggVorbisNamespace::ogg_packet op;
  156464. OggVorbisNamespace::vorbis_info vi;
  156465. OggVorbisNamespace::vorbis_comment vc;
  156466. OggVorbisNamespace::vorbis_dsp_state vd;
  156467. OggVorbisNamespace::vorbis_block vb;
  156468. public:
  156469. bool ok;
  156470. OggWriter (OutputStream* const out,
  156471. const double sampleRate,
  156472. const int numChannels,
  156473. const int bitsPerSample,
  156474. const int qualityIndex)
  156475. : AudioFormatWriter (out, TRANS (oggFormatName),
  156476. sampleRate,
  156477. numChannels,
  156478. bitsPerSample)
  156479. {
  156480. using namespace OggVorbisNamespace;
  156481. ok = false;
  156482. vorbis_info_init (&vi);
  156483. if (vorbis_encode_init_vbr (&vi,
  156484. numChannels,
  156485. (int) sampleRate,
  156486. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  156487. {
  156488. vorbis_comment_init (&vc);
  156489. if (JUCEApplication::getInstance() != 0)
  156490. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8()));
  156491. vorbis_analysis_init (&vd, &vi);
  156492. vorbis_block_init (&vd, &vb);
  156493. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  156494. ogg_packet header;
  156495. ogg_packet header_comm;
  156496. ogg_packet header_code;
  156497. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  156498. ogg_stream_packetin (&os, &header);
  156499. ogg_stream_packetin (&os, &header_comm);
  156500. ogg_stream_packetin (&os, &header_code);
  156501. for (;;)
  156502. {
  156503. if (ogg_stream_flush (&os, &og) == 0)
  156504. break;
  156505. output->write (og.header, og.header_len);
  156506. output->write (og.body, og.body_len);
  156507. }
  156508. ok = true;
  156509. }
  156510. }
  156511. ~OggWriter()
  156512. {
  156513. using namespace OggVorbisNamespace;
  156514. if (ok)
  156515. {
  156516. // write a zero-length packet to show ogg that we're finished..
  156517. write (0, 0);
  156518. ogg_stream_clear (&os);
  156519. vorbis_block_clear (&vb);
  156520. vorbis_dsp_clear (&vd);
  156521. vorbis_comment_clear (&vc);
  156522. vorbis_info_clear (&vi);
  156523. output->flush();
  156524. }
  156525. else
  156526. {
  156527. vorbis_info_clear (&vi);
  156528. output = 0; // to stop the base class deleting this, as it needs to be returned
  156529. // to the caller of createWriter()
  156530. }
  156531. }
  156532. bool write (const int** samplesToWrite, int numSamples)
  156533. {
  156534. using namespace OggVorbisNamespace;
  156535. if (! ok)
  156536. return false;
  156537. if (numSamples > 0)
  156538. {
  156539. const double gain = 1.0 / 0x80000000u;
  156540. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  156541. for (int i = numChannels; --i >= 0;)
  156542. {
  156543. float* const dst = vorbisBuffer[i];
  156544. const int* const src = samplesToWrite [i];
  156545. if (src != 0 && dst != 0)
  156546. {
  156547. for (int j = 0; j < numSamples; ++j)
  156548. dst[j] = (float) (src[j] * gain);
  156549. }
  156550. }
  156551. }
  156552. vorbis_analysis_wrote (&vd, numSamples);
  156553. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  156554. {
  156555. vorbis_analysis (&vb, 0);
  156556. vorbis_bitrate_addblock (&vb);
  156557. while (vorbis_bitrate_flushpacket (&vd, &op))
  156558. {
  156559. ogg_stream_packetin (&os, &op);
  156560. for (;;)
  156561. {
  156562. if (ogg_stream_pageout (&os, &og) == 0)
  156563. break;
  156564. output->write (og.header, og.header_len);
  156565. output->write (og.body, og.body_len);
  156566. if (ogg_page_eos (&og))
  156567. break;
  156568. }
  156569. }
  156570. }
  156571. return true;
  156572. }
  156573. juce_UseDebuggingNewOperator
  156574. };
  156575. OggVorbisAudioFormat::OggVorbisAudioFormat()
  156576. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  156577. {
  156578. }
  156579. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  156580. {
  156581. }
  156582. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  156583. {
  156584. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  156585. return Array <int> (rates);
  156586. }
  156587. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  156588. {
  156589. Array <int> depths;
  156590. depths.add (32);
  156591. return depths;
  156592. }
  156593. bool OggVorbisAudioFormat::canDoStereo()
  156594. {
  156595. return true;
  156596. }
  156597. bool OggVorbisAudioFormat::canDoMono()
  156598. {
  156599. return true;
  156600. }
  156601. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  156602. const bool deleteStreamIfOpeningFails)
  156603. {
  156604. ScopedPointer <OggReader> r (new OggReader (in));
  156605. if (r->sampleRate != 0)
  156606. return r.release();
  156607. if (! deleteStreamIfOpeningFails)
  156608. r->input = 0;
  156609. return 0;
  156610. }
  156611. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  156612. double sampleRate,
  156613. unsigned int numChannels,
  156614. int bitsPerSample,
  156615. const StringPairArray& /*metadataValues*/,
  156616. int qualityOptionIndex)
  156617. {
  156618. ScopedPointer <OggWriter> w (new OggWriter (out,
  156619. sampleRate,
  156620. numChannels,
  156621. bitsPerSample,
  156622. qualityOptionIndex));
  156623. return w->ok ? w.release() : 0;
  156624. }
  156625. bool OggVorbisAudioFormat::isCompressed()
  156626. {
  156627. return true;
  156628. }
  156629. const StringArray OggVorbisAudioFormat::getQualityOptions()
  156630. {
  156631. StringArray s;
  156632. s.add ("Low Quality");
  156633. s.add ("Medium Quality");
  156634. s.add ("High Quality");
  156635. return s;
  156636. }
  156637. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  156638. {
  156639. FileInputStream* const in = source.createInputStream();
  156640. if (in != 0)
  156641. {
  156642. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  156643. if (r != 0)
  156644. {
  156645. const int64 numSamps = r->lengthInSamples;
  156646. r = 0;
  156647. const int64 fileNumSamps = source.getSize() / 4;
  156648. const double ratio = numSamps / (double) fileNumSamps;
  156649. if (ratio > 12.0)
  156650. return 0;
  156651. else if (ratio > 6.0)
  156652. return 1;
  156653. else
  156654. return 2;
  156655. }
  156656. }
  156657. return 1;
  156658. }
  156659. END_JUCE_NAMESPACE
  156660. #endif
  156661. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  156662. #endif
  156663. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  156664. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  156665. #if JUCE_MSVC
  156666. #pragma warning (push)
  156667. #endif
  156668. namespace jpeglibNamespace
  156669. {
  156670. #if JUCE_INCLUDE_JPEGLIB_CODE
  156671. #if JUCE_MINGW
  156672. typedef unsigned char boolean;
  156673. #endif
  156674. extern "C"
  156675. {
  156676. #define JPEG_INTERNALS
  156677. #undef FAR
  156678. /*** Start of inlined file: jpeglib.h ***/
  156679. #ifndef JPEGLIB_H
  156680. #define JPEGLIB_H
  156681. /*
  156682. * First we include the configuration files that record how this
  156683. * installation of the JPEG library is set up. jconfig.h can be
  156684. * generated automatically for many systems. jmorecfg.h contains
  156685. * manual configuration options that most people need not worry about.
  156686. */
  156687. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  156688. /*** Start of inlined file: jconfig.h ***/
  156689. /* see jconfig.doc for explanations */
  156690. // disable all the warnings under MSVC
  156691. #ifdef _MSC_VER
  156692. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  156693. #endif
  156694. #ifdef __BORLANDC__
  156695. #pragma warn -8057
  156696. #pragma warn -8019
  156697. #pragma warn -8004
  156698. #pragma warn -8008
  156699. #endif
  156700. #define HAVE_PROTOTYPES
  156701. #define HAVE_UNSIGNED_CHAR
  156702. #define HAVE_UNSIGNED_SHORT
  156703. /* #define void char */
  156704. /* #define const */
  156705. #undef CHAR_IS_UNSIGNED
  156706. #define HAVE_STDDEF_H
  156707. #define HAVE_STDLIB_H
  156708. #undef NEED_BSD_STRINGS
  156709. #undef NEED_SYS_TYPES_H
  156710. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  156711. #undef NEED_SHORT_EXTERNAL_NAMES
  156712. #undef INCOMPLETE_TYPES_BROKEN
  156713. /* Define "boolean" as unsigned char, not int, per Windows custom */
  156714. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  156715. typedef unsigned char boolean;
  156716. #endif
  156717. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  156718. #ifdef JPEG_INTERNALS
  156719. #undef RIGHT_SHIFT_IS_UNSIGNED
  156720. #endif /* JPEG_INTERNALS */
  156721. #ifdef JPEG_CJPEG_DJPEG
  156722. #define BMP_SUPPORTED /* BMP image file format */
  156723. #define GIF_SUPPORTED /* GIF image file format */
  156724. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  156725. #undef RLE_SUPPORTED /* Utah RLE image file format */
  156726. #define TARGA_SUPPORTED /* Targa image file format */
  156727. #define TWO_FILE_COMMANDLINE /* optional */
  156728. #define USE_SETMODE /* Microsoft has setmode() */
  156729. #undef NEED_SIGNAL_CATCHER
  156730. #undef DONT_USE_B_MODE
  156731. #undef PROGRESS_REPORT /* optional */
  156732. #endif /* JPEG_CJPEG_DJPEG */
  156733. /*** End of inlined file: jconfig.h ***/
  156734. /* widely used configuration options */
  156735. #endif
  156736. /*** Start of inlined file: jmorecfg.h ***/
  156737. /*
  156738. * Define BITS_IN_JSAMPLE as either
  156739. * 8 for 8-bit sample values (the usual setting)
  156740. * 12 for 12-bit sample values
  156741. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  156742. * JPEG standard, and the IJG code does not support anything else!
  156743. * We do not support run-time selection of data precision, sorry.
  156744. */
  156745. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  156746. /*
  156747. * Maximum number of components (color channels) allowed in JPEG image.
  156748. * To meet the letter of the JPEG spec, set this to 255. However, darn
  156749. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  156750. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  156751. * really short on memory. (Each allowed component costs a hundred or so
  156752. * bytes of storage, whether actually used in an image or not.)
  156753. */
  156754. #define MAX_COMPONENTS 10 /* maximum number of image components */
  156755. /*
  156756. * Basic data types.
  156757. * You may need to change these if you have a machine with unusual data
  156758. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  156759. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  156760. * but it had better be at least 16.
  156761. */
  156762. /* Representation of a single sample (pixel element value).
  156763. * We frequently allocate large arrays of these, so it's important to keep
  156764. * them small. But if you have memory to burn and access to char or short
  156765. * arrays is very slow on your hardware, you might want to change these.
  156766. */
  156767. #if BITS_IN_JSAMPLE == 8
  156768. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  156769. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  156770. */
  156771. #ifdef HAVE_UNSIGNED_CHAR
  156772. typedef unsigned char JSAMPLE;
  156773. #define GETJSAMPLE(value) ((int) (value))
  156774. #else /* not HAVE_UNSIGNED_CHAR */
  156775. typedef char JSAMPLE;
  156776. #ifdef CHAR_IS_UNSIGNED
  156777. #define GETJSAMPLE(value) ((int) (value))
  156778. #else
  156779. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  156780. #endif /* CHAR_IS_UNSIGNED */
  156781. #endif /* HAVE_UNSIGNED_CHAR */
  156782. #define MAXJSAMPLE 255
  156783. #define CENTERJSAMPLE 128
  156784. #endif /* BITS_IN_JSAMPLE == 8 */
  156785. #if BITS_IN_JSAMPLE == 12
  156786. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  156787. * On nearly all machines "short" will do nicely.
  156788. */
  156789. typedef short JSAMPLE;
  156790. #define GETJSAMPLE(value) ((int) (value))
  156791. #define MAXJSAMPLE 4095
  156792. #define CENTERJSAMPLE 2048
  156793. #endif /* BITS_IN_JSAMPLE == 12 */
  156794. /* Representation of a DCT frequency coefficient.
  156795. * This should be a signed value of at least 16 bits; "short" is usually OK.
  156796. * Again, we allocate large arrays of these, but you can change to int
  156797. * if you have memory to burn and "short" is really slow.
  156798. */
  156799. typedef short JCOEF;
  156800. /* Compressed datastreams are represented as arrays of JOCTET.
  156801. * These must be EXACTLY 8 bits wide, at least once they are written to
  156802. * external storage. Note that when using the stdio data source/destination
  156803. * managers, this is also the data type passed to fread/fwrite.
  156804. */
  156805. #ifdef HAVE_UNSIGNED_CHAR
  156806. typedef unsigned char JOCTET;
  156807. #define GETJOCTET(value) (value)
  156808. #else /* not HAVE_UNSIGNED_CHAR */
  156809. typedef char JOCTET;
  156810. #ifdef CHAR_IS_UNSIGNED
  156811. #define GETJOCTET(value) (value)
  156812. #else
  156813. #define GETJOCTET(value) ((value) & 0xFF)
  156814. #endif /* CHAR_IS_UNSIGNED */
  156815. #endif /* HAVE_UNSIGNED_CHAR */
  156816. /* These typedefs are used for various table entries and so forth.
  156817. * They must be at least as wide as specified; but making them too big
  156818. * won't cost a huge amount of memory, so we don't provide special
  156819. * extraction code like we did for JSAMPLE. (In other words, these
  156820. * typedefs live at a different point on the speed/space tradeoff curve.)
  156821. */
  156822. /* UINT8 must hold at least the values 0..255. */
  156823. #ifdef HAVE_UNSIGNED_CHAR
  156824. typedef unsigned char UINT8;
  156825. #else /* not HAVE_UNSIGNED_CHAR */
  156826. #ifdef CHAR_IS_UNSIGNED
  156827. typedef char UINT8;
  156828. #else /* not CHAR_IS_UNSIGNED */
  156829. typedef short UINT8;
  156830. #endif /* CHAR_IS_UNSIGNED */
  156831. #endif /* HAVE_UNSIGNED_CHAR */
  156832. /* UINT16 must hold at least the values 0..65535. */
  156833. #ifdef HAVE_UNSIGNED_SHORT
  156834. typedef unsigned short UINT16;
  156835. #else /* not HAVE_UNSIGNED_SHORT */
  156836. typedef unsigned int UINT16;
  156837. #endif /* HAVE_UNSIGNED_SHORT */
  156838. /* INT16 must hold at least the values -32768..32767. */
  156839. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  156840. typedef short INT16;
  156841. #endif
  156842. /* INT32 must hold at least signed 32-bit values. */
  156843. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  156844. typedef long INT32;
  156845. #endif
  156846. /* Datatype used for image dimensions. The JPEG standard only supports
  156847. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  156848. * "unsigned int" is sufficient on all machines. However, if you need to
  156849. * handle larger images and you don't mind deviating from the spec, you
  156850. * can change this datatype.
  156851. */
  156852. typedef unsigned int JDIMENSION;
  156853. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  156854. /* These macros are used in all function definitions and extern declarations.
  156855. * You could modify them if you need to change function linkage conventions;
  156856. * in particular, you'll need to do that to make the library a Windows DLL.
  156857. * Another application is to make all functions global for use with debuggers
  156858. * or code profilers that require it.
  156859. */
  156860. /* a function called through method pointers: */
  156861. #define METHODDEF(type) static type
  156862. /* a function used only in its module: */
  156863. #define LOCAL(type) static type
  156864. /* a function referenced thru EXTERNs: */
  156865. #define GLOBAL(type) type
  156866. /* a reference to a GLOBAL function: */
  156867. #define EXTERN(type) extern type
  156868. /* This macro is used to declare a "method", that is, a function pointer.
  156869. * We want to supply prototype parameters if the compiler can cope.
  156870. * Note that the arglist parameter must be parenthesized!
  156871. * Again, you can customize this if you need special linkage keywords.
  156872. */
  156873. #ifdef HAVE_PROTOTYPES
  156874. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  156875. #else
  156876. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  156877. #endif
  156878. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  156879. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  156880. * by just saying "FAR *" where such a pointer is needed. In a few places
  156881. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  156882. */
  156883. #ifdef NEED_FAR_POINTERS
  156884. #define FAR far
  156885. #else
  156886. #define FAR
  156887. #endif
  156888. /*
  156889. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  156890. * in standard header files. Or you may have conflicts with application-
  156891. * specific header files that you want to include together with these files.
  156892. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  156893. */
  156894. #ifndef HAVE_BOOLEAN
  156895. typedef int boolean;
  156896. #endif
  156897. #ifndef FALSE /* in case these macros already exist */
  156898. #define FALSE 0 /* values of boolean */
  156899. #endif
  156900. #ifndef TRUE
  156901. #define TRUE 1
  156902. #endif
  156903. /*
  156904. * The remaining options affect code selection within the JPEG library,
  156905. * but they don't need to be visible to most applications using the library.
  156906. * To minimize application namespace pollution, the symbols won't be
  156907. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  156908. */
  156909. #ifdef JPEG_INTERNALS
  156910. #define JPEG_INTERNAL_OPTIONS
  156911. #endif
  156912. #ifdef JPEG_INTERNAL_OPTIONS
  156913. /*
  156914. * These defines indicate whether to include various optional functions.
  156915. * Undefining some of these symbols will produce a smaller but less capable
  156916. * library. Note that you can leave certain source files out of the
  156917. * compilation/linking process if you've #undef'd the corresponding symbols.
  156918. * (You may HAVE to do that if your compiler doesn't like null source files.)
  156919. */
  156920. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  156921. /* Capability options common to encoder and decoder: */
  156922. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  156923. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  156924. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  156925. /* Encoder capability options: */
  156926. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  156927. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  156928. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  156929. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  156930. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  156931. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  156932. * precision, so jchuff.c normally uses entropy optimization to compute
  156933. * usable tables for higher precision. If you don't want to do optimization,
  156934. * you'll have to supply different default Huffman tables.
  156935. * The exact same statements apply for progressive JPEG: the default tables
  156936. * don't work for progressive mode. (This may get fixed, however.)
  156937. */
  156938. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  156939. /* Decoder capability options: */
  156940. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  156941. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  156942. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  156943. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  156944. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  156945. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  156946. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  156947. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  156948. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  156949. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  156950. /* more capability options later, no doubt */
  156951. /*
  156952. * Ordering of RGB data in scanlines passed to or from the application.
  156953. * If your application wants to deal with data in the order B,G,R, just
  156954. * change these macros. You can also deal with formats such as R,G,B,X
  156955. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  156956. * the offsets will also change the order in which colormap data is organized.
  156957. * RESTRICTIONS:
  156958. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  156959. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  156960. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  156961. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  156962. * is not 3 (they don't understand about dummy color components!). So you
  156963. * can't use color quantization if you change that value.
  156964. */
  156965. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  156966. #define RGB_GREEN 1 /* Offset of Green */
  156967. #define RGB_BLUE 2 /* Offset of Blue */
  156968. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  156969. /* Definitions for speed-related optimizations. */
  156970. /* If your compiler supports inline functions, define INLINE
  156971. * as the inline keyword; otherwise define it as empty.
  156972. */
  156973. #ifndef INLINE
  156974. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  156975. #define INLINE __inline__
  156976. #endif
  156977. #ifndef INLINE
  156978. #define INLINE /* default is to define it as empty */
  156979. #endif
  156980. #endif
  156981. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  156982. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  156983. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  156984. */
  156985. #ifndef MULTIPLIER
  156986. #define MULTIPLIER int /* type for fastest integer multiply */
  156987. #endif
  156988. /* FAST_FLOAT should be either float or double, whichever is done faster
  156989. * by your compiler. (Note that this type is only used in the floating point
  156990. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  156991. * Typically, float is faster in ANSI C compilers, while double is faster in
  156992. * pre-ANSI compilers (because they insist on converting to double anyway).
  156993. * The code below therefore chooses float if we have ANSI-style prototypes.
  156994. */
  156995. #ifndef FAST_FLOAT
  156996. #ifdef HAVE_PROTOTYPES
  156997. #define FAST_FLOAT float
  156998. #else
  156999. #define FAST_FLOAT double
  157000. #endif
  157001. #endif
  157002. #endif /* JPEG_INTERNAL_OPTIONS */
  157003. /*** End of inlined file: jmorecfg.h ***/
  157004. /* seldom changed options */
  157005. /* Version ID for the JPEG library.
  157006. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  157007. */
  157008. #define JPEG_LIB_VERSION 62 /* Version 6b */
  157009. /* Various constants determining the sizes of things.
  157010. * All of these are specified by the JPEG standard, so don't change them
  157011. * if you want to be compatible.
  157012. */
  157013. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  157014. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  157015. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  157016. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  157017. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  157018. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  157019. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  157020. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  157021. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  157022. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  157023. * to handle it. We even let you do this from the jconfig.h file. However,
  157024. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  157025. * sometimes emits noncompliant files doesn't mean you should too.
  157026. */
  157027. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  157028. #ifndef D_MAX_BLOCKS_IN_MCU
  157029. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  157030. #endif
  157031. /* Data structures for images (arrays of samples and of DCT coefficients).
  157032. * On 80x86 machines, the image arrays are too big for near pointers,
  157033. * but the pointer arrays can fit in near memory.
  157034. */
  157035. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  157036. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  157037. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  157038. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  157039. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  157040. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  157041. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  157042. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  157043. /* Types for JPEG compression parameters and working tables. */
  157044. /* DCT coefficient quantization tables. */
  157045. typedef struct {
  157046. /* This array gives the coefficient quantizers in natural array order
  157047. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  157048. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  157049. */
  157050. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  157051. /* This field is used only during compression. It's initialized FALSE when
  157052. * the table is created, and set TRUE when it's been output to the file.
  157053. * You could suppress output of a table by setting this to TRUE.
  157054. * (See jpeg_suppress_tables for an example.)
  157055. */
  157056. boolean sent_table; /* TRUE when table has been output */
  157057. } JQUANT_TBL;
  157058. /* Huffman coding tables. */
  157059. typedef struct {
  157060. /* These two fields directly represent the contents of a JPEG DHT marker */
  157061. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  157062. /* length k bits; bits[0] is unused */
  157063. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  157064. /* This field is used only during compression. It's initialized FALSE when
  157065. * the table is created, and set TRUE when it's been output to the file.
  157066. * You could suppress output of a table by setting this to TRUE.
  157067. * (See jpeg_suppress_tables for an example.)
  157068. */
  157069. boolean sent_table; /* TRUE when table has been output */
  157070. } JHUFF_TBL;
  157071. /* Basic info about one component (color channel). */
  157072. typedef struct {
  157073. /* These values are fixed over the whole image. */
  157074. /* For compression, they must be supplied by parameter setup; */
  157075. /* for decompression, they are read from the SOF marker. */
  157076. int component_id; /* identifier for this component (0..255) */
  157077. int component_index; /* its index in SOF or cinfo->comp_info[] */
  157078. int h_samp_factor; /* horizontal sampling factor (1..4) */
  157079. int v_samp_factor; /* vertical sampling factor (1..4) */
  157080. int quant_tbl_no; /* quantization table selector (0..3) */
  157081. /* These values may vary between scans. */
  157082. /* For compression, they must be supplied by parameter setup; */
  157083. /* for decompression, they are read from the SOS marker. */
  157084. /* The decompressor output side may not use these variables. */
  157085. int dc_tbl_no; /* DC entropy table selector (0..3) */
  157086. int ac_tbl_no; /* AC entropy table selector (0..3) */
  157087. /* Remaining fields should be treated as private by applications. */
  157088. /* These values are computed during compression or decompression startup: */
  157089. /* Component's size in DCT blocks.
  157090. * Any dummy blocks added to complete an MCU are not counted; therefore
  157091. * these values do not depend on whether a scan is interleaved or not.
  157092. */
  157093. JDIMENSION width_in_blocks;
  157094. JDIMENSION height_in_blocks;
  157095. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  157096. * For decompression this is the size of the output from one DCT block,
  157097. * reflecting any scaling we choose to apply during the IDCT step.
  157098. * Values of 1,2,4,8 are likely to be supported. Note that different
  157099. * components may receive different IDCT scalings.
  157100. */
  157101. int DCT_scaled_size;
  157102. /* The downsampled dimensions are the component's actual, unpadded number
  157103. * of samples at the main buffer (preprocessing/compression interface), thus
  157104. * downsampled_width = ceil(image_width * Hi/Hmax)
  157105. * and similarly for height. For decompression, IDCT scaling is included, so
  157106. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  157107. */
  157108. JDIMENSION downsampled_width; /* actual width in samples */
  157109. JDIMENSION downsampled_height; /* actual height in samples */
  157110. /* This flag is used only for decompression. In cases where some of the
  157111. * components will be ignored (eg grayscale output from YCbCr image),
  157112. * we can skip most computations for the unused components.
  157113. */
  157114. boolean component_needed; /* do we need the value of this component? */
  157115. /* These values are computed before starting a scan of the component. */
  157116. /* The decompressor output side may not use these variables. */
  157117. int MCU_width; /* number of blocks per MCU, horizontally */
  157118. int MCU_height; /* number of blocks per MCU, vertically */
  157119. int MCU_blocks; /* MCU_width * MCU_height */
  157120. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  157121. int last_col_width; /* # of non-dummy blocks across in last MCU */
  157122. int last_row_height; /* # of non-dummy blocks down in last MCU */
  157123. /* Saved quantization table for component; NULL if none yet saved.
  157124. * See jdinput.c comments about the need for this information.
  157125. * This field is currently used only for decompression.
  157126. */
  157127. JQUANT_TBL * quant_table;
  157128. /* Private per-component storage for DCT or IDCT subsystem. */
  157129. void * dct_table;
  157130. } jpeg_component_info;
  157131. /* The script for encoding a multiple-scan file is an array of these: */
  157132. typedef struct {
  157133. int comps_in_scan; /* number of components encoded in this scan */
  157134. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  157135. int Ss, Se; /* progressive JPEG spectral selection parms */
  157136. int Ah, Al; /* progressive JPEG successive approx. parms */
  157137. } jpeg_scan_info;
  157138. /* The decompressor can save APPn and COM markers in a list of these: */
  157139. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  157140. struct jpeg_marker_struct {
  157141. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  157142. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  157143. unsigned int original_length; /* # bytes of data in the file */
  157144. unsigned int data_length; /* # bytes of data saved at data[] */
  157145. JOCTET FAR * data; /* the data contained in the marker */
  157146. /* the marker length word is not counted in data_length or original_length */
  157147. };
  157148. /* Known color spaces. */
  157149. typedef enum {
  157150. JCS_UNKNOWN, /* error/unspecified */
  157151. JCS_GRAYSCALE, /* monochrome */
  157152. JCS_RGB, /* red/green/blue */
  157153. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  157154. JCS_CMYK, /* C/M/Y/K */
  157155. JCS_YCCK /* Y/Cb/Cr/K */
  157156. } J_COLOR_SPACE;
  157157. /* DCT/IDCT algorithm options. */
  157158. typedef enum {
  157159. JDCT_ISLOW, /* slow but accurate integer algorithm */
  157160. JDCT_IFAST, /* faster, less accurate integer method */
  157161. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  157162. } J_DCT_METHOD;
  157163. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  157164. #define JDCT_DEFAULT JDCT_ISLOW
  157165. #endif
  157166. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  157167. #define JDCT_FASTEST JDCT_IFAST
  157168. #endif
  157169. /* Dithering options for decompression. */
  157170. typedef enum {
  157171. JDITHER_NONE, /* no dithering */
  157172. JDITHER_ORDERED, /* simple ordered dither */
  157173. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  157174. } J_DITHER_MODE;
  157175. /* Common fields between JPEG compression and decompression master structs. */
  157176. #define jpeg_common_fields \
  157177. struct jpeg_error_mgr * err; /* Error handler module */\
  157178. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  157179. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  157180. void * client_data; /* Available for use by application */\
  157181. boolean is_decompressor; /* So common code can tell which is which */\
  157182. int global_state /* For checking call sequence validity */
  157183. /* Routines that are to be used by both halves of the library are declared
  157184. * to receive a pointer to this structure. There are no actual instances of
  157185. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  157186. */
  157187. struct jpeg_common_struct {
  157188. jpeg_common_fields; /* Fields common to both master struct types */
  157189. /* Additional fields follow in an actual jpeg_compress_struct or
  157190. * jpeg_decompress_struct. All three structs must agree on these
  157191. * initial fields! (This would be a lot cleaner in C++.)
  157192. */
  157193. };
  157194. typedef struct jpeg_common_struct * j_common_ptr;
  157195. typedef struct jpeg_compress_struct * j_compress_ptr;
  157196. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  157197. /* Master record for a compression instance */
  157198. struct jpeg_compress_struct {
  157199. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  157200. /* Destination for compressed data */
  157201. struct jpeg_destination_mgr * dest;
  157202. /* Description of source image --- these fields must be filled in by
  157203. * outer application before starting compression. in_color_space must
  157204. * be correct before you can even call jpeg_set_defaults().
  157205. */
  157206. JDIMENSION image_width; /* input image width */
  157207. JDIMENSION image_height; /* input image height */
  157208. int input_components; /* # of color components in input image */
  157209. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  157210. double input_gamma; /* image gamma of input image */
  157211. /* Compression parameters --- these fields must be set before calling
  157212. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  157213. * initialize everything to reasonable defaults, then changing anything
  157214. * the application specifically wants to change. That way you won't get
  157215. * burnt when new parameters are added. Also note that there are several
  157216. * helper routines to simplify changing parameters.
  157217. */
  157218. int data_precision; /* bits of precision in image data */
  157219. int num_components; /* # of color components in JPEG image */
  157220. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  157221. jpeg_component_info * comp_info;
  157222. /* comp_info[i] describes component that appears i'th in SOF */
  157223. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  157224. /* ptrs to coefficient quantization tables, or NULL if not defined */
  157225. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  157226. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  157227. /* ptrs to Huffman coding tables, or NULL if not defined */
  157228. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  157229. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  157230. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  157231. int num_scans; /* # of entries in scan_info array */
  157232. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  157233. /* The default value of scan_info is NULL, which causes a single-scan
  157234. * sequential JPEG file to be emitted. To create a multi-scan file,
  157235. * set num_scans and scan_info to point to an array of scan definitions.
  157236. */
  157237. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  157238. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  157239. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  157240. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  157241. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  157242. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  157243. /* The restart interval can be specified in absolute MCUs by setting
  157244. * restart_interval, or in MCU rows by setting restart_in_rows
  157245. * (in which case the correct restart_interval will be figured
  157246. * for each scan).
  157247. */
  157248. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  157249. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  157250. /* Parameters controlling emission of special markers. */
  157251. boolean write_JFIF_header; /* should a JFIF marker be written? */
  157252. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  157253. UINT8 JFIF_minor_version;
  157254. /* These three values are not used by the JPEG code, merely copied */
  157255. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  157256. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  157257. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  157258. UINT8 density_unit; /* JFIF code for pixel size units */
  157259. UINT16 X_density; /* Horizontal pixel density */
  157260. UINT16 Y_density; /* Vertical pixel density */
  157261. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  157262. /* State variable: index of next scanline to be written to
  157263. * jpeg_write_scanlines(). Application may use this to control its
  157264. * processing loop, e.g., "while (next_scanline < image_height)".
  157265. */
  157266. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  157267. /* Remaining fields are known throughout compressor, but generally
  157268. * should not be touched by a surrounding application.
  157269. */
  157270. /*
  157271. * These fields are computed during compression startup
  157272. */
  157273. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  157274. int max_h_samp_factor; /* largest h_samp_factor */
  157275. int max_v_samp_factor; /* largest v_samp_factor */
  157276. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  157277. /* The coefficient controller receives data in units of MCU rows as defined
  157278. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  157279. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  157280. * "iMCU" (interleaved MCU) row.
  157281. */
  157282. /*
  157283. * These fields are valid during any one scan.
  157284. * They describe the components and MCUs actually appearing in the scan.
  157285. */
  157286. int comps_in_scan; /* # of JPEG components in this scan */
  157287. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  157288. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  157289. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  157290. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  157291. int blocks_in_MCU; /* # of DCT blocks per MCU */
  157292. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  157293. /* MCU_membership[i] is index in cur_comp_info of component owning */
  157294. /* i'th block in an MCU */
  157295. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  157296. /*
  157297. * Links to compression subobjects (methods and private variables of modules)
  157298. */
  157299. struct jpeg_comp_master * master;
  157300. struct jpeg_c_main_controller * main;
  157301. struct jpeg_c_prep_controller * prep;
  157302. struct jpeg_c_coef_controller * coef;
  157303. struct jpeg_marker_writer * marker;
  157304. struct jpeg_color_converter * cconvert;
  157305. struct jpeg_downsampler * downsample;
  157306. struct jpeg_forward_dct * fdct;
  157307. struct jpeg_entropy_encoder * entropy;
  157308. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  157309. int script_space_size;
  157310. };
  157311. /* Master record for a decompression instance */
  157312. struct jpeg_decompress_struct {
  157313. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  157314. /* Source of compressed data */
  157315. struct jpeg_source_mgr * src;
  157316. /* Basic description of image --- filled in by jpeg_read_header(). */
  157317. /* Application may inspect these values to decide how to process image. */
  157318. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  157319. JDIMENSION image_height; /* nominal image height */
  157320. int num_components; /* # of color components in JPEG image */
  157321. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  157322. /* Decompression processing parameters --- these fields must be set before
  157323. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  157324. * them to default values.
  157325. */
  157326. J_COLOR_SPACE out_color_space; /* colorspace for output */
  157327. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  157328. double output_gamma; /* image gamma wanted in output */
  157329. boolean buffered_image; /* TRUE=multiple output passes */
  157330. boolean raw_data_out; /* TRUE=downsampled data wanted */
  157331. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  157332. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  157333. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  157334. boolean quantize_colors; /* TRUE=colormapped output wanted */
  157335. /* the following are ignored if not quantize_colors: */
  157336. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  157337. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  157338. int desired_number_of_colors; /* max # colors to use in created colormap */
  157339. /* these are significant only in buffered-image mode: */
  157340. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  157341. boolean enable_external_quant;/* enable future use of external colormap */
  157342. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  157343. /* Description of actual output image that will be returned to application.
  157344. * These fields are computed by jpeg_start_decompress().
  157345. * You can also use jpeg_calc_output_dimensions() to determine these values
  157346. * in advance of calling jpeg_start_decompress().
  157347. */
  157348. JDIMENSION output_width; /* scaled image width */
  157349. JDIMENSION output_height; /* scaled image height */
  157350. int out_color_components; /* # of color components in out_color_space */
  157351. int output_components; /* # of color components returned */
  157352. /* output_components is 1 (a colormap index) when quantizing colors;
  157353. * otherwise it equals out_color_components.
  157354. */
  157355. int rec_outbuf_height; /* min recommended height of scanline buffer */
  157356. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  157357. * high, space and time will be wasted due to unnecessary data copying.
  157358. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  157359. */
  157360. /* When quantizing colors, the output colormap is described by these fields.
  157361. * The application can supply a colormap by setting colormap non-NULL before
  157362. * calling jpeg_start_decompress; otherwise a colormap is created during
  157363. * jpeg_start_decompress or jpeg_start_output.
  157364. * The map has out_color_components rows and actual_number_of_colors columns.
  157365. */
  157366. int actual_number_of_colors; /* number of entries in use */
  157367. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  157368. /* State variables: these variables indicate the progress of decompression.
  157369. * The application may examine these but must not modify them.
  157370. */
  157371. /* Row index of next scanline to be read from jpeg_read_scanlines().
  157372. * Application may use this to control its processing loop, e.g.,
  157373. * "while (output_scanline < output_height)".
  157374. */
  157375. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  157376. /* Current input scan number and number of iMCU rows completed in scan.
  157377. * These indicate the progress of the decompressor input side.
  157378. */
  157379. int input_scan_number; /* Number of SOS markers seen so far */
  157380. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  157381. /* The "output scan number" is the notional scan being displayed by the
  157382. * output side. The decompressor will not allow output scan/row number
  157383. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  157384. */
  157385. int output_scan_number; /* Nominal scan number being displayed */
  157386. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  157387. /* Current progression status. coef_bits[c][i] indicates the precision
  157388. * with which component c's DCT coefficient i (in zigzag order) is known.
  157389. * It is -1 when no data has yet been received, otherwise it is the point
  157390. * transform (shift) value for the most recent scan of the coefficient
  157391. * (thus, 0 at completion of the progression).
  157392. * This pointer is NULL when reading a non-progressive file.
  157393. */
  157394. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  157395. /* Internal JPEG parameters --- the application usually need not look at
  157396. * these fields. Note that the decompressor output side may not use
  157397. * any parameters that can change between scans.
  157398. */
  157399. /* Quantization and Huffman tables are carried forward across input
  157400. * datastreams when processing abbreviated JPEG datastreams.
  157401. */
  157402. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  157403. /* ptrs to coefficient quantization tables, or NULL if not defined */
  157404. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  157405. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  157406. /* ptrs to Huffman coding tables, or NULL if not defined */
  157407. /* These parameters are never carried across datastreams, since they
  157408. * are given in SOF/SOS markers or defined to be reset by SOI.
  157409. */
  157410. int data_precision; /* bits of precision in image data */
  157411. jpeg_component_info * comp_info;
  157412. /* comp_info[i] describes component that appears i'th in SOF */
  157413. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  157414. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  157415. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  157416. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  157417. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  157418. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  157419. /* These fields record data obtained from optional markers recognized by
  157420. * the JPEG library.
  157421. */
  157422. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  157423. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  157424. UINT8 JFIF_major_version; /* JFIF version number */
  157425. UINT8 JFIF_minor_version;
  157426. UINT8 density_unit; /* JFIF code for pixel size units */
  157427. UINT16 X_density; /* Horizontal pixel density */
  157428. UINT16 Y_density; /* Vertical pixel density */
  157429. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  157430. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  157431. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  157432. /* Aside from the specific data retained from APPn markers known to the
  157433. * library, the uninterpreted contents of any or all APPn and COM markers
  157434. * can be saved in a list for examination by the application.
  157435. */
  157436. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  157437. /* Remaining fields are known throughout decompressor, but generally
  157438. * should not be touched by a surrounding application.
  157439. */
  157440. /*
  157441. * These fields are computed during decompression startup
  157442. */
  157443. int max_h_samp_factor; /* largest h_samp_factor */
  157444. int max_v_samp_factor; /* largest v_samp_factor */
  157445. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  157446. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  157447. /* The coefficient controller's input and output progress is measured in
  157448. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  157449. * in fully interleaved JPEG scans, but are used whether the scan is
  157450. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  157451. * rows of each component. Therefore, the IDCT output contains
  157452. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  157453. */
  157454. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  157455. /*
  157456. * These fields are valid during any one scan.
  157457. * They describe the components and MCUs actually appearing in the scan.
  157458. * Note that the decompressor output side must not use these fields.
  157459. */
  157460. int comps_in_scan; /* # of JPEG components in this scan */
  157461. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  157462. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  157463. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  157464. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  157465. int blocks_in_MCU; /* # of DCT blocks per MCU */
  157466. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  157467. /* MCU_membership[i] is index in cur_comp_info of component owning */
  157468. /* i'th block in an MCU */
  157469. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  157470. /* This field is shared between entropy decoder and marker parser.
  157471. * It is either zero or the code of a JPEG marker that has been
  157472. * read from the data source, but has not yet been processed.
  157473. */
  157474. int unread_marker;
  157475. /*
  157476. * Links to decompression subobjects (methods, private variables of modules)
  157477. */
  157478. struct jpeg_decomp_master * master;
  157479. struct jpeg_d_main_controller * main;
  157480. struct jpeg_d_coef_controller * coef;
  157481. struct jpeg_d_post_controller * post;
  157482. struct jpeg_input_controller * inputctl;
  157483. struct jpeg_marker_reader * marker;
  157484. struct jpeg_entropy_decoder * entropy;
  157485. struct jpeg_inverse_dct * idct;
  157486. struct jpeg_upsampler * upsample;
  157487. struct jpeg_color_deconverter * cconvert;
  157488. struct jpeg_color_quantizer * cquantize;
  157489. };
  157490. /* "Object" declarations for JPEG modules that may be supplied or called
  157491. * directly by the surrounding application.
  157492. * As with all objects in the JPEG library, these structs only define the
  157493. * publicly visible methods and state variables of a module. Additional
  157494. * private fields may exist after the public ones.
  157495. */
  157496. /* Error handler object */
  157497. struct jpeg_error_mgr {
  157498. /* Error exit handler: does not return to caller */
  157499. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  157500. /* Conditionally emit a trace or warning message */
  157501. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  157502. /* Routine that actually outputs a trace or error message */
  157503. JMETHOD(void, output_message, (j_common_ptr cinfo));
  157504. /* Format a message string for the most recent JPEG error or message */
  157505. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  157506. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  157507. /* Reset error state variables at start of a new image */
  157508. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  157509. /* The message ID code and any parameters are saved here.
  157510. * A message can have one string parameter or up to 8 int parameters.
  157511. */
  157512. int msg_code;
  157513. #define JMSG_STR_PARM_MAX 80
  157514. union {
  157515. int i[8];
  157516. char s[JMSG_STR_PARM_MAX];
  157517. } msg_parm;
  157518. /* Standard state variables for error facility */
  157519. int trace_level; /* max msg_level that will be displayed */
  157520. /* For recoverable corrupt-data errors, we emit a warning message,
  157521. * but keep going unless emit_message chooses to abort. emit_message
  157522. * should count warnings in num_warnings. The surrounding application
  157523. * can check for bad data by seeing if num_warnings is nonzero at the
  157524. * end of processing.
  157525. */
  157526. long num_warnings; /* number of corrupt-data warnings */
  157527. /* These fields point to the table(s) of error message strings.
  157528. * An application can change the table pointer to switch to a different
  157529. * message list (typically, to change the language in which errors are
  157530. * reported). Some applications may wish to add additional error codes
  157531. * that will be handled by the JPEG library error mechanism; the second
  157532. * table pointer is used for this purpose.
  157533. *
  157534. * First table includes all errors generated by JPEG library itself.
  157535. * Error code 0 is reserved for a "no such error string" message.
  157536. */
  157537. const char * const * jpeg_message_table; /* Library errors */
  157538. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  157539. /* Second table can be added by application (see cjpeg/djpeg for example).
  157540. * It contains strings numbered first_addon_message..last_addon_message.
  157541. */
  157542. const char * const * addon_message_table; /* Non-library errors */
  157543. int first_addon_message; /* code for first string in addon table */
  157544. int last_addon_message; /* code for last string in addon table */
  157545. };
  157546. /* Progress monitor object */
  157547. struct jpeg_progress_mgr {
  157548. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  157549. long pass_counter; /* work units completed in this pass */
  157550. long pass_limit; /* total number of work units in this pass */
  157551. int completed_passes; /* passes completed so far */
  157552. int total_passes; /* total number of passes expected */
  157553. };
  157554. /* Data destination object for compression */
  157555. struct jpeg_destination_mgr {
  157556. JOCTET * next_output_byte; /* => next byte to write in buffer */
  157557. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  157558. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  157559. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  157560. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  157561. };
  157562. /* Data source object for decompression */
  157563. struct jpeg_source_mgr {
  157564. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  157565. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  157566. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  157567. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  157568. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  157569. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  157570. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  157571. };
  157572. /* Memory manager object.
  157573. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  157574. * and "really big" objects (virtual arrays with backing store if needed).
  157575. * The memory manager does not allow individual objects to be freed; rather,
  157576. * each created object is assigned to a pool, and whole pools can be freed
  157577. * at once. This is faster and more convenient than remembering exactly what
  157578. * to free, especially where malloc()/free() are not too speedy.
  157579. * NB: alloc routines never return NULL. They exit to error_exit if not
  157580. * successful.
  157581. */
  157582. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  157583. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  157584. #define JPOOL_NUMPOOLS 2
  157585. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  157586. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  157587. struct jpeg_memory_mgr {
  157588. /* Method pointers */
  157589. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  157590. size_t sizeofobject));
  157591. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  157592. size_t sizeofobject));
  157593. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  157594. JDIMENSION samplesperrow,
  157595. JDIMENSION numrows));
  157596. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  157597. JDIMENSION blocksperrow,
  157598. JDIMENSION numrows));
  157599. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  157600. int pool_id,
  157601. boolean pre_zero,
  157602. JDIMENSION samplesperrow,
  157603. JDIMENSION numrows,
  157604. JDIMENSION maxaccess));
  157605. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  157606. int pool_id,
  157607. boolean pre_zero,
  157608. JDIMENSION blocksperrow,
  157609. JDIMENSION numrows,
  157610. JDIMENSION maxaccess));
  157611. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  157612. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  157613. jvirt_sarray_ptr ptr,
  157614. JDIMENSION start_row,
  157615. JDIMENSION num_rows,
  157616. boolean writable));
  157617. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  157618. jvirt_barray_ptr ptr,
  157619. JDIMENSION start_row,
  157620. JDIMENSION num_rows,
  157621. boolean writable));
  157622. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  157623. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  157624. /* Limit on memory allocation for this JPEG object. (Note that this is
  157625. * merely advisory, not a guaranteed maximum; it only affects the space
  157626. * used for virtual-array buffers.) May be changed by outer application
  157627. * after creating the JPEG object.
  157628. */
  157629. long max_memory_to_use;
  157630. /* Maximum allocation request accepted by alloc_large. */
  157631. long max_alloc_chunk;
  157632. };
  157633. /* Routine signature for application-supplied marker processing methods.
  157634. * Need not pass marker code since it is stored in cinfo->unread_marker.
  157635. */
  157636. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  157637. /* Declarations for routines called by application.
  157638. * The JPP macro hides prototype parameters from compilers that can't cope.
  157639. * Note JPP requires double parentheses.
  157640. */
  157641. #ifdef HAVE_PROTOTYPES
  157642. #define JPP(arglist) arglist
  157643. #else
  157644. #define JPP(arglist) ()
  157645. #endif
  157646. /* Short forms of external names for systems with brain-damaged linkers.
  157647. * We shorten external names to be unique in the first six letters, which
  157648. * is good enough for all known systems.
  157649. * (If your compiler itself needs names to be unique in less than 15
  157650. * characters, you are out of luck. Get a better compiler.)
  157651. */
  157652. #ifdef NEED_SHORT_EXTERNAL_NAMES
  157653. #define jpeg_std_error jStdError
  157654. #define jpeg_CreateCompress jCreaCompress
  157655. #define jpeg_CreateDecompress jCreaDecompress
  157656. #define jpeg_destroy_compress jDestCompress
  157657. #define jpeg_destroy_decompress jDestDecompress
  157658. #define jpeg_stdio_dest jStdDest
  157659. #define jpeg_stdio_src jStdSrc
  157660. #define jpeg_set_defaults jSetDefaults
  157661. #define jpeg_set_colorspace jSetColorspace
  157662. #define jpeg_default_colorspace jDefColorspace
  157663. #define jpeg_set_quality jSetQuality
  157664. #define jpeg_set_linear_quality jSetLQuality
  157665. #define jpeg_add_quant_table jAddQuantTable
  157666. #define jpeg_quality_scaling jQualityScaling
  157667. #define jpeg_simple_progression jSimProgress
  157668. #define jpeg_suppress_tables jSuppressTables
  157669. #define jpeg_alloc_quant_table jAlcQTable
  157670. #define jpeg_alloc_huff_table jAlcHTable
  157671. #define jpeg_start_compress jStrtCompress
  157672. #define jpeg_write_scanlines jWrtScanlines
  157673. #define jpeg_finish_compress jFinCompress
  157674. #define jpeg_write_raw_data jWrtRawData
  157675. #define jpeg_write_marker jWrtMarker
  157676. #define jpeg_write_m_header jWrtMHeader
  157677. #define jpeg_write_m_byte jWrtMByte
  157678. #define jpeg_write_tables jWrtTables
  157679. #define jpeg_read_header jReadHeader
  157680. #define jpeg_start_decompress jStrtDecompress
  157681. #define jpeg_read_scanlines jReadScanlines
  157682. #define jpeg_finish_decompress jFinDecompress
  157683. #define jpeg_read_raw_data jReadRawData
  157684. #define jpeg_has_multiple_scans jHasMultScn
  157685. #define jpeg_start_output jStrtOutput
  157686. #define jpeg_finish_output jFinOutput
  157687. #define jpeg_input_complete jInComplete
  157688. #define jpeg_new_colormap jNewCMap
  157689. #define jpeg_consume_input jConsumeInput
  157690. #define jpeg_calc_output_dimensions jCalcDimensions
  157691. #define jpeg_save_markers jSaveMarkers
  157692. #define jpeg_set_marker_processor jSetMarker
  157693. #define jpeg_read_coefficients jReadCoefs
  157694. #define jpeg_write_coefficients jWrtCoefs
  157695. #define jpeg_copy_critical_parameters jCopyCrit
  157696. #define jpeg_abort_compress jAbrtCompress
  157697. #define jpeg_abort_decompress jAbrtDecompress
  157698. #define jpeg_abort jAbort
  157699. #define jpeg_destroy jDestroy
  157700. #define jpeg_resync_to_restart jResyncRestart
  157701. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  157702. /* Default error-management setup */
  157703. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  157704. JPP((struct jpeg_error_mgr * err));
  157705. /* Initialization of JPEG compression objects.
  157706. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  157707. * names that applications should call. These expand to calls on
  157708. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  157709. * passed for version mismatch checking.
  157710. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  157711. */
  157712. #define jpeg_create_compress(cinfo) \
  157713. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  157714. (size_t) sizeof(struct jpeg_compress_struct))
  157715. #define jpeg_create_decompress(cinfo) \
  157716. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  157717. (size_t) sizeof(struct jpeg_decompress_struct))
  157718. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  157719. int version, size_t structsize));
  157720. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  157721. int version, size_t structsize));
  157722. /* Destruction of JPEG compression objects */
  157723. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  157724. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  157725. /* Standard data source and destination managers: stdio streams. */
  157726. /* Caller is responsible for opening the file before and closing after. */
  157727. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  157728. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  157729. /* Default parameter setup for compression */
  157730. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  157731. /* Compression parameter setup aids */
  157732. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  157733. J_COLOR_SPACE colorspace));
  157734. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  157735. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  157736. boolean force_baseline));
  157737. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  157738. int scale_factor,
  157739. boolean force_baseline));
  157740. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  157741. const unsigned int *basic_table,
  157742. int scale_factor,
  157743. boolean force_baseline));
  157744. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  157745. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  157746. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  157747. boolean suppress));
  157748. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  157749. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  157750. /* Main entry points for compression */
  157751. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  157752. boolean write_all_tables));
  157753. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  157754. JSAMPARRAY scanlines,
  157755. JDIMENSION num_lines));
  157756. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  157757. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  157758. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  157759. JSAMPIMAGE data,
  157760. JDIMENSION num_lines));
  157761. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  157762. EXTERN(void) jpeg_write_marker
  157763. JPP((j_compress_ptr cinfo, int marker,
  157764. const JOCTET * dataptr, unsigned int datalen));
  157765. /* Same, but piecemeal. */
  157766. EXTERN(void) jpeg_write_m_header
  157767. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  157768. EXTERN(void) jpeg_write_m_byte
  157769. JPP((j_compress_ptr cinfo, int val));
  157770. /* Alternate compression function: just write an abbreviated table file */
  157771. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  157772. /* Decompression startup: read start of JPEG datastream to see what's there */
  157773. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  157774. boolean require_image));
  157775. /* Return value is one of: */
  157776. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  157777. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  157778. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  157779. /* If you pass require_image = TRUE (normal case), you need not check for
  157780. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  157781. * JPEG_SUSPENDED is only possible if you use a data source module that can
  157782. * give a suspension return (the stdio source module doesn't).
  157783. */
  157784. /* Main entry points for decompression */
  157785. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  157786. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  157787. JSAMPARRAY scanlines,
  157788. JDIMENSION max_lines));
  157789. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  157790. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  157791. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  157792. JSAMPIMAGE data,
  157793. JDIMENSION max_lines));
  157794. /* Additional entry points for buffered-image mode. */
  157795. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  157796. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  157797. int scan_number));
  157798. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  157799. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  157800. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  157801. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  157802. /* Return value is one of: */
  157803. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  157804. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  157805. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  157806. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  157807. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  157808. /* Precalculate output dimensions for current decompression parameters. */
  157809. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  157810. /* Control saving of COM and APPn markers into marker_list. */
  157811. EXTERN(void) jpeg_save_markers
  157812. JPP((j_decompress_ptr cinfo, int marker_code,
  157813. unsigned int length_limit));
  157814. /* Install a special processing method for COM or APPn markers. */
  157815. EXTERN(void) jpeg_set_marker_processor
  157816. JPP((j_decompress_ptr cinfo, int marker_code,
  157817. jpeg_marker_parser_method routine));
  157818. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  157819. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  157820. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  157821. jvirt_barray_ptr * coef_arrays));
  157822. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  157823. j_compress_ptr dstinfo));
  157824. /* If you choose to abort compression or decompression before completing
  157825. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  157826. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  157827. * if you're done with the JPEG object, but if you want to clean it up and
  157828. * reuse it, call this:
  157829. */
  157830. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  157831. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  157832. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  157833. * flavor of JPEG object. These may be more convenient in some places.
  157834. */
  157835. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  157836. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  157837. /* Default restart-marker-resync procedure for use by data source modules */
  157838. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  157839. int desired));
  157840. /* These marker codes are exported since applications and data source modules
  157841. * are likely to want to use them.
  157842. */
  157843. #define JPEG_RST0 0xD0 /* RST0 marker code */
  157844. #define JPEG_EOI 0xD9 /* EOI marker code */
  157845. #define JPEG_APP0 0xE0 /* APP0 marker code */
  157846. #define JPEG_COM 0xFE /* COM marker code */
  157847. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  157848. * for structure definitions that are never filled in, keep it quiet by
  157849. * supplying dummy definitions for the various substructures.
  157850. */
  157851. #ifdef INCOMPLETE_TYPES_BROKEN
  157852. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  157853. struct jvirt_sarray_control { long dummy; };
  157854. struct jvirt_barray_control { long dummy; };
  157855. struct jpeg_comp_master { long dummy; };
  157856. struct jpeg_c_main_controller { long dummy; };
  157857. struct jpeg_c_prep_controller { long dummy; };
  157858. struct jpeg_c_coef_controller { long dummy; };
  157859. struct jpeg_marker_writer { long dummy; };
  157860. struct jpeg_color_converter { long dummy; };
  157861. struct jpeg_downsampler { long dummy; };
  157862. struct jpeg_forward_dct { long dummy; };
  157863. struct jpeg_entropy_encoder { long dummy; };
  157864. struct jpeg_decomp_master { long dummy; };
  157865. struct jpeg_d_main_controller { long dummy; };
  157866. struct jpeg_d_coef_controller { long dummy; };
  157867. struct jpeg_d_post_controller { long dummy; };
  157868. struct jpeg_input_controller { long dummy; };
  157869. struct jpeg_marker_reader { long dummy; };
  157870. struct jpeg_entropy_decoder { long dummy; };
  157871. struct jpeg_inverse_dct { long dummy; };
  157872. struct jpeg_upsampler { long dummy; };
  157873. struct jpeg_color_deconverter { long dummy; };
  157874. struct jpeg_color_quantizer { long dummy; };
  157875. #endif /* JPEG_INTERNALS */
  157876. #endif /* INCOMPLETE_TYPES_BROKEN */
  157877. /*
  157878. * The JPEG library modules define JPEG_INTERNALS before including this file.
  157879. * The internal structure declarations are read only when that is true.
  157880. * Applications using the library should not include jpegint.h, but may wish
  157881. * to include jerror.h.
  157882. */
  157883. #ifdef JPEG_INTERNALS
  157884. /*** Start of inlined file: jpegint.h ***/
  157885. /* Declarations for both compression & decompression */
  157886. typedef enum { /* Operating modes for buffer controllers */
  157887. JBUF_PASS_THRU, /* Plain stripwise operation */
  157888. /* Remaining modes require a full-image buffer to have been created */
  157889. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  157890. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  157891. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  157892. } J_BUF_MODE;
  157893. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  157894. #define CSTATE_START 100 /* after create_compress */
  157895. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  157896. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  157897. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  157898. #define DSTATE_START 200 /* after create_decompress */
  157899. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  157900. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  157901. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  157902. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  157903. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  157904. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  157905. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  157906. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  157907. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  157908. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  157909. /* Declarations for compression modules */
  157910. /* Master control module */
  157911. struct jpeg_comp_master {
  157912. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  157913. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  157914. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  157915. /* State variables made visible to other modules */
  157916. boolean call_pass_startup; /* True if pass_startup must be called */
  157917. boolean is_last_pass; /* True during last pass */
  157918. };
  157919. /* Main buffer control (downsampled-data buffer) */
  157920. struct jpeg_c_main_controller {
  157921. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  157922. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  157923. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  157924. JDIMENSION in_rows_avail));
  157925. };
  157926. /* Compression preprocessing (downsampling input buffer control) */
  157927. struct jpeg_c_prep_controller {
  157928. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  157929. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  157930. JSAMPARRAY input_buf,
  157931. JDIMENSION *in_row_ctr,
  157932. JDIMENSION in_rows_avail,
  157933. JSAMPIMAGE output_buf,
  157934. JDIMENSION *out_row_group_ctr,
  157935. JDIMENSION out_row_groups_avail));
  157936. };
  157937. /* Coefficient buffer control */
  157938. struct jpeg_c_coef_controller {
  157939. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  157940. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  157941. JSAMPIMAGE input_buf));
  157942. };
  157943. /* Colorspace conversion */
  157944. struct jpeg_color_converter {
  157945. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  157946. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  157947. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  157948. JDIMENSION output_row, int num_rows));
  157949. };
  157950. /* Downsampling */
  157951. struct jpeg_downsampler {
  157952. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  157953. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  157954. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  157955. JSAMPIMAGE output_buf,
  157956. JDIMENSION out_row_group_index));
  157957. boolean need_context_rows; /* TRUE if need rows above & below */
  157958. };
  157959. /* Forward DCT (also controls coefficient quantization) */
  157960. struct jpeg_forward_dct {
  157961. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  157962. /* perhaps this should be an array??? */
  157963. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  157964. jpeg_component_info * compptr,
  157965. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  157966. JDIMENSION start_row, JDIMENSION start_col,
  157967. JDIMENSION num_blocks));
  157968. };
  157969. /* Entropy encoding */
  157970. struct jpeg_entropy_encoder {
  157971. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  157972. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  157973. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  157974. };
  157975. /* Marker writing */
  157976. struct jpeg_marker_writer {
  157977. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  157978. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  157979. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  157980. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  157981. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  157982. /* These routines are exported to allow insertion of extra markers */
  157983. /* Probably only COM and APPn markers should be written this way */
  157984. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  157985. unsigned int datalen));
  157986. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  157987. };
  157988. /* Declarations for decompression modules */
  157989. /* Master control module */
  157990. struct jpeg_decomp_master {
  157991. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  157992. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  157993. /* State variables made visible to other modules */
  157994. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  157995. };
  157996. /* Input control module */
  157997. struct jpeg_input_controller {
  157998. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  157999. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  158000. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  158001. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  158002. /* State variables made visible to other modules */
  158003. boolean has_multiple_scans; /* True if file has multiple scans */
  158004. boolean eoi_reached; /* True when EOI has been consumed */
  158005. };
  158006. /* Main buffer control (downsampled-data buffer) */
  158007. struct jpeg_d_main_controller {
  158008. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  158009. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  158010. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  158011. JDIMENSION out_rows_avail));
  158012. };
  158013. /* Coefficient buffer control */
  158014. struct jpeg_d_coef_controller {
  158015. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  158016. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  158017. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  158018. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  158019. JSAMPIMAGE output_buf));
  158020. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  158021. jvirt_barray_ptr *coef_arrays;
  158022. };
  158023. /* Decompression postprocessing (color quantization buffer control) */
  158024. struct jpeg_d_post_controller {
  158025. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  158026. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  158027. JSAMPIMAGE input_buf,
  158028. JDIMENSION *in_row_group_ctr,
  158029. JDIMENSION in_row_groups_avail,
  158030. JSAMPARRAY output_buf,
  158031. JDIMENSION *out_row_ctr,
  158032. JDIMENSION out_rows_avail));
  158033. };
  158034. /* Marker reading & parsing */
  158035. struct jpeg_marker_reader {
  158036. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  158037. /* Read markers until SOS or EOI.
  158038. * Returns same codes as are defined for jpeg_consume_input:
  158039. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  158040. */
  158041. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  158042. /* Read a restart marker --- exported for use by entropy decoder only */
  158043. jpeg_marker_parser_method read_restart_marker;
  158044. /* State of marker reader --- nominally internal, but applications
  158045. * supplying COM or APPn handlers might like to know the state.
  158046. */
  158047. boolean saw_SOI; /* found SOI? */
  158048. boolean saw_SOF; /* found SOF? */
  158049. int next_restart_num; /* next restart number expected (0-7) */
  158050. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  158051. };
  158052. /* Entropy decoding */
  158053. struct jpeg_entropy_decoder {
  158054. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  158055. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  158056. JBLOCKROW *MCU_data));
  158057. /* This is here to share code between baseline and progressive decoders; */
  158058. /* other modules probably should not use it */
  158059. boolean insufficient_data; /* set TRUE after emitting warning */
  158060. };
  158061. /* Inverse DCT (also performs dequantization) */
  158062. typedef JMETHOD(void, inverse_DCT_method_ptr,
  158063. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  158064. JCOEFPTR coef_block,
  158065. JSAMPARRAY output_buf, JDIMENSION output_col));
  158066. struct jpeg_inverse_dct {
  158067. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  158068. /* It is useful to allow each component to have a separate IDCT method. */
  158069. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  158070. };
  158071. /* Upsampling (note that upsampler must also call color converter) */
  158072. struct jpeg_upsampler {
  158073. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  158074. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  158075. JSAMPIMAGE input_buf,
  158076. JDIMENSION *in_row_group_ctr,
  158077. JDIMENSION in_row_groups_avail,
  158078. JSAMPARRAY output_buf,
  158079. JDIMENSION *out_row_ctr,
  158080. JDIMENSION out_rows_avail));
  158081. boolean need_context_rows; /* TRUE if need rows above & below */
  158082. };
  158083. /* Colorspace conversion */
  158084. struct jpeg_color_deconverter {
  158085. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  158086. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  158087. JSAMPIMAGE input_buf, JDIMENSION input_row,
  158088. JSAMPARRAY output_buf, int num_rows));
  158089. };
  158090. /* Color quantization or color precision reduction */
  158091. struct jpeg_color_quantizer {
  158092. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  158093. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  158094. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  158095. int num_rows));
  158096. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  158097. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  158098. };
  158099. /* Miscellaneous useful macros */
  158100. #undef MAX
  158101. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  158102. #undef MIN
  158103. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  158104. /* We assume that right shift corresponds to signed division by 2 with
  158105. * rounding towards minus infinity. This is correct for typical "arithmetic
  158106. * shift" instructions that shift in copies of the sign bit. But some
  158107. * C compilers implement >> with an unsigned shift. For these machines you
  158108. * must define RIGHT_SHIFT_IS_UNSIGNED.
  158109. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  158110. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  158111. * included in the variables of any routine using RIGHT_SHIFT.
  158112. */
  158113. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  158114. #define SHIFT_TEMPS INT32 shift_temp;
  158115. #define RIGHT_SHIFT(x,shft) \
  158116. ((shift_temp = (x)) < 0 ? \
  158117. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  158118. (shift_temp >> (shft)))
  158119. #else
  158120. #define SHIFT_TEMPS
  158121. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  158122. #endif
  158123. /* Short forms of external names for systems with brain-damaged linkers. */
  158124. #ifdef NEED_SHORT_EXTERNAL_NAMES
  158125. #define jinit_compress_master jICompress
  158126. #define jinit_c_master_control jICMaster
  158127. #define jinit_c_main_controller jICMainC
  158128. #define jinit_c_prep_controller jICPrepC
  158129. #define jinit_c_coef_controller jICCoefC
  158130. #define jinit_color_converter jICColor
  158131. #define jinit_downsampler jIDownsampler
  158132. #define jinit_forward_dct jIFDCT
  158133. #define jinit_huff_encoder jIHEncoder
  158134. #define jinit_phuff_encoder jIPHEncoder
  158135. #define jinit_marker_writer jIMWriter
  158136. #define jinit_master_decompress jIDMaster
  158137. #define jinit_d_main_controller jIDMainC
  158138. #define jinit_d_coef_controller jIDCoefC
  158139. #define jinit_d_post_controller jIDPostC
  158140. #define jinit_input_controller jIInCtlr
  158141. #define jinit_marker_reader jIMReader
  158142. #define jinit_huff_decoder jIHDecoder
  158143. #define jinit_phuff_decoder jIPHDecoder
  158144. #define jinit_inverse_dct jIIDCT
  158145. #define jinit_upsampler jIUpsampler
  158146. #define jinit_color_deconverter jIDColor
  158147. #define jinit_1pass_quantizer jI1Quant
  158148. #define jinit_2pass_quantizer jI2Quant
  158149. #define jinit_merged_upsampler jIMUpsampler
  158150. #define jinit_memory_mgr jIMemMgr
  158151. #define jdiv_round_up jDivRound
  158152. #define jround_up jRound
  158153. #define jcopy_sample_rows jCopySamples
  158154. #define jcopy_block_row jCopyBlocks
  158155. #define jzero_far jZeroFar
  158156. #define jpeg_zigzag_order jZIGTable
  158157. #define jpeg_natural_order jZAGTable
  158158. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  158159. /* Compression module initialization routines */
  158160. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  158161. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  158162. boolean transcode_only));
  158163. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  158164. boolean need_full_buffer));
  158165. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  158166. boolean need_full_buffer));
  158167. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  158168. boolean need_full_buffer));
  158169. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  158170. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  158171. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  158172. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  158173. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  158174. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  158175. /* Decompression module initialization routines */
  158176. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  158177. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  158178. boolean need_full_buffer));
  158179. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  158180. boolean need_full_buffer));
  158181. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  158182. boolean need_full_buffer));
  158183. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  158184. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  158185. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  158186. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  158187. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  158188. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  158189. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  158190. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  158191. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  158192. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  158193. /* Memory manager initialization */
  158194. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  158195. /* Utility routines in jutils.c */
  158196. EXTERN(long) jdiv_round_up JPP((long a, long b));
  158197. EXTERN(long) jround_up JPP((long a, long b));
  158198. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  158199. JSAMPARRAY output_array, int dest_row,
  158200. int num_rows, JDIMENSION num_cols));
  158201. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  158202. JDIMENSION num_blocks));
  158203. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  158204. /* Constant tables in jutils.c */
  158205. #if 0 /* This table is not actually needed in v6a */
  158206. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  158207. #endif
  158208. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  158209. /* Suppress undefined-structure complaints if necessary. */
  158210. #ifdef INCOMPLETE_TYPES_BROKEN
  158211. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  158212. struct jvirt_sarray_control { long dummy; };
  158213. struct jvirt_barray_control { long dummy; };
  158214. #endif
  158215. #endif /* INCOMPLETE_TYPES_BROKEN */
  158216. /*** End of inlined file: jpegint.h ***/
  158217. /* fetch private declarations */
  158218. /*** Start of inlined file: jerror.h ***/
  158219. /*
  158220. * To define the enum list of message codes, include this file without
  158221. * defining macro JMESSAGE. To create a message string table, include it
  158222. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  158223. */
  158224. #ifndef JMESSAGE
  158225. #ifndef JERROR_H
  158226. /* First time through, define the enum list */
  158227. #define JMAKE_ENUM_LIST
  158228. #else
  158229. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  158230. #define JMESSAGE(code,string)
  158231. #endif /* JERROR_H */
  158232. #endif /* JMESSAGE */
  158233. #ifdef JMAKE_ENUM_LIST
  158234. typedef enum {
  158235. #define JMESSAGE(code,string) code ,
  158236. #endif /* JMAKE_ENUM_LIST */
  158237. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  158238. /* For maintenance convenience, list is alphabetical by message code name */
  158239. JMESSAGE(JERR_ARITH_NOTIMPL,
  158240. "Sorry, there are legal restrictions on arithmetic coding")
  158241. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  158242. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  158243. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  158244. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  158245. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  158246. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  158247. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  158248. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  158249. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  158250. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  158251. JMESSAGE(JERR_BAD_LIB_VERSION,
  158252. "Wrong JPEG library version: library is %d, caller expects %d")
  158253. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  158254. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  158255. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  158256. JMESSAGE(JERR_BAD_PROGRESSION,
  158257. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  158258. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  158259. "Invalid progressive parameters at scan script entry %d")
  158260. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  158261. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  158262. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  158263. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  158264. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  158265. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  158266. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  158267. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  158268. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  158269. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  158270. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  158271. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  158272. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  158273. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  158274. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  158275. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  158276. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  158277. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  158278. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  158279. JMESSAGE(JERR_FILE_READ, "Input file read error")
  158280. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  158281. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  158282. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  158283. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  158284. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  158285. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  158286. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  158287. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  158288. "Cannot transcode due to multiple use of quantization table %d")
  158289. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  158290. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  158291. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  158292. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  158293. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  158294. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  158295. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  158296. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  158297. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  158298. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  158299. JMESSAGE(JERR_QUANT_COMPONENTS,
  158300. "Cannot quantize more than %d color components")
  158301. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  158302. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  158303. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  158304. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  158305. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  158306. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  158307. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  158308. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  158309. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  158310. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  158311. JMESSAGE(JERR_TFILE_WRITE,
  158312. "Write failed on temporary file --- out of disk space?")
  158313. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  158314. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  158315. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  158316. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  158317. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  158318. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  158319. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  158320. JMESSAGE(JMSG_VERSION, JVERSION)
  158321. JMESSAGE(JTRC_16BIT_TABLES,
  158322. "Caution: quantization tables are too coarse for baseline JPEG")
  158323. JMESSAGE(JTRC_ADOBE,
  158324. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  158325. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  158326. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  158327. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  158328. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  158329. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  158330. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  158331. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  158332. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  158333. JMESSAGE(JTRC_EOI, "End Of Image")
  158334. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  158335. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  158336. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  158337. "Warning: thumbnail image size does not match data length %u")
  158338. JMESSAGE(JTRC_JFIF_EXTENSION,
  158339. "JFIF extension marker: type 0x%02x, length %u")
  158340. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  158341. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  158342. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  158343. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  158344. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  158345. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  158346. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  158347. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  158348. JMESSAGE(JTRC_RST, "RST%d")
  158349. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  158350. "Smoothing not supported with nonstandard sampling ratios")
  158351. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  158352. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  158353. JMESSAGE(JTRC_SOI, "Start of Image")
  158354. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  158355. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  158356. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  158357. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  158358. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  158359. JMESSAGE(JTRC_THUMB_JPEG,
  158360. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  158361. JMESSAGE(JTRC_THUMB_PALETTE,
  158362. "JFIF extension marker: palette thumbnail image, length %u")
  158363. JMESSAGE(JTRC_THUMB_RGB,
  158364. "JFIF extension marker: RGB thumbnail image, length %u")
  158365. JMESSAGE(JTRC_UNKNOWN_IDS,
  158366. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  158367. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  158368. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  158369. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  158370. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  158371. "Inconsistent progression sequence for component %d coefficient %d")
  158372. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  158373. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  158374. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  158375. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  158376. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  158377. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  158378. JMESSAGE(JWRN_MUST_RESYNC,
  158379. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  158380. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  158381. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  158382. #ifdef JMAKE_ENUM_LIST
  158383. JMSG_LASTMSGCODE
  158384. } J_MESSAGE_CODE;
  158385. #undef JMAKE_ENUM_LIST
  158386. #endif /* JMAKE_ENUM_LIST */
  158387. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  158388. #undef JMESSAGE
  158389. #ifndef JERROR_H
  158390. #define JERROR_H
  158391. /* Macros to simplify using the error and trace message stuff */
  158392. /* The first parameter is either type of cinfo pointer */
  158393. /* Fatal errors (print message and exit) */
  158394. #define ERREXIT(cinfo,code) \
  158395. ((cinfo)->err->msg_code = (code), \
  158396. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  158397. #define ERREXIT1(cinfo,code,p1) \
  158398. ((cinfo)->err->msg_code = (code), \
  158399. (cinfo)->err->msg_parm.i[0] = (p1), \
  158400. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  158401. #define ERREXIT2(cinfo,code,p1,p2) \
  158402. ((cinfo)->err->msg_code = (code), \
  158403. (cinfo)->err->msg_parm.i[0] = (p1), \
  158404. (cinfo)->err->msg_parm.i[1] = (p2), \
  158405. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  158406. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  158407. ((cinfo)->err->msg_code = (code), \
  158408. (cinfo)->err->msg_parm.i[0] = (p1), \
  158409. (cinfo)->err->msg_parm.i[1] = (p2), \
  158410. (cinfo)->err->msg_parm.i[2] = (p3), \
  158411. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  158412. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  158413. ((cinfo)->err->msg_code = (code), \
  158414. (cinfo)->err->msg_parm.i[0] = (p1), \
  158415. (cinfo)->err->msg_parm.i[1] = (p2), \
  158416. (cinfo)->err->msg_parm.i[2] = (p3), \
  158417. (cinfo)->err->msg_parm.i[3] = (p4), \
  158418. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  158419. #define ERREXITS(cinfo,code,str) \
  158420. ((cinfo)->err->msg_code = (code), \
  158421. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  158422. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  158423. #define MAKESTMT(stuff) do { stuff } while (0)
  158424. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  158425. #define WARNMS(cinfo,code) \
  158426. ((cinfo)->err->msg_code = (code), \
  158427. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  158428. #define WARNMS1(cinfo,code,p1) \
  158429. ((cinfo)->err->msg_code = (code), \
  158430. (cinfo)->err->msg_parm.i[0] = (p1), \
  158431. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  158432. #define WARNMS2(cinfo,code,p1,p2) \
  158433. ((cinfo)->err->msg_code = (code), \
  158434. (cinfo)->err->msg_parm.i[0] = (p1), \
  158435. (cinfo)->err->msg_parm.i[1] = (p2), \
  158436. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  158437. /* Informational/debugging messages */
  158438. #define TRACEMS(cinfo,lvl,code) \
  158439. ((cinfo)->err->msg_code = (code), \
  158440. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  158441. #define TRACEMS1(cinfo,lvl,code,p1) \
  158442. ((cinfo)->err->msg_code = (code), \
  158443. (cinfo)->err->msg_parm.i[0] = (p1), \
  158444. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  158445. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  158446. ((cinfo)->err->msg_code = (code), \
  158447. (cinfo)->err->msg_parm.i[0] = (p1), \
  158448. (cinfo)->err->msg_parm.i[1] = (p2), \
  158449. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  158450. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  158451. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  158452. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  158453. (cinfo)->err->msg_code = (code); \
  158454. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  158455. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  158456. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  158457. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  158458. (cinfo)->err->msg_code = (code); \
  158459. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  158460. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  158461. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  158462. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  158463. _mp[4] = (p5); \
  158464. (cinfo)->err->msg_code = (code); \
  158465. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  158466. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  158467. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  158468. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  158469. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  158470. (cinfo)->err->msg_code = (code); \
  158471. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  158472. #define TRACEMSS(cinfo,lvl,code,str) \
  158473. ((cinfo)->err->msg_code = (code), \
  158474. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  158475. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  158476. #endif /* JERROR_H */
  158477. /*** End of inlined file: jerror.h ***/
  158478. /* fetch error codes too */
  158479. #endif
  158480. #endif /* JPEGLIB_H */
  158481. /*** End of inlined file: jpeglib.h ***/
  158482. /*** Start of inlined file: jcapimin.c ***/
  158483. #define JPEG_INTERNALS
  158484. /*** Start of inlined file: jinclude.h ***/
  158485. /* Include auto-config file to find out which system include files we need. */
  158486. #ifndef __jinclude_h__
  158487. #define __jinclude_h__
  158488. /*** Start of inlined file: jconfig.h ***/
  158489. /* see jconfig.doc for explanations */
  158490. // disable all the warnings under MSVC
  158491. #ifdef _MSC_VER
  158492. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  158493. #endif
  158494. #ifdef __BORLANDC__
  158495. #pragma warn -8057
  158496. #pragma warn -8019
  158497. #pragma warn -8004
  158498. #pragma warn -8008
  158499. #endif
  158500. #define HAVE_PROTOTYPES
  158501. #define HAVE_UNSIGNED_CHAR
  158502. #define HAVE_UNSIGNED_SHORT
  158503. /* #define void char */
  158504. /* #define const */
  158505. #undef CHAR_IS_UNSIGNED
  158506. #define HAVE_STDDEF_H
  158507. #define HAVE_STDLIB_H
  158508. #undef NEED_BSD_STRINGS
  158509. #undef NEED_SYS_TYPES_H
  158510. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  158511. #undef NEED_SHORT_EXTERNAL_NAMES
  158512. #undef INCOMPLETE_TYPES_BROKEN
  158513. /* Define "boolean" as unsigned char, not int, per Windows custom */
  158514. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  158515. typedef unsigned char boolean;
  158516. #endif
  158517. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  158518. #ifdef JPEG_INTERNALS
  158519. #undef RIGHT_SHIFT_IS_UNSIGNED
  158520. #endif /* JPEG_INTERNALS */
  158521. #ifdef JPEG_CJPEG_DJPEG
  158522. #define BMP_SUPPORTED /* BMP image file format */
  158523. #define GIF_SUPPORTED /* GIF image file format */
  158524. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  158525. #undef RLE_SUPPORTED /* Utah RLE image file format */
  158526. #define TARGA_SUPPORTED /* Targa image file format */
  158527. #define TWO_FILE_COMMANDLINE /* optional */
  158528. #define USE_SETMODE /* Microsoft has setmode() */
  158529. #undef NEED_SIGNAL_CATCHER
  158530. #undef DONT_USE_B_MODE
  158531. #undef PROGRESS_REPORT /* optional */
  158532. #endif /* JPEG_CJPEG_DJPEG */
  158533. /*** End of inlined file: jconfig.h ***/
  158534. /* auto configuration options */
  158535. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  158536. /*
  158537. * We need the NULL macro and size_t typedef.
  158538. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  158539. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  158540. * pull in <sys/types.h> as well.
  158541. * Note that the core JPEG library does not require <stdio.h>;
  158542. * only the default error handler and data source/destination modules do.
  158543. * But we must pull it in because of the references to FILE in jpeglib.h.
  158544. * You can remove those references if you want to compile without <stdio.h>.
  158545. */
  158546. #ifdef HAVE_STDDEF_H
  158547. #include <stddef.h>
  158548. #endif
  158549. #ifdef HAVE_STDLIB_H
  158550. #include <stdlib.h>
  158551. #endif
  158552. #ifdef NEED_SYS_TYPES_H
  158553. #include <sys/types.h>
  158554. #endif
  158555. #include <stdio.h>
  158556. /*
  158557. * We need memory copying and zeroing functions, plus strncpy().
  158558. * ANSI and System V implementations declare these in <string.h>.
  158559. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  158560. * Some systems may declare memset and memcpy in <memory.h>.
  158561. *
  158562. * NOTE: we assume the size parameters to these functions are of type size_t.
  158563. * Change the casts in these macros if not!
  158564. */
  158565. #ifdef NEED_BSD_STRINGS
  158566. #include <strings.h>
  158567. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  158568. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  158569. #else /* not BSD, assume ANSI/SysV string lib */
  158570. #include <string.h>
  158571. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  158572. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  158573. #endif
  158574. /*
  158575. * In ANSI C, and indeed any rational implementation, size_t is also the
  158576. * type returned by sizeof(). However, it seems there are some irrational
  158577. * implementations out there, in which sizeof() returns an int even though
  158578. * size_t is defined as long or unsigned long. To ensure consistent results
  158579. * we always use this SIZEOF() macro in place of using sizeof() directly.
  158580. */
  158581. #define SIZEOF(object) ((size_t) sizeof(object))
  158582. /*
  158583. * The modules that use fread() and fwrite() always invoke them through
  158584. * these macros. On some systems you may need to twiddle the argument casts.
  158585. * CAUTION: argument order is different from underlying functions!
  158586. */
  158587. #define JFREAD(file,buf,sizeofbuf) \
  158588. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  158589. #define JFWRITE(file,buf,sizeofbuf) \
  158590. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  158591. typedef enum { /* JPEG marker codes */
  158592. M_SOF0 = 0xc0,
  158593. M_SOF1 = 0xc1,
  158594. M_SOF2 = 0xc2,
  158595. M_SOF3 = 0xc3,
  158596. M_SOF5 = 0xc5,
  158597. M_SOF6 = 0xc6,
  158598. M_SOF7 = 0xc7,
  158599. M_JPG = 0xc8,
  158600. M_SOF9 = 0xc9,
  158601. M_SOF10 = 0xca,
  158602. M_SOF11 = 0xcb,
  158603. M_SOF13 = 0xcd,
  158604. M_SOF14 = 0xce,
  158605. M_SOF15 = 0xcf,
  158606. M_DHT = 0xc4,
  158607. M_DAC = 0xcc,
  158608. M_RST0 = 0xd0,
  158609. M_RST1 = 0xd1,
  158610. M_RST2 = 0xd2,
  158611. M_RST3 = 0xd3,
  158612. M_RST4 = 0xd4,
  158613. M_RST5 = 0xd5,
  158614. M_RST6 = 0xd6,
  158615. M_RST7 = 0xd7,
  158616. M_SOI = 0xd8,
  158617. M_EOI = 0xd9,
  158618. M_SOS = 0xda,
  158619. M_DQT = 0xdb,
  158620. M_DNL = 0xdc,
  158621. M_DRI = 0xdd,
  158622. M_DHP = 0xde,
  158623. M_EXP = 0xdf,
  158624. M_APP0 = 0xe0,
  158625. M_APP1 = 0xe1,
  158626. M_APP2 = 0xe2,
  158627. M_APP3 = 0xe3,
  158628. M_APP4 = 0xe4,
  158629. M_APP5 = 0xe5,
  158630. M_APP6 = 0xe6,
  158631. M_APP7 = 0xe7,
  158632. M_APP8 = 0xe8,
  158633. M_APP9 = 0xe9,
  158634. M_APP10 = 0xea,
  158635. M_APP11 = 0xeb,
  158636. M_APP12 = 0xec,
  158637. M_APP13 = 0xed,
  158638. M_APP14 = 0xee,
  158639. M_APP15 = 0xef,
  158640. M_JPG0 = 0xf0,
  158641. M_JPG13 = 0xfd,
  158642. M_COM = 0xfe,
  158643. M_TEM = 0x01,
  158644. M_ERROR = 0x100
  158645. } JPEG_MARKER;
  158646. /*
  158647. * Figure F.12: extend sign bit.
  158648. * On some machines, a shift and add will be faster than a table lookup.
  158649. */
  158650. #ifdef AVOID_TABLES
  158651. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  158652. #else
  158653. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  158654. static const int extend_test[16] = /* entry n is 2**(n-1) */
  158655. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  158656. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  158657. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  158658. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  158659. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  158660. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  158661. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  158662. #endif /* AVOID_TABLES */
  158663. #endif
  158664. /*** End of inlined file: jinclude.h ***/
  158665. /*
  158666. * Initialization of a JPEG compression object.
  158667. * The error manager must already be set up (in case memory manager fails).
  158668. */
  158669. GLOBAL(void)
  158670. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  158671. {
  158672. int i;
  158673. /* Guard against version mismatches between library and caller. */
  158674. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  158675. if (version != JPEG_LIB_VERSION)
  158676. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  158677. if (structsize != SIZEOF(struct jpeg_compress_struct))
  158678. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  158679. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  158680. /* For debugging purposes, we zero the whole master structure.
  158681. * But the application has already set the err pointer, and may have set
  158682. * client_data, so we have to save and restore those fields.
  158683. * Note: if application hasn't set client_data, tools like Purify may
  158684. * complain here.
  158685. */
  158686. {
  158687. struct jpeg_error_mgr * err = cinfo->err;
  158688. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  158689. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  158690. cinfo->err = err;
  158691. cinfo->client_data = client_data;
  158692. }
  158693. cinfo->is_decompressor = FALSE;
  158694. /* Initialize a memory manager instance for this object */
  158695. jinit_memory_mgr((j_common_ptr) cinfo);
  158696. /* Zero out pointers to permanent structures. */
  158697. cinfo->progress = NULL;
  158698. cinfo->dest = NULL;
  158699. cinfo->comp_info = NULL;
  158700. for (i = 0; i < NUM_QUANT_TBLS; i++)
  158701. cinfo->quant_tbl_ptrs[i] = NULL;
  158702. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  158703. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  158704. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  158705. }
  158706. cinfo->script_space = NULL;
  158707. cinfo->input_gamma = 1.0; /* in case application forgets */
  158708. /* OK, I'm ready */
  158709. cinfo->global_state = CSTATE_START;
  158710. }
  158711. /*
  158712. * Destruction of a JPEG compression object
  158713. */
  158714. GLOBAL(void)
  158715. jpeg_destroy_compress (j_compress_ptr cinfo)
  158716. {
  158717. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  158718. }
  158719. /*
  158720. * Abort processing of a JPEG compression operation,
  158721. * but don't destroy the object itself.
  158722. */
  158723. GLOBAL(void)
  158724. jpeg_abort_compress (j_compress_ptr cinfo)
  158725. {
  158726. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  158727. }
  158728. /*
  158729. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  158730. * Marks all currently defined tables as already written (if suppress)
  158731. * or not written (if !suppress). This will control whether they get emitted
  158732. * by a subsequent jpeg_start_compress call.
  158733. *
  158734. * This routine is exported for use by applications that want to produce
  158735. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  158736. * since it is called by jpeg_start_compress, we put it here --- otherwise
  158737. * jcparam.o would be linked whether the application used it or not.
  158738. */
  158739. GLOBAL(void)
  158740. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  158741. {
  158742. int i;
  158743. JQUANT_TBL * qtbl;
  158744. JHUFF_TBL * htbl;
  158745. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  158746. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  158747. qtbl->sent_table = suppress;
  158748. }
  158749. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  158750. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  158751. htbl->sent_table = suppress;
  158752. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  158753. htbl->sent_table = suppress;
  158754. }
  158755. }
  158756. /*
  158757. * Finish JPEG compression.
  158758. *
  158759. * If a multipass operating mode was selected, this may do a great deal of
  158760. * work including most of the actual output.
  158761. */
  158762. GLOBAL(void)
  158763. jpeg_finish_compress (j_compress_ptr cinfo)
  158764. {
  158765. JDIMENSION iMCU_row;
  158766. if (cinfo->global_state == CSTATE_SCANNING ||
  158767. cinfo->global_state == CSTATE_RAW_OK) {
  158768. /* Terminate first pass */
  158769. if (cinfo->next_scanline < cinfo->image_height)
  158770. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  158771. (*cinfo->master->finish_pass) (cinfo);
  158772. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  158773. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158774. /* Perform any remaining passes */
  158775. while (! cinfo->master->is_last_pass) {
  158776. (*cinfo->master->prepare_for_pass) (cinfo);
  158777. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  158778. if (cinfo->progress != NULL) {
  158779. cinfo->progress->pass_counter = (long) iMCU_row;
  158780. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  158781. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  158782. }
  158783. /* We bypass the main controller and invoke coef controller directly;
  158784. * all work is being done from the coefficient buffer.
  158785. */
  158786. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  158787. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  158788. }
  158789. (*cinfo->master->finish_pass) (cinfo);
  158790. }
  158791. /* Write EOI, do final cleanup */
  158792. (*cinfo->marker->write_file_trailer) (cinfo);
  158793. (*cinfo->dest->term_destination) (cinfo);
  158794. /* We can use jpeg_abort to release memory and reset global_state */
  158795. jpeg_abort((j_common_ptr) cinfo);
  158796. }
  158797. /*
  158798. * Write a special marker.
  158799. * This is only recommended for writing COM or APPn markers.
  158800. * Must be called after jpeg_start_compress() and before
  158801. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  158802. */
  158803. GLOBAL(void)
  158804. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  158805. const JOCTET *dataptr, unsigned int datalen)
  158806. {
  158807. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  158808. if (cinfo->next_scanline != 0 ||
  158809. (cinfo->global_state != CSTATE_SCANNING &&
  158810. cinfo->global_state != CSTATE_RAW_OK &&
  158811. cinfo->global_state != CSTATE_WRCOEFS))
  158812. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158813. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  158814. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  158815. while (datalen--) {
  158816. (*write_marker_byte) (cinfo, *dataptr);
  158817. dataptr++;
  158818. }
  158819. }
  158820. /* Same, but piecemeal. */
  158821. GLOBAL(void)
  158822. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  158823. {
  158824. if (cinfo->next_scanline != 0 ||
  158825. (cinfo->global_state != CSTATE_SCANNING &&
  158826. cinfo->global_state != CSTATE_RAW_OK &&
  158827. cinfo->global_state != CSTATE_WRCOEFS))
  158828. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158829. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  158830. }
  158831. GLOBAL(void)
  158832. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  158833. {
  158834. (*cinfo->marker->write_marker_byte) (cinfo, val);
  158835. }
  158836. /*
  158837. * Alternate compression function: just write an abbreviated table file.
  158838. * Before calling this, all parameters and a data destination must be set up.
  158839. *
  158840. * To produce a pair of files containing abbreviated tables and abbreviated
  158841. * image data, one would proceed as follows:
  158842. *
  158843. * initialize JPEG object
  158844. * set JPEG parameters
  158845. * set destination to table file
  158846. * jpeg_write_tables(cinfo);
  158847. * set destination to image file
  158848. * jpeg_start_compress(cinfo, FALSE);
  158849. * write data...
  158850. * jpeg_finish_compress(cinfo);
  158851. *
  158852. * jpeg_write_tables has the side effect of marking all tables written
  158853. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  158854. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  158855. */
  158856. GLOBAL(void)
  158857. jpeg_write_tables (j_compress_ptr cinfo)
  158858. {
  158859. if (cinfo->global_state != CSTATE_START)
  158860. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158861. /* (Re)initialize error mgr and destination modules */
  158862. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  158863. (*cinfo->dest->init_destination) (cinfo);
  158864. /* Initialize the marker writer ... bit of a crock to do it here. */
  158865. jinit_marker_writer(cinfo);
  158866. /* Write them tables! */
  158867. (*cinfo->marker->write_tables_only) (cinfo);
  158868. /* And clean up. */
  158869. (*cinfo->dest->term_destination) (cinfo);
  158870. /*
  158871. * In library releases up through v6a, we called jpeg_abort() here to free
  158872. * any working memory allocated by the destination manager and marker
  158873. * writer. Some applications had a problem with that: they allocated space
  158874. * of their own from the library memory manager, and didn't want it to go
  158875. * away during write_tables. So now we do nothing. This will cause a
  158876. * memory leak if an app calls write_tables repeatedly without doing a full
  158877. * compression cycle or otherwise resetting the JPEG object. However, that
  158878. * seems less bad than unexpectedly freeing memory in the normal case.
  158879. * An app that prefers the old behavior can call jpeg_abort for itself after
  158880. * each call to jpeg_write_tables().
  158881. */
  158882. }
  158883. /*** End of inlined file: jcapimin.c ***/
  158884. /*** Start of inlined file: jcapistd.c ***/
  158885. #define JPEG_INTERNALS
  158886. /*
  158887. * Compression initialization.
  158888. * Before calling this, all parameters and a data destination must be set up.
  158889. *
  158890. * We require a write_all_tables parameter as a failsafe check when writing
  158891. * multiple datastreams from the same compression object. Since prior runs
  158892. * will have left all the tables marked sent_table=TRUE, a subsequent run
  158893. * would emit an abbreviated stream (no tables) by default. This may be what
  158894. * is wanted, but for safety's sake it should not be the default behavior:
  158895. * programmers should have to make a deliberate choice to emit abbreviated
  158896. * images. Therefore the documentation and examples should encourage people
  158897. * to pass write_all_tables=TRUE; then it will take active thought to do the
  158898. * wrong thing.
  158899. */
  158900. GLOBAL(void)
  158901. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  158902. {
  158903. if (cinfo->global_state != CSTATE_START)
  158904. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158905. if (write_all_tables)
  158906. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  158907. /* (Re)initialize error mgr and destination modules */
  158908. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  158909. (*cinfo->dest->init_destination) (cinfo);
  158910. /* Perform master selection of active modules */
  158911. jinit_compress_master(cinfo);
  158912. /* Set up for the first pass */
  158913. (*cinfo->master->prepare_for_pass) (cinfo);
  158914. /* Ready for application to drive first pass through jpeg_write_scanlines
  158915. * or jpeg_write_raw_data.
  158916. */
  158917. cinfo->next_scanline = 0;
  158918. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  158919. }
  158920. /*
  158921. * Write some scanlines of data to the JPEG compressor.
  158922. *
  158923. * The return value will be the number of lines actually written.
  158924. * This should be less than the supplied num_lines only in case that
  158925. * the data destination module has requested suspension of the compressor,
  158926. * or if more than image_height scanlines are passed in.
  158927. *
  158928. * Note: we warn about excess calls to jpeg_write_scanlines() since
  158929. * this likely signals an application programmer error. However,
  158930. * excess scanlines passed in the last valid call are *silently* ignored,
  158931. * so that the application need not adjust num_lines for end-of-image
  158932. * when using a multiple-scanline buffer.
  158933. */
  158934. GLOBAL(JDIMENSION)
  158935. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  158936. JDIMENSION num_lines)
  158937. {
  158938. JDIMENSION row_ctr, rows_left;
  158939. if (cinfo->global_state != CSTATE_SCANNING)
  158940. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158941. if (cinfo->next_scanline >= cinfo->image_height)
  158942. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  158943. /* Call progress monitor hook if present */
  158944. if (cinfo->progress != NULL) {
  158945. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  158946. cinfo->progress->pass_limit = (long) cinfo->image_height;
  158947. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  158948. }
  158949. /* Give master control module another chance if this is first call to
  158950. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  158951. * delayed so that application can write COM, etc, markers between
  158952. * jpeg_start_compress and jpeg_write_scanlines.
  158953. */
  158954. if (cinfo->master->call_pass_startup)
  158955. (*cinfo->master->pass_startup) (cinfo);
  158956. /* Ignore any extra scanlines at bottom of image. */
  158957. rows_left = cinfo->image_height - cinfo->next_scanline;
  158958. if (num_lines > rows_left)
  158959. num_lines = rows_left;
  158960. row_ctr = 0;
  158961. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  158962. cinfo->next_scanline += row_ctr;
  158963. return row_ctr;
  158964. }
  158965. /*
  158966. * Alternate entry point to write raw data.
  158967. * Processes exactly one iMCU row per call, unless suspended.
  158968. */
  158969. GLOBAL(JDIMENSION)
  158970. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  158971. JDIMENSION num_lines)
  158972. {
  158973. JDIMENSION lines_per_iMCU_row;
  158974. if (cinfo->global_state != CSTATE_RAW_OK)
  158975. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158976. if (cinfo->next_scanline >= cinfo->image_height) {
  158977. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  158978. return 0;
  158979. }
  158980. /* Call progress monitor hook if present */
  158981. if (cinfo->progress != NULL) {
  158982. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  158983. cinfo->progress->pass_limit = (long) cinfo->image_height;
  158984. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  158985. }
  158986. /* Give master control module another chance if this is first call to
  158987. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  158988. * delayed so that application can write COM, etc, markers between
  158989. * jpeg_start_compress and jpeg_write_raw_data.
  158990. */
  158991. if (cinfo->master->call_pass_startup)
  158992. (*cinfo->master->pass_startup) (cinfo);
  158993. /* Verify that at least one iMCU row has been passed. */
  158994. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  158995. if (num_lines < lines_per_iMCU_row)
  158996. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  158997. /* Directly compress the row. */
  158998. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  158999. /* If compressor did not consume the whole row, suspend processing. */
  159000. return 0;
  159001. }
  159002. /* OK, we processed one iMCU row. */
  159003. cinfo->next_scanline += lines_per_iMCU_row;
  159004. return lines_per_iMCU_row;
  159005. }
  159006. /*** End of inlined file: jcapistd.c ***/
  159007. /*** Start of inlined file: jccoefct.c ***/
  159008. #define JPEG_INTERNALS
  159009. /* We use a full-image coefficient buffer when doing Huffman optimization,
  159010. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  159011. * step is run during the first pass, and subsequent passes need only read
  159012. * the buffered coefficients.
  159013. */
  159014. #ifdef ENTROPY_OPT_SUPPORTED
  159015. #define FULL_COEF_BUFFER_SUPPORTED
  159016. #else
  159017. #ifdef C_MULTISCAN_FILES_SUPPORTED
  159018. #define FULL_COEF_BUFFER_SUPPORTED
  159019. #endif
  159020. #endif
  159021. /* Private buffer controller object */
  159022. typedef struct {
  159023. struct jpeg_c_coef_controller pub; /* public fields */
  159024. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  159025. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  159026. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  159027. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  159028. /* For single-pass compression, it's sufficient to buffer just one MCU
  159029. * (although this may prove a bit slow in practice). We allocate a
  159030. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  159031. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  159032. * it's not really very big; this is to keep the module interfaces unchanged
  159033. * when a large coefficient buffer is necessary.)
  159034. * In multi-pass modes, this array points to the current MCU's blocks
  159035. * within the virtual arrays.
  159036. */
  159037. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  159038. /* In multi-pass modes, we need a virtual block array for each component. */
  159039. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  159040. } my_coef_controller;
  159041. typedef my_coef_controller * my_coef_ptr;
  159042. /* Forward declarations */
  159043. METHODDEF(boolean) compress_data
  159044. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  159045. #ifdef FULL_COEF_BUFFER_SUPPORTED
  159046. METHODDEF(boolean) compress_first_pass
  159047. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  159048. METHODDEF(boolean) compress_output
  159049. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  159050. #endif
  159051. LOCAL(void)
  159052. start_iMCU_row (j_compress_ptr cinfo)
  159053. /* Reset within-iMCU-row counters for a new row */
  159054. {
  159055. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  159056. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  159057. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  159058. * But at the bottom of the image, process only what's left.
  159059. */
  159060. if (cinfo->comps_in_scan > 1) {
  159061. coef->MCU_rows_per_iMCU_row = 1;
  159062. } else {
  159063. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  159064. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  159065. else
  159066. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  159067. }
  159068. coef->mcu_ctr = 0;
  159069. coef->MCU_vert_offset = 0;
  159070. }
  159071. /*
  159072. * Initialize for a processing pass.
  159073. */
  159074. METHODDEF(void)
  159075. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  159076. {
  159077. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  159078. coef->iMCU_row_num = 0;
  159079. start_iMCU_row(cinfo);
  159080. switch (pass_mode) {
  159081. case JBUF_PASS_THRU:
  159082. if (coef->whole_image[0] != NULL)
  159083. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  159084. coef->pub.compress_data = compress_data;
  159085. break;
  159086. #ifdef FULL_COEF_BUFFER_SUPPORTED
  159087. case JBUF_SAVE_AND_PASS:
  159088. if (coef->whole_image[0] == NULL)
  159089. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  159090. coef->pub.compress_data = compress_first_pass;
  159091. break;
  159092. case JBUF_CRANK_DEST:
  159093. if (coef->whole_image[0] == NULL)
  159094. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  159095. coef->pub.compress_data = compress_output;
  159096. break;
  159097. #endif
  159098. default:
  159099. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  159100. break;
  159101. }
  159102. }
  159103. /*
  159104. * Process some data in the single-pass case.
  159105. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  159106. * per call, ie, v_samp_factor block rows for each component in the image.
  159107. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  159108. *
  159109. * NB: input_buf contains a plane for each component in image,
  159110. * which we index according to the component's SOF position.
  159111. */
  159112. METHODDEF(boolean)
  159113. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  159114. {
  159115. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  159116. JDIMENSION MCU_col_num; /* index of current MCU within row */
  159117. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  159118. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  159119. int blkn, bi, ci, yindex, yoffset, blockcnt;
  159120. JDIMENSION ypos, xpos;
  159121. jpeg_component_info *compptr;
  159122. /* Loop to write as much as one whole iMCU row */
  159123. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  159124. yoffset++) {
  159125. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  159126. MCU_col_num++) {
  159127. /* Determine where data comes from in input_buf and do the DCT thing.
  159128. * Each call on forward_DCT processes a horizontal row of DCT blocks
  159129. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  159130. * sequentially. Dummy blocks at the right or bottom edge are filled in
  159131. * specially. The data in them does not matter for image reconstruction,
  159132. * so we fill them with values that will encode to the smallest amount of
  159133. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  159134. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  159135. */
  159136. blkn = 0;
  159137. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  159138. compptr = cinfo->cur_comp_info[ci];
  159139. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  159140. : compptr->last_col_width;
  159141. xpos = MCU_col_num * compptr->MCU_sample_width;
  159142. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  159143. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  159144. if (coef->iMCU_row_num < last_iMCU_row ||
  159145. yoffset+yindex < compptr->last_row_height) {
  159146. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  159147. input_buf[compptr->component_index],
  159148. coef->MCU_buffer[blkn],
  159149. ypos, xpos, (JDIMENSION) blockcnt);
  159150. if (blockcnt < compptr->MCU_width) {
  159151. /* Create some dummy blocks at the right edge of the image. */
  159152. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  159153. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  159154. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  159155. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  159156. }
  159157. }
  159158. } else {
  159159. /* Create a row of dummy blocks at the bottom of the image. */
  159160. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  159161. compptr->MCU_width * SIZEOF(JBLOCK));
  159162. for (bi = 0; bi < compptr->MCU_width; bi++) {
  159163. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  159164. }
  159165. }
  159166. blkn += compptr->MCU_width;
  159167. ypos += DCTSIZE;
  159168. }
  159169. }
  159170. /* Try to write the MCU. In event of a suspension failure, we will
  159171. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  159172. */
  159173. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  159174. /* Suspension forced; update state counters and exit */
  159175. coef->MCU_vert_offset = yoffset;
  159176. coef->mcu_ctr = MCU_col_num;
  159177. return FALSE;
  159178. }
  159179. }
  159180. /* Completed an MCU row, but perhaps not an iMCU row */
  159181. coef->mcu_ctr = 0;
  159182. }
  159183. /* Completed the iMCU row, advance counters for next one */
  159184. coef->iMCU_row_num++;
  159185. start_iMCU_row(cinfo);
  159186. return TRUE;
  159187. }
  159188. #ifdef FULL_COEF_BUFFER_SUPPORTED
  159189. /*
  159190. * Process some data in the first pass of a multi-pass case.
  159191. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  159192. * per call, ie, v_samp_factor block rows for each component in the image.
  159193. * This amount of data is read from the source buffer, DCT'd and quantized,
  159194. * and saved into the virtual arrays. We also generate suitable dummy blocks
  159195. * as needed at the right and lower edges. (The dummy blocks are constructed
  159196. * in the virtual arrays, which have been padded appropriately.) This makes
  159197. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  159198. *
  159199. * We must also emit the data to the entropy encoder. This is conveniently
  159200. * done by calling compress_output() after we've loaded the current strip
  159201. * of the virtual arrays.
  159202. *
  159203. * NB: input_buf contains a plane for each component in image. All
  159204. * components are DCT'd and loaded into the virtual arrays in this pass.
  159205. * However, it may be that only a subset of the components are emitted to
  159206. * the entropy encoder during this first pass; be careful about looking
  159207. * at the scan-dependent variables (MCU dimensions, etc).
  159208. */
  159209. METHODDEF(boolean)
  159210. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  159211. {
  159212. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  159213. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  159214. JDIMENSION blocks_across, MCUs_across, MCUindex;
  159215. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  159216. JCOEF lastDC;
  159217. jpeg_component_info *compptr;
  159218. JBLOCKARRAY buffer;
  159219. JBLOCKROW thisblockrow, lastblockrow;
  159220. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159221. ci++, compptr++) {
  159222. /* Align the virtual buffer for this component. */
  159223. buffer = (*cinfo->mem->access_virt_barray)
  159224. ((j_common_ptr) cinfo, coef->whole_image[ci],
  159225. coef->iMCU_row_num * compptr->v_samp_factor,
  159226. (JDIMENSION) compptr->v_samp_factor, TRUE);
  159227. /* Count non-dummy DCT block rows in this iMCU row. */
  159228. if (coef->iMCU_row_num < last_iMCU_row)
  159229. block_rows = compptr->v_samp_factor;
  159230. else {
  159231. /* NB: can't use last_row_height here, since may not be set! */
  159232. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  159233. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  159234. }
  159235. blocks_across = compptr->width_in_blocks;
  159236. h_samp_factor = compptr->h_samp_factor;
  159237. /* Count number of dummy blocks to be added at the right margin. */
  159238. ndummy = (int) (blocks_across % h_samp_factor);
  159239. if (ndummy > 0)
  159240. ndummy = h_samp_factor - ndummy;
  159241. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  159242. * on forward_DCT processes a complete horizontal row of DCT blocks.
  159243. */
  159244. for (block_row = 0; block_row < block_rows; block_row++) {
  159245. thisblockrow = buffer[block_row];
  159246. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  159247. input_buf[ci], thisblockrow,
  159248. (JDIMENSION) (block_row * DCTSIZE),
  159249. (JDIMENSION) 0, blocks_across);
  159250. if (ndummy > 0) {
  159251. /* Create dummy blocks at the right edge of the image. */
  159252. thisblockrow += blocks_across; /* => first dummy block */
  159253. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  159254. lastDC = thisblockrow[-1][0];
  159255. for (bi = 0; bi < ndummy; bi++) {
  159256. thisblockrow[bi][0] = lastDC;
  159257. }
  159258. }
  159259. }
  159260. /* If at end of image, create dummy block rows as needed.
  159261. * The tricky part here is that within each MCU, we want the DC values
  159262. * of the dummy blocks to match the last real block's DC value.
  159263. * This squeezes a few more bytes out of the resulting file...
  159264. */
  159265. if (coef->iMCU_row_num == last_iMCU_row) {
  159266. blocks_across += ndummy; /* include lower right corner */
  159267. MCUs_across = blocks_across / h_samp_factor;
  159268. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  159269. block_row++) {
  159270. thisblockrow = buffer[block_row];
  159271. lastblockrow = buffer[block_row-1];
  159272. jzero_far((void FAR *) thisblockrow,
  159273. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  159274. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  159275. lastDC = lastblockrow[h_samp_factor-1][0];
  159276. for (bi = 0; bi < h_samp_factor; bi++) {
  159277. thisblockrow[bi][0] = lastDC;
  159278. }
  159279. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  159280. lastblockrow += h_samp_factor;
  159281. }
  159282. }
  159283. }
  159284. }
  159285. /* NB: compress_output will increment iMCU_row_num if successful.
  159286. * A suspension return will result in redoing all the work above next time.
  159287. */
  159288. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  159289. return compress_output(cinfo, input_buf);
  159290. }
  159291. /*
  159292. * Process some data in subsequent passes of a multi-pass case.
  159293. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  159294. * per call, ie, v_samp_factor block rows for each component in the scan.
  159295. * The data is obtained from the virtual arrays and fed to the entropy coder.
  159296. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  159297. *
  159298. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  159299. */
  159300. METHODDEF(boolean)
  159301. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  159302. {
  159303. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  159304. JDIMENSION MCU_col_num; /* index of current MCU within row */
  159305. int blkn, ci, xindex, yindex, yoffset;
  159306. JDIMENSION start_col;
  159307. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  159308. JBLOCKROW buffer_ptr;
  159309. jpeg_component_info *compptr;
  159310. /* Align the virtual buffers for the components used in this scan.
  159311. * NB: during first pass, this is safe only because the buffers will
  159312. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  159313. */
  159314. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  159315. compptr = cinfo->cur_comp_info[ci];
  159316. buffer[ci] = (*cinfo->mem->access_virt_barray)
  159317. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  159318. coef->iMCU_row_num * compptr->v_samp_factor,
  159319. (JDIMENSION) compptr->v_samp_factor, FALSE);
  159320. }
  159321. /* Loop to process one whole iMCU row */
  159322. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  159323. yoffset++) {
  159324. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  159325. MCU_col_num++) {
  159326. /* Construct list of pointers to DCT blocks belonging to this MCU */
  159327. blkn = 0; /* index of current DCT block within MCU */
  159328. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  159329. compptr = cinfo->cur_comp_info[ci];
  159330. start_col = MCU_col_num * compptr->MCU_width;
  159331. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  159332. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  159333. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  159334. coef->MCU_buffer[blkn++] = buffer_ptr++;
  159335. }
  159336. }
  159337. }
  159338. /* Try to write the MCU. */
  159339. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  159340. /* Suspension forced; update state counters and exit */
  159341. coef->MCU_vert_offset = yoffset;
  159342. coef->mcu_ctr = MCU_col_num;
  159343. return FALSE;
  159344. }
  159345. }
  159346. /* Completed an MCU row, but perhaps not an iMCU row */
  159347. coef->mcu_ctr = 0;
  159348. }
  159349. /* Completed the iMCU row, advance counters for next one */
  159350. coef->iMCU_row_num++;
  159351. start_iMCU_row(cinfo);
  159352. return TRUE;
  159353. }
  159354. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  159355. /*
  159356. * Initialize coefficient buffer controller.
  159357. */
  159358. GLOBAL(void)
  159359. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  159360. {
  159361. my_coef_ptr coef;
  159362. coef = (my_coef_ptr)
  159363. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159364. SIZEOF(my_coef_controller));
  159365. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  159366. coef->pub.start_pass = start_pass_coef;
  159367. /* Create the coefficient buffer. */
  159368. if (need_full_buffer) {
  159369. #ifdef FULL_COEF_BUFFER_SUPPORTED
  159370. /* Allocate a full-image virtual array for each component, */
  159371. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  159372. int ci;
  159373. jpeg_component_info *compptr;
  159374. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159375. ci++, compptr++) {
  159376. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  159377. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  159378. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  159379. (long) compptr->h_samp_factor),
  159380. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  159381. (long) compptr->v_samp_factor),
  159382. (JDIMENSION) compptr->v_samp_factor);
  159383. }
  159384. #else
  159385. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  159386. #endif
  159387. } else {
  159388. /* We only need a single-MCU buffer. */
  159389. JBLOCKROW buffer;
  159390. int i;
  159391. buffer = (JBLOCKROW)
  159392. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159393. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  159394. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  159395. coef->MCU_buffer[i] = buffer + i;
  159396. }
  159397. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  159398. }
  159399. }
  159400. /*** End of inlined file: jccoefct.c ***/
  159401. /*** Start of inlined file: jccolor.c ***/
  159402. #define JPEG_INTERNALS
  159403. /* Private subobject */
  159404. typedef struct {
  159405. struct jpeg_color_converter pub; /* public fields */
  159406. /* Private state for RGB->YCC conversion */
  159407. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  159408. } my_color_converter;
  159409. typedef my_color_converter * my_cconvert_ptr;
  159410. /**************** RGB -> YCbCr conversion: most common case **************/
  159411. /*
  159412. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  159413. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  159414. * The conversion equations to be implemented are therefore
  159415. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  159416. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  159417. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  159418. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  159419. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  159420. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  159421. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  159422. * were not represented exactly. Now we sacrifice exact representation of
  159423. * maximum red and maximum blue in order to get exact grayscales.
  159424. *
  159425. * To avoid floating-point arithmetic, we represent the fractional constants
  159426. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  159427. * the products by 2^16, with appropriate rounding, to get the correct answer.
  159428. *
  159429. * For even more speed, we avoid doing any multiplications in the inner loop
  159430. * by precalculating the constants times R,G,B for all possible values.
  159431. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  159432. * for 12-bit samples it is still acceptable. It's not very reasonable for
  159433. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  159434. * colorspace anyway.
  159435. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  159436. * in the tables to save adding them separately in the inner loop.
  159437. */
  159438. #define SCALEBITS 16 /* speediest right-shift on some machines */
  159439. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  159440. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  159441. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  159442. /* We allocate one big table and divide it up into eight parts, instead of
  159443. * doing eight alloc_small requests. This lets us use a single table base
  159444. * address, which can be held in a register in the inner loops on many
  159445. * machines (more than can hold all eight addresses, anyway).
  159446. */
  159447. #define R_Y_OFF 0 /* offset to R => Y section */
  159448. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  159449. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  159450. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  159451. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  159452. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  159453. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  159454. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  159455. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  159456. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  159457. /*
  159458. * Initialize for RGB->YCC colorspace conversion.
  159459. */
  159460. METHODDEF(void)
  159461. rgb_ycc_start (j_compress_ptr cinfo)
  159462. {
  159463. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  159464. INT32 * rgb_ycc_tab;
  159465. INT32 i;
  159466. /* Allocate and fill in the conversion tables. */
  159467. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  159468. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159469. (TABLE_SIZE * SIZEOF(INT32)));
  159470. for (i = 0; i <= MAXJSAMPLE; i++) {
  159471. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  159472. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  159473. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  159474. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  159475. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  159476. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  159477. * This ensures that the maximum output will round to MAXJSAMPLE
  159478. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  159479. */
  159480. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  159481. /* B=>Cb and R=>Cr tables are the same
  159482. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  159483. */
  159484. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  159485. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  159486. }
  159487. }
  159488. /*
  159489. * Convert some rows of samples to the JPEG colorspace.
  159490. *
  159491. * Note that we change from the application's interleaved-pixel format
  159492. * to our internal noninterleaved, one-plane-per-component format.
  159493. * The input buffer is therefore three times as wide as the output buffer.
  159494. *
  159495. * A starting row offset is provided only for the output buffer. The caller
  159496. * can easily adjust the passed input_buf value to accommodate any row
  159497. * offset required on that side.
  159498. */
  159499. METHODDEF(void)
  159500. rgb_ycc_convert (j_compress_ptr cinfo,
  159501. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  159502. JDIMENSION output_row, int num_rows)
  159503. {
  159504. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  159505. register int r, g, b;
  159506. register INT32 * ctab = cconvert->rgb_ycc_tab;
  159507. register JSAMPROW inptr;
  159508. register JSAMPROW outptr0, outptr1, outptr2;
  159509. register JDIMENSION col;
  159510. JDIMENSION num_cols = cinfo->image_width;
  159511. while (--num_rows >= 0) {
  159512. inptr = *input_buf++;
  159513. outptr0 = output_buf[0][output_row];
  159514. outptr1 = output_buf[1][output_row];
  159515. outptr2 = output_buf[2][output_row];
  159516. output_row++;
  159517. for (col = 0; col < num_cols; col++) {
  159518. r = GETJSAMPLE(inptr[RGB_RED]);
  159519. g = GETJSAMPLE(inptr[RGB_GREEN]);
  159520. b = GETJSAMPLE(inptr[RGB_BLUE]);
  159521. inptr += RGB_PIXELSIZE;
  159522. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  159523. * must be too; we do not need an explicit range-limiting operation.
  159524. * Hence the value being shifted is never negative, and we don't
  159525. * need the general RIGHT_SHIFT macro.
  159526. */
  159527. /* Y */
  159528. outptr0[col] = (JSAMPLE)
  159529. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  159530. >> SCALEBITS);
  159531. /* Cb */
  159532. outptr1[col] = (JSAMPLE)
  159533. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  159534. >> SCALEBITS);
  159535. /* Cr */
  159536. outptr2[col] = (JSAMPLE)
  159537. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  159538. >> SCALEBITS);
  159539. }
  159540. }
  159541. }
  159542. /**************** Cases other than RGB -> YCbCr **************/
  159543. /*
  159544. * Convert some rows of samples to the JPEG colorspace.
  159545. * This version handles RGB->grayscale conversion, which is the same
  159546. * as the RGB->Y portion of RGB->YCbCr.
  159547. * We assume rgb_ycc_start has been called (we only use the Y tables).
  159548. */
  159549. METHODDEF(void)
  159550. rgb_gray_convert (j_compress_ptr cinfo,
  159551. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  159552. JDIMENSION output_row, int num_rows)
  159553. {
  159554. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  159555. register int r, g, b;
  159556. register INT32 * ctab = cconvert->rgb_ycc_tab;
  159557. register JSAMPROW inptr;
  159558. register JSAMPROW outptr;
  159559. register JDIMENSION col;
  159560. JDIMENSION num_cols = cinfo->image_width;
  159561. while (--num_rows >= 0) {
  159562. inptr = *input_buf++;
  159563. outptr = output_buf[0][output_row];
  159564. output_row++;
  159565. for (col = 0; col < num_cols; col++) {
  159566. r = GETJSAMPLE(inptr[RGB_RED]);
  159567. g = GETJSAMPLE(inptr[RGB_GREEN]);
  159568. b = GETJSAMPLE(inptr[RGB_BLUE]);
  159569. inptr += RGB_PIXELSIZE;
  159570. /* Y */
  159571. outptr[col] = (JSAMPLE)
  159572. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  159573. >> SCALEBITS);
  159574. }
  159575. }
  159576. }
  159577. /*
  159578. * Convert some rows of samples to the JPEG colorspace.
  159579. * This version handles Adobe-style CMYK->YCCK conversion,
  159580. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  159581. * conversion as above, while passing K (black) unchanged.
  159582. * We assume rgb_ycc_start has been called.
  159583. */
  159584. METHODDEF(void)
  159585. cmyk_ycck_convert (j_compress_ptr cinfo,
  159586. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  159587. JDIMENSION output_row, int num_rows)
  159588. {
  159589. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  159590. register int r, g, b;
  159591. register INT32 * ctab = cconvert->rgb_ycc_tab;
  159592. register JSAMPROW inptr;
  159593. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  159594. register JDIMENSION col;
  159595. JDIMENSION num_cols = cinfo->image_width;
  159596. while (--num_rows >= 0) {
  159597. inptr = *input_buf++;
  159598. outptr0 = output_buf[0][output_row];
  159599. outptr1 = output_buf[1][output_row];
  159600. outptr2 = output_buf[2][output_row];
  159601. outptr3 = output_buf[3][output_row];
  159602. output_row++;
  159603. for (col = 0; col < num_cols; col++) {
  159604. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  159605. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  159606. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  159607. /* K passes through as-is */
  159608. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  159609. inptr += 4;
  159610. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  159611. * must be too; we do not need an explicit range-limiting operation.
  159612. * Hence the value being shifted is never negative, and we don't
  159613. * need the general RIGHT_SHIFT macro.
  159614. */
  159615. /* Y */
  159616. outptr0[col] = (JSAMPLE)
  159617. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  159618. >> SCALEBITS);
  159619. /* Cb */
  159620. outptr1[col] = (JSAMPLE)
  159621. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  159622. >> SCALEBITS);
  159623. /* Cr */
  159624. outptr2[col] = (JSAMPLE)
  159625. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  159626. >> SCALEBITS);
  159627. }
  159628. }
  159629. }
  159630. /*
  159631. * Convert some rows of samples to the JPEG colorspace.
  159632. * This version handles grayscale output with no conversion.
  159633. * The source can be either plain grayscale or YCbCr (since Y == gray).
  159634. */
  159635. METHODDEF(void)
  159636. grayscale_convert (j_compress_ptr cinfo,
  159637. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  159638. JDIMENSION output_row, int num_rows)
  159639. {
  159640. register JSAMPROW inptr;
  159641. register JSAMPROW outptr;
  159642. register JDIMENSION col;
  159643. JDIMENSION num_cols = cinfo->image_width;
  159644. int instride = cinfo->input_components;
  159645. while (--num_rows >= 0) {
  159646. inptr = *input_buf++;
  159647. outptr = output_buf[0][output_row];
  159648. output_row++;
  159649. for (col = 0; col < num_cols; col++) {
  159650. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  159651. inptr += instride;
  159652. }
  159653. }
  159654. }
  159655. /*
  159656. * Convert some rows of samples to the JPEG colorspace.
  159657. * This version handles multi-component colorspaces without conversion.
  159658. * We assume input_components == num_components.
  159659. */
  159660. METHODDEF(void)
  159661. null_convert (j_compress_ptr cinfo,
  159662. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  159663. JDIMENSION output_row, int num_rows)
  159664. {
  159665. register JSAMPROW inptr;
  159666. register JSAMPROW outptr;
  159667. register JDIMENSION col;
  159668. register int ci;
  159669. int nc = cinfo->num_components;
  159670. JDIMENSION num_cols = cinfo->image_width;
  159671. while (--num_rows >= 0) {
  159672. /* It seems fastest to make a separate pass for each component. */
  159673. for (ci = 0; ci < nc; ci++) {
  159674. inptr = *input_buf;
  159675. outptr = output_buf[ci][output_row];
  159676. for (col = 0; col < num_cols; col++) {
  159677. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  159678. inptr += nc;
  159679. }
  159680. }
  159681. input_buf++;
  159682. output_row++;
  159683. }
  159684. }
  159685. /*
  159686. * Empty method for start_pass.
  159687. */
  159688. METHODDEF(void)
  159689. null_method (j_compress_ptr)
  159690. {
  159691. /* no work needed */
  159692. }
  159693. /*
  159694. * Module initialization routine for input colorspace conversion.
  159695. */
  159696. GLOBAL(void)
  159697. jinit_color_converter (j_compress_ptr cinfo)
  159698. {
  159699. my_cconvert_ptr cconvert;
  159700. cconvert = (my_cconvert_ptr)
  159701. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159702. SIZEOF(my_color_converter));
  159703. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  159704. /* set start_pass to null method until we find out differently */
  159705. cconvert->pub.start_pass = null_method;
  159706. /* Make sure input_components agrees with in_color_space */
  159707. switch (cinfo->in_color_space) {
  159708. case JCS_GRAYSCALE:
  159709. if (cinfo->input_components != 1)
  159710. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  159711. break;
  159712. case JCS_RGB:
  159713. #if RGB_PIXELSIZE != 3
  159714. if (cinfo->input_components != RGB_PIXELSIZE)
  159715. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  159716. break;
  159717. #endif /* else share code with YCbCr */
  159718. case JCS_YCbCr:
  159719. if (cinfo->input_components != 3)
  159720. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  159721. break;
  159722. case JCS_CMYK:
  159723. case JCS_YCCK:
  159724. if (cinfo->input_components != 4)
  159725. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  159726. break;
  159727. default: /* JCS_UNKNOWN can be anything */
  159728. if (cinfo->input_components < 1)
  159729. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  159730. break;
  159731. }
  159732. /* Check num_components, set conversion method based on requested space */
  159733. switch (cinfo->jpeg_color_space) {
  159734. case JCS_GRAYSCALE:
  159735. if (cinfo->num_components != 1)
  159736. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  159737. if (cinfo->in_color_space == JCS_GRAYSCALE)
  159738. cconvert->pub.color_convert = grayscale_convert;
  159739. else if (cinfo->in_color_space == JCS_RGB) {
  159740. cconvert->pub.start_pass = rgb_ycc_start;
  159741. cconvert->pub.color_convert = rgb_gray_convert;
  159742. } else if (cinfo->in_color_space == JCS_YCbCr)
  159743. cconvert->pub.color_convert = grayscale_convert;
  159744. else
  159745. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  159746. break;
  159747. case JCS_RGB:
  159748. if (cinfo->num_components != 3)
  159749. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  159750. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  159751. cconvert->pub.color_convert = null_convert;
  159752. else
  159753. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  159754. break;
  159755. case JCS_YCbCr:
  159756. if (cinfo->num_components != 3)
  159757. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  159758. if (cinfo->in_color_space == JCS_RGB) {
  159759. cconvert->pub.start_pass = rgb_ycc_start;
  159760. cconvert->pub.color_convert = rgb_ycc_convert;
  159761. } else if (cinfo->in_color_space == JCS_YCbCr)
  159762. cconvert->pub.color_convert = null_convert;
  159763. else
  159764. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  159765. break;
  159766. case JCS_CMYK:
  159767. if (cinfo->num_components != 4)
  159768. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  159769. if (cinfo->in_color_space == JCS_CMYK)
  159770. cconvert->pub.color_convert = null_convert;
  159771. else
  159772. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  159773. break;
  159774. case JCS_YCCK:
  159775. if (cinfo->num_components != 4)
  159776. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  159777. if (cinfo->in_color_space == JCS_CMYK) {
  159778. cconvert->pub.start_pass = rgb_ycc_start;
  159779. cconvert->pub.color_convert = cmyk_ycck_convert;
  159780. } else if (cinfo->in_color_space == JCS_YCCK)
  159781. cconvert->pub.color_convert = null_convert;
  159782. else
  159783. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  159784. break;
  159785. default: /* allow null conversion of JCS_UNKNOWN */
  159786. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  159787. cinfo->num_components != cinfo->input_components)
  159788. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  159789. cconvert->pub.color_convert = null_convert;
  159790. break;
  159791. }
  159792. }
  159793. /*** End of inlined file: jccolor.c ***/
  159794. #undef FIX
  159795. /*** Start of inlined file: jcdctmgr.c ***/
  159796. #define JPEG_INTERNALS
  159797. /*** Start of inlined file: jdct.h ***/
  159798. /*
  159799. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  159800. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  159801. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  159802. * implementations use an array of type FAST_FLOAT, instead.)
  159803. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  159804. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  159805. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  159806. * convention improves accuracy in integer implementations and saves some
  159807. * work in floating-point ones.
  159808. * Quantization of the output coefficients is done by jcdctmgr.c.
  159809. */
  159810. #ifndef __jdct_h__
  159811. #define __jdct_h__
  159812. #if BITS_IN_JSAMPLE == 8
  159813. typedef int DCTELEM; /* 16 or 32 bits is fine */
  159814. #else
  159815. typedef INT32 DCTELEM; /* must have 32 bits */
  159816. #endif
  159817. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  159818. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  159819. /*
  159820. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  159821. * to an output sample array. The routine must dequantize the input data as
  159822. * well as perform the IDCT; for dequantization, it uses the multiplier table
  159823. * pointed to by compptr->dct_table. The output data is to be placed into the
  159824. * sample array starting at a specified column. (Any row offset needed will
  159825. * be applied to the array pointer before it is passed to the IDCT code.)
  159826. * Note that the number of samples emitted by the IDCT routine is
  159827. * DCT_scaled_size * DCT_scaled_size.
  159828. */
  159829. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  159830. /*
  159831. * Each IDCT routine has its own ideas about the best dct_table element type.
  159832. */
  159833. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  159834. #if BITS_IN_JSAMPLE == 8
  159835. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  159836. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  159837. #else
  159838. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  159839. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  159840. #endif
  159841. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  159842. /*
  159843. * Each IDCT routine is responsible for range-limiting its results and
  159844. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  159845. * be quite far out of range if the input data is corrupt, so a bulletproof
  159846. * range-limiting step is required. We use a mask-and-table-lookup method
  159847. * to do the combined operations quickly. See the comments with
  159848. * prepare_range_limit_table (in jdmaster.c) for more info.
  159849. */
  159850. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  159851. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  159852. /* Short forms of external names for systems with brain-damaged linkers. */
  159853. #ifdef NEED_SHORT_EXTERNAL_NAMES
  159854. #define jpeg_fdct_islow jFDislow
  159855. #define jpeg_fdct_ifast jFDifast
  159856. #define jpeg_fdct_float jFDfloat
  159857. #define jpeg_idct_islow jRDislow
  159858. #define jpeg_idct_ifast jRDifast
  159859. #define jpeg_idct_float jRDfloat
  159860. #define jpeg_idct_4x4 jRD4x4
  159861. #define jpeg_idct_2x2 jRD2x2
  159862. #define jpeg_idct_1x1 jRD1x1
  159863. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  159864. /* Extern declarations for the forward and inverse DCT routines. */
  159865. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  159866. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  159867. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  159868. EXTERN(void) jpeg_idct_islow
  159869. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  159870. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  159871. EXTERN(void) jpeg_idct_ifast
  159872. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  159873. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  159874. EXTERN(void) jpeg_idct_float
  159875. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  159876. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  159877. EXTERN(void) jpeg_idct_4x4
  159878. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  159879. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  159880. EXTERN(void) jpeg_idct_2x2
  159881. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  159882. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  159883. EXTERN(void) jpeg_idct_1x1
  159884. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  159885. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  159886. /*
  159887. * Macros for handling fixed-point arithmetic; these are used by many
  159888. * but not all of the DCT/IDCT modules.
  159889. *
  159890. * All values are expected to be of type INT32.
  159891. * Fractional constants are scaled left by CONST_BITS bits.
  159892. * CONST_BITS is defined within each module using these macros,
  159893. * and may differ from one module to the next.
  159894. */
  159895. #define ONE ((INT32) 1)
  159896. #define CONST_SCALE (ONE << CONST_BITS)
  159897. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  159898. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  159899. * thus causing a lot of useless floating-point operations at run time.
  159900. */
  159901. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  159902. /* Descale and correctly round an INT32 value that's scaled by N bits.
  159903. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  159904. * the fudge factor is correct for either sign of X.
  159905. */
  159906. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  159907. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  159908. * This macro is used only when the two inputs will actually be no more than
  159909. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  159910. * full 32x32 multiply. This provides a useful speedup on many machines.
  159911. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  159912. * in C, but some C compilers will do the right thing if you provide the
  159913. * correct combination of casts.
  159914. */
  159915. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  159916. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  159917. #endif
  159918. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  159919. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  159920. #endif
  159921. #ifndef MULTIPLY16C16 /* default definition */
  159922. #define MULTIPLY16C16(var,const) ((var) * (const))
  159923. #endif
  159924. /* Same except both inputs are variables. */
  159925. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  159926. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  159927. #endif
  159928. #ifndef MULTIPLY16V16 /* default definition */
  159929. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  159930. #endif
  159931. #endif
  159932. /*** End of inlined file: jdct.h ***/
  159933. /* Private declarations for DCT subsystem */
  159934. /* Private subobject for this module */
  159935. typedef struct {
  159936. struct jpeg_forward_dct pub; /* public fields */
  159937. /* Pointer to the DCT routine actually in use */
  159938. forward_DCT_method_ptr do_dct;
  159939. /* The actual post-DCT divisors --- not identical to the quant table
  159940. * entries, because of scaling (especially for an unnormalized DCT).
  159941. * Each table is given in normal array order.
  159942. */
  159943. DCTELEM * divisors[NUM_QUANT_TBLS];
  159944. #ifdef DCT_FLOAT_SUPPORTED
  159945. /* Same as above for the floating-point case. */
  159946. float_DCT_method_ptr do_float_dct;
  159947. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  159948. #endif
  159949. } my_fdct_controller;
  159950. typedef my_fdct_controller * my_fdct_ptr;
  159951. /*
  159952. * Initialize for a processing pass.
  159953. * Verify that all referenced Q-tables are present, and set up
  159954. * the divisor table for each one.
  159955. * In the current implementation, DCT of all components is done during
  159956. * the first pass, even if only some components will be output in the
  159957. * first scan. Hence all components should be examined here.
  159958. */
  159959. METHODDEF(void)
  159960. start_pass_fdctmgr (j_compress_ptr cinfo)
  159961. {
  159962. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  159963. int ci, qtblno, i;
  159964. jpeg_component_info *compptr;
  159965. JQUANT_TBL * qtbl;
  159966. DCTELEM * dtbl;
  159967. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159968. ci++, compptr++) {
  159969. qtblno = compptr->quant_tbl_no;
  159970. /* Make sure specified quantization table is present */
  159971. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  159972. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  159973. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  159974. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  159975. /* Compute divisors for this quant table */
  159976. /* We may do this more than once for same table, but it's not a big deal */
  159977. switch (cinfo->dct_method) {
  159978. #ifdef DCT_ISLOW_SUPPORTED
  159979. case JDCT_ISLOW:
  159980. /* For LL&M IDCT method, divisors are equal to raw quantization
  159981. * coefficients multiplied by 8 (to counteract scaling).
  159982. */
  159983. if (fdct->divisors[qtblno] == NULL) {
  159984. fdct->divisors[qtblno] = (DCTELEM *)
  159985. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159986. DCTSIZE2 * SIZEOF(DCTELEM));
  159987. }
  159988. dtbl = fdct->divisors[qtblno];
  159989. for (i = 0; i < DCTSIZE2; i++) {
  159990. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  159991. }
  159992. break;
  159993. #endif
  159994. #ifdef DCT_IFAST_SUPPORTED
  159995. case JDCT_IFAST:
  159996. {
  159997. /* For AA&N IDCT method, divisors are equal to quantization
  159998. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  159999. * scalefactor[0] = 1
  160000. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  160001. * We apply a further scale factor of 8.
  160002. */
  160003. #define CONST_BITS 14
  160004. static const INT16 aanscales[DCTSIZE2] = {
  160005. /* precomputed values scaled up by 14 bits */
  160006. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  160007. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  160008. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  160009. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  160010. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  160011. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  160012. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  160013. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  160014. };
  160015. SHIFT_TEMPS
  160016. if (fdct->divisors[qtblno] == NULL) {
  160017. fdct->divisors[qtblno] = (DCTELEM *)
  160018. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160019. DCTSIZE2 * SIZEOF(DCTELEM));
  160020. }
  160021. dtbl = fdct->divisors[qtblno];
  160022. for (i = 0; i < DCTSIZE2; i++) {
  160023. dtbl[i] = (DCTELEM)
  160024. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  160025. (INT32) aanscales[i]),
  160026. CONST_BITS-3);
  160027. }
  160028. }
  160029. break;
  160030. #endif
  160031. #ifdef DCT_FLOAT_SUPPORTED
  160032. case JDCT_FLOAT:
  160033. {
  160034. /* For float AA&N IDCT method, divisors are equal to quantization
  160035. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  160036. * scalefactor[0] = 1
  160037. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  160038. * We apply a further scale factor of 8.
  160039. * What's actually stored is 1/divisor so that the inner loop can
  160040. * use a multiplication rather than a division.
  160041. */
  160042. FAST_FLOAT * fdtbl;
  160043. int row, col;
  160044. static const double aanscalefactor[DCTSIZE] = {
  160045. 1.0, 1.387039845, 1.306562965, 1.175875602,
  160046. 1.0, 0.785694958, 0.541196100, 0.275899379
  160047. };
  160048. if (fdct->float_divisors[qtblno] == NULL) {
  160049. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  160050. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160051. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  160052. }
  160053. fdtbl = fdct->float_divisors[qtblno];
  160054. i = 0;
  160055. for (row = 0; row < DCTSIZE; row++) {
  160056. for (col = 0; col < DCTSIZE; col++) {
  160057. fdtbl[i] = (FAST_FLOAT)
  160058. (1.0 / (((double) qtbl->quantval[i] *
  160059. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  160060. i++;
  160061. }
  160062. }
  160063. }
  160064. break;
  160065. #endif
  160066. default:
  160067. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160068. break;
  160069. }
  160070. }
  160071. }
  160072. /*
  160073. * Perform forward DCT on one or more blocks of a component.
  160074. *
  160075. * The input samples are taken from the sample_data[] array starting at
  160076. * position start_row/start_col, and moving to the right for any additional
  160077. * blocks. The quantized coefficients are returned in coef_blocks[].
  160078. */
  160079. METHODDEF(void)
  160080. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  160081. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  160082. JDIMENSION start_row, JDIMENSION start_col,
  160083. JDIMENSION num_blocks)
  160084. /* This version is used for integer DCT implementations. */
  160085. {
  160086. /* This routine is heavily used, so it's worth coding it tightly. */
  160087. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  160088. forward_DCT_method_ptr do_dct = fdct->do_dct;
  160089. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  160090. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  160091. JDIMENSION bi;
  160092. sample_data += start_row; /* fold in the vertical offset once */
  160093. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  160094. /* Load data into workspace, applying unsigned->signed conversion */
  160095. { register DCTELEM *workspaceptr;
  160096. register JSAMPROW elemptr;
  160097. register int elemr;
  160098. workspaceptr = workspace;
  160099. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  160100. elemptr = sample_data[elemr] + start_col;
  160101. #if DCTSIZE == 8 /* unroll the inner loop */
  160102. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  160103. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  160104. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  160105. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  160106. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  160107. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  160108. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  160109. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  160110. #else
  160111. { register int elemc;
  160112. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  160113. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  160114. }
  160115. }
  160116. #endif
  160117. }
  160118. }
  160119. /* Perform the DCT */
  160120. (*do_dct) (workspace);
  160121. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  160122. { register DCTELEM temp, qval;
  160123. register int i;
  160124. register JCOEFPTR output_ptr = coef_blocks[bi];
  160125. for (i = 0; i < DCTSIZE2; i++) {
  160126. qval = divisors[i];
  160127. temp = workspace[i];
  160128. /* Divide the coefficient value by qval, ensuring proper rounding.
  160129. * Since C does not specify the direction of rounding for negative
  160130. * quotients, we have to force the dividend positive for portability.
  160131. *
  160132. * In most files, at least half of the output values will be zero
  160133. * (at default quantization settings, more like three-quarters...)
  160134. * so we should ensure that this case is fast. On many machines,
  160135. * a comparison is enough cheaper than a divide to make a special test
  160136. * a win. Since both inputs will be nonnegative, we need only test
  160137. * for a < b to discover whether a/b is 0.
  160138. * If your machine's division is fast enough, define FAST_DIVIDE.
  160139. */
  160140. #ifdef FAST_DIVIDE
  160141. #define DIVIDE_BY(a,b) a /= b
  160142. #else
  160143. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  160144. #endif
  160145. if (temp < 0) {
  160146. temp = -temp;
  160147. temp += qval>>1; /* for rounding */
  160148. DIVIDE_BY(temp, qval);
  160149. temp = -temp;
  160150. } else {
  160151. temp += qval>>1; /* for rounding */
  160152. DIVIDE_BY(temp, qval);
  160153. }
  160154. output_ptr[i] = (JCOEF) temp;
  160155. }
  160156. }
  160157. }
  160158. }
  160159. #ifdef DCT_FLOAT_SUPPORTED
  160160. METHODDEF(void)
  160161. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  160162. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  160163. JDIMENSION start_row, JDIMENSION start_col,
  160164. JDIMENSION num_blocks)
  160165. /* This version is used for floating-point DCT implementations. */
  160166. {
  160167. /* This routine is heavily used, so it's worth coding it tightly. */
  160168. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  160169. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  160170. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  160171. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  160172. JDIMENSION bi;
  160173. sample_data += start_row; /* fold in the vertical offset once */
  160174. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  160175. /* Load data into workspace, applying unsigned->signed conversion */
  160176. { register FAST_FLOAT *workspaceptr;
  160177. register JSAMPROW elemptr;
  160178. register int elemr;
  160179. workspaceptr = workspace;
  160180. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  160181. elemptr = sample_data[elemr] + start_col;
  160182. #if DCTSIZE == 8 /* unroll the inner loop */
  160183. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  160184. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  160185. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  160186. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  160187. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  160188. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  160189. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  160190. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  160191. #else
  160192. { register int elemc;
  160193. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  160194. *workspaceptr++ = (FAST_FLOAT)
  160195. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  160196. }
  160197. }
  160198. #endif
  160199. }
  160200. }
  160201. /* Perform the DCT */
  160202. (*do_dct) (workspace);
  160203. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  160204. { register FAST_FLOAT temp;
  160205. register int i;
  160206. register JCOEFPTR output_ptr = coef_blocks[bi];
  160207. for (i = 0; i < DCTSIZE2; i++) {
  160208. /* Apply the quantization and scaling factor */
  160209. temp = workspace[i] * divisors[i];
  160210. /* Round to nearest integer.
  160211. * Since C does not specify the direction of rounding for negative
  160212. * quotients, we have to force the dividend positive for portability.
  160213. * The maximum coefficient size is +-16K (for 12-bit data), so this
  160214. * code should work for either 16-bit or 32-bit ints.
  160215. */
  160216. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  160217. }
  160218. }
  160219. }
  160220. }
  160221. #endif /* DCT_FLOAT_SUPPORTED */
  160222. /*
  160223. * Initialize FDCT manager.
  160224. */
  160225. GLOBAL(void)
  160226. jinit_forward_dct (j_compress_ptr cinfo)
  160227. {
  160228. my_fdct_ptr fdct;
  160229. int i;
  160230. fdct = (my_fdct_ptr)
  160231. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160232. SIZEOF(my_fdct_controller));
  160233. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  160234. fdct->pub.start_pass = start_pass_fdctmgr;
  160235. switch (cinfo->dct_method) {
  160236. #ifdef DCT_ISLOW_SUPPORTED
  160237. case JDCT_ISLOW:
  160238. fdct->pub.forward_DCT = forward_DCT;
  160239. fdct->do_dct = jpeg_fdct_islow;
  160240. break;
  160241. #endif
  160242. #ifdef DCT_IFAST_SUPPORTED
  160243. case JDCT_IFAST:
  160244. fdct->pub.forward_DCT = forward_DCT;
  160245. fdct->do_dct = jpeg_fdct_ifast;
  160246. break;
  160247. #endif
  160248. #ifdef DCT_FLOAT_SUPPORTED
  160249. case JDCT_FLOAT:
  160250. fdct->pub.forward_DCT = forward_DCT_float;
  160251. fdct->do_float_dct = jpeg_fdct_float;
  160252. break;
  160253. #endif
  160254. default:
  160255. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160256. break;
  160257. }
  160258. /* Mark divisor tables unallocated */
  160259. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  160260. fdct->divisors[i] = NULL;
  160261. #ifdef DCT_FLOAT_SUPPORTED
  160262. fdct->float_divisors[i] = NULL;
  160263. #endif
  160264. }
  160265. }
  160266. /*** End of inlined file: jcdctmgr.c ***/
  160267. #undef CONST_BITS
  160268. /*** Start of inlined file: jchuff.c ***/
  160269. #define JPEG_INTERNALS
  160270. /*** Start of inlined file: jchuff.h ***/
  160271. /* The legal range of a DCT coefficient is
  160272. * -1024 .. +1023 for 8-bit data;
  160273. * -16384 .. +16383 for 12-bit data.
  160274. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  160275. */
  160276. #ifndef _jchuff_h_
  160277. #define _jchuff_h_
  160278. #if BITS_IN_JSAMPLE == 8
  160279. #define MAX_COEF_BITS 10
  160280. #else
  160281. #define MAX_COEF_BITS 14
  160282. #endif
  160283. /* Derived data constructed for each Huffman table */
  160284. typedef struct {
  160285. unsigned int ehufco[256]; /* code for each symbol */
  160286. char ehufsi[256]; /* length of code for each symbol */
  160287. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  160288. } c_derived_tbl;
  160289. /* Short forms of external names for systems with brain-damaged linkers. */
  160290. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160291. #define jpeg_make_c_derived_tbl jMkCDerived
  160292. #define jpeg_gen_optimal_table jGenOptTbl
  160293. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160294. /* Expand a Huffman table definition into the derived format */
  160295. EXTERN(void) jpeg_make_c_derived_tbl
  160296. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  160297. c_derived_tbl ** pdtbl));
  160298. /* Generate an optimal table definition given the specified counts */
  160299. EXTERN(void) jpeg_gen_optimal_table
  160300. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  160301. #endif
  160302. /*** End of inlined file: jchuff.h ***/
  160303. /* Declarations shared with jcphuff.c */
  160304. /* Expanded entropy encoder object for Huffman encoding.
  160305. *
  160306. * The savable_state subrecord contains fields that change within an MCU,
  160307. * but must not be updated permanently until we complete the MCU.
  160308. */
  160309. typedef struct {
  160310. INT32 put_buffer; /* current bit-accumulation buffer */
  160311. int put_bits; /* # of bits now in it */
  160312. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  160313. } savable_state;
  160314. /* This macro is to work around compilers with missing or broken
  160315. * structure assignment. You'll need to fix this code if you have
  160316. * such a compiler and you change MAX_COMPS_IN_SCAN.
  160317. */
  160318. #ifndef NO_STRUCT_ASSIGN
  160319. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  160320. #else
  160321. #if MAX_COMPS_IN_SCAN == 4
  160322. #define ASSIGN_STATE(dest,src) \
  160323. ((dest).put_buffer = (src).put_buffer, \
  160324. (dest).put_bits = (src).put_bits, \
  160325. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  160326. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  160327. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  160328. (dest).last_dc_val[3] = (src).last_dc_val[3])
  160329. #endif
  160330. #endif
  160331. typedef struct {
  160332. struct jpeg_entropy_encoder pub; /* public fields */
  160333. savable_state saved; /* Bit buffer & DC state at start of MCU */
  160334. /* These fields are NOT loaded into local working state. */
  160335. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  160336. int next_restart_num; /* next restart number to write (0-7) */
  160337. /* Pointers to derived tables (these workspaces have image lifespan) */
  160338. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  160339. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  160340. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  160341. long * dc_count_ptrs[NUM_HUFF_TBLS];
  160342. long * ac_count_ptrs[NUM_HUFF_TBLS];
  160343. #endif
  160344. } huff_entropy_encoder;
  160345. typedef huff_entropy_encoder * huff_entropy_ptr;
  160346. /* Working state while writing an MCU.
  160347. * This struct contains all the fields that are needed by subroutines.
  160348. */
  160349. typedef struct {
  160350. JOCTET * next_output_byte; /* => next byte to write in buffer */
  160351. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  160352. savable_state cur; /* Current bit buffer & DC state */
  160353. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  160354. } working_state;
  160355. /* Forward declarations */
  160356. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  160357. JBLOCKROW *MCU_data));
  160358. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  160359. #ifdef ENTROPY_OPT_SUPPORTED
  160360. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  160361. JBLOCKROW *MCU_data));
  160362. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  160363. #endif
  160364. /*
  160365. * Initialize for a Huffman-compressed scan.
  160366. * If gather_statistics is TRUE, we do not output anything during the scan,
  160367. * just count the Huffman symbols used and generate Huffman code tables.
  160368. */
  160369. METHODDEF(void)
  160370. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  160371. {
  160372. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  160373. int ci, dctbl, actbl;
  160374. jpeg_component_info * compptr;
  160375. if (gather_statistics) {
  160376. #ifdef ENTROPY_OPT_SUPPORTED
  160377. entropy->pub.encode_mcu = encode_mcu_gather;
  160378. entropy->pub.finish_pass = finish_pass_gather;
  160379. #else
  160380. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160381. #endif
  160382. } else {
  160383. entropy->pub.encode_mcu = encode_mcu_huff;
  160384. entropy->pub.finish_pass = finish_pass_huff;
  160385. }
  160386. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  160387. compptr = cinfo->cur_comp_info[ci];
  160388. dctbl = compptr->dc_tbl_no;
  160389. actbl = compptr->ac_tbl_no;
  160390. if (gather_statistics) {
  160391. #ifdef ENTROPY_OPT_SUPPORTED
  160392. /* Check for invalid table indexes */
  160393. /* (make_c_derived_tbl does this in the other path) */
  160394. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  160395. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  160396. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  160397. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  160398. /* Allocate and zero the statistics tables */
  160399. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  160400. if (entropy->dc_count_ptrs[dctbl] == NULL)
  160401. entropy->dc_count_ptrs[dctbl] = (long *)
  160402. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160403. 257 * SIZEOF(long));
  160404. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  160405. if (entropy->ac_count_ptrs[actbl] == NULL)
  160406. entropy->ac_count_ptrs[actbl] = (long *)
  160407. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160408. 257 * SIZEOF(long));
  160409. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  160410. #endif
  160411. } else {
  160412. /* Compute derived values for Huffman tables */
  160413. /* We may do this more than once for a table, but it's not expensive */
  160414. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  160415. & entropy->dc_derived_tbls[dctbl]);
  160416. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  160417. & entropy->ac_derived_tbls[actbl]);
  160418. }
  160419. /* Initialize DC predictions to 0 */
  160420. entropy->saved.last_dc_val[ci] = 0;
  160421. }
  160422. /* Initialize bit buffer to empty */
  160423. entropy->saved.put_buffer = 0;
  160424. entropy->saved.put_bits = 0;
  160425. /* Initialize restart stuff */
  160426. entropy->restarts_to_go = cinfo->restart_interval;
  160427. entropy->next_restart_num = 0;
  160428. }
  160429. /*
  160430. * Compute the derived values for a Huffman table.
  160431. * This routine also performs some validation checks on the table.
  160432. *
  160433. * Note this is also used by jcphuff.c.
  160434. */
  160435. GLOBAL(void)
  160436. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  160437. c_derived_tbl ** pdtbl)
  160438. {
  160439. JHUFF_TBL *htbl;
  160440. c_derived_tbl *dtbl;
  160441. int p, i, l, lastp, si, maxsymbol;
  160442. char huffsize[257];
  160443. unsigned int huffcode[257];
  160444. unsigned int code;
  160445. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  160446. * paralleling the order of the symbols themselves in htbl->huffval[].
  160447. */
  160448. /* Find the input Huffman table */
  160449. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  160450. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  160451. htbl =
  160452. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  160453. if (htbl == NULL)
  160454. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  160455. /* Allocate a workspace if we haven't already done so. */
  160456. if (*pdtbl == NULL)
  160457. *pdtbl = (c_derived_tbl *)
  160458. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160459. SIZEOF(c_derived_tbl));
  160460. dtbl = *pdtbl;
  160461. /* Figure C.1: make table of Huffman code length for each symbol */
  160462. p = 0;
  160463. for (l = 1; l <= 16; l++) {
  160464. i = (int) htbl->bits[l];
  160465. if (i < 0 || p + i > 256) /* protect against table overrun */
  160466. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  160467. while (i--)
  160468. huffsize[p++] = (char) l;
  160469. }
  160470. huffsize[p] = 0;
  160471. lastp = p;
  160472. /* Figure C.2: generate the codes themselves */
  160473. /* We also validate that the counts represent a legal Huffman code tree. */
  160474. code = 0;
  160475. si = huffsize[0];
  160476. p = 0;
  160477. while (huffsize[p]) {
  160478. while (((int) huffsize[p]) == si) {
  160479. huffcode[p++] = code;
  160480. code++;
  160481. }
  160482. /* code is now 1 more than the last code used for codelength si; but
  160483. * it must still fit in si bits, since no code is allowed to be all ones.
  160484. */
  160485. if (((INT32) code) >= (((INT32) 1) << si))
  160486. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  160487. code <<= 1;
  160488. si++;
  160489. }
  160490. /* Figure C.3: generate encoding tables */
  160491. /* These are code and size indexed by symbol value */
  160492. /* Set all codeless symbols to have code length 0;
  160493. * this lets us detect duplicate VAL entries here, and later
  160494. * allows emit_bits to detect any attempt to emit such symbols.
  160495. */
  160496. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  160497. /* This is also a convenient place to check for out-of-range
  160498. * and duplicated VAL entries. We allow 0..255 for AC symbols
  160499. * but only 0..15 for DC. (We could constrain them further
  160500. * based on data depth and mode, but this seems enough.)
  160501. */
  160502. maxsymbol = isDC ? 15 : 255;
  160503. for (p = 0; p < lastp; p++) {
  160504. i = htbl->huffval[p];
  160505. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  160506. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  160507. dtbl->ehufco[i] = huffcode[p];
  160508. dtbl->ehufsi[i] = huffsize[p];
  160509. }
  160510. }
  160511. /* Outputting bytes to the file */
  160512. /* Emit a byte, taking 'action' if must suspend. */
  160513. #define emit_byte(state,val,action) \
  160514. { *(state)->next_output_byte++ = (JOCTET) (val); \
  160515. if (--(state)->free_in_buffer == 0) \
  160516. if (! dump_buffer(state)) \
  160517. { action; } }
  160518. LOCAL(boolean)
  160519. dump_buffer (working_state * state)
  160520. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  160521. {
  160522. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  160523. if (! (*dest->empty_output_buffer) (state->cinfo))
  160524. return FALSE;
  160525. /* After a successful buffer dump, must reset buffer pointers */
  160526. state->next_output_byte = dest->next_output_byte;
  160527. state->free_in_buffer = dest->free_in_buffer;
  160528. return TRUE;
  160529. }
  160530. /* Outputting bits to the file */
  160531. /* Only the right 24 bits of put_buffer are used; the valid bits are
  160532. * left-justified in this part. At most 16 bits can be passed to emit_bits
  160533. * in one call, and we never retain more than 7 bits in put_buffer
  160534. * between calls, so 24 bits are sufficient.
  160535. */
  160536. INLINE
  160537. LOCAL(boolean)
  160538. emit_bits (working_state * state, unsigned int code, int size)
  160539. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  160540. {
  160541. /* This routine is heavily used, so it's worth coding tightly. */
  160542. register INT32 put_buffer = (INT32) code;
  160543. register int put_bits = state->cur.put_bits;
  160544. /* if size is 0, caller used an invalid Huffman table entry */
  160545. if (size == 0)
  160546. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  160547. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  160548. put_bits += size; /* new number of bits in buffer */
  160549. put_buffer <<= 24 - put_bits; /* align incoming bits */
  160550. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  160551. while (put_bits >= 8) {
  160552. int c = (int) ((put_buffer >> 16) & 0xFF);
  160553. emit_byte(state, c, return FALSE);
  160554. if (c == 0xFF) { /* need to stuff a zero byte? */
  160555. emit_byte(state, 0, return FALSE);
  160556. }
  160557. put_buffer <<= 8;
  160558. put_bits -= 8;
  160559. }
  160560. state->cur.put_buffer = put_buffer; /* update state variables */
  160561. state->cur.put_bits = put_bits;
  160562. return TRUE;
  160563. }
  160564. LOCAL(boolean)
  160565. flush_bits (working_state * state)
  160566. {
  160567. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  160568. return FALSE;
  160569. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  160570. state->cur.put_bits = 0;
  160571. return TRUE;
  160572. }
  160573. /* Encode a single block's worth of coefficients */
  160574. LOCAL(boolean)
  160575. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  160576. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  160577. {
  160578. register int temp, temp2;
  160579. register int nbits;
  160580. register int k, r, i;
  160581. /* Encode the DC coefficient difference per section F.1.2.1 */
  160582. temp = temp2 = block[0] - last_dc_val;
  160583. if (temp < 0) {
  160584. temp = -temp; /* temp is abs value of input */
  160585. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  160586. /* This code assumes we are on a two's complement machine */
  160587. temp2--;
  160588. }
  160589. /* Find the number of bits needed for the magnitude of the coefficient */
  160590. nbits = 0;
  160591. while (temp) {
  160592. nbits++;
  160593. temp >>= 1;
  160594. }
  160595. /* Check for out-of-range coefficient values.
  160596. * Since we're encoding a difference, the range limit is twice as much.
  160597. */
  160598. if (nbits > MAX_COEF_BITS+1)
  160599. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  160600. /* Emit the Huffman-coded symbol for the number of bits */
  160601. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  160602. return FALSE;
  160603. /* Emit that number of bits of the value, if positive, */
  160604. /* or the complement of its magnitude, if negative. */
  160605. if (nbits) /* emit_bits rejects calls with size 0 */
  160606. if (! emit_bits(state, (unsigned int) temp2, nbits))
  160607. return FALSE;
  160608. /* Encode the AC coefficients per section F.1.2.2 */
  160609. r = 0; /* r = run length of zeros */
  160610. for (k = 1; k < DCTSIZE2; k++) {
  160611. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  160612. r++;
  160613. } else {
  160614. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  160615. while (r > 15) {
  160616. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  160617. return FALSE;
  160618. r -= 16;
  160619. }
  160620. temp2 = temp;
  160621. if (temp < 0) {
  160622. temp = -temp; /* temp is abs value of input */
  160623. /* This code assumes we are on a two's complement machine */
  160624. temp2--;
  160625. }
  160626. /* Find the number of bits needed for the magnitude of the coefficient */
  160627. nbits = 1; /* there must be at least one 1 bit */
  160628. while ((temp >>= 1))
  160629. nbits++;
  160630. /* Check for out-of-range coefficient values */
  160631. if (nbits > MAX_COEF_BITS)
  160632. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  160633. /* Emit Huffman symbol for run length / number of bits */
  160634. i = (r << 4) + nbits;
  160635. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  160636. return FALSE;
  160637. /* Emit that number of bits of the value, if positive, */
  160638. /* or the complement of its magnitude, if negative. */
  160639. if (! emit_bits(state, (unsigned int) temp2, nbits))
  160640. return FALSE;
  160641. r = 0;
  160642. }
  160643. }
  160644. /* If the last coef(s) were zero, emit an end-of-block code */
  160645. if (r > 0)
  160646. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  160647. return FALSE;
  160648. return TRUE;
  160649. }
  160650. /*
  160651. * Emit a restart marker & resynchronize predictions.
  160652. */
  160653. LOCAL(boolean)
  160654. emit_restart (working_state * state, int restart_num)
  160655. {
  160656. int ci;
  160657. if (! flush_bits(state))
  160658. return FALSE;
  160659. emit_byte(state, 0xFF, return FALSE);
  160660. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  160661. /* Re-initialize DC predictions to 0 */
  160662. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  160663. state->cur.last_dc_val[ci] = 0;
  160664. /* The restart counter is not updated until we successfully write the MCU. */
  160665. return TRUE;
  160666. }
  160667. /*
  160668. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  160669. */
  160670. METHODDEF(boolean)
  160671. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  160672. {
  160673. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  160674. working_state state;
  160675. int blkn, ci;
  160676. jpeg_component_info * compptr;
  160677. /* Load up working state */
  160678. state.next_output_byte = cinfo->dest->next_output_byte;
  160679. state.free_in_buffer = cinfo->dest->free_in_buffer;
  160680. ASSIGN_STATE(state.cur, entropy->saved);
  160681. state.cinfo = cinfo;
  160682. /* Emit restart marker if needed */
  160683. if (cinfo->restart_interval) {
  160684. if (entropy->restarts_to_go == 0)
  160685. if (! emit_restart(&state, entropy->next_restart_num))
  160686. return FALSE;
  160687. }
  160688. /* Encode the MCU data blocks */
  160689. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  160690. ci = cinfo->MCU_membership[blkn];
  160691. compptr = cinfo->cur_comp_info[ci];
  160692. if (! encode_one_block(&state,
  160693. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  160694. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  160695. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  160696. return FALSE;
  160697. /* Update last_dc_val */
  160698. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  160699. }
  160700. /* Completed MCU, so update state */
  160701. cinfo->dest->next_output_byte = state.next_output_byte;
  160702. cinfo->dest->free_in_buffer = state.free_in_buffer;
  160703. ASSIGN_STATE(entropy->saved, state.cur);
  160704. /* Update restart-interval state too */
  160705. if (cinfo->restart_interval) {
  160706. if (entropy->restarts_to_go == 0) {
  160707. entropy->restarts_to_go = cinfo->restart_interval;
  160708. entropy->next_restart_num++;
  160709. entropy->next_restart_num &= 7;
  160710. }
  160711. entropy->restarts_to_go--;
  160712. }
  160713. return TRUE;
  160714. }
  160715. /*
  160716. * Finish up at the end of a Huffman-compressed scan.
  160717. */
  160718. METHODDEF(void)
  160719. finish_pass_huff (j_compress_ptr cinfo)
  160720. {
  160721. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  160722. working_state state;
  160723. /* Load up working state ... flush_bits needs it */
  160724. state.next_output_byte = cinfo->dest->next_output_byte;
  160725. state.free_in_buffer = cinfo->dest->free_in_buffer;
  160726. ASSIGN_STATE(state.cur, entropy->saved);
  160727. state.cinfo = cinfo;
  160728. /* Flush out the last data */
  160729. if (! flush_bits(&state))
  160730. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  160731. /* Update state */
  160732. cinfo->dest->next_output_byte = state.next_output_byte;
  160733. cinfo->dest->free_in_buffer = state.free_in_buffer;
  160734. ASSIGN_STATE(entropy->saved, state.cur);
  160735. }
  160736. /*
  160737. * Huffman coding optimization.
  160738. *
  160739. * We first scan the supplied data and count the number of uses of each symbol
  160740. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  160741. * Then we build a Huffman coding tree for the observed counts.
  160742. * Symbols which are not needed at all for the particular image are not
  160743. * assigned any code, which saves space in the DHT marker as well as in
  160744. * the compressed data.
  160745. */
  160746. #ifdef ENTROPY_OPT_SUPPORTED
  160747. /* Process a single block's worth of coefficients */
  160748. LOCAL(void)
  160749. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  160750. long dc_counts[], long ac_counts[])
  160751. {
  160752. register int temp;
  160753. register int nbits;
  160754. register int k, r;
  160755. /* Encode the DC coefficient difference per section F.1.2.1 */
  160756. temp = block[0] - last_dc_val;
  160757. if (temp < 0)
  160758. temp = -temp;
  160759. /* Find the number of bits needed for the magnitude of the coefficient */
  160760. nbits = 0;
  160761. while (temp) {
  160762. nbits++;
  160763. temp >>= 1;
  160764. }
  160765. /* Check for out-of-range coefficient values.
  160766. * Since we're encoding a difference, the range limit is twice as much.
  160767. */
  160768. if (nbits > MAX_COEF_BITS+1)
  160769. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  160770. /* Count the Huffman symbol for the number of bits */
  160771. dc_counts[nbits]++;
  160772. /* Encode the AC coefficients per section F.1.2.2 */
  160773. r = 0; /* r = run length of zeros */
  160774. for (k = 1; k < DCTSIZE2; k++) {
  160775. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  160776. r++;
  160777. } else {
  160778. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  160779. while (r > 15) {
  160780. ac_counts[0xF0]++;
  160781. r -= 16;
  160782. }
  160783. /* Find the number of bits needed for the magnitude of the coefficient */
  160784. if (temp < 0)
  160785. temp = -temp;
  160786. /* Find the number of bits needed for the magnitude of the coefficient */
  160787. nbits = 1; /* there must be at least one 1 bit */
  160788. while ((temp >>= 1))
  160789. nbits++;
  160790. /* Check for out-of-range coefficient values */
  160791. if (nbits > MAX_COEF_BITS)
  160792. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  160793. /* Count Huffman symbol for run length / number of bits */
  160794. ac_counts[(r << 4) + nbits]++;
  160795. r = 0;
  160796. }
  160797. }
  160798. /* If the last coef(s) were zero, emit an end-of-block code */
  160799. if (r > 0)
  160800. ac_counts[0]++;
  160801. }
  160802. /*
  160803. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  160804. * No data is actually output, so no suspension return is possible.
  160805. */
  160806. METHODDEF(boolean)
  160807. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  160808. {
  160809. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  160810. int blkn, ci;
  160811. jpeg_component_info * compptr;
  160812. /* Take care of restart intervals if needed */
  160813. if (cinfo->restart_interval) {
  160814. if (entropy->restarts_to_go == 0) {
  160815. /* Re-initialize DC predictions to 0 */
  160816. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  160817. entropy->saved.last_dc_val[ci] = 0;
  160818. /* Update restart state */
  160819. entropy->restarts_to_go = cinfo->restart_interval;
  160820. }
  160821. entropy->restarts_to_go--;
  160822. }
  160823. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  160824. ci = cinfo->MCU_membership[blkn];
  160825. compptr = cinfo->cur_comp_info[ci];
  160826. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  160827. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  160828. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  160829. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  160830. }
  160831. return TRUE;
  160832. }
  160833. /*
  160834. * Generate the best Huffman code table for the given counts, fill htbl.
  160835. * Note this is also used by jcphuff.c.
  160836. *
  160837. * The JPEG standard requires that no symbol be assigned a codeword of all
  160838. * one bits (so that padding bits added at the end of a compressed segment
  160839. * can't look like a valid code). Because of the canonical ordering of
  160840. * codewords, this just means that there must be an unused slot in the
  160841. * longest codeword length category. Section K.2 of the JPEG spec suggests
  160842. * reserving such a slot by pretending that symbol 256 is a valid symbol
  160843. * with count 1. In theory that's not optimal; giving it count zero but
  160844. * including it in the symbol set anyway should give a better Huffman code.
  160845. * But the theoretically better code actually seems to come out worse in
  160846. * practice, because it produces more all-ones bytes (which incur stuffed
  160847. * zero bytes in the final file). In any case the difference is tiny.
  160848. *
  160849. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  160850. * If some symbols have a very small but nonzero probability, the Huffman tree
  160851. * must be adjusted to meet the code length restriction. We currently use
  160852. * the adjustment method suggested in JPEG section K.2. This method is *not*
  160853. * optimal; it may not choose the best possible limited-length code. But
  160854. * typically only very-low-frequency symbols will be given less-than-optimal
  160855. * lengths, so the code is almost optimal. Experimental comparisons against
  160856. * an optimal limited-length-code algorithm indicate that the difference is
  160857. * microscopic --- usually less than a hundredth of a percent of total size.
  160858. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  160859. */
  160860. GLOBAL(void)
  160861. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  160862. {
  160863. #define MAX_CLEN 32 /* assumed maximum initial code length */
  160864. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  160865. int codesize[257]; /* codesize[k] = code length of symbol k */
  160866. int others[257]; /* next symbol in current branch of tree */
  160867. int c1, c2;
  160868. int p, i, j;
  160869. long v;
  160870. /* This algorithm is explained in section K.2 of the JPEG standard */
  160871. MEMZERO(bits, SIZEOF(bits));
  160872. MEMZERO(codesize, SIZEOF(codesize));
  160873. for (i = 0; i < 257; i++)
  160874. others[i] = -1; /* init links to empty */
  160875. freq[256] = 1; /* make sure 256 has a nonzero count */
  160876. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  160877. * that no real symbol is given code-value of all ones, because 256
  160878. * will be placed last in the largest codeword category.
  160879. */
  160880. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  160881. for (;;) {
  160882. /* Find the smallest nonzero frequency, set c1 = its symbol */
  160883. /* In case of ties, take the larger symbol number */
  160884. c1 = -1;
  160885. v = 1000000000L;
  160886. for (i = 0; i <= 256; i++) {
  160887. if (freq[i] && freq[i] <= v) {
  160888. v = freq[i];
  160889. c1 = i;
  160890. }
  160891. }
  160892. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  160893. /* In case of ties, take the larger symbol number */
  160894. c2 = -1;
  160895. v = 1000000000L;
  160896. for (i = 0; i <= 256; i++) {
  160897. if (freq[i] && freq[i] <= v && i != c1) {
  160898. v = freq[i];
  160899. c2 = i;
  160900. }
  160901. }
  160902. /* Done if we've merged everything into one frequency */
  160903. if (c2 < 0)
  160904. break;
  160905. /* Else merge the two counts/trees */
  160906. freq[c1] += freq[c2];
  160907. freq[c2] = 0;
  160908. /* Increment the codesize of everything in c1's tree branch */
  160909. codesize[c1]++;
  160910. while (others[c1] >= 0) {
  160911. c1 = others[c1];
  160912. codesize[c1]++;
  160913. }
  160914. others[c1] = c2; /* chain c2 onto c1's tree branch */
  160915. /* Increment the codesize of everything in c2's tree branch */
  160916. codesize[c2]++;
  160917. while (others[c2] >= 0) {
  160918. c2 = others[c2];
  160919. codesize[c2]++;
  160920. }
  160921. }
  160922. /* Now count the number of symbols of each code length */
  160923. for (i = 0; i <= 256; i++) {
  160924. if (codesize[i]) {
  160925. /* The JPEG standard seems to think that this can't happen, */
  160926. /* but I'm paranoid... */
  160927. if (codesize[i] > MAX_CLEN)
  160928. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  160929. bits[codesize[i]]++;
  160930. }
  160931. }
  160932. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  160933. * Huffman procedure assigned any such lengths, we must adjust the coding.
  160934. * Here is what the JPEG spec says about how this next bit works:
  160935. * Since symbols are paired for the longest Huffman code, the symbols are
  160936. * removed from this length category two at a time. The prefix for the pair
  160937. * (which is one bit shorter) is allocated to one of the pair; then,
  160938. * skipping the BITS entry for that prefix length, a code word from the next
  160939. * shortest nonzero BITS entry is converted into a prefix for two code words
  160940. * one bit longer.
  160941. */
  160942. for (i = MAX_CLEN; i > 16; i--) {
  160943. while (bits[i] > 0) {
  160944. j = i - 2; /* find length of new prefix to be used */
  160945. while (bits[j] == 0)
  160946. j--;
  160947. bits[i] -= 2; /* remove two symbols */
  160948. bits[i-1]++; /* one goes in this length */
  160949. bits[j+1] += 2; /* two new symbols in this length */
  160950. bits[j]--; /* symbol of this length is now a prefix */
  160951. }
  160952. }
  160953. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  160954. while (bits[i] == 0) /* find largest codelength still in use */
  160955. i--;
  160956. bits[i]--;
  160957. /* Return final symbol counts (only for lengths 0..16) */
  160958. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  160959. /* Return a list of the symbols sorted by code length */
  160960. /* It's not real clear to me why we don't need to consider the codelength
  160961. * changes made above, but the JPEG spec seems to think this works.
  160962. */
  160963. p = 0;
  160964. for (i = 1; i <= MAX_CLEN; i++) {
  160965. for (j = 0; j <= 255; j++) {
  160966. if (codesize[j] == i) {
  160967. htbl->huffval[p] = (UINT8) j;
  160968. p++;
  160969. }
  160970. }
  160971. }
  160972. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  160973. htbl->sent_table = FALSE;
  160974. }
  160975. /*
  160976. * Finish up a statistics-gathering pass and create the new Huffman tables.
  160977. */
  160978. METHODDEF(void)
  160979. finish_pass_gather (j_compress_ptr cinfo)
  160980. {
  160981. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  160982. int ci, dctbl, actbl;
  160983. jpeg_component_info * compptr;
  160984. JHUFF_TBL **htblptr;
  160985. boolean did_dc[NUM_HUFF_TBLS];
  160986. boolean did_ac[NUM_HUFF_TBLS];
  160987. /* It's important not to apply jpeg_gen_optimal_table more than once
  160988. * per table, because it clobbers the input frequency counts!
  160989. */
  160990. MEMZERO(did_dc, SIZEOF(did_dc));
  160991. MEMZERO(did_ac, SIZEOF(did_ac));
  160992. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  160993. compptr = cinfo->cur_comp_info[ci];
  160994. dctbl = compptr->dc_tbl_no;
  160995. actbl = compptr->ac_tbl_no;
  160996. if (! did_dc[dctbl]) {
  160997. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  160998. if (*htblptr == NULL)
  160999. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  161000. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  161001. did_dc[dctbl] = TRUE;
  161002. }
  161003. if (! did_ac[actbl]) {
  161004. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  161005. if (*htblptr == NULL)
  161006. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  161007. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  161008. did_ac[actbl] = TRUE;
  161009. }
  161010. }
  161011. }
  161012. #endif /* ENTROPY_OPT_SUPPORTED */
  161013. /*
  161014. * Module initialization routine for Huffman entropy encoding.
  161015. */
  161016. GLOBAL(void)
  161017. jinit_huff_encoder (j_compress_ptr cinfo)
  161018. {
  161019. huff_entropy_ptr entropy;
  161020. int i;
  161021. entropy = (huff_entropy_ptr)
  161022. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161023. SIZEOF(huff_entropy_encoder));
  161024. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  161025. entropy->pub.start_pass = start_pass_huff;
  161026. /* Mark tables unallocated */
  161027. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161028. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  161029. #ifdef ENTROPY_OPT_SUPPORTED
  161030. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  161031. #endif
  161032. }
  161033. }
  161034. /*** End of inlined file: jchuff.c ***/
  161035. #undef emit_byte
  161036. /*** Start of inlined file: jcinit.c ***/
  161037. #define JPEG_INTERNALS
  161038. /*
  161039. * Master selection of compression modules.
  161040. * This is done once at the start of processing an image. We determine
  161041. * which modules will be used and give them appropriate initialization calls.
  161042. */
  161043. GLOBAL(void)
  161044. jinit_compress_master (j_compress_ptr cinfo)
  161045. {
  161046. /* Initialize master control (includes parameter checking/processing) */
  161047. jinit_c_master_control(cinfo, FALSE /* full compression */);
  161048. /* Preprocessing */
  161049. if (! cinfo->raw_data_in) {
  161050. jinit_color_converter(cinfo);
  161051. jinit_downsampler(cinfo);
  161052. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  161053. }
  161054. /* Forward DCT */
  161055. jinit_forward_dct(cinfo);
  161056. /* Entropy encoding: either Huffman or arithmetic coding. */
  161057. if (cinfo->arith_code) {
  161058. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  161059. } else {
  161060. if (cinfo->progressive_mode) {
  161061. #ifdef C_PROGRESSIVE_SUPPORTED
  161062. jinit_phuff_encoder(cinfo);
  161063. #else
  161064. ERREXIT(cinfo, JERR_NOT_COMPILED);
  161065. #endif
  161066. } else
  161067. jinit_huff_encoder(cinfo);
  161068. }
  161069. /* Need a full-image coefficient buffer in any multi-pass mode. */
  161070. jinit_c_coef_controller(cinfo,
  161071. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  161072. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  161073. jinit_marker_writer(cinfo);
  161074. /* We can now tell the memory manager to allocate virtual arrays. */
  161075. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  161076. /* Write the datastream header (SOI) immediately.
  161077. * Frame and scan headers are postponed till later.
  161078. * This lets application insert special markers after the SOI.
  161079. */
  161080. (*cinfo->marker->write_file_header) (cinfo);
  161081. }
  161082. /*** End of inlined file: jcinit.c ***/
  161083. /*** Start of inlined file: jcmainct.c ***/
  161084. #define JPEG_INTERNALS
  161085. /* Note: currently, there is no operating mode in which a full-image buffer
  161086. * is needed at this step. If there were, that mode could not be used with
  161087. * "raw data" input, since this module is bypassed in that case. However,
  161088. * we've left the code here for possible use in special applications.
  161089. */
  161090. #undef FULL_MAIN_BUFFER_SUPPORTED
  161091. /* Private buffer controller object */
  161092. typedef struct {
  161093. struct jpeg_c_main_controller pub; /* public fields */
  161094. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  161095. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  161096. boolean suspended; /* remember if we suspended output */
  161097. J_BUF_MODE pass_mode; /* current operating mode */
  161098. /* If using just a strip buffer, this points to the entire set of buffers
  161099. * (we allocate one for each component). In the full-image case, this
  161100. * points to the currently accessible strips of the virtual arrays.
  161101. */
  161102. JSAMPARRAY buffer[MAX_COMPONENTS];
  161103. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  161104. /* If using full-image storage, this array holds pointers to virtual-array
  161105. * control blocks for each component. Unused if not full-image storage.
  161106. */
  161107. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  161108. #endif
  161109. } my_main_controller;
  161110. typedef my_main_controller * my_main_ptr;
  161111. /* Forward declarations */
  161112. METHODDEF(void) process_data_simple_main
  161113. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  161114. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  161115. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  161116. METHODDEF(void) process_data_buffer_main
  161117. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  161118. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  161119. #endif
  161120. /*
  161121. * Initialize for a processing pass.
  161122. */
  161123. METHODDEF(void)
  161124. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  161125. {
  161126. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  161127. /* Do nothing in raw-data mode. */
  161128. if (cinfo->raw_data_in)
  161129. return;
  161130. main_->cur_iMCU_row = 0; /* initialize counters */
  161131. main_->rowgroup_ctr = 0;
  161132. main_->suspended = FALSE;
  161133. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  161134. switch (pass_mode) {
  161135. case JBUF_PASS_THRU:
  161136. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  161137. if (main_->whole_image[0] != NULL)
  161138. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161139. #endif
  161140. main_->pub.process_data = process_data_simple_main;
  161141. break;
  161142. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  161143. case JBUF_SAVE_SOURCE:
  161144. case JBUF_CRANK_DEST:
  161145. case JBUF_SAVE_AND_PASS:
  161146. if (main_->whole_image[0] == NULL)
  161147. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161148. main_->pub.process_data = process_data_buffer_main;
  161149. break;
  161150. #endif
  161151. default:
  161152. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161153. break;
  161154. }
  161155. }
  161156. /*
  161157. * Process some data.
  161158. * This routine handles the simple pass-through mode,
  161159. * where we have only a strip buffer.
  161160. */
  161161. METHODDEF(void)
  161162. process_data_simple_main (j_compress_ptr cinfo,
  161163. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  161164. JDIMENSION in_rows_avail)
  161165. {
  161166. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  161167. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  161168. /* Read input data if we haven't filled the main buffer yet */
  161169. if (main_->rowgroup_ctr < DCTSIZE)
  161170. (*cinfo->prep->pre_process_data) (cinfo,
  161171. input_buf, in_row_ctr, in_rows_avail,
  161172. main_->buffer, &main_->rowgroup_ctr,
  161173. (JDIMENSION) DCTSIZE);
  161174. /* If we don't have a full iMCU row buffered, return to application for
  161175. * more data. Note that preprocessor will always pad to fill the iMCU row
  161176. * at the bottom of the image.
  161177. */
  161178. if (main_->rowgroup_ctr != DCTSIZE)
  161179. return;
  161180. /* Send the completed row to the compressor */
  161181. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  161182. /* If compressor did not consume the whole row, then we must need to
  161183. * suspend processing and return to the application. In this situation
  161184. * we pretend we didn't yet consume the last input row; otherwise, if
  161185. * it happened to be the last row of the image, the application would
  161186. * think we were done.
  161187. */
  161188. if (! main_->suspended) {
  161189. (*in_row_ctr)--;
  161190. main_->suspended = TRUE;
  161191. }
  161192. return;
  161193. }
  161194. /* We did finish the row. Undo our little suspension hack if a previous
  161195. * call suspended; then mark the main buffer empty.
  161196. */
  161197. if (main_->suspended) {
  161198. (*in_row_ctr)++;
  161199. main_->suspended = FALSE;
  161200. }
  161201. main_->rowgroup_ctr = 0;
  161202. main_->cur_iMCU_row++;
  161203. }
  161204. }
  161205. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  161206. /*
  161207. * Process some data.
  161208. * This routine handles all of the modes that use a full-size buffer.
  161209. */
  161210. METHODDEF(void)
  161211. process_data_buffer_main (j_compress_ptr cinfo,
  161212. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  161213. JDIMENSION in_rows_avail)
  161214. {
  161215. my_main_ptr main = (my_main_ptr) cinfo->main;
  161216. int ci;
  161217. jpeg_component_info *compptr;
  161218. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  161219. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  161220. /* Realign the virtual buffers if at the start of an iMCU row. */
  161221. if (main->rowgroup_ctr == 0) {
  161222. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161223. ci++, compptr++) {
  161224. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  161225. ((j_common_ptr) cinfo, main->whole_image[ci],
  161226. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  161227. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  161228. }
  161229. /* In a read pass, pretend we just read some source data. */
  161230. if (! writing) {
  161231. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  161232. main->rowgroup_ctr = DCTSIZE;
  161233. }
  161234. }
  161235. /* If a write pass, read input data until the current iMCU row is full. */
  161236. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  161237. if (writing) {
  161238. (*cinfo->prep->pre_process_data) (cinfo,
  161239. input_buf, in_row_ctr, in_rows_avail,
  161240. main->buffer, &main->rowgroup_ctr,
  161241. (JDIMENSION) DCTSIZE);
  161242. /* Return to application if we need more data to fill the iMCU row. */
  161243. if (main->rowgroup_ctr < DCTSIZE)
  161244. return;
  161245. }
  161246. /* Emit data, unless this is a sink-only pass. */
  161247. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  161248. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  161249. /* If compressor did not consume the whole row, then we must need to
  161250. * suspend processing and return to the application. In this situation
  161251. * we pretend we didn't yet consume the last input row; otherwise, if
  161252. * it happened to be the last row of the image, the application would
  161253. * think we were done.
  161254. */
  161255. if (! main->suspended) {
  161256. (*in_row_ctr)--;
  161257. main->suspended = TRUE;
  161258. }
  161259. return;
  161260. }
  161261. /* We did finish the row. Undo our little suspension hack if a previous
  161262. * call suspended; then mark the main buffer empty.
  161263. */
  161264. if (main->suspended) {
  161265. (*in_row_ctr)++;
  161266. main->suspended = FALSE;
  161267. }
  161268. }
  161269. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  161270. main->rowgroup_ctr = 0;
  161271. main->cur_iMCU_row++;
  161272. }
  161273. }
  161274. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  161275. /*
  161276. * Initialize main buffer controller.
  161277. */
  161278. GLOBAL(void)
  161279. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  161280. {
  161281. my_main_ptr main_;
  161282. int ci;
  161283. jpeg_component_info *compptr;
  161284. main_ = (my_main_ptr)
  161285. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161286. SIZEOF(my_main_controller));
  161287. cinfo->main = (struct jpeg_c_main_controller *) main_;
  161288. main_->pub.start_pass = start_pass_main;
  161289. /* We don't need to create a buffer in raw-data mode. */
  161290. if (cinfo->raw_data_in)
  161291. return;
  161292. /* Create the buffer. It holds downsampled data, so each component
  161293. * may be of a different size.
  161294. */
  161295. if (need_full_buffer) {
  161296. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  161297. /* Allocate a full-image virtual array for each component */
  161298. /* Note we pad the bottom to a multiple of the iMCU height */
  161299. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161300. ci++, compptr++) {
  161301. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  161302. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  161303. compptr->width_in_blocks * DCTSIZE,
  161304. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  161305. (long) compptr->v_samp_factor) * DCTSIZE,
  161306. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  161307. }
  161308. #else
  161309. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161310. #endif
  161311. } else {
  161312. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  161313. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  161314. #endif
  161315. /* Allocate a strip buffer for each component */
  161316. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161317. ci++, compptr++) {
  161318. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  161319. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161320. compptr->width_in_blocks * DCTSIZE,
  161321. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  161322. }
  161323. }
  161324. }
  161325. /*** End of inlined file: jcmainct.c ***/
  161326. /*** Start of inlined file: jcmarker.c ***/
  161327. #define JPEG_INTERNALS
  161328. /* Private state */
  161329. typedef struct {
  161330. struct jpeg_marker_writer pub; /* public fields */
  161331. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  161332. } my_marker_writer;
  161333. typedef my_marker_writer * my_marker_ptr;
  161334. /*
  161335. * Basic output routines.
  161336. *
  161337. * Note that we do not support suspension while writing a marker.
  161338. * Therefore, an application using suspension must ensure that there is
  161339. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  161340. * calling jpeg_start_compress, and enough space to write the trailing EOI
  161341. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  161342. * modes are not supported at all with suspension, so those two are the only
  161343. * points where markers will be written.
  161344. */
  161345. LOCAL(void)
  161346. emit_byte (j_compress_ptr cinfo, int val)
  161347. /* Emit a byte */
  161348. {
  161349. struct jpeg_destination_mgr * dest = cinfo->dest;
  161350. *(dest->next_output_byte)++ = (JOCTET) val;
  161351. if (--dest->free_in_buffer == 0) {
  161352. if (! (*dest->empty_output_buffer) (cinfo))
  161353. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  161354. }
  161355. }
  161356. LOCAL(void)
  161357. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  161358. /* Emit a marker code */
  161359. {
  161360. emit_byte(cinfo, 0xFF);
  161361. emit_byte(cinfo, (int) mark);
  161362. }
  161363. LOCAL(void)
  161364. emit_2bytes (j_compress_ptr cinfo, int value)
  161365. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  161366. {
  161367. emit_byte(cinfo, (value >> 8) & 0xFF);
  161368. emit_byte(cinfo, value & 0xFF);
  161369. }
  161370. /*
  161371. * Routines to write specific marker types.
  161372. */
  161373. LOCAL(int)
  161374. emit_dqt (j_compress_ptr cinfo, int index)
  161375. /* Emit a DQT marker */
  161376. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  161377. {
  161378. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  161379. int prec;
  161380. int i;
  161381. if (qtbl == NULL)
  161382. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  161383. prec = 0;
  161384. for (i = 0; i < DCTSIZE2; i++) {
  161385. if (qtbl->quantval[i] > 255)
  161386. prec = 1;
  161387. }
  161388. if (! qtbl->sent_table) {
  161389. emit_marker(cinfo, M_DQT);
  161390. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  161391. emit_byte(cinfo, index + (prec<<4));
  161392. for (i = 0; i < DCTSIZE2; i++) {
  161393. /* The table entries must be emitted in zigzag order. */
  161394. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  161395. if (prec)
  161396. emit_byte(cinfo, (int) (qval >> 8));
  161397. emit_byte(cinfo, (int) (qval & 0xFF));
  161398. }
  161399. qtbl->sent_table = TRUE;
  161400. }
  161401. return prec;
  161402. }
  161403. LOCAL(void)
  161404. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  161405. /* Emit a DHT marker */
  161406. {
  161407. JHUFF_TBL * htbl;
  161408. int length, i;
  161409. if (is_ac) {
  161410. htbl = cinfo->ac_huff_tbl_ptrs[index];
  161411. index += 0x10; /* output index has AC bit set */
  161412. } else {
  161413. htbl = cinfo->dc_huff_tbl_ptrs[index];
  161414. }
  161415. if (htbl == NULL)
  161416. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  161417. if (! htbl->sent_table) {
  161418. emit_marker(cinfo, M_DHT);
  161419. length = 0;
  161420. for (i = 1; i <= 16; i++)
  161421. length += htbl->bits[i];
  161422. emit_2bytes(cinfo, length + 2 + 1 + 16);
  161423. emit_byte(cinfo, index);
  161424. for (i = 1; i <= 16; i++)
  161425. emit_byte(cinfo, htbl->bits[i]);
  161426. for (i = 0; i < length; i++)
  161427. emit_byte(cinfo, htbl->huffval[i]);
  161428. htbl->sent_table = TRUE;
  161429. }
  161430. }
  161431. LOCAL(void)
  161432. emit_dac (j_compress_ptr)
  161433. /* Emit a DAC marker */
  161434. /* Since the useful info is so small, we want to emit all the tables in */
  161435. /* one DAC marker. Therefore this routine does its own scan of the table. */
  161436. {
  161437. #ifdef C_ARITH_CODING_SUPPORTED
  161438. char dc_in_use[NUM_ARITH_TBLS];
  161439. char ac_in_use[NUM_ARITH_TBLS];
  161440. int length, i;
  161441. jpeg_component_info *compptr;
  161442. for (i = 0; i < NUM_ARITH_TBLS; i++)
  161443. dc_in_use[i] = ac_in_use[i] = 0;
  161444. for (i = 0; i < cinfo->comps_in_scan; i++) {
  161445. compptr = cinfo->cur_comp_info[i];
  161446. dc_in_use[compptr->dc_tbl_no] = 1;
  161447. ac_in_use[compptr->ac_tbl_no] = 1;
  161448. }
  161449. length = 0;
  161450. for (i = 0; i < NUM_ARITH_TBLS; i++)
  161451. length += dc_in_use[i] + ac_in_use[i];
  161452. emit_marker(cinfo, M_DAC);
  161453. emit_2bytes(cinfo, length*2 + 2);
  161454. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  161455. if (dc_in_use[i]) {
  161456. emit_byte(cinfo, i);
  161457. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  161458. }
  161459. if (ac_in_use[i]) {
  161460. emit_byte(cinfo, i + 0x10);
  161461. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  161462. }
  161463. }
  161464. #endif /* C_ARITH_CODING_SUPPORTED */
  161465. }
  161466. LOCAL(void)
  161467. emit_dri (j_compress_ptr cinfo)
  161468. /* Emit a DRI marker */
  161469. {
  161470. emit_marker(cinfo, M_DRI);
  161471. emit_2bytes(cinfo, 4); /* fixed length */
  161472. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  161473. }
  161474. LOCAL(void)
  161475. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  161476. /* Emit a SOF marker */
  161477. {
  161478. int ci;
  161479. jpeg_component_info *compptr;
  161480. emit_marker(cinfo, code);
  161481. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  161482. /* Make sure image isn't bigger than SOF field can handle */
  161483. if ((long) cinfo->image_height > 65535L ||
  161484. (long) cinfo->image_width > 65535L)
  161485. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  161486. emit_byte(cinfo, cinfo->data_precision);
  161487. emit_2bytes(cinfo, (int) cinfo->image_height);
  161488. emit_2bytes(cinfo, (int) cinfo->image_width);
  161489. emit_byte(cinfo, cinfo->num_components);
  161490. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161491. ci++, compptr++) {
  161492. emit_byte(cinfo, compptr->component_id);
  161493. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  161494. emit_byte(cinfo, compptr->quant_tbl_no);
  161495. }
  161496. }
  161497. LOCAL(void)
  161498. emit_sos (j_compress_ptr cinfo)
  161499. /* Emit a SOS marker */
  161500. {
  161501. int i, td, ta;
  161502. jpeg_component_info *compptr;
  161503. emit_marker(cinfo, M_SOS);
  161504. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  161505. emit_byte(cinfo, cinfo->comps_in_scan);
  161506. for (i = 0; i < cinfo->comps_in_scan; i++) {
  161507. compptr = cinfo->cur_comp_info[i];
  161508. emit_byte(cinfo, compptr->component_id);
  161509. td = compptr->dc_tbl_no;
  161510. ta = compptr->ac_tbl_no;
  161511. if (cinfo->progressive_mode) {
  161512. /* Progressive mode: only DC or only AC tables are used in one scan;
  161513. * furthermore, Huffman coding of DC refinement uses no table at all.
  161514. * We emit 0 for unused field(s); this is recommended by the P&M text
  161515. * but does not seem to be specified in the standard.
  161516. */
  161517. if (cinfo->Ss == 0) {
  161518. ta = 0; /* DC scan */
  161519. if (cinfo->Ah != 0 && !cinfo->arith_code)
  161520. td = 0; /* no DC table either */
  161521. } else {
  161522. td = 0; /* AC scan */
  161523. }
  161524. }
  161525. emit_byte(cinfo, (td << 4) + ta);
  161526. }
  161527. emit_byte(cinfo, cinfo->Ss);
  161528. emit_byte(cinfo, cinfo->Se);
  161529. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  161530. }
  161531. LOCAL(void)
  161532. emit_jfif_app0 (j_compress_ptr cinfo)
  161533. /* Emit a JFIF-compliant APP0 marker */
  161534. {
  161535. /*
  161536. * Length of APP0 block (2 bytes)
  161537. * Block ID (4 bytes - ASCII "JFIF")
  161538. * Zero byte (1 byte to terminate the ID string)
  161539. * Version Major, Minor (2 bytes - major first)
  161540. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  161541. * Xdpu (2 bytes - dots per unit horizontal)
  161542. * Ydpu (2 bytes - dots per unit vertical)
  161543. * Thumbnail X size (1 byte)
  161544. * Thumbnail Y size (1 byte)
  161545. */
  161546. emit_marker(cinfo, M_APP0);
  161547. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  161548. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  161549. emit_byte(cinfo, 0x46);
  161550. emit_byte(cinfo, 0x49);
  161551. emit_byte(cinfo, 0x46);
  161552. emit_byte(cinfo, 0);
  161553. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  161554. emit_byte(cinfo, cinfo->JFIF_minor_version);
  161555. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  161556. emit_2bytes(cinfo, (int) cinfo->X_density);
  161557. emit_2bytes(cinfo, (int) cinfo->Y_density);
  161558. emit_byte(cinfo, 0); /* No thumbnail image */
  161559. emit_byte(cinfo, 0);
  161560. }
  161561. LOCAL(void)
  161562. emit_adobe_app14 (j_compress_ptr cinfo)
  161563. /* Emit an Adobe APP14 marker */
  161564. {
  161565. /*
  161566. * Length of APP14 block (2 bytes)
  161567. * Block ID (5 bytes - ASCII "Adobe")
  161568. * Version Number (2 bytes - currently 100)
  161569. * Flags0 (2 bytes - currently 0)
  161570. * Flags1 (2 bytes - currently 0)
  161571. * Color transform (1 byte)
  161572. *
  161573. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  161574. * now in circulation seem to use Version = 100, so that's what we write.
  161575. *
  161576. * We write the color transform byte as 1 if the JPEG color space is
  161577. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  161578. * whether the encoder performed a transformation, which is pretty useless.
  161579. */
  161580. emit_marker(cinfo, M_APP14);
  161581. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  161582. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  161583. emit_byte(cinfo, 0x64);
  161584. emit_byte(cinfo, 0x6F);
  161585. emit_byte(cinfo, 0x62);
  161586. emit_byte(cinfo, 0x65);
  161587. emit_2bytes(cinfo, 100); /* Version */
  161588. emit_2bytes(cinfo, 0); /* Flags0 */
  161589. emit_2bytes(cinfo, 0); /* Flags1 */
  161590. switch (cinfo->jpeg_color_space) {
  161591. case JCS_YCbCr:
  161592. emit_byte(cinfo, 1); /* Color transform = 1 */
  161593. break;
  161594. case JCS_YCCK:
  161595. emit_byte(cinfo, 2); /* Color transform = 2 */
  161596. break;
  161597. default:
  161598. emit_byte(cinfo, 0); /* Color transform = 0 */
  161599. break;
  161600. }
  161601. }
  161602. /*
  161603. * These routines allow writing an arbitrary marker with parameters.
  161604. * The only intended use is to emit COM or APPn markers after calling
  161605. * write_file_header and before calling write_frame_header.
  161606. * Other uses are not guaranteed to produce desirable results.
  161607. * Counting the parameter bytes properly is the caller's responsibility.
  161608. */
  161609. METHODDEF(void)
  161610. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  161611. /* Emit an arbitrary marker header */
  161612. {
  161613. if (datalen > (unsigned int) 65533) /* safety check */
  161614. ERREXIT(cinfo, JERR_BAD_LENGTH);
  161615. emit_marker(cinfo, (JPEG_MARKER) marker);
  161616. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  161617. }
  161618. METHODDEF(void)
  161619. write_marker_byte (j_compress_ptr cinfo, int val)
  161620. /* Emit one byte of marker parameters following write_marker_header */
  161621. {
  161622. emit_byte(cinfo, val);
  161623. }
  161624. /*
  161625. * Write datastream header.
  161626. * This consists of an SOI and optional APPn markers.
  161627. * We recommend use of the JFIF marker, but not the Adobe marker,
  161628. * when using YCbCr or grayscale data. The JFIF marker should NOT
  161629. * be used for any other JPEG colorspace. The Adobe marker is helpful
  161630. * to distinguish RGB, CMYK, and YCCK colorspaces.
  161631. * Note that an application can write additional header markers after
  161632. * jpeg_start_compress returns.
  161633. */
  161634. METHODDEF(void)
  161635. write_file_header (j_compress_ptr cinfo)
  161636. {
  161637. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  161638. emit_marker(cinfo, M_SOI); /* first the SOI */
  161639. /* SOI is defined to reset restart interval to 0 */
  161640. marker->last_restart_interval = 0;
  161641. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  161642. emit_jfif_app0(cinfo);
  161643. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  161644. emit_adobe_app14(cinfo);
  161645. }
  161646. /*
  161647. * Write frame header.
  161648. * This consists of DQT and SOFn markers.
  161649. * Note that we do not emit the SOF until we have emitted the DQT(s).
  161650. * This avoids compatibility problems with incorrect implementations that
  161651. * try to error-check the quant table numbers as soon as they see the SOF.
  161652. */
  161653. METHODDEF(void)
  161654. write_frame_header (j_compress_ptr cinfo)
  161655. {
  161656. int ci, prec;
  161657. boolean is_baseline;
  161658. jpeg_component_info *compptr;
  161659. /* Emit DQT for each quantization table.
  161660. * Note that emit_dqt() suppresses any duplicate tables.
  161661. */
  161662. prec = 0;
  161663. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161664. ci++, compptr++) {
  161665. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  161666. }
  161667. /* now prec is nonzero iff there are any 16-bit quant tables. */
  161668. /* Check for a non-baseline specification.
  161669. * Note we assume that Huffman table numbers won't be changed later.
  161670. */
  161671. if (cinfo->arith_code || cinfo->progressive_mode ||
  161672. cinfo->data_precision != 8) {
  161673. is_baseline = FALSE;
  161674. } else {
  161675. is_baseline = TRUE;
  161676. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161677. ci++, compptr++) {
  161678. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  161679. is_baseline = FALSE;
  161680. }
  161681. if (prec && is_baseline) {
  161682. is_baseline = FALSE;
  161683. /* If it's baseline except for quantizer size, warn the user */
  161684. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  161685. }
  161686. }
  161687. /* Emit the proper SOF marker */
  161688. if (cinfo->arith_code) {
  161689. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  161690. } else {
  161691. if (cinfo->progressive_mode)
  161692. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  161693. else if (is_baseline)
  161694. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  161695. else
  161696. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  161697. }
  161698. }
  161699. /*
  161700. * Write scan header.
  161701. * This consists of DHT or DAC markers, optional DRI, and SOS.
  161702. * Compressed data will be written following the SOS.
  161703. */
  161704. METHODDEF(void)
  161705. write_scan_header (j_compress_ptr cinfo)
  161706. {
  161707. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  161708. int i;
  161709. jpeg_component_info *compptr;
  161710. if (cinfo->arith_code) {
  161711. /* Emit arith conditioning info. We may have some duplication
  161712. * if the file has multiple scans, but it's so small it's hardly
  161713. * worth worrying about.
  161714. */
  161715. emit_dac(cinfo);
  161716. } else {
  161717. /* Emit Huffman tables.
  161718. * Note that emit_dht() suppresses any duplicate tables.
  161719. */
  161720. for (i = 0; i < cinfo->comps_in_scan; i++) {
  161721. compptr = cinfo->cur_comp_info[i];
  161722. if (cinfo->progressive_mode) {
  161723. /* Progressive mode: only DC or only AC tables are used in one scan */
  161724. if (cinfo->Ss == 0) {
  161725. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  161726. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  161727. } else {
  161728. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  161729. }
  161730. } else {
  161731. /* Sequential mode: need both DC and AC tables */
  161732. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  161733. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  161734. }
  161735. }
  161736. }
  161737. /* Emit DRI if required --- note that DRI value could change for each scan.
  161738. * We avoid wasting space with unnecessary DRIs, however.
  161739. */
  161740. if (cinfo->restart_interval != marker->last_restart_interval) {
  161741. emit_dri(cinfo);
  161742. marker->last_restart_interval = cinfo->restart_interval;
  161743. }
  161744. emit_sos(cinfo);
  161745. }
  161746. /*
  161747. * Write datastream trailer.
  161748. */
  161749. METHODDEF(void)
  161750. write_file_trailer (j_compress_ptr cinfo)
  161751. {
  161752. emit_marker(cinfo, M_EOI);
  161753. }
  161754. /*
  161755. * Write an abbreviated table-specification datastream.
  161756. * This consists of SOI, DQT and DHT tables, and EOI.
  161757. * Any table that is defined and not marked sent_table = TRUE will be
  161758. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  161759. */
  161760. METHODDEF(void)
  161761. write_tables_only (j_compress_ptr cinfo)
  161762. {
  161763. int i;
  161764. emit_marker(cinfo, M_SOI);
  161765. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161766. if (cinfo->quant_tbl_ptrs[i] != NULL)
  161767. (void) emit_dqt(cinfo, i);
  161768. }
  161769. if (! cinfo->arith_code) {
  161770. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161771. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  161772. emit_dht(cinfo, i, FALSE);
  161773. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  161774. emit_dht(cinfo, i, TRUE);
  161775. }
  161776. }
  161777. emit_marker(cinfo, M_EOI);
  161778. }
  161779. /*
  161780. * Initialize the marker writer module.
  161781. */
  161782. GLOBAL(void)
  161783. jinit_marker_writer (j_compress_ptr cinfo)
  161784. {
  161785. my_marker_ptr marker;
  161786. /* Create the subobject */
  161787. marker = (my_marker_ptr)
  161788. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161789. SIZEOF(my_marker_writer));
  161790. cinfo->marker = (struct jpeg_marker_writer *) marker;
  161791. /* Initialize method pointers */
  161792. marker->pub.write_file_header = write_file_header;
  161793. marker->pub.write_frame_header = write_frame_header;
  161794. marker->pub.write_scan_header = write_scan_header;
  161795. marker->pub.write_file_trailer = write_file_trailer;
  161796. marker->pub.write_tables_only = write_tables_only;
  161797. marker->pub.write_marker_header = write_marker_header;
  161798. marker->pub.write_marker_byte = write_marker_byte;
  161799. /* Initialize private state */
  161800. marker->last_restart_interval = 0;
  161801. }
  161802. /*** End of inlined file: jcmarker.c ***/
  161803. /*** Start of inlined file: jcmaster.c ***/
  161804. #define JPEG_INTERNALS
  161805. /* Private state */
  161806. typedef enum {
  161807. main_pass, /* input data, also do first output step */
  161808. huff_opt_pass, /* Huffman code optimization pass */
  161809. output_pass /* data output pass */
  161810. } c_pass_type;
  161811. typedef struct {
  161812. struct jpeg_comp_master pub; /* public fields */
  161813. c_pass_type pass_type; /* the type of the current pass */
  161814. int pass_number; /* # of passes completed */
  161815. int total_passes; /* total # of passes needed */
  161816. int scan_number; /* current index in scan_info[] */
  161817. } my_comp_master;
  161818. typedef my_comp_master * my_master_ptr;
  161819. /*
  161820. * Support routines that do various essential calculations.
  161821. */
  161822. LOCAL(void)
  161823. initial_setup (j_compress_ptr cinfo)
  161824. /* Do computations that are needed before master selection phase */
  161825. {
  161826. int ci;
  161827. jpeg_component_info *compptr;
  161828. long samplesperrow;
  161829. JDIMENSION jd_samplesperrow;
  161830. /* Sanity check on image dimensions */
  161831. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  161832. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  161833. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  161834. /* Make sure image isn't bigger than I can handle */
  161835. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  161836. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  161837. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  161838. /* Width of an input scanline must be representable as JDIMENSION. */
  161839. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  161840. jd_samplesperrow = (JDIMENSION) samplesperrow;
  161841. if ((long) jd_samplesperrow != samplesperrow)
  161842. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  161843. /* For now, precision must match compiled-in value... */
  161844. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  161845. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  161846. /* Check that number of components won't exceed internal array sizes */
  161847. if (cinfo->num_components > MAX_COMPONENTS)
  161848. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  161849. MAX_COMPONENTS);
  161850. /* Compute maximum sampling factors; check factor validity */
  161851. cinfo->max_h_samp_factor = 1;
  161852. cinfo->max_v_samp_factor = 1;
  161853. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161854. ci++, compptr++) {
  161855. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  161856. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  161857. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  161858. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  161859. compptr->h_samp_factor);
  161860. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  161861. compptr->v_samp_factor);
  161862. }
  161863. /* Compute dimensions of components */
  161864. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161865. ci++, compptr++) {
  161866. /* Fill in the correct component_index value; don't rely on application */
  161867. compptr->component_index = ci;
  161868. /* For compression, we never do DCT scaling. */
  161869. compptr->DCT_scaled_size = DCTSIZE;
  161870. /* Size in DCT blocks */
  161871. compptr->width_in_blocks = (JDIMENSION)
  161872. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  161873. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  161874. compptr->height_in_blocks = (JDIMENSION)
  161875. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  161876. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  161877. /* Size in samples */
  161878. compptr->downsampled_width = (JDIMENSION)
  161879. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  161880. (long) cinfo->max_h_samp_factor);
  161881. compptr->downsampled_height = (JDIMENSION)
  161882. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  161883. (long) cinfo->max_v_samp_factor);
  161884. /* Mark component needed (this flag isn't actually used for compression) */
  161885. compptr->component_needed = TRUE;
  161886. }
  161887. /* Compute number of fully interleaved MCU rows (number of times that
  161888. * main controller will call coefficient controller).
  161889. */
  161890. cinfo->total_iMCU_rows = (JDIMENSION)
  161891. jdiv_round_up((long) cinfo->image_height,
  161892. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  161893. }
  161894. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161895. LOCAL(void)
  161896. validate_script (j_compress_ptr cinfo)
  161897. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  161898. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  161899. */
  161900. {
  161901. const jpeg_scan_info * scanptr;
  161902. int scanno, ncomps, ci, coefi, thisi;
  161903. int Ss, Se, Ah, Al;
  161904. boolean component_sent[MAX_COMPONENTS];
  161905. #ifdef C_PROGRESSIVE_SUPPORTED
  161906. int * last_bitpos_ptr;
  161907. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  161908. /* -1 until that coefficient has been seen; then last Al for it */
  161909. #endif
  161910. if (cinfo->num_scans <= 0)
  161911. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  161912. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  161913. * for progressive JPEG, no scan can have this.
  161914. */
  161915. scanptr = cinfo->scan_info;
  161916. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  161917. #ifdef C_PROGRESSIVE_SUPPORTED
  161918. cinfo->progressive_mode = TRUE;
  161919. last_bitpos_ptr = & last_bitpos[0][0];
  161920. for (ci = 0; ci < cinfo->num_components; ci++)
  161921. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  161922. *last_bitpos_ptr++ = -1;
  161923. #else
  161924. ERREXIT(cinfo, JERR_NOT_COMPILED);
  161925. #endif
  161926. } else {
  161927. cinfo->progressive_mode = FALSE;
  161928. for (ci = 0; ci < cinfo->num_components; ci++)
  161929. component_sent[ci] = FALSE;
  161930. }
  161931. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  161932. /* Validate component indexes */
  161933. ncomps = scanptr->comps_in_scan;
  161934. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  161935. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  161936. for (ci = 0; ci < ncomps; ci++) {
  161937. thisi = scanptr->component_index[ci];
  161938. if (thisi < 0 || thisi >= cinfo->num_components)
  161939. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  161940. /* Components must appear in SOF order within each scan */
  161941. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  161942. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  161943. }
  161944. /* Validate progression parameters */
  161945. Ss = scanptr->Ss;
  161946. Se = scanptr->Se;
  161947. Ah = scanptr->Ah;
  161948. Al = scanptr->Al;
  161949. if (cinfo->progressive_mode) {
  161950. #ifdef C_PROGRESSIVE_SUPPORTED
  161951. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  161952. * seems wrong: the upper bound ought to depend on data precision.
  161953. * Perhaps they really meant 0..N+1 for N-bit precision.
  161954. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  161955. * out-of-range reconstructed DC values during the first DC scan,
  161956. * which might cause problems for some decoders.
  161957. */
  161958. #if BITS_IN_JSAMPLE == 8
  161959. #define MAX_AH_AL 10
  161960. #else
  161961. #define MAX_AH_AL 13
  161962. #endif
  161963. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  161964. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  161965. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  161966. if (Ss == 0) {
  161967. if (Se != 0) /* DC and AC together not OK */
  161968. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  161969. } else {
  161970. if (ncomps != 1) /* AC scans must be for only one component */
  161971. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  161972. }
  161973. for (ci = 0; ci < ncomps; ci++) {
  161974. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  161975. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  161976. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  161977. for (coefi = Ss; coefi <= Se; coefi++) {
  161978. if (last_bitpos_ptr[coefi] < 0) {
  161979. /* first scan of this coefficient */
  161980. if (Ah != 0)
  161981. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  161982. } else {
  161983. /* not first scan */
  161984. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  161985. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  161986. }
  161987. last_bitpos_ptr[coefi] = Al;
  161988. }
  161989. }
  161990. #endif
  161991. } else {
  161992. /* For sequential JPEG, all progression parameters must be these: */
  161993. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  161994. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  161995. /* Make sure components are not sent twice */
  161996. for (ci = 0; ci < ncomps; ci++) {
  161997. thisi = scanptr->component_index[ci];
  161998. if (component_sent[thisi])
  161999. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  162000. component_sent[thisi] = TRUE;
  162001. }
  162002. }
  162003. }
  162004. /* Now verify that everything got sent. */
  162005. if (cinfo->progressive_mode) {
  162006. #ifdef C_PROGRESSIVE_SUPPORTED
  162007. /* For progressive mode, we only check that at least some DC data
  162008. * got sent for each component; the spec does not require that all bits
  162009. * of all coefficients be transmitted. Would it be wiser to enforce
  162010. * transmission of all coefficient bits??
  162011. */
  162012. for (ci = 0; ci < cinfo->num_components; ci++) {
  162013. if (last_bitpos[ci][0] < 0)
  162014. ERREXIT(cinfo, JERR_MISSING_DATA);
  162015. }
  162016. #endif
  162017. } else {
  162018. for (ci = 0; ci < cinfo->num_components; ci++) {
  162019. if (! component_sent[ci])
  162020. ERREXIT(cinfo, JERR_MISSING_DATA);
  162021. }
  162022. }
  162023. }
  162024. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  162025. LOCAL(void)
  162026. select_scan_parameters (j_compress_ptr cinfo)
  162027. /* Set up the scan parameters for the current scan */
  162028. {
  162029. int ci;
  162030. #ifdef C_MULTISCAN_FILES_SUPPORTED
  162031. if (cinfo->scan_info != NULL) {
  162032. /* Prepare for current scan --- the script is already validated */
  162033. my_master_ptr master = (my_master_ptr) cinfo->master;
  162034. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  162035. cinfo->comps_in_scan = scanptr->comps_in_scan;
  162036. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  162037. cinfo->cur_comp_info[ci] =
  162038. &cinfo->comp_info[scanptr->component_index[ci]];
  162039. }
  162040. cinfo->Ss = scanptr->Ss;
  162041. cinfo->Se = scanptr->Se;
  162042. cinfo->Ah = scanptr->Ah;
  162043. cinfo->Al = scanptr->Al;
  162044. }
  162045. else
  162046. #endif
  162047. {
  162048. /* Prepare for single sequential-JPEG scan containing all components */
  162049. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  162050. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  162051. MAX_COMPS_IN_SCAN);
  162052. cinfo->comps_in_scan = cinfo->num_components;
  162053. for (ci = 0; ci < cinfo->num_components; ci++) {
  162054. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  162055. }
  162056. cinfo->Ss = 0;
  162057. cinfo->Se = DCTSIZE2-1;
  162058. cinfo->Ah = 0;
  162059. cinfo->Al = 0;
  162060. }
  162061. }
  162062. LOCAL(void)
  162063. per_scan_setup (j_compress_ptr cinfo)
  162064. /* Do computations that are needed before processing a JPEG scan */
  162065. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  162066. {
  162067. int ci, mcublks, tmp;
  162068. jpeg_component_info *compptr;
  162069. if (cinfo->comps_in_scan == 1) {
  162070. /* Noninterleaved (single-component) scan */
  162071. compptr = cinfo->cur_comp_info[0];
  162072. /* Overall image size in MCUs */
  162073. cinfo->MCUs_per_row = compptr->width_in_blocks;
  162074. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  162075. /* For noninterleaved scan, always one block per MCU */
  162076. compptr->MCU_width = 1;
  162077. compptr->MCU_height = 1;
  162078. compptr->MCU_blocks = 1;
  162079. compptr->MCU_sample_width = DCTSIZE;
  162080. compptr->last_col_width = 1;
  162081. /* For noninterleaved scans, it is convenient to define last_row_height
  162082. * as the number of block rows present in the last iMCU row.
  162083. */
  162084. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  162085. if (tmp == 0) tmp = compptr->v_samp_factor;
  162086. compptr->last_row_height = tmp;
  162087. /* Prepare array describing MCU composition */
  162088. cinfo->blocks_in_MCU = 1;
  162089. cinfo->MCU_membership[0] = 0;
  162090. } else {
  162091. /* Interleaved (multi-component) scan */
  162092. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  162093. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  162094. MAX_COMPS_IN_SCAN);
  162095. /* Overall image size in MCUs */
  162096. cinfo->MCUs_per_row = (JDIMENSION)
  162097. jdiv_round_up((long) cinfo->image_width,
  162098. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  162099. cinfo->MCU_rows_in_scan = (JDIMENSION)
  162100. jdiv_round_up((long) cinfo->image_height,
  162101. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  162102. cinfo->blocks_in_MCU = 0;
  162103. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162104. compptr = cinfo->cur_comp_info[ci];
  162105. /* Sampling factors give # of blocks of component in each MCU */
  162106. compptr->MCU_width = compptr->h_samp_factor;
  162107. compptr->MCU_height = compptr->v_samp_factor;
  162108. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  162109. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  162110. /* Figure number of non-dummy blocks in last MCU column & row */
  162111. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  162112. if (tmp == 0) tmp = compptr->MCU_width;
  162113. compptr->last_col_width = tmp;
  162114. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  162115. if (tmp == 0) tmp = compptr->MCU_height;
  162116. compptr->last_row_height = tmp;
  162117. /* Prepare array describing MCU composition */
  162118. mcublks = compptr->MCU_blocks;
  162119. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  162120. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  162121. while (mcublks-- > 0) {
  162122. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  162123. }
  162124. }
  162125. }
  162126. /* Convert restart specified in rows to actual MCU count. */
  162127. /* Note that count must fit in 16 bits, so we provide limiting. */
  162128. if (cinfo->restart_in_rows > 0) {
  162129. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  162130. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  162131. }
  162132. }
  162133. /*
  162134. * Per-pass setup.
  162135. * This is called at the beginning of each pass. We determine which modules
  162136. * will be active during this pass and give them appropriate start_pass calls.
  162137. * We also set is_last_pass to indicate whether any more passes will be
  162138. * required.
  162139. */
  162140. METHODDEF(void)
  162141. prepare_for_pass (j_compress_ptr cinfo)
  162142. {
  162143. my_master_ptr master = (my_master_ptr) cinfo->master;
  162144. switch (master->pass_type) {
  162145. case main_pass:
  162146. /* Initial pass: will collect input data, and do either Huffman
  162147. * optimization or data output for the first scan.
  162148. */
  162149. select_scan_parameters(cinfo);
  162150. per_scan_setup(cinfo);
  162151. if (! cinfo->raw_data_in) {
  162152. (*cinfo->cconvert->start_pass) (cinfo);
  162153. (*cinfo->downsample->start_pass) (cinfo);
  162154. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  162155. }
  162156. (*cinfo->fdct->start_pass) (cinfo);
  162157. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  162158. (*cinfo->coef->start_pass) (cinfo,
  162159. (master->total_passes > 1 ?
  162160. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  162161. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  162162. if (cinfo->optimize_coding) {
  162163. /* No immediate data output; postpone writing frame/scan headers */
  162164. master->pub.call_pass_startup = FALSE;
  162165. } else {
  162166. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  162167. master->pub.call_pass_startup = TRUE;
  162168. }
  162169. break;
  162170. #ifdef ENTROPY_OPT_SUPPORTED
  162171. case huff_opt_pass:
  162172. /* Do Huffman optimization for a scan after the first one. */
  162173. select_scan_parameters(cinfo);
  162174. per_scan_setup(cinfo);
  162175. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  162176. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  162177. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  162178. master->pub.call_pass_startup = FALSE;
  162179. break;
  162180. }
  162181. /* Special case: Huffman DC refinement scans need no Huffman table
  162182. * and therefore we can skip the optimization pass for them.
  162183. */
  162184. master->pass_type = output_pass;
  162185. master->pass_number++;
  162186. /*FALLTHROUGH*/
  162187. #endif
  162188. case output_pass:
  162189. /* Do a data-output pass. */
  162190. /* We need not repeat per-scan setup if prior optimization pass did it. */
  162191. if (! cinfo->optimize_coding) {
  162192. select_scan_parameters(cinfo);
  162193. per_scan_setup(cinfo);
  162194. }
  162195. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  162196. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  162197. /* We emit frame/scan headers now */
  162198. if (master->scan_number == 0)
  162199. (*cinfo->marker->write_frame_header) (cinfo);
  162200. (*cinfo->marker->write_scan_header) (cinfo);
  162201. master->pub.call_pass_startup = FALSE;
  162202. break;
  162203. default:
  162204. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162205. }
  162206. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  162207. /* Set up progress monitor's pass info if present */
  162208. if (cinfo->progress != NULL) {
  162209. cinfo->progress->completed_passes = master->pass_number;
  162210. cinfo->progress->total_passes = master->total_passes;
  162211. }
  162212. }
  162213. /*
  162214. * Special start-of-pass hook.
  162215. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  162216. * In single-pass processing, we need this hook because we don't want to
  162217. * write frame/scan headers during jpeg_start_compress; we want to let the
  162218. * application write COM markers etc. between jpeg_start_compress and the
  162219. * jpeg_write_scanlines loop.
  162220. * In multi-pass processing, this routine is not used.
  162221. */
  162222. METHODDEF(void)
  162223. pass_startup (j_compress_ptr cinfo)
  162224. {
  162225. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  162226. (*cinfo->marker->write_frame_header) (cinfo);
  162227. (*cinfo->marker->write_scan_header) (cinfo);
  162228. }
  162229. /*
  162230. * Finish up at end of pass.
  162231. */
  162232. METHODDEF(void)
  162233. finish_pass_master (j_compress_ptr cinfo)
  162234. {
  162235. my_master_ptr master = (my_master_ptr) cinfo->master;
  162236. /* The entropy coder always needs an end-of-pass call,
  162237. * either to analyze statistics or to flush its output buffer.
  162238. */
  162239. (*cinfo->entropy->finish_pass) (cinfo);
  162240. /* Update state for next pass */
  162241. switch (master->pass_type) {
  162242. case main_pass:
  162243. /* next pass is either output of scan 0 (after optimization)
  162244. * or output of scan 1 (if no optimization).
  162245. */
  162246. master->pass_type = output_pass;
  162247. if (! cinfo->optimize_coding)
  162248. master->scan_number++;
  162249. break;
  162250. case huff_opt_pass:
  162251. /* next pass is always output of current scan */
  162252. master->pass_type = output_pass;
  162253. break;
  162254. case output_pass:
  162255. /* next pass is either optimization or output of next scan */
  162256. if (cinfo->optimize_coding)
  162257. master->pass_type = huff_opt_pass;
  162258. master->scan_number++;
  162259. break;
  162260. }
  162261. master->pass_number++;
  162262. }
  162263. /*
  162264. * Initialize master compression control.
  162265. */
  162266. GLOBAL(void)
  162267. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  162268. {
  162269. my_master_ptr master;
  162270. master = (my_master_ptr)
  162271. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162272. SIZEOF(my_comp_master));
  162273. cinfo->master = (struct jpeg_comp_master *) master;
  162274. master->pub.prepare_for_pass = prepare_for_pass;
  162275. master->pub.pass_startup = pass_startup;
  162276. master->pub.finish_pass = finish_pass_master;
  162277. master->pub.is_last_pass = FALSE;
  162278. /* Validate parameters, determine derived values */
  162279. initial_setup(cinfo);
  162280. if (cinfo->scan_info != NULL) {
  162281. #ifdef C_MULTISCAN_FILES_SUPPORTED
  162282. validate_script(cinfo);
  162283. #else
  162284. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162285. #endif
  162286. } else {
  162287. cinfo->progressive_mode = FALSE;
  162288. cinfo->num_scans = 1;
  162289. }
  162290. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  162291. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  162292. /* Initialize my private state */
  162293. if (transcode_only) {
  162294. /* no main pass in transcoding */
  162295. if (cinfo->optimize_coding)
  162296. master->pass_type = huff_opt_pass;
  162297. else
  162298. master->pass_type = output_pass;
  162299. } else {
  162300. /* for normal compression, first pass is always this type: */
  162301. master->pass_type = main_pass;
  162302. }
  162303. master->scan_number = 0;
  162304. master->pass_number = 0;
  162305. if (cinfo->optimize_coding)
  162306. master->total_passes = cinfo->num_scans * 2;
  162307. else
  162308. master->total_passes = cinfo->num_scans;
  162309. }
  162310. /*** End of inlined file: jcmaster.c ***/
  162311. /*** Start of inlined file: jcomapi.c ***/
  162312. #define JPEG_INTERNALS
  162313. /*
  162314. * Abort processing of a JPEG compression or decompression operation,
  162315. * but don't destroy the object itself.
  162316. *
  162317. * For this, we merely clean up all the nonpermanent memory pools.
  162318. * Note that temp files (virtual arrays) are not allowed to belong to
  162319. * the permanent pool, so we will be able to close all temp files here.
  162320. * Closing a data source or destination, if necessary, is the application's
  162321. * responsibility.
  162322. */
  162323. GLOBAL(void)
  162324. jpeg_abort (j_common_ptr cinfo)
  162325. {
  162326. int pool;
  162327. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  162328. if (cinfo->mem == NULL)
  162329. return;
  162330. /* Releasing pools in reverse order might help avoid fragmentation
  162331. * with some (brain-damaged) malloc libraries.
  162332. */
  162333. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  162334. (*cinfo->mem->free_pool) (cinfo, pool);
  162335. }
  162336. /* Reset overall state for possible reuse of object */
  162337. if (cinfo->is_decompressor) {
  162338. cinfo->global_state = DSTATE_START;
  162339. /* Try to keep application from accessing now-deleted marker list.
  162340. * A bit kludgy to do it here, but this is the most central place.
  162341. */
  162342. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  162343. } else {
  162344. cinfo->global_state = CSTATE_START;
  162345. }
  162346. }
  162347. /*
  162348. * Destruction of a JPEG object.
  162349. *
  162350. * Everything gets deallocated except the master jpeg_compress_struct itself
  162351. * and the error manager struct. Both of these are supplied by the application
  162352. * and must be freed, if necessary, by the application. (Often they are on
  162353. * the stack and so don't need to be freed anyway.)
  162354. * Closing a data source or destination, if necessary, is the application's
  162355. * responsibility.
  162356. */
  162357. GLOBAL(void)
  162358. jpeg_destroy (j_common_ptr cinfo)
  162359. {
  162360. /* We need only tell the memory manager to release everything. */
  162361. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  162362. if (cinfo->mem != NULL)
  162363. (*cinfo->mem->self_destruct) (cinfo);
  162364. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  162365. cinfo->global_state = 0; /* mark it destroyed */
  162366. }
  162367. /*
  162368. * Convenience routines for allocating quantization and Huffman tables.
  162369. * (Would jutils.c be a more reasonable place to put these?)
  162370. */
  162371. GLOBAL(JQUANT_TBL *)
  162372. jpeg_alloc_quant_table (j_common_ptr cinfo)
  162373. {
  162374. JQUANT_TBL *tbl;
  162375. tbl = (JQUANT_TBL *)
  162376. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  162377. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  162378. return tbl;
  162379. }
  162380. GLOBAL(JHUFF_TBL *)
  162381. jpeg_alloc_huff_table (j_common_ptr cinfo)
  162382. {
  162383. JHUFF_TBL *tbl;
  162384. tbl = (JHUFF_TBL *)
  162385. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  162386. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  162387. return tbl;
  162388. }
  162389. /*** End of inlined file: jcomapi.c ***/
  162390. /*** Start of inlined file: jcparam.c ***/
  162391. #define JPEG_INTERNALS
  162392. /*
  162393. * Quantization table setup routines
  162394. */
  162395. GLOBAL(void)
  162396. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  162397. const unsigned int *basic_table,
  162398. int scale_factor, boolean force_baseline)
  162399. /* Define a quantization table equal to the basic_table times
  162400. * a scale factor (given as a percentage).
  162401. * If force_baseline is TRUE, the computed quantization table entries
  162402. * are limited to 1..255 for JPEG baseline compatibility.
  162403. */
  162404. {
  162405. JQUANT_TBL ** qtblptr;
  162406. int i;
  162407. long temp;
  162408. /* Safety check to ensure start_compress not called yet. */
  162409. if (cinfo->global_state != CSTATE_START)
  162410. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162411. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  162412. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  162413. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  162414. if (*qtblptr == NULL)
  162415. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  162416. for (i = 0; i < DCTSIZE2; i++) {
  162417. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  162418. /* limit the values to the valid range */
  162419. if (temp <= 0L) temp = 1L;
  162420. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  162421. if (force_baseline && temp > 255L)
  162422. temp = 255L; /* limit to baseline range if requested */
  162423. (*qtblptr)->quantval[i] = (UINT16) temp;
  162424. }
  162425. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  162426. (*qtblptr)->sent_table = FALSE;
  162427. }
  162428. GLOBAL(void)
  162429. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  162430. boolean force_baseline)
  162431. /* Set or change the 'quality' (quantization) setting, using default tables
  162432. * and a straight percentage-scaling quality scale. In most cases it's better
  162433. * to use jpeg_set_quality (below); this entry point is provided for
  162434. * applications that insist on a linear percentage scaling.
  162435. */
  162436. {
  162437. /* These are the sample quantization tables given in JPEG spec section K.1.
  162438. * The spec says that the values given produce "good" quality, and
  162439. * when divided by 2, "very good" quality.
  162440. */
  162441. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  162442. 16, 11, 10, 16, 24, 40, 51, 61,
  162443. 12, 12, 14, 19, 26, 58, 60, 55,
  162444. 14, 13, 16, 24, 40, 57, 69, 56,
  162445. 14, 17, 22, 29, 51, 87, 80, 62,
  162446. 18, 22, 37, 56, 68, 109, 103, 77,
  162447. 24, 35, 55, 64, 81, 104, 113, 92,
  162448. 49, 64, 78, 87, 103, 121, 120, 101,
  162449. 72, 92, 95, 98, 112, 100, 103, 99
  162450. };
  162451. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  162452. 17, 18, 24, 47, 99, 99, 99, 99,
  162453. 18, 21, 26, 66, 99, 99, 99, 99,
  162454. 24, 26, 56, 99, 99, 99, 99, 99,
  162455. 47, 66, 99, 99, 99, 99, 99, 99,
  162456. 99, 99, 99, 99, 99, 99, 99, 99,
  162457. 99, 99, 99, 99, 99, 99, 99, 99,
  162458. 99, 99, 99, 99, 99, 99, 99, 99,
  162459. 99, 99, 99, 99, 99, 99, 99, 99
  162460. };
  162461. /* Set up two quantization tables using the specified scaling */
  162462. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  162463. scale_factor, force_baseline);
  162464. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  162465. scale_factor, force_baseline);
  162466. }
  162467. GLOBAL(int)
  162468. jpeg_quality_scaling (int quality)
  162469. /* Convert a user-specified quality rating to a percentage scaling factor
  162470. * for an underlying quantization table, using our recommended scaling curve.
  162471. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  162472. */
  162473. {
  162474. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  162475. if (quality <= 0) quality = 1;
  162476. if (quality > 100) quality = 100;
  162477. /* The basic table is used as-is (scaling 100) for a quality of 50.
  162478. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  162479. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  162480. * to make all the table entries 1 (hence, minimum quantization loss).
  162481. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  162482. */
  162483. if (quality < 50)
  162484. quality = 5000 / quality;
  162485. else
  162486. quality = 200 - quality*2;
  162487. return quality;
  162488. }
  162489. GLOBAL(void)
  162490. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  162491. /* Set or change the 'quality' (quantization) setting, using default tables.
  162492. * This is the standard quality-adjusting entry point for typical user
  162493. * interfaces; only those who want detailed control over quantization tables
  162494. * would use the preceding three routines directly.
  162495. */
  162496. {
  162497. /* Convert user 0-100 rating to percentage scaling */
  162498. quality = jpeg_quality_scaling(quality);
  162499. /* Set up standard quality tables */
  162500. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  162501. }
  162502. /*
  162503. * Huffman table setup routines
  162504. */
  162505. LOCAL(void)
  162506. add_huff_table (j_compress_ptr cinfo,
  162507. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  162508. /* Define a Huffman table */
  162509. {
  162510. int nsymbols, len;
  162511. if (*htblptr == NULL)
  162512. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  162513. /* Copy the number-of-symbols-of-each-code-length counts */
  162514. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  162515. /* Validate the counts. We do this here mainly so we can copy the right
  162516. * number of symbols from the val[] array, without risking marching off
  162517. * the end of memory. jchuff.c will do a more thorough test later.
  162518. */
  162519. nsymbols = 0;
  162520. for (len = 1; len <= 16; len++)
  162521. nsymbols += bits[len];
  162522. if (nsymbols < 1 || nsymbols > 256)
  162523. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  162524. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  162525. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  162526. (*htblptr)->sent_table = FALSE;
  162527. }
  162528. LOCAL(void)
  162529. std_huff_tables (j_compress_ptr cinfo)
  162530. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  162531. /* IMPORTANT: these are only valid for 8-bit data precision! */
  162532. {
  162533. static const UINT8 bits_dc_luminance[17] =
  162534. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  162535. static const UINT8 val_dc_luminance[] =
  162536. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  162537. static const UINT8 bits_dc_chrominance[17] =
  162538. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  162539. static const UINT8 val_dc_chrominance[] =
  162540. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  162541. static const UINT8 bits_ac_luminance[17] =
  162542. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  162543. static const UINT8 val_ac_luminance[] =
  162544. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  162545. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  162546. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  162547. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  162548. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  162549. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  162550. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  162551. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  162552. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  162553. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  162554. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  162555. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  162556. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  162557. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  162558. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  162559. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  162560. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  162561. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  162562. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  162563. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  162564. 0xf9, 0xfa };
  162565. static const UINT8 bits_ac_chrominance[17] =
  162566. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  162567. static const UINT8 val_ac_chrominance[] =
  162568. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  162569. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  162570. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  162571. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  162572. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  162573. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  162574. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  162575. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  162576. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  162577. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  162578. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  162579. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  162580. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  162581. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  162582. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  162583. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  162584. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  162585. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  162586. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  162587. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  162588. 0xf9, 0xfa };
  162589. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  162590. bits_dc_luminance, val_dc_luminance);
  162591. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  162592. bits_ac_luminance, val_ac_luminance);
  162593. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  162594. bits_dc_chrominance, val_dc_chrominance);
  162595. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  162596. bits_ac_chrominance, val_ac_chrominance);
  162597. }
  162598. /*
  162599. * Default parameter setup for compression.
  162600. *
  162601. * Applications that don't choose to use this routine must do their
  162602. * own setup of all these parameters. Alternately, you can call this
  162603. * to establish defaults and then alter parameters selectively. This
  162604. * is the recommended approach since, if we add any new parameters,
  162605. * your code will still work (they'll be set to reasonable defaults).
  162606. */
  162607. GLOBAL(void)
  162608. jpeg_set_defaults (j_compress_ptr cinfo)
  162609. {
  162610. int i;
  162611. /* Safety check to ensure start_compress not called yet. */
  162612. if (cinfo->global_state != CSTATE_START)
  162613. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162614. /* Allocate comp_info array large enough for maximum component count.
  162615. * Array is made permanent in case application wants to compress
  162616. * multiple images at same param settings.
  162617. */
  162618. if (cinfo->comp_info == NULL)
  162619. cinfo->comp_info = (jpeg_component_info *)
  162620. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  162621. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  162622. /* Initialize everything not dependent on the color space */
  162623. cinfo->data_precision = BITS_IN_JSAMPLE;
  162624. /* Set up two quantization tables using default quality of 75 */
  162625. jpeg_set_quality(cinfo, 75, TRUE);
  162626. /* Set up two Huffman tables */
  162627. std_huff_tables(cinfo);
  162628. /* Initialize default arithmetic coding conditioning */
  162629. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  162630. cinfo->arith_dc_L[i] = 0;
  162631. cinfo->arith_dc_U[i] = 1;
  162632. cinfo->arith_ac_K[i] = 5;
  162633. }
  162634. /* Default is no multiple-scan output */
  162635. cinfo->scan_info = NULL;
  162636. cinfo->num_scans = 0;
  162637. /* Expect normal source image, not raw downsampled data */
  162638. cinfo->raw_data_in = FALSE;
  162639. /* Use Huffman coding, not arithmetic coding, by default */
  162640. cinfo->arith_code = FALSE;
  162641. /* By default, don't do extra passes to optimize entropy coding */
  162642. cinfo->optimize_coding = FALSE;
  162643. /* The standard Huffman tables are only valid for 8-bit data precision.
  162644. * If the precision is higher, force optimization on so that usable
  162645. * tables will be computed. This test can be removed if default tables
  162646. * are supplied that are valid for the desired precision.
  162647. */
  162648. if (cinfo->data_precision > 8)
  162649. cinfo->optimize_coding = TRUE;
  162650. /* By default, use the simpler non-cosited sampling alignment */
  162651. cinfo->CCIR601_sampling = FALSE;
  162652. /* No input smoothing */
  162653. cinfo->smoothing_factor = 0;
  162654. /* DCT algorithm preference */
  162655. cinfo->dct_method = JDCT_DEFAULT;
  162656. /* No restart markers */
  162657. cinfo->restart_interval = 0;
  162658. cinfo->restart_in_rows = 0;
  162659. /* Fill in default JFIF marker parameters. Note that whether the marker
  162660. * will actually be written is determined by jpeg_set_colorspace.
  162661. *
  162662. * By default, the library emits JFIF version code 1.01.
  162663. * An application that wants to emit JFIF 1.02 extension markers should set
  162664. * JFIF_minor_version to 2. We could probably get away with just defaulting
  162665. * to 1.02, but there may still be some decoders in use that will complain
  162666. * about that; saying 1.01 should minimize compatibility problems.
  162667. */
  162668. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  162669. cinfo->JFIF_minor_version = 1;
  162670. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  162671. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  162672. cinfo->Y_density = 1;
  162673. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  162674. jpeg_default_colorspace(cinfo);
  162675. }
  162676. /*
  162677. * Select an appropriate JPEG colorspace for in_color_space.
  162678. */
  162679. GLOBAL(void)
  162680. jpeg_default_colorspace (j_compress_ptr cinfo)
  162681. {
  162682. switch (cinfo->in_color_space) {
  162683. case JCS_GRAYSCALE:
  162684. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  162685. break;
  162686. case JCS_RGB:
  162687. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  162688. break;
  162689. case JCS_YCbCr:
  162690. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  162691. break;
  162692. case JCS_CMYK:
  162693. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  162694. break;
  162695. case JCS_YCCK:
  162696. jpeg_set_colorspace(cinfo, JCS_YCCK);
  162697. break;
  162698. case JCS_UNKNOWN:
  162699. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  162700. break;
  162701. default:
  162702. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162703. }
  162704. }
  162705. /*
  162706. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  162707. */
  162708. GLOBAL(void)
  162709. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  162710. {
  162711. jpeg_component_info * compptr;
  162712. int ci;
  162713. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  162714. (compptr = &cinfo->comp_info[index], \
  162715. compptr->component_id = (id), \
  162716. compptr->h_samp_factor = (hsamp), \
  162717. compptr->v_samp_factor = (vsamp), \
  162718. compptr->quant_tbl_no = (quant), \
  162719. compptr->dc_tbl_no = (dctbl), \
  162720. compptr->ac_tbl_no = (actbl) )
  162721. /* Safety check to ensure start_compress not called yet. */
  162722. if (cinfo->global_state != CSTATE_START)
  162723. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162724. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  162725. * tables 1 for chrominance components.
  162726. */
  162727. cinfo->jpeg_color_space = colorspace;
  162728. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  162729. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  162730. switch (colorspace) {
  162731. case JCS_GRAYSCALE:
  162732. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  162733. cinfo->num_components = 1;
  162734. /* JFIF specifies component ID 1 */
  162735. SET_COMP(0, 1, 1,1, 0, 0,0);
  162736. break;
  162737. case JCS_RGB:
  162738. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  162739. cinfo->num_components = 3;
  162740. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  162741. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  162742. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  162743. break;
  162744. case JCS_YCbCr:
  162745. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  162746. cinfo->num_components = 3;
  162747. /* JFIF specifies component IDs 1,2,3 */
  162748. /* We default to 2x2 subsamples of chrominance */
  162749. SET_COMP(0, 1, 2,2, 0, 0,0);
  162750. SET_COMP(1, 2, 1,1, 1, 1,1);
  162751. SET_COMP(2, 3, 1,1, 1, 1,1);
  162752. break;
  162753. case JCS_CMYK:
  162754. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  162755. cinfo->num_components = 4;
  162756. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  162757. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  162758. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  162759. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  162760. break;
  162761. case JCS_YCCK:
  162762. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  162763. cinfo->num_components = 4;
  162764. SET_COMP(0, 1, 2,2, 0, 0,0);
  162765. SET_COMP(1, 2, 1,1, 1, 1,1);
  162766. SET_COMP(2, 3, 1,1, 1, 1,1);
  162767. SET_COMP(3, 4, 2,2, 0, 0,0);
  162768. break;
  162769. case JCS_UNKNOWN:
  162770. cinfo->num_components = cinfo->input_components;
  162771. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  162772. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  162773. MAX_COMPONENTS);
  162774. for (ci = 0; ci < cinfo->num_components; ci++) {
  162775. SET_COMP(ci, ci, 1,1, 0, 0,0);
  162776. }
  162777. break;
  162778. default:
  162779. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162780. }
  162781. }
  162782. #ifdef C_PROGRESSIVE_SUPPORTED
  162783. LOCAL(jpeg_scan_info *)
  162784. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  162785. int Ss, int Se, int Ah, int Al)
  162786. /* Support routine: generate one scan for specified component */
  162787. {
  162788. scanptr->comps_in_scan = 1;
  162789. scanptr->component_index[0] = ci;
  162790. scanptr->Ss = Ss;
  162791. scanptr->Se = Se;
  162792. scanptr->Ah = Ah;
  162793. scanptr->Al = Al;
  162794. scanptr++;
  162795. return scanptr;
  162796. }
  162797. LOCAL(jpeg_scan_info *)
  162798. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  162799. int Ss, int Se, int Ah, int Al)
  162800. /* Support routine: generate one scan for each component */
  162801. {
  162802. int ci;
  162803. for (ci = 0; ci < ncomps; ci++) {
  162804. scanptr->comps_in_scan = 1;
  162805. scanptr->component_index[0] = ci;
  162806. scanptr->Ss = Ss;
  162807. scanptr->Se = Se;
  162808. scanptr->Ah = Ah;
  162809. scanptr->Al = Al;
  162810. scanptr++;
  162811. }
  162812. return scanptr;
  162813. }
  162814. LOCAL(jpeg_scan_info *)
  162815. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  162816. /* Support routine: generate interleaved DC scan if possible, else N scans */
  162817. {
  162818. int ci;
  162819. if (ncomps <= MAX_COMPS_IN_SCAN) {
  162820. /* Single interleaved DC scan */
  162821. scanptr->comps_in_scan = ncomps;
  162822. for (ci = 0; ci < ncomps; ci++)
  162823. scanptr->component_index[ci] = ci;
  162824. scanptr->Ss = scanptr->Se = 0;
  162825. scanptr->Ah = Ah;
  162826. scanptr->Al = Al;
  162827. scanptr++;
  162828. } else {
  162829. /* Noninterleaved DC scan for each component */
  162830. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  162831. }
  162832. return scanptr;
  162833. }
  162834. /*
  162835. * Create a recommended progressive-JPEG script.
  162836. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  162837. */
  162838. GLOBAL(void)
  162839. jpeg_simple_progression (j_compress_ptr cinfo)
  162840. {
  162841. int ncomps = cinfo->num_components;
  162842. int nscans;
  162843. jpeg_scan_info * scanptr;
  162844. /* Safety check to ensure start_compress not called yet. */
  162845. if (cinfo->global_state != CSTATE_START)
  162846. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162847. /* Figure space needed for script. Calculation must match code below! */
  162848. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  162849. /* Custom script for YCbCr color images. */
  162850. nscans = 10;
  162851. } else {
  162852. /* All-purpose script for other color spaces. */
  162853. if (ncomps > MAX_COMPS_IN_SCAN)
  162854. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  162855. else
  162856. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  162857. }
  162858. /* Allocate space for script.
  162859. * We need to put it in the permanent pool in case the application performs
  162860. * multiple compressions without changing the settings. To avoid a memory
  162861. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  162862. * object, we try to re-use previously allocated space, and we allocate
  162863. * enough space to handle YCbCr even if initially asked for grayscale.
  162864. */
  162865. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  162866. cinfo->script_space_size = MAX(nscans, 10);
  162867. cinfo->script_space = (jpeg_scan_info *)
  162868. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  162869. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  162870. }
  162871. scanptr = cinfo->script_space;
  162872. cinfo->scan_info = scanptr;
  162873. cinfo->num_scans = nscans;
  162874. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  162875. /* Custom script for YCbCr color images. */
  162876. /* Initial DC scan */
  162877. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  162878. /* Initial AC scan: get some luma data out in a hurry */
  162879. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  162880. /* Chroma data is too small to be worth expending many scans on */
  162881. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  162882. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  162883. /* Complete spectral selection for luma AC */
  162884. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  162885. /* Refine next bit of luma AC */
  162886. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  162887. /* Finish DC successive approximation */
  162888. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  162889. /* Finish AC successive approximation */
  162890. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  162891. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  162892. /* Luma bottom bit comes last since it's usually largest scan */
  162893. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  162894. } else {
  162895. /* All-purpose script for other color spaces. */
  162896. /* Successive approximation first pass */
  162897. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  162898. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  162899. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  162900. /* Successive approximation second pass */
  162901. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  162902. /* Successive approximation final pass */
  162903. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  162904. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  162905. }
  162906. }
  162907. #endif /* C_PROGRESSIVE_SUPPORTED */
  162908. /*** End of inlined file: jcparam.c ***/
  162909. /*** Start of inlined file: jcphuff.c ***/
  162910. #define JPEG_INTERNALS
  162911. #ifdef C_PROGRESSIVE_SUPPORTED
  162912. /* Expanded entropy encoder object for progressive Huffman encoding. */
  162913. typedef struct {
  162914. struct jpeg_entropy_encoder pub; /* public fields */
  162915. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  162916. boolean gather_statistics;
  162917. /* Bit-level coding status.
  162918. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  162919. */
  162920. JOCTET * next_output_byte; /* => next byte to write in buffer */
  162921. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  162922. INT32 put_buffer; /* current bit-accumulation buffer */
  162923. int put_bits; /* # of bits now in it */
  162924. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  162925. /* Coding status for DC components */
  162926. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  162927. /* Coding status for AC components */
  162928. int ac_tbl_no; /* the table number of the single component */
  162929. unsigned int EOBRUN; /* run length of EOBs */
  162930. unsigned int BE; /* # of buffered correction bits before MCU */
  162931. char * bit_buffer; /* buffer for correction bits (1 per char) */
  162932. /* packing correction bits tightly would save some space but cost time... */
  162933. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  162934. int next_restart_num; /* next restart number to write (0-7) */
  162935. /* Pointers to derived tables (these workspaces have image lifespan).
  162936. * Since any one scan codes only DC or only AC, we only need one set
  162937. * of tables, not one for DC and one for AC.
  162938. */
  162939. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  162940. /* Statistics tables for optimization; again, one set is enough */
  162941. long * count_ptrs[NUM_HUFF_TBLS];
  162942. } phuff_entropy_encoder;
  162943. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  162944. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  162945. * buffer can hold. Larger sizes may slightly improve compression, but
  162946. * 1000 is already well into the realm of overkill.
  162947. * The minimum safe size is 64 bits.
  162948. */
  162949. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  162950. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  162951. * We assume that int right shift is unsigned if INT32 right shift is,
  162952. * which should be safe.
  162953. */
  162954. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  162955. #define ISHIFT_TEMPS int ishift_temp;
  162956. #define IRIGHT_SHIFT(x,shft) \
  162957. ((ishift_temp = (x)) < 0 ? \
  162958. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  162959. (ishift_temp >> (shft)))
  162960. #else
  162961. #define ISHIFT_TEMPS
  162962. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  162963. #endif
  162964. /* Forward declarations */
  162965. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  162966. JBLOCKROW *MCU_data));
  162967. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  162968. JBLOCKROW *MCU_data));
  162969. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  162970. JBLOCKROW *MCU_data));
  162971. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  162972. JBLOCKROW *MCU_data));
  162973. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  162974. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  162975. /*
  162976. * Initialize for a Huffman-compressed scan using progressive JPEG.
  162977. */
  162978. METHODDEF(void)
  162979. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  162980. {
  162981. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  162982. boolean is_DC_band;
  162983. int ci, tbl;
  162984. jpeg_component_info * compptr;
  162985. entropy->cinfo = cinfo;
  162986. entropy->gather_statistics = gather_statistics;
  162987. is_DC_band = (cinfo->Ss == 0);
  162988. /* We assume jcmaster.c already validated the scan parameters. */
  162989. /* Select execution routines */
  162990. if (cinfo->Ah == 0) {
  162991. if (is_DC_band)
  162992. entropy->pub.encode_mcu = encode_mcu_DC_first;
  162993. else
  162994. entropy->pub.encode_mcu = encode_mcu_AC_first;
  162995. } else {
  162996. if (is_DC_band)
  162997. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  162998. else {
  162999. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  163000. /* AC refinement needs a correction bit buffer */
  163001. if (entropy->bit_buffer == NULL)
  163002. entropy->bit_buffer = (char *)
  163003. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163004. MAX_CORR_BITS * SIZEOF(char));
  163005. }
  163006. }
  163007. if (gather_statistics)
  163008. entropy->pub.finish_pass = finish_pass_gather_phuff;
  163009. else
  163010. entropy->pub.finish_pass = finish_pass_phuff;
  163011. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  163012. * for AC coefficients.
  163013. */
  163014. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163015. compptr = cinfo->cur_comp_info[ci];
  163016. /* Initialize DC predictions to 0 */
  163017. entropy->last_dc_val[ci] = 0;
  163018. /* Get table index */
  163019. if (is_DC_band) {
  163020. if (cinfo->Ah != 0) /* DC refinement needs no table */
  163021. continue;
  163022. tbl = compptr->dc_tbl_no;
  163023. } else {
  163024. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  163025. }
  163026. if (gather_statistics) {
  163027. /* Check for invalid table index */
  163028. /* (make_c_derived_tbl does this in the other path) */
  163029. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  163030. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  163031. /* Allocate and zero the statistics tables */
  163032. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  163033. if (entropy->count_ptrs[tbl] == NULL)
  163034. entropy->count_ptrs[tbl] = (long *)
  163035. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163036. 257 * SIZEOF(long));
  163037. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  163038. } else {
  163039. /* Compute derived values for Huffman table */
  163040. /* We may do this more than once for a table, but it's not expensive */
  163041. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  163042. & entropy->derived_tbls[tbl]);
  163043. }
  163044. }
  163045. /* Initialize AC stuff */
  163046. entropy->EOBRUN = 0;
  163047. entropy->BE = 0;
  163048. /* Initialize bit buffer to empty */
  163049. entropy->put_buffer = 0;
  163050. entropy->put_bits = 0;
  163051. /* Initialize restart stuff */
  163052. entropy->restarts_to_go = cinfo->restart_interval;
  163053. entropy->next_restart_num = 0;
  163054. }
  163055. /* Outputting bytes to the file.
  163056. * NB: these must be called only when actually outputting,
  163057. * that is, entropy->gather_statistics == FALSE.
  163058. */
  163059. /* Emit a byte */
  163060. #define emit_byte(entropy,val) \
  163061. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  163062. if (--(entropy)->free_in_buffer == 0) \
  163063. dump_buffer_p(entropy); }
  163064. LOCAL(void)
  163065. dump_buffer_p (phuff_entropy_ptr entropy)
  163066. /* Empty the output buffer; we do not support suspension in this module. */
  163067. {
  163068. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  163069. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  163070. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  163071. /* After a successful buffer dump, must reset buffer pointers */
  163072. entropy->next_output_byte = dest->next_output_byte;
  163073. entropy->free_in_buffer = dest->free_in_buffer;
  163074. }
  163075. /* Outputting bits to the file */
  163076. /* Only the right 24 bits of put_buffer are used; the valid bits are
  163077. * left-justified in this part. At most 16 bits can be passed to emit_bits
  163078. * in one call, and we never retain more than 7 bits in put_buffer
  163079. * between calls, so 24 bits are sufficient.
  163080. */
  163081. INLINE
  163082. LOCAL(void)
  163083. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  163084. /* Emit some bits, unless we are in gather mode */
  163085. {
  163086. /* This routine is heavily used, so it's worth coding tightly. */
  163087. register INT32 put_buffer = (INT32) code;
  163088. register int put_bits = entropy->put_bits;
  163089. /* if size is 0, caller used an invalid Huffman table entry */
  163090. if (size == 0)
  163091. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  163092. if (entropy->gather_statistics)
  163093. return; /* do nothing if we're only getting stats */
  163094. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  163095. put_bits += size; /* new number of bits in buffer */
  163096. put_buffer <<= 24 - put_bits; /* align incoming bits */
  163097. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  163098. while (put_bits >= 8) {
  163099. int c = (int) ((put_buffer >> 16) & 0xFF);
  163100. emit_byte(entropy, c);
  163101. if (c == 0xFF) { /* need to stuff a zero byte? */
  163102. emit_byte(entropy, 0);
  163103. }
  163104. put_buffer <<= 8;
  163105. put_bits -= 8;
  163106. }
  163107. entropy->put_buffer = put_buffer; /* update variables */
  163108. entropy->put_bits = put_bits;
  163109. }
  163110. LOCAL(void)
  163111. flush_bits_p (phuff_entropy_ptr entropy)
  163112. {
  163113. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  163114. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  163115. entropy->put_bits = 0;
  163116. }
  163117. /*
  163118. * Emit (or just count) a Huffman symbol.
  163119. */
  163120. INLINE
  163121. LOCAL(void)
  163122. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  163123. {
  163124. if (entropy->gather_statistics)
  163125. entropy->count_ptrs[tbl_no][symbol]++;
  163126. else {
  163127. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  163128. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  163129. }
  163130. }
  163131. /*
  163132. * Emit bits from a correction bit buffer.
  163133. */
  163134. LOCAL(void)
  163135. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  163136. unsigned int nbits)
  163137. {
  163138. if (entropy->gather_statistics)
  163139. return; /* no real work */
  163140. while (nbits > 0) {
  163141. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  163142. bufstart++;
  163143. nbits--;
  163144. }
  163145. }
  163146. /*
  163147. * Emit any pending EOBRUN symbol.
  163148. */
  163149. LOCAL(void)
  163150. emit_eobrun (phuff_entropy_ptr entropy)
  163151. {
  163152. register int temp, nbits;
  163153. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  163154. temp = entropy->EOBRUN;
  163155. nbits = 0;
  163156. while ((temp >>= 1))
  163157. nbits++;
  163158. /* safety check: shouldn't happen given limited correction-bit buffer */
  163159. if (nbits > 14)
  163160. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  163161. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  163162. if (nbits)
  163163. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  163164. entropy->EOBRUN = 0;
  163165. /* Emit any buffered correction bits */
  163166. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  163167. entropy->BE = 0;
  163168. }
  163169. }
  163170. /*
  163171. * Emit a restart marker & resynchronize predictions.
  163172. */
  163173. LOCAL(void)
  163174. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  163175. {
  163176. int ci;
  163177. emit_eobrun(entropy);
  163178. if (! entropy->gather_statistics) {
  163179. flush_bits_p(entropy);
  163180. emit_byte(entropy, 0xFF);
  163181. emit_byte(entropy, JPEG_RST0 + restart_num);
  163182. }
  163183. if (entropy->cinfo->Ss == 0) {
  163184. /* Re-initialize DC predictions to 0 */
  163185. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  163186. entropy->last_dc_val[ci] = 0;
  163187. } else {
  163188. /* Re-initialize all AC-related fields to 0 */
  163189. entropy->EOBRUN = 0;
  163190. entropy->BE = 0;
  163191. }
  163192. }
  163193. /*
  163194. * MCU encoding for DC initial scan (either spectral selection,
  163195. * or first pass of successive approximation).
  163196. */
  163197. METHODDEF(boolean)
  163198. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163199. {
  163200. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  163201. register int temp, temp2;
  163202. register int nbits;
  163203. int blkn, ci;
  163204. int Al = cinfo->Al;
  163205. JBLOCKROW block;
  163206. jpeg_component_info * compptr;
  163207. ISHIFT_TEMPS
  163208. entropy->next_output_byte = cinfo->dest->next_output_byte;
  163209. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  163210. /* Emit restart marker if needed */
  163211. if (cinfo->restart_interval)
  163212. if (entropy->restarts_to_go == 0)
  163213. emit_restart_p(entropy, entropy->next_restart_num);
  163214. /* Encode the MCU data blocks */
  163215. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163216. block = MCU_data[blkn];
  163217. ci = cinfo->MCU_membership[blkn];
  163218. compptr = cinfo->cur_comp_info[ci];
  163219. /* Compute the DC value after the required point transform by Al.
  163220. * This is simply an arithmetic right shift.
  163221. */
  163222. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  163223. /* DC differences are figured on the point-transformed values. */
  163224. temp = temp2 - entropy->last_dc_val[ci];
  163225. entropy->last_dc_val[ci] = temp2;
  163226. /* Encode the DC coefficient difference per section G.1.2.1 */
  163227. temp2 = temp;
  163228. if (temp < 0) {
  163229. temp = -temp; /* temp is abs value of input */
  163230. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  163231. /* This code assumes we are on a two's complement machine */
  163232. temp2--;
  163233. }
  163234. /* Find the number of bits needed for the magnitude of the coefficient */
  163235. nbits = 0;
  163236. while (temp) {
  163237. nbits++;
  163238. temp >>= 1;
  163239. }
  163240. /* Check for out-of-range coefficient values.
  163241. * Since we're encoding a difference, the range limit is twice as much.
  163242. */
  163243. if (nbits > MAX_COEF_BITS+1)
  163244. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163245. /* Count/emit the Huffman-coded symbol for the number of bits */
  163246. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  163247. /* Emit that number of bits of the value, if positive, */
  163248. /* or the complement of its magnitude, if negative. */
  163249. if (nbits) /* emit_bits rejects calls with size 0 */
  163250. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  163251. }
  163252. cinfo->dest->next_output_byte = entropy->next_output_byte;
  163253. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  163254. /* Update restart-interval state too */
  163255. if (cinfo->restart_interval) {
  163256. if (entropy->restarts_to_go == 0) {
  163257. entropy->restarts_to_go = cinfo->restart_interval;
  163258. entropy->next_restart_num++;
  163259. entropy->next_restart_num &= 7;
  163260. }
  163261. entropy->restarts_to_go--;
  163262. }
  163263. return TRUE;
  163264. }
  163265. /*
  163266. * MCU encoding for AC initial scan (either spectral selection,
  163267. * or first pass of successive approximation).
  163268. */
  163269. METHODDEF(boolean)
  163270. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163271. {
  163272. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  163273. register int temp, temp2;
  163274. register int nbits;
  163275. register int r, k;
  163276. int Se = cinfo->Se;
  163277. int Al = cinfo->Al;
  163278. JBLOCKROW block;
  163279. entropy->next_output_byte = cinfo->dest->next_output_byte;
  163280. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  163281. /* Emit restart marker if needed */
  163282. if (cinfo->restart_interval)
  163283. if (entropy->restarts_to_go == 0)
  163284. emit_restart_p(entropy, entropy->next_restart_num);
  163285. /* Encode the MCU data block */
  163286. block = MCU_data[0];
  163287. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  163288. r = 0; /* r = run length of zeros */
  163289. for (k = cinfo->Ss; k <= Se; k++) {
  163290. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  163291. r++;
  163292. continue;
  163293. }
  163294. /* We must apply the point transform by Al. For AC coefficients this
  163295. * is an integer division with rounding towards 0. To do this portably
  163296. * in C, we shift after obtaining the absolute value; so the code is
  163297. * interwoven with finding the abs value (temp) and output bits (temp2).
  163298. */
  163299. if (temp < 0) {
  163300. temp = -temp; /* temp is abs value of input */
  163301. temp >>= Al; /* apply the point transform */
  163302. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  163303. temp2 = ~temp;
  163304. } else {
  163305. temp >>= Al; /* apply the point transform */
  163306. temp2 = temp;
  163307. }
  163308. /* Watch out for case that nonzero coef is zero after point transform */
  163309. if (temp == 0) {
  163310. r++;
  163311. continue;
  163312. }
  163313. /* Emit any pending EOBRUN */
  163314. if (entropy->EOBRUN > 0)
  163315. emit_eobrun(entropy);
  163316. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163317. while (r > 15) {
  163318. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  163319. r -= 16;
  163320. }
  163321. /* Find the number of bits needed for the magnitude of the coefficient */
  163322. nbits = 1; /* there must be at least one 1 bit */
  163323. while ((temp >>= 1))
  163324. nbits++;
  163325. /* Check for out-of-range coefficient values */
  163326. if (nbits > MAX_COEF_BITS)
  163327. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163328. /* Count/emit Huffman symbol for run length / number of bits */
  163329. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  163330. /* Emit that number of bits of the value, if positive, */
  163331. /* or the complement of its magnitude, if negative. */
  163332. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  163333. r = 0; /* reset zero run length */
  163334. }
  163335. if (r > 0) { /* If there are trailing zeroes, */
  163336. entropy->EOBRUN++; /* count an EOB */
  163337. if (entropy->EOBRUN == 0x7FFF)
  163338. emit_eobrun(entropy); /* force it out to avoid overflow */
  163339. }
  163340. cinfo->dest->next_output_byte = entropy->next_output_byte;
  163341. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  163342. /* Update restart-interval state too */
  163343. if (cinfo->restart_interval) {
  163344. if (entropy->restarts_to_go == 0) {
  163345. entropy->restarts_to_go = cinfo->restart_interval;
  163346. entropy->next_restart_num++;
  163347. entropy->next_restart_num &= 7;
  163348. }
  163349. entropy->restarts_to_go--;
  163350. }
  163351. return TRUE;
  163352. }
  163353. /*
  163354. * MCU encoding for DC successive approximation refinement scan.
  163355. * Note: we assume such scans can be multi-component, although the spec
  163356. * is not very clear on the point.
  163357. */
  163358. METHODDEF(boolean)
  163359. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163360. {
  163361. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  163362. register int temp;
  163363. int blkn;
  163364. int Al = cinfo->Al;
  163365. JBLOCKROW block;
  163366. entropy->next_output_byte = cinfo->dest->next_output_byte;
  163367. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  163368. /* Emit restart marker if needed */
  163369. if (cinfo->restart_interval)
  163370. if (entropy->restarts_to_go == 0)
  163371. emit_restart_p(entropy, entropy->next_restart_num);
  163372. /* Encode the MCU data blocks */
  163373. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163374. block = MCU_data[blkn];
  163375. /* We simply emit the Al'th bit of the DC coefficient value. */
  163376. temp = (*block)[0];
  163377. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  163378. }
  163379. cinfo->dest->next_output_byte = entropy->next_output_byte;
  163380. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  163381. /* Update restart-interval state too */
  163382. if (cinfo->restart_interval) {
  163383. if (entropy->restarts_to_go == 0) {
  163384. entropy->restarts_to_go = cinfo->restart_interval;
  163385. entropy->next_restart_num++;
  163386. entropy->next_restart_num &= 7;
  163387. }
  163388. entropy->restarts_to_go--;
  163389. }
  163390. return TRUE;
  163391. }
  163392. /*
  163393. * MCU encoding for AC successive approximation refinement scan.
  163394. */
  163395. METHODDEF(boolean)
  163396. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163397. {
  163398. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  163399. register int temp;
  163400. register int r, k;
  163401. int EOB;
  163402. char *BR_buffer;
  163403. unsigned int BR;
  163404. int Se = cinfo->Se;
  163405. int Al = cinfo->Al;
  163406. JBLOCKROW block;
  163407. int absvalues[DCTSIZE2];
  163408. entropy->next_output_byte = cinfo->dest->next_output_byte;
  163409. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  163410. /* Emit restart marker if needed */
  163411. if (cinfo->restart_interval)
  163412. if (entropy->restarts_to_go == 0)
  163413. emit_restart_p(entropy, entropy->next_restart_num);
  163414. /* Encode the MCU data block */
  163415. block = MCU_data[0];
  163416. /* It is convenient to make a pre-pass to determine the transformed
  163417. * coefficients' absolute values and the EOB position.
  163418. */
  163419. EOB = 0;
  163420. for (k = cinfo->Ss; k <= Se; k++) {
  163421. temp = (*block)[jpeg_natural_order[k]];
  163422. /* We must apply the point transform by Al. For AC coefficients this
  163423. * is an integer division with rounding towards 0. To do this portably
  163424. * in C, we shift after obtaining the absolute value.
  163425. */
  163426. if (temp < 0)
  163427. temp = -temp; /* temp is abs value of input */
  163428. temp >>= Al; /* apply the point transform */
  163429. absvalues[k] = temp; /* save abs value for main pass */
  163430. if (temp == 1)
  163431. EOB = k; /* EOB = index of last newly-nonzero coef */
  163432. }
  163433. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  163434. r = 0; /* r = run length of zeros */
  163435. BR = 0; /* BR = count of buffered bits added now */
  163436. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  163437. for (k = cinfo->Ss; k <= Se; k++) {
  163438. if ((temp = absvalues[k]) == 0) {
  163439. r++;
  163440. continue;
  163441. }
  163442. /* Emit any required ZRLs, but not if they can be folded into EOB */
  163443. while (r > 15 && k <= EOB) {
  163444. /* emit any pending EOBRUN and the BE correction bits */
  163445. emit_eobrun(entropy);
  163446. /* Emit ZRL */
  163447. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  163448. r -= 16;
  163449. /* Emit buffered correction bits that must be associated with ZRL */
  163450. emit_buffered_bits(entropy, BR_buffer, BR);
  163451. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  163452. BR = 0;
  163453. }
  163454. /* If the coef was previously nonzero, it only needs a correction bit.
  163455. * NOTE: a straight translation of the spec's figure G.7 would suggest
  163456. * that we also need to test r > 15. But if r > 15, we can only get here
  163457. * if k > EOB, which implies that this coefficient is not 1.
  163458. */
  163459. if (temp > 1) {
  163460. /* The correction bit is the next bit of the absolute value. */
  163461. BR_buffer[BR++] = (char) (temp & 1);
  163462. continue;
  163463. }
  163464. /* Emit any pending EOBRUN and the BE correction bits */
  163465. emit_eobrun(entropy);
  163466. /* Count/emit Huffman symbol for run length / number of bits */
  163467. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  163468. /* Emit output bit for newly-nonzero coef */
  163469. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  163470. emit_bits_p(entropy, (unsigned int) temp, 1);
  163471. /* Emit buffered correction bits that must be associated with this code */
  163472. emit_buffered_bits(entropy, BR_buffer, BR);
  163473. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  163474. BR = 0;
  163475. r = 0; /* reset zero run length */
  163476. }
  163477. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  163478. entropy->EOBRUN++; /* count an EOB */
  163479. entropy->BE += BR; /* concat my correction bits to older ones */
  163480. /* We force out the EOB if we risk either:
  163481. * 1. overflow of the EOB counter;
  163482. * 2. overflow of the correction bit buffer during the next MCU.
  163483. */
  163484. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  163485. emit_eobrun(entropy);
  163486. }
  163487. cinfo->dest->next_output_byte = entropy->next_output_byte;
  163488. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  163489. /* Update restart-interval state too */
  163490. if (cinfo->restart_interval) {
  163491. if (entropy->restarts_to_go == 0) {
  163492. entropy->restarts_to_go = cinfo->restart_interval;
  163493. entropy->next_restart_num++;
  163494. entropy->next_restart_num &= 7;
  163495. }
  163496. entropy->restarts_to_go--;
  163497. }
  163498. return TRUE;
  163499. }
  163500. /*
  163501. * Finish up at the end of a Huffman-compressed progressive scan.
  163502. */
  163503. METHODDEF(void)
  163504. finish_pass_phuff (j_compress_ptr cinfo)
  163505. {
  163506. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  163507. entropy->next_output_byte = cinfo->dest->next_output_byte;
  163508. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  163509. /* Flush out any buffered data */
  163510. emit_eobrun(entropy);
  163511. flush_bits_p(entropy);
  163512. cinfo->dest->next_output_byte = entropy->next_output_byte;
  163513. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  163514. }
  163515. /*
  163516. * Finish up a statistics-gathering pass and create the new Huffman tables.
  163517. */
  163518. METHODDEF(void)
  163519. finish_pass_gather_phuff (j_compress_ptr cinfo)
  163520. {
  163521. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  163522. boolean is_DC_band;
  163523. int ci, tbl;
  163524. jpeg_component_info * compptr;
  163525. JHUFF_TBL **htblptr;
  163526. boolean did[NUM_HUFF_TBLS];
  163527. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  163528. emit_eobrun(entropy);
  163529. is_DC_band = (cinfo->Ss == 0);
  163530. /* It's important not to apply jpeg_gen_optimal_table more than once
  163531. * per table, because it clobbers the input frequency counts!
  163532. */
  163533. MEMZERO(did, SIZEOF(did));
  163534. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163535. compptr = cinfo->cur_comp_info[ci];
  163536. if (is_DC_band) {
  163537. if (cinfo->Ah != 0) /* DC refinement needs no table */
  163538. continue;
  163539. tbl = compptr->dc_tbl_no;
  163540. } else {
  163541. tbl = compptr->ac_tbl_no;
  163542. }
  163543. if (! did[tbl]) {
  163544. if (is_DC_band)
  163545. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  163546. else
  163547. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  163548. if (*htblptr == NULL)
  163549. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163550. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  163551. did[tbl] = TRUE;
  163552. }
  163553. }
  163554. }
  163555. /*
  163556. * Module initialization routine for progressive Huffman entropy encoding.
  163557. */
  163558. GLOBAL(void)
  163559. jinit_phuff_encoder (j_compress_ptr cinfo)
  163560. {
  163561. phuff_entropy_ptr entropy;
  163562. int i;
  163563. entropy = (phuff_entropy_ptr)
  163564. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163565. SIZEOF(phuff_entropy_encoder));
  163566. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  163567. entropy->pub.start_pass = start_pass_phuff;
  163568. /* Mark tables unallocated */
  163569. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163570. entropy->derived_tbls[i] = NULL;
  163571. entropy->count_ptrs[i] = NULL;
  163572. }
  163573. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  163574. }
  163575. #endif /* C_PROGRESSIVE_SUPPORTED */
  163576. /*** End of inlined file: jcphuff.c ***/
  163577. /*** Start of inlined file: jcprepct.c ***/
  163578. #define JPEG_INTERNALS
  163579. /* At present, jcsample.c can request context rows only for smoothing.
  163580. * In the future, we might also need context rows for CCIR601 sampling
  163581. * or other more-complex downsampling procedures. The code to support
  163582. * context rows should be compiled only if needed.
  163583. */
  163584. #ifdef INPUT_SMOOTHING_SUPPORTED
  163585. #define CONTEXT_ROWS_SUPPORTED
  163586. #endif
  163587. /*
  163588. * For the simple (no-context-row) case, we just need to buffer one
  163589. * row group's worth of pixels for the downsampling step. At the bottom of
  163590. * the image, we pad to a full row group by replicating the last pixel row.
  163591. * The downsampler's last output row is then replicated if needed to pad
  163592. * out to a full iMCU row.
  163593. *
  163594. * When providing context rows, we must buffer three row groups' worth of
  163595. * pixels. Three row groups are physically allocated, but the row pointer
  163596. * arrays are made five row groups high, with the extra pointers above and
  163597. * below "wrapping around" to point to the last and first real row groups.
  163598. * This allows the downsampler to access the proper context rows.
  163599. * At the top and bottom of the image, we create dummy context rows by
  163600. * copying the first or last real pixel row. This copying could be avoided
  163601. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  163602. * trouble on the compression side.
  163603. */
  163604. /* Private buffer controller object */
  163605. typedef struct {
  163606. struct jpeg_c_prep_controller pub; /* public fields */
  163607. /* Downsampling input buffer. This buffer holds color-converted data
  163608. * until we have enough to do a downsample step.
  163609. */
  163610. JSAMPARRAY color_buf[MAX_COMPONENTS];
  163611. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  163612. int next_buf_row; /* index of next row to store in color_buf */
  163613. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  163614. int this_row_group; /* starting row index of group to process */
  163615. int next_buf_stop; /* downsample when we reach this index */
  163616. #endif
  163617. } my_prep_controller;
  163618. typedef my_prep_controller * my_prep_ptr;
  163619. /*
  163620. * Initialize for a processing pass.
  163621. */
  163622. METHODDEF(void)
  163623. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  163624. {
  163625. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  163626. if (pass_mode != JBUF_PASS_THRU)
  163627. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163628. /* Initialize total-height counter for detecting bottom of image */
  163629. prep->rows_to_go = cinfo->image_height;
  163630. /* Mark the conversion buffer empty */
  163631. prep->next_buf_row = 0;
  163632. #ifdef CONTEXT_ROWS_SUPPORTED
  163633. /* Preset additional state variables for context mode.
  163634. * These aren't used in non-context mode, so we needn't test which mode.
  163635. */
  163636. prep->this_row_group = 0;
  163637. /* Set next_buf_stop to stop after two row groups have been read in. */
  163638. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  163639. #endif
  163640. }
  163641. /*
  163642. * Expand an image vertically from height input_rows to height output_rows,
  163643. * by duplicating the bottom row.
  163644. */
  163645. LOCAL(void)
  163646. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  163647. int input_rows, int output_rows)
  163648. {
  163649. register int row;
  163650. for (row = input_rows; row < output_rows; row++) {
  163651. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  163652. 1, num_cols);
  163653. }
  163654. }
  163655. /*
  163656. * Process some data in the simple no-context case.
  163657. *
  163658. * Preprocessor output data is counted in "row groups". A row group
  163659. * is defined to be v_samp_factor sample rows of each component.
  163660. * Downsampling will produce this much data from each max_v_samp_factor
  163661. * input rows.
  163662. */
  163663. METHODDEF(void)
  163664. pre_process_data (j_compress_ptr cinfo,
  163665. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163666. JDIMENSION in_rows_avail,
  163667. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  163668. JDIMENSION out_row_groups_avail)
  163669. {
  163670. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  163671. int numrows, ci;
  163672. JDIMENSION inrows;
  163673. jpeg_component_info * compptr;
  163674. while (*in_row_ctr < in_rows_avail &&
  163675. *out_row_group_ctr < out_row_groups_avail) {
  163676. /* Do color conversion to fill the conversion buffer. */
  163677. inrows = in_rows_avail - *in_row_ctr;
  163678. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  163679. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  163680. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  163681. prep->color_buf,
  163682. (JDIMENSION) prep->next_buf_row,
  163683. numrows);
  163684. *in_row_ctr += numrows;
  163685. prep->next_buf_row += numrows;
  163686. prep->rows_to_go -= numrows;
  163687. /* If at bottom of image, pad to fill the conversion buffer. */
  163688. if (prep->rows_to_go == 0 &&
  163689. prep->next_buf_row < cinfo->max_v_samp_factor) {
  163690. for (ci = 0; ci < cinfo->num_components; ci++) {
  163691. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  163692. prep->next_buf_row, cinfo->max_v_samp_factor);
  163693. }
  163694. prep->next_buf_row = cinfo->max_v_samp_factor;
  163695. }
  163696. /* If we've filled the conversion buffer, empty it. */
  163697. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  163698. (*cinfo->downsample->downsample) (cinfo,
  163699. prep->color_buf, (JDIMENSION) 0,
  163700. output_buf, *out_row_group_ctr);
  163701. prep->next_buf_row = 0;
  163702. (*out_row_group_ctr)++;
  163703. }
  163704. /* If at bottom of image, pad the output to a full iMCU height.
  163705. * Note we assume the caller is providing a one-iMCU-height output buffer!
  163706. */
  163707. if (prep->rows_to_go == 0 &&
  163708. *out_row_group_ctr < out_row_groups_avail) {
  163709. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163710. ci++, compptr++) {
  163711. expand_bottom_edge(output_buf[ci],
  163712. compptr->width_in_blocks * DCTSIZE,
  163713. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  163714. (int) (out_row_groups_avail * compptr->v_samp_factor));
  163715. }
  163716. *out_row_group_ctr = out_row_groups_avail;
  163717. break; /* can exit outer loop without test */
  163718. }
  163719. }
  163720. }
  163721. #ifdef CONTEXT_ROWS_SUPPORTED
  163722. /*
  163723. * Process some data in the context case.
  163724. */
  163725. METHODDEF(void)
  163726. pre_process_context (j_compress_ptr cinfo,
  163727. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163728. JDIMENSION in_rows_avail,
  163729. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  163730. JDIMENSION out_row_groups_avail)
  163731. {
  163732. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  163733. int numrows, ci;
  163734. int buf_height = cinfo->max_v_samp_factor * 3;
  163735. JDIMENSION inrows;
  163736. while (*out_row_group_ctr < out_row_groups_avail) {
  163737. if (*in_row_ctr < in_rows_avail) {
  163738. /* Do color conversion to fill the conversion buffer. */
  163739. inrows = in_rows_avail - *in_row_ctr;
  163740. numrows = prep->next_buf_stop - prep->next_buf_row;
  163741. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  163742. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  163743. prep->color_buf,
  163744. (JDIMENSION) prep->next_buf_row,
  163745. numrows);
  163746. /* Pad at top of image, if first time through */
  163747. if (prep->rows_to_go == cinfo->image_height) {
  163748. for (ci = 0; ci < cinfo->num_components; ci++) {
  163749. int row;
  163750. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  163751. jcopy_sample_rows(prep->color_buf[ci], 0,
  163752. prep->color_buf[ci], -row,
  163753. 1, cinfo->image_width);
  163754. }
  163755. }
  163756. }
  163757. *in_row_ctr += numrows;
  163758. prep->next_buf_row += numrows;
  163759. prep->rows_to_go -= numrows;
  163760. } else {
  163761. /* Return for more data, unless we are at the bottom of the image. */
  163762. if (prep->rows_to_go != 0)
  163763. break;
  163764. /* When at bottom of image, pad to fill the conversion buffer. */
  163765. if (prep->next_buf_row < prep->next_buf_stop) {
  163766. for (ci = 0; ci < cinfo->num_components; ci++) {
  163767. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  163768. prep->next_buf_row, prep->next_buf_stop);
  163769. }
  163770. prep->next_buf_row = prep->next_buf_stop;
  163771. }
  163772. }
  163773. /* If we've gotten enough data, downsample a row group. */
  163774. if (prep->next_buf_row == prep->next_buf_stop) {
  163775. (*cinfo->downsample->downsample) (cinfo,
  163776. prep->color_buf,
  163777. (JDIMENSION) prep->this_row_group,
  163778. output_buf, *out_row_group_ctr);
  163779. (*out_row_group_ctr)++;
  163780. /* Advance pointers with wraparound as necessary. */
  163781. prep->this_row_group += cinfo->max_v_samp_factor;
  163782. if (prep->this_row_group >= buf_height)
  163783. prep->this_row_group = 0;
  163784. if (prep->next_buf_row >= buf_height)
  163785. prep->next_buf_row = 0;
  163786. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  163787. }
  163788. }
  163789. }
  163790. /*
  163791. * Create the wrapped-around downsampling input buffer needed for context mode.
  163792. */
  163793. LOCAL(void)
  163794. create_context_buffer (j_compress_ptr cinfo)
  163795. {
  163796. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  163797. int rgroup_height = cinfo->max_v_samp_factor;
  163798. int ci, i;
  163799. jpeg_component_info * compptr;
  163800. JSAMPARRAY true_buffer, fake_buffer;
  163801. /* Grab enough space for fake row pointers for all the components;
  163802. * we need five row groups' worth of pointers for each component.
  163803. */
  163804. fake_buffer = (JSAMPARRAY)
  163805. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163806. (cinfo->num_components * 5 * rgroup_height) *
  163807. SIZEOF(JSAMPROW));
  163808. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163809. ci++, compptr++) {
  163810. /* Allocate the actual buffer space (3 row groups) for this component.
  163811. * We make the buffer wide enough to allow the downsampler to edge-expand
  163812. * horizontally within the buffer, if it so chooses.
  163813. */
  163814. true_buffer = (*cinfo->mem->alloc_sarray)
  163815. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163816. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  163817. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  163818. (JDIMENSION) (3 * rgroup_height));
  163819. /* Copy true buffer row pointers into the middle of the fake row array */
  163820. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  163821. 3 * rgroup_height * SIZEOF(JSAMPROW));
  163822. /* Fill in the above and below wraparound pointers */
  163823. for (i = 0; i < rgroup_height; i++) {
  163824. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  163825. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  163826. }
  163827. prep->color_buf[ci] = fake_buffer + rgroup_height;
  163828. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  163829. }
  163830. }
  163831. #endif /* CONTEXT_ROWS_SUPPORTED */
  163832. /*
  163833. * Initialize preprocessing controller.
  163834. */
  163835. GLOBAL(void)
  163836. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  163837. {
  163838. my_prep_ptr prep;
  163839. int ci;
  163840. jpeg_component_info * compptr;
  163841. if (need_full_buffer) /* safety check */
  163842. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163843. prep = (my_prep_ptr)
  163844. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163845. SIZEOF(my_prep_controller));
  163846. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  163847. prep->pub.start_pass = start_pass_prep;
  163848. /* Allocate the color conversion buffer.
  163849. * We make the buffer wide enough to allow the downsampler to edge-expand
  163850. * horizontally within the buffer, if it so chooses.
  163851. */
  163852. if (cinfo->downsample->need_context_rows) {
  163853. /* Set up to provide context rows */
  163854. #ifdef CONTEXT_ROWS_SUPPORTED
  163855. prep->pub.pre_process_data = pre_process_context;
  163856. create_context_buffer(cinfo);
  163857. #else
  163858. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163859. #endif
  163860. } else {
  163861. /* No context, just make it tall enough for one row group */
  163862. prep->pub.pre_process_data = pre_process_data;
  163863. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163864. ci++, compptr++) {
  163865. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  163866. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163867. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  163868. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  163869. (JDIMENSION) cinfo->max_v_samp_factor);
  163870. }
  163871. }
  163872. }
  163873. /*** End of inlined file: jcprepct.c ***/
  163874. /*** Start of inlined file: jcsample.c ***/
  163875. #define JPEG_INTERNALS
  163876. /* Pointer to routine to downsample a single component */
  163877. typedef JMETHOD(void, downsample1_ptr,
  163878. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163879. JSAMPARRAY input_data, JSAMPARRAY output_data));
  163880. /* Private subobject */
  163881. typedef struct {
  163882. struct jpeg_downsampler pub; /* public fields */
  163883. /* Downsampling method pointers, one per component */
  163884. downsample1_ptr methods[MAX_COMPONENTS];
  163885. } my_downsampler;
  163886. typedef my_downsampler * my_downsample_ptr;
  163887. /*
  163888. * Initialize for a downsampling pass.
  163889. */
  163890. METHODDEF(void)
  163891. start_pass_downsample (j_compress_ptr)
  163892. {
  163893. /* no work for now */
  163894. }
  163895. /*
  163896. * Expand a component horizontally from width input_cols to width output_cols,
  163897. * by duplicating the rightmost samples.
  163898. */
  163899. LOCAL(void)
  163900. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  163901. JDIMENSION input_cols, JDIMENSION output_cols)
  163902. {
  163903. register JSAMPROW ptr;
  163904. register JSAMPLE pixval;
  163905. register int count;
  163906. int row;
  163907. int numcols = (int) (output_cols - input_cols);
  163908. if (numcols > 0) {
  163909. for (row = 0; row < num_rows; row++) {
  163910. ptr = image_data[row] + input_cols;
  163911. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  163912. for (count = numcols; count > 0; count--)
  163913. *ptr++ = pixval;
  163914. }
  163915. }
  163916. }
  163917. /*
  163918. * Do downsampling for a whole row group (all components).
  163919. *
  163920. * In this version we simply downsample each component independently.
  163921. */
  163922. METHODDEF(void)
  163923. sep_downsample (j_compress_ptr cinfo,
  163924. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  163925. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  163926. {
  163927. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  163928. int ci;
  163929. jpeg_component_info * compptr;
  163930. JSAMPARRAY in_ptr, out_ptr;
  163931. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163932. ci++, compptr++) {
  163933. in_ptr = input_buf[ci] + in_row_index;
  163934. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  163935. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  163936. }
  163937. }
  163938. /*
  163939. * Downsample pixel values of a single component.
  163940. * One row group is processed per call.
  163941. * This version handles arbitrary integral sampling ratios, without smoothing.
  163942. * Note that this version is not actually used for customary sampling ratios.
  163943. */
  163944. METHODDEF(void)
  163945. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163946. JSAMPARRAY input_data, JSAMPARRAY output_data)
  163947. {
  163948. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  163949. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  163950. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  163951. JSAMPROW inptr, outptr;
  163952. INT32 outvalue;
  163953. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  163954. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  163955. numpix = h_expand * v_expand;
  163956. numpix2 = numpix/2;
  163957. /* Expand input data enough to let all the output samples be generated
  163958. * by the standard loop. Special-casing padded output would be more
  163959. * efficient.
  163960. */
  163961. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  163962. cinfo->image_width, output_cols * h_expand);
  163963. inrow = 0;
  163964. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  163965. outptr = output_data[outrow];
  163966. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  163967. outcol++, outcol_h += h_expand) {
  163968. outvalue = 0;
  163969. for (v = 0; v < v_expand; v++) {
  163970. inptr = input_data[inrow+v] + outcol_h;
  163971. for (h = 0; h < h_expand; h++) {
  163972. outvalue += (INT32) GETJSAMPLE(*inptr++);
  163973. }
  163974. }
  163975. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  163976. }
  163977. inrow += v_expand;
  163978. }
  163979. }
  163980. /*
  163981. * Downsample pixel values of a single component.
  163982. * This version handles the special case of a full-size component,
  163983. * without smoothing.
  163984. */
  163985. METHODDEF(void)
  163986. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163987. JSAMPARRAY input_data, JSAMPARRAY output_data)
  163988. {
  163989. /* Copy the data */
  163990. jcopy_sample_rows(input_data, 0, output_data, 0,
  163991. cinfo->max_v_samp_factor, cinfo->image_width);
  163992. /* Edge-expand */
  163993. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  163994. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  163995. }
  163996. /*
  163997. * Downsample pixel values of a single component.
  163998. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  163999. * without smoothing.
  164000. *
  164001. * A note about the "bias" calculations: when rounding fractional values to
  164002. * integer, we do not want to always round 0.5 up to the next integer.
  164003. * If we did that, we'd introduce a noticeable bias towards larger values.
  164004. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  164005. * alternate pixel locations (a simple ordered dither pattern).
  164006. */
  164007. METHODDEF(void)
  164008. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  164009. JSAMPARRAY input_data, JSAMPARRAY output_data)
  164010. {
  164011. int outrow;
  164012. JDIMENSION outcol;
  164013. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  164014. register JSAMPROW inptr, outptr;
  164015. register int bias;
  164016. /* Expand input data enough to let all the output samples be generated
  164017. * by the standard loop. Special-casing padded output would be more
  164018. * efficient.
  164019. */
  164020. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  164021. cinfo->image_width, output_cols * 2);
  164022. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  164023. outptr = output_data[outrow];
  164024. inptr = input_data[outrow];
  164025. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  164026. for (outcol = 0; outcol < output_cols; outcol++) {
  164027. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  164028. + bias) >> 1);
  164029. bias ^= 1; /* 0=>1, 1=>0 */
  164030. inptr += 2;
  164031. }
  164032. }
  164033. }
  164034. /*
  164035. * Downsample pixel values of a single component.
  164036. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  164037. * without smoothing.
  164038. */
  164039. METHODDEF(void)
  164040. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  164041. JSAMPARRAY input_data, JSAMPARRAY output_data)
  164042. {
  164043. int inrow, outrow;
  164044. JDIMENSION outcol;
  164045. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  164046. register JSAMPROW inptr0, inptr1, outptr;
  164047. register int bias;
  164048. /* Expand input data enough to let all the output samples be generated
  164049. * by the standard loop. Special-casing padded output would be more
  164050. * efficient.
  164051. */
  164052. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  164053. cinfo->image_width, output_cols * 2);
  164054. inrow = 0;
  164055. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  164056. outptr = output_data[outrow];
  164057. inptr0 = input_data[inrow];
  164058. inptr1 = input_data[inrow+1];
  164059. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  164060. for (outcol = 0; outcol < output_cols; outcol++) {
  164061. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  164062. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  164063. + bias) >> 2);
  164064. bias ^= 3; /* 1=>2, 2=>1 */
  164065. inptr0 += 2; inptr1 += 2;
  164066. }
  164067. inrow += 2;
  164068. }
  164069. }
  164070. #ifdef INPUT_SMOOTHING_SUPPORTED
  164071. /*
  164072. * Downsample pixel values of a single component.
  164073. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  164074. * with smoothing. One row of context is required.
  164075. */
  164076. METHODDEF(void)
  164077. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  164078. JSAMPARRAY input_data, JSAMPARRAY output_data)
  164079. {
  164080. int inrow, outrow;
  164081. JDIMENSION colctr;
  164082. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  164083. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  164084. INT32 membersum, neighsum, memberscale, neighscale;
  164085. /* Expand input data enough to let all the output samples be generated
  164086. * by the standard loop. Special-casing padded output would be more
  164087. * efficient.
  164088. */
  164089. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  164090. cinfo->image_width, output_cols * 2);
  164091. /* We don't bother to form the individual "smoothed" input pixel values;
  164092. * we can directly compute the output which is the average of the four
  164093. * smoothed values. Each of the four member pixels contributes a fraction
  164094. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  164095. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  164096. * output. The four corner-adjacent neighbor pixels contribute a fraction
  164097. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  164098. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  164099. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  164100. * factors are scaled by 2^16 = 65536.
  164101. * Also recall that SF = smoothing_factor / 1024.
  164102. */
  164103. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  164104. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  164105. inrow = 0;
  164106. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  164107. outptr = output_data[outrow];
  164108. inptr0 = input_data[inrow];
  164109. inptr1 = input_data[inrow+1];
  164110. above_ptr = input_data[inrow-1];
  164111. below_ptr = input_data[inrow+2];
  164112. /* Special case for first column: pretend column -1 is same as column 0 */
  164113. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  164114. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  164115. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  164116. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  164117. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  164118. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  164119. neighsum += neighsum;
  164120. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  164121. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  164122. membersum = membersum * memberscale + neighsum * neighscale;
  164123. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  164124. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  164125. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  164126. /* sum of pixels directly mapped to this output element */
  164127. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  164128. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  164129. /* sum of edge-neighbor pixels */
  164130. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  164131. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  164132. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  164133. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  164134. /* The edge-neighbors count twice as much as corner-neighbors */
  164135. neighsum += neighsum;
  164136. /* Add in the corner-neighbors */
  164137. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  164138. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  164139. /* form final output scaled up by 2^16 */
  164140. membersum = membersum * memberscale + neighsum * neighscale;
  164141. /* round, descale and output it */
  164142. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  164143. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  164144. }
  164145. /* Special case for last column */
  164146. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  164147. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  164148. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  164149. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  164150. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  164151. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  164152. neighsum += neighsum;
  164153. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  164154. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  164155. membersum = membersum * memberscale + neighsum * neighscale;
  164156. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  164157. inrow += 2;
  164158. }
  164159. }
  164160. /*
  164161. * Downsample pixel values of a single component.
  164162. * This version handles the special case of a full-size component,
  164163. * with smoothing. One row of context is required.
  164164. */
  164165. METHODDEF(void)
  164166. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  164167. JSAMPARRAY input_data, JSAMPARRAY output_data)
  164168. {
  164169. int outrow;
  164170. JDIMENSION colctr;
  164171. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  164172. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  164173. INT32 membersum, neighsum, memberscale, neighscale;
  164174. int colsum, lastcolsum, nextcolsum;
  164175. /* Expand input data enough to let all the output samples be generated
  164176. * by the standard loop. Special-casing padded output would be more
  164177. * efficient.
  164178. */
  164179. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  164180. cinfo->image_width, output_cols);
  164181. /* Each of the eight neighbor pixels contributes a fraction SF to the
  164182. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  164183. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  164184. * Also recall that SF = smoothing_factor / 1024.
  164185. */
  164186. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  164187. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  164188. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  164189. outptr = output_data[outrow];
  164190. inptr = input_data[outrow];
  164191. above_ptr = input_data[outrow-1];
  164192. below_ptr = input_data[outrow+1];
  164193. /* Special case for first column */
  164194. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  164195. GETJSAMPLE(*inptr);
  164196. membersum = GETJSAMPLE(*inptr++);
  164197. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  164198. GETJSAMPLE(*inptr);
  164199. neighsum = colsum + (colsum - membersum) + nextcolsum;
  164200. membersum = membersum * memberscale + neighsum * neighscale;
  164201. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  164202. lastcolsum = colsum; colsum = nextcolsum;
  164203. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  164204. membersum = GETJSAMPLE(*inptr++);
  164205. above_ptr++; below_ptr++;
  164206. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  164207. GETJSAMPLE(*inptr);
  164208. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  164209. membersum = membersum * memberscale + neighsum * neighscale;
  164210. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  164211. lastcolsum = colsum; colsum = nextcolsum;
  164212. }
  164213. /* Special case for last column */
  164214. membersum = GETJSAMPLE(*inptr);
  164215. neighsum = lastcolsum + (colsum - membersum) + colsum;
  164216. membersum = membersum * memberscale + neighsum * neighscale;
  164217. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  164218. }
  164219. }
  164220. #endif /* INPUT_SMOOTHING_SUPPORTED */
  164221. /*
  164222. * Module initialization routine for downsampling.
  164223. * Note that we must select a routine for each component.
  164224. */
  164225. GLOBAL(void)
  164226. jinit_downsampler (j_compress_ptr cinfo)
  164227. {
  164228. my_downsample_ptr downsample;
  164229. int ci;
  164230. jpeg_component_info * compptr;
  164231. boolean smoothok = TRUE;
  164232. downsample = (my_downsample_ptr)
  164233. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164234. SIZEOF(my_downsampler));
  164235. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  164236. downsample->pub.start_pass = start_pass_downsample;
  164237. downsample->pub.downsample = sep_downsample;
  164238. downsample->pub.need_context_rows = FALSE;
  164239. if (cinfo->CCIR601_sampling)
  164240. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  164241. /* Verify we can handle the sampling factors, and set up method pointers */
  164242. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164243. ci++, compptr++) {
  164244. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  164245. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  164246. #ifdef INPUT_SMOOTHING_SUPPORTED
  164247. if (cinfo->smoothing_factor) {
  164248. downsample->methods[ci] = fullsize_smooth_downsample;
  164249. downsample->pub.need_context_rows = TRUE;
  164250. } else
  164251. #endif
  164252. downsample->methods[ci] = fullsize_downsample;
  164253. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  164254. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  164255. smoothok = FALSE;
  164256. downsample->methods[ci] = h2v1_downsample;
  164257. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  164258. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  164259. #ifdef INPUT_SMOOTHING_SUPPORTED
  164260. if (cinfo->smoothing_factor) {
  164261. downsample->methods[ci] = h2v2_smooth_downsample;
  164262. downsample->pub.need_context_rows = TRUE;
  164263. } else
  164264. #endif
  164265. downsample->methods[ci] = h2v2_downsample;
  164266. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  164267. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  164268. smoothok = FALSE;
  164269. downsample->methods[ci] = int_downsample;
  164270. } else
  164271. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  164272. }
  164273. #ifdef INPUT_SMOOTHING_SUPPORTED
  164274. if (cinfo->smoothing_factor && !smoothok)
  164275. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  164276. #endif
  164277. }
  164278. /*** End of inlined file: jcsample.c ***/
  164279. /*** Start of inlined file: jctrans.c ***/
  164280. #define JPEG_INTERNALS
  164281. /* Forward declarations */
  164282. LOCAL(void) transencode_master_selection
  164283. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  164284. LOCAL(void) transencode_coef_controller
  164285. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  164286. /*
  164287. * Compression initialization for writing raw-coefficient data.
  164288. * Before calling this, all parameters and a data destination must be set up.
  164289. * Call jpeg_finish_compress() to actually write the data.
  164290. *
  164291. * The number of passed virtual arrays must match cinfo->num_components.
  164292. * Note that the virtual arrays need not be filled or even realized at
  164293. * the time write_coefficients is called; indeed, if the virtual arrays
  164294. * were requested from this compression object's memory manager, they
  164295. * typically will be realized during this routine and filled afterwards.
  164296. */
  164297. GLOBAL(void)
  164298. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  164299. {
  164300. if (cinfo->global_state != CSTATE_START)
  164301. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164302. /* Mark all tables to be written */
  164303. jpeg_suppress_tables(cinfo, FALSE);
  164304. /* (Re)initialize error mgr and destination modules */
  164305. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  164306. (*cinfo->dest->init_destination) (cinfo);
  164307. /* Perform master selection of active modules */
  164308. transencode_master_selection(cinfo, coef_arrays);
  164309. /* Wait for jpeg_finish_compress() call */
  164310. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  164311. cinfo->global_state = CSTATE_WRCOEFS;
  164312. }
  164313. /*
  164314. * Initialize the compression object with default parameters,
  164315. * then copy from the source object all parameters needed for lossless
  164316. * transcoding. Parameters that can be varied without loss (such as
  164317. * scan script and Huffman optimization) are left in their default states.
  164318. */
  164319. GLOBAL(void)
  164320. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  164321. j_compress_ptr dstinfo)
  164322. {
  164323. JQUANT_TBL ** qtblptr;
  164324. jpeg_component_info *incomp, *outcomp;
  164325. JQUANT_TBL *c_quant, *slot_quant;
  164326. int tblno, ci, coefi;
  164327. /* Safety check to ensure start_compress not called yet. */
  164328. if (dstinfo->global_state != CSTATE_START)
  164329. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  164330. /* Copy fundamental image dimensions */
  164331. dstinfo->image_width = srcinfo->image_width;
  164332. dstinfo->image_height = srcinfo->image_height;
  164333. dstinfo->input_components = srcinfo->num_components;
  164334. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  164335. /* Initialize all parameters to default values */
  164336. jpeg_set_defaults(dstinfo);
  164337. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  164338. * Fix it to get the right header markers for the image colorspace.
  164339. */
  164340. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  164341. dstinfo->data_precision = srcinfo->data_precision;
  164342. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  164343. /* Copy the source's quantization tables. */
  164344. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  164345. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  164346. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  164347. if (*qtblptr == NULL)
  164348. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  164349. MEMCOPY((*qtblptr)->quantval,
  164350. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  164351. SIZEOF((*qtblptr)->quantval));
  164352. (*qtblptr)->sent_table = FALSE;
  164353. }
  164354. }
  164355. /* Copy the source's per-component info.
  164356. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  164357. */
  164358. dstinfo->num_components = srcinfo->num_components;
  164359. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  164360. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  164361. MAX_COMPONENTS);
  164362. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  164363. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  164364. outcomp->component_id = incomp->component_id;
  164365. outcomp->h_samp_factor = incomp->h_samp_factor;
  164366. outcomp->v_samp_factor = incomp->v_samp_factor;
  164367. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  164368. /* Make sure saved quantization table for component matches the qtable
  164369. * slot. If not, the input file re-used this qtable slot.
  164370. * IJG encoder currently cannot duplicate this.
  164371. */
  164372. tblno = outcomp->quant_tbl_no;
  164373. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  164374. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  164375. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  164376. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  164377. c_quant = incomp->quant_table;
  164378. if (c_quant != NULL) {
  164379. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  164380. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  164381. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  164382. }
  164383. }
  164384. /* Note: we do not copy the source's Huffman table assignments;
  164385. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  164386. */
  164387. }
  164388. /* Also copy JFIF version and resolution information, if available.
  164389. * Strictly speaking this isn't "critical" info, but it's nearly
  164390. * always appropriate to copy it if available. In particular,
  164391. * if the application chooses to copy JFIF 1.02 extension markers from
  164392. * the source file, we need to copy the version to make sure we don't
  164393. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  164394. * We will *not*, however, copy version info from mislabeled "2.01" files.
  164395. */
  164396. if (srcinfo->saw_JFIF_marker) {
  164397. if (srcinfo->JFIF_major_version == 1) {
  164398. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  164399. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  164400. }
  164401. dstinfo->density_unit = srcinfo->density_unit;
  164402. dstinfo->X_density = srcinfo->X_density;
  164403. dstinfo->Y_density = srcinfo->Y_density;
  164404. }
  164405. }
  164406. /*
  164407. * Master selection of compression modules for transcoding.
  164408. * This substitutes for jcinit.c's initialization of the full compressor.
  164409. */
  164410. LOCAL(void)
  164411. transencode_master_selection (j_compress_ptr cinfo,
  164412. jvirt_barray_ptr * coef_arrays)
  164413. {
  164414. /* Although we don't actually use input_components for transcoding,
  164415. * jcmaster.c's initial_setup will complain if input_components is 0.
  164416. */
  164417. cinfo->input_components = 1;
  164418. /* Initialize master control (includes parameter checking/processing) */
  164419. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  164420. /* Entropy encoding: either Huffman or arithmetic coding. */
  164421. if (cinfo->arith_code) {
  164422. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  164423. } else {
  164424. if (cinfo->progressive_mode) {
  164425. #ifdef C_PROGRESSIVE_SUPPORTED
  164426. jinit_phuff_encoder(cinfo);
  164427. #else
  164428. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164429. #endif
  164430. } else
  164431. jinit_huff_encoder(cinfo);
  164432. }
  164433. /* We need a special coefficient buffer controller. */
  164434. transencode_coef_controller(cinfo, coef_arrays);
  164435. jinit_marker_writer(cinfo);
  164436. /* We can now tell the memory manager to allocate virtual arrays. */
  164437. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  164438. /* Write the datastream header (SOI, JFIF) immediately.
  164439. * Frame and scan headers are postponed till later.
  164440. * This lets application insert special markers after the SOI.
  164441. */
  164442. (*cinfo->marker->write_file_header) (cinfo);
  164443. }
  164444. /*
  164445. * The rest of this file is a special implementation of the coefficient
  164446. * buffer controller. This is similar to jccoefct.c, but it handles only
  164447. * output from presupplied virtual arrays. Furthermore, we generate any
  164448. * dummy padding blocks on-the-fly rather than expecting them to be present
  164449. * in the arrays.
  164450. */
  164451. /* Private buffer controller object */
  164452. typedef struct {
  164453. struct jpeg_c_coef_controller pub; /* public fields */
  164454. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  164455. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  164456. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  164457. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  164458. /* Virtual block array for each component. */
  164459. jvirt_barray_ptr * whole_image;
  164460. /* Workspace for constructing dummy blocks at right/bottom edges. */
  164461. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  164462. } my_coef_controller2;
  164463. typedef my_coef_controller2 * my_coef_ptr2;
  164464. LOCAL(void)
  164465. start_iMCU_row2 (j_compress_ptr cinfo)
  164466. /* Reset within-iMCU-row counters for a new row */
  164467. {
  164468. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  164469. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  164470. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  164471. * But at the bottom of the image, process only what's left.
  164472. */
  164473. if (cinfo->comps_in_scan > 1) {
  164474. coef->MCU_rows_per_iMCU_row = 1;
  164475. } else {
  164476. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  164477. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  164478. else
  164479. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  164480. }
  164481. coef->mcu_ctr = 0;
  164482. coef->MCU_vert_offset = 0;
  164483. }
  164484. /*
  164485. * Initialize for a processing pass.
  164486. */
  164487. METHODDEF(void)
  164488. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  164489. {
  164490. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  164491. if (pass_mode != JBUF_CRANK_DEST)
  164492. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164493. coef->iMCU_row_num = 0;
  164494. start_iMCU_row2(cinfo);
  164495. }
  164496. /*
  164497. * Process some data.
  164498. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  164499. * per call, ie, v_samp_factor block rows for each component in the scan.
  164500. * The data is obtained from the virtual arrays and fed to the entropy coder.
  164501. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  164502. *
  164503. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  164504. */
  164505. METHODDEF(boolean)
  164506. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  164507. {
  164508. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  164509. JDIMENSION MCU_col_num; /* index of current MCU within row */
  164510. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  164511. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  164512. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  164513. JDIMENSION start_col;
  164514. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  164515. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  164516. JBLOCKROW buffer_ptr;
  164517. jpeg_component_info *compptr;
  164518. /* Align the virtual buffers for the components used in this scan. */
  164519. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164520. compptr = cinfo->cur_comp_info[ci];
  164521. buffer[ci] = (*cinfo->mem->access_virt_barray)
  164522. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  164523. coef->iMCU_row_num * compptr->v_samp_factor,
  164524. (JDIMENSION) compptr->v_samp_factor, FALSE);
  164525. }
  164526. /* Loop to process one whole iMCU row */
  164527. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  164528. yoffset++) {
  164529. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  164530. MCU_col_num++) {
  164531. /* Construct list of pointers to DCT blocks belonging to this MCU */
  164532. blkn = 0; /* index of current DCT block within MCU */
  164533. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164534. compptr = cinfo->cur_comp_info[ci];
  164535. start_col = MCU_col_num * compptr->MCU_width;
  164536. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  164537. : compptr->last_col_width;
  164538. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  164539. if (coef->iMCU_row_num < last_iMCU_row ||
  164540. yindex+yoffset < compptr->last_row_height) {
  164541. /* Fill in pointers to real blocks in this row */
  164542. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  164543. for (xindex = 0; xindex < blockcnt; xindex++)
  164544. MCU_buffer[blkn++] = buffer_ptr++;
  164545. } else {
  164546. /* At bottom of image, need a whole row of dummy blocks */
  164547. xindex = 0;
  164548. }
  164549. /* Fill in any dummy blocks needed in this row.
  164550. * Dummy blocks are filled in the same way as in jccoefct.c:
  164551. * all zeroes in the AC entries, DC entries equal to previous
  164552. * block's DC value. The init routine has already zeroed the
  164553. * AC entries, so we need only set the DC entries correctly.
  164554. */
  164555. for (; xindex < compptr->MCU_width; xindex++) {
  164556. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  164557. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  164558. blkn++;
  164559. }
  164560. }
  164561. }
  164562. /* Try to write the MCU. */
  164563. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  164564. /* Suspension forced; update state counters and exit */
  164565. coef->MCU_vert_offset = yoffset;
  164566. coef->mcu_ctr = MCU_col_num;
  164567. return FALSE;
  164568. }
  164569. }
  164570. /* Completed an MCU row, but perhaps not an iMCU row */
  164571. coef->mcu_ctr = 0;
  164572. }
  164573. /* Completed the iMCU row, advance counters for next one */
  164574. coef->iMCU_row_num++;
  164575. start_iMCU_row2(cinfo);
  164576. return TRUE;
  164577. }
  164578. /*
  164579. * Initialize coefficient buffer controller.
  164580. *
  164581. * Each passed coefficient array must be the right size for that
  164582. * coefficient: width_in_blocks wide and height_in_blocks high,
  164583. * with unitheight at least v_samp_factor.
  164584. */
  164585. LOCAL(void)
  164586. transencode_coef_controller (j_compress_ptr cinfo,
  164587. jvirt_barray_ptr * coef_arrays)
  164588. {
  164589. my_coef_ptr2 coef;
  164590. JBLOCKROW buffer;
  164591. int i;
  164592. coef = (my_coef_ptr2)
  164593. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164594. SIZEOF(my_coef_controller2));
  164595. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  164596. coef->pub.start_pass = start_pass_coef2;
  164597. coef->pub.compress_data = compress_output2;
  164598. /* Save pointer to virtual arrays */
  164599. coef->whole_image = coef_arrays;
  164600. /* Allocate and pre-zero space for dummy DCT blocks. */
  164601. buffer = (JBLOCKROW)
  164602. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164603. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  164604. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  164605. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  164606. coef->dummy_buffer[i] = buffer + i;
  164607. }
  164608. }
  164609. /*** End of inlined file: jctrans.c ***/
  164610. /*** Start of inlined file: jdapistd.c ***/
  164611. #define JPEG_INTERNALS
  164612. /* Forward declarations */
  164613. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  164614. /*
  164615. * Decompression initialization.
  164616. * jpeg_read_header must be completed before calling this.
  164617. *
  164618. * If a multipass operating mode was selected, this will do all but the
  164619. * last pass, and thus may take a great deal of time.
  164620. *
  164621. * Returns FALSE if suspended. The return value need be inspected only if
  164622. * a suspending data source is used.
  164623. */
  164624. GLOBAL(boolean)
  164625. jpeg_start_decompress (j_decompress_ptr cinfo)
  164626. {
  164627. if (cinfo->global_state == DSTATE_READY) {
  164628. /* First call: initialize master control, select active modules */
  164629. jinit_master_decompress(cinfo);
  164630. if (cinfo->buffered_image) {
  164631. /* No more work here; expecting jpeg_start_output next */
  164632. cinfo->global_state = DSTATE_BUFIMAGE;
  164633. return TRUE;
  164634. }
  164635. cinfo->global_state = DSTATE_PRELOAD;
  164636. }
  164637. if (cinfo->global_state == DSTATE_PRELOAD) {
  164638. /* If file has multiple scans, absorb them all into the coef buffer */
  164639. if (cinfo->inputctl->has_multiple_scans) {
  164640. #ifdef D_MULTISCAN_FILES_SUPPORTED
  164641. for (;;) {
  164642. int retcode;
  164643. /* Call progress monitor hook if present */
  164644. if (cinfo->progress != NULL)
  164645. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  164646. /* Absorb some more input */
  164647. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  164648. if (retcode == JPEG_SUSPENDED)
  164649. return FALSE;
  164650. if (retcode == JPEG_REACHED_EOI)
  164651. break;
  164652. /* Advance progress counter if appropriate */
  164653. if (cinfo->progress != NULL &&
  164654. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  164655. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  164656. /* jdmaster underestimated number of scans; ratchet up one scan */
  164657. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  164658. }
  164659. }
  164660. }
  164661. #else
  164662. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164663. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  164664. }
  164665. cinfo->output_scan_number = cinfo->input_scan_number;
  164666. } else if (cinfo->global_state != DSTATE_PRESCAN)
  164667. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164668. /* Perform any dummy output passes, and set up for the final pass */
  164669. return output_pass_setup(cinfo);
  164670. }
  164671. /*
  164672. * Set up for an output pass, and perform any dummy pass(es) needed.
  164673. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  164674. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  164675. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  164676. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  164677. */
  164678. LOCAL(boolean)
  164679. output_pass_setup (j_decompress_ptr cinfo)
  164680. {
  164681. if (cinfo->global_state != DSTATE_PRESCAN) {
  164682. /* First call: do pass setup */
  164683. (*cinfo->master->prepare_for_output_pass) (cinfo);
  164684. cinfo->output_scanline = 0;
  164685. cinfo->global_state = DSTATE_PRESCAN;
  164686. }
  164687. /* Loop over any required dummy passes */
  164688. while (cinfo->master->is_dummy_pass) {
  164689. #ifdef QUANT_2PASS_SUPPORTED
  164690. /* Crank through the dummy pass */
  164691. while (cinfo->output_scanline < cinfo->output_height) {
  164692. JDIMENSION last_scanline;
  164693. /* Call progress monitor hook if present */
  164694. if (cinfo->progress != NULL) {
  164695. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  164696. cinfo->progress->pass_limit = (long) cinfo->output_height;
  164697. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  164698. }
  164699. /* Process some data */
  164700. last_scanline = cinfo->output_scanline;
  164701. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  164702. &cinfo->output_scanline, (JDIMENSION) 0);
  164703. if (cinfo->output_scanline == last_scanline)
  164704. return FALSE; /* No progress made, must suspend */
  164705. }
  164706. /* Finish up dummy pass, and set up for another one */
  164707. (*cinfo->master->finish_output_pass) (cinfo);
  164708. (*cinfo->master->prepare_for_output_pass) (cinfo);
  164709. cinfo->output_scanline = 0;
  164710. #else
  164711. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164712. #endif /* QUANT_2PASS_SUPPORTED */
  164713. }
  164714. /* Ready for application to drive output pass through
  164715. * jpeg_read_scanlines or jpeg_read_raw_data.
  164716. */
  164717. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  164718. return TRUE;
  164719. }
  164720. /*
  164721. * Read some scanlines of data from the JPEG decompressor.
  164722. *
  164723. * The return value will be the number of lines actually read.
  164724. * This may be less than the number requested in several cases,
  164725. * including bottom of image, data source suspension, and operating
  164726. * modes that emit multiple scanlines at a time.
  164727. *
  164728. * Note: we warn about excess calls to jpeg_read_scanlines() since
  164729. * this likely signals an application programmer error. However,
  164730. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  164731. */
  164732. GLOBAL(JDIMENSION)
  164733. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  164734. JDIMENSION max_lines)
  164735. {
  164736. JDIMENSION row_ctr;
  164737. if (cinfo->global_state != DSTATE_SCANNING)
  164738. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164739. if (cinfo->output_scanline >= cinfo->output_height) {
  164740. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  164741. return 0;
  164742. }
  164743. /* Call progress monitor hook if present */
  164744. if (cinfo->progress != NULL) {
  164745. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  164746. cinfo->progress->pass_limit = (long) cinfo->output_height;
  164747. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  164748. }
  164749. /* Process some data */
  164750. row_ctr = 0;
  164751. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  164752. cinfo->output_scanline += row_ctr;
  164753. return row_ctr;
  164754. }
  164755. /*
  164756. * Alternate entry point to read raw data.
  164757. * Processes exactly one iMCU row per call, unless suspended.
  164758. */
  164759. GLOBAL(JDIMENSION)
  164760. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  164761. JDIMENSION max_lines)
  164762. {
  164763. JDIMENSION lines_per_iMCU_row;
  164764. if (cinfo->global_state != DSTATE_RAW_OK)
  164765. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164766. if (cinfo->output_scanline >= cinfo->output_height) {
  164767. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  164768. return 0;
  164769. }
  164770. /* Call progress monitor hook if present */
  164771. if (cinfo->progress != NULL) {
  164772. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  164773. cinfo->progress->pass_limit = (long) cinfo->output_height;
  164774. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  164775. }
  164776. /* Verify that at least one iMCU row can be returned. */
  164777. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  164778. if (max_lines < lines_per_iMCU_row)
  164779. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  164780. /* Decompress directly into user's buffer. */
  164781. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  164782. return 0; /* suspension forced, can do nothing more */
  164783. /* OK, we processed one iMCU row. */
  164784. cinfo->output_scanline += lines_per_iMCU_row;
  164785. return lines_per_iMCU_row;
  164786. }
  164787. /* Additional entry points for buffered-image mode. */
  164788. #ifdef D_MULTISCAN_FILES_SUPPORTED
  164789. /*
  164790. * Initialize for an output pass in buffered-image mode.
  164791. */
  164792. GLOBAL(boolean)
  164793. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  164794. {
  164795. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  164796. cinfo->global_state != DSTATE_PRESCAN)
  164797. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164798. /* Limit scan number to valid range */
  164799. if (scan_number <= 0)
  164800. scan_number = 1;
  164801. if (cinfo->inputctl->eoi_reached &&
  164802. scan_number > cinfo->input_scan_number)
  164803. scan_number = cinfo->input_scan_number;
  164804. cinfo->output_scan_number = scan_number;
  164805. /* Perform any dummy output passes, and set up for the real pass */
  164806. return output_pass_setup(cinfo);
  164807. }
  164808. /*
  164809. * Finish up after an output pass in buffered-image mode.
  164810. *
  164811. * Returns FALSE if suspended. The return value need be inspected only if
  164812. * a suspending data source is used.
  164813. */
  164814. GLOBAL(boolean)
  164815. jpeg_finish_output (j_decompress_ptr cinfo)
  164816. {
  164817. if ((cinfo->global_state == DSTATE_SCANNING ||
  164818. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  164819. /* Terminate this pass. */
  164820. /* We do not require the whole pass to have been completed. */
  164821. (*cinfo->master->finish_output_pass) (cinfo);
  164822. cinfo->global_state = DSTATE_BUFPOST;
  164823. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  164824. /* BUFPOST = repeat call after a suspension, anything else is error */
  164825. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164826. }
  164827. /* Read markers looking for SOS or EOI */
  164828. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  164829. ! cinfo->inputctl->eoi_reached) {
  164830. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  164831. return FALSE; /* Suspend, come back later */
  164832. }
  164833. cinfo->global_state = DSTATE_BUFIMAGE;
  164834. return TRUE;
  164835. }
  164836. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  164837. /*** End of inlined file: jdapistd.c ***/
  164838. /*** Start of inlined file: jdapimin.c ***/
  164839. #define JPEG_INTERNALS
  164840. /*
  164841. * Initialization of a JPEG decompression object.
  164842. * The error manager must already be set up (in case memory manager fails).
  164843. */
  164844. GLOBAL(void)
  164845. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  164846. {
  164847. int i;
  164848. /* Guard against version mismatches between library and caller. */
  164849. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  164850. if (version != JPEG_LIB_VERSION)
  164851. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  164852. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  164853. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  164854. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  164855. /* For debugging purposes, we zero the whole master structure.
  164856. * But the application has already set the err pointer, and may have set
  164857. * client_data, so we have to save and restore those fields.
  164858. * Note: if application hasn't set client_data, tools like Purify may
  164859. * complain here.
  164860. */
  164861. {
  164862. struct jpeg_error_mgr * err = cinfo->err;
  164863. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  164864. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  164865. cinfo->err = err;
  164866. cinfo->client_data = client_data;
  164867. }
  164868. cinfo->is_decompressor = TRUE;
  164869. /* Initialize a memory manager instance for this object */
  164870. jinit_memory_mgr((j_common_ptr) cinfo);
  164871. /* Zero out pointers to permanent structures. */
  164872. cinfo->progress = NULL;
  164873. cinfo->src = NULL;
  164874. for (i = 0; i < NUM_QUANT_TBLS; i++)
  164875. cinfo->quant_tbl_ptrs[i] = NULL;
  164876. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164877. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  164878. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  164879. }
  164880. /* Initialize marker processor so application can override methods
  164881. * for COM, APPn markers before calling jpeg_read_header.
  164882. */
  164883. cinfo->marker_list = NULL;
  164884. jinit_marker_reader(cinfo);
  164885. /* And initialize the overall input controller. */
  164886. jinit_input_controller(cinfo);
  164887. /* OK, I'm ready */
  164888. cinfo->global_state = DSTATE_START;
  164889. }
  164890. /*
  164891. * Destruction of a JPEG decompression object
  164892. */
  164893. GLOBAL(void)
  164894. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  164895. {
  164896. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  164897. }
  164898. /*
  164899. * Abort processing of a JPEG decompression operation,
  164900. * but don't destroy the object itself.
  164901. */
  164902. GLOBAL(void)
  164903. jpeg_abort_decompress (j_decompress_ptr cinfo)
  164904. {
  164905. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  164906. }
  164907. /*
  164908. * Set default decompression parameters.
  164909. */
  164910. LOCAL(void)
  164911. default_decompress_parms (j_decompress_ptr cinfo)
  164912. {
  164913. /* Guess the input colorspace, and set output colorspace accordingly. */
  164914. /* (Wish JPEG committee had provided a real way to specify this...) */
  164915. /* Note application may override our guesses. */
  164916. switch (cinfo->num_components) {
  164917. case 1:
  164918. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  164919. cinfo->out_color_space = JCS_GRAYSCALE;
  164920. break;
  164921. case 3:
  164922. if (cinfo->saw_JFIF_marker) {
  164923. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  164924. } else if (cinfo->saw_Adobe_marker) {
  164925. switch (cinfo->Adobe_transform) {
  164926. case 0:
  164927. cinfo->jpeg_color_space = JCS_RGB;
  164928. break;
  164929. case 1:
  164930. cinfo->jpeg_color_space = JCS_YCbCr;
  164931. break;
  164932. default:
  164933. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  164934. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  164935. break;
  164936. }
  164937. } else {
  164938. /* Saw no special markers, try to guess from the component IDs */
  164939. int cid0 = cinfo->comp_info[0].component_id;
  164940. int cid1 = cinfo->comp_info[1].component_id;
  164941. int cid2 = cinfo->comp_info[2].component_id;
  164942. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  164943. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  164944. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  164945. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  164946. else {
  164947. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  164948. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  164949. }
  164950. }
  164951. /* Always guess RGB is proper output colorspace. */
  164952. cinfo->out_color_space = JCS_RGB;
  164953. break;
  164954. case 4:
  164955. if (cinfo->saw_Adobe_marker) {
  164956. switch (cinfo->Adobe_transform) {
  164957. case 0:
  164958. cinfo->jpeg_color_space = JCS_CMYK;
  164959. break;
  164960. case 2:
  164961. cinfo->jpeg_color_space = JCS_YCCK;
  164962. break;
  164963. default:
  164964. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  164965. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  164966. break;
  164967. }
  164968. } else {
  164969. /* No special markers, assume straight CMYK. */
  164970. cinfo->jpeg_color_space = JCS_CMYK;
  164971. }
  164972. cinfo->out_color_space = JCS_CMYK;
  164973. break;
  164974. default:
  164975. cinfo->jpeg_color_space = JCS_UNKNOWN;
  164976. cinfo->out_color_space = JCS_UNKNOWN;
  164977. break;
  164978. }
  164979. /* Set defaults for other decompression parameters. */
  164980. cinfo->scale_num = 1; /* 1:1 scaling */
  164981. cinfo->scale_denom = 1;
  164982. cinfo->output_gamma = 1.0;
  164983. cinfo->buffered_image = FALSE;
  164984. cinfo->raw_data_out = FALSE;
  164985. cinfo->dct_method = JDCT_DEFAULT;
  164986. cinfo->do_fancy_upsampling = TRUE;
  164987. cinfo->do_block_smoothing = TRUE;
  164988. cinfo->quantize_colors = FALSE;
  164989. /* We set these in case application only sets quantize_colors. */
  164990. cinfo->dither_mode = JDITHER_FS;
  164991. #ifdef QUANT_2PASS_SUPPORTED
  164992. cinfo->two_pass_quantize = TRUE;
  164993. #else
  164994. cinfo->two_pass_quantize = FALSE;
  164995. #endif
  164996. cinfo->desired_number_of_colors = 256;
  164997. cinfo->colormap = NULL;
  164998. /* Initialize for no mode change in buffered-image mode. */
  164999. cinfo->enable_1pass_quant = FALSE;
  165000. cinfo->enable_external_quant = FALSE;
  165001. cinfo->enable_2pass_quant = FALSE;
  165002. }
  165003. /*
  165004. * Decompression startup: read start of JPEG datastream to see what's there.
  165005. * Need only initialize JPEG object and supply a data source before calling.
  165006. *
  165007. * This routine will read as far as the first SOS marker (ie, actual start of
  165008. * compressed data), and will save all tables and parameters in the JPEG
  165009. * object. It will also initialize the decompression parameters to default
  165010. * values, and finally return JPEG_HEADER_OK. On return, the application may
  165011. * adjust the decompression parameters and then call jpeg_start_decompress.
  165012. * (Or, if the application only wanted to determine the image parameters,
  165013. * the data need not be decompressed. In that case, call jpeg_abort or
  165014. * jpeg_destroy to release any temporary space.)
  165015. * If an abbreviated (tables only) datastream is presented, the routine will
  165016. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  165017. * re-use the JPEG object to read the abbreviated image datastream(s).
  165018. * It is unnecessary (but OK) to call jpeg_abort in this case.
  165019. * The JPEG_SUSPENDED return code only occurs if the data source module
  165020. * requests suspension of the decompressor. In this case the application
  165021. * should load more source data and then re-call jpeg_read_header to resume
  165022. * processing.
  165023. * If a non-suspending data source is used and require_image is TRUE, then the
  165024. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  165025. *
  165026. * This routine is now just a front end to jpeg_consume_input, with some
  165027. * extra error checking.
  165028. */
  165029. GLOBAL(int)
  165030. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  165031. {
  165032. int retcode;
  165033. if (cinfo->global_state != DSTATE_START &&
  165034. cinfo->global_state != DSTATE_INHEADER)
  165035. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165036. retcode = jpeg_consume_input(cinfo);
  165037. switch (retcode) {
  165038. case JPEG_REACHED_SOS:
  165039. retcode = JPEG_HEADER_OK;
  165040. break;
  165041. case JPEG_REACHED_EOI:
  165042. if (require_image) /* Complain if application wanted an image */
  165043. ERREXIT(cinfo, JERR_NO_IMAGE);
  165044. /* Reset to start state; it would be safer to require the application to
  165045. * call jpeg_abort, but we can't change it now for compatibility reasons.
  165046. * A side effect is to free any temporary memory (there shouldn't be any).
  165047. */
  165048. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  165049. retcode = JPEG_HEADER_TABLES_ONLY;
  165050. break;
  165051. case JPEG_SUSPENDED:
  165052. /* no work */
  165053. break;
  165054. }
  165055. return retcode;
  165056. }
  165057. /*
  165058. * Consume data in advance of what the decompressor requires.
  165059. * This can be called at any time once the decompressor object has
  165060. * been created and a data source has been set up.
  165061. *
  165062. * This routine is essentially a state machine that handles a couple
  165063. * of critical state-transition actions, namely initial setup and
  165064. * transition from header scanning to ready-for-start_decompress.
  165065. * All the actual input is done via the input controller's consume_input
  165066. * method.
  165067. */
  165068. GLOBAL(int)
  165069. jpeg_consume_input (j_decompress_ptr cinfo)
  165070. {
  165071. int retcode = JPEG_SUSPENDED;
  165072. /* NB: every possible DSTATE value should be listed in this switch */
  165073. switch (cinfo->global_state) {
  165074. case DSTATE_START:
  165075. /* Start-of-datastream actions: reset appropriate modules */
  165076. (*cinfo->inputctl->reset_input_controller) (cinfo);
  165077. /* Initialize application's data source module */
  165078. (*cinfo->src->init_source) (cinfo);
  165079. cinfo->global_state = DSTATE_INHEADER;
  165080. /*FALLTHROUGH*/
  165081. case DSTATE_INHEADER:
  165082. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  165083. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  165084. /* Set up default parameters based on header data */
  165085. default_decompress_parms(cinfo);
  165086. /* Set global state: ready for start_decompress */
  165087. cinfo->global_state = DSTATE_READY;
  165088. }
  165089. break;
  165090. case DSTATE_READY:
  165091. /* Can't advance past first SOS until start_decompress is called */
  165092. retcode = JPEG_REACHED_SOS;
  165093. break;
  165094. case DSTATE_PRELOAD:
  165095. case DSTATE_PRESCAN:
  165096. case DSTATE_SCANNING:
  165097. case DSTATE_RAW_OK:
  165098. case DSTATE_BUFIMAGE:
  165099. case DSTATE_BUFPOST:
  165100. case DSTATE_STOPPING:
  165101. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  165102. break;
  165103. default:
  165104. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165105. }
  165106. return retcode;
  165107. }
  165108. /*
  165109. * Have we finished reading the input file?
  165110. */
  165111. GLOBAL(boolean)
  165112. jpeg_input_complete (j_decompress_ptr cinfo)
  165113. {
  165114. /* Check for valid jpeg object */
  165115. if (cinfo->global_state < DSTATE_START ||
  165116. cinfo->global_state > DSTATE_STOPPING)
  165117. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165118. return cinfo->inputctl->eoi_reached;
  165119. }
  165120. /*
  165121. * Is there more than one scan?
  165122. */
  165123. GLOBAL(boolean)
  165124. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  165125. {
  165126. /* Only valid after jpeg_read_header completes */
  165127. if (cinfo->global_state < DSTATE_READY ||
  165128. cinfo->global_state > DSTATE_STOPPING)
  165129. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165130. return cinfo->inputctl->has_multiple_scans;
  165131. }
  165132. /*
  165133. * Finish JPEG decompression.
  165134. *
  165135. * This will normally just verify the file trailer and release temp storage.
  165136. *
  165137. * Returns FALSE if suspended. The return value need be inspected only if
  165138. * a suspending data source is used.
  165139. */
  165140. GLOBAL(boolean)
  165141. jpeg_finish_decompress (j_decompress_ptr cinfo)
  165142. {
  165143. if ((cinfo->global_state == DSTATE_SCANNING ||
  165144. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  165145. /* Terminate final pass of non-buffered mode */
  165146. if (cinfo->output_scanline < cinfo->output_height)
  165147. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  165148. (*cinfo->master->finish_output_pass) (cinfo);
  165149. cinfo->global_state = DSTATE_STOPPING;
  165150. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  165151. /* Finishing after a buffered-image operation */
  165152. cinfo->global_state = DSTATE_STOPPING;
  165153. } else if (cinfo->global_state != DSTATE_STOPPING) {
  165154. /* STOPPING = repeat call after a suspension, anything else is error */
  165155. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165156. }
  165157. /* Read until EOI */
  165158. while (! cinfo->inputctl->eoi_reached) {
  165159. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  165160. return FALSE; /* Suspend, come back later */
  165161. }
  165162. /* Do final cleanup */
  165163. (*cinfo->src->term_source) (cinfo);
  165164. /* We can use jpeg_abort to release memory and reset global_state */
  165165. jpeg_abort((j_common_ptr) cinfo);
  165166. return TRUE;
  165167. }
  165168. /*** End of inlined file: jdapimin.c ***/
  165169. /*** Start of inlined file: jdatasrc.c ***/
  165170. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  165171. /*** Start of inlined file: jerror.h ***/
  165172. /*
  165173. * To define the enum list of message codes, include this file without
  165174. * defining macro JMESSAGE. To create a message string table, include it
  165175. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  165176. */
  165177. #ifndef JMESSAGE
  165178. #ifndef JERROR_H
  165179. /* First time through, define the enum list */
  165180. #define JMAKE_ENUM_LIST
  165181. #else
  165182. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  165183. #define JMESSAGE(code,string)
  165184. #endif /* JERROR_H */
  165185. #endif /* JMESSAGE */
  165186. #ifdef JMAKE_ENUM_LIST
  165187. typedef enum {
  165188. #define JMESSAGE(code,string) code ,
  165189. #endif /* JMAKE_ENUM_LIST */
  165190. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  165191. /* For maintenance convenience, list is alphabetical by message code name */
  165192. JMESSAGE(JERR_ARITH_NOTIMPL,
  165193. "Sorry, there are legal restrictions on arithmetic coding")
  165194. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  165195. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  165196. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  165197. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  165198. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  165199. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  165200. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  165201. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  165202. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  165203. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  165204. JMESSAGE(JERR_BAD_LIB_VERSION,
  165205. "Wrong JPEG library version: library is %d, caller expects %d")
  165206. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  165207. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  165208. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  165209. JMESSAGE(JERR_BAD_PROGRESSION,
  165210. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  165211. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  165212. "Invalid progressive parameters at scan script entry %d")
  165213. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  165214. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  165215. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  165216. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  165217. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  165218. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  165219. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  165220. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  165221. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  165222. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  165223. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  165224. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  165225. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  165226. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  165227. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  165228. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  165229. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  165230. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  165231. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  165232. JMESSAGE(JERR_FILE_READ, "Input file read error")
  165233. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  165234. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  165235. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  165236. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  165237. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  165238. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  165239. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  165240. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  165241. "Cannot transcode due to multiple use of quantization table %d")
  165242. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  165243. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  165244. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  165245. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  165246. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  165247. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  165248. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  165249. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  165250. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  165251. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  165252. JMESSAGE(JERR_QUANT_COMPONENTS,
  165253. "Cannot quantize more than %d color components")
  165254. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  165255. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  165256. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  165257. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  165258. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  165259. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  165260. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  165261. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  165262. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  165263. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  165264. JMESSAGE(JERR_TFILE_WRITE,
  165265. "Write failed on temporary file --- out of disk space?")
  165266. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  165267. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  165268. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  165269. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  165270. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  165271. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  165272. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  165273. JMESSAGE(JMSG_VERSION, JVERSION)
  165274. JMESSAGE(JTRC_16BIT_TABLES,
  165275. "Caution: quantization tables are too coarse for baseline JPEG")
  165276. JMESSAGE(JTRC_ADOBE,
  165277. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  165278. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  165279. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  165280. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  165281. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  165282. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  165283. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  165284. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  165285. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  165286. JMESSAGE(JTRC_EOI, "End Of Image")
  165287. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  165288. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  165289. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  165290. "Warning: thumbnail image size does not match data length %u")
  165291. JMESSAGE(JTRC_JFIF_EXTENSION,
  165292. "JFIF extension marker: type 0x%02x, length %u")
  165293. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  165294. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  165295. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  165296. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  165297. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  165298. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  165299. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  165300. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  165301. JMESSAGE(JTRC_RST, "RST%d")
  165302. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  165303. "Smoothing not supported with nonstandard sampling ratios")
  165304. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  165305. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  165306. JMESSAGE(JTRC_SOI, "Start of Image")
  165307. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  165308. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  165309. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  165310. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  165311. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  165312. JMESSAGE(JTRC_THUMB_JPEG,
  165313. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  165314. JMESSAGE(JTRC_THUMB_PALETTE,
  165315. "JFIF extension marker: palette thumbnail image, length %u")
  165316. JMESSAGE(JTRC_THUMB_RGB,
  165317. "JFIF extension marker: RGB thumbnail image, length %u")
  165318. JMESSAGE(JTRC_UNKNOWN_IDS,
  165319. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  165320. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  165321. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  165322. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  165323. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  165324. "Inconsistent progression sequence for component %d coefficient %d")
  165325. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  165326. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  165327. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  165328. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  165329. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  165330. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  165331. JMESSAGE(JWRN_MUST_RESYNC,
  165332. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  165333. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  165334. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  165335. #ifdef JMAKE_ENUM_LIST
  165336. JMSG_LASTMSGCODE
  165337. } J_MESSAGE_CODE;
  165338. #undef JMAKE_ENUM_LIST
  165339. #endif /* JMAKE_ENUM_LIST */
  165340. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  165341. #undef JMESSAGE
  165342. #ifndef JERROR_H
  165343. #define JERROR_H
  165344. /* Macros to simplify using the error and trace message stuff */
  165345. /* The first parameter is either type of cinfo pointer */
  165346. /* Fatal errors (print message and exit) */
  165347. #define ERREXIT(cinfo,code) \
  165348. ((cinfo)->err->msg_code = (code), \
  165349. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  165350. #define ERREXIT1(cinfo,code,p1) \
  165351. ((cinfo)->err->msg_code = (code), \
  165352. (cinfo)->err->msg_parm.i[0] = (p1), \
  165353. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  165354. #define ERREXIT2(cinfo,code,p1,p2) \
  165355. ((cinfo)->err->msg_code = (code), \
  165356. (cinfo)->err->msg_parm.i[0] = (p1), \
  165357. (cinfo)->err->msg_parm.i[1] = (p2), \
  165358. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  165359. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  165360. ((cinfo)->err->msg_code = (code), \
  165361. (cinfo)->err->msg_parm.i[0] = (p1), \
  165362. (cinfo)->err->msg_parm.i[1] = (p2), \
  165363. (cinfo)->err->msg_parm.i[2] = (p3), \
  165364. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  165365. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  165366. ((cinfo)->err->msg_code = (code), \
  165367. (cinfo)->err->msg_parm.i[0] = (p1), \
  165368. (cinfo)->err->msg_parm.i[1] = (p2), \
  165369. (cinfo)->err->msg_parm.i[2] = (p3), \
  165370. (cinfo)->err->msg_parm.i[3] = (p4), \
  165371. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  165372. #define ERREXITS(cinfo,code,str) \
  165373. ((cinfo)->err->msg_code = (code), \
  165374. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  165375. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  165376. #define MAKESTMT(stuff) do { stuff } while (0)
  165377. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  165378. #define WARNMS(cinfo,code) \
  165379. ((cinfo)->err->msg_code = (code), \
  165380. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  165381. #define WARNMS1(cinfo,code,p1) \
  165382. ((cinfo)->err->msg_code = (code), \
  165383. (cinfo)->err->msg_parm.i[0] = (p1), \
  165384. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  165385. #define WARNMS2(cinfo,code,p1,p2) \
  165386. ((cinfo)->err->msg_code = (code), \
  165387. (cinfo)->err->msg_parm.i[0] = (p1), \
  165388. (cinfo)->err->msg_parm.i[1] = (p2), \
  165389. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  165390. /* Informational/debugging messages */
  165391. #define TRACEMS(cinfo,lvl,code) \
  165392. ((cinfo)->err->msg_code = (code), \
  165393. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  165394. #define TRACEMS1(cinfo,lvl,code,p1) \
  165395. ((cinfo)->err->msg_code = (code), \
  165396. (cinfo)->err->msg_parm.i[0] = (p1), \
  165397. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  165398. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  165399. ((cinfo)->err->msg_code = (code), \
  165400. (cinfo)->err->msg_parm.i[0] = (p1), \
  165401. (cinfo)->err->msg_parm.i[1] = (p2), \
  165402. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  165403. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  165404. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  165405. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  165406. (cinfo)->err->msg_code = (code); \
  165407. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  165408. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  165409. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  165410. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  165411. (cinfo)->err->msg_code = (code); \
  165412. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  165413. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  165414. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  165415. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  165416. _mp[4] = (p5); \
  165417. (cinfo)->err->msg_code = (code); \
  165418. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  165419. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  165420. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  165421. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  165422. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  165423. (cinfo)->err->msg_code = (code); \
  165424. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  165425. #define TRACEMSS(cinfo,lvl,code,str) \
  165426. ((cinfo)->err->msg_code = (code), \
  165427. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  165428. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  165429. #endif /* JERROR_H */
  165430. /*** End of inlined file: jerror.h ***/
  165431. /* Expanded data source object for stdio input */
  165432. typedef struct {
  165433. struct jpeg_source_mgr pub; /* public fields */
  165434. FILE * infile; /* source stream */
  165435. JOCTET * buffer; /* start of buffer */
  165436. boolean start_of_file; /* have we gotten any data yet? */
  165437. } my_source_mgr;
  165438. typedef my_source_mgr * my_src_ptr;
  165439. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  165440. /*
  165441. * Initialize source --- called by jpeg_read_header
  165442. * before any data is actually read.
  165443. */
  165444. METHODDEF(void)
  165445. init_source (j_decompress_ptr cinfo)
  165446. {
  165447. my_src_ptr src = (my_src_ptr) cinfo->src;
  165448. /* We reset the empty-input-file flag for each image,
  165449. * but we don't clear the input buffer.
  165450. * This is correct behavior for reading a series of images from one source.
  165451. */
  165452. src->start_of_file = TRUE;
  165453. }
  165454. /*
  165455. * Fill the input buffer --- called whenever buffer is emptied.
  165456. *
  165457. * In typical applications, this should read fresh data into the buffer
  165458. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  165459. * reset the pointer & count to the start of the buffer, and return TRUE
  165460. * indicating that the buffer has been reloaded. It is not necessary to
  165461. * fill the buffer entirely, only to obtain at least one more byte.
  165462. *
  165463. * There is no such thing as an EOF return. If the end of the file has been
  165464. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  165465. * the buffer. In most cases, generating a warning message and inserting a
  165466. * fake EOI marker is the best course of action --- this will allow the
  165467. * decompressor to output however much of the image is there. However,
  165468. * the resulting error message is misleading if the real problem is an empty
  165469. * input file, so we handle that case specially.
  165470. *
  165471. * In applications that need to be able to suspend compression due to input
  165472. * not being available yet, a FALSE return indicates that no more data can be
  165473. * obtained right now, but more may be forthcoming later. In this situation,
  165474. * the decompressor will return to its caller (with an indication of the
  165475. * number of scanlines it has read, if any). The application should resume
  165476. * decompression after it has loaded more data into the input buffer. Note
  165477. * that there are substantial restrictions on the use of suspension --- see
  165478. * the documentation.
  165479. *
  165480. * When suspending, the decompressor will back up to a convenient restart point
  165481. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  165482. * indicate where the restart point will be if the current call returns FALSE.
  165483. * Data beyond this point must be rescanned after resumption, so move it to
  165484. * the front of the buffer rather than discarding it.
  165485. */
  165486. METHODDEF(boolean)
  165487. fill_input_buffer (j_decompress_ptr cinfo)
  165488. {
  165489. my_src_ptr src = (my_src_ptr) cinfo->src;
  165490. size_t nbytes;
  165491. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  165492. if (nbytes <= 0) {
  165493. if (src->start_of_file) /* Treat empty input file as fatal error */
  165494. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  165495. WARNMS(cinfo, JWRN_JPEG_EOF);
  165496. /* Insert a fake EOI marker */
  165497. src->buffer[0] = (JOCTET) 0xFF;
  165498. src->buffer[1] = (JOCTET) JPEG_EOI;
  165499. nbytes = 2;
  165500. }
  165501. src->pub.next_input_byte = src->buffer;
  165502. src->pub.bytes_in_buffer = nbytes;
  165503. src->start_of_file = FALSE;
  165504. return TRUE;
  165505. }
  165506. /*
  165507. * Skip data --- used to skip over a potentially large amount of
  165508. * uninteresting data (such as an APPn marker).
  165509. *
  165510. * Writers of suspendable-input applications must note that skip_input_data
  165511. * is not granted the right to give a suspension return. If the skip extends
  165512. * beyond the data currently in the buffer, the buffer can be marked empty so
  165513. * that the next read will cause a fill_input_buffer call that can suspend.
  165514. * Arranging for additional bytes to be discarded before reloading the input
  165515. * buffer is the application writer's problem.
  165516. */
  165517. METHODDEF(void)
  165518. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  165519. {
  165520. my_src_ptr src = (my_src_ptr) cinfo->src;
  165521. /* Just a dumb implementation for now. Could use fseek() except
  165522. * it doesn't work on pipes. Not clear that being smart is worth
  165523. * any trouble anyway --- large skips are infrequent.
  165524. */
  165525. if (num_bytes > 0) {
  165526. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  165527. num_bytes -= (long) src->pub.bytes_in_buffer;
  165528. (void) fill_input_buffer(cinfo);
  165529. /* note we assume that fill_input_buffer will never return FALSE,
  165530. * so suspension need not be handled.
  165531. */
  165532. }
  165533. src->pub.next_input_byte += (size_t) num_bytes;
  165534. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  165535. }
  165536. }
  165537. /*
  165538. * An additional method that can be provided by data source modules is the
  165539. * resync_to_restart method for error recovery in the presence of RST markers.
  165540. * For the moment, this source module just uses the default resync method
  165541. * provided by the JPEG library. That method assumes that no backtracking
  165542. * is possible.
  165543. */
  165544. /*
  165545. * Terminate source --- called by jpeg_finish_decompress
  165546. * after all data has been read. Often a no-op.
  165547. *
  165548. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  165549. * application must deal with any cleanup that should happen even
  165550. * for error exit.
  165551. */
  165552. METHODDEF(void)
  165553. term_source (j_decompress_ptr)
  165554. {
  165555. /* no work necessary here */
  165556. }
  165557. /*
  165558. * Prepare for input from a stdio stream.
  165559. * The caller must have already opened the stream, and is responsible
  165560. * for closing it after finishing decompression.
  165561. */
  165562. GLOBAL(void)
  165563. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  165564. {
  165565. my_src_ptr src;
  165566. /* The source object and input buffer are made permanent so that a series
  165567. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  165568. * only before the first one. (If we discarded the buffer at the end of
  165569. * one image, we'd likely lose the start of the next one.)
  165570. * This makes it unsafe to use this manager and a different source
  165571. * manager serially with the same JPEG object. Caveat programmer.
  165572. */
  165573. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  165574. cinfo->src = (struct jpeg_source_mgr *)
  165575. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165576. SIZEOF(my_source_mgr));
  165577. src = (my_src_ptr) cinfo->src;
  165578. src->buffer = (JOCTET *)
  165579. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165580. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  165581. }
  165582. src = (my_src_ptr) cinfo->src;
  165583. src->pub.init_source = init_source;
  165584. src->pub.fill_input_buffer = fill_input_buffer;
  165585. src->pub.skip_input_data = skip_input_data;
  165586. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  165587. src->pub.term_source = term_source;
  165588. src->infile = infile;
  165589. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  165590. src->pub.next_input_byte = NULL; /* until buffer loaded */
  165591. }
  165592. /*** End of inlined file: jdatasrc.c ***/
  165593. /*** Start of inlined file: jdcoefct.c ***/
  165594. #define JPEG_INTERNALS
  165595. /* Block smoothing is only applicable for progressive JPEG, so: */
  165596. #ifndef D_PROGRESSIVE_SUPPORTED
  165597. #undef BLOCK_SMOOTHING_SUPPORTED
  165598. #endif
  165599. /* Private buffer controller object */
  165600. typedef struct {
  165601. struct jpeg_d_coef_controller pub; /* public fields */
  165602. /* These variables keep track of the current location of the input side. */
  165603. /* cinfo->input_iMCU_row is also used for this. */
  165604. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  165605. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  165606. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  165607. /* The output side's location is represented by cinfo->output_iMCU_row. */
  165608. /* In single-pass modes, it's sufficient to buffer just one MCU.
  165609. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  165610. * and let the entropy decoder write into that workspace each time.
  165611. * (On 80x86, the workspace is FAR even though it's not really very big;
  165612. * this is to keep the module interfaces unchanged when a large coefficient
  165613. * buffer is necessary.)
  165614. * In multi-pass modes, this array points to the current MCU's blocks
  165615. * within the virtual arrays; it is used only by the input side.
  165616. */
  165617. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  165618. #ifdef D_MULTISCAN_FILES_SUPPORTED
  165619. /* In multi-pass modes, we need a virtual block array for each component. */
  165620. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  165621. #endif
  165622. #ifdef BLOCK_SMOOTHING_SUPPORTED
  165623. /* When doing block smoothing, we latch coefficient Al values here */
  165624. int * coef_bits_latch;
  165625. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  165626. #endif
  165627. } my_coef_controller3;
  165628. typedef my_coef_controller3 * my_coef_ptr3;
  165629. /* Forward declarations */
  165630. METHODDEF(int) decompress_onepass
  165631. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  165632. #ifdef D_MULTISCAN_FILES_SUPPORTED
  165633. METHODDEF(int) decompress_data
  165634. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  165635. #endif
  165636. #ifdef BLOCK_SMOOTHING_SUPPORTED
  165637. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  165638. METHODDEF(int) decompress_smooth_data
  165639. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  165640. #endif
  165641. LOCAL(void)
  165642. start_iMCU_row3 (j_decompress_ptr cinfo)
  165643. /* Reset within-iMCU-row counters for a new row (input side) */
  165644. {
  165645. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  165646. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  165647. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  165648. * But at the bottom of the image, process only what's left.
  165649. */
  165650. if (cinfo->comps_in_scan > 1) {
  165651. coef->MCU_rows_per_iMCU_row = 1;
  165652. } else {
  165653. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  165654. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  165655. else
  165656. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  165657. }
  165658. coef->MCU_ctr = 0;
  165659. coef->MCU_vert_offset = 0;
  165660. }
  165661. /*
  165662. * Initialize for an input processing pass.
  165663. */
  165664. METHODDEF(void)
  165665. start_input_pass (j_decompress_ptr cinfo)
  165666. {
  165667. cinfo->input_iMCU_row = 0;
  165668. start_iMCU_row3(cinfo);
  165669. }
  165670. /*
  165671. * Initialize for an output processing pass.
  165672. */
  165673. METHODDEF(void)
  165674. start_output_pass (j_decompress_ptr cinfo)
  165675. {
  165676. #ifdef BLOCK_SMOOTHING_SUPPORTED
  165677. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  165678. /* If multipass, check to see whether to use block smoothing on this pass */
  165679. if (coef->pub.coef_arrays != NULL) {
  165680. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  165681. coef->pub.decompress_data = decompress_smooth_data;
  165682. else
  165683. coef->pub.decompress_data = decompress_data;
  165684. }
  165685. #endif
  165686. cinfo->output_iMCU_row = 0;
  165687. }
  165688. /*
  165689. * Decompress and return some data in the single-pass case.
  165690. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  165691. * Input and output must run in lockstep since we have only a one-MCU buffer.
  165692. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  165693. *
  165694. * NB: output_buf contains a plane for each component in image,
  165695. * which we index according to the component's SOF position.
  165696. */
  165697. METHODDEF(int)
  165698. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  165699. {
  165700. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  165701. JDIMENSION MCU_col_num; /* index of current MCU within row */
  165702. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  165703. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  165704. int blkn, ci, xindex, yindex, yoffset, useful_width;
  165705. JSAMPARRAY output_ptr;
  165706. JDIMENSION start_col, output_col;
  165707. jpeg_component_info *compptr;
  165708. inverse_DCT_method_ptr inverse_DCT;
  165709. /* Loop to process as much as one whole iMCU row */
  165710. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  165711. yoffset++) {
  165712. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  165713. MCU_col_num++) {
  165714. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  165715. jzero_far((void FAR *) coef->MCU_buffer[0],
  165716. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  165717. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  165718. /* Suspension forced; update state counters and exit */
  165719. coef->MCU_vert_offset = yoffset;
  165720. coef->MCU_ctr = MCU_col_num;
  165721. return JPEG_SUSPENDED;
  165722. }
  165723. /* Determine where data should go in output_buf and do the IDCT thing.
  165724. * We skip dummy blocks at the right and bottom edges (but blkn gets
  165725. * incremented past them!). Note the inner loop relies on having
  165726. * allocated the MCU_buffer[] blocks sequentially.
  165727. */
  165728. blkn = 0; /* index of current DCT block within MCU */
  165729. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165730. compptr = cinfo->cur_comp_info[ci];
  165731. /* Don't bother to IDCT an uninteresting component. */
  165732. if (! compptr->component_needed) {
  165733. blkn += compptr->MCU_blocks;
  165734. continue;
  165735. }
  165736. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  165737. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  165738. : compptr->last_col_width;
  165739. output_ptr = output_buf[compptr->component_index] +
  165740. yoffset * compptr->DCT_scaled_size;
  165741. start_col = MCU_col_num * compptr->MCU_sample_width;
  165742. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  165743. if (cinfo->input_iMCU_row < last_iMCU_row ||
  165744. yoffset+yindex < compptr->last_row_height) {
  165745. output_col = start_col;
  165746. for (xindex = 0; xindex < useful_width; xindex++) {
  165747. (*inverse_DCT) (cinfo, compptr,
  165748. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  165749. output_ptr, output_col);
  165750. output_col += compptr->DCT_scaled_size;
  165751. }
  165752. }
  165753. blkn += compptr->MCU_width;
  165754. output_ptr += compptr->DCT_scaled_size;
  165755. }
  165756. }
  165757. }
  165758. /* Completed an MCU row, but perhaps not an iMCU row */
  165759. coef->MCU_ctr = 0;
  165760. }
  165761. /* Completed the iMCU row, advance counters for next one */
  165762. cinfo->output_iMCU_row++;
  165763. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  165764. start_iMCU_row3(cinfo);
  165765. return JPEG_ROW_COMPLETED;
  165766. }
  165767. /* Completed the scan */
  165768. (*cinfo->inputctl->finish_input_pass) (cinfo);
  165769. return JPEG_SCAN_COMPLETED;
  165770. }
  165771. /*
  165772. * Dummy consume-input routine for single-pass operation.
  165773. */
  165774. METHODDEF(int)
  165775. dummy_consume_data (j_decompress_ptr)
  165776. {
  165777. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  165778. }
  165779. #ifdef D_MULTISCAN_FILES_SUPPORTED
  165780. /*
  165781. * Consume input data and store it in the full-image coefficient buffer.
  165782. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  165783. * ie, v_samp_factor block rows for each component in the scan.
  165784. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  165785. */
  165786. METHODDEF(int)
  165787. consume_data (j_decompress_ptr cinfo)
  165788. {
  165789. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  165790. JDIMENSION MCU_col_num; /* index of current MCU within row */
  165791. int blkn, ci, xindex, yindex, yoffset;
  165792. JDIMENSION start_col;
  165793. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  165794. JBLOCKROW buffer_ptr;
  165795. jpeg_component_info *compptr;
  165796. /* Align the virtual buffers for the components used in this scan. */
  165797. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165798. compptr = cinfo->cur_comp_info[ci];
  165799. buffer[ci] = (*cinfo->mem->access_virt_barray)
  165800. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  165801. cinfo->input_iMCU_row * compptr->v_samp_factor,
  165802. (JDIMENSION) compptr->v_samp_factor, TRUE);
  165803. /* Note: entropy decoder expects buffer to be zeroed,
  165804. * but this is handled automatically by the memory manager
  165805. * because we requested a pre-zeroed array.
  165806. */
  165807. }
  165808. /* Loop to process one whole iMCU row */
  165809. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  165810. yoffset++) {
  165811. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  165812. MCU_col_num++) {
  165813. /* Construct list of pointers to DCT blocks belonging to this MCU */
  165814. blkn = 0; /* index of current DCT block within MCU */
  165815. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165816. compptr = cinfo->cur_comp_info[ci];
  165817. start_col = MCU_col_num * compptr->MCU_width;
  165818. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  165819. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  165820. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  165821. coef->MCU_buffer[blkn++] = buffer_ptr++;
  165822. }
  165823. }
  165824. }
  165825. /* Try to fetch the MCU. */
  165826. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  165827. /* Suspension forced; update state counters and exit */
  165828. coef->MCU_vert_offset = yoffset;
  165829. coef->MCU_ctr = MCU_col_num;
  165830. return JPEG_SUSPENDED;
  165831. }
  165832. }
  165833. /* Completed an MCU row, but perhaps not an iMCU row */
  165834. coef->MCU_ctr = 0;
  165835. }
  165836. /* Completed the iMCU row, advance counters for next one */
  165837. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  165838. start_iMCU_row3(cinfo);
  165839. return JPEG_ROW_COMPLETED;
  165840. }
  165841. /* Completed the scan */
  165842. (*cinfo->inputctl->finish_input_pass) (cinfo);
  165843. return JPEG_SCAN_COMPLETED;
  165844. }
  165845. /*
  165846. * Decompress and return some data in the multi-pass case.
  165847. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  165848. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  165849. *
  165850. * NB: output_buf contains a plane for each component in image.
  165851. */
  165852. METHODDEF(int)
  165853. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  165854. {
  165855. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  165856. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  165857. JDIMENSION block_num;
  165858. int ci, block_row, block_rows;
  165859. JBLOCKARRAY buffer;
  165860. JBLOCKROW buffer_ptr;
  165861. JSAMPARRAY output_ptr;
  165862. JDIMENSION output_col;
  165863. jpeg_component_info *compptr;
  165864. inverse_DCT_method_ptr inverse_DCT;
  165865. /* Force some input to be done if we are getting ahead of the input. */
  165866. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  165867. (cinfo->input_scan_number == cinfo->output_scan_number &&
  165868. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  165869. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  165870. return JPEG_SUSPENDED;
  165871. }
  165872. /* OK, output from the virtual arrays. */
  165873. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165874. ci++, compptr++) {
  165875. /* Don't bother to IDCT an uninteresting component. */
  165876. if (! compptr->component_needed)
  165877. continue;
  165878. /* Align the virtual buffer for this component. */
  165879. buffer = (*cinfo->mem->access_virt_barray)
  165880. ((j_common_ptr) cinfo, coef->whole_image[ci],
  165881. cinfo->output_iMCU_row * compptr->v_samp_factor,
  165882. (JDIMENSION) compptr->v_samp_factor, FALSE);
  165883. /* Count non-dummy DCT block rows in this iMCU row. */
  165884. if (cinfo->output_iMCU_row < last_iMCU_row)
  165885. block_rows = compptr->v_samp_factor;
  165886. else {
  165887. /* NB: can't use last_row_height here; it is input-side-dependent! */
  165888. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  165889. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  165890. }
  165891. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  165892. output_ptr = output_buf[ci];
  165893. /* Loop over all DCT blocks to be processed. */
  165894. for (block_row = 0; block_row < block_rows; block_row++) {
  165895. buffer_ptr = buffer[block_row];
  165896. output_col = 0;
  165897. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  165898. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  165899. output_ptr, output_col);
  165900. buffer_ptr++;
  165901. output_col += compptr->DCT_scaled_size;
  165902. }
  165903. output_ptr += compptr->DCT_scaled_size;
  165904. }
  165905. }
  165906. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  165907. return JPEG_ROW_COMPLETED;
  165908. return JPEG_SCAN_COMPLETED;
  165909. }
  165910. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  165911. #ifdef BLOCK_SMOOTHING_SUPPORTED
  165912. /*
  165913. * This code applies interblock smoothing as described by section K.8
  165914. * of the JPEG standard: the first 5 AC coefficients are estimated from
  165915. * the DC values of a DCT block and its 8 neighboring blocks.
  165916. * We apply smoothing only for progressive JPEG decoding, and only if
  165917. * the coefficients it can estimate are not yet known to full precision.
  165918. */
  165919. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  165920. #define Q01_POS 1
  165921. #define Q10_POS 8
  165922. #define Q20_POS 16
  165923. #define Q11_POS 9
  165924. #define Q02_POS 2
  165925. /*
  165926. * Determine whether block smoothing is applicable and safe.
  165927. * We also latch the current states of the coef_bits[] entries for the
  165928. * AC coefficients; otherwise, if the input side of the decompressor
  165929. * advances into a new scan, we might think the coefficients are known
  165930. * more accurately than they really are.
  165931. */
  165932. LOCAL(boolean)
  165933. smoothing_ok (j_decompress_ptr cinfo)
  165934. {
  165935. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  165936. boolean smoothing_useful = FALSE;
  165937. int ci, coefi;
  165938. jpeg_component_info *compptr;
  165939. JQUANT_TBL * qtable;
  165940. int * coef_bits;
  165941. int * coef_bits_latch;
  165942. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  165943. return FALSE;
  165944. /* Allocate latch area if not already done */
  165945. if (coef->coef_bits_latch == NULL)
  165946. coef->coef_bits_latch = (int *)
  165947. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165948. cinfo->num_components *
  165949. (SAVED_COEFS * SIZEOF(int)));
  165950. coef_bits_latch = coef->coef_bits_latch;
  165951. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165952. ci++, compptr++) {
  165953. /* All components' quantization values must already be latched. */
  165954. if ((qtable = compptr->quant_table) == NULL)
  165955. return FALSE;
  165956. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  165957. if (qtable->quantval[0] == 0 ||
  165958. qtable->quantval[Q01_POS] == 0 ||
  165959. qtable->quantval[Q10_POS] == 0 ||
  165960. qtable->quantval[Q20_POS] == 0 ||
  165961. qtable->quantval[Q11_POS] == 0 ||
  165962. qtable->quantval[Q02_POS] == 0)
  165963. return FALSE;
  165964. /* DC values must be at least partly known for all components. */
  165965. coef_bits = cinfo->coef_bits[ci];
  165966. if (coef_bits[0] < 0)
  165967. return FALSE;
  165968. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  165969. for (coefi = 1; coefi <= 5; coefi++) {
  165970. coef_bits_latch[coefi] = coef_bits[coefi];
  165971. if (coef_bits[coefi] != 0)
  165972. smoothing_useful = TRUE;
  165973. }
  165974. coef_bits_latch += SAVED_COEFS;
  165975. }
  165976. return smoothing_useful;
  165977. }
  165978. /*
  165979. * Variant of decompress_data for use when doing block smoothing.
  165980. */
  165981. METHODDEF(int)
  165982. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  165983. {
  165984. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  165985. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  165986. JDIMENSION block_num, last_block_column;
  165987. int ci, block_row, block_rows, access_rows;
  165988. JBLOCKARRAY buffer;
  165989. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  165990. JSAMPARRAY output_ptr;
  165991. JDIMENSION output_col;
  165992. jpeg_component_info *compptr;
  165993. inverse_DCT_method_ptr inverse_DCT;
  165994. boolean first_row, last_row;
  165995. JBLOCK workspace;
  165996. int *coef_bits;
  165997. JQUANT_TBL *quanttbl;
  165998. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  165999. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  166000. int Al, pred;
  166001. /* Force some input to be done if we are getting ahead of the input. */
  166002. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  166003. ! cinfo->inputctl->eoi_reached) {
  166004. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  166005. /* If input is working on current scan, we ordinarily want it to
  166006. * have completed the current row. But if input scan is DC,
  166007. * we want it to keep one row ahead so that next block row's DC
  166008. * values are up to date.
  166009. */
  166010. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  166011. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  166012. break;
  166013. }
  166014. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  166015. return JPEG_SUSPENDED;
  166016. }
  166017. /* OK, output from the virtual arrays. */
  166018. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166019. ci++, compptr++) {
  166020. /* Don't bother to IDCT an uninteresting component. */
  166021. if (! compptr->component_needed)
  166022. continue;
  166023. /* Count non-dummy DCT block rows in this iMCU row. */
  166024. if (cinfo->output_iMCU_row < last_iMCU_row) {
  166025. block_rows = compptr->v_samp_factor;
  166026. access_rows = block_rows * 2; /* this and next iMCU row */
  166027. last_row = FALSE;
  166028. } else {
  166029. /* NB: can't use last_row_height here; it is input-side-dependent! */
  166030. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  166031. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  166032. access_rows = block_rows; /* this iMCU row only */
  166033. last_row = TRUE;
  166034. }
  166035. /* Align the virtual buffer for this component. */
  166036. if (cinfo->output_iMCU_row > 0) {
  166037. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  166038. buffer = (*cinfo->mem->access_virt_barray)
  166039. ((j_common_ptr) cinfo, coef->whole_image[ci],
  166040. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  166041. (JDIMENSION) access_rows, FALSE);
  166042. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  166043. first_row = FALSE;
  166044. } else {
  166045. buffer = (*cinfo->mem->access_virt_barray)
  166046. ((j_common_ptr) cinfo, coef->whole_image[ci],
  166047. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  166048. first_row = TRUE;
  166049. }
  166050. /* Fetch component-dependent info */
  166051. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  166052. quanttbl = compptr->quant_table;
  166053. Q00 = quanttbl->quantval[0];
  166054. Q01 = quanttbl->quantval[Q01_POS];
  166055. Q10 = quanttbl->quantval[Q10_POS];
  166056. Q20 = quanttbl->quantval[Q20_POS];
  166057. Q11 = quanttbl->quantval[Q11_POS];
  166058. Q02 = quanttbl->quantval[Q02_POS];
  166059. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  166060. output_ptr = output_buf[ci];
  166061. /* Loop over all DCT blocks to be processed. */
  166062. for (block_row = 0; block_row < block_rows; block_row++) {
  166063. buffer_ptr = buffer[block_row];
  166064. if (first_row && block_row == 0)
  166065. prev_block_row = buffer_ptr;
  166066. else
  166067. prev_block_row = buffer[block_row-1];
  166068. if (last_row && block_row == block_rows-1)
  166069. next_block_row = buffer_ptr;
  166070. else
  166071. next_block_row = buffer[block_row+1];
  166072. /* We fetch the surrounding DC values using a sliding-register approach.
  166073. * Initialize all nine here so as to do the right thing on narrow pics.
  166074. */
  166075. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  166076. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  166077. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  166078. output_col = 0;
  166079. last_block_column = compptr->width_in_blocks - 1;
  166080. for (block_num = 0; block_num <= last_block_column; block_num++) {
  166081. /* Fetch current DCT block into workspace so we can modify it. */
  166082. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  166083. /* Update DC values */
  166084. if (block_num < last_block_column) {
  166085. DC3 = (int) prev_block_row[1][0];
  166086. DC6 = (int) buffer_ptr[1][0];
  166087. DC9 = (int) next_block_row[1][0];
  166088. }
  166089. /* Compute coefficient estimates per K.8.
  166090. * An estimate is applied only if coefficient is still zero,
  166091. * and is not known to be fully accurate.
  166092. */
  166093. /* AC01 */
  166094. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  166095. num = 36 * Q00 * (DC4 - DC6);
  166096. if (num >= 0) {
  166097. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  166098. if (Al > 0 && pred >= (1<<Al))
  166099. pred = (1<<Al)-1;
  166100. } else {
  166101. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  166102. if (Al > 0 && pred >= (1<<Al))
  166103. pred = (1<<Al)-1;
  166104. pred = -pred;
  166105. }
  166106. workspace[1] = (JCOEF) pred;
  166107. }
  166108. /* AC10 */
  166109. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  166110. num = 36 * Q00 * (DC2 - DC8);
  166111. if (num >= 0) {
  166112. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  166113. if (Al > 0 && pred >= (1<<Al))
  166114. pred = (1<<Al)-1;
  166115. } else {
  166116. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  166117. if (Al > 0 && pred >= (1<<Al))
  166118. pred = (1<<Al)-1;
  166119. pred = -pred;
  166120. }
  166121. workspace[8] = (JCOEF) pred;
  166122. }
  166123. /* AC20 */
  166124. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  166125. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  166126. if (num >= 0) {
  166127. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  166128. if (Al > 0 && pred >= (1<<Al))
  166129. pred = (1<<Al)-1;
  166130. } else {
  166131. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  166132. if (Al > 0 && pred >= (1<<Al))
  166133. pred = (1<<Al)-1;
  166134. pred = -pred;
  166135. }
  166136. workspace[16] = (JCOEF) pred;
  166137. }
  166138. /* AC11 */
  166139. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  166140. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  166141. if (num >= 0) {
  166142. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  166143. if (Al > 0 && pred >= (1<<Al))
  166144. pred = (1<<Al)-1;
  166145. } else {
  166146. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  166147. if (Al > 0 && pred >= (1<<Al))
  166148. pred = (1<<Al)-1;
  166149. pred = -pred;
  166150. }
  166151. workspace[9] = (JCOEF) pred;
  166152. }
  166153. /* AC02 */
  166154. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  166155. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  166156. if (num >= 0) {
  166157. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  166158. if (Al > 0 && pred >= (1<<Al))
  166159. pred = (1<<Al)-1;
  166160. } else {
  166161. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  166162. if (Al > 0 && pred >= (1<<Al))
  166163. pred = (1<<Al)-1;
  166164. pred = -pred;
  166165. }
  166166. workspace[2] = (JCOEF) pred;
  166167. }
  166168. /* OK, do the IDCT */
  166169. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  166170. output_ptr, output_col);
  166171. /* Advance for next column */
  166172. DC1 = DC2; DC2 = DC3;
  166173. DC4 = DC5; DC5 = DC6;
  166174. DC7 = DC8; DC8 = DC9;
  166175. buffer_ptr++, prev_block_row++, next_block_row++;
  166176. output_col += compptr->DCT_scaled_size;
  166177. }
  166178. output_ptr += compptr->DCT_scaled_size;
  166179. }
  166180. }
  166181. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  166182. return JPEG_ROW_COMPLETED;
  166183. return JPEG_SCAN_COMPLETED;
  166184. }
  166185. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  166186. /*
  166187. * Initialize coefficient buffer controller.
  166188. */
  166189. GLOBAL(void)
  166190. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  166191. {
  166192. my_coef_ptr3 coef;
  166193. coef = (my_coef_ptr3)
  166194. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166195. SIZEOF(my_coef_controller3));
  166196. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  166197. coef->pub.start_input_pass = start_input_pass;
  166198. coef->pub.start_output_pass = start_output_pass;
  166199. #ifdef BLOCK_SMOOTHING_SUPPORTED
  166200. coef->coef_bits_latch = NULL;
  166201. #endif
  166202. /* Create the coefficient buffer. */
  166203. if (need_full_buffer) {
  166204. #ifdef D_MULTISCAN_FILES_SUPPORTED
  166205. /* Allocate a full-image virtual array for each component, */
  166206. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  166207. /* Note we ask for a pre-zeroed array. */
  166208. int ci, access_rows;
  166209. jpeg_component_info *compptr;
  166210. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166211. ci++, compptr++) {
  166212. access_rows = compptr->v_samp_factor;
  166213. #ifdef BLOCK_SMOOTHING_SUPPORTED
  166214. /* If block smoothing could be used, need a bigger window */
  166215. if (cinfo->progressive_mode)
  166216. access_rows *= 3;
  166217. #endif
  166218. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  166219. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  166220. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  166221. (long) compptr->h_samp_factor),
  166222. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  166223. (long) compptr->v_samp_factor),
  166224. (JDIMENSION) access_rows);
  166225. }
  166226. coef->pub.consume_data = consume_data;
  166227. coef->pub.decompress_data = decompress_data;
  166228. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  166229. #else
  166230. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166231. #endif
  166232. } else {
  166233. /* We only need a single-MCU buffer. */
  166234. JBLOCKROW buffer;
  166235. int i;
  166236. buffer = (JBLOCKROW)
  166237. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166238. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  166239. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  166240. coef->MCU_buffer[i] = buffer + i;
  166241. }
  166242. coef->pub.consume_data = dummy_consume_data;
  166243. coef->pub.decompress_data = decompress_onepass;
  166244. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  166245. }
  166246. }
  166247. /*** End of inlined file: jdcoefct.c ***/
  166248. #undef FIX
  166249. /*** Start of inlined file: jdcolor.c ***/
  166250. #define JPEG_INTERNALS
  166251. /* Private subobject */
  166252. typedef struct {
  166253. struct jpeg_color_deconverter pub; /* public fields */
  166254. /* Private state for YCC->RGB conversion */
  166255. int * Cr_r_tab; /* => table for Cr to R conversion */
  166256. int * Cb_b_tab; /* => table for Cb to B conversion */
  166257. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  166258. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  166259. } my_color_deconverter2;
  166260. typedef my_color_deconverter2 * my_cconvert_ptr2;
  166261. /**************** YCbCr -> RGB conversion: most common case **************/
  166262. /*
  166263. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  166264. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  166265. * The conversion equations to be implemented are therefore
  166266. * R = Y + 1.40200 * Cr
  166267. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  166268. * B = Y + 1.77200 * Cb
  166269. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  166270. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  166271. *
  166272. * To avoid floating-point arithmetic, we represent the fractional constants
  166273. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  166274. * the products by 2^16, with appropriate rounding, to get the correct answer.
  166275. * Notice that Y, being an integral input, does not contribute any fraction
  166276. * so it need not participate in the rounding.
  166277. *
  166278. * For even more speed, we avoid doing any multiplications in the inner loop
  166279. * by precalculating the constants times Cb and Cr for all possible values.
  166280. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  166281. * for 12-bit samples it is still acceptable. It's not very reasonable for
  166282. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  166283. * colorspace anyway.
  166284. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  166285. * values for the G calculation are left scaled up, since we must add them
  166286. * together before rounding.
  166287. */
  166288. #define SCALEBITS 16 /* speediest right-shift on some machines */
  166289. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  166290. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  166291. /*
  166292. * Initialize tables for YCC->RGB colorspace conversion.
  166293. */
  166294. LOCAL(void)
  166295. build_ycc_rgb_table (j_decompress_ptr cinfo)
  166296. {
  166297. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  166298. int i;
  166299. INT32 x;
  166300. SHIFT_TEMPS
  166301. cconvert->Cr_r_tab = (int *)
  166302. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166303. (MAXJSAMPLE+1) * SIZEOF(int));
  166304. cconvert->Cb_b_tab = (int *)
  166305. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166306. (MAXJSAMPLE+1) * SIZEOF(int));
  166307. cconvert->Cr_g_tab = (INT32 *)
  166308. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166309. (MAXJSAMPLE+1) * SIZEOF(INT32));
  166310. cconvert->Cb_g_tab = (INT32 *)
  166311. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166312. (MAXJSAMPLE+1) * SIZEOF(INT32));
  166313. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  166314. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  166315. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  166316. /* Cr=>R value is nearest int to 1.40200 * x */
  166317. cconvert->Cr_r_tab[i] = (int)
  166318. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  166319. /* Cb=>B value is nearest int to 1.77200 * x */
  166320. cconvert->Cb_b_tab[i] = (int)
  166321. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  166322. /* Cr=>G value is scaled-up -0.71414 * x */
  166323. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  166324. /* Cb=>G value is scaled-up -0.34414 * x */
  166325. /* We also add in ONE_HALF so that need not do it in inner loop */
  166326. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  166327. }
  166328. }
  166329. /*
  166330. * Convert some rows of samples to the output colorspace.
  166331. *
  166332. * Note that we change from noninterleaved, one-plane-per-component format
  166333. * to interleaved-pixel format. The output buffer is therefore three times
  166334. * as wide as the input buffer.
  166335. * A starting row offset is provided only for the input buffer. The caller
  166336. * can easily adjust the passed output_buf value to accommodate any row
  166337. * offset required on that side.
  166338. */
  166339. METHODDEF(void)
  166340. ycc_rgb_convert (j_decompress_ptr cinfo,
  166341. JSAMPIMAGE input_buf, JDIMENSION input_row,
  166342. JSAMPARRAY output_buf, int num_rows)
  166343. {
  166344. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  166345. register int y, cb, cr;
  166346. register JSAMPROW outptr;
  166347. register JSAMPROW inptr0, inptr1, inptr2;
  166348. register JDIMENSION col;
  166349. JDIMENSION num_cols = cinfo->output_width;
  166350. /* copy these pointers into registers if possible */
  166351. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  166352. register int * Crrtab = cconvert->Cr_r_tab;
  166353. register int * Cbbtab = cconvert->Cb_b_tab;
  166354. register INT32 * Crgtab = cconvert->Cr_g_tab;
  166355. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  166356. SHIFT_TEMPS
  166357. while (--num_rows >= 0) {
  166358. inptr0 = input_buf[0][input_row];
  166359. inptr1 = input_buf[1][input_row];
  166360. inptr2 = input_buf[2][input_row];
  166361. input_row++;
  166362. outptr = *output_buf++;
  166363. for (col = 0; col < num_cols; col++) {
  166364. y = GETJSAMPLE(inptr0[col]);
  166365. cb = GETJSAMPLE(inptr1[col]);
  166366. cr = GETJSAMPLE(inptr2[col]);
  166367. /* Range-limiting is essential due to noise introduced by DCT losses. */
  166368. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  166369. outptr[RGB_GREEN] = range_limit[y +
  166370. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  166371. SCALEBITS))];
  166372. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  166373. outptr += RGB_PIXELSIZE;
  166374. }
  166375. }
  166376. }
  166377. /**************** Cases other than YCbCr -> RGB **************/
  166378. /*
  166379. * Color conversion for no colorspace change: just copy the data,
  166380. * converting from separate-planes to interleaved representation.
  166381. */
  166382. METHODDEF(void)
  166383. null_convert2 (j_decompress_ptr cinfo,
  166384. JSAMPIMAGE input_buf, JDIMENSION input_row,
  166385. JSAMPARRAY output_buf, int num_rows)
  166386. {
  166387. register JSAMPROW inptr, outptr;
  166388. register JDIMENSION count;
  166389. register int num_components = cinfo->num_components;
  166390. JDIMENSION num_cols = cinfo->output_width;
  166391. int ci;
  166392. while (--num_rows >= 0) {
  166393. for (ci = 0; ci < num_components; ci++) {
  166394. inptr = input_buf[ci][input_row];
  166395. outptr = output_buf[0] + ci;
  166396. for (count = num_cols; count > 0; count--) {
  166397. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  166398. outptr += num_components;
  166399. }
  166400. }
  166401. input_row++;
  166402. output_buf++;
  166403. }
  166404. }
  166405. /*
  166406. * Color conversion for grayscale: just copy the data.
  166407. * This also works for YCbCr -> grayscale conversion, in which
  166408. * we just copy the Y (luminance) component and ignore chrominance.
  166409. */
  166410. METHODDEF(void)
  166411. grayscale_convert2 (j_decompress_ptr cinfo,
  166412. JSAMPIMAGE input_buf, JDIMENSION input_row,
  166413. JSAMPARRAY output_buf, int num_rows)
  166414. {
  166415. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  166416. num_rows, cinfo->output_width);
  166417. }
  166418. /*
  166419. * Convert grayscale to RGB: just duplicate the graylevel three times.
  166420. * This is provided to support applications that don't want to cope
  166421. * with grayscale as a separate case.
  166422. */
  166423. METHODDEF(void)
  166424. gray_rgb_convert (j_decompress_ptr cinfo,
  166425. JSAMPIMAGE input_buf, JDIMENSION input_row,
  166426. JSAMPARRAY output_buf, int num_rows)
  166427. {
  166428. register JSAMPROW inptr, outptr;
  166429. register JDIMENSION col;
  166430. JDIMENSION num_cols = cinfo->output_width;
  166431. while (--num_rows >= 0) {
  166432. inptr = input_buf[0][input_row++];
  166433. outptr = *output_buf++;
  166434. for (col = 0; col < num_cols; col++) {
  166435. /* We can dispense with GETJSAMPLE() here */
  166436. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  166437. outptr += RGB_PIXELSIZE;
  166438. }
  166439. }
  166440. }
  166441. /*
  166442. * Adobe-style YCCK->CMYK conversion.
  166443. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  166444. * conversion as above, while passing K (black) unchanged.
  166445. * We assume build_ycc_rgb_table has been called.
  166446. */
  166447. METHODDEF(void)
  166448. ycck_cmyk_convert (j_decompress_ptr cinfo,
  166449. JSAMPIMAGE input_buf, JDIMENSION input_row,
  166450. JSAMPARRAY output_buf, int num_rows)
  166451. {
  166452. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  166453. register int y, cb, cr;
  166454. register JSAMPROW outptr;
  166455. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  166456. register JDIMENSION col;
  166457. JDIMENSION num_cols = cinfo->output_width;
  166458. /* copy these pointers into registers if possible */
  166459. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  166460. register int * Crrtab = cconvert->Cr_r_tab;
  166461. register int * Cbbtab = cconvert->Cb_b_tab;
  166462. register INT32 * Crgtab = cconvert->Cr_g_tab;
  166463. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  166464. SHIFT_TEMPS
  166465. while (--num_rows >= 0) {
  166466. inptr0 = input_buf[0][input_row];
  166467. inptr1 = input_buf[1][input_row];
  166468. inptr2 = input_buf[2][input_row];
  166469. inptr3 = input_buf[3][input_row];
  166470. input_row++;
  166471. outptr = *output_buf++;
  166472. for (col = 0; col < num_cols; col++) {
  166473. y = GETJSAMPLE(inptr0[col]);
  166474. cb = GETJSAMPLE(inptr1[col]);
  166475. cr = GETJSAMPLE(inptr2[col]);
  166476. /* Range-limiting is essential due to noise introduced by DCT losses. */
  166477. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  166478. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  166479. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  166480. SCALEBITS)))];
  166481. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  166482. /* K passes through unchanged */
  166483. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  166484. outptr += 4;
  166485. }
  166486. }
  166487. }
  166488. /*
  166489. * Empty method for start_pass.
  166490. */
  166491. METHODDEF(void)
  166492. start_pass_dcolor (j_decompress_ptr)
  166493. {
  166494. /* no work needed */
  166495. }
  166496. /*
  166497. * Module initialization routine for output colorspace conversion.
  166498. */
  166499. GLOBAL(void)
  166500. jinit_color_deconverter (j_decompress_ptr cinfo)
  166501. {
  166502. my_cconvert_ptr2 cconvert;
  166503. int ci;
  166504. cconvert = (my_cconvert_ptr2)
  166505. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166506. SIZEOF(my_color_deconverter2));
  166507. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  166508. cconvert->pub.start_pass = start_pass_dcolor;
  166509. /* Make sure num_components agrees with jpeg_color_space */
  166510. switch (cinfo->jpeg_color_space) {
  166511. case JCS_GRAYSCALE:
  166512. if (cinfo->num_components != 1)
  166513. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  166514. break;
  166515. case JCS_RGB:
  166516. case JCS_YCbCr:
  166517. if (cinfo->num_components != 3)
  166518. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  166519. break;
  166520. case JCS_CMYK:
  166521. case JCS_YCCK:
  166522. if (cinfo->num_components != 4)
  166523. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  166524. break;
  166525. default: /* JCS_UNKNOWN can be anything */
  166526. if (cinfo->num_components < 1)
  166527. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  166528. break;
  166529. }
  166530. /* Set out_color_components and conversion method based on requested space.
  166531. * Also clear the component_needed flags for any unused components,
  166532. * so that earlier pipeline stages can avoid useless computation.
  166533. */
  166534. switch (cinfo->out_color_space) {
  166535. case JCS_GRAYSCALE:
  166536. cinfo->out_color_components = 1;
  166537. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  166538. cinfo->jpeg_color_space == JCS_YCbCr) {
  166539. cconvert->pub.color_convert = grayscale_convert2;
  166540. /* For color->grayscale conversion, only the Y (0) component is needed */
  166541. for (ci = 1; ci < cinfo->num_components; ci++)
  166542. cinfo->comp_info[ci].component_needed = FALSE;
  166543. } else
  166544. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  166545. break;
  166546. case JCS_RGB:
  166547. cinfo->out_color_components = RGB_PIXELSIZE;
  166548. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  166549. cconvert->pub.color_convert = ycc_rgb_convert;
  166550. build_ycc_rgb_table(cinfo);
  166551. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  166552. cconvert->pub.color_convert = gray_rgb_convert;
  166553. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  166554. cconvert->pub.color_convert = null_convert2;
  166555. } else
  166556. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  166557. break;
  166558. case JCS_CMYK:
  166559. cinfo->out_color_components = 4;
  166560. if (cinfo->jpeg_color_space == JCS_YCCK) {
  166561. cconvert->pub.color_convert = ycck_cmyk_convert;
  166562. build_ycc_rgb_table(cinfo);
  166563. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  166564. cconvert->pub.color_convert = null_convert2;
  166565. } else
  166566. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  166567. break;
  166568. default:
  166569. /* Permit null conversion to same output space */
  166570. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  166571. cinfo->out_color_components = cinfo->num_components;
  166572. cconvert->pub.color_convert = null_convert2;
  166573. } else /* unsupported non-null conversion */
  166574. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  166575. break;
  166576. }
  166577. if (cinfo->quantize_colors)
  166578. cinfo->output_components = 1; /* single colormapped output component */
  166579. else
  166580. cinfo->output_components = cinfo->out_color_components;
  166581. }
  166582. /*** End of inlined file: jdcolor.c ***/
  166583. #undef FIX
  166584. /*** Start of inlined file: jddctmgr.c ***/
  166585. #define JPEG_INTERNALS
  166586. /*
  166587. * The decompressor input side (jdinput.c) saves away the appropriate
  166588. * quantization table for each component at the start of the first scan
  166589. * involving that component. (This is necessary in order to correctly
  166590. * decode files that reuse Q-table slots.)
  166591. * When we are ready to make an output pass, the saved Q-table is converted
  166592. * to a multiplier table that will actually be used by the IDCT routine.
  166593. * The multiplier table contents are IDCT-method-dependent. To support
  166594. * application changes in IDCT method between scans, we can remake the
  166595. * multiplier tables if necessary.
  166596. * In buffered-image mode, the first output pass may occur before any data
  166597. * has been seen for some components, and thus before their Q-tables have
  166598. * been saved away. To handle this case, multiplier tables are preset
  166599. * to zeroes; the result of the IDCT will be a neutral gray level.
  166600. */
  166601. /* Private subobject for this module */
  166602. typedef struct {
  166603. struct jpeg_inverse_dct pub; /* public fields */
  166604. /* This array contains the IDCT method code that each multiplier table
  166605. * is currently set up for, or -1 if it's not yet set up.
  166606. * The actual multiplier tables are pointed to by dct_table in the
  166607. * per-component comp_info structures.
  166608. */
  166609. int cur_method[MAX_COMPONENTS];
  166610. } my_idct_controller;
  166611. typedef my_idct_controller * my_idct_ptr;
  166612. /* Allocated multiplier tables: big enough for any supported variant */
  166613. typedef union {
  166614. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  166615. #ifdef DCT_IFAST_SUPPORTED
  166616. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  166617. #endif
  166618. #ifdef DCT_FLOAT_SUPPORTED
  166619. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  166620. #endif
  166621. } multiplier_table;
  166622. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  166623. * so be sure to compile that code if either ISLOW or SCALING is requested.
  166624. */
  166625. #ifdef DCT_ISLOW_SUPPORTED
  166626. #define PROVIDE_ISLOW_TABLES
  166627. #else
  166628. #ifdef IDCT_SCALING_SUPPORTED
  166629. #define PROVIDE_ISLOW_TABLES
  166630. #endif
  166631. #endif
  166632. /*
  166633. * Prepare for an output pass.
  166634. * Here we select the proper IDCT routine for each component and build
  166635. * a matching multiplier table.
  166636. */
  166637. METHODDEF(void)
  166638. start_pass (j_decompress_ptr cinfo)
  166639. {
  166640. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  166641. int ci, i;
  166642. jpeg_component_info *compptr;
  166643. int method = 0;
  166644. inverse_DCT_method_ptr method_ptr = NULL;
  166645. JQUANT_TBL * qtbl;
  166646. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166647. ci++, compptr++) {
  166648. /* Select the proper IDCT routine for this component's scaling */
  166649. switch (compptr->DCT_scaled_size) {
  166650. #ifdef IDCT_SCALING_SUPPORTED
  166651. case 1:
  166652. method_ptr = jpeg_idct_1x1;
  166653. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  166654. break;
  166655. case 2:
  166656. method_ptr = jpeg_idct_2x2;
  166657. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  166658. break;
  166659. case 4:
  166660. method_ptr = jpeg_idct_4x4;
  166661. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  166662. break;
  166663. #endif
  166664. case DCTSIZE:
  166665. switch (cinfo->dct_method) {
  166666. #ifdef DCT_ISLOW_SUPPORTED
  166667. case JDCT_ISLOW:
  166668. method_ptr = jpeg_idct_islow;
  166669. method = JDCT_ISLOW;
  166670. break;
  166671. #endif
  166672. #ifdef DCT_IFAST_SUPPORTED
  166673. case JDCT_IFAST:
  166674. method_ptr = jpeg_idct_ifast;
  166675. method = JDCT_IFAST;
  166676. break;
  166677. #endif
  166678. #ifdef DCT_FLOAT_SUPPORTED
  166679. case JDCT_FLOAT:
  166680. method_ptr = jpeg_idct_float;
  166681. method = JDCT_FLOAT;
  166682. break;
  166683. #endif
  166684. default:
  166685. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166686. break;
  166687. }
  166688. break;
  166689. default:
  166690. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  166691. break;
  166692. }
  166693. idct->pub.inverse_DCT[ci] = method_ptr;
  166694. /* Create multiplier table from quant table.
  166695. * However, we can skip this if the component is uninteresting
  166696. * or if we already built the table. Also, if no quant table
  166697. * has yet been saved for the component, we leave the
  166698. * multiplier table all-zero; we'll be reading zeroes from the
  166699. * coefficient controller's buffer anyway.
  166700. */
  166701. if (! compptr->component_needed || idct->cur_method[ci] == method)
  166702. continue;
  166703. qtbl = compptr->quant_table;
  166704. if (qtbl == NULL) /* happens if no data yet for component */
  166705. continue;
  166706. idct->cur_method[ci] = method;
  166707. switch (method) {
  166708. #ifdef PROVIDE_ISLOW_TABLES
  166709. case JDCT_ISLOW:
  166710. {
  166711. /* For LL&M IDCT method, multipliers are equal to raw quantization
  166712. * coefficients, but are stored as ints to ensure access efficiency.
  166713. */
  166714. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  166715. for (i = 0; i < DCTSIZE2; i++) {
  166716. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  166717. }
  166718. }
  166719. break;
  166720. #endif
  166721. #ifdef DCT_IFAST_SUPPORTED
  166722. case JDCT_IFAST:
  166723. {
  166724. /* For AA&N IDCT method, multipliers are equal to quantization
  166725. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  166726. * scalefactor[0] = 1
  166727. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  166728. * For integer operation, the multiplier table is to be scaled by
  166729. * IFAST_SCALE_BITS.
  166730. */
  166731. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  166732. #define CONST_BITS 14
  166733. static const INT16 aanscales[DCTSIZE2] = {
  166734. /* precomputed values scaled up by 14 bits */
  166735. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  166736. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  166737. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  166738. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  166739. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  166740. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  166741. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  166742. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  166743. };
  166744. SHIFT_TEMPS
  166745. for (i = 0; i < DCTSIZE2; i++) {
  166746. ifmtbl[i] = (IFAST_MULT_TYPE)
  166747. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  166748. (INT32) aanscales[i]),
  166749. CONST_BITS-IFAST_SCALE_BITS);
  166750. }
  166751. }
  166752. break;
  166753. #endif
  166754. #ifdef DCT_FLOAT_SUPPORTED
  166755. case JDCT_FLOAT:
  166756. {
  166757. /* For float AA&N IDCT method, multipliers are equal to quantization
  166758. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  166759. * scalefactor[0] = 1
  166760. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  166761. */
  166762. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  166763. int row, col;
  166764. static const double aanscalefactor[DCTSIZE] = {
  166765. 1.0, 1.387039845, 1.306562965, 1.175875602,
  166766. 1.0, 0.785694958, 0.541196100, 0.275899379
  166767. };
  166768. i = 0;
  166769. for (row = 0; row < DCTSIZE; row++) {
  166770. for (col = 0; col < DCTSIZE; col++) {
  166771. fmtbl[i] = (FLOAT_MULT_TYPE)
  166772. ((double) qtbl->quantval[i] *
  166773. aanscalefactor[row] * aanscalefactor[col]);
  166774. i++;
  166775. }
  166776. }
  166777. }
  166778. break;
  166779. #endif
  166780. default:
  166781. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166782. break;
  166783. }
  166784. }
  166785. }
  166786. /*
  166787. * Initialize IDCT manager.
  166788. */
  166789. GLOBAL(void)
  166790. jinit_inverse_dct (j_decompress_ptr cinfo)
  166791. {
  166792. my_idct_ptr idct;
  166793. int ci;
  166794. jpeg_component_info *compptr;
  166795. idct = (my_idct_ptr)
  166796. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166797. SIZEOF(my_idct_controller));
  166798. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  166799. idct->pub.start_pass = start_pass;
  166800. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166801. ci++, compptr++) {
  166802. /* Allocate and pre-zero a multiplier table for each component */
  166803. compptr->dct_table =
  166804. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166805. SIZEOF(multiplier_table));
  166806. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  166807. /* Mark multiplier table not yet set up for any method */
  166808. idct->cur_method[ci] = -1;
  166809. }
  166810. }
  166811. /*** End of inlined file: jddctmgr.c ***/
  166812. #undef CONST_BITS
  166813. #undef ASSIGN_STATE
  166814. /*** Start of inlined file: jdhuff.c ***/
  166815. #define JPEG_INTERNALS
  166816. /*** Start of inlined file: jdhuff.h ***/
  166817. /* Short forms of external names for systems with brain-damaged linkers. */
  166818. #ifndef __jdhuff_h__
  166819. #define __jdhuff_h__
  166820. #ifdef NEED_SHORT_EXTERNAL_NAMES
  166821. #define jpeg_make_d_derived_tbl jMkDDerived
  166822. #define jpeg_fill_bit_buffer jFilBitBuf
  166823. #define jpeg_huff_decode jHufDecode
  166824. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  166825. /* Derived data constructed for each Huffman table */
  166826. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  166827. typedef struct {
  166828. /* Basic tables: (element [0] of each array is unused) */
  166829. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  166830. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  166831. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  166832. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  166833. * the smallest code of length k; so given a code of length k, the
  166834. * corresponding symbol is huffval[code + valoffset[k]]
  166835. */
  166836. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  166837. JHUFF_TBL *pub;
  166838. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  166839. * the input data stream. If the next Huffman code is no more
  166840. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  166841. * the corresponding symbol directly from these tables.
  166842. */
  166843. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  166844. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  166845. } d_derived_tbl;
  166846. /* Expand a Huffman table definition into the derived format */
  166847. EXTERN(void) jpeg_make_d_derived_tbl
  166848. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  166849. d_derived_tbl ** pdtbl));
  166850. /*
  166851. * Fetching the next N bits from the input stream is a time-critical operation
  166852. * for the Huffman decoders. We implement it with a combination of inline
  166853. * macros and out-of-line subroutines. Note that N (the number of bits
  166854. * demanded at one time) never exceeds 15 for JPEG use.
  166855. *
  166856. * We read source bytes into get_buffer and dole out bits as needed.
  166857. * If get_buffer already contains enough bits, they are fetched in-line
  166858. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  166859. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  166860. * as full as possible (not just to the number of bits needed; this
  166861. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  166862. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  166863. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  166864. * at least the requested number of bits --- dummy zeroes are inserted if
  166865. * necessary.
  166866. */
  166867. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  166868. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  166869. /* If long is > 32 bits on your machine, and shifting/masking longs is
  166870. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  166871. * appropriately should be a win. Unfortunately we can't define the size
  166872. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  166873. * because not all machines measure sizeof in 8-bit bytes.
  166874. */
  166875. typedef struct { /* Bitreading state saved across MCUs */
  166876. bit_buf_type get_buffer; /* current bit-extraction buffer */
  166877. int bits_left; /* # of unused bits in it */
  166878. } bitread_perm_state;
  166879. typedef struct { /* Bitreading working state within an MCU */
  166880. /* Current data source location */
  166881. /* We need a copy, rather than munging the original, in case of suspension */
  166882. const JOCTET * next_input_byte; /* => next byte to read from source */
  166883. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  166884. /* Bit input buffer --- note these values are kept in register variables,
  166885. * not in this struct, inside the inner loops.
  166886. */
  166887. bit_buf_type get_buffer; /* current bit-extraction buffer */
  166888. int bits_left; /* # of unused bits in it */
  166889. /* Pointer needed by jpeg_fill_bit_buffer. */
  166890. j_decompress_ptr cinfo; /* back link to decompress master record */
  166891. } bitread_working_state;
  166892. /* Macros to declare and load/save bitread local variables. */
  166893. #define BITREAD_STATE_VARS \
  166894. register bit_buf_type get_buffer; \
  166895. register int bits_left; \
  166896. bitread_working_state br_state
  166897. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  166898. br_state.cinfo = cinfop; \
  166899. br_state.next_input_byte = cinfop->src->next_input_byte; \
  166900. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  166901. get_buffer = permstate.get_buffer; \
  166902. bits_left = permstate.bits_left;
  166903. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  166904. cinfop->src->next_input_byte = br_state.next_input_byte; \
  166905. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  166906. permstate.get_buffer = get_buffer; \
  166907. permstate.bits_left = bits_left
  166908. /*
  166909. * These macros provide the in-line portion of bit fetching.
  166910. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  166911. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  166912. * The variables get_buffer and bits_left are assumed to be locals,
  166913. * but the state struct might not be (jpeg_huff_decode needs this).
  166914. * CHECK_BIT_BUFFER(state,n,action);
  166915. * Ensure there are N bits in get_buffer; if suspend, take action.
  166916. * val = GET_BITS(n);
  166917. * Fetch next N bits.
  166918. * val = PEEK_BITS(n);
  166919. * Fetch next N bits without removing them from the buffer.
  166920. * DROP_BITS(n);
  166921. * Discard next N bits.
  166922. * The value N should be a simple variable, not an expression, because it
  166923. * is evaluated multiple times.
  166924. */
  166925. #define CHECK_BIT_BUFFER(state,nbits,action) \
  166926. { if (bits_left < (nbits)) { \
  166927. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  166928. { action; } \
  166929. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  166930. #define GET_BITS(nbits) \
  166931. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  166932. #define PEEK_BITS(nbits) \
  166933. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  166934. #define DROP_BITS(nbits) \
  166935. (bits_left -= (nbits))
  166936. /* Load up the bit buffer to a depth of at least nbits */
  166937. EXTERN(boolean) jpeg_fill_bit_buffer
  166938. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  166939. register int bits_left, int nbits));
  166940. /*
  166941. * Code for extracting next Huffman-coded symbol from input bit stream.
  166942. * Again, this is time-critical and we make the main paths be macros.
  166943. *
  166944. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  166945. * without looping. Usually, more than 95% of the Huffman codes will be 8
  166946. * or fewer bits long. The few overlength codes are handled with a loop,
  166947. * which need not be inline code.
  166948. *
  166949. * Notes about the HUFF_DECODE macro:
  166950. * 1. Near the end of the data segment, we may fail to get enough bits
  166951. * for a lookahead. In that case, we do it the hard way.
  166952. * 2. If the lookahead table contains no entry, the next code must be
  166953. * more than HUFF_LOOKAHEAD bits long.
  166954. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  166955. */
  166956. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  166957. { register int nb, look; \
  166958. if (bits_left < HUFF_LOOKAHEAD) { \
  166959. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  166960. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  166961. if (bits_left < HUFF_LOOKAHEAD) { \
  166962. nb = 1; goto slowlabel; \
  166963. } \
  166964. } \
  166965. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  166966. if ((nb = htbl->look_nbits[look]) != 0) { \
  166967. DROP_BITS(nb); \
  166968. result = htbl->look_sym[look]; \
  166969. } else { \
  166970. nb = HUFF_LOOKAHEAD+1; \
  166971. slowlabel: \
  166972. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  166973. { failaction; } \
  166974. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  166975. } \
  166976. }
  166977. /* Out-of-line case for Huffman code fetching */
  166978. EXTERN(int) jpeg_huff_decode
  166979. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  166980. register int bits_left, d_derived_tbl * htbl, int min_bits));
  166981. #endif
  166982. /*** End of inlined file: jdhuff.h ***/
  166983. /* Declarations shared with jdphuff.c */
  166984. /*
  166985. * Expanded entropy decoder object for Huffman decoding.
  166986. *
  166987. * The savable_state subrecord contains fields that change within an MCU,
  166988. * but must not be updated permanently until we complete the MCU.
  166989. */
  166990. typedef struct {
  166991. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  166992. } savable_state2;
  166993. /* This macro is to work around compilers with missing or broken
  166994. * structure assignment. You'll need to fix this code if you have
  166995. * such a compiler and you change MAX_COMPS_IN_SCAN.
  166996. */
  166997. #ifndef NO_STRUCT_ASSIGN
  166998. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  166999. #else
  167000. #if MAX_COMPS_IN_SCAN == 4
  167001. #define ASSIGN_STATE(dest,src) \
  167002. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  167003. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  167004. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  167005. (dest).last_dc_val[3] = (src).last_dc_val[3])
  167006. #endif
  167007. #endif
  167008. typedef struct {
  167009. struct jpeg_entropy_decoder pub; /* public fields */
  167010. /* These fields are loaded into local variables at start of each MCU.
  167011. * In case of suspension, we exit WITHOUT updating them.
  167012. */
  167013. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  167014. savable_state2 saved; /* Other state at start of MCU */
  167015. /* These fields are NOT loaded into local working state. */
  167016. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  167017. /* Pointers to derived tables (these workspaces have image lifespan) */
  167018. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  167019. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  167020. /* Precalculated info set up by start_pass for use in decode_mcu: */
  167021. /* Pointers to derived tables to be used for each block within an MCU */
  167022. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  167023. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  167024. /* Whether we care about the DC and AC coefficient values for each block */
  167025. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  167026. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  167027. } huff_entropy_decoder2;
  167028. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  167029. /*
  167030. * Initialize for a Huffman-compressed scan.
  167031. */
  167032. METHODDEF(void)
  167033. start_pass_huff_decoder (j_decompress_ptr cinfo)
  167034. {
  167035. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  167036. int ci, blkn, dctbl, actbl;
  167037. jpeg_component_info * compptr;
  167038. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  167039. * This ought to be an error condition, but we make it a warning because
  167040. * there are some baseline files out there with all zeroes in these bytes.
  167041. */
  167042. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  167043. cinfo->Ah != 0 || cinfo->Al != 0)
  167044. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  167045. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167046. compptr = cinfo->cur_comp_info[ci];
  167047. dctbl = compptr->dc_tbl_no;
  167048. actbl = compptr->ac_tbl_no;
  167049. /* Compute derived values for Huffman tables */
  167050. /* We may do this more than once for a table, but it's not expensive */
  167051. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  167052. & entropy->dc_derived_tbls[dctbl]);
  167053. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  167054. & entropy->ac_derived_tbls[actbl]);
  167055. /* Initialize DC predictions to 0 */
  167056. entropy->saved.last_dc_val[ci] = 0;
  167057. }
  167058. /* Precalculate decoding info for each block in an MCU of this scan */
  167059. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  167060. ci = cinfo->MCU_membership[blkn];
  167061. compptr = cinfo->cur_comp_info[ci];
  167062. /* Precalculate which table to use for each block */
  167063. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  167064. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  167065. /* Decide whether we really care about the coefficient values */
  167066. if (compptr->component_needed) {
  167067. entropy->dc_needed[blkn] = TRUE;
  167068. /* we don't need the ACs if producing a 1/8th-size image */
  167069. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  167070. } else {
  167071. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  167072. }
  167073. }
  167074. /* Initialize bitread state variables */
  167075. entropy->bitstate.bits_left = 0;
  167076. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  167077. entropy->pub.insufficient_data = FALSE;
  167078. /* Initialize restart counter */
  167079. entropy->restarts_to_go = cinfo->restart_interval;
  167080. }
  167081. /*
  167082. * Compute the derived values for a Huffman table.
  167083. * This routine also performs some validation checks on the table.
  167084. *
  167085. * Note this is also used by jdphuff.c.
  167086. */
  167087. GLOBAL(void)
  167088. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  167089. d_derived_tbl ** pdtbl)
  167090. {
  167091. JHUFF_TBL *htbl;
  167092. d_derived_tbl *dtbl;
  167093. int p, i, l, si, numsymbols;
  167094. int lookbits, ctr;
  167095. char huffsize[257];
  167096. unsigned int huffcode[257];
  167097. unsigned int code;
  167098. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  167099. * paralleling the order of the symbols themselves in htbl->huffval[].
  167100. */
  167101. /* Find the input Huffman table */
  167102. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  167103. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  167104. htbl =
  167105. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  167106. if (htbl == NULL)
  167107. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  167108. /* Allocate a workspace if we haven't already done so. */
  167109. if (*pdtbl == NULL)
  167110. *pdtbl = (d_derived_tbl *)
  167111. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167112. SIZEOF(d_derived_tbl));
  167113. dtbl = *pdtbl;
  167114. dtbl->pub = htbl; /* fill in back link */
  167115. /* Figure C.1: make table of Huffman code length for each symbol */
  167116. p = 0;
  167117. for (l = 1; l <= 16; l++) {
  167118. i = (int) htbl->bits[l];
  167119. if (i < 0 || p + i > 256) /* protect against table overrun */
  167120. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  167121. while (i--)
  167122. huffsize[p++] = (char) l;
  167123. }
  167124. huffsize[p] = 0;
  167125. numsymbols = p;
  167126. /* Figure C.2: generate the codes themselves */
  167127. /* We also validate that the counts represent a legal Huffman code tree. */
  167128. code = 0;
  167129. si = huffsize[0];
  167130. p = 0;
  167131. while (huffsize[p]) {
  167132. while (((int) huffsize[p]) == si) {
  167133. huffcode[p++] = code;
  167134. code++;
  167135. }
  167136. /* code is now 1 more than the last code used for codelength si; but
  167137. * it must still fit in si bits, since no code is allowed to be all ones.
  167138. */
  167139. if (((INT32) code) >= (((INT32) 1) << si))
  167140. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  167141. code <<= 1;
  167142. si++;
  167143. }
  167144. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  167145. p = 0;
  167146. for (l = 1; l <= 16; l++) {
  167147. if (htbl->bits[l]) {
  167148. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  167149. * minus the minimum code of length l
  167150. */
  167151. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  167152. p += htbl->bits[l];
  167153. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  167154. } else {
  167155. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  167156. }
  167157. }
  167158. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  167159. /* Compute lookahead tables to speed up decoding.
  167160. * First we set all the table entries to 0, indicating "too long";
  167161. * then we iterate through the Huffman codes that are short enough and
  167162. * fill in all the entries that correspond to bit sequences starting
  167163. * with that code.
  167164. */
  167165. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  167166. p = 0;
  167167. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  167168. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  167169. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  167170. /* Generate left-justified code followed by all possible bit sequences */
  167171. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  167172. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  167173. dtbl->look_nbits[lookbits] = l;
  167174. dtbl->look_sym[lookbits] = htbl->huffval[p];
  167175. lookbits++;
  167176. }
  167177. }
  167178. }
  167179. /* Validate symbols as being reasonable.
  167180. * For AC tables, we make no check, but accept all byte values 0..255.
  167181. * For DC tables, we require the symbols to be in range 0..15.
  167182. * (Tighter bounds could be applied depending on the data depth and mode,
  167183. * but this is sufficient to ensure safe decoding.)
  167184. */
  167185. if (isDC) {
  167186. for (i = 0; i < numsymbols; i++) {
  167187. int sym = htbl->huffval[i];
  167188. if (sym < 0 || sym > 15)
  167189. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  167190. }
  167191. }
  167192. }
  167193. /*
  167194. * Out-of-line code for bit fetching (shared with jdphuff.c).
  167195. * See jdhuff.h for info about usage.
  167196. * Note: current values of get_buffer and bits_left are passed as parameters,
  167197. * but are returned in the corresponding fields of the state struct.
  167198. *
  167199. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  167200. * of get_buffer to be used. (On machines with wider words, an even larger
  167201. * buffer could be used.) However, on some machines 32-bit shifts are
  167202. * quite slow and take time proportional to the number of places shifted.
  167203. * (This is true with most PC compilers, for instance.) In this case it may
  167204. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  167205. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  167206. */
  167207. #ifdef SLOW_SHIFT_32
  167208. #define MIN_GET_BITS 15 /* minimum allowable value */
  167209. #else
  167210. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  167211. #endif
  167212. GLOBAL(boolean)
  167213. jpeg_fill_bit_buffer (bitread_working_state * state,
  167214. register bit_buf_type get_buffer, register int bits_left,
  167215. int nbits)
  167216. /* Load up the bit buffer to a depth of at least nbits */
  167217. {
  167218. /* Copy heavily used state fields into locals (hopefully registers) */
  167219. register const JOCTET * next_input_byte = state->next_input_byte;
  167220. register size_t bytes_in_buffer = state->bytes_in_buffer;
  167221. j_decompress_ptr cinfo = state->cinfo;
  167222. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  167223. /* (It is assumed that no request will be for more than that many bits.) */
  167224. /* We fail to do so only if we hit a marker or are forced to suspend. */
  167225. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  167226. while (bits_left < MIN_GET_BITS) {
  167227. register int c;
  167228. /* Attempt to read a byte */
  167229. if (bytes_in_buffer == 0) {
  167230. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  167231. return FALSE;
  167232. next_input_byte = cinfo->src->next_input_byte;
  167233. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  167234. }
  167235. bytes_in_buffer--;
  167236. c = GETJOCTET(*next_input_byte++);
  167237. /* If it's 0xFF, check and discard stuffed zero byte */
  167238. if (c == 0xFF) {
  167239. /* Loop here to discard any padding FF's on terminating marker,
  167240. * so that we can save a valid unread_marker value. NOTE: we will
  167241. * accept multiple FF's followed by a 0 as meaning a single FF data
  167242. * byte. This data pattern is not valid according to the standard.
  167243. */
  167244. do {
  167245. if (bytes_in_buffer == 0) {
  167246. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  167247. return FALSE;
  167248. next_input_byte = cinfo->src->next_input_byte;
  167249. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  167250. }
  167251. bytes_in_buffer--;
  167252. c = GETJOCTET(*next_input_byte++);
  167253. } while (c == 0xFF);
  167254. if (c == 0) {
  167255. /* Found FF/00, which represents an FF data byte */
  167256. c = 0xFF;
  167257. } else {
  167258. /* Oops, it's actually a marker indicating end of compressed data.
  167259. * Save the marker code for later use.
  167260. * Fine point: it might appear that we should save the marker into
  167261. * bitread working state, not straight into permanent state. But
  167262. * once we have hit a marker, we cannot need to suspend within the
  167263. * current MCU, because we will read no more bytes from the data
  167264. * source. So it is OK to update permanent state right away.
  167265. */
  167266. cinfo->unread_marker = c;
  167267. /* See if we need to insert some fake zero bits. */
  167268. goto no_more_bytes;
  167269. }
  167270. }
  167271. /* OK, load c into get_buffer */
  167272. get_buffer = (get_buffer << 8) | c;
  167273. bits_left += 8;
  167274. } /* end while */
  167275. } else {
  167276. no_more_bytes:
  167277. /* We get here if we've read the marker that terminates the compressed
  167278. * data segment. There should be enough bits in the buffer register
  167279. * to satisfy the request; if so, no problem.
  167280. */
  167281. if (nbits > bits_left) {
  167282. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  167283. * the data stream, so that we can produce some kind of image.
  167284. * We use a nonvolatile flag to ensure that only one warning message
  167285. * appears per data segment.
  167286. */
  167287. if (! cinfo->entropy->insufficient_data) {
  167288. WARNMS(cinfo, JWRN_HIT_MARKER);
  167289. cinfo->entropy->insufficient_data = TRUE;
  167290. }
  167291. /* Fill the buffer with zero bits */
  167292. get_buffer <<= MIN_GET_BITS - bits_left;
  167293. bits_left = MIN_GET_BITS;
  167294. }
  167295. }
  167296. /* Unload the local registers */
  167297. state->next_input_byte = next_input_byte;
  167298. state->bytes_in_buffer = bytes_in_buffer;
  167299. state->get_buffer = get_buffer;
  167300. state->bits_left = bits_left;
  167301. return TRUE;
  167302. }
  167303. /*
  167304. * Out-of-line code for Huffman code decoding.
  167305. * See jdhuff.h for info about usage.
  167306. */
  167307. GLOBAL(int)
  167308. jpeg_huff_decode (bitread_working_state * state,
  167309. register bit_buf_type get_buffer, register int bits_left,
  167310. d_derived_tbl * htbl, int min_bits)
  167311. {
  167312. register int l = min_bits;
  167313. register INT32 code;
  167314. /* HUFF_DECODE has determined that the code is at least min_bits */
  167315. /* bits long, so fetch that many bits in one swoop. */
  167316. CHECK_BIT_BUFFER(*state, l, return -1);
  167317. code = GET_BITS(l);
  167318. /* Collect the rest of the Huffman code one bit at a time. */
  167319. /* This is per Figure F.16 in the JPEG spec. */
  167320. while (code > htbl->maxcode[l]) {
  167321. code <<= 1;
  167322. CHECK_BIT_BUFFER(*state, 1, return -1);
  167323. code |= GET_BITS(1);
  167324. l++;
  167325. }
  167326. /* Unload the local registers */
  167327. state->get_buffer = get_buffer;
  167328. state->bits_left = bits_left;
  167329. /* With garbage input we may reach the sentinel value l = 17. */
  167330. if (l > 16) {
  167331. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  167332. return 0; /* fake a zero as the safest result */
  167333. }
  167334. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  167335. }
  167336. /*
  167337. * Check for a restart marker & resynchronize decoder.
  167338. * Returns FALSE if must suspend.
  167339. */
  167340. LOCAL(boolean)
  167341. process_restart (j_decompress_ptr cinfo)
  167342. {
  167343. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  167344. int ci;
  167345. /* Throw away any unused bits remaining in bit buffer; */
  167346. /* include any full bytes in next_marker's count of discarded bytes */
  167347. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  167348. entropy->bitstate.bits_left = 0;
  167349. /* Advance past the RSTn marker */
  167350. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  167351. return FALSE;
  167352. /* Re-initialize DC predictions to 0 */
  167353. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  167354. entropy->saved.last_dc_val[ci] = 0;
  167355. /* Reset restart counter */
  167356. entropy->restarts_to_go = cinfo->restart_interval;
  167357. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  167358. * against a marker. In that case we will end up treating the next data
  167359. * segment as empty, and we can avoid producing bogus output pixels by
  167360. * leaving the flag set.
  167361. */
  167362. if (cinfo->unread_marker == 0)
  167363. entropy->pub.insufficient_data = FALSE;
  167364. return TRUE;
  167365. }
  167366. /*
  167367. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  167368. * The coefficients are reordered from zigzag order into natural array order,
  167369. * but are not dequantized.
  167370. *
  167371. * The i'th block of the MCU is stored into the block pointed to by
  167372. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  167373. * (Wholesale zeroing is usually a little faster than retail...)
  167374. *
  167375. * Returns FALSE if data source requested suspension. In that case no
  167376. * changes have been made to permanent state. (Exception: some output
  167377. * coefficients may already have been assigned. This is harmless for
  167378. * this module, since we'll just re-assign them on the next call.)
  167379. */
  167380. METHODDEF(boolean)
  167381. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  167382. {
  167383. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  167384. int blkn;
  167385. BITREAD_STATE_VARS;
  167386. savable_state2 state;
  167387. /* Process restart marker if needed; may have to suspend */
  167388. if (cinfo->restart_interval) {
  167389. if (entropy->restarts_to_go == 0)
  167390. if (! process_restart(cinfo))
  167391. return FALSE;
  167392. }
  167393. /* If we've run out of data, just leave the MCU set to zeroes.
  167394. * This way, we return uniform gray for the remainder of the segment.
  167395. */
  167396. if (! entropy->pub.insufficient_data) {
  167397. /* Load up working state */
  167398. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  167399. ASSIGN_STATE(state, entropy->saved);
  167400. /* Outer loop handles each block in the MCU */
  167401. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  167402. JBLOCKROW block = MCU_data[blkn];
  167403. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  167404. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  167405. register int s, k, r;
  167406. /* Decode a single block's worth of coefficients */
  167407. /* Section F.2.2.1: decode the DC coefficient difference */
  167408. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  167409. if (s) {
  167410. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  167411. r = GET_BITS(s);
  167412. s = HUFF_EXTEND(r, s);
  167413. }
  167414. if (entropy->dc_needed[blkn]) {
  167415. /* Convert DC difference to actual value, update last_dc_val */
  167416. int ci = cinfo->MCU_membership[blkn];
  167417. s += state.last_dc_val[ci];
  167418. state.last_dc_val[ci] = s;
  167419. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  167420. (*block)[0] = (JCOEF) s;
  167421. }
  167422. if (entropy->ac_needed[blkn]) {
  167423. /* Section F.2.2.2: decode the AC coefficients */
  167424. /* Since zeroes are skipped, output area must be cleared beforehand */
  167425. for (k = 1; k < DCTSIZE2; k++) {
  167426. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  167427. r = s >> 4;
  167428. s &= 15;
  167429. if (s) {
  167430. k += r;
  167431. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  167432. r = GET_BITS(s);
  167433. s = HUFF_EXTEND(r, s);
  167434. /* Output coefficient in natural (dezigzagged) order.
  167435. * Note: the extra entries in jpeg_natural_order[] will save us
  167436. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  167437. */
  167438. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  167439. } else {
  167440. if (r != 15)
  167441. break;
  167442. k += 15;
  167443. }
  167444. }
  167445. } else {
  167446. /* Section F.2.2.2: decode the AC coefficients */
  167447. /* In this path we just discard the values */
  167448. for (k = 1; k < DCTSIZE2; k++) {
  167449. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  167450. r = s >> 4;
  167451. s &= 15;
  167452. if (s) {
  167453. k += r;
  167454. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  167455. DROP_BITS(s);
  167456. } else {
  167457. if (r != 15)
  167458. break;
  167459. k += 15;
  167460. }
  167461. }
  167462. }
  167463. }
  167464. /* Completed MCU, so update state */
  167465. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  167466. ASSIGN_STATE(entropy->saved, state);
  167467. }
  167468. /* Account for restart interval (no-op if not using restarts) */
  167469. entropy->restarts_to_go--;
  167470. return TRUE;
  167471. }
  167472. /*
  167473. * Module initialization routine for Huffman entropy decoding.
  167474. */
  167475. GLOBAL(void)
  167476. jinit_huff_decoder (j_decompress_ptr cinfo)
  167477. {
  167478. huff_entropy_ptr2 entropy;
  167479. int i;
  167480. entropy = (huff_entropy_ptr2)
  167481. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167482. SIZEOF(huff_entropy_decoder2));
  167483. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  167484. entropy->pub.start_pass = start_pass_huff_decoder;
  167485. entropy->pub.decode_mcu = decode_mcu;
  167486. /* Mark tables unallocated */
  167487. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167488. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  167489. }
  167490. }
  167491. /*** End of inlined file: jdhuff.c ***/
  167492. /*** Start of inlined file: jdinput.c ***/
  167493. #define JPEG_INTERNALS
  167494. /* Private state */
  167495. typedef struct {
  167496. struct jpeg_input_controller pub; /* public fields */
  167497. boolean inheaders; /* TRUE until first SOS is reached */
  167498. } my_input_controller;
  167499. typedef my_input_controller * my_inputctl_ptr;
  167500. /* Forward declarations */
  167501. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  167502. /*
  167503. * Routines to calculate various quantities related to the size of the image.
  167504. */
  167505. LOCAL(void)
  167506. initial_setup2 (j_decompress_ptr cinfo)
  167507. /* Called once, when first SOS marker is reached */
  167508. {
  167509. int ci;
  167510. jpeg_component_info *compptr;
  167511. /* Make sure image isn't bigger than I can handle */
  167512. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  167513. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  167514. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  167515. /* For now, precision must match compiled-in value... */
  167516. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  167517. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  167518. /* Check that number of components won't exceed internal array sizes */
  167519. if (cinfo->num_components > MAX_COMPONENTS)
  167520. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  167521. MAX_COMPONENTS);
  167522. /* Compute maximum sampling factors; check factor validity */
  167523. cinfo->max_h_samp_factor = 1;
  167524. cinfo->max_v_samp_factor = 1;
  167525. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167526. ci++, compptr++) {
  167527. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  167528. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  167529. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  167530. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  167531. compptr->h_samp_factor);
  167532. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  167533. compptr->v_samp_factor);
  167534. }
  167535. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  167536. * In the full decompressor, this will be overridden by jdmaster.c;
  167537. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  167538. */
  167539. cinfo->min_DCT_scaled_size = DCTSIZE;
  167540. /* Compute dimensions of components */
  167541. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167542. ci++, compptr++) {
  167543. compptr->DCT_scaled_size = DCTSIZE;
  167544. /* Size in DCT blocks */
  167545. compptr->width_in_blocks = (JDIMENSION)
  167546. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  167547. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  167548. compptr->height_in_blocks = (JDIMENSION)
  167549. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  167550. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  167551. /* downsampled_width and downsampled_height will also be overridden by
  167552. * jdmaster.c if we are doing full decompression. The transcoder library
  167553. * doesn't use these values, but the calling application might.
  167554. */
  167555. /* Size in samples */
  167556. compptr->downsampled_width = (JDIMENSION)
  167557. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  167558. (long) cinfo->max_h_samp_factor);
  167559. compptr->downsampled_height = (JDIMENSION)
  167560. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  167561. (long) cinfo->max_v_samp_factor);
  167562. /* Mark component needed, until color conversion says otherwise */
  167563. compptr->component_needed = TRUE;
  167564. /* Mark no quantization table yet saved for component */
  167565. compptr->quant_table = NULL;
  167566. }
  167567. /* Compute number of fully interleaved MCU rows. */
  167568. cinfo->total_iMCU_rows = (JDIMENSION)
  167569. jdiv_round_up((long) cinfo->image_height,
  167570. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  167571. /* Decide whether file contains multiple scans */
  167572. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  167573. cinfo->inputctl->has_multiple_scans = TRUE;
  167574. else
  167575. cinfo->inputctl->has_multiple_scans = FALSE;
  167576. }
  167577. LOCAL(void)
  167578. per_scan_setup2 (j_decompress_ptr cinfo)
  167579. /* Do computations that are needed before processing a JPEG scan */
  167580. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  167581. {
  167582. int ci, mcublks, tmp;
  167583. jpeg_component_info *compptr;
  167584. if (cinfo->comps_in_scan == 1) {
  167585. /* Noninterleaved (single-component) scan */
  167586. compptr = cinfo->cur_comp_info[0];
  167587. /* Overall image size in MCUs */
  167588. cinfo->MCUs_per_row = compptr->width_in_blocks;
  167589. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  167590. /* For noninterleaved scan, always one block per MCU */
  167591. compptr->MCU_width = 1;
  167592. compptr->MCU_height = 1;
  167593. compptr->MCU_blocks = 1;
  167594. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  167595. compptr->last_col_width = 1;
  167596. /* For noninterleaved scans, it is convenient to define last_row_height
  167597. * as the number of block rows present in the last iMCU row.
  167598. */
  167599. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  167600. if (tmp == 0) tmp = compptr->v_samp_factor;
  167601. compptr->last_row_height = tmp;
  167602. /* Prepare array describing MCU composition */
  167603. cinfo->blocks_in_MCU = 1;
  167604. cinfo->MCU_membership[0] = 0;
  167605. } else {
  167606. /* Interleaved (multi-component) scan */
  167607. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  167608. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  167609. MAX_COMPS_IN_SCAN);
  167610. /* Overall image size in MCUs */
  167611. cinfo->MCUs_per_row = (JDIMENSION)
  167612. jdiv_round_up((long) cinfo->image_width,
  167613. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  167614. cinfo->MCU_rows_in_scan = (JDIMENSION)
  167615. jdiv_round_up((long) cinfo->image_height,
  167616. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  167617. cinfo->blocks_in_MCU = 0;
  167618. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167619. compptr = cinfo->cur_comp_info[ci];
  167620. /* Sampling factors give # of blocks of component in each MCU */
  167621. compptr->MCU_width = compptr->h_samp_factor;
  167622. compptr->MCU_height = compptr->v_samp_factor;
  167623. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  167624. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  167625. /* Figure number of non-dummy blocks in last MCU column & row */
  167626. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  167627. if (tmp == 0) tmp = compptr->MCU_width;
  167628. compptr->last_col_width = tmp;
  167629. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  167630. if (tmp == 0) tmp = compptr->MCU_height;
  167631. compptr->last_row_height = tmp;
  167632. /* Prepare array describing MCU composition */
  167633. mcublks = compptr->MCU_blocks;
  167634. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  167635. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  167636. while (mcublks-- > 0) {
  167637. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  167638. }
  167639. }
  167640. }
  167641. }
  167642. /*
  167643. * Save away a copy of the Q-table referenced by each component present
  167644. * in the current scan, unless already saved during a prior scan.
  167645. *
  167646. * In a multiple-scan JPEG file, the encoder could assign different components
  167647. * the same Q-table slot number, but change table definitions between scans
  167648. * so that each component uses a different Q-table. (The IJG encoder is not
  167649. * currently capable of doing this, but other encoders might.) Since we want
  167650. * to be able to dequantize all the components at the end of the file, this
  167651. * means that we have to save away the table actually used for each component.
  167652. * We do this by copying the table at the start of the first scan containing
  167653. * the component.
  167654. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  167655. * slot between scans of a component using that slot. If the encoder does so
  167656. * anyway, this decoder will simply use the Q-table values that were current
  167657. * at the start of the first scan for the component.
  167658. *
  167659. * The decompressor output side looks only at the saved quant tables,
  167660. * not at the current Q-table slots.
  167661. */
  167662. LOCAL(void)
  167663. latch_quant_tables (j_decompress_ptr cinfo)
  167664. {
  167665. int ci, qtblno;
  167666. jpeg_component_info *compptr;
  167667. JQUANT_TBL * qtbl;
  167668. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167669. compptr = cinfo->cur_comp_info[ci];
  167670. /* No work if we already saved Q-table for this component */
  167671. if (compptr->quant_table != NULL)
  167672. continue;
  167673. /* Make sure specified quantization table is present */
  167674. qtblno = compptr->quant_tbl_no;
  167675. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  167676. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  167677. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  167678. /* OK, save away the quantization table */
  167679. qtbl = (JQUANT_TBL *)
  167680. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167681. SIZEOF(JQUANT_TBL));
  167682. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  167683. compptr->quant_table = qtbl;
  167684. }
  167685. }
  167686. /*
  167687. * Initialize the input modules to read a scan of compressed data.
  167688. * The first call to this is done by jdmaster.c after initializing
  167689. * the entire decompressor (during jpeg_start_decompress).
  167690. * Subsequent calls come from consume_markers, below.
  167691. */
  167692. METHODDEF(void)
  167693. start_input_pass2 (j_decompress_ptr cinfo)
  167694. {
  167695. per_scan_setup2(cinfo);
  167696. latch_quant_tables(cinfo);
  167697. (*cinfo->entropy->start_pass) (cinfo);
  167698. (*cinfo->coef->start_input_pass) (cinfo);
  167699. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  167700. }
  167701. /*
  167702. * Finish up after inputting a compressed-data scan.
  167703. * This is called by the coefficient controller after it's read all
  167704. * the expected data of the scan.
  167705. */
  167706. METHODDEF(void)
  167707. finish_input_pass (j_decompress_ptr cinfo)
  167708. {
  167709. cinfo->inputctl->consume_input = consume_markers;
  167710. }
  167711. /*
  167712. * Read JPEG markers before, between, or after compressed-data scans.
  167713. * Change state as necessary when a new scan is reached.
  167714. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  167715. *
  167716. * The consume_input method pointer points either here or to the
  167717. * coefficient controller's consume_data routine, depending on whether
  167718. * we are reading a compressed data segment or inter-segment markers.
  167719. */
  167720. METHODDEF(int)
  167721. consume_markers (j_decompress_ptr cinfo)
  167722. {
  167723. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  167724. int val;
  167725. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  167726. return JPEG_REACHED_EOI;
  167727. val = (*cinfo->marker->read_markers) (cinfo);
  167728. switch (val) {
  167729. case JPEG_REACHED_SOS: /* Found SOS */
  167730. if (inputctl->inheaders) { /* 1st SOS */
  167731. initial_setup2(cinfo);
  167732. inputctl->inheaders = FALSE;
  167733. /* Note: start_input_pass must be called by jdmaster.c
  167734. * before any more input can be consumed. jdapimin.c is
  167735. * responsible for enforcing this sequencing.
  167736. */
  167737. } else { /* 2nd or later SOS marker */
  167738. if (! inputctl->pub.has_multiple_scans)
  167739. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  167740. start_input_pass2(cinfo);
  167741. }
  167742. break;
  167743. case JPEG_REACHED_EOI: /* Found EOI */
  167744. inputctl->pub.eoi_reached = TRUE;
  167745. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  167746. if (cinfo->marker->saw_SOF)
  167747. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  167748. } else {
  167749. /* Prevent infinite loop in coef ctlr's decompress_data routine
  167750. * if user set output_scan_number larger than number of scans.
  167751. */
  167752. if (cinfo->output_scan_number > cinfo->input_scan_number)
  167753. cinfo->output_scan_number = cinfo->input_scan_number;
  167754. }
  167755. break;
  167756. case JPEG_SUSPENDED:
  167757. break;
  167758. }
  167759. return val;
  167760. }
  167761. /*
  167762. * Reset state to begin a fresh datastream.
  167763. */
  167764. METHODDEF(void)
  167765. reset_input_controller (j_decompress_ptr cinfo)
  167766. {
  167767. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  167768. inputctl->pub.consume_input = consume_markers;
  167769. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  167770. inputctl->pub.eoi_reached = FALSE;
  167771. inputctl->inheaders = TRUE;
  167772. /* Reset other modules */
  167773. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  167774. (*cinfo->marker->reset_marker_reader) (cinfo);
  167775. /* Reset progression state -- would be cleaner if entropy decoder did this */
  167776. cinfo->coef_bits = NULL;
  167777. }
  167778. /*
  167779. * Initialize the input controller module.
  167780. * This is called only once, when the decompression object is created.
  167781. */
  167782. GLOBAL(void)
  167783. jinit_input_controller (j_decompress_ptr cinfo)
  167784. {
  167785. my_inputctl_ptr inputctl;
  167786. /* Create subobject in permanent pool */
  167787. inputctl = (my_inputctl_ptr)
  167788. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  167789. SIZEOF(my_input_controller));
  167790. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  167791. /* Initialize method pointers */
  167792. inputctl->pub.consume_input = consume_markers;
  167793. inputctl->pub.reset_input_controller = reset_input_controller;
  167794. inputctl->pub.start_input_pass = start_input_pass2;
  167795. inputctl->pub.finish_input_pass = finish_input_pass;
  167796. /* Initialize state: can't use reset_input_controller since we don't
  167797. * want to try to reset other modules yet.
  167798. */
  167799. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  167800. inputctl->pub.eoi_reached = FALSE;
  167801. inputctl->inheaders = TRUE;
  167802. }
  167803. /*** End of inlined file: jdinput.c ***/
  167804. /*** Start of inlined file: jdmainct.c ***/
  167805. #define JPEG_INTERNALS
  167806. /*
  167807. * In the current system design, the main buffer need never be a full-image
  167808. * buffer; any full-height buffers will be found inside the coefficient or
  167809. * postprocessing controllers. Nonetheless, the main controller is not
  167810. * trivial. Its responsibility is to provide context rows for upsampling/
  167811. * rescaling, and doing this in an efficient fashion is a bit tricky.
  167812. *
  167813. * Postprocessor input data is counted in "row groups". A row group
  167814. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  167815. * sample rows of each component. (We require DCT_scaled_size values to be
  167816. * chosen such that these numbers are integers. In practice DCT_scaled_size
  167817. * values will likely be powers of two, so we actually have the stronger
  167818. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  167819. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  167820. * row group (times any additional scale factor that the upsampler is
  167821. * applying).
  167822. *
  167823. * The coefficient controller will deliver data to us one iMCU row at a time;
  167824. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  167825. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  167826. * to one row of MCUs when the image is fully interleaved.) Note that the
  167827. * number of sample rows varies across components, but the number of row
  167828. * groups does not. Some garbage sample rows may be included in the last iMCU
  167829. * row at the bottom of the image.
  167830. *
  167831. * Depending on the vertical scaling algorithm used, the upsampler may need
  167832. * access to the sample row(s) above and below its current input row group.
  167833. * The upsampler is required to set need_context_rows TRUE at global selection
  167834. * time if so. When need_context_rows is FALSE, this controller can simply
  167835. * obtain one iMCU row at a time from the coefficient controller and dole it
  167836. * out as row groups to the postprocessor.
  167837. *
  167838. * When need_context_rows is TRUE, this controller guarantees that the buffer
  167839. * passed to postprocessing contains at least one row group's worth of samples
  167840. * above and below the row group(s) being processed. Note that the context
  167841. * rows "above" the first passed row group appear at negative row offsets in
  167842. * the passed buffer. At the top and bottom of the image, the required
  167843. * context rows are manufactured by duplicating the first or last real sample
  167844. * row; this avoids having special cases in the upsampling inner loops.
  167845. *
  167846. * The amount of context is fixed at one row group just because that's a
  167847. * convenient number for this controller to work with. The existing
  167848. * upsamplers really only need one sample row of context. An upsampler
  167849. * supporting arbitrary output rescaling might wish for more than one row
  167850. * group of context when shrinking the image; tough, we don't handle that.
  167851. * (This is justified by the assumption that downsizing will be handled mostly
  167852. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  167853. * the upsample step needn't be much less than one.)
  167854. *
  167855. * To provide the desired context, we have to retain the last two row groups
  167856. * of one iMCU row while reading in the next iMCU row. (The last row group
  167857. * can't be processed until we have another row group for its below-context,
  167858. * and so we have to save the next-to-last group too for its above-context.)
  167859. * We could do this most simply by copying data around in our buffer, but
  167860. * that'd be very slow. We can avoid copying any data by creating a rather
  167861. * strange pointer structure. Here's how it works. We allocate a workspace
  167862. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  167863. * of row groups per iMCU row). We create two sets of redundant pointers to
  167864. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  167865. * pointer lists look like this:
  167866. * M+1 M-1
  167867. * master pointer --> 0 master pointer --> 0
  167868. * 1 1
  167869. * ... ...
  167870. * M-3 M-3
  167871. * M-2 M
  167872. * M-1 M+1
  167873. * M M-2
  167874. * M+1 M-1
  167875. * 0 0
  167876. * We read alternate iMCU rows using each master pointer; thus the last two
  167877. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  167878. * The pointer lists are set up so that the required context rows appear to
  167879. * be adjacent to the proper places when we pass the pointer lists to the
  167880. * upsampler.
  167881. *
  167882. * The above pictures describe the normal state of the pointer lists.
  167883. * At top and bottom of the image, we diddle the pointer lists to duplicate
  167884. * the first or last sample row as necessary (this is cheaper than copying
  167885. * sample rows around).
  167886. *
  167887. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  167888. * situation each iMCU row provides only one row group so the buffering logic
  167889. * must be different (eg, we must read two iMCU rows before we can emit the
  167890. * first row group). For now, we simply do not support providing context
  167891. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  167892. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  167893. * want it quick and dirty, so a context-free upsampler is sufficient.
  167894. */
  167895. /* Private buffer controller object */
  167896. typedef struct {
  167897. struct jpeg_d_main_controller pub; /* public fields */
  167898. /* Pointer to allocated workspace (M or M+2 row groups). */
  167899. JSAMPARRAY buffer[MAX_COMPONENTS];
  167900. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  167901. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  167902. /* Remaining fields are only used in the context case. */
  167903. /* These are the master pointers to the funny-order pointer lists. */
  167904. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  167905. int whichptr; /* indicates which pointer set is now in use */
  167906. int context_state; /* process_data state machine status */
  167907. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  167908. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  167909. } my_main_controller4;
  167910. typedef my_main_controller4 * my_main_ptr4;
  167911. /* context_state values: */
  167912. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  167913. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  167914. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  167915. /* Forward declarations */
  167916. METHODDEF(void) process_data_simple_main2
  167917. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  167918. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  167919. METHODDEF(void) process_data_context_main
  167920. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  167921. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  167922. #ifdef QUANT_2PASS_SUPPORTED
  167923. METHODDEF(void) process_data_crank_post
  167924. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  167925. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  167926. #endif
  167927. LOCAL(void)
  167928. alloc_funny_pointers (j_decompress_ptr cinfo)
  167929. /* Allocate space for the funny pointer lists.
  167930. * This is done only once, not once per pass.
  167931. */
  167932. {
  167933. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  167934. int ci, rgroup;
  167935. int M = cinfo->min_DCT_scaled_size;
  167936. jpeg_component_info *compptr;
  167937. JSAMPARRAY xbuf;
  167938. /* Get top-level space for component array pointers.
  167939. * We alloc both arrays with one call to save a few cycles.
  167940. */
  167941. main_->xbuffer[0] = (JSAMPIMAGE)
  167942. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167943. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  167944. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  167945. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167946. ci++, compptr++) {
  167947. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  167948. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  167949. /* Get space for pointer lists --- M+4 row groups in each list.
  167950. * We alloc both pointer lists with one call to save a few cycles.
  167951. */
  167952. xbuf = (JSAMPARRAY)
  167953. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167954. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  167955. xbuf += rgroup; /* want one row group at negative offsets */
  167956. main_->xbuffer[0][ci] = xbuf;
  167957. xbuf += rgroup * (M + 4);
  167958. main_->xbuffer[1][ci] = xbuf;
  167959. }
  167960. }
  167961. LOCAL(void)
  167962. make_funny_pointers (j_decompress_ptr cinfo)
  167963. /* Create the funny pointer lists discussed in the comments above.
  167964. * The actual workspace is already allocated (in main->buffer),
  167965. * and the space for the pointer lists is allocated too.
  167966. * This routine just fills in the curiously ordered lists.
  167967. * This will be repeated at the beginning of each pass.
  167968. */
  167969. {
  167970. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  167971. int ci, i, rgroup;
  167972. int M = cinfo->min_DCT_scaled_size;
  167973. jpeg_component_info *compptr;
  167974. JSAMPARRAY buf, xbuf0, xbuf1;
  167975. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167976. ci++, compptr++) {
  167977. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  167978. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  167979. xbuf0 = main_->xbuffer[0][ci];
  167980. xbuf1 = main_->xbuffer[1][ci];
  167981. /* First copy the workspace pointers as-is */
  167982. buf = main_->buffer[ci];
  167983. for (i = 0; i < rgroup * (M + 2); i++) {
  167984. xbuf0[i] = xbuf1[i] = buf[i];
  167985. }
  167986. /* In the second list, put the last four row groups in swapped order */
  167987. for (i = 0; i < rgroup * 2; i++) {
  167988. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  167989. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  167990. }
  167991. /* The wraparound pointers at top and bottom will be filled later
  167992. * (see set_wraparound_pointers, below). Initially we want the "above"
  167993. * pointers to duplicate the first actual data line. This only needs
  167994. * to happen in xbuffer[0].
  167995. */
  167996. for (i = 0; i < rgroup; i++) {
  167997. xbuf0[i - rgroup] = xbuf0[0];
  167998. }
  167999. }
  168000. }
  168001. LOCAL(void)
  168002. set_wraparound_pointers (j_decompress_ptr cinfo)
  168003. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  168004. * This changes the pointer list state from top-of-image to the normal state.
  168005. */
  168006. {
  168007. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  168008. int ci, i, rgroup;
  168009. int M = cinfo->min_DCT_scaled_size;
  168010. jpeg_component_info *compptr;
  168011. JSAMPARRAY xbuf0, xbuf1;
  168012. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168013. ci++, compptr++) {
  168014. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  168015. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  168016. xbuf0 = main_->xbuffer[0][ci];
  168017. xbuf1 = main_->xbuffer[1][ci];
  168018. for (i = 0; i < rgroup; i++) {
  168019. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  168020. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  168021. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  168022. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  168023. }
  168024. }
  168025. }
  168026. LOCAL(void)
  168027. set_bottom_pointers (j_decompress_ptr cinfo)
  168028. /* Change the pointer lists to duplicate the last sample row at the bottom
  168029. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  168030. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  168031. */
  168032. {
  168033. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  168034. int ci, i, rgroup, iMCUheight, rows_left;
  168035. jpeg_component_info *compptr;
  168036. JSAMPARRAY xbuf;
  168037. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168038. ci++, compptr++) {
  168039. /* Count sample rows in one iMCU row and in one row group */
  168040. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  168041. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  168042. /* Count nondummy sample rows remaining for this component */
  168043. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  168044. if (rows_left == 0) rows_left = iMCUheight;
  168045. /* Count nondummy row groups. Should get same answer for each component,
  168046. * so we need only do it once.
  168047. */
  168048. if (ci == 0) {
  168049. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  168050. }
  168051. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  168052. * last partial rowgroup and ensures at least one full rowgroup of context.
  168053. */
  168054. xbuf = main_->xbuffer[main_->whichptr][ci];
  168055. for (i = 0; i < rgroup * 2; i++) {
  168056. xbuf[rows_left + i] = xbuf[rows_left-1];
  168057. }
  168058. }
  168059. }
  168060. /*
  168061. * Initialize for a processing pass.
  168062. */
  168063. METHODDEF(void)
  168064. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  168065. {
  168066. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  168067. switch (pass_mode) {
  168068. case JBUF_PASS_THRU:
  168069. if (cinfo->upsample->need_context_rows) {
  168070. main_->pub.process_data = process_data_context_main;
  168071. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  168072. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  168073. main_->context_state = CTX_PREPARE_FOR_IMCU;
  168074. main_->iMCU_row_ctr = 0;
  168075. } else {
  168076. /* Simple case with no context needed */
  168077. main_->pub.process_data = process_data_simple_main2;
  168078. }
  168079. main_->buffer_full = FALSE; /* Mark buffer empty */
  168080. main_->rowgroup_ctr = 0;
  168081. break;
  168082. #ifdef QUANT_2PASS_SUPPORTED
  168083. case JBUF_CRANK_DEST:
  168084. /* For last pass of 2-pass quantization, just crank the postprocessor */
  168085. main_->pub.process_data = process_data_crank_post;
  168086. break;
  168087. #endif
  168088. default:
  168089. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  168090. break;
  168091. }
  168092. }
  168093. /*
  168094. * Process some data.
  168095. * This handles the simple case where no context is required.
  168096. */
  168097. METHODDEF(void)
  168098. process_data_simple_main2 (j_decompress_ptr cinfo,
  168099. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  168100. JDIMENSION out_rows_avail)
  168101. {
  168102. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  168103. JDIMENSION rowgroups_avail;
  168104. /* Read input data if we haven't filled the main buffer yet */
  168105. if (! main_->buffer_full) {
  168106. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  168107. return; /* suspension forced, can do nothing more */
  168108. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  168109. }
  168110. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  168111. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  168112. /* Note: at the bottom of the image, we may pass extra garbage row groups
  168113. * to the postprocessor. The postprocessor has to check for bottom
  168114. * of image anyway (at row resolution), so no point in us doing it too.
  168115. */
  168116. /* Feed the postprocessor */
  168117. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  168118. &main_->rowgroup_ctr, rowgroups_avail,
  168119. output_buf, out_row_ctr, out_rows_avail);
  168120. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  168121. if (main_->rowgroup_ctr >= rowgroups_avail) {
  168122. main_->buffer_full = FALSE;
  168123. main_->rowgroup_ctr = 0;
  168124. }
  168125. }
  168126. /*
  168127. * Process some data.
  168128. * This handles the case where context rows must be provided.
  168129. */
  168130. METHODDEF(void)
  168131. process_data_context_main (j_decompress_ptr cinfo,
  168132. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  168133. JDIMENSION out_rows_avail)
  168134. {
  168135. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  168136. /* Read input data if we haven't filled the main buffer yet */
  168137. if (! main_->buffer_full) {
  168138. if (! (*cinfo->coef->decompress_data) (cinfo,
  168139. main_->xbuffer[main_->whichptr]))
  168140. return; /* suspension forced, can do nothing more */
  168141. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  168142. main_->iMCU_row_ctr++; /* count rows received */
  168143. }
  168144. /* Postprocessor typically will not swallow all the input data it is handed
  168145. * in one call (due to filling the output buffer first). Must be prepared
  168146. * to exit and restart. This switch lets us keep track of how far we got.
  168147. * Note that each case falls through to the next on successful completion.
  168148. */
  168149. switch (main_->context_state) {
  168150. case CTX_POSTPONED_ROW:
  168151. /* Call postprocessor using previously set pointers for postponed row */
  168152. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  168153. &main_->rowgroup_ctr, main_->rowgroups_avail,
  168154. output_buf, out_row_ctr, out_rows_avail);
  168155. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  168156. return; /* Need to suspend */
  168157. main_->context_state = CTX_PREPARE_FOR_IMCU;
  168158. if (*out_row_ctr >= out_rows_avail)
  168159. return; /* Postprocessor exactly filled output buf */
  168160. /*FALLTHROUGH*/
  168161. case CTX_PREPARE_FOR_IMCU:
  168162. /* Prepare to process first M-1 row groups of this iMCU row */
  168163. main_->rowgroup_ctr = 0;
  168164. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  168165. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  168166. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  168167. */
  168168. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  168169. set_bottom_pointers(cinfo);
  168170. main_->context_state = CTX_PROCESS_IMCU;
  168171. /*FALLTHROUGH*/
  168172. case CTX_PROCESS_IMCU:
  168173. /* Call postprocessor using previously set pointers */
  168174. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  168175. &main_->rowgroup_ctr, main_->rowgroups_avail,
  168176. output_buf, out_row_ctr, out_rows_avail);
  168177. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  168178. return; /* Need to suspend */
  168179. /* After the first iMCU, change wraparound pointers to normal state */
  168180. if (main_->iMCU_row_ctr == 1)
  168181. set_wraparound_pointers(cinfo);
  168182. /* Prepare to load new iMCU row using other xbuffer list */
  168183. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  168184. main_->buffer_full = FALSE;
  168185. /* Still need to process last row group of this iMCU row, */
  168186. /* which is saved at index M+1 of the other xbuffer */
  168187. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  168188. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  168189. main_->context_state = CTX_POSTPONED_ROW;
  168190. }
  168191. }
  168192. /*
  168193. * Process some data.
  168194. * Final pass of two-pass quantization: just call the postprocessor.
  168195. * Source data will be the postprocessor controller's internal buffer.
  168196. */
  168197. #ifdef QUANT_2PASS_SUPPORTED
  168198. METHODDEF(void)
  168199. process_data_crank_post (j_decompress_ptr cinfo,
  168200. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  168201. JDIMENSION out_rows_avail)
  168202. {
  168203. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  168204. (JDIMENSION *) NULL, (JDIMENSION) 0,
  168205. output_buf, out_row_ctr, out_rows_avail);
  168206. }
  168207. #endif /* QUANT_2PASS_SUPPORTED */
  168208. /*
  168209. * Initialize main buffer controller.
  168210. */
  168211. GLOBAL(void)
  168212. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  168213. {
  168214. my_main_ptr4 main_;
  168215. int ci, rgroup, ngroups;
  168216. jpeg_component_info *compptr;
  168217. main_ = (my_main_ptr4)
  168218. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168219. SIZEOF(my_main_controller4));
  168220. cinfo->main = (struct jpeg_d_main_controller *) main_;
  168221. main_->pub.start_pass = start_pass_main2;
  168222. if (need_full_buffer) /* shouldn't happen */
  168223. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  168224. /* Allocate the workspace.
  168225. * ngroups is the number of row groups we need.
  168226. */
  168227. if (cinfo->upsample->need_context_rows) {
  168228. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  168229. ERREXIT(cinfo, JERR_NOTIMPL);
  168230. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  168231. ngroups = cinfo->min_DCT_scaled_size + 2;
  168232. } else {
  168233. ngroups = cinfo->min_DCT_scaled_size;
  168234. }
  168235. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168236. ci++, compptr++) {
  168237. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  168238. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  168239. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  168240. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168241. compptr->width_in_blocks * compptr->DCT_scaled_size,
  168242. (JDIMENSION) (rgroup * ngroups));
  168243. }
  168244. }
  168245. /*** End of inlined file: jdmainct.c ***/
  168246. /*** Start of inlined file: jdmarker.c ***/
  168247. #define JPEG_INTERNALS
  168248. /* Private state */
  168249. typedef struct {
  168250. struct jpeg_marker_reader pub; /* public fields */
  168251. /* Application-overridable marker processing methods */
  168252. jpeg_marker_parser_method process_COM;
  168253. jpeg_marker_parser_method process_APPn[16];
  168254. /* Limit on marker data length to save for each marker type */
  168255. unsigned int length_limit_COM;
  168256. unsigned int length_limit_APPn[16];
  168257. /* Status of COM/APPn marker saving */
  168258. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  168259. unsigned int bytes_read; /* data bytes read so far in marker */
  168260. /* Note: cur_marker is not linked into marker_list until it's all read. */
  168261. } my_marker_reader;
  168262. typedef my_marker_reader * my_marker_ptr2;
  168263. /*
  168264. * Macros for fetching data from the data source module.
  168265. *
  168266. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  168267. * the current restart point; we update them only when we have reached a
  168268. * suitable place to restart if a suspension occurs.
  168269. */
  168270. /* Declare and initialize local copies of input pointer/count */
  168271. #define INPUT_VARS(cinfo) \
  168272. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  168273. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  168274. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  168275. /* Unload the local copies --- do this only at a restart boundary */
  168276. #define INPUT_SYNC(cinfo) \
  168277. ( datasrc->next_input_byte = next_input_byte, \
  168278. datasrc->bytes_in_buffer = bytes_in_buffer )
  168279. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  168280. #define INPUT_RELOAD(cinfo) \
  168281. ( next_input_byte = datasrc->next_input_byte, \
  168282. bytes_in_buffer = datasrc->bytes_in_buffer )
  168283. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  168284. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  168285. * but we must reload the local copies after a successful fill.
  168286. */
  168287. #define MAKE_BYTE_AVAIL(cinfo,action) \
  168288. if (bytes_in_buffer == 0) { \
  168289. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  168290. { action; } \
  168291. INPUT_RELOAD(cinfo); \
  168292. }
  168293. /* Read a byte into variable V.
  168294. * If must suspend, take the specified action (typically "return FALSE").
  168295. */
  168296. #define INPUT_BYTE(cinfo,V,action) \
  168297. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  168298. bytes_in_buffer--; \
  168299. V = GETJOCTET(*next_input_byte++); )
  168300. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  168301. * V should be declared unsigned int or perhaps INT32.
  168302. */
  168303. #define INPUT_2BYTES(cinfo,V,action) \
  168304. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  168305. bytes_in_buffer--; \
  168306. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  168307. MAKE_BYTE_AVAIL(cinfo,action); \
  168308. bytes_in_buffer--; \
  168309. V += GETJOCTET(*next_input_byte++); )
  168310. /*
  168311. * Routines to process JPEG markers.
  168312. *
  168313. * Entry condition: JPEG marker itself has been read and its code saved
  168314. * in cinfo->unread_marker; input restart point is just after the marker.
  168315. *
  168316. * Exit: if return TRUE, have read and processed any parameters, and have
  168317. * updated the restart point to point after the parameters.
  168318. * If return FALSE, was forced to suspend before reaching end of
  168319. * marker parameters; restart point has not been moved. Same routine
  168320. * will be called again after application supplies more input data.
  168321. *
  168322. * This approach to suspension assumes that all of a marker's parameters
  168323. * can fit into a single input bufferload. This should hold for "normal"
  168324. * markers. Some COM/APPn markers might have large parameter segments
  168325. * that might not fit. If we are simply dropping such a marker, we use
  168326. * skip_input_data to get past it, and thereby put the problem on the
  168327. * source manager's shoulders. If we are saving the marker's contents
  168328. * into memory, we use a slightly different convention: when forced to
  168329. * suspend, the marker processor updates the restart point to the end of
  168330. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  168331. * On resumption, cinfo->unread_marker still contains the marker code,
  168332. * but the data source will point to the next chunk of marker data.
  168333. * The marker processor must retain internal state to deal with this.
  168334. *
  168335. * Note that we don't bother to avoid duplicate trace messages if a
  168336. * suspension occurs within marker parameters. Other side effects
  168337. * require more care.
  168338. */
  168339. LOCAL(boolean)
  168340. get_soi (j_decompress_ptr cinfo)
  168341. /* Process an SOI marker */
  168342. {
  168343. int i;
  168344. TRACEMS(cinfo, 1, JTRC_SOI);
  168345. if (cinfo->marker->saw_SOI)
  168346. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  168347. /* Reset all parameters that are defined to be reset by SOI */
  168348. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  168349. cinfo->arith_dc_L[i] = 0;
  168350. cinfo->arith_dc_U[i] = 1;
  168351. cinfo->arith_ac_K[i] = 5;
  168352. }
  168353. cinfo->restart_interval = 0;
  168354. /* Set initial assumptions for colorspace etc */
  168355. cinfo->jpeg_color_space = JCS_UNKNOWN;
  168356. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  168357. cinfo->saw_JFIF_marker = FALSE;
  168358. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  168359. cinfo->JFIF_minor_version = 1;
  168360. cinfo->density_unit = 0;
  168361. cinfo->X_density = 1;
  168362. cinfo->Y_density = 1;
  168363. cinfo->saw_Adobe_marker = FALSE;
  168364. cinfo->Adobe_transform = 0;
  168365. cinfo->marker->saw_SOI = TRUE;
  168366. return TRUE;
  168367. }
  168368. LOCAL(boolean)
  168369. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  168370. /* Process a SOFn marker */
  168371. {
  168372. INT32 length;
  168373. int c, ci;
  168374. jpeg_component_info * compptr;
  168375. INPUT_VARS(cinfo);
  168376. cinfo->progressive_mode = is_prog;
  168377. cinfo->arith_code = is_arith;
  168378. INPUT_2BYTES(cinfo, length, return FALSE);
  168379. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  168380. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  168381. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  168382. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  168383. length -= 8;
  168384. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  168385. (int) cinfo->image_width, (int) cinfo->image_height,
  168386. cinfo->num_components);
  168387. if (cinfo->marker->saw_SOF)
  168388. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  168389. /* We don't support files in which the image height is initially specified */
  168390. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  168391. /* might as well have a general sanity check. */
  168392. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  168393. || cinfo->num_components <= 0)
  168394. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  168395. if (length != (cinfo->num_components * 3))
  168396. ERREXIT(cinfo, JERR_BAD_LENGTH);
  168397. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  168398. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  168399. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168400. cinfo->num_components * SIZEOF(jpeg_component_info));
  168401. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168402. ci++, compptr++) {
  168403. compptr->component_index = ci;
  168404. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  168405. INPUT_BYTE(cinfo, c, return FALSE);
  168406. compptr->h_samp_factor = (c >> 4) & 15;
  168407. compptr->v_samp_factor = (c ) & 15;
  168408. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  168409. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  168410. compptr->component_id, compptr->h_samp_factor,
  168411. compptr->v_samp_factor, compptr->quant_tbl_no);
  168412. }
  168413. cinfo->marker->saw_SOF = TRUE;
  168414. INPUT_SYNC(cinfo);
  168415. return TRUE;
  168416. }
  168417. LOCAL(boolean)
  168418. get_sos (j_decompress_ptr cinfo)
  168419. /* Process a SOS marker */
  168420. {
  168421. INT32 length;
  168422. int i, ci, n, c, cc;
  168423. jpeg_component_info * compptr;
  168424. INPUT_VARS(cinfo);
  168425. if (! cinfo->marker->saw_SOF)
  168426. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  168427. INPUT_2BYTES(cinfo, length, return FALSE);
  168428. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  168429. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  168430. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  168431. ERREXIT(cinfo, JERR_BAD_LENGTH);
  168432. cinfo->comps_in_scan = n;
  168433. /* Collect the component-spec parameters */
  168434. for (i = 0; i < n; i++) {
  168435. INPUT_BYTE(cinfo, cc, return FALSE);
  168436. INPUT_BYTE(cinfo, c, return FALSE);
  168437. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168438. ci++, compptr++) {
  168439. if (cc == compptr->component_id)
  168440. goto id_found;
  168441. }
  168442. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  168443. id_found:
  168444. cinfo->cur_comp_info[i] = compptr;
  168445. compptr->dc_tbl_no = (c >> 4) & 15;
  168446. compptr->ac_tbl_no = (c ) & 15;
  168447. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  168448. compptr->dc_tbl_no, compptr->ac_tbl_no);
  168449. }
  168450. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  168451. INPUT_BYTE(cinfo, c, return FALSE);
  168452. cinfo->Ss = c;
  168453. INPUT_BYTE(cinfo, c, return FALSE);
  168454. cinfo->Se = c;
  168455. INPUT_BYTE(cinfo, c, return FALSE);
  168456. cinfo->Ah = (c >> 4) & 15;
  168457. cinfo->Al = (c ) & 15;
  168458. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  168459. cinfo->Ah, cinfo->Al);
  168460. /* Prepare to scan data & restart markers */
  168461. cinfo->marker->next_restart_num = 0;
  168462. /* Count another SOS marker */
  168463. cinfo->input_scan_number++;
  168464. INPUT_SYNC(cinfo);
  168465. return TRUE;
  168466. }
  168467. #ifdef D_ARITH_CODING_SUPPORTED
  168468. LOCAL(boolean)
  168469. get_dac (j_decompress_ptr cinfo)
  168470. /* Process a DAC marker */
  168471. {
  168472. INT32 length;
  168473. int index, val;
  168474. INPUT_VARS(cinfo);
  168475. INPUT_2BYTES(cinfo, length, return FALSE);
  168476. length -= 2;
  168477. while (length > 0) {
  168478. INPUT_BYTE(cinfo, index, return FALSE);
  168479. INPUT_BYTE(cinfo, val, return FALSE);
  168480. length -= 2;
  168481. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  168482. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  168483. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  168484. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  168485. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  168486. } else { /* define DC table */
  168487. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  168488. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  168489. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  168490. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  168491. }
  168492. }
  168493. if (length != 0)
  168494. ERREXIT(cinfo, JERR_BAD_LENGTH);
  168495. INPUT_SYNC(cinfo);
  168496. return TRUE;
  168497. }
  168498. #else /* ! D_ARITH_CODING_SUPPORTED */
  168499. #define get_dac(cinfo) skip_variable(cinfo)
  168500. #endif /* D_ARITH_CODING_SUPPORTED */
  168501. LOCAL(boolean)
  168502. get_dht (j_decompress_ptr cinfo)
  168503. /* Process a DHT marker */
  168504. {
  168505. INT32 length;
  168506. UINT8 bits[17];
  168507. UINT8 huffval[256];
  168508. int i, index, count;
  168509. JHUFF_TBL **htblptr;
  168510. INPUT_VARS(cinfo);
  168511. INPUT_2BYTES(cinfo, length, return FALSE);
  168512. length -= 2;
  168513. while (length > 16) {
  168514. INPUT_BYTE(cinfo, index, return FALSE);
  168515. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  168516. bits[0] = 0;
  168517. count = 0;
  168518. for (i = 1; i <= 16; i++) {
  168519. INPUT_BYTE(cinfo, bits[i], return FALSE);
  168520. count += bits[i];
  168521. }
  168522. length -= 1 + 16;
  168523. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  168524. bits[1], bits[2], bits[3], bits[4],
  168525. bits[5], bits[6], bits[7], bits[8]);
  168526. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  168527. bits[9], bits[10], bits[11], bits[12],
  168528. bits[13], bits[14], bits[15], bits[16]);
  168529. /* Here we just do minimal validation of the counts to avoid walking
  168530. * off the end of our table space. jdhuff.c will check more carefully.
  168531. */
  168532. if (count > 256 || ((INT32) count) > length)
  168533. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  168534. for (i = 0; i < count; i++)
  168535. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  168536. length -= count;
  168537. if (index & 0x10) { /* AC table definition */
  168538. index -= 0x10;
  168539. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  168540. } else { /* DC table definition */
  168541. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  168542. }
  168543. if (index < 0 || index >= NUM_HUFF_TBLS)
  168544. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  168545. if (*htblptr == NULL)
  168546. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  168547. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  168548. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  168549. }
  168550. if (length != 0)
  168551. ERREXIT(cinfo, JERR_BAD_LENGTH);
  168552. INPUT_SYNC(cinfo);
  168553. return TRUE;
  168554. }
  168555. LOCAL(boolean)
  168556. get_dqt (j_decompress_ptr cinfo)
  168557. /* Process a DQT marker */
  168558. {
  168559. INT32 length;
  168560. int n, i, prec;
  168561. unsigned int tmp;
  168562. JQUANT_TBL *quant_ptr;
  168563. INPUT_VARS(cinfo);
  168564. INPUT_2BYTES(cinfo, length, return FALSE);
  168565. length -= 2;
  168566. while (length > 0) {
  168567. INPUT_BYTE(cinfo, n, return FALSE);
  168568. prec = n >> 4;
  168569. n &= 0x0F;
  168570. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  168571. if (n >= NUM_QUANT_TBLS)
  168572. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  168573. if (cinfo->quant_tbl_ptrs[n] == NULL)
  168574. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  168575. quant_ptr = cinfo->quant_tbl_ptrs[n];
  168576. for (i = 0; i < DCTSIZE2; i++) {
  168577. if (prec)
  168578. INPUT_2BYTES(cinfo, tmp, return FALSE);
  168579. else
  168580. INPUT_BYTE(cinfo, tmp, return FALSE);
  168581. /* We convert the zigzag-order table to natural array order. */
  168582. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  168583. }
  168584. if (cinfo->err->trace_level >= 2) {
  168585. for (i = 0; i < DCTSIZE2; i += 8) {
  168586. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  168587. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  168588. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  168589. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  168590. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  168591. }
  168592. }
  168593. length -= DCTSIZE2+1;
  168594. if (prec) length -= DCTSIZE2;
  168595. }
  168596. if (length != 0)
  168597. ERREXIT(cinfo, JERR_BAD_LENGTH);
  168598. INPUT_SYNC(cinfo);
  168599. return TRUE;
  168600. }
  168601. LOCAL(boolean)
  168602. get_dri (j_decompress_ptr cinfo)
  168603. /* Process a DRI marker */
  168604. {
  168605. INT32 length;
  168606. unsigned int tmp;
  168607. INPUT_VARS(cinfo);
  168608. INPUT_2BYTES(cinfo, length, return FALSE);
  168609. if (length != 4)
  168610. ERREXIT(cinfo, JERR_BAD_LENGTH);
  168611. INPUT_2BYTES(cinfo, tmp, return FALSE);
  168612. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  168613. cinfo->restart_interval = tmp;
  168614. INPUT_SYNC(cinfo);
  168615. return TRUE;
  168616. }
  168617. /*
  168618. * Routines for processing APPn and COM markers.
  168619. * These are either saved in memory or discarded, per application request.
  168620. * APP0 and APP14 are specially checked to see if they are
  168621. * JFIF and Adobe markers, respectively.
  168622. */
  168623. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  168624. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  168625. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  168626. LOCAL(void)
  168627. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  168628. unsigned int datalen, INT32 remaining)
  168629. /* Examine first few bytes from an APP0.
  168630. * Take appropriate action if it is a JFIF marker.
  168631. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  168632. */
  168633. {
  168634. INT32 totallen = (INT32) datalen + remaining;
  168635. if (datalen >= APP0_DATA_LEN &&
  168636. GETJOCTET(data[0]) == 0x4A &&
  168637. GETJOCTET(data[1]) == 0x46 &&
  168638. GETJOCTET(data[2]) == 0x49 &&
  168639. GETJOCTET(data[3]) == 0x46 &&
  168640. GETJOCTET(data[4]) == 0) {
  168641. /* Found JFIF APP0 marker: save info */
  168642. cinfo->saw_JFIF_marker = TRUE;
  168643. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  168644. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  168645. cinfo->density_unit = GETJOCTET(data[7]);
  168646. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  168647. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  168648. /* Check version.
  168649. * Major version must be 1, anything else signals an incompatible change.
  168650. * (We used to treat this as an error, but now it's a nonfatal warning,
  168651. * because some bozo at Hijaak couldn't read the spec.)
  168652. * Minor version should be 0..2, but process anyway if newer.
  168653. */
  168654. if (cinfo->JFIF_major_version != 1)
  168655. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  168656. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  168657. /* Generate trace messages */
  168658. TRACEMS5(cinfo, 1, JTRC_JFIF,
  168659. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  168660. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  168661. /* Validate thumbnail dimensions and issue appropriate messages */
  168662. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  168663. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  168664. GETJOCTET(data[12]), GETJOCTET(data[13]));
  168665. totallen -= APP0_DATA_LEN;
  168666. if (totallen !=
  168667. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  168668. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  168669. } else if (datalen >= 6 &&
  168670. GETJOCTET(data[0]) == 0x4A &&
  168671. GETJOCTET(data[1]) == 0x46 &&
  168672. GETJOCTET(data[2]) == 0x58 &&
  168673. GETJOCTET(data[3]) == 0x58 &&
  168674. GETJOCTET(data[4]) == 0) {
  168675. /* Found JFIF "JFXX" extension APP0 marker */
  168676. /* The library doesn't actually do anything with these,
  168677. * but we try to produce a helpful trace message.
  168678. */
  168679. switch (GETJOCTET(data[5])) {
  168680. case 0x10:
  168681. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  168682. break;
  168683. case 0x11:
  168684. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  168685. break;
  168686. case 0x13:
  168687. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  168688. break;
  168689. default:
  168690. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  168691. GETJOCTET(data[5]), (int) totallen);
  168692. break;
  168693. }
  168694. } else {
  168695. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  168696. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  168697. }
  168698. }
  168699. LOCAL(void)
  168700. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  168701. unsigned int datalen, INT32 remaining)
  168702. /* Examine first few bytes from an APP14.
  168703. * Take appropriate action if it is an Adobe marker.
  168704. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  168705. */
  168706. {
  168707. unsigned int version, flags0, flags1, transform;
  168708. if (datalen >= APP14_DATA_LEN &&
  168709. GETJOCTET(data[0]) == 0x41 &&
  168710. GETJOCTET(data[1]) == 0x64 &&
  168711. GETJOCTET(data[2]) == 0x6F &&
  168712. GETJOCTET(data[3]) == 0x62 &&
  168713. GETJOCTET(data[4]) == 0x65) {
  168714. /* Found Adobe APP14 marker */
  168715. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  168716. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  168717. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  168718. transform = GETJOCTET(data[11]);
  168719. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  168720. cinfo->saw_Adobe_marker = TRUE;
  168721. cinfo->Adobe_transform = (UINT8) transform;
  168722. } else {
  168723. /* Start of APP14 does not match "Adobe", or too short */
  168724. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  168725. }
  168726. }
  168727. METHODDEF(boolean)
  168728. get_interesting_appn (j_decompress_ptr cinfo)
  168729. /* Process an APP0 or APP14 marker without saving it */
  168730. {
  168731. INT32 length;
  168732. JOCTET b[APPN_DATA_LEN];
  168733. unsigned int i, numtoread;
  168734. INPUT_VARS(cinfo);
  168735. INPUT_2BYTES(cinfo, length, return FALSE);
  168736. length -= 2;
  168737. /* get the interesting part of the marker data */
  168738. if (length >= APPN_DATA_LEN)
  168739. numtoread = APPN_DATA_LEN;
  168740. else if (length > 0)
  168741. numtoread = (unsigned int) length;
  168742. else
  168743. numtoread = 0;
  168744. for (i = 0; i < numtoread; i++)
  168745. INPUT_BYTE(cinfo, b[i], return FALSE);
  168746. length -= numtoread;
  168747. /* process it */
  168748. switch (cinfo->unread_marker) {
  168749. case M_APP0:
  168750. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  168751. break;
  168752. case M_APP14:
  168753. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  168754. break;
  168755. default:
  168756. /* can't get here unless jpeg_save_markers chooses wrong processor */
  168757. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  168758. break;
  168759. }
  168760. /* skip any remaining data -- could be lots */
  168761. INPUT_SYNC(cinfo);
  168762. if (length > 0)
  168763. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  168764. return TRUE;
  168765. }
  168766. #ifdef SAVE_MARKERS_SUPPORTED
  168767. METHODDEF(boolean)
  168768. save_marker (j_decompress_ptr cinfo)
  168769. /* Save an APPn or COM marker into the marker list */
  168770. {
  168771. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  168772. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  168773. unsigned int bytes_read, data_length;
  168774. JOCTET FAR * data;
  168775. INT32 length = 0;
  168776. INPUT_VARS(cinfo);
  168777. if (cur_marker == NULL) {
  168778. /* begin reading a marker */
  168779. INPUT_2BYTES(cinfo, length, return FALSE);
  168780. length -= 2;
  168781. if (length >= 0) { /* watch out for bogus length word */
  168782. /* figure out how much we want to save */
  168783. unsigned int limit;
  168784. if (cinfo->unread_marker == (int) M_COM)
  168785. limit = marker->length_limit_COM;
  168786. else
  168787. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  168788. if ((unsigned int) length < limit)
  168789. limit = (unsigned int) length;
  168790. /* allocate and initialize the marker item */
  168791. cur_marker = (jpeg_saved_marker_ptr)
  168792. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168793. SIZEOF(struct jpeg_marker_struct) + limit);
  168794. cur_marker->next = NULL;
  168795. cur_marker->marker = (UINT8) cinfo->unread_marker;
  168796. cur_marker->original_length = (unsigned int) length;
  168797. cur_marker->data_length = limit;
  168798. /* data area is just beyond the jpeg_marker_struct */
  168799. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  168800. marker->cur_marker = cur_marker;
  168801. marker->bytes_read = 0;
  168802. bytes_read = 0;
  168803. data_length = limit;
  168804. } else {
  168805. /* deal with bogus length word */
  168806. bytes_read = data_length = 0;
  168807. data = NULL;
  168808. }
  168809. } else {
  168810. /* resume reading a marker */
  168811. bytes_read = marker->bytes_read;
  168812. data_length = cur_marker->data_length;
  168813. data = cur_marker->data + bytes_read;
  168814. }
  168815. while (bytes_read < data_length) {
  168816. INPUT_SYNC(cinfo); /* move the restart point to here */
  168817. marker->bytes_read = bytes_read;
  168818. /* If there's not at least one byte in buffer, suspend */
  168819. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  168820. /* Copy bytes with reasonable rapidity */
  168821. while (bytes_read < data_length && bytes_in_buffer > 0) {
  168822. *data++ = *next_input_byte++;
  168823. bytes_in_buffer--;
  168824. bytes_read++;
  168825. }
  168826. }
  168827. /* Done reading what we want to read */
  168828. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  168829. /* Add new marker to end of list */
  168830. if (cinfo->marker_list == NULL) {
  168831. cinfo->marker_list = cur_marker;
  168832. } else {
  168833. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  168834. while (prev->next != NULL)
  168835. prev = prev->next;
  168836. prev->next = cur_marker;
  168837. }
  168838. /* Reset pointer & calc remaining data length */
  168839. data = cur_marker->data;
  168840. length = cur_marker->original_length - data_length;
  168841. }
  168842. /* Reset to initial state for next marker */
  168843. marker->cur_marker = NULL;
  168844. /* Process the marker if interesting; else just make a generic trace msg */
  168845. switch (cinfo->unread_marker) {
  168846. case M_APP0:
  168847. examine_app0(cinfo, data, data_length, length);
  168848. break;
  168849. case M_APP14:
  168850. examine_app14(cinfo, data, data_length, length);
  168851. break;
  168852. default:
  168853. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  168854. (int) (data_length + length));
  168855. break;
  168856. }
  168857. /* skip any remaining data -- could be lots */
  168858. INPUT_SYNC(cinfo); /* do before skip_input_data */
  168859. if (length > 0)
  168860. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  168861. return TRUE;
  168862. }
  168863. #endif /* SAVE_MARKERS_SUPPORTED */
  168864. METHODDEF(boolean)
  168865. skip_variable (j_decompress_ptr cinfo)
  168866. /* Skip over an unknown or uninteresting variable-length marker */
  168867. {
  168868. INT32 length;
  168869. INPUT_VARS(cinfo);
  168870. INPUT_2BYTES(cinfo, length, return FALSE);
  168871. length -= 2;
  168872. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  168873. INPUT_SYNC(cinfo); /* do before skip_input_data */
  168874. if (length > 0)
  168875. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  168876. return TRUE;
  168877. }
  168878. /*
  168879. * Find the next JPEG marker, save it in cinfo->unread_marker.
  168880. * Returns FALSE if had to suspend before reaching a marker;
  168881. * in that case cinfo->unread_marker is unchanged.
  168882. *
  168883. * Note that the result might not be a valid marker code,
  168884. * but it will never be 0 or FF.
  168885. */
  168886. LOCAL(boolean)
  168887. next_marker (j_decompress_ptr cinfo)
  168888. {
  168889. int c;
  168890. INPUT_VARS(cinfo);
  168891. for (;;) {
  168892. INPUT_BYTE(cinfo, c, return FALSE);
  168893. /* Skip any non-FF bytes.
  168894. * This may look a bit inefficient, but it will not occur in a valid file.
  168895. * We sync after each discarded byte so that a suspending data source
  168896. * can discard the byte from its buffer.
  168897. */
  168898. while (c != 0xFF) {
  168899. cinfo->marker->discarded_bytes++;
  168900. INPUT_SYNC(cinfo);
  168901. INPUT_BYTE(cinfo, c, return FALSE);
  168902. }
  168903. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  168904. * pad bytes, so don't count them in discarded_bytes. We assume there
  168905. * will not be so many consecutive FF bytes as to overflow a suspending
  168906. * data source's input buffer.
  168907. */
  168908. do {
  168909. INPUT_BYTE(cinfo, c, return FALSE);
  168910. } while (c == 0xFF);
  168911. if (c != 0)
  168912. break; /* found a valid marker, exit loop */
  168913. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  168914. * Discard it and loop back to try again.
  168915. */
  168916. cinfo->marker->discarded_bytes += 2;
  168917. INPUT_SYNC(cinfo);
  168918. }
  168919. if (cinfo->marker->discarded_bytes != 0) {
  168920. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  168921. cinfo->marker->discarded_bytes = 0;
  168922. }
  168923. cinfo->unread_marker = c;
  168924. INPUT_SYNC(cinfo);
  168925. return TRUE;
  168926. }
  168927. LOCAL(boolean)
  168928. first_marker (j_decompress_ptr cinfo)
  168929. /* Like next_marker, but used to obtain the initial SOI marker. */
  168930. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  168931. * we might well scan an entire input file before realizing it ain't JPEG.
  168932. * If an application wants to process non-JFIF files, it must seek to the
  168933. * SOI before calling the JPEG library.
  168934. */
  168935. {
  168936. int c, c2;
  168937. INPUT_VARS(cinfo);
  168938. INPUT_BYTE(cinfo, c, return FALSE);
  168939. INPUT_BYTE(cinfo, c2, return FALSE);
  168940. if (c != 0xFF || c2 != (int) M_SOI)
  168941. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  168942. cinfo->unread_marker = c2;
  168943. INPUT_SYNC(cinfo);
  168944. return TRUE;
  168945. }
  168946. /*
  168947. * Read markers until SOS or EOI.
  168948. *
  168949. * Returns same codes as are defined for jpeg_consume_input:
  168950. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  168951. */
  168952. METHODDEF(int)
  168953. read_markers (j_decompress_ptr cinfo)
  168954. {
  168955. /* Outer loop repeats once for each marker. */
  168956. for (;;) {
  168957. /* Collect the marker proper, unless we already did. */
  168958. /* NB: first_marker() enforces the requirement that SOI appear first. */
  168959. if (cinfo->unread_marker == 0) {
  168960. if (! cinfo->marker->saw_SOI) {
  168961. if (! first_marker(cinfo))
  168962. return JPEG_SUSPENDED;
  168963. } else {
  168964. if (! next_marker(cinfo))
  168965. return JPEG_SUSPENDED;
  168966. }
  168967. }
  168968. /* At this point cinfo->unread_marker contains the marker code and the
  168969. * input point is just past the marker proper, but before any parameters.
  168970. * A suspension will cause us to return with this state still true.
  168971. */
  168972. switch (cinfo->unread_marker) {
  168973. case M_SOI:
  168974. if (! get_soi(cinfo))
  168975. return JPEG_SUSPENDED;
  168976. break;
  168977. case M_SOF0: /* Baseline */
  168978. case M_SOF1: /* Extended sequential, Huffman */
  168979. if (! get_sof(cinfo, FALSE, FALSE))
  168980. return JPEG_SUSPENDED;
  168981. break;
  168982. case M_SOF2: /* Progressive, Huffman */
  168983. if (! get_sof(cinfo, TRUE, FALSE))
  168984. return JPEG_SUSPENDED;
  168985. break;
  168986. case M_SOF9: /* Extended sequential, arithmetic */
  168987. if (! get_sof(cinfo, FALSE, TRUE))
  168988. return JPEG_SUSPENDED;
  168989. break;
  168990. case M_SOF10: /* Progressive, arithmetic */
  168991. if (! get_sof(cinfo, TRUE, TRUE))
  168992. return JPEG_SUSPENDED;
  168993. break;
  168994. /* Currently unsupported SOFn types */
  168995. case M_SOF3: /* Lossless, Huffman */
  168996. case M_SOF5: /* Differential sequential, Huffman */
  168997. case M_SOF6: /* Differential progressive, Huffman */
  168998. case M_SOF7: /* Differential lossless, Huffman */
  168999. case M_JPG: /* Reserved for JPEG extensions */
  169000. case M_SOF11: /* Lossless, arithmetic */
  169001. case M_SOF13: /* Differential sequential, arithmetic */
  169002. case M_SOF14: /* Differential progressive, arithmetic */
  169003. case M_SOF15: /* Differential lossless, arithmetic */
  169004. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  169005. break;
  169006. case M_SOS:
  169007. if (! get_sos(cinfo))
  169008. return JPEG_SUSPENDED;
  169009. cinfo->unread_marker = 0; /* processed the marker */
  169010. return JPEG_REACHED_SOS;
  169011. case M_EOI:
  169012. TRACEMS(cinfo, 1, JTRC_EOI);
  169013. cinfo->unread_marker = 0; /* processed the marker */
  169014. return JPEG_REACHED_EOI;
  169015. case M_DAC:
  169016. if (! get_dac(cinfo))
  169017. return JPEG_SUSPENDED;
  169018. break;
  169019. case M_DHT:
  169020. if (! get_dht(cinfo))
  169021. return JPEG_SUSPENDED;
  169022. break;
  169023. case M_DQT:
  169024. if (! get_dqt(cinfo))
  169025. return JPEG_SUSPENDED;
  169026. break;
  169027. case M_DRI:
  169028. if (! get_dri(cinfo))
  169029. return JPEG_SUSPENDED;
  169030. break;
  169031. case M_APP0:
  169032. case M_APP1:
  169033. case M_APP2:
  169034. case M_APP3:
  169035. case M_APP4:
  169036. case M_APP5:
  169037. case M_APP6:
  169038. case M_APP7:
  169039. case M_APP8:
  169040. case M_APP9:
  169041. case M_APP10:
  169042. case M_APP11:
  169043. case M_APP12:
  169044. case M_APP13:
  169045. case M_APP14:
  169046. case M_APP15:
  169047. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  169048. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  169049. return JPEG_SUSPENDED;
  169050. break;
  169051. case M_COM:
  169052. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  169053. return JPEG_SUSPENDED;
  169054. break;
  169055. case M_RST0: /* these are all parameterless */
  169056. case M_RST1:
  169057. case M_RST2:
  169058. case M_RST3:
  169059. case M_RST4:
  169060. case M_RST5:
  169061. case M_RST6:
  169062. case M_RST7:
  169063. case M_TEM:
  169064. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  169065. break;
  169066. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  169067. if (! skip_variable(cinfo))
  169068. return JPEG_SUSPENDED;
  169069. break;
  169070. default: /* must be DHP, EXP, JPGn, or RESn */
  169071. /* For now, we treat the reserved markers as fatal errors since they are
  169072. * likely to be used to signal incompatible JPEG Part 3 extensions.
  169073. * Once the JPEG 3 version-number marker is well defined, this code
  169074. * ought to change!
  169075. */
  169076. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  169077. break;
  169078. }
  169079. /* Successfully processed marker, so reset state variable */
  169080. cinfo->unread_marker = 0;
  169081. } /* end loop */
  169082. }
  169083. /*
  169084. * Read a restart marker, which is expected to appear next in the datastream;
  169085. * if the marker is not there, take appropriate recovery action.
  169086. * Returns FALSE if suspension is required.
  169087. *
  169088. * This is called by the entropy decoder after it has read an appropriate
  169089. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  169090. * has already read a marker from the data source. Under normal conditions
  169091. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  169092. * it holds a marker which the decoder will be unable to read past.
  169093. */
  169094. METHODDEF(boolean)
  169095. read_restart_marker (j_decompress_ptr cinfo)
  169096. {
  169097. /* Obtain a marker unless we already did. */
  169098. /* Note that next_marker will complain if it skips any data. */
  169099. if (cinfo->unread_marker == 0) {
  169100. if (! next_marker(cinfo))
  169101. return FALSE;
  169102. }
  169103. if (cinfo->unread_marker ==
  169104. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  169105. /* Normal case --- swallow the marker and let entropy decoder continue */
  169106. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  169107. cinfo->unread_marker = 0;
  169108. } else {
  169109. /* Uh-oh, the restart markers have been messed up. */
  169110. /* Let the data source manager determine how to resync. */
  169111. if (! (*cinfo->src->resync_to_restart) (cinfo,
  169112. cinfo->marker->next_restart_num))
  169113. return FALSE;
  169114. }
  169115. /* Update next-restart state */
  169116. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  169117. return TRUE;
  169118. }
  169119. /*
  169120. * This is the default resync_to_restart method for data source managers
  169121. * to use if they don't have any better approach. Some data source managers
  169122. * may be able to back up, or may have additional knowledge about the data
  169123. * which permits a more intelligent recovery strategy; such managers would
  169124. * presumably supply their own resync method.
  169125. *
  169126. * read_restart_marker calls resync_to_restart if it finds a marker other than
  169127. * the restart marker it was expecting. (This code is *not* used unless
  169128. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  169129. * the marker code actually found (might be anything, except 0 or FF).
  169130. * The desired restart marker number (0..7) is passed as a parameter.
  169131. * This routine is supposed to apply whatever error recovery strategy seems
  169132. * appropriate in order to position the input stream to the next data segment.
  169133. * Note that cinfo->unread_marker is treated as a marker appearing before
  169134. * the current data-source input point; usually it should be reset to zero
  169135. * before returning.
  169136. * Returns FALSE if suspension is required.
  169137. *
  169138. * This implementation is substantially constrained by wanting to treat the
  169139. * input as a data stream; this means we can't back up. Therefore, we have
  169140. * only the following actions to work with:
  169141. * 1. Simply discard the marker and let the entropy decoder resume at next
  169142. * byte of file.
  169143. * 2. Read forward until we find another marker, discarding intervening
  169144. * data. (In theory we could look ahead within the current bufferload,
  169145. * without having to discard data if we don't find the desired marker.
  169146. * This idea is not implemented here, in part because it makes behavior
  169147. * dependent on buffer size and chance buffer-boundary positions.)
  169148. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  169149. * This will cause the entropy decoder to process an empty data segment,
  169150. * inserting dummy zeroes, and then we will reprocess the marker.
  169151. *
  169152. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  169153. * appropriate if the found marker is a future restart marker (indicating
  169154. * that we have missed the desired restart marker, probably because it got
  169155. * corrupted).
  169156. * We apply #2 or #3 if the found marker is a restart marker no more than
  169157. * two counts behind or ahead of the expected one. We also apply #2 if the
  169158. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  169159. * If the found marker is a restart marker more than 2 counts away, we do #1
  169160. * (too much risk that the marker is erroneous; with luck we will be able to
  169161. * resync at some future point).
  169162. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  169163. * overrunning the end of a scan. An implementation limited to single-scan
  169164. * files might find it better to apply #2 for markers other than EOI, since
  169165. * any other marker would have to be bogus data in that case.
  169166. */
  169167. GLOBAL(boolean)
  169168. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  169169. {
  169170. int marker = cinfo->unread_marker;
  169171. int action = 1;
  169172. /* Always put up a warning. */
  169173. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  169174. /* Outer loop handles repeated decision after scanning forward. */
  169175. for (;;) {
  169176. if (marker < (int) M_SOF0)
  169177. action = 2; /* invalid marker */
  169178. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  169179. action = 3; /* valid non-restart marker */
  169180. else {
  169181. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  169182. marker == ((int) M_RST0 + ((desired+2) & 7)))
  169183. action = 3; /* one of the next two expected restarts */
  169184. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  169185. marker == ((int) M_RST0 + ((desired-2) & 7)))
  169186. action = 2; /* a prior restart, so advance */
  169187. else
  169188. action = 1; /* desired restart or too far away */
  169189. }
  169190. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  169191. switch (action) {
  169192. case 1:
  169193. /* Discard marker and let entropy decoder resume processing. */
  169194. cinfo->unread_marker = 0;
  169195. return TRUE;
  169196. case 2:
  169197. /* Scan to the next marker, and repeat the decision loop. */
  169198. if (! next_marker(cinfo))
  169199. return FALSE;
  169200. marker = cinfo->unread_marker;
  169201. break;
  169202. case 3:
  169203. /* Return without advancing past this marker. */
  169204. /* Entropy decoder will be forced to process an empty segment. */
  169205. return TRUE;
  169206. }
  169207. } /* end loop */
  169208. }
  169209. /*
  169210. * Reset marker processing state to begin a fresh datastream.
  169211. */
  169212. METHODDEF(void)
  169213. reset_marker_reader (j_decompress_ptr cinfo)
  169214. {
  169215. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  169216. cinfo->comp_info = NULL; /* until allocated by get_sof */
  169217. cinfo->input_scan_number = 0; /* no SOS seen yet */
  169218. cinfo->unread_marker = 0; /* no pending marker */
  169219. marker->pub.saw_SOI = FALSE; /* set internal state too */
  169220. marker->pub.saw_SOF = FALSE;
  169221. marker->pub.discarded_bytes = 0;
  169222. marker->cur_marker = NULL;
  169223. }
  169224. /*
  169225. * Initialize the marker reader module.
  169226. * This is called only once, when the decompression object is created.
  169227. */
  169228. GLOBAL(void)
  169229. jinit_marker_reader (j_decompress_ptr cinfo)
  169230. {
  169231. my_marker_ptr2 marker;
  169232. int i;
  169233. /* Create subobject in permanent pool */
  169234. marker = (my_marker_ptr2)
  169235. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  169236. SIZEOF(my_marker_reader));
  169237. cinfo->marker = (struct jpeg_marker_reader *) marker;
  169238. /* Initialize public method pointers */
  169239. marker->pub.reset_marker_reader = reset_marker_reader;
  169240. marker->pub.read_markers = read_markers;
  169241. marker->pub.read_restart_marker = read_restart_marker;
  169242. /* Initialize COM/APPn processing.
  169243. * By default, we examine and then discard APP0 and APP14,
  169244. * but simply discard COM and all other APPn.
  169245. */
  169246. marker->process_COM = skip_variable;
  169247. marker->length_limit_COM = 0;
  169248. for (i = 0; i < 16; i++) {
  169249. marker->process_APPn[i] = skip_variable;
  169250. marker->length_limit_APPn[i] = 0;
  169251. }
  169252. marker->process_APPn[0] = get_interesting_appn;
  169253. marker->process_APPn[14] = get_interesting_appn;
  169254. /* Reset marker processing state */
  169255. reset_marker_reader(cinfo);
  169256. }
  169257. /*
  169258. * Control saving of COM and APPn markers into marker_list.
  169259. */
  169260. #ifdef SAVE_MARKERS_SUPPORTED
  169261. GLOBAL(void)
  169262. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  169263. unsigned int length_limit)
  169264. {
  169265. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  169266. long maxlength;
  169267. jpeg_marker_parser_method processor;
  169268. /* Length limit mustn't be larger than what we can allocate
  169269. * (should only be a concern in a 16-bit environment).
  169270. */
  169271. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  169272. if (((long) length_limit) > maxlength)
  169273. length_limit = (unsigned int) maxlength;
  169274. /* Choose processor routine to use.
  169275. * APP0/APP14 have special requirements.
  169276. */
  169277. if (length_limit) {
  169278. processor = save_marker;
  169279. /* If saving APP0/APP14, save at least enough for our internal use. */
  169280. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  169281. length_limit = APP0_DATA_LEN;
  169282. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  169283. length_limit = APP14_DATA_LEN;
  169284. } else {
  169285. processor = skip_variable;
  169286. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  169287. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  169288. processor = get_interesting_appn;
  169289. }
  169290. if (marker_code == (int) M_COM) {
  169291. marker->process_COM = processor;
  169292. marker->length_limit_COM = length_limit;
  169293. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  169294. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  169295. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  169296. } else
  169297. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  169298. }
  169299. #endif /* SAVE_MARKERS_SUPPORTED */
  169300. /*
  169301. * Install a special processing method for COM or APPn markers.
  169302. */
  169303. GLOBAL(void)
  169304. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  169305. jpeg_marker_parser_method routine)
  169306. {
  169307. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  169308. if (marker_code == (int) M_COM)
  169309. marker->process_COM = routine;
  169310. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  169311. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  169312. else
  169313. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  169314. }
  169315. /*** End of inlined file: jdmarker.c ***/
  169316. /*** Start of inlined file: jdmaster.c ***/
  169317. #define JPEG_INTERNALS
  169318. /* Private state */
  169319. typedef struct {
  169320. struct jpeg_decomp_master pub; /* public fields */
  169321. int pass_number; /* # of passes completed */
  169322. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  169323. /* Saved references to initialized quantizer modules,
  169324. * in case we need to switch modes.
  169325. */
  169326. struct jpeg_color_quantizer * quantizer_1pass;
  169327. struct jpeg_color_quantizer * quantizer_2pass;
  169328. } my_decomp_master;
  169329. typedef my_decomp_master * my_master_ptr6;
  169330. /*
  169331. * Determine whether merged upsample/color conversion should be used.
  169332. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  169333. */
  169334. LOCAL(boolean)
  169335. use_merged_upsample (j_decompress_ptr cinfo)
  169336. {
  169337. #ifdef UPSAMPLE_MERGING_SUPPORTED
  169338. /* Merging is the equivalent of plain box-filter upsampling */
  169339. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  169340. return FALSE;
  169341. /* jdmerge.c only supports YCC=>RGB color conversion */
  169342. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  169343. cinfo->out_color_space != JCS_RGB ||
  169344. cinfo->out_color_components != RGB_PIXELSIZE)
  169345. return FALSE;
  169346. /* and it only handles 2h1v or 2h2v sampling ratios */
  169347. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  169348. cinfo->comp_info[1].h_samp_factor != 1 ||
  169349. cinfo->comp_info[2].h_samp_factor != 1 ||
  169350. cinfo->comp_info[0].v_samp_factor > 2 ||
  169351. cinfo->comp_info[1].v_samp_factor != 1 ||
  169352. cinfo->comp_info[2].v_samp_factor != 1)
  169353. return FALSE;
  169354. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  169355. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  169356. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  169357. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  169358. return FALSE;
  169359. /* ??? also need to test for upsample-time rescaling, when & if supported */
  169360. return TRUE; /* by golly, it'll work... */
  169361. #else
  169362. return FALSE;
  169363. #endif
  169364. }
  169365. /*
  169366. * Compute output image dimensions and related values.
  169367. * NOTE: this is exported for possible use by application.
  169368. * Hence it mustn't do anything that can't be done twice.
  169369. * Also note that it may be called before the master module is initialized!
  169370. */
  169371. GLOBAL(void)
  169372. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  169373. /* Do computations that are needed before master selection phase */
  169374. {
  169375. #ifdef IDCT_SCALING_SUPPORTED
  169376. int ci;
  169377. jpeg_component_info *compptr;
  169378. #endif
  169379. /* Prevent application from calling me at wrong times */
  169380. if (cinfo->global_state != DSTATE_READY)
  169381. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  169382. #ifdef IDCT_SCALING_SUPPORTED
  169383. /* Compute actual output image dimensions and DCT scaling choices. */
  169384. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  169385. /* Provide 1/8 scaling */
  169386. cinfo->output_width = (JDIMENSION)
  169387. jdiv_round_up((long) cinfo->image_width, 8L);
  169388. cinfo->output_height = (JDIMENSION)
  169389. jdiv_round_up((long) cinfo->image_height, 8L);
  169390. cinfo->min_DCT_scaled_size = 1;
  169391. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  169392. /* Provide 1/4 scaling */
  169393. cinfo->output_width = (JDIMENSION)
  169394. jdiv_round_up((long) cinfo->image_width, 4L);
  169395. cinfo->output_height = (JDIMENSION)
  169396. jdiv_round_up((long) cinfo->image_height, 4L);
  169397. cinfo->min_DCT_scaled_size = 2;
  169398. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  169399. /* Provide 1/2 scaling */
  169400. cinfo->output_width = (JDIMENSION)
  169401. jdiv_round_up((long) cinfo->image_width, 2L);
  169402. cinfo->output_height = (JDIMENSION)
  169403. jdiv_round_up((long) cinfo->image_height, 2L);
  169404. cinfo->min_DCT_scaled_size = 4;
  169405. } else {
  169406. /* Provide 1/1 scaling */
  169407. cinfo->output_width = cinfo->image_width;
  169408. cinfo->output_height = cinfo->image_height;
  169409. cinfo->min_DCT_scaled_size = DCTSIZE;
  169410. }
  169411. /* In selecting the actual DCT scaling for each component, we try to
  169412. * scale up the chroma components via IDCT scaling rather than upsampling.
  169413. * This saves time if the upsampler gets to use 1:1 scaling.
  169414. * Note this code assumes that the supported DCT scalings are powers of 2.
  169415. */
  169416. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169417. ci++, compptr++) {
  169418. int ssize = cinfo->min_DCT_scaled_size;
  169419. while (ssize < DCTSIZE &&
  169420. (compptr->h_samp_factor * ssize * 2 <=
  169421. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  169422. (compptr->v_samp_factor * ssize * 2 <=
  169423. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  169424. ssize = ssize * 2;
  169425. }
  169426. compptr->DCT_scaled_size = ssize;
  169427. }
  169428. /* Recompute downsampled dimensions of components;
  169429. * application needs to know these if using raw downsampled data.
  169430. */
  169431. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169432. ci++, compptr++) {
  169433. /* Size in samples, after IDCT scaling */
  169434. compptr->downsampled_width = (JDIMENSION)
  169435. jdiv_round_up((long) cinfo->image_width *
  169436. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  169437. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  169438. compptr->downsampled_height = (JDIMENSION)
  169439. jdiv_round_up((long) cinfo->image_height *
  169440. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  169441. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  169442. }
  169443. #else /* !IDCT_SCALING_SUPPORTED */
  169444. /* Hardwire it to "no scaling" */
  169445. cinfo->output_width = cinfo->image_width;
  169446. cinfo->output_height = cinfo->image_height;
  169447. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  169448. * and has computed unscaled downsampled_width and downsampled_height.
  169449. */
  169450. #endif /* IDCT_SCALING_SUPPORTED */
  169451. /* Report number of components in selected colorspace. */
  169452. /* Probably this should be in the color conversion module... */
  169453. switch (cinfo->out_color_space) {
  169454. case JCS_GRAYSCALE:
  169455. cinfo->out_color_components = 1;
  169456. break;
  169457. case JCS_RGB:
  169458. #if RGB_PIXELSIZE != 3
  169459. cinfo->out_color_components = RGB_PIXELSIZE;
  169460. break;
  169461. #endif /* else share code with YCbCr */
  169462. case JCS_YCbCr:
  169463. cinfo->out_color_components = 3;
  169464. break;
  169465. case JCS_CMYK:
  169466. case JCS_YCCK:
  169467. cinfo->out_color_components = 4;
  169468. break;
  169469. default: /* else must be same colorspace as in file */
  169470. cinfo->out_color_components = cinfo->num_components;
  169471. break;
  169472. }
  169473. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  169474. cinfo->out_color_components);
  169475. /* See if upsampler will want to emit more than one row at a time */
  169476. if (use_merged_upsample(cinfo))
  169477. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  169478. else
  169479. cinfo->rec_outbuf_height = 1;
  169480. }
  169481. /*
  169482. * Several decompression processes need to range-limit values to the range
  169483. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  169484. * due to noise introduced by quantization, roundoff error, etc. These
  169485. * processes are inner loops and need to be as fast as possible. On most
  169486. * machines, particularly CPUs with pipelines or instruction prefetch,
  169487. * a (subscript-check-less) C table lookup
  169488. * x = sample_range_limit[x];
  169489. * is faster than explicit tests
  169490. * if (x < 0) x = 0;
  169491. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  169492. * These processes all use a common table prepared by the routine below.
  169493. *
  169494. * For most steps we can mathematically guarantee that the initial value
  169495. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  169496. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  169497. * limiting step (just after the IDCT), a wildly out-of-range value is
  169498. * possible if the input data is corrupt. To avoid any chance of indexing
  169499. * off the end of memory and getting a bad-pointer trap, we perform the
  169500. * post-IDCT limiting thus:
  169501. * x = range_limit[x & MASK];
  169502. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  169503. * samples. Under normal circumstances this is more than enough range and
  169504. * a correct output will be generated; with bogus input data the mask will
  169505. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  169506. * For the post-IDCT step, we want to convert the data from signed to unsigned
  169507. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  169508. * So the post-IDCT limiting table ends up looking like this:
  169509. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  169510. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  169511. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  169512. * 0,1,...,CENTERJSAMPLE-1
  169513. * Negative inputs select values from the upper half of the table after
  169514. * masking.
  169515. *
  169516. * We can save some space by overlapping the start of the post-IDCT table
  169517. * with the simpler range limiting table. The post-IDCT table begins at
  169518. * sample_range_limit + CENTERJSAMPLE.
  169519. *
  169520. * Note that the table is allocated in near data space on PCs; it's small
  169521. * enough and used often enough to justify this.
  169522. */
  169523. LOCAL(void)
  169524. prepare_range_limit_table (j_decompress_ptr cinfo)
  169525. /* Allocate and fill in the sample_range_limit table */
  169526. {
  169527. JSAMPLE * table;
  169528. int i;
  169529. table = (JSAMPLE *)
  169530. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169531. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  169532. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  169533. cinfo->sample_range_limit = table;
  169534. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  169535. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  169536. /* Main part of "simple" table: limit[x] = x */
  169537. for (i = 0; i <= MAXJSAMPLE; i++)
  169538. table[i] = (JSAMPLE) i;
  169539. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  169540. /* End of simple table, rest of first half of post-IDCT table */
  169541. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  169542. table[i] = MAXJSAMPLE;
  169543. /* Second half of post-IDCT table */
  169544. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  169545. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  169546. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  169547. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  169548. }
  169549. /*
  169550. * Master selection of decompression modules.
  169551. * This is done once at jpeg_start_decompress time. We determine
  169552. * which modules will be used and give them appropriate initialization calls.
  169553. * We also initialize the decompressor input side to begin consuming data.
  169554. *
  169555. * Since jpeg_read_header has finished, we know what is in the SOF
  169556. * and (first) SOS markers. We also have all the application parameter
  169557. * settings.
  169558. */
  169559. LOCAL(void)
  169560. master_selection (j_decompress_ptr cinfo)
  169561. {
  169562. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  169563. boolean use_c_buffer;
  169564. long samplesperrow;
  169565. JDIMENSION jd_samplesperrow;
  169566. /* Initialize dimensions and other stuff */
  169567. jpeg_calc_output_dimensions(cinfo);
  169568. prepare_range_limit_table(cinfo);
  169569. /* Width of an output scanline must be representable as JDIMENSION. */
  169570. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  169571. jd_samplesperrow = (JDIMENSION) samplesperrow;
  169572. if ((long) jd_samplesperrow != samplesperrow)
  169573. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  169574. /* Initialize my private state */
  169575. master->pass_number = 0;
  169576. master->using_merged_upsample = use_merged_upsample(cinfo);
  169577. /* Color quantizer selection */
  169578. master->quantizer_1pass = NULL;
  169579. master->quantizer_2pass = NULL;
  169580. /* No mode changes if not using buffered-image mode. */
  169581. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  169582. cinfo->enable_1pass_quant = FALSE;
  169583. cinfo->enable_external_quant = FALSE;
  169584. cinfo->enable_2pass_quant = FALSE;
  169585. }
  169586. if (cinfo->quantize_colors) {
  169587. if (cinfo->raw_data_out)
  169588. ERREXIT(cinfo, JERR_NOTIMPL);
  169589. /* 2-pass quantizer only works in 3-component color space. */
  169590. if (cinfo->out_color_components != 3) {
  169591. cinfo->enable_1pass_quant = TRUE;
  169592. cinfo->enable_external_quant = FALSE;
  169593. cinfo->enable_2pass_quant = FALSE;
  169594. cinfo->colormap = NULL;
  169595. } else if (cinfo->colormap != NULL) {
  169596. cinfo->enable_external_quant = TRUE;
  169597. } else if (cinfo->two_pass_quantize) {
  169598. cinfo->enable_2pass_quant = TRUE;
  169599. } else {
  169600. cinfo->enable_1pass_quant = TRUE;
  169601. }
  169602. if (cinfo->enable_1pass_quant) {
  169603. #ifdef QUANT_1PASS_SUPPORTED
  169604. jinit_1pass_quantizer(cinfo);
  169605. master->quantizer_1pass = cinfo->cquantize;
  169606. #else
  169607. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169608. #endif
  169609. }
  169610. /* We use the 2-pass code to map to external colormaps. */
  169611. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  169612. #ifdef QUANT_2PASS_SUPPORTED
  169613. jinit_2pass_quantizer(cinfo);
  169614. master->quantizer_2pass = cinfo->cquantize;
  169615. #else
  169616. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169617. #endif
  169618. }
  169619. /* If both quantizers are initialized, the 2-pass one is left active;
  169620. * this is necessary for starting with quantization to an external map.
  169621. */
  169622. }
  169623. /* Post-processing: in particular, color conversion first */
  169624. if (! cinfo->raw_data_out) {
  169625. if (master->using_merged_upsample) {
  169626. #ifdef UPSAMPLE_MERGING_SUPPORTED
  169627. jinit_merged_upsampler(cinfo); /* does color conversion too */
  169628. #else
  169629. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169630. #endif
  169631. } else {
  169632. jinit_color_deconverter(cinfo);
  169633. jinit_upsampler(cinfo);
  169634. }
  169635. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  169636. }
  169637. /* Inverse DCT */
  169638. jinit_inverse_dct(cinfo);
  169639. /* Entropy decoding: either Huffman or arithmetic coding. */
  169640. if (cinfo->arith_code) {
  169641. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  169642. } else {
  169643. if (cinfo->progressive_mode) {
  169644. #ifdef D_PROGRESSIVE_SUPPORTED
  169645. jinit_phuff_decoder(cinfo);
  169646. #else
  169647. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169648. #endif
  169649. } else
  169650. jinit_huff_decoder(cinfo);
  169651. }
  169652. /* Initialize principal buffer controllers. */
  169653. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  169654. jinit_d_coef_controller(cinfo, use_c_buffer);
  169655. if (! cinfo->raw_data_out)
  169656. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  169657. /* We can now tell the memory manager to allocate virtual arrays. */
  169658. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  169659. /* Initialize input side of decompressor to consume first scan. */
  169660. (*cinfo->inputctl->start_input_pass) (cinfo);
  169661. #ifdef D_MULTISCAN_FILES_SUPPORTED
  169662. /* If jpeg_start_decompress will read the whole file, initialize
  169663. * progress monitoring appropriately. The input step is counted
  169664. * as one pass.
  169665. */
  169666. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  169667. cinfo->inputctl->has_multiple_scans) {
  169668. int nscans;
  169669. /* Estimate number of scans to set pass_limit. */
  169670. if (cinfo->progressive_mode) {
  169671. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  169672. nscans = 2 + 3 * cinfo->num_components;
  169673. } else {
  169674. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  169675. nscans = cinfo->num_components;
  169676. }
  169677. cinfo->progress->pass_counter = 0L;
  169678. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  169679. cinfo->progress->completed_passes = 0;
  169680. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  169681. /* Count the input pass as done */
  169682. master->pass_number++;
  169683. }
  169684. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  169685. }
  169686. /*
  169687. * Per-pass setup.
  169688. * This is called at the beginning of each output pass. We determine which
  169689. * modules will be active during this pass and give them appropriate
  169690. * start_pass calls. We also set is_dummy_pass to indicate whether this
  169691. * is a "real" output pass or a dummy pass for color quantization.
  169692. * (In the latter case, jdapistd.c will crank the pass to completion.)
  169693. */
  169694. METHODDEF(void)
  169695. prepare_for_output_pass (j_decompress_ptr cinfo)
  169696. {
  169697. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  169698. if (master->pub.is_dummy_pass) {
  169699. #ifdef QUANT_2PASS_SUPPORTED
  169700. /* Final pass of 2-pass quantization */
  169701. master->pub.is_dummy_pass = FALSE;
  169702. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  169703. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  169704. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  169705. #else
  169706. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169707. #endif /* QUANT_2PASS_SUPPORTED */
  169708. } else {
  169709. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  169710. /* Select new quantization method */
  169711. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  169712. cinfo->cquantize = master->quantizer_2pass;
  169713. master->pub.is_dummy_pass = TRUE;
  169714. } else if (cinfo->enable_1pass_quant) {
  169715. cinfo->cquantize = master->quantizer_1pass;
  169716. } else {
  169717. ERREXIT(cinfo, JERR_MODE_CHANGE);
  169718. }
  169719. }
  169720. (*cinfo->idct->start_pass) (cinfo);
  169721. (*cinfo->coef->start_output_pass) (cinfo);
  169722. if (! cinfo->raw_data_out) {
  169723. if (! master->using_merged_upsample)
  169724. (*cinfo->cconvert->start_pass) (cinfo);
  169725. (*cinfo->upsample->start_pass) (cinfo);
  169726. if (cinfo->quantize_colors)
  169727. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  169728. (*cinfo->post->start_pass) (cinfo,
  169729. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  169730. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  169731. }
  169732. }
  169733. /* Set up progress monitor's pass info if present */
  169734. if (cinfo->progress != NULL) {
  169735. cinfo->progress->completed_passes = master->pass_number;
  169736. cinfo->progress->total_passes = master->pass_number +
  169737. (master->pub.is_dummy_pass ? 2 : 1);
  169738. /* In buffered-image mode, we assume one more output pass if EOI not
  169739. * yet reached, but no more passes if EOI has been reached.
  169740. */
  169741. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  169742. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  169743. }
  169744. }
  169745. }
  169746. /*
  169747. * Finish up at end of an output pass.
  169748. */
  169749. METHODDEF(void)
  169750. finish_output_pass (j_decompress_ptr cinfo)
  169751. {
  169752. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  169753. if (cinfo->quantize_colors)
  169754. (*cinfo->cquantize->finish_pass) (cinfo);
  169755. master->pass_number++;
  169756. }
  169757. #ifdef D_MULTISCAN_FILES_SUPPORTED
  169758. /*
  169759. * Switch to a new external colormap between output passes.
  169760. */
  169761. GLOBAL(void)
  169762. jpeg_new_colormap (j_decompress_ptr cinfo)
  169763. {
  169764. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  169765. /* Prevent application from calling me at wrong times */
  169766. if (cinfo->global_state != DSTATE_BUFIMAGE)
  169767. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  169768. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  169769. cinfo->colormap != NULL) {
  169770. /* Select 2-pass quantizer for external colormap use */
  169771. cinfo->cquantize = master->quantizer_2pass;
  169772. /* Notify quantizer of colormap change */
  169773. (*cinfo->cquantize->new_color_map) (cinfo);
  169774. master->pub.is_dummy_pass = FALSE; /* just in case */
  169775. } else
  169776. ERREXIT(cinfo, JERR_MODE_CHANGE);
  169777. }
  169778. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  169779. /*
  169780. * Initialize master decompression control and select active modules.
  169781. * This is performed at the start of jpeg_start_decompress.
  169782. */
  169783. GLOBAL(void)
  169784. jinit_master_decompress (j_decompress_ptr cinfo)
  169785. {
  169786. my_master_ptr6 master;
  169787. master = (my_master_ptr6)
  169788. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169789. SIZEOF(my_decomp_master));
  169790. cinfo->master = (struct jpeg_decomp_master *) master;
  169791. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  169792. master->pub.finish_output_pass = finish_output_pass;
  169793. master->pub.is_dummy_pass = FALSE;
  169794. master_selection(cinfo);
  169795. }
  169796. /*** End of inlined file: jdmaster.c ***/
  169797. #undef FIX
  169798. /*** Start of inlined file: jdmerge.c ***/
  169799. #define JPEG_INTERNALS
  169800. #ifdef UPSAMPLE_MERGING_SUPPORTED
  169801. /* Private subobject */
  169802. typedef struct {
  169803. struct jpeg_upsampler pub; /* public fields */
  169804. /* Pointer to routine to do actual upsampling/conversion of one row group */
  169805. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  169806. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  169807. JSAMPARRAY output_buf));
  169808. /* Private state for YCC->RGB conversion */
  169809. int * Cr_r_tab; /* => table for Cr to R conversion */
  169810. int * Cb_b_tab; /* => table for Cb to B conversion */
  169811. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  169812. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  169813. /* For 2:1 vertical sampling, we produce two output rows at a time.
  169814. * We need a "spare" row buffer to hold the second output row if the
  169815. * application provides just a one-row buffer; we also use the spare
  169816. * to discard the dummy last row if the image height is odd.
  169817. */
  169818. JSAMPROW spare_row;
  169819. boolean spare_full; /* T if spare buffer is occupied */
  169820. JDIMENSION out_row_width; /* samples per output row */
  169821. JDIMENSION rows_to_go; /* counts rows remaining in image */
  169822. } my_upsampler;
  169823. typedef my_upsampler * my_upsample_ptr;
  169824. #define SCALEBITS 16 /* speediest right-shift on some machines */
  169825. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  169826. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  169827. /*
  169828. * Initialize tables for YCC->RGB colorspace conversion.
  169829. * This is taken directly from jdcolor.c; see that file for more info.
  169830. */
  169831. LOCAL(void)
  169832. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  169833. {
  169834. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  169835. int i;
  169836. INT32 x;
  169837. SHIFT_TEMPS
  169838. upsample->Cr_r_tab = (int *)
  169839. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169840. (MAXJSAMPLE+1) * SIZEOF(int));
  169841. upsample->Cb_b_tab = (int *)
  169842. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169843. (MAXJSAMPLE+1) * SIZEOF(int));
  169844. upsample->Cr_g_tab = (INT32 *)
  169845. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169846. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169847. upsample->Cb_g_tab = (INT32 *)
  169848. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169849. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169850. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  169851. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  169852. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  169853. /* Cr=>R value is nearest int to 1.40200 * x */
  169854. upsample->Cr_r_tab[i] = (int)
  169855. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  169856. /* Cb=>B value is nearest int to 1.77200 * x */
  169857. upsample->Cb_b_tab[i] = (int)
  169858. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  169859. /* Cr=>G value is scaled-up -0.71414 * x */
  169860. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  169861. /* Cb=>G value is scaled-up -0.34414 * x */
  169862. /* We also add in ONE_HALF so that need not do it in inner loop */
  169863. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  169864. }
  169865. }
  169866. /*
  169867. * Initialize for an upsampling pass.
  169868. */
  169869. METHODDEF(void)
  169870. start_pass_merged_upsample (j_decompress_ptr cinfo)
  169871. {
  169872. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  169873. /* Mark the spare buffer empty */
  169874. upsample->spare_full = FALSE;
  169875. /* Initialize total-height counter for detecting bottom of image */
  169876. upsample->rows_to_go = cinfo->output_height;
  169877. }
  169878. /*
  169879. * Control routine to do upsampling (and color conversion).
  169880. *
  169881. * The control routine just handles the row buffering considerations.
  169882. */
  169883. METHODDEF(void)
  169884. merged_2v_upsample (j_decompress_ptr cinfo,
  169885. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169886. JDIMENSION,
  169887. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169888. JDIMENSION out_rows_avail)
  169889. /* 2:1 vertical sampling case: may need a spare row. */
  169890. {
  169891. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  169892. JSAMPROW work_ptrs[2];
  169893. JDIMENSION num_rows; /* number of rows returned to caller */
  169894. if (upsample->spare_full) {
  169895. /* If we have a spare row saved from a previous cycle, just return it. */
  169896. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  169897. 1, upsample->out_row_width);
  169898. num_rows = 1;
  169899. upsample->spare_full = FALSE;
  169900. } else {
  169901. /* Figure number of rows to return to caller. */
  169902. num_rows = 2;
  169903. /* Not more than the distance to the end of the image. */
  169904. if (num_rows > upsample->rows_to_go)
  169905. num_rows = upsample->rows_to_go;
  169906. /* And not more than what the client can accept: */
  169907. out_rows_avail -= *out_row_ctr;
  169908. if (num_rows > out_rows_avail)
  169909. num_rows = out_rows_avail;
  169910. /* Create output pointer array for upsampler. */
  169911. work_ptrs[0] = output_buf[*out_row_ctr];
  169912. if (num_rows > 1) {
  169913. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  169914. } else {
  169915. work_ptrs[1] = upsample->spare_row;
  169916. upsample->spare_full = TRUE;
  169917. }
  169918. /* Now do the upsampling. */
  169919. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  169920. }
  169921. /* Adjust counts */
  169922. *out_row_ctr += num_rows;
  169923. upsample->rows_to_go -= num_rows;
  169924. /* When the buffer is emptied, declare this input row group consumed */
  169925. if (! upsample->spare_full)
  169926. (*in_row_group_ctr)++;
  169927. }
  169928. METHODDEF(void)
  169929. merged_1v_upsample (j_decompress_ptr cinfo,
  169930. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169931. JDIMENSION,
  169932. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169933. JDIMENSION)
  169934. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  169935. {
  169936. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  169937. /* Just do the upsampling. */
  169938. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  169939. output_buf + *out_row_ctr);
  169940. /* Adjust counts */
  169941. (*out_row_ctr)++;
  169942. (*in_row_group_ctr)++;
  169943. }
  169944. /*
  169945. * These are the routines invoked by the control routines to do
  169946. * the actual upsampling/conversion. One row group is processed per call.
  169947. *
  169948. * Note: since we may be writing directly into application-supplied buffers,
  169949. * we have to be honest about the output width; we can't assume the buffer
  169950. * has been rounded up to an even width.
  169951. */
  169952. /*
  169953. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  169954. */
  169955. METHODDEF(void)
  169956. h2v1_merged_upsample (j_decompress_ptr cinfo,
  169957. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  169958. JSAMPARRAY output_buf)
  169959. {
  169960. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  169961. register int y, cred, cgreen, cblue;
  169962. int cb, cr;
  169963. register JSAMPROW outptr;
  169964. JSAMPROW inptr0, inptr1, inptr2;
  169965. JDIMENSION col;
  169966. /* copy these pointers into registers if possible */
  169967. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169968. int * Crrtab = upsample->Cr_r_tab;
  169969. int * Cbbtab = upsample->Cb_b_tab;
  169970. INT32 * Crgtab = upsample->Cr_g_tab;
  169971. INT32 * Cbgtab = upsample->Cb_g_tab;
  169972. SHIFT_TEMPS
  169973. inptr0 = input_buf[0][in_row_group_ctr];
  169974. inptr1 = input_buf[1][in_row_group_ctr];
  169975. inptr2 = input_buf[2][in_row_group_ctr];
  169976. outptr = output_buf[0];
  169977. /* Loop for each pair of output pixels */
  169978. for (col = cinfo->output_width >> 1; col > 0; col--) {
  169979. /* Do the chroma part of the calculation */
  169980. cb = GETJSAMPLE(*inptr1++);
  169981. cr = GETJSAMPLE(*inptr2++);
  169982. cred = Crrtab[cr];
  169983. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  169984. cblue = Cbbtab[cb];
  169985. /* Fetch 2 Y values and emit 2 pixels */
  169986. y = GETJSAMPLE(*inptr0++);
  169987. outptr[RGB_RED] = range_limit[y + cred];
  169988. outptr[RGB_GREEN] = range_limit[y + cgreen];
  169989. outptr[RGB_BLUE] = range_limit[y + cblue];
  169990. outptr += RGB_PIXELSIZE;
  169991. y = GETJSAMPLE(*inptr0++);
  169992. outptr[RGB_RED] = range_limit[y + cred];
  169993. outptr[RGB_GREEN] = range_limit[y + cgreen];
  169994. outptr[RGB_BLUE] = range_limit[y + cblue];
  169995. outptr += RGB_PIXELSIZE;
  169996. }
  169997. /* If image width is odd, do the last output column separately */
  169998. if (cinfo->output_width & 1) {
  169999. cb = GETJSAMPLE(*inptr1);
  170000. cr = GETJSAMPLE(*inptr2);
  170001. cred = Crrtab[cr];
  170002. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  170003. cblue = Cbbtab[cb];
  170004. y = GETJSAMPLE(*inptr0);
  170005. outptr[RGB_RED] = range_limit[y + cred];
  170006. outptr[RGB_GREEN] = range_limit[y + cgreen];
  170007. outptr[RGB_BLUE] = range_limit[y + cblue];
  170008. }
  170009. }
  170010. /*
  170011. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  170012. */
  170013. METHODDEF(void)
  170014. h2v2_merged_upsample (j_decompress_ptr cinfo,
  170015. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  170016. JSAMPARRAY output_buf)
  170017. {
  170018. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  170019. register int y, cred, cgreen, cblue;
  170020. int cb, cr;
  170021. register JSAMPROW outptr0, outptr1;
  170022. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  170023. JDIMENSION col;
  170024. /* copy these pointers into registers if possible */
  170025. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  170026. int * Crrtab = upsample->Cr_r_tab;
  170027. int * Cbbtab = upsample->Cb_b_tab;
  170028. INT32 * Crgtab = upsample->Cr_g_tab;
  170029. INT32 * Cbgtab = upsample->Cb_g_tab;
  170030. SHIFT_TEMPS
  170031. inptr00 = input_buf[0][in_row_group_ctr*2];
  170032. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  170033. inptr1 = input_buf[1][in_row_group_ctr];
  170034. inptr2 = input_buf[2][in_row_group_ctr];
  170035. outptr0 = output_buf[0];
  170036. outptr1 = output_buf[1];
  170037. /* Loop for each group of output pixels */
  170038. for (col = cinfo->output_width >> 1; col > 0; col--) {
  170039. /* Do the chroma part of the calculation */
  170040. cb = GETJSAMPLE(*inptr1++);
  170041. cr = GETJSAMPLE(*inptr2++);
  170042. cred = Crrtab[cr];
  170043. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  170044. cblue = Cbbtab[cb];
  170045. /* Fetch 4 Y values and emit 4 pixels */
  170046. y = GETJSAMPLE(*inptr00++);
  170047. outptr0[RGB_RED] = range_limit[y + cred];
  170048. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  170049. outptr0[RGB_BLUE] = range_limit[y + cblue];
  170050. outptr0 += RGB_PIXELSIZE;
  170051. y = GETJSAMPLE(*inptr00++);
  170052. outptr0[RGB_RED] = range_limit[y + cred];
  170053. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  170054. outptr0[RGB_BLUE] = range_limit[y + cblue];
  170055. outptr0 += RGB_PIXELSIZE;
  170056. y = GETJSAMPLE(*inptr01++);
  170057. outptr1[RGB_RED] = range_limit[y + cred];
  170058. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  170059. outptr1[RGB_BLUE] = range_limit[y + cblue];
  170060. outptr1 += RGB_PIXELSIZE;
  170061. y = GETJSAMPLE(*inptr01++);
  170062. outptr1[RGB_RED] = range_limit[y + cred];
  170063. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  170064. outptr1[RGB_BLUE] = range_limit[y + cblue];
  170065. outptr1 += RGB_PIXELSIZE;
  170066. }
  170067. /* If image width is odd, do the last output column separately */
  170068. if (cinfo->output_width & 1) {
  170069. cb = GETJSAMPLE(*inptr1);
  170070. cr = GETJSAMPLE(*inptr2);
  170071. cred = Crrtab[cr];
  170072. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  170073. cblue = Cbbtab[cb];
  170074. y = GETJSAMPLE(*inptr00);
  170075. outptr0[RGB_RED] = range_limit[y + cred];
  170076. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  170077. outptr0[RGB_BLUE] = range_limit[y + cblue];
  170078. y = GETJSAMPLE(*inptr01);
  170079. outptr1[RGB_RED] = range_limit[y + cred];
  170080. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  170081. outptr1[RGB_BLUE] = range_limit[y + cblue];
  170082. }
  170083. }
  170084. /*
  170085. * Module initialization routine for merged upsampling/color conversion.
  170086. *
  170087. * NB: this is called under the conditions determined by use_merged_upsample()
  170088. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  170089. * of this module; no safety checks are made here.
  170090. */
  170091. GLOBAL(void)
  170092. jinit_merged_upsampler (j_decompress_ptr cinfo)
  170093. {
  170094. my_upsample_ptr upsample;
  170095. upsample = (my_upsample_ptr)
  170096. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170097. SIZEOF(my_upsampler));
  170098. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  170099. upsample->pub.start_pass = start_pass_merged_upsample;
  170100. upsample->pub.need_context_rows = FALSE;
  170101. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  170102. if (cinfo->max_v_samp_factor == 2) {
  170103. upsample->pub.upsample = merged_2v_upsample;
  170104. upsample->upmethod = h2v2_merged_upsample;
  170105. /* Allocate a spare row buffer */
  170106. upsample->spare_row = (JSAMPROW)
  170107. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170108. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  170109. } else {
  170110. upsample->pub.upsample = merged_1v_upsample;
  170111. upsample->upmethod = h2v1_merged_upsample;
  170112. /* No spare row needed */
  170113. upsample->spare_row = NULL;
  170114. }
  170115. build_ycc_rgb_table2(cinfo);
  170116. }
  170117. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  170118. /*** End of inlined file: jdmerge.c ***/
  170119. #undef ASSIGN_STATE
  170120. /*** Start of inlined file: jdphuff.c ***/
  170121. #define JPEG_INTERNALS
  170122. #ifdef D_PROGRESSIVE_SUPPORTED
  170123. /*
  170124. * Expanded entropy decoder object for progressive Huffman decoding.
  170125. *
  170126. * The savable_state subrecord contains fields that change within an MCU,
  170127. * but must not be updated permanently until we complete the MCU.
  170128. */
  170129. typedef struct {
  170130. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  170131. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  170132. } savable_state3;
  170133. /* This macro is to work around compilers with missing or broken
  170134. * structure assignment. You'll need to fix this code if you have
  170135. * such a compiler and you change MAX_COMPS_IN_SCAN.
  170136. */
  170137. #ifndef NO_STRUCT_ASSIGN
  170138. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  170139. #else
  170140. #if MAX_COMPS_IN_SCAN == 4
  170141. #define ASSIGN_STATE(dest,src) \
  170142. ((dest).EOBRUN = (src).EOBRUN, \
  170143. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  170144. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  170145. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  170146. (dest).last_dc_val[3] = (src).last_dc_val[3])
  170147. #endif
  170148. #endif
  170149. typedef struct {
  170150. struct jpeg_entropy_decoder pub; /* public fields */
  170151. /* These fields are loaded into local variables at start of each MCU.
  170152. * In case of suspension, we exit WITHOUT updating them.
  170153. */
  170154. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  170155. savable_state3 saved; /* Other state at start of MCU */
  170156. /* These fields are NOT loaded into local working state. */
  170157. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  170158. /* Pointers to derived tables (these workspaces have image lifespan) */
  170159. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  170160. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  170161. } phuff_entropy_decoder;
  170162. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  170163. /* Forward declarations */
  170164. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  170165. JBLOCKROW *MCU_data));
  170166. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  170167. JBLOCKROW *MCU_data));
  170168. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  170169. JBLOCKROW *MCU_data));
  170170. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  170171. JBLOCKROW *MCU_data));
  170172. /*
  170173. * Initialize for a Huffman-compressed scan.
  170174. */
  170175. METHODDEF(void)
  170176. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  170177. {
  170178. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  170179. boolean is_DC_band, bad;
  170180. int ci, coefi, tbl;
  170181. int *coef_bit_ptr;
  170182. jpeg_component_info * compptr;
  170183. is_DC_band = (cinfo->Ss == 0);
  170184. /* Validate scan parameters */
  170185. bad = FALSE;
  170186. if (is_DC_band) {
  170187. if (cinfo->Se != 0)
  170188. bad = TRUE;
  170189. } else {
  170190. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  170191. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  170192. bad = TRUE;
  170193. /* AC scans may have only one component */
  170194. if (cinfo->comps_in_scan != 1)
  170195. bad = TRUE;
  170196. }
  170197. if (cinfo->Ah != 0) {
  170198. /* Successive approximation refinement scan: must have Al = Ah-1. */
  170199. if (cinfo->Al != cinfo->Ah-1)
  170200. bad = TRUE;
  170201. }
  170202. if (cinfo->Al > 13) /* need not check for < 0 */
  170203. bad = TRUE;
  170204. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  170205. * but the spec doesn't say so, and we try to be liberal about what we
  170206. * accept. Note: large Al values could result in out-of-range DC
  170207. * coefficients during early scans, leading to bizarre displays due to
  170208. * overflows in the IDCT math. But we won't crash.
  170209. */
  170210. if (bad)
  170211. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  170212. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  170213. /* Update progression status, and verify that scan order is legal.
  170214. * Note that inter-scan inconsistencies are treated as warnings
  170215. * not fatal errors ... not clear if this is right way to behave.
  170216. */
  170217. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170218. int cindex = cinfo->cur_comp_info[ci]->component_index;
  170219. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  170220. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  170221. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  170222. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  170223. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  170224. if (cinfo->Ah != expected)
  170225. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  170226. coef_bit_ptr[coefi] = cinfo->Al;
  170227. }
  170228. }
  170229. /* Select MCU decoding routine */
  170230. if (cinfo->Ah == 0) {
  170231. if (is_DC_band)
  170232. entropy->pub.decode_mcu = decode_mcu_DC_first;
  170233. else
  170234. entropy->pub.decode_mcu = decode_mcu_AC_first;
  170235. } else {
  170236. if (is_DC_band)
  170237. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  170238. else
  170239. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  170240. }
  170241. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170242. compptr = cinfo->cur_comp_info[ci];
  170243. /* Make sure requested tables are present, and compute derived tables.
  170244. * We may build same derived table more than once, but it's not expensive.
  170245. */
  170246. if (is_DC_band) {
  170247. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  170248. tbl = compptr->dc_tbl_no;
  170249. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  170250. & entropy->derived_tbls[tbl]);
  170251. }
  170252. } else {
  170253. tbl = compptr->ac_tbl_no;
  170254. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  170255. & entropy->derived_tbls[tbl]);
  170256. /* remember the single active table */
  170257. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  170258. }
  170259. /* Initialize DC predictions to 0 */
  170260. entropy->saved.last_dc_val[ci] = 0;
  170261. }
  170262. /* Initialize bitread state variables */
  170263. entropy->bitstate.bits_left = 0;
  170264. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  170265. entropy->pub.insufficient_data = FALSE;
  170266. /* Initialize private state variables */
  170267. entropy->saved.EOBRUN = 0;
  170268. /* Initialize restart counter */
  170269. entropy->restarts_to_go = cinfo->restart_interval;
  170270. }
  170271. /*
  170272. * Check for a restart marker & resynchronize decoder.
  170273. * Returns FALSE if must suspend.
  170274. */
  170275. LOCAL(boolean)
  170276. process_restartp (j_decompress_ptr cinfo)
  170277. {
  170278. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  170279. int ci;
  170280. /* Throw away any unused bits remaining in bit buffer; */
  170281. /* include any full bytes in next_marker's count of discarded bytes */
  170282. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  170283. entropy->bitstate.bits_left = 0;
  170284. /* Advance past the RSTn marker */
  170285. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  170286. return FALSE;
  170287. /* Re-initialize DC predictions to 0 */
  170288. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  170289. entropy->saved.last_dc_val[ci] = 0;
  170290. /* Re-init EOB run count, too */
  170291. entropy->saved.EOBRUN = 0;
  170292. /* Reset restart counter */
  170293. entropy->restarts_to_go = cinfo->restart_interval;
  170294. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  170295. * against a marker. In that case we will end up treating the next data
  170296. * segment as empty, and we can avoid producing bogus output pixels by
  170297. * leaving the flag set.
  170298. */
  170299. if (cinfo->unread_marker == 0)
  170300. entropy->pub.insufficient_data = FALSE;
  170301. return TRUE;
  170302. }
  170303. /*
  170304. * Huffman MCU decoding.
  170305. * Each of these routines decodes and returns one MCU's worth of
  170306. * Huffman-compressed coefficients.
  170307. * The coefficients are reordered from zigzag order into natural array order,
  170308. * but are not dequantized.
  170309. *
  170310. * The i'th block of the MCU is stored into the block pointed to by
  170311. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  170312. *
  170313. * We return FALSE if data source requested suspension. In that case no
  170314. * changes have been made to permanent state. (Exception: some output
  170315. * coefficients may already have been assigned. This is harmless for
  170316. * spectral selection, since we'll just re-assign them on the next call.
  170317. * Successive approximation AC refinement has to be more careful, however.)
  170318. */
  170319. /*
  170320. * MCU decoding for DC initial scan (either spectral selection,
  170321. * or first pass of successive approximation).
  170322. */
  170323. METHODDEF(boolean)
  170324. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  170325. {
  170326. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  170327. int Al = cinfo->Al;
  170328. register int s, r;
  170329. int blkn, ci;
  170330. JBLOCKROW block;
  170331. BITREAD_STATE_VARS;
  170332. savable_state3 state;
  170333. d_derived_tbl * tbl;
  170334. jpeg_component_info * compptr;
  170335. /* Process restart marker if needed; may have to suspend */
  170336. if (cinfo->restart_interval) {
  170337. if (entropy->restarts_to_go == 0)
  170338. if (! process_restartp(cinfo))
  170339. return FALSE;
  170340. }
  170341. /* If we've run out of data, just leave the MCU set to zeroes.
  170342. * This way, we return uniform gray for the remainder of the segment.
  170343. */
  170344. if (! entropy->pub.insufficient_data) {
  170345. /* Load up working state */
  170346. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  170347. ASSIGN_STATE(state, entropy->saved);
  170348. /* Outer loop handles each block in the MCU */
  170349. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170350. block = MCU_data[blkn];
  170351. ci = cinfo->MCU_membership[blkn];
  170352. compptr = cinfo->cur_comp_info[ci];
  170353. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  170354. /* Decode a single block's worth of coefficients */
  170355. /* Section F.2.2.1: decode the DC coefficient difference */
  170356. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  170357. if (s) {
  170358. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170359. r = GET_BITS(s);
  170360. s = HUFF_EXTEND(r, s);
  170361. }
  170362. /* Convert DC difference to actual value, update last_dc_val */
  170363. s += state.last_dc_val[ci];
  170364. state.last_dc_val[ci] = s;
  170365. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  170366. (*block)[0] = (JCOEF) (s << Al);
  170367. }
  170368. /* Completed MCU, so update state */
  170369. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170370. ASSIGN_STATE(entropy->saved, state);
  170371. }
  170372. /* Account for restart interval (no-op if not using restarts) */
  170373. entropy->restarts_to_go--;
  170374. return TRUE;
  170375. }
  170376. /*
  170377. * MCU decoding for AC initial scan (either spectral selection,
  170378. * or first pass of successive approximation).
  170379. */
  170380. METHODDEF(boolean)
  170381. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  170382. {
  170383. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  170384. int Se = cinfo->Se;
  170385. int Al = cinfo->Al;
  170386. register int s, k, r;
  170387. unsigned int EOBRUN;
  170388. JBLOCKROW block;
  170389. BITREAD_STATE_VARS;
  170390. d_derived_tbl * tbl;
  170391. /* Process restart marker if needed; may have to suspend */
  170392. if (cinfo->restart_interval) {
  170393. if (entropy->restarts_to_go == 0)
  170394. if (! process_restartp(cinfo))
  170395. return FALSE;
  170396. }
  170397. /* If we've run out of data, just leave the MCU set to zeroes.
  170398. * This way, we return uniform gray for the remainder of the segment.
  170399. */
  170400. if (! entropy->pub.insufficient_data) {
  170401. /* Load up working state.
  170402. * We can avoid loading/saving bitread state if in an EOB run.
  170403. */
  170404. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  170405. /* There is always only one block per MCU */
  170406. if (EOBRUN > 0) /* if it's a band of zeroes... */
  170407. EOBRUN--; /* ...process it now (we do nothing) */
  170408. else {
  170409. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  170410. block = MCU_data[0];
  170411. tbl = entropy->ac_derived_tbl;
  170412. for (k = cinfo->Ss; k <= Se; k++) {
  170413. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  170414. r = s >> 4;
  170415. s &= 15;
  170416. if (s) {
  170417. k += r;
  170418. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170419. r = GET_BITS(s);
  170420. s = HUFF_EXTEND(r, s);
  170421. /* Scale and output coefficient in natural (dezigzagged) order */
  170422. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  170423. } else {
  170424. if (r == 15) { /* ZRL */
  170425. k += 15; /* skip 15 zeroes in band */
  170426. } else { /* EOBr, run length is 2^r + appended bits */
  170427. EOBRUN = 1 << r;
  170428. if (r) { /* EOBr, r > 0 */
  170429. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  170430. r = GET_BITS(r);
  170431. EOBRUN += r;
  170432. }
  170433. EOBRUN--; /* this band is processed at this moment */
  170434. break; /* force end-of-band */
  170435. }
  170436. }
  170437. }
  170438. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170439. }
  170440. /* Completed MCU, so update state */
  170441. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  170442. }
  170443. /* Account for restart interval (no-op if not using restarts) */
  170444. entropy->restarts_to_go--;
  170445. return TRUE;
  170446. }
  170447. /*
  170448. * MCU decoding for DC successive approximation refinement scan.
  170449. * Note: we assume such scans can be multi-component, although the spec
  170450. * is not very clear on the point.
  170451. */
  170452. METHODDEF(boolean)
  170453. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  170454. {
  170455. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  170456. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  170457. int blkn;
  170458. JBLOCKROW block;
  170459. BITREAD_STATE_VARS;
  170460. /* Process restart marker if needed; may have to suspend */
  170461. if (cinfo->restart_interval) {
  170462. if (entropy->restarts_to_go == 0)
  170463. if (! process_restartp(cinfo))
  170464. return FALSE;
  170465. }
  170466. /* Not worth the cycles to check insufficient_data here,
  170467. * since we will not change the data anyway if we read zeroes.
  170468. */
  170469. /* Load up working state */
  170470. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  170471. /* Outer loop handles each block in the MCU */
  170472. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170473. block = MCU_data[blkn];
  170474. /* Encoded data is simply the next bit of the two's-complement DC value */
  170475. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  170476. if (GET_BITS(1))
  170477. (*block)[0] |= p1;
  170478. /* Note: since we use |=, repeating the assignment later is safe */
  170479. }
  170480. /* Completed MCU, so update state */
  170481. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170482. /* Account for restart interval (no-op if not using restarts) */
  170483. entropy->restarts_to_go--;
  170484. return TRUE;
  170485. }
  170486. /*
  170487. * MCU decoding for AC successive approximation refinement scan.
  170488. */
  170489. METHODDEF(boolean)
  170490. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  170491. {
  170492. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  170493. int Se = cinfo->Se;
  170494. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  170495. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  170496. register int s, k, r;
  170497. unsigned int EOBRUN;
  170498. JBLOCKROW block;
  170499. JCOEFPTR thiscoef;
  170500. BITREAD_STATE_VARS;
  170501. d_derived_tbl * tbl;
  170502. int num_newnz;
  170503. int newnz_pos[DCTSIZE2];
  170504. /* Process restart marker if needed; may have to suspend */
  170505. if (cinfo->restart_interval) {
  170506. if (entropy->restarts_to_go == 0)
  170507. if (! process_restartp(cinfo))
  170508. return FALSE;
  170509. }
  170510. /* If we've run out of data, don't modify the MCU.
  170511. */
  170512. if (! entropy->pub.insufficient_data) {
  170513. /* Load up working state */
  170514. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  170515. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  170516. /* There is always only one block per MCU */
  170517. block = MCU_data[0];
  170518. tbl = entropy->ac_derived_tbl;
  170519. /* If we are forced to suspend, we must undo the assignments to any newly
  170520. * nonzero coefficients in the block, because otherwise we'd get confused
  170521. * next time about which coefficients were already nonzero.
  170522. * But we need not undo addition of bits to already-nonzero coefficients;
  170523. * instead, we can test the current bit to see if we already did it.
  170524. */
  170525. num_newnz = 0;
  170526. /* initialize coefficient loop counter to start of band */
  170527. k = cinfo->Ss;
  170528. if (EOBRUN == 0) {
  170529. for (; k <= Se; k++) {
  170530. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  170531. r = s >> 4;
  170532. s &= 15;
  170533. if (s) {
  170534. if (s != 1) /* size of new coef should always be 1 */
  170535. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  170536. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  170537. if (GET_BITS(1))
  170538. s = p1; /* newly nonzero coef is positive */
  170539. else
  170540. s = m1; /* newly nonzero coef is negative */
  170541. } else {
  170542. if (r != 15) {
  170543. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  170544. if (r) {
  170545. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  170546. r = GET_BITS(r);
  170547. EOBRUN += r;
  170548. }
  170549. break; /* rest of block is handled by EOB logic */
  170550. }
  170551. /* note s = 0 for processing ZRL */
  170552. }
  170553. /* Advance over already-nonzero coefs and r still-zero coefs,
  170554. * appending correction bits to the nonzeroes. A correction bit is 1
  170555. * if the absolute value of the coefficient must be increased.
  170556. */
  170557. do {
  170558. thiscoef = *block + jpeg_natural_order[k];
  170559. if (*thiscoef != 0) {
  170560. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  170561. if (GET_BITS(1)) {
  170562. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  170563. if (*thiscoef >= 0)
  170564. *thiscoef += p1;
  170565. else
  170566. *thiscoef += m1;
  170567. }
  170568. }
  170569. } else {
  170570. if (--r < 0)
  170571. break; /* reached target zero coefficient */
  170572. }
  170573. k++;
  170574. } while (k <= Se);
  170575. if (s) {
  170576. int pos = jpeg_natural_order[k];
  170577. /* Output newly nonzero coefficient */
  170578. (*block)[pos] = (JCOEF) s;
  170579. /* Remember its position in case we have to suspend */
  170580. newnz_pos[num_newnz++] = pos;
  170581. }
  170582. }
  170583. }
  170584. if (EOBRUN > 0) {
  170585. /* Scan any remaining coefficient positions after the end-of-band
  170586. * (the last newly nonzero coefficient, if any). Append a correction
  170587. * bit to each already-nonzero coefficient. A correction bit is 1
  170588. * if the absolute value of the coefficient must be increased.
  170589. */
  170590. for (; k <= Se; k++) {
  170591. thiscoef = *block + jpeg_natural_order[k];
  170592. if (*thiscoef != 0) {
  170593. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  170594. if (GET_BITS(1)) {
  170595. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  170596. if (*thiscoef >= 0)
  170597. *thiscoef += p1;
  170598. else
  170599. *thiscoef += m1;
  170600. }
  170601. }
  170602. }
  170603. }
  170604. /* Count one block completed in EOB run */
  170605. EOBRUN--;
  170606. }
  170607. /* Completed MCU, so update state */
  170608. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170609. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  170610. }
  170611. /* Account for restart interval (no-op if not using restarts) */
  170612. entropy->restarts_to_go--;
  170613. return TRUE;
  170614. undoit:
  170615. /* Re-zero any output coefficients that we made newly nonzero */
  170616. while (num_newnz > 0)
  170617. (*block)[newnz_pos[--num_newnz]] = 0;
  170618. return FALSE;
  170619. }
  170620. /*
  170621. * Module initialization routine for progressive Huffman entropy decoding.
  170622. */
  170623. GLOBAL(void)
  170624. jinit_phuff_decoder (j_decompress_ptr cinfo)
  170625. {
  170626. phuff_entropy_ptr2 entropy;
  170627. int *coef_bit_ptr;
  170628. int ci, i;
  170629. entropy = (phuff_entropy_ptr2)
  170630. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170631. SIZEOF(phuff_entropy_decoder));
  170632. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  170633. entropy->pub.start_pass = start_pass_phuff_decoder;
  170634. /* Mark derived tables unallocated */
  170635. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  170636. entropy->derived_tbls[i] = NULL;
  170637. }
  170638. /* Create progression status table */
  170639. cinfo->coef_bits = (int (*)[DCTSIZE2])
  170640. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170641. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  170642. coef_bit_ptr = & cinfo->coef_bits[0][0];
  170643. for (ci = 0; ci < cinfo->num_components; ci++)
  170644. for (i = 0; i < DCTSIZE2; i++)
  170645. *coef_bit_ptr++ = -1;
  170646. }
  170647. #endif /* D_PROGRESSIVE_SUPPORTED */
  170648. /*** End of inlined file: jdphuff.c ***/
  170649. /*** Start of inlined file: jdpostct.c ***/
  170650. #define JPEG_INTERNALS
  170651. /* Private buffer controller object */
  170652. typedef struct {
  170653. struct jpeg_d_post_controller pub; /* public fields */
  170654. /* Color quantization source buffer: this holds output data from
  170655. * the upsample/color conversion step to be passed to the quantizer.
  170656. * For two-pass color quantization, we need a full-image buffer;
  170657. * for one-pass operation, a strip buffer is sufficient.
  170658. */
  170659. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  170660. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  170661. JDIMENSION strip_height; /* buffer size in rows */
  170662. /* for two-pass mode only: */
  170663. JDIMENSION starting_row; /* row # of first row in current strip */
  170664. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  170665. } my_post_controller;
  170666. typedef my_post_controller * my_post_ptr;
  170667. /* Forward declarations */
  170668. METHODDEF(void) post_process_1pass
  170669. JPP((j_decompress_ptr cinfo,
  170670. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  170671. JDIMENSION in_row_groups_avail,
  170672. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170673. JDIMENSION out_rows_avail));
  170674. #ifdef QUANT_2PASS_SUPPORTED
  170675. METHODDEF(void) post_process_prepass
  170676. JPP((j_decompress_ptr cinfo,
  170677. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  170678. JDIMENSION in_row_groups_avail,
  170679. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170680. JDIMENSION out_rows_avail));
  170681. METHODDEF(void) post_process_2pass
  170682. JPP((j_decompress_ptr cinfo,
  170683. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  170684. JDIMENSION in_row_groups_avail,
  170685. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170686. JDIMENSION out_rows_avail));
  170687. #endif
  170688. /*
  170689. * Initialize for a processing pass.
  170690. */
  170691. METHODDEF(void)
  170692. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  170693. {
  170694. my_post_ptr post = (my_post_ptr) cinfo->post;
  170695. switch (pass_mode) {
  170696. case JBUF_PASS_THRU:
  170697. if (cinfo->quantize_colors) {
  170698. /* Single-pass processing with color quantization. */
  170699. post->pub.post_process_data = post_process_1pass;
  170700. /* We could be doing buffered-image output before starting a 2-pass
  170701. * color quantization; in that case, jinit_d_post_controller did not
  170702. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  170703. */
  170704. if (post->buffer == NULL) {
  170705. post->buffer = (*cinfo->mem->access_virt_sarray)
  170706. ((j_common_ptr) cinfo, post->whole_image,
  170707. (JDIMENSION) 0, post->strip_height, TRUE);
  170708. }
  170709. } else {
  170710. /* For single-pass processing without color quantization,
  170711. * I have no work to do; just call the upsampler directly.
  170712. */
  170713. post->pub.post_process_data = cinfo->upsample->upsample;
  170714. }
  170715. break;
  170716. #ifdef QUANT_2PASS_SUPPORTED
  170717. case JBUF_SAVE_AND_PASS:
  170718. /* First pass of 2-pass quantization */
  170719. if (post->whole_image == NULL)
  170720. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170721. post->pub.post_process_data = post_process_prepass;
  170722. break;
  170723. case JBUF_CRANK_DEST:
  170724. /* Second pass of 2-pass quantization */
  170725. if (post->whole_image == NULL)
  170726. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170727. post->pub.post_process_data = post_process_2pass;
  170728. break;
  170729. #endif /* QUANT_2PASS_SUPPORTED */
  170730. default:
  170731. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170732. break;
  170733. }
  170734. post->starting_row = post->next_row = 0;
  170735. }
  170736. /*
  170737. * Process some data in the one-pass (strip buffer) case.
  170738. * This is used for color precision reduction as well as one-pass quantization.
  170739. */
  170740. METHODDEF(void)
  170741. post_process_1pass (j_decompress_ptr cinfo,
  170742. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  170743. JDIMENSION in_row_groups_avail,
  170744. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170745. JDIMENSION out_rows_avail)
  170746. {
  170747. my_post_ptr post = (my_post_ptr) cinfo->post;
  170748. JDIMENSION num_rows, max_rows;
  170749. /* Fill the buffer, but not more than what we can dump out in one go. */
  170750. /* Note we rely on the upsampler to detect bottom of image. */
  170751. max_rows = out_rows_avail - *out_row_ctr;
  170752. if (max_rows > post->strip_height)
  170753. max_rows = post->strip_height;
  170754. num_rows = 0;
  170755. (*cinfo->upsample->upsample) (cinfo,
  170756. input_buf, in_row_group_ctr, in_row_groups_avail,
  170757. post->buffer, &num_rows, max_rows);
  170758. /* Quantize and emit data. */
  170759. (*cinfo->cquantize->color_quantize) (cinfo,
  170760. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  170761. *out_row_ctr += num_rows;
  170762. }
  170763. #ifdef QUANT_2PASS_SUPPORTED
  170764. /*
  170765. * Process some data in the first pass of 2-pass quantization.
  170766. */
  170767. METHODDEF(void)
  170768. post_process_prepass (j_decompress_ptr cinfo,
  170769. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  170770. JDIMENSION in_row_groups_avail,
  170771. JSAMPARRAY, JDIMENSION *out_row_ctr,
  170772. JDIMENSION)
  170773. {
  170774. my_post_ptr post = (my_post_ptr) cinfo->post;
  170775. JDIMENSION old_next_row, num_rows;
  170776. /* Reposition virtual buffer if at start of strip. */
  170777. if (post->next_row == 0) {
  170778. post->buffer = (*cinfo->mem->access_virt_sarray)
  170779. ((j_common_ptr) cinfo, post->whole_image,
  170780. post->starting_row, post->strip_height, TRUE);
  170781. }
  170782. /* Upsample some data (up to a strip height's worth). */
  170783. old_next_row = post->next_row;
  170784. (*cinfo->upsample->upsample) (cinfo,
  170785. input_buf, in_row_group_ctr, in_row_groups_avail,
  170786. post->buffer, &post->next_row, post->strip_height);
  170787. /* Allow quantizer to scan new data. No data is emitted, */
  170788. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  170789. if (post->next_row > old_next_row) {
  170790. num_rows = post->next_row - old_next_row;
  170791. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  170792. (JSAMPARRAY) NULL, (int) num_rows);
  170793. *out_row_ctr += num_rows;
  170794. }
  170795. /* Advance if we filled the strip. */
  170796. if (post->next_row >= post->strip_height) {
  170797. post->starting_row += post->strip_height;
  170798. post->next_row = 0;
  170799. }
  170800. }
  170801. /*
  170802. * Process some data in the second pass of 2-pass quantization.
  170803. */
  170804. METHODDEF(void)
  170805. post_process_2pass (j_decompress_ptr cinfo,
  170806. JSAMPIMAGE, JDIMENSION *,
  170807. JDIMENSION,
  170808. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170809. JDIMENSION out_rows_avail)
  170810. {
  170811. my_post_ptr post = (my_post_ptr) cinfo->post;
  170812. JDIMENSION num_rows, max_rows;
  170813. /* Reposition virtual buffer if at start of strip. */
  170814. if (post->next_row == 0) {
  170815. post->buffer = (*cinfo->mem->access_virt_sarray)
  170816. ((j_common_ptr) cinfo, post->whole_image,
  170817. post->starting_row, post->strip_height, FALSE);
  170818. }
  170819. /* Determine number of rows to emit. */
  170820. num_rows = post->strip_height - post->next_row; /* available in strip */
  170821. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  170822. if (num_rows > max_rows)
  170823. num_rows = max_rows;
  170824. /* We have to check bottom of image here, can't depend on upsampler. */
  170825. max_rows = cinfo->output_height - post->starting_row;
  170826. if (num_rows > max_rows)
  170827. num_rows = max_rows;
  170828. /* Quantize and emit data. */
  170829. (*cinfo->cquantize->color_quantize) (cinfo,
  170830. post->buffer + post->next_row, output_buf + *out_row_ctr,
  170831. (int) num_rows);
  170832. *out_row_ctr += num_rows;
  170833. /* Advance if we filled the strip. */
  170834. post->next_row += num_rows;
  170835. if (post->next_row >= post->strip_height) {
  170836. post->starting_row += post->strip_height;
  170837. post->next_row = 0;
  170838. }
  170839. }
  170840. #endif /* QUANT_2PASS_SUPPORTED */
  170841. /*
  170842. * Initialize postprocessing controller.
  170843. */
  170844. GLOBAL(void)
  170845. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  170846. {
  170847. my_post_ptr post;
  170848. post = (my_post_ptr)
  170849. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170850. SIZEOF(my_post_controller));
  170851. cinfo->post = (struct jpeg_d_post_controller *) post;
  170852. post->pub.start_pass = start_pass_dpost;
  170853. post->whole_image = NULL; /* flag for no virtual arrays */
  170854. post->buffer = NULL; /* flag for no strip buffer */
  170855. /* Create the quantization buffer, if needed */
  170856. if (cinfo->quantize_colors) {
  170857. /* The buffer strip height is max_v_samp_factor, which is typically
  170858. * an efficient number of rows for upsampling to return.
  170859. * (In the presence of output rescaling, we might want to be smarter?)
  170860. */
  170861. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  170862. if (need_full_buffer) {
  170863. /* Two-pass color quantization: need full-image storage. */
  170864. /* We round up the number of rows to a multiple of the strip height. */
  170865. #ifdef QUANT_2PASS_SUPPORTED
  170866. post->whole_image = (*cinfo->mem->request_virt_sarray)
  170867. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  170868. cinfo->output_width * cinfo->out_color_components,
  170869. (JDIMENSION) jround_up((long) cinfo->output_height,
  170870. (long) post->strip_height),
  170871. post->strip_height);
  170872. #else
  170873. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170874. #endif /* QUANT_2PASS_SUPPORTED */
  170875. } else {
  170876. /* One-pass color quantization: just make a strip buffer. */
  170877. post->buffer = (*cinfo->mem->alloc_sarray)
  170878. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170879. cinfo->output_width * cinfo->out_color_components,
  170880. post->strip_height);
  170881. }
  170882. }
  170883. }
  170884. /*** End of inlined file: jdpostct.c ***/
  170885. #undef FIX
  170886. /*** Start of inlined file: jdsample.c ***/
  170887. #define JPEG_INTERNALS
  170888. /* Pointer to routine to upsample a single component */
  170889. typedef JMETHOD(void, upsample1_ptr,
  170890. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170891. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  170892. /* Private subobject */
  170893. typedef struct {
  170894. struct jpeg_upsampler pub; /* public fields */
  170895. /* Color conversion buffer. When using separate upsampling and color
  170896. * conversion steps, this buffer holds one upsampled row group until it
  170897. * has been color converted and output.
  170898. * Note: we do not allocate any storage for component(s) which are full-size,
  170899. * ie do not need rescaling. The corresponding entry of color_buf[] is
  170900. * simply set to point to the input data array, thereby avoiding copying.
  170901. */
  170902. JSAMPARRAY color_buf[MAX_COMPONENTS];
  170903. /* Per-component upsampling method pointers */
  170904. upsample1_ptr methods[MAX_COMPONENTS];
  170905. int next_row_out; /* counts rows emitted from color_buf */
  170906. JDIMENSION rows_to_go; /* counts rows remaining in image */
  170907. /* Height of an input row group for each component. */
  170908. int rowgroup_height[MAX_COMPONENTS];
  170909. /* These arrays save pixel expansion factors so that int_expand need not
  170910. * recompute them each time. They are unused for other upsampling methods.
  170911. */
  170912. UINT8 h_expand[MAX_COMPONENTS];
  170913. UINT8 v_expand[MAX_COMPONENTS];
  170914. } my_upsampler2;
  170915. typedef my_upsampler2 * my_upsample_ptr2;
  170916. /*
  170917. * Initialize for an upsampling pass.
  170918. */
  170919. METHODDEF(void)
  170920. start_pass_upsample (j_decompress_ptr cinfo)
  170921. {
  170922. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  170923. /* Mark the conversion buffer empty */
  170924. upsample->next_row_out = cinfo->max_v_samp_factor;
  170925. /* Initialize total-height counter for detecting bottom of image */
  170926. upsample->rows_to_go = cinfo->output_height;
  170927. }
  170928. /*
  170929. * Control routine to do upsampling (and color conversion).
  170930. *
  170931. * In this version we upsample each component independently.
  170932. * We upsample one row group into the conversion buffer, then apply
  170933. * color conversion a row at a time.
  170934. */
  170935. METHODDEF(void)
  170936. sep_upsample (j_decompress_ptr cinfo,
  170937. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  170938. JDIMENSION,
  170939. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170940. JDIMENSION out_rows_avail)
  170941. {
  170942. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  170943. int ci;
  170944. jpeg_component_info * compptr;
  170945. JDIMENSION num_rows;
  170946. /* Fill the conversion buffer, if it's empty */
  170947. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  170948. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170949. ci++, compptr++) {
  170950. /* Invoke per-component upsample method. Notice we pass a POINTER
  170951. * to color_buf[ci], so that fullsize_upsample can change it.
  170952. */
  170953. (*upsample->methods[ci]) (cinfo, compptr,
  170954. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  170955. upsample->color_buf + ci);
  170956. }
  170957. upsample->next_row_out = 0;
  170958. }
  170959. /* Color-convert and emit rows */
  170960. /* How many we have in the buffer: */
  170961. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  170962. /* Not more than the distance to the end of the image. Need this test
  170963. * in case the image height is not a multiple of max_v_samp_factor:
  170964. */
  170965. if (num_rows > upsample->rows_to_go)
  170966. num_rows = upsample->rows_to_go;
  170967. /* And not more than what the client can accept: */
  170968. out_rows_avail -= *out_row_ctr;
  170969. if (num_rows > out_rows_avail)
  170970. num_rows = out_rows_avail;
  170971. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  170972. (JDIMENSION) upsample->next_row_out,
  170973. output_buf + *out_row_ctr,
  170974. (int) num_rows);
  170975. /* Adjust counts */
  170976. *out_row_ctr += num_rows;
  170977. upsample->rows_to_go -= num_rows;
  170978. upsample->next_row_out += num_rows;
  170979. /* When the buffer is emptied, declare this input row group consumed */
  170980. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  170981. (*in_row_group_ctr)++;
  170982. }
  170983. /*
  170984. * These are the routines invoked by sep_upsample to upsample pixel values
  170985. * of a single component. One row group is processed per call.
  170986. */
  170987. /*
  170988. * For full-size components, we just make color_buf[ci] point at the
  170989. * input buffer, and thus avoid copying any data. Note that this is
  170990. * safe only because sep_upsample doesn't declare the input row group
  170991. * "consumed" until we are done color converting and emitting it.
  170992. */
  170993. METHODDEF(void)
  170994. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  170995. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  170996. {
  170997. *output_data_ptr = input_data;
  170998. }
  170999. /*
  171000. * This is a no-op version used for "uninteresting" components.
  171001. * These components will not be referenced by color conversion.
  171002. */
  171003. METHODDEF(void)
  171004. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  171005. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  171006. {
  171007. *output_data_ptr = NULL; /* safety check */
  171008. }
  171009. /*
  171010. * This version handles any integral sampling ratios.
  171011. * This is not used for typical JPEG files, so it need not be fast.
  171012. * Nor, for that matter, is it particularly accurate: the algorithm is
  171013. * simple replication of the input pixel onto the corresponding output
  171014. * pixels. The hi-falutin sampling literature refers to this as a
  171015. * "box filter". A box filter tends to introduce visible artifacts,
  171016. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  171017. * you would be well advised to improve this code.
  171018. */
  171019. METHODDEF(void)
  171020. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  171021. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  171022. {
  171023. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  171024. JSAMPARRAY output_data = *output_data_ptr;
  171025. register JSAMPROW inptr, outptr;
  171026. register JSAMPLE invalue;
  171027. register int h;
  171028. JSAMPROW outend;
  171029. int h_expand, v_expand;
  171030. int inrow, outrow;
  171031. h_expand = upsample->h_expand[compptr->component_index];
  171032. v_expand = upsample->v_expand[compptr->component_index];
  171033. inrow = outrow = 0;
  171034. while (outrow < cinfo->max_v_samp_factor) {
  171035. /* Generate one output row with proper horizontal expansion */
  171036. inptr = input_data[inrow];
  171037. outptr = output_data[outrow];
  171038. outend = outptr + cinfo->output_width;
  171039. while (outptr < outend) {
  171040. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  171041. for (h = h_expand; h > 0; h--) {
  171042. *outptr++ = invalue;
  171043. }
  171044. }
  171045. /* Generate any additional output rows by duplicating the first one */
  171046. if (v_expand > 1) {
  171047. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  171048. v_expand-1, cinfo->output_width);
  171049. }
  171050. inrow++;
  171051. outrow += v_expand;
  171052. }
  171053. }
  171054. /*
  171055. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  171056. * It's still a box filter.
  171057. */
  171058. METHODDEF(void)
  171059. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  171060. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  171061. {
  171062. JSAMPARRAY output_data = *output_data_ptr;
  171063. register JSAMPROW inptr, outptr;
  171064. register JSAMPLE invalue;
  171065. JSAMPROW outend;
  171066. int inrow;
  171067. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  171068. inptr = input_data[inrow];
  171069. outptr = output_data[inrow];
  171070. outend = outptr + cinfo->output_width;
  171071. while (outptr < outend) {
  171072. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  171073. *outptr++ = invalue;
  171074. *outptr++ = invalue;
  171075. }
  171076. }
  171077. }
  171078. /*
  171079. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  171080. * It's still a box filter.
  171081. */
  171082. METHODDEF(void)
  171083. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  171084. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  171085. {
  171086. JSAMPARRAY output_data = *output_data_ptr;
  171087. register JSAMPROW inptr, outptr;
  171088. register JSAMPLE invalue;
  171089. JSAMPROW outend;
  171090. int inrow, outrow;
  171091. inrow = outrow = 0;
  171092. while (outrow < cinfo->max_v_samp_factor) {
  171093. inptr = input_data[inrow];
  171094. outptr = output_data[outrow];
  171095. outend = outptr + cinfo->output_width;
  171096. while (outptr < outend) {
  171097. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  171098. *outptr++ = invalue;
  171099. *outptr++ = invalue;
  171100. }
  171101. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  171102. 1, cinfo->output_width);
  171103. inrow++;
  171104. outrow += 2;
  171105. }
  171106. }
  171107. /*
  171108. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  171109. *
  171110. * The upsampling algorithm is linear interpolation between pixel centers,
  171111. * also known as a "triangle filter". This is a good compromise between
  171112. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  171113. * of the way between input pixel centers.
  171114. *
  171115. * A note about the "bias" calculations: when rounding fractional values to
  171116. * integer, we do not want to always round 0.5 up to the next integer.
  171117. * If we did that, we'd introduce a noticeable bias towards larger values.
  171118. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  171119. * alternate pixel locations (a simple ordered dither pattern).
  171120. */
  171121. METHODDEF(void)
  171122. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  171123. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  171124. {
  171125. JSAMPARRAY output_data = *output_data_ptr;
  171126. register JSAMPROW inptr, outptr;
  171127. register int invalue;
  171128. register JDIMENSION colctr;
  171129. int inrow;
  171130. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  171131. inptr = input_data[inrow];
  171132. outptr = output_data[inrow];
  171133. /* Special case for first column */
  171134. invalue = GETJSAMPLE(*inptr++);
  171135. *outptr++ = (JSAMPLE) invalue;
  171136. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  171137. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  171138. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  171139. invalue = GETJSAMPLE(*inptr++) * 3;
  171140. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  171141. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  171142. }
  171143. /* Special case for last column */
  171144. invalue = GETJSAMPLE(*inptr);
  171145. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  171146. *outptr++ = (JSAMPLE) invalue;
  171147. }
  171148. }
  171149. /*
  171150. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  171151. * Again a triangle filter; see comments for h2v1 case, above.
  171152. *
  171153. * It is OK for us to reference the adjacent input rows because we demanded
  171154. * context from the main buffer controller (see initialization code).
  171155. */
  171156. METHODDEF(void)
  171157. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  171158. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  171159. {
  171160. JSAMPARRAY output_data = *output_data_ptr;
  171161. register JSAMPROW inptr0, inptr1, outptr;
  171162. #if BITS_IN_JSAMPLE == 8
  171163. register int thiscolsum, lastcolsum, nextcolsum;
  171164. #else
  171165. register INT32 thiscolsum, lastcolsum, nextcolsum;
  171166. #endif
  171167. register JDIMENSION colctr;
  171168. int inrow, outrow, v;
  171169. inrow = outrow = 0;
  171170. while (outrow < cinfo->max_v_samp_factor) {
  171171. for (v = 0; v < 2; v++) {
  171172. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  171173. inptr0 = input_data[inrow];
  171174. if (v == 0) /* next nearest is row above */
  171175. inptr1 = input_data[inrow-1];
  171176. else /* next nearest is row below */
  171177. inptr1 = input_data[inrow+1];
  171178. outptr = output_data[outrow++];
  171179. /* Special case for first column */
  171180. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  171181. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  171182. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  171183. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  171184. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  171185. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  171186. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  171187. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  171188. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  171189. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  171190. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  171191. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  171192. }
  171193. /* Special case for last column */
  171194. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  171195. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  171196. }
  171197. inrow++;
  171198. }
  171199. }
  171200. /*
  171201. * Module initialization routine for upsampling.
  171202. */
  171203. GLOBAL(void)
  171204. jinit_upsampler (j_decompress_ptr cinfo)
  171205. {
  171206. my_upsample_ptr2 upsample;
  171207. int ci;
  171208. jpeg_component_info * compptr;
  171209. boolean need_buffer, do_fancy;
  171210. int h_in_group, v_in_group, h_out_group, v_out_group;
  171211. upsample = (my_upsample_ptr2)
  171212. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171213. SIZEOF(my_upsampler2));
  171214. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  171215. upsample->pub.start_pass = start_pass_upsample;
  171216. upsample->pub.upsample = sep_upsample;
  171217. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  171218. if (cinfo->CCIR601_sampling) /* this isn't supported */
  171219. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  171220. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  171221. * so don't ask for it.
  171222. */
  171223. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  171224. /* Verify we can handle the sampling factors, select per-component methods,
  171225. * and create storage as needed.
  171226. */
  171227. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171228. ci++, compptr++) {
  171229. /* Compute size of an "input group" after IDCT scaling. This many samples
  171230. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  171231. */
  171232. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  171233. cinfo->min_DCT_scaled_size;
  171234. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171235. cinfo->min_DCT_scaled_size;
  171236. h_out_group = cinfo->max_h_samp_factor;
  171237. v_out_group = cinfo->max_v_samp_factor;
  171238. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  171239. need_buffer = TRUE;
  171240. if (! compptr->component_needed) {
  171241. /* Don't bother to upsample an uninteresting component. */
  171242. upsample->methods[ci] = noop_upsample;
  171243. need_buffer = FALSE;
  171244. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  171245. /* Fullsize components can be processed without any work. */
  171246. upsample->methods[ci] = fullsize_upsample;
  171247. need_buffer = FALSE;
  171248. } else if (h_in_group * 2 == h_out_group &&
  171249. v_in_group == v_out_group) {
  171250. /* Special cases for 2h1v upsampling */
  171251. if (do_fancy && compptr->downsampled_width > 2)
  171252. upsample->methods[ci] = h2v1_fancy_upsample;
  171253. else
  171254. upsample->methods[ci] = h2v1_upsample;
  171255. } else if (h_in_group * 2 == h_out_group &&
  171256. v_in_group * 2 == v_out_group) {
  171257. /* Special cases for 2h2v upsampling */
  171258. if (do_fancy && compptr->downsampled_width > 2) {
  171259. upsample->methods[ci] = h2v2_fancy_upsample;
  171260. upsample->pub.need_context_rows = TRUE;
  171261. } else
  171262. upsample->methods[ci] = h2v2_upsample;
  171263. } else if ((h_out_group % h_in_group) == 0 &&
  171264. (v_out_group % v_in_group) == 0) {
  171265. /* Generic integral-factors upsampling method */
  171266. upsample->methods[ci] = int_upsample;
  171267. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  171268. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  171269. } else
  171270. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  171271. if (need_buffer) {
  171272. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  171273. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171274. (JDIMENSION) jround_up((long) cinfo->output_width,
  171275. (long) cinfo->max_h_samp_factor),
  171276. (JDIMENSION) cinfo->max_v_samp_factor);
  171277. }
  171278. }
  171279. }
  171280. /*** End of inlined file: jdsample.c ***/
  171281. /*** Start of inlined file: jdtrans.c ***/
  171282. #define JPEG_INTERNALS
  171283. /* Forward declarations */
  171284. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  171285. /*
  171286. * Read the coefficient arrays from a JPEG file.
  171287. * jpeg_read_header must be completed before calling this.
  171288. *
  171289. * The entire image is read into a set of virtual coefficient-block arrays,
  171290. * one per component. The return value is a pointer to the array of
  171291. * virtual-array descriptors. These can be manipulated directly via the
  171292. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  171293. * To release the memory occupied by the virtual arrays, call
  171294. * jpeg_finish_decompress() when done with the data.
  171295. *
  171296. * An alternative usage is to simply obtain access to the coefficient arrays
  171297. * during a buffered-image-mode decompression operation. This is allowed
  171298. * after any jpeg_finish_output() call. The arrays can be accessed until
  171299. * jpeg_finish_decompress() is called. (Note that any call to the library
  171300. * may reposition the arrays, so don't rely on access_virt_barray() results
  171301. * to stay valid across library calls.)
  171302. *
  171303. * Returns NULL if suspended. This case need be checked only if
  171304. * a suspending data source is used.
  171305. */
  171306. GLOBAL(jvirt_barray_ptr *)
  171307. jpeg_read_coefficients (j_decompress_ptr cinfo)
  171308. {
  171309. if (cinfo->global_state == DSTATE_READY) {
  171310. /* First call: initialize active modules */
  171311. transdecode_master_selection(cinfo);
  171312. cinfo->global_state = DSTATE_RDCOEFS;
  171313. }
  171314. if (cinfo->global_state == DSTATE_RDCOEFS) {
  171315. /* Absorb whole file into the coef buffer */
  171316. for (;;) {
  171317. int retcode;
  171318. /* Call progress monitor hook if present */
  171319. if (cinfo->progress != NULL)
  171320. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  171321. /* Absorb some more input */
  171322. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  171323. if (retcode == JPEG_SUSPENDED)
  171324. return NULL;
  171325. if (retcode == JPEG_REACHED_EOI)
  171326. break;
  171327. /* Advance progress counter if appropriate */
  171328. if (cinfo->progress != NULL &&
  171329. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  171330. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  171331. /* startup underestimated number of scans; ratchet up one scan */
  171332. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  171333. }
  171334. }
  171335. }
  171336. /* Set state so that jpeg_finish_decompress does the right thing */
  171337. cinfo->global_state = DSTATE_STOPPING;
  171338. }
  171339. /* At this point we should be in state DSTATE_STOPPING if being used
  171340. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  171341. * to the coefficients during a full buffered-image-mode decompression.
  171342. */
  171343. if ((cinfo->global_state == DSTATE_STOPPING ||
  171344. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  171345. return cinfo->coef->coef_arrays;
  171346. }
  171347. /* Oops, improper usage */
  171348. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  171349. return NULL; /* keep compiler happy */
  171350. }
  171351. /*
  171352. * Master selection of decompression modules for transcoding.
  171353. * This substitutes for jdmaster.c's initialization of the full decompressor.
  171354. */
  171355. LOCAL(void)
  171356. transdecode_master_selection (j_decompress_ptr cinfo)
  171357. {
  171358. /* This is effectively a buffered-image operation. */
  171359. cinfo->buffered_image = TRUE;
  171360. /* Entropy decoding: either Huffman or arithmetic coding. */
  171361. if (cinfo->arith_code) {
  171362. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  171363. } else {
  171364. if (cinfo->progressive_mode) {
  171365. #ifdef D_PROGRESSIVE_SUPPORTED
  171366. jinit_phuff_decoder(cinfo);
  171367. #else
  171368. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171369. #endif
  171370. } else
  171371. jinit_huff_decoder(cinfo);
  171372. }
  171373. /* Always get a full-image coefficient buffer. */
  171374. jinit_d_coef_controller(cinfo, TRUE);
  171375. /* We can now tell the memory manager to allocate virtual arrays. */
  171376. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  171377. /* Initialize input side of decompressor to consume first scan. */
  171378. (*cinfo->inputctl->start_input_pass) (cinfo);
  171379. /* Initialize progress monitoring. */
  171380. if (cinfo->progress != NULL) {
  171381. int nscans;
  171382. /* Estimate number of scans to set pass_limit. */
  171383. if (cinfo->progressive_mode) {
  171384. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  171385. nscans = 2 + 3 * cinfo->num_components;
  171386. } else if (cinfo->inputctl->has_multiple_scans) {
  171387. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  171388. nscans = cinfo->num_components;
  171389. } else {
  171390. nscans = 1;
  171391. }
  171392. cinfo->progress->pass_counter = 0L;
  171393. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  171394. cinfo->progress->completed_passes = 0;
  171395. cinfo->progress->total_passes = 1;
  171396. }
  171397. }
  171398. /*** End of inlined file: jdtrans.c ***/
  171399. /*** Start of inlined file: jfdctflt.c ***/
  171400. #define JPEG_INTERNALS
  171401. #ifdef DCT_FLOAT_SUPPORTED
  171402. /*
  171403. * This module is specialized to the case DCTSIZE = 8.
  171404. */
  171405. #if DCTSIZE != 8
  171406. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  171407. #endif
  171408. /*
  171409. * Perform the forward DCT on one block of samples.
  171410. */
  171411. GLOBAL(void)
  171412. jpeg_fdct_float (FAST_FLOAT * data)
  171413. {
  171414. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  171415. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  171416. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  171417. FAST_FLOAT *dataptr;
  171418. int ctr;
  171419. /* Pass 1: process rows. */
  171420. dataptr = data;
  171421. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  171422. tmp0 = dataptr[0] + dataptr[7];
  171423. tmp7 = dataptr[0] - dataptr[7];
  171424. tmp1 = dataptr[1] + dataptr[6];
  171425. tmp6 = dataptr[1] - dataptr[6];
  171426. tmp2 = dataptr[2] + dataptr[5];
  171427. tmp5 = dataptr[2] - dataptr[5];
  171428. tmp3 = dataptr[3] + dataptr[4];
  171429. tmp4 = dataptr[3] - dataptr[4];
  171430. /* Even part */
  171431. tmp10 = tmp0 + tmp3; /* phase 2 */
  171432. tmp13 = tmp0 - tmp3;
  171433. tmp11 = tmp1 + tmp2;
  171434. tmp12 = tmp1 - tmp2;
  171435. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  171436. dataptr[4] = tmp10 - tmp11;
  171437. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  171438. dataptr[2] = tmp13 + z1; /* phase 5 */
  171439. dataptr[6] = tmp13 - z1;
  171440. /* Odd part */
  171441. tmp10 = tmp4 + tmp5; /* phase 2 */
  171442. tmp11 = tmp5 + tmp6;
  171443. tmp12 = tmp6 + tmp7;
  171444. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  171445. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  171446. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  171447. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  171448. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  171449. z11 = tmp7 + z3; /* phase 5 */
  171450. z13 = tmp7 - z3;
  171451. dataptr[5] = z13 + z2; /* phase 6 */
  171452. dataptr[3] = z13 - z2;
  171453. dataptr[1] = z11 + z4;
  171454. dataptr[7] = z11 - z4;
  171455. dataptr += DCTSIZE; /* advance pointer to next row */
  171456. }
  171457. /* Pass 2: process columns. */
  171458. dataptr = data;
  171459. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  171460. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  171461. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  171462. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  171463. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  171464. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  171465. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  171466. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  171467. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  171468. /* Even part */
  171469. tmp10 = tmp0 + tmp3; /* phase 2 */
  171470. tmp13 = tmp0 - tmp3;
  171471. tmp11 = tmp1 + tmp2;
  171472. tmp12 = tmp1 - tmp2;
  171473. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  171474. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  171475. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  171476. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  171477. dataptr[DCTSIZE*6] = tmp13 - z1;
  171478. /* Odd part */
  171479. tmp10 = tmp4 + tmp5; /* phase 2 */
  171480. tmp11 = tmp5 + tmp6;
  171481. tmp12 = tmp6 + tmp7;
  171482. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  171483. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  171484. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  171485. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  171486. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  171487. z11 = tmp7 + z3; /* phase 5 */
  171488. z13 = tmp7 - z3;
  171489. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  171490. dataptr[DCTSIZE*3] = z13 - z2;
  171491. dataptr[DCTSIZE*1] = z11 + z4;
  171492. dataptr[DCTSIZE*7] = z11 - z4;
  171493. dataptr++; /* advance pointer to next column */
  171494. }
  171495. }
  171496. #endif /* DCT_FLOAT_SUPPORTED */
  171497. /*** End of inlined file: jfdctflt.c ***/
  171498. /*** Start of inlined file: jfdctint.c ***/
  171499. #define JPEG_INTERNALS
  171500. #ifdef DCT_ISLOW_SUPPORTED
  171501. /*
  171502. * This module is specialized to the case DCTSIZE = 8.
  171503. */
  171504. #if DCTSIZE != 8
  171505. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  171506. #endif
  171507. /*
  171508. * The poop on this scaling stuff is as follows:
  171509. *
  171510. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  171511. * larger than the true DCT outputs. The final outputs are therefore
  171512. * a factor of N larger than desired; since N=8 this can be cured by
  171513. * a simple right shift at the end of the algorithm. The advantage of
  171514. * this arrangement is that we save two multiplications per 1-D DCT,
  171515. * because the y0 and y4 outputs need not be divided by sqrt(N).
  171516. * In the IJG code, this factor of 8 is removed by the quantization step
  171517. * (in jcdctmgr.c), NOT in this module.
  171518. *
  171519. * We have to do addition and subtraction of the integer inputs, which
  171520. * is no problem, and multiplication by fractional constants, which is
  171521. * a problem to do in integer arithmetic. We multiply all the constants
  171522. * by CONST_SCALE and convert them to integer constants (thus retaining
  171523. * CONST_BITS bits of precision in the constants). After doing a
  171524. * multiplication we have to divide the product by CONST_SCALE, with proper
  171525. * rounding, to produce the correct output. This division can be done
  171526. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  171527. * as long as possible so that partial sums can be added together with
  171528. * full fractional precision.
  171529. *
  171530. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  171531. * they are represented to better-than-integral precision. These outputs
  171532. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  171533. * with the recommended scaling. (For 12-bit sample data, the intermediate
  171534. * array is INT32 anyway.)
  171535. *
  171536. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  171537. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  171538. * shows that the values given below are the most effective.
  171539. */
  171540. #if BITS_IN_JSAMPLE == 8
  171541. #define CONST_BITS 13
  171542. #define PASS1_BITS 2
  171543. #else
  171544. #define CONST_BITS 13
  171545. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  171546. #endif
  171547. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  171548. * causing a lot of useless floating-point operations at run time.
  171549. * To get around this we use the following pre-calculated constants.
  171550. * If you change CONST_BITS you may want to add appropriate values.
  171551. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  171552. */
  171553. #if CONST_BITS == 13
  171554. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  171555. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  171556. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  171557. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  171558. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  171559. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  171560. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  171561. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  171562. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  171563. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  171564. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  171565. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  171566. #else
  171567. #define FIX_0_298631336 FIX(0.298631336)
  171568. #define FIX_0_390180644 FIX(0.390180644)
  171569. #define FIX_0_541196100 FIX(0.541196100)
  171570. #define FIX_0_765366865 FIX(0.765366865)
  171571. #define FIX_0_899976223 FIX(0.899976223)
  171572. #define FIX_1_175875602 FIX(1.175875602)
  171573. #define FIX_1_501321110 FIX(1.501321110)
  171574. #define FIX_1_847759065 FIX(1.847759065)
  171575. #define FIX_1_961570560 FIX(1.961570560)
  171576. #define FIX_2_053119869 FIX(2.053119869)
  171577. #define FIX_2_562915447 FIX(2.562915447)
  171578. #define FIX_3_072711026 FIX(3.072711026)
  171579. #endif
  171580. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  171581. * For 8-bit samples with the recommended scaling, all the variable
  171582. * and constant values involved are no more than 16 bits wide, so a
  171583. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  171584. * For 12-bit samples, a full 32-bit multiplication will be needed.
  171585. */
  171586. #if BITS_IN_JSAMPLE == 8
  171587. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  171588. #else
  171589. #define MULTIPLY(var,const) ((var) * (const))
  171590. #endif
  171591. /*
  171592. * Perform the forward DCT on one block of samples.
  171593. */
  171594. GLOBAL(void)
  171595. jpeg_fdct_islow (DCTELEM * data)
  171596. {
  171597. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  171598. INT32 tmp10, tmp11, tmp12, tmp13;
  171599. INT32 z1, z2, z3, z4, z5;
  171600. DCTELEM *dataptr;
  171601. int ctr;
  171602. SHIFT_TEMPS
  171603. /* Pass 1: process rows. */
  171604. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  171605. /* furthermore, we scale the results by 2**PASS1_BITS. */
  171606. dataptr = data;
  171607. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  171608. tmp0 = dataptr[0] + dataptr[7];
  171609. tmp7 = dataptr[0] - dataptr[7];
  171610. tmp1 = dataptr[1] + dataptr[6];
  171611. tmp6 = dataptr[1] - dataptr[6];
  171612. tmp2 = dataptr[2] + dataptr[5];
  171613. tmp5 = dataptr[2] - dataptr[5];
  171614. tmp3 = dataptr[3] + dataptr[4];
  171615. tmp4 = dataptr[3] - dataptr[4];
  171616. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  171617. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  171618. */
  171619. tmp10 = tmp0 + tmp3;
  171620. tmp13 = tmp0 - tmp3;
  171621. tmp11 = tmp1 + tmp2;
  171622. tmp12 = tmp1 - tmp2;
  171623. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  171624. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  171625. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  171626. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  171627. CONST_BITS-PASS1_BITS);
  171628. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  171629. CONST_BITS-PASS1_BITS);
  171630. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  171631. * cK represents cos(K*pi/16).
  171632. * i0..i3 in the paper are tmp4..tmp7 here.
  171633. */
  171634. z1 = tmp4 + tmp7;
  171635. z2 = tmp5 + tmp6;
  171636. z3 = tmp4 + tmp6;
  171637. z4 = tmp5 + tmp7;
  171638. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  171639. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  171640. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  171641. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  171642. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  171643. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  171644. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  171645. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  171646. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  171647. z3 += z5;
  171648. z4 += z5;
  171649. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  171650. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  171651. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  171652. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  171653. dataptr += DCTSIZE; /* advance pointer to next row */
  171654. }
  171655. /* Pass 2: process columns.
  171656. * We remove the PASS1_BITS scaling, but leave the results scaled up
  171657. * by an overall factor of 8.
  171658. */
  171659. dataptr = data;
  171660. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  171661. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  171662. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  171663. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  171664. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  171665. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  171666. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  171667. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  171668. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  171669. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  171670. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  171671. */
  171672. tmp10 = tmp0 + tmp3;
  171673. tmp13 = tmp0 - tmp3;
  171674. tmp11 = tmp1 + tmp2;
  171675. tmp12 = tmp1 - tmp2;
  171676. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  171677. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  171678. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  171679. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  171680. CONST_BITS+PASS1_BITS);
  171681. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  171682. CONST_BITS+PASS1_BITS);
  171683. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  171684. * cK represents cos(K*pi/16).
  171685. * i0..i3 in the paper are tmp4..tmp7 here.
  171686. */
  171687. z1 = tmp4 + tmp7;
  171688. z2 = tmp5 + tmp6;
  171689. z3 = tmp4 + tmp6;
  171690. z4 = tmp5 + tmp7;
  171691. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  171692. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  171693. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  171694. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  171695. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  171696. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  171697. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  171698. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  171699. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  171700. z3 += z5;
  171701. z4 += z5;
  171702. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  171703. CONST_BITS+PASS1_BITS);
  171704. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  171705. CONST_BITS+PASS1_BITS);
  171706. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  171707. CONST_BITS+PASS1_BITS);
  171708. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  171709. CONST_BITS+PASS1_BITS);
  171710. dataptr++; /* advance pointer to next column */
  171711. }
  171712. }
  171713. #endif /* DCT_ISLOW_SUPPORTED */
  171714. /*** End of inlined file: jfdctint.c ***/
  171715. #undef CONST_BITS
  171716. #undef MULTIPLY
  171717. #undef FIX_0_541196100
  171718. /*** Start of inlined file: jfdctfst.c ***/
  171719. #define JPEG_INTERNALS
  171720. #ifdef DCT_IFAST_SUPPORTED
  171721. /*
  171722. * This module is specialized to the case DCTSIZE = 8.
  171723. */
  171724. #if DCTSIZE != 8
  171725. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  171726. #endif
  171727. /* Scaling decisions are generally the same as in the LL&M algorithm;
  171728. * see jfdctint.c for more details. However, we choose to descale
  171729. * (right shift) multiplication products as soon as they are formed,
  171730. * rather than carrying additional fractional bits into subsequent additions.
  171731. * This compromises accuracy slightly, but it lets us save a few shifts.
  171732. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  171733. * everywhere except in the multiplications proper; this saves a good deal
  171734. * of work on 16-bit-int machines.
  171735. *
  171736. * Again to save a few shifts, the intermediate results between pass 1 and
  171737. * pass 2 are not upscaled, but are represented only to integral precision.
  171738. *
  171739. * A final compromise is to represent the multiplicative constants to only
  171740. * 8 fractional bits, rather than 13. This saves some shifting work on some
  171741. * machines, and may also reduce the cost of multiplication (since there
  171742. * are fewer one-bits in the constants).
  171743. */
  171744. #define CONST_BITS 8
  171745. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  171746. * causing a lot of useless floating-point operations at run time.
  171747. * To get around this we use the following pre-calculated constants.
  171748. * If you change CONST_BITS you may want to add appropriate values.
  171749. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  171750. */
  171751. #if CONST_BITS == 8
  171752. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  171753. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  171754. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  171755. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  171756. #else
  171757. #define FIX_0_382683433 FIX(0.382683433)
  171758. #define FIX_0_541196100 FIX(0.541196100)
  171759. #define FIX_0_707106781 FIX(0.707106781)
  171760. #define FIX_1_306562965 FIX(1.306562965)
  171761. #endif
  171762. /* We can gain a little more speed, with a further compromise in accuracy,
  171763. * by omitting the addition in a descaling shift. This yields an incorrectly
  171764. * rounded result half the time...
  171765. */
  171766. #ifndef USE_ACCURATE_ROUNDING
  171767. #undef DESCALE
  171768. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  171769. #endif
  171770. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  171771. * descale to yield a DCTELEM result.
  171772. */
  171773. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  171774. /*
  171775. * Perform the forward DCT on one block of samples.
  171776. */
  171777. GLOBAL(void)
  171778. jpeg_fdct_ifast (DCTELEM * data)
  171779. {
  171780. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  171781. DCTELEM tmp10, tmp11, tmp12, tmp13;
  171782. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  171783. DCTELEM *dataptr;
  171784. int ctr;
  171785. SHIFT_TEMPS
  171786. /* Pass 1: process rows. */
  171787. dataptr = data;
  171788. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  171789. tmp0 = dataptr[0] + dataptr[7];
  171790. tmp7 = dataptr[0] - dataptr[7];
  171791. tmp1 = dataptr[1] + dataptr[6];
  171792. tmp6 = dataptr[1] - dataptr[6];
  171793. tmp2 = dataptr[2] + dataptr[5];
  171794. tmp5 = dataptr[2] - dataptr[5];
  171795. tmp3 = dataptr[3] + dataptr[4];
  171796. tmp4 = dataptr[3] - dataptr[4];
  171797. /* Even part */
  171798. tmp10 = tmp0 + tmp3; /* phase 2 */
  171799. tmp13 = tmp0 - tmp3;
  171800. tmp11 = tmp1 + tmp2;
  171801. tmp12 = tmp1 - tmp2;
  171802. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  171803. dataptr[4] = tmp10 - tmp11;
  171804. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  171805. dataptr[2] = tmp13 + z1; /* phase 5 */
  171806. dataptr[6] = tmp13 - z1;
  171807. /* Odd part */
  171808. tmp10 = tmp4 + tmp5; /* phase 2 */
  171809. tmp11 = tmp5 + tmp6;
  171810. tmp12 = tmp6 + tmp7;
  171811. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  171812. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  171813. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  171814. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  171815. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  171816. z11 = tmp7 + z3; /* phase 5 */
  171817. z13 = tmp7 - z3;
  171818. dataptr[5] = z13 + z2; /* phase 6 */
  171819. dataptr[3] = z13 - z2;
  171820. dataptr[1] = z11 + z4;
  171821. dataptr[7] = z11 - z4;
  171822. dataptr += DCTSIZE; /* advance pointer to next row */
  171823. }
  171824. /* Pass 2: process columns. */
  171825. dataptr = data;
  171826. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  171827. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  171828. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  171829. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  171830. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  171831. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  171832. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  171833. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  171834. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  171835. /* Even part */
  171836. tmp10 = tmp0 + tmp3; /* phase 2 */
  171837. tmp13 = tmp0 - tmp3;
  171838. tmp11 = tmp1 + tmp2;
  171839. tmp12 = tmp1 - tmp2;
  171840. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  171841. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  171842. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  171843. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  171844. dataptr[DCTSIZE*6] = tmp13 - z1;
  171845. /* Odd part */
  171846. tmp10 = tmp4 + tmp5; /* phase 2 */
  171847. tmp11 = tmp5 + tmp6;
  171848. tmp12 = tmp6 + tmp7;
  171849. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  171850. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  171851. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  171852. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  171853. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  171854. z11 = tmp7 + z3; /* phase 5 */
  171855. z13 = tmp7 - z3;
  171856. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  171857. dataptr[DCTSIZE*3] = z13 - z2;
  171858. dataptr[DCTSIZE*1] = z11 + z4;
  171859. dataptr[DCTSIZE*7] = z11 - z4;
  171860. dataptr++; /* advance pointer to next column */
  171861. }
  171862. }
  171863. #endif /* DCT_IFAST_SUPPORTED */
  171864. /*** End of inlined file: jfdctfst.c ***/
  171865. #undef FIX_0_541196100
  171866. /*** Start of inlined file: jidctflt.c ***/
  171867. #define JPEG_INTERNALS
  171868. #ifdef DCT_FLOAT_SUPPORTED
  171869. /*
  171870. * This module is specialized to the case DCTSIZE = 8.
  171871. */
  171872. #if DCTSIZE != 8
  171873. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  171874. #endif
  171875. /* Dequantize a coefficient by multiplying it by the multiplier-table
  171876. * entry; produce a float result.
  171877. */
  171878. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  171879. /*
  171880. * Perform dequantization and inverse DCT on one block of coefficients.
  171881. */
  171882. GLOBAL(void)
  171883. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  171884. JCOEFPTR coef_block,
  171885. JSAMPARRAY output_buf, JDIMENSION output_col)
  171886. {
  171887. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  171888. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  171889. FAST_FLOAT z5, z10, z11, z12, z13;
  171890. JCOEFPTR inptr;
  171891. FLOAT_MULT_TYPE * quantptr;
  171892. FAST_FLOAT * wsptr;
  171893. JSAMPROW outptr;
  171894. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  171895. int ctr;
  171896. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  171897. SHIFT_TEMPS
  171898. /* Pass 1: process columns from input, store into work array. */
  171899. inptr = coef_block;
  171900. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  171901. wsptr = workspace;
  171902. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  171903. /* Due to quantization, we will usually find that many of the input
  171904. * coefficients are zero, especially the AC terms. We can exploit this
  171905. * by short-circuiting the IDCT calculation for any column in which all
  171906. * the AC terms are zero. In that case each output is equal to the
  171907. * DC coefficient (with scale factor as needed).
  171908. * With typical images and quantization tables, half or more of the
  171909. * column DCT calculations can be simplified this way.
  171910. */
  171911. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  171912. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  171913. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  171914. inptr[DCTSIZE*7] == 0) {
  171915. /* AC terms all zero */
  171916. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  171917. wsptr[DCTSIZE*0] = dcval;
  171918. wsptr[DCTSIZE*1] = dcval;
  171919. wsptr[DCTSIZE*2] = dcval;
  171920. wsptr[DCTSIZE*3] = dcval;
  171921. wsptr[DCTSIZE*4] = dcval;
  171922. wsptr[DCTSIZE*5] = dcval;
  171923. wsptr[DCTSIZE*6] = dcval;
  171924. wsptr[DCTSIZE*7] = dcval;
  171925. inptr++; /* advance pointers to next column */
  171926. quantptr++;
  171927. wsptr++;
  171928. continue;
  171929. }
  171930. /* Even part */
  171931. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  171932. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  171933. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  171934. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  171935. tmp10 = tmp0 + tmp2; /* phase 3 */
  171936. tmp11 = tmp0 - tmp2;
  171937. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  171938. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  171939. tmp0 = tmp10 + tmp13; /* phase 2 */
  171940. tmp3 = tmp10 - tmp13;
  171941. tmp1 = tmp11 + tmp12;
  171942. tmp2 = tmp11 - tmp12;
  171943. /* Odd part */
  171944. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  171945. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  171946. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  171947. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  171948. z13 = tmp6 + tmp5; /* phase 6 */
  171949. z10 = tmp6 - tmp5;
  171950. z11 = tmp4 + tmp7;
  171951. z12 = tmp4 - tmp7;
  171952. tmp7 = z11 + z13; /* phase 5 */
  171953. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  171954. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  171955. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  171956. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  171957. tmp6 = tmp12 - tmp7; /* phase 2 */
  171958. tmp5 = tmp11 - tmp6;
  171959. tmp4 = tmp10 + tmp5;
  171960. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  171961. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  171962. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  171963. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  171964. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  171965. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  171966. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  171967. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  171968. inptr++; /* advance pointers to next column */
  171969. quantptr++;
  171970. wsptr++;
  171971. }
  171972. /* Pass 2: process rows from work array, store into output array. */
  171973. /* Note that we must descale the results by a factor of 8 == 2**3. */
  171974. wsptr = workspace;
  171975. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  171976. outptr = output_buf[ctr] + output_col;
  171977. /* Rows of zeroes can be exploited in the same way as we did with columns.
  171978. * However, the column calculation has created many nonzero AC terms, so
  171979. * the simplification applies less often (typically 5% to 10% of the time).
  171980. * And testing floats for zero is relatively expensive, so we don't bother.
  171981. */
  171982. /* Even part */
  171983. tmp10 = wsptr[0] + wsptr[4];
  171984. tmp11 = wsptr[0] - wsptr[4];
  171985. tmp13 = wsptr[2] + wsptr[6];
  171986. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  171987. tmp0 = tmp10 + tmp13;
  171988. tmp3 = tmp10 - tmp13;
  171989. tmp1 = tmp11 + tmp12;
  171990. tmp2 = tmp11 - tmp12;
  171991. /* Odd part */
  171992. z13 = wsptr[5] + wsptr[3];
  171993. z10 = wsptr[5] - wsptr[3];
  171994. z11 = wsptr[1] + wsptr[7];
  171995. z12 = wsptr[1] - wsptr[7];
  171996. tmp7 = z11 + z13;
  171997. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  171998. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  171999. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  172000. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  172001. tmp6 = tmp12 - tmp7;
  172002. tmp5 = tmp11 - tmp6;
  172003. tmp4 = tmp10 + tmp5;
  172004. /* Final output stage: scale down by a factor of 8 and range-limit */
  172005. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  172006. & RANGE_MASK];
  172007. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  172008. & RANGE_MASK];
  172009. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  172010. & RANGE_MASK];
  172011. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  172012. & RANGE_MASK];
  172013. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  172014. & RANGE_MASK];
  172015. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  172016. & RANGE_MASK];
  172017. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  172018. & RANGE_MASK];
  172019. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  172020. & RANGE_MASK];
  172021. wsptr += DCTSIZE; /* advance pointer to next row */
  172022. }
  172023. }
  172024. #endif /* DCT_FLOAT_SUPPORTED */
  172025. /*** End of inlined file: jidctflt.c ***/
  172026. #undef CONST_BITS
  172027. #undef FIX_1_847759065
  172028. #undef MULTIPLY
  172029. #undef DEQUANTIZE
  172030. #undef DESCALE
  172031. /*** Start of inlined file: jidctfst.c ***/
  172032. #define JPEG_INTERNALS
  172033. #ifdef DCT_IFAST_SUPPORTED
  172034. /*
  172035. * This module is specialized to the case DCTSIZE = 8.
  172036. */
  172037. #if DCTSIZE != 8
  172038. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  172039. #endif
  172040. /* Scaling decisions are generally the same as in the LL&M algorithm;
  172041. * see jidctint.c for more details. However, we choose to descale
  172042. * (right shift) multiplication products as soon as they are formed,
  172043. * rather than carrying additional fractional bits into subsequent additions.
  172044. * This compromises accuracy slightly, but it lets us save a few shifts.
  172045. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  172046. * everywhere except in the multiplications proper; this saves a good deal
  172047. * of work on 16-bit-int machines.
  172048. *
  172049. * The dequantized coefficients are not integers because the AA&N scaling
  172050. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  172051. * so that the first and second IDCT rounds have the same input scaling.
  172052. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  172053. * avoid a descaling shift; this compromises accuracy rather drastically
  172054. * for small quantization table entries, but it saves a lot of shifts.
  172055. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  172056. * so we use a much larger scaling factor to preserve accuracy.
  172057. *
  172058. * A final compromise is to represent the multiplicative constants to only
  172059. * 8 fractional bits, rather than 13. This saves some shifting work on some
  172060. * machines, and may also reduce the cost of multiplication (since there
  172061. * are fewer one-bits in the constants).
  172062. */
  172063. #if BITS_IN_JSAMPLE == 8
  172064. #define CONST_BITS 8
  172065. #define PASS1_BITS 2
  172066. #else
  172067. #define CONST_BITS 8
  172068. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  172069. #endif
  172070. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  172071. * causing a lot of useless floating-point operations at run time.
  172072. * To get around this we use the following pre-calculated constants.
  172073. * If you change CONST_BITS you may want to add appropriate values.
  172074. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  172075. */
  172076. #if CONST_BITS == 8
  172077. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  172078. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  172079. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  172080. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  172081. #else
  172082. #define FIX_1_082392200 FIX(1.082392200)
  172083. #define FIX_1_414213562 FIX(1.414213562)
  172084. #define FIX_1_847759065 FIX(1.847759065)
  172085. #define FIX_2_613125930 FIX(2.613125930)
  172086. #endif
  172087. /* We can gain a little more speed, with a further compromise in accuracy,
  172088. * by omitting the addition in a descaling shift. This yields an incorrectly
  172089. * rounded result half the time...
  172090. */
  172091. #ifndef USE_ACCURATE_ROUNDING
  172092. #undef DESCALE
  172093. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  172094. #endif
  172095. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  172096. * descale to yield a DCTELEM result.
  172097. */
  172098. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  172099. /* Dequantize a coefficient by multiplying it by the multiplier-table
  172100. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  172101. * multiplication will do. For 12-bit data, the multiplier table is
  172102. * declared INT32, so a 32-bit multiply will be used.
  172103. */
  172104. #if BITS_IN_JSAMPLE == 8
  172105. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  172106. #else
  172107. #define DEQUANTIZE(coef,quantval) \
  172108. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  172109. #endif
  172110. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  172111. * We assume that int right shift is unsigned if INT32 right shift is.
  172112. */
  172113. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  172114. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  172115. #if BITS_IN_JSAMPLE == 8
  172116. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  172117. #else
  172118. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  172119. #endif
  172120. #define IRIGHT_SHIFT(x,shft) \
  172121. ((ishift_temp = (x)) < 0 ? \
  172122. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  172123. (ishift_temp >> (shft)))
  172124. #else
  172125. #define ISHIFT_TEMPS
  172126. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  172127. #endif
  172128. #ifdef USE_ACCURATE_ROUNDING
  172129. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  172130. #else
  172131. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  172132. #endif
  172133. /*
  172134. * Perform dequantization and inverse DCT on one block of coefficients.
  172135. */
  172136. GLOBAL(void)
  172137. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  172138. JCOEFPTR coef_block,
  172139. JSAMPARRAY output_buf, JDIMENSION output_col)
  172140. {
  172141. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  172142. DCTELEM tmp10, tmp11, tmp12, tmp13;
  172143. DCTELEM z5, z10, z11, z12, z13;
  172144. JCOEFPTR inptr;
  172145. IFAST_MULT_TYPE * quantptr;
  172146. int * wsptr;
  172147. JSAMPROW outptr;
  172148. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  172149. int ctr;
  172150. int workspace[DCTSIZE2]; /* buffers data between passes */
  172151. SHIFT_TEMPS /* for DESCALE */
  172152. ISHIFT_TEMPS /* for IDESCALE */
  172153. /* Pass 1: process columns from input, store into work array. */
  172154. inptr = coef_block;
  172155. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  172156. wsptr = workspace;
  172157. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  172158. /* Due to quantization, we will usually find that many of the input
  172159. * coefficients are zero, especially the AC terms. We can exploit this
  172160. * by short-circuiting the IDCT calculation for any column in which all
  172161. * the AC terms are zero. In that case each output is equal to the
  172162. * DC coefficient (with scale factor as needed).
  172163. * With typical images and quantization tables, half or more of the
  172164. * column DCT calculations can be simplified this way.
  172165. */
  172166. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  172167. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  172168. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  172169. inptr[DCTSIZE*7] == 0) {
  172170. /* AC terms all zero */
  172171. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  172172. wsptr[DCTSIZE*0] = dcval;
  172173. wsptr[DCTSIZE*1] = dcval;
  172174. wsptr[DCTSIZE*2] = dcval;
  172175. wsptr[DCTSIZE*3] = dcval;
  172176. wsptr[DCTSIZE*4] = dcval;
  172177. wsptr[DCTSIZE*5] = dcval;
  172178. wsptr[DCTSIZE*6] = dcval;
  172179. wsptr[DCTSIZE*7] = dcval;
  172180. inptr++; /* advance pointers to next column */
  172181. quantptr++;
  172182. wsptr++;
  172183. continue;
  172184. }
  172185. /* Even part */
  172186. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  172187. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  172188. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  172189. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  172190. tmp10 = tmp0 + tmp2; /* phase 3 */
  172191. tmp11 = tmp0 - tmp2;
  172192. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  172193. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  172194. tmp0 = tmp10 + tmp13; /* phase 2 */
  172195. tmp3 = tmp10 - tmp13;
  172196. tmp1 = tmp11 + tmp12;
  172197. tmp2 = tmp11 - tmp12;
  172198. /* Odd part */
  172199. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  172200. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  172201. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  172202. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  172203. z13 = tmp6 + tmp5; /* phase 6 */
  172204. z10 = tmp6 - tmp5;
  172205. z11 = tmp4 + tmp7;
  172206. z12 = tmp4 - tmp7;
  172207. tmp7 = z11 + z13; /* phase 5 */
  172208. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  172209. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  172210. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  172211. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  172212. tmp6 = tmp12 - tmp7; /* phase 2 */
  172213. tmp5 = tmp11 - tmp6;
  172214. tmp4 = tmp10 + tmp5;
  172215. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  172216. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  172217. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  172218. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  172219. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  172220. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  172221. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  172222. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  172223. inptr++; /* advance pointers to next column */
  172224. quantptr++;
  172225. wsptr++;
  172226. }
  172227. /* Pass 2: process rows from work array, store into output array. */
  172228. /* Note that we must descale the results by a factor of 8 == 2**3, */
  172229. /* and also undo the PASS1_BITS scaling. */
  172230. wsptr = workspace;
  172231. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  172232. outptr = output_buf[ctr] + output_col;
  172233. /* Rows of zeroes can be exploited in the same way as we did with columns.
  172234. * However, the column calculation has created many nonzero AC terms, so
  172235. * the simplification applies less often (typically 5% to 10% of the time).
  172236. * On machines with very fast multiplication, it's possible that the
  172237. * test takes more time than it's worth. In that case this section
  172238. * may be commented out.
  172239. */
  172240. #ifndef NO_ZERO_ROW_TEST
  172241. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  172242. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  172243. /* AC terms all zero */
  172244. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  172245. & RANGE_MASK];
  172246. outptr[0] = dcval;
  172247. outptr[1] = dcval;
  172248. outptr[2] = dcval;
  172249. outptr[3] = dcval;
  172250. outptr[4] = dcval;
  172251. outptr[5] = dcval;
  172252. outptr[6] = dcval;
  172253. outptr[7] = dcval;
  172254. wsptr += DCTSIZE; /* advance pointer to next row */
  172255. continue;
  172256. }
  172257. #endif
  172258. /* Even part */
  172259. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  172260. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  172261. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  172262. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  172263. - tmp13;
  172264. tmp0 = tmp10 + tmp13;
  172265. tmp3 = tmp10 - tmp13;
  172266. tmp1 = tmp11 + tmp12;
  172267. tmp2 = tmp11 - tmp12;
  172268. /* Odd part */
  172269. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  172270. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  172271. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  172272. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  172273. tmp7 = z11 + z13; /* phase 5 */
  172274. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  172275. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  172276. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  172277. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  172278. tmp6 = tmp12 - tmp7; /* phase 2 */
  172279. tmp5 = tmp11 - tmp6;
  172280. tmp4 = tmp10 + tmp5;
  172281. /* Final output stage: scale down by a factor of 8 and range-limit */
  172282. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  172283. & RANGE_MASK];
  172284. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  172285. & RANGE_MASK];
  172286. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  172287. & RANGE_MASK];
  172288. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  172289. & RANGE_MASK];
  172290. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  172291. & RANGE_MASK];
  172292. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  172293. & RANGE_MASK];
  172294. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  172295. & RANGE_MASK];
  172296. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  172297. & RANGE_MASK];
  172298. wsptr += DCTSIZE; /* advance pointer to next row */
  172299. }
  172300. }
  172301. #endif /* DCT_IFAST_SUPPORTED */
  172302. /*** End of inlined file: jidctfst.c ***/
  172303. #undef CONST_BITS
  172304. #undef FIX_1_847759065
  172305. #undef MULTIPLY
  172306. #undef DEQUANTIZE
  172307. /*** Start of inlined file: jidctint.c ***/
  172308. #define JPEG_INTERNALS
  172309. #ifdef DCT_ISLOW_SUPPORTED
  172310. /*
  172311. * This module is specialized to the case DCTSIZE = 8.
  172312. */
  172313. #if DCTSIZE != 8
  172314. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  172315. #endif
  172316. /*
  172317. * The poop on this scaling stuff is as follows:
  172318. *
  172319. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  172320. * larger than the true IDCT outputs. The final outputs are therefore
  172321. * a factor of N larger than desired; since N=8 this can be cured by
  172322. * a simple right shift at the end of the algorithm. The advantage of
  172323. * this arrangement is that we save two multiplications per 1-D IDCT,
  172324. * because the y0 and y4 inputs need not be divided by sqrt(N).
  172325. *
  172326. * We have to do addition and subtraction of the integer inputs, which
  172327. * is no problem, and multiplication by fractional constants, which is
  172328. * a problem to do in integer arithmetic. We multiply all the constants
  172329. * by CONST_SCALE and convert them to integer constants (thus retaining
  172330. * CONST_BITS bits of precision in the constants). After doing a
  172331. * multiplication we have to divide the product by CONST_SCALE, with proper
  172332. * rounding, to produce the correct output. This division can be done
  172333. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  172334. * as long as possible so that partial sums can be added together with
  172335. * full fractional precision.
  172336. *
  172337. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  172338. * they are represented to better-than-integral precision. These outputs
  172339. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  172340. * with the recommended scaling. (To scale up 12-bit sample data further, an
  172341. * intermediate INT32 array would be needed.)
  172342. *
  172343. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  172344. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  172345. * shows that the values given below are the most effective.
  172346. */
  172347. #if BITS_IN_JSAMPLE == 8
  172348. #define CONST_BITS 13
  172349. #define PASS1_BITS 2
  172350. #else
  172351. #define CONST_BITS 13
  172352. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  172353. #endif
  172354. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  172355. * causing a lot of useless floating-point operations at run time.
  172356. * To get around this we use the following pre-calculated constants.
  172357. * If you change CONST_BITS you may want to add appropriate values.
  172358. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  172359. */
  172360. #if CONST_BITS == 13
  172361. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  172362. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  172363. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  172364. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  172365. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  172366. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  172367. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  172368. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  172369. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  172370. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  172371. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  172372. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  172373. #else
  172374. #define FIX_0_298631336 FIX(0.298631336)
  172375. #define FIX_0_390180644 FIX(0.390180644)
  172376. #define FIX_0_541196100 FIX(0.541196100)
  172377. #define FIX_0_765366865 FIX(0.765366865)
  172378. #define FIX_0_899976223 FIX(0.899976223)
  172379. #define FIX_1_175875602 FIX(1.175875602)
  172380. #define FIX_1_501321110 FIX(1.501321110)
  172381. #define FIX_1_847759065 FIX(1.847759065)
  172382. #define FIX_1_961570560 FIX(1.961570560)
  172383. #define FIX_2_053119869 FIX(2.053119869)
  172384. #define FIX_2_562915447 FIX(2.562915447)
  172385. #define FIX_3_072711026 FIX(3.072711026)
  172386. #endif
  172387. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  172388. * For 8-bit samples with the recommended scaling, all the variable
  172389. * and constant values involved are no more than 16 bits wide, so a
  172390. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  172391. * For 12-bit samples, a full 32-bit multiplication will be needed.
  172392. */
  172393. #if BITS_IN_JSAMPLE == 8
  172394. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  172395. #else
  172396. #define MULTIPLY(var,const) ((var) * (const))
  172397. #endif
  172398. /* Dequantize a coefficient by multiplying it by the multiplier-table
  172399. * entry; produce an int result. In this module, both inputs and result
  172400. * are 16 bits or less, so either int or short multiply will work.
  172401. */
  172402. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  172403. /*
  172404. * Perform dequantization and inverse DCT on one block of coefficients.
  172405. */
  172406. GLOBAL(void)
  172407. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  172408. JCOEFPTR coef_block,
  172409. JSAMPARRAY output_buf, JDIMENSION output_col)
  172410. {
  172411. INT32 tmp0, tmp1, tmp2, tmp3;
  172412. INT32 tmp10, tmp11, tmp12, tmp13;
  172413. INT32 z1, z2, z3, z4, z5;
  172414. JCOEFPTR inptr;
  172415. ISLOW_MULT_TYPE * quantptr;
  172416. int * wsptr;
  172417. JSAMPROW outptr;
  172418. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  172419. int ctr;
  172420. int workspace[DCTSIZE2]; /* buffers data between passes */
  172421. SHIFT_TEMPS
  172422. /* Pass 1: process columns from input, store into work array. */
  172423. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  172424. /* furthermore, we scale the results by 2**PASS1_BITS. */
  172425. inptr = coef_block;
  172426. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  172427. wsptr = workspace;
  172428. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  172429. /* Due to quantization, we will usually find that many of the input
  172430. * coefficients are zero, especially the AC terms. We can exploit this
  172431. * by short-circuiting the IDCT calculation for any column in which all
  172432. * the AC terms are zero. In that case each output is equal to the
  172433. * DC coefficient (with scale factor as needed).
  172434. * With typical images and quantization tables, half or more of the
  172435. * column DCT calculations can be simplified this way.
  172436. */
  172437. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  172438. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  172439. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  172440. inptr[DCTSIZE*7] == 0) {
  172441. /* AC terms all zero */
  172442. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  172443. wsptr[DCTSIZE*0] = dcval;
  172444. wsptr[DCTSIZE*1] = dcval;
  172445. wsptr[DCTSIZE*2] = dcval;
  172446. wsptr[DCTSIZE*3] = dcval;
  172447. wsptr[DCTSIZE*4] = dcval;
  172448. wsptr[DCTSIZE*5] = dcval;
  172449. wsptr[DCTSIZE*6] = dcval;
  172450. wsptr[DCTSIZE*7] = dcval;
  172451. inptr++; /* advance pointers to next column */
  172452. quantptr++;
  172453. wsptr++;
  172454. continue;
  172455. }
  172456. /* Even part: reverse the even part of the forward DCT. */
  172457. /* The rotator is sqrt(2)*c(-6). */
  172458. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  172459. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  172460. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  172461. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  172462. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  172463. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  172464. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  172465. tmp0 = (z2 + z3) << CONST_BITS;
  172466. tmp1 = (z2 - z3) << CONST_BITS;
  172467. tmp10 = tmp0 + tmp3;
  172468. tmp13 = tmp0 - tmp3;
  172469. tmp11 = tmp1 + tmp2;
  172470. tmp12 = tmp1 - tmp2;
  172471. /* Odd part per figure 8; the matrix is unitary and hence its
  172472. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  172473. */
  172474. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  172475. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  172476. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  172477. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  172478. z1 = tmp0 + tmp3;
  172479. z2 = tmp1 + tmp2;
  172480. z3 = tmp0 + tmp2;
  172481. z4 = tmp1 + tmp3;
  172482. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  172483. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  172484. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  172485. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  172486. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  172487. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  172488. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  172489. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  172490. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  172491. z3 += z5;
  172492. z4 += z5;
  172493. tmp0 += z1 + z3;
  172494. tmp1 += z2 + z4;
  172495. tmp2 += z2 + z3;
  172496. tmp3 += z1 + z4;
  172497. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  172498. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  172499. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  172500. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  172501. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  172502. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  172503. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  172504. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  172505. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  172506. inptr++; /* advance pointers to next column */
  172507. quantptr++;
  172508. wsptr++;
  172509. }
  172510. /* Pass 2: process rows from work array, store into output array. */
  172511. /* Note that we must descale the results by a factor of 8 == 2**3, */
  172512. /* and also undo the PASS1_BITS scaling. */
  172513. wsptr = workspace;
  172514. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  172515. outptr = output_buf[ctr] + output_col;
  172516. /* Rows of zeroes can be exploited in the same way as we did with columns.
  172517. * However, the column calculation has created many nonzero AC terms, so
  172518. * the simplification applies less often (typically 5% to 10% of the time).
  172519. * On machines with very fast multiplication, it's possible that the
  172520. * test takes more time than it's worth. In that case this section
  172521. * may be commented out.
  172522. */
  172523. #ifndef NO_ZERO_ROW_TEST
  172524. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  172525. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  172526. /* AC terms all zero */
  172527. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  172528. & RANGE_MASK];
  172529. outptr[0] = dcval;
  172530. outptr[1] = dcval;
  172531. outptr[2] = dcval;
  172532. outptr[3] = dcval;
  172533. outptr[4] = dcval;
  172534. outptr[5] = dcval;
  172535. outptr[6] = dcval;
  172536. outptr[7] = dcval;
  172537. wsptr += DCTSIZE; /* advance pointer to next row */
  172538. continue;
  172539. }
  172540. #endif
  172541. /* Even part: reverse the even part of the forward DCT. */
  172542. /* The rotator is sqrt(2)*c(-6). */
  172543. z2 = (INT32) wsptr[2];
  172544. z3 = (INT32) wsptr[6];
  172545. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  172546. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  172547. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  172548. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  172549. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  172550. tmp10 = tmp0 + tmp3;
  172551. tmp13 = tmp0 - tmp3;
  172552. tmp11 = tmp1 + tmp2;
  172553. tmp12 = tmp1 - tmp2;
  172554. /* Odd part per figure 8; the matrix is unitary and hence its
  172555. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  172556. */
  172557. tmp0 = (INT32) wsptr[7];
  172558. tmp1 = (INT32) wsptr[5];
  172559. tmp2 = (INT32) wsptr[3];
  172560. tmp3 = (INT32) wsptr[1];
  172561. z1 = tmp0 + tmp3;
  172562. z2 = tmp1 + tmp2;
  172563. z3 = tmp0 + tmp2;
  172564. z4 = tmp1 + tmp3;
  172565. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  172566. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  172567. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  172568. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  172569. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  172570. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  172571. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  172572. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  172573. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  172574. z3 += z5;
  172575. z4 += z5;
  172576. tmp0 += z1 + z3;
  172577. tmp1 += z2 + z4;
  172578. tmp2 += z2 + z3;
  172579. tmp3 += z1 + z4;
  172580. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  172581. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  172582. CONST_BITS+PASS1_BITS+3)
  172583. & RANGE_MASK];
  172584. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  172585. CONST_BITS+PASS1_BITS+3)
  172586. & RANGE_MASK];
  172587. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  172588. CONST_BITS+PASS1_BITS+3)
  172589. & RANGE_MASK];
  172590. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  172591. CONST_BITS+PASS1_BITS+3)
  172592. & RANGE_MASK];
  172593. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  172594. CONST_BITS+PASS1_BITS+3)
  172595. & RANGE_MASK];
  172596. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  172597. CONST_BITS+PASS1_BITS+3)
  172598. & RANGE_MASK];
  172599. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  172600. CONST_BITS+PASS1_BITS+3)
  172601. & RANGE_MASK];
  172602. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  172603. CONST_BITS+PASS1_BITS+3)
  172604. & RANGE_MASK];
  172605. wsptr += DCTSIZE; /* advance pointer to next row */
  172606. }
  172607. }
  172608. #endif /* DCT_ISLOW_SUPPORTED */
  172609. /*** End of inlined file: jidctint.c ***/
  172610. /*** Start of inlined file: jidctred.c ***/
  172611. #define JPEG_INTERNALS
  172612. #ifdef IDCT_SCALING_SUPPORTED
  172613. /*
  172614. * This module is specialized to the case DCTSIZE = 8.
  172615. */
  172616. #if DCTSIZE != 8
  172617. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  172618. #endif
  172619. /* Scaling is the same as in jidctint.c. */
  172620. #if BITS_IN_JSAMPLE == 8
  172621. #define CONST_BITS 13
  172622. #define PASS1_BITS 2
  172623. #else
  172624. #define CONST_BITS 13
  172625. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  172626. #endif
  172627. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  172628. * causing a lot of useless floating-point operations at run time.
  172629. * To get around this we use the following pre-calculated constants.
  172630. * If you change CONST_BITS you may want to add appropriate values.
  172631. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  172632. */
  172633. #if CONST_BITS == 13
  172634. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  172635. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  172636. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  172637. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  172638. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  172639. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  172640. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  172641. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  172642. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  172643. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  172644. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  172645. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  172646. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  172647. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  172648. #else
  172649. #define FIX_0_211164243 FIX(0.211164243)
  172650. #define FIX_0_509795579 FIX(0.509795579)
  172651. #define FIX_0_601344887 FIX(0.601344887)
  172652. #define FIX_0_720959822 FIX(0.720959822)
  172653. #define FIX_0_765366865 FIX(0.765366865)
  172654. #define FIX_0_850430095 FIX(0.850430095)
  172655. #define FIX_0_899976223 FIX(0.899976223)
  172656. #define FIX_1_061594337 FIX(1.061594337)
  172657. #define FIX_1_272758580 FIX(1.272758580)
  172658. #define FIX_1_451774981 FIX(1.451774981)
  172659. #define FIX_1_847759065 FIX(1.847759065)
  172660. #define FIX_2_172734803 FIX(2.172734803)
  172661. #define FIX_2_562915447 FIX(2.562915447)
  172662. #define FIX_3_624509785 FIX(3.624509785)
  172663. #endif
  172664. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  172665. * For 8-bit samples with the recommended scaling, all the variable
  172666. * and constant values involved are no more than 16 bits wide, so a
  172667. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  172668. * For 12-bit samples, a full 32-bit multiplication will be needed.
  172669. */
  172670. #if BITS_IN_JSAMPLE == 8
  172671. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  172672. #else
  172673. #define MULTIPLY(var,const) ((var) * (const))
  172674. #endif
  172675. /* Dequantize a coefficient by multiplying it by the multiplier-table
  172676. * entry; produce an int result. In this module, both inputs and result
  172677. * are 16 bits or less, so either int or short multiply will work.
  172678. */
  172679. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  172680. /*
  172681. * Perform dequantization and inverse DCT on one block of coefficients,
  172682. * producing a reduced-size 4x4 output block.
  172683. */
  172684. GLOBAL(void)
  172685. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  172686. JCOEFPTR coef_block,
  172687. JSAMPARRAY output_buf, JDIMENSION output_col)
  172688. {
  172689. INT32 tmp0, tmp2, tmp10, tmp12;
  172690. INT32 z1, z2, z3, z4;
  172691. JCOEFPTR inptr;
  172692. ISLOW_MULT_TYPE * quantptr;
  172693. int * wsptr;
  172694. JSAMPROW outptr;
  172695. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  172696. int ctr;
  172697. int workspace[DCTSIZE*4]; /* buffers data between passes */
  172698. SHIFT_TEMPS
  172699. /* Pass 1: process columns from input, store into work array. */
  172700. inptr = coef_block;
  172701. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  172702. wsptr = workspace;
  172703. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  172704. /* Don't bother to process column 4, because second pass won't use it */
  172705. if (ctr == DCTSIZE-4)
  172706. continue;
  172707. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  172708. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  172709. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  172710. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  172711. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  172712. wsptr[DCTSIZE*0] = dcval;
  172713. wsptr[DCTSIZE*1] = dcval;
  172714. wsptr[DCTSIZE*2] = dcval;
  172715. wsptr[DCTSIZE*3] = dcval;
  172716. continue;
  172717. }
  172718. /* Even part */
  172719. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  172720. tmp0 <<= (CONST_BITS+1);
  172721. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  172722. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  172723. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  172724. tmp10 = tmp0 + tmp2;
  172725. tmp12 = tmp0 - tmp2;
  172726. /* Odd part */
  172727. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  172728. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  172729. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  172730. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  172731. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  172732. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  172733. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  172734. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  172735. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  172736. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  172737. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  172738. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  172739. /* Final output stage */
  172740. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  172741. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  172742. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  172743. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  172744. }
  172745. /* Pass 2: process 4 rows from work array, store into output array. */
  172746. wsptr = workspace;
  172747. for (ctr = 0; ctr < 4; ctr++) {
  172748. outptr = output_buf[ctr] + output_col;
  172749. /* It's not clear whether a zero row test is worthwhile here ... */
  172750. #ifndef NO_ZERO_ROW_TEST
  172751. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  172752. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  172753. /* AC terms all zero */
  172754. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  172755. & RANGE_MASK];
  172756. outptr[0] = dcval;
  172757. outptr[1] = dcval;
  172758. outptr[2] = dcval;
  172759. outptr[3] = dcval;
  172760. wsptr += DCTSIZE; /* advance pointer to next row */
  172761. continue;
  172762. }
  172763. #endif
  172764. /* Even part */
  172765. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  172766. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  172767. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  172768. tmp10 = tmp0 + tmp2;
  172769. tmp12 = tmp0 - tmp2;
  172770. /* Odd part */
  172771. z1 = (INT32) wsptr[7];
  172772. z2 = (INT32) wsptr[5];
  172773. z3 = (INT32) wsptr[3];
  172774. z4 = (INT32) wsptr[1];
  172775. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  172776. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  172777. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  172778. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  172779. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  172780. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  172781. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  172782. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  172783. /* Final output stage */
  172784. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  172785. CONST_BITS+PASS1_BITS+3+1)
  172786. & RANGE_MASK];
  172787. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  172788. CONST_BITS+PASS1_BITS+3+1)
  172789. & RANGE_MASK];
  172790. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  172791. CONST_BITS+PASS1_BITS+3+1)
  172792. & RANGE_MASK];
  172793. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  172794. CONST_BITS+PASS1_BITS+3+1)
  172795. & RANGE_MASK];
  172796. wsptr += DCTSIZE; /* advance pointer to next row */
  172797. }
  172798. }
  172799. /*
  172800. * Perform dequantization and inverse DCT on one block of coefficients,
  172801. * producing a reduced-size 2x2 output block.
  172802. */
  172803. GLOBAL(void)
  172804. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  172805. JCOEFPTR coef_block,
  172806. JSAMPARRAY output_buf, JDIMENSION output_col)
  172807. {
  172808. INT32 tmp0, tmp10, z1;
  172809. JCOEFPTR inptr;
  172810. ISLOW_MULT_TYPE * quantptr;
  172811. int * wsptr;
  172812. JSAMPROW outptr;
  172813. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  172814. int ctr;
  172815. int workspace[DCTSIZE*2]; /* buffers data between passes */
  172816. SHIFT_TEMPS
  172817. /* Pass 1: process columns from input, store into work array. */
  172818. inptr = coef_block;
  172819. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  172820. wsptr = workspace;
  172821. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  172822. /* Don't bother to process columns 2,4,6 */
  172823. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  172824. continue;
  172825. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  172826. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  172827. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  172828. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  172829. wsptr[DCTSIZE*0] = dcval;
  172830. wsptr[DCTSIZE*1] = dcval;
  172831. continue;
  172832. }
  172833. /* Even part */
  172834. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  172835. tmp10 = z1 << (CONST_BITS+2);
  172836. /* Odd part */
  172837. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  172838. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  172839. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  172840. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  172841. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  172842. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  172843. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  172844. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  172845. /* Final output stage */
  172846. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  172847. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  172848. }
  172849. /* Pass 2: process 2 rows from work array, store into output array. */
  172850. wsptr = workspace;
  172851. for (ctr = 0; ctr < 2; ctr++) {
  172852. outptr = output_buf[ctr] + output_col;
  172853. /* It's not clear whether a zero row test is worthwhile here ... */
  172854. #ifndef NO_ZERO_ROW_TEST
  172855. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  172856. /* AC terms all zero */
  172857. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  172858. & RANGE_MASK];
  172859. outptr[0] = dcval;
  172860. outptr[1] = dcval;
  172861. wsptr += DCTSIZE; /* advance pointer to next row */
  172862. continue;
  172863. }
  172864. #endif
  172865. /* Even part */
  172866. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  172867. /* Odd part */
  172868. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  172869. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  172870. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  172871. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  172872. /* Final output stage */
  172873. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  172874. CONST_BITS+PASS1_BITS+3+2)
  172875. & RANGE_MASK];
  172876. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  172877. CONST_BITS+PASS1_BITS+3+2)
  172878. & RANGE_MASK];
  172879. wsptr += DCTSIZE; /* advance pointer to next row */
  172880. }
  172881. }
  172882. /*
  172883. * Perform dequantization and inverse DCT on one block of coefficients,
  172884. * producing a reduced-size 1x1 output block.
  172885. */
  172886. GLOBAL(void)
  172887. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  172888. JCOEFPTR coef_block,
  172889. JSAMPARRAY output_buf, JDIMENSION output_col)
  172890. {
  172891. int dcval;
  172892. ISLOW_MULT_TYPE * quantptr;
  172893. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  172894. SHIFT_TEMPS
  172895. /* We hardly need an inverse DCT routine for this: just take the
  172896. * average pixel value, which is one-eighth of the DC coefficient.
  172897. */
  172898. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  172899. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  172900. dcval = (int) DESCALE((INT32) dcval, 3);
  172901. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  172902. }
  172903. #endif /* IDCT_SCALING_SUPPORTED */
  172904. /*** End of inlined file: jidctred.c ***/
  172905. /*** Start of inlined file: jmemmgr.c ***/
  172906. #define JPEG_INTERNALS
  172907. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  172908. /*** Start of inlined file: jmemsys.h ***/
  172909. #ifndef __jmemsys_h__
  172910. #define __jmemsys_h__
  172911. /* Short forms of external names for systems with brain-damaged linkers. */
  172912. #ifdef NEED_SHORT_EXTERNAL_NAMES
  172913. #define jpeg_get_small jGetSmall
  172914. #define jpeg_free_small jFreeSmall
  172915. #define jpeg_get_large jGetLarge
  172916. #define jpeg_free_large jFreeLarge
  172917. #define jpeg_mem_available jMemAvail
  172918. #define jpeg_open_backing_store jOpenBackStore
  172919. #define jpeg_mem_init jMemInit
  172920. #define jpeg_mem_term jMemTerm
  172921. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  172922. /*
  172923. * These two functions are used to allocate and release small chunks of
  172924. * memory. (Typically the total amount requested through jpeg_get_small is
  172925. * no more than 20K or so; this will be requested in chunks of a few K each.)
  172926. * Behavior should be the same as for the standard library functions malloc
  172927. * and free; in particular, jpeg_get_small must return NULL on failure.
  172928. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  172929. * size of the object being freed, just in case it's needed.
  172930. * On an 80x86 machine using small-data memory model, these manage near heap.
  172931. */
  172932. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  172933. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  172934. size_t sizeofobject));
  172935. /*
  172936. * These two functions are used to allocate and release large chunks of
  172937. * memory (up to the total free space designated by jpeg_mem_available).
  172938. * The interface is the same as above, except that on an 80x86 machine,
  172939. * far pointers are used. On most other machines these are identical to
  172940. * the jpeg_get/free_small routines; but we keep them separate anyway,
  172941. * in case a different allocation strategy is desirable for large chunks.
  172942. */
  172943. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  172944. size_t sizeofobject));
  172945. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  172946. size_t sizeofobject));
  172947. /*
  172948. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  172949. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  172950. * matter, but that case should never come into play). This macro is needed
  172951. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  172952. * On those machines, we expect that jconfig.h will provide a proper value.
  172953. * On machines with 32-bit flat address spaces, any large constant may be used.
  172954. *
  172955. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  172956. * size_t and will be a multiple of sizeof(align_type).
  172957. */
  172958. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  172959. #define MAX_ALLOC_CHUNK 1000000000L
  172960. #endif
  172961. /*
  172962. * This routine computes the total space still available for allocation by
  172963. * jpeg_get_large. If more space than this is needed, backing store will be
  172964. * used. NOTE: any memory already allocated must not be counted.
  172965. *
  172966. * There is a minimum space requirement, corresponding to the minimum
  172967. * feasible buffer sizes; jmemmgr.c will request that much space even if
  172968. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  172969. * all working storage in memory, is also passed in case it is useful.
  172970. * Finally, the total space already allocated is passed. If no better
  172971. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  172972. * is often a suitable calculation.
  172973. *
  172974. * It is OK for jpeg_mem_available to underestimate the space available
  172975. * (that'll just lead to more backing-store access than is really necessary).
  172976. * However, an overestimate will lead to failure. Hence it's wise to subtract
  172977. * a slop factor from the true available space. 5% should be enough.
  172978. *
  172979. * On machines with lots of virtual memory, any large constant may be returned.
  172980. * Conversely, zero may be returned to always use the minimum amount of memory.
  172981. */
  172982. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  172983. long min_bytes_needed,
  172984. long max_bytes_needed,
  172985. long already_allocated));
  172986. /*
  172987. * This structure holds whatever state is needed to access a single
  172988. * backing-store object. The read/write/close method pointers are called
  172989. * by jmemmgr.c to manipulate the backing-store object; all other fields
  172990. * are private to the system-dependent backing store routines.
  172991. */
  172992. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  172993. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  172994. typedef unsigned short XMSH; /* type of extended-memory handles */
  172995. typedef unsigned short EMSH; /* type of expanded-memory handles */
  172996. typedef union {
  172997. short file_handle; /* DOS file handle if it's a temp file */
  172998. XMSH xms_handle; /* handle if it's a chunk of XMS */
  172999. EMSH ems_handle; /* handle if it's a chunk of EMS */
  173000. } handle_union;
  173001. #endif /* USE_MSDOS_MEMMGR */
  173002. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  173003. #include <Files.h>
  173004. #endif /* USE_MAC_MEMMGR */
  173005. //typedef struct backing_store_struct * backing_store_ptr;
  173006. typedef struct backing_store_struct {
  173007. /* Methods for reading/writing/closing this backing-store object */
  173008. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  173009. struct backing_store_struct *info,
  173010. void FAR * buffer_address,
  173011. long file_offset, long byte_count));
  173012. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  173013. struct backing_store_struct *info,
  173014. void FAR * buffer_address,
  173015. long file_offset, long byte_count));
  173016. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  173017. struct backing_store_struct *info));
  173018. /* Private fields for system-dependent backing-store management */
  173019. #ifdef USE_MSDOS_MEMMGR
  173020. /* For the MS-DOS manager (jmemdos.c), we need: */
  173021. handle_union handle; /* reference to backing-store storage object */
  173022. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  173023. #else
  173024. #ifdef USE_MAC_MEMMGR
  173025. /* For the Mac manager (jmemmac.c), we need: */
  173026. short temp_file; /* file reference number to temp file */
  173027. FSSpec tempSpec; /* the FSSpec for the temp file */
  173028. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  173029. #else
  173030. /* For a typical implementation with temp files, we need: */
  173031. FILE * temp_file; /* stdio reference to temp file */
  173032. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  173033. #endif
  173034. #endif
  173035. } backing_store_info;
  173036. /*
  173037. * Initial opening of a backing-store object. This must fill in the
  173038. * read/write/close pointers in the object. The read/write routines
  173039. * may take an error exit if the specified maximum file size is exceeded.
  173040. * (If jpeg_mem_available always returns a large value, this routine can
  173041. * just take an error exit.)
  173042. */
  173043. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  173044. struct backing_store_struct *info,
  173045. long total_bytes_needed));
  173046. /*
  173047. * These routines take care of any system-dependent initialization and
  173048. * cleanup required. jpeg_mem_init will be called before anything is
  173049. * allocated (and, therefore, nothing in cinfo is of use except the error
  173050. * manager pointer). It should return a suitable default value for
  173051. * max_memory_to_use; this may subsequently be overridden by the surrounding
  173052. * application. (Note that max_memory_to_use is only important if
  173053. * jpeg_mem_available chooses to consult it ... no one else will.)
  173054. * jpeg_mem_term may assume that all requested memory has been freed and that
  173055. * all opened backing-store objects have been closed.
  173056. */
  173057. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  173058. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  173059. #endif
  173060. /*** End of inlined file: jmemsys.h ***/
  173061. /* import the system-dependent declarations */
  173062. #ifndef NO_GETENV
  173063. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  173064. extern char * getenv JPP((const char * name));
  173065. #endif
  173066. #endif
  173067. /*
  173068. * Some important notes:
  173069. * The allocation routines provided here must never return NULL.
  173070. * They should exit to error_exit if unsuccessful.
  173071. *
  173072. * It's not a good idea to try to merge the sarray and barray routines,
  173073. * even though they are textually almost the same, because samples are
  173074. * usually stored as bytes while coefficients are shorts or ints. Thus,
  173075. * in machines where byte pointers have a different representation from
  173076. * word pointers, the resulting machine code could not be the same.
  173077. */
  173078. /*
  173079. * Many machines require storage alignment: longs must start on 4-byte
  173080. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  173081. * always returns pointers that are multiples of the worst-case alignment
  173082. * requirement, and we had better do so too.
  173083. * There isn't any really portable way to determine the worst-case alignment
  173084. * requirement. This module assumes that the alignment requirement is
  173085. * multiples of sizeof(ALIGN_TYPE).
  173086. * By default, we define ALIGN_TYPE as double. This is necessary on some
  173087. * workstations (where doubles really do need 8-byte alignment) and will work
  173088. * fine on nearly everything. If your machine has lesser alignment needs,
  173089. * you can save a few bytes by making ALIGN_TYPE smaller.
  173090. * The only place I know of where this will NOT work is certain Macintosh
  173091. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  173092. * Doing 10-byte alignment is counterproductive because longwords won't be
  173093. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  173094. * such a compiler.
  173095. */
  173096. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  173097. #define ALIGN_TYPE double
  173098. #endif
  173099. /*
  173100. * We allocate objects from "pools", where each pool is gotten with a single
  173101. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  173102. * overhead within a pool, except for alignment padding. Each pool has a
  173103. * header with a link to the next pool of the same class.
  173104. * Small and large pool headers are identical except that the latter's
  173105. * link pointer must be FAR on 80x86 machines.
  173106. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  173107. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  173108. * of the alignment requirement of ALIGN_TYPE.
  173109. */
  173110. typedef union small_pool_struct * small_pool_ptr;
  173111. typedef union small_pool_struct {
  173112. struct {
  173113. small_pool_ptr next; /* next in list of pools */
  173114. size_t bytes_used; /* how many bytes already used within pool */
  173115. size_t bytes_left; /* bytes still available in this pool */
  173116. } hdr;
  173117. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  173118. } small_pool_hdr;
  173119. typedef union large_pool_struct FAR * large_pool_ptr;
  173120. typedef union large_pool_struct {
  173121. struct {
  173122. large_pool_ptr next; /* next in list of pools */
  173123. size_t bytes_used; /* how many bytes already used within pool */
  173124. size_t bytes_left; /* bytes still available in this pool */
  173125. } hdr;
  173126. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  173127. } large_pool_hdr;
  173128. /*
  173129. * Here is the full definition of a memory manager object.
  173130. */
  173131. typedef struct {
  173132. struct jpeg_memory_mgr pub; /* public fields */
  173133. /* Each pool identifier (lifetime class) names a linked list of pools. */
  173134. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  173135. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  173136. /* Since we only have one lifetime class of virtual arrays, only one
  173137. * linked list is necessary (for each datatype). Note that the virtual
  173138. * array control blocks being linked together are actually stored somewhere
  173139. * in the small-pool list.
  173140. */
  173141. jvirt_sarray_ptr virt_sarray_list;
  173142. jvirt_barray_ptr virt_barray_list;
  173143. /* This counts total space obtained from jpeg_get_small/large */
  173144. long total_space_allocated;
  173145. /* alloc_sarray and alloc_barray set this value for use by virtual
  173146. * array routines.
  173147. */
  173148. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  173149. } my_memory_mgr;
  173150. typedef my_memory_mgr * my_mem_ptr;
  173151. /*
  173152. * The control blocks for virtual arrays.
  173153. * Note that these blocks are allocated in the "small" pool area.
  173154. * System-dependent info for the associated backing store (if any) is hidden
  173155. * inside the backing_store_info struct.
  173156. */
  173157. struct jvirt_sarray_control {
  173158. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  173159. JDIMENSION rows_in_array; /* total virtual array height */
  173160. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  173161. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  173162. JDIMENSION rows_in_mem; /* height of memory buffer */
  173163. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  173164. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  173165. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  173166. boolean pre_zero; /* pre-zero mode requested? */
  173167. boolean dirty; /* do current buffer contents need written? */
  173168. boolean b_s_open; /* is backing-store data valid? */
  173169. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  173170. backing_store_info b_s_info; /* System-dependent control info */
  173171. };
  173172. struct jvirt_barray_control {
  173173. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  173174. JDIMENSION rows_in_array; /* total virtual array height */
  173175. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  173176. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  173177. JDIMENSION rows_in_mem; /* height of memory buffer */
  173178. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  173179. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  173180. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  173181. boolean pre_zero; /* pre-zero mode requested? */
  173182. boolean dirty; /* do current buffer contents need written? */
  173183. boolean b_s_open; /* is backing-store data valid? */
  173184. jvirt_barray_ptr next; /* link to next virtual barray control block */
  173185. backing_store_info b_s_info; /* System-dependent control info */
  173186. };
  173187. #ifdef MEM_STATS /* optional extra stuff for statistics */
  173188. LOCAL(void)
  173189. print_mem_stats (j_common_ptr cinfo, int pool_id)
  173190. {
  173191. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  173192. small_pool_ptr shdr_ptr;
  173193. large_pool_ptr lhdr_ptr;
  173194. /* Since this is only a debugging stub, we can cheat a little by using
  173195. * fprintf directly rather than going through the trace message code.
  173196. * This is helpful because message parm array can't handle longs.
  173197. */
  173198. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  173199. pool_id, mem->total_space_allocated);
  173200. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  173201. lhdr_ptr = lhdr_ptr->hdr.next) {
  173202. fprintf(stderr, " Large chunk used %ld\n",
  173203. (long) lhdr_ptr->hdr.bytes_used);
  173204. }
  173205. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  173206. shdr_ptr = shdr_ptr->hdr.next) {
  173207. fprintf(stderr, " Small chunk used %ld free %ld\n",
  173208. (long) shdr_ptr->hdr.bytes_used,
  173209. (long) shdr_ptr->hdr.bytes_left);
  173210. }
  173211. }
  173212. #endif /* MEM_STATS */
  173213. LOCAL(void)
  173214. out_of_memory (j_common_ptr cinfo, int which)
  173215. /* Report an out-of-memory error and stop execution */
  173216. /* If we compiled MEM_STATS support, report alloc requests before dying */
  173217. {
  173218. #ifdef MEM_STATS
  173219. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  173220. #endif
  173221. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  173222. }
  173223. /*
  173224. * Allocation of "small" objects.
  173225. *
  173226. * For these, we use pooled storage. When a new pool must be created,
  173227. * we try to get enough space for the current request plus a "slop" factor,
  173228. * where the slop will be the amount of leftover space in the new pool.
  173229. * The speed vs. space tradeoff is largely determined by the slop values.
  173230. * A different slop value is provided for each pool class (lifetime),
  173231. * and we also distinguish the first pool of a class from later ones.
  173232. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  173233. * machines, but may be too small if longs are 64 bits or more.
  173234. */
  173235. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  173236. {
  173237. 1600, /* first PERMANENT pool */
  173238. 16000 /* first IMAGE pool */
  173239. };
  173240. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  173241. {
  173242. 0, /* additional PERMANENT pools */
  173243. 5000 /* additional IMAGE pools */
  173244. };
  173245. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  173246. METHODDEF(void *)
  173247. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  173248. /* Allocate a "small" object */
  173249. {
  173250. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  173251. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  173252. char * data_ptr;
  173253. size_t odd_bytes, min_request, slop;
  173254. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  173255. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  173256. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  173257. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  173258. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  173259. if (odd_bytes > 0)
  173260. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  173261. /* See if space is available in any existing pool */
  173262. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  173263. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  173264. prev_hdr_ptr = NULL;
  173265. hdr_ptr = mem->small_list[pool_id];
  173266. while (hdr_ptr != NULL) {
  173267. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  173268. break; /* found pool with enough space */
  173269. prev_hdr_ptr = hdr_ptr;
  173270. hdr_ptr = hdr_ptr->hdr.next;
  173271. }
  173272. /* Time to make a new pool? */
  173273. if (hdr_ptr == NULL) {
  173274. /* min_request is what we need now, slop is what will be leftover */
  173275. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  173276. if (prev_hdr_ptr == NULL) /* first pool in class? */
  173277. slop = first_pool_slop[pool_id];
  173278. else
  173279. slop = extra_pool_slop[pool_id];
  173280. /* Don't ask for more than MAX_ALLOC_CHUNK */
  173281. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  173282. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  173283. /* Try to get space, if fail reduce slop and try again */
  173284. for (;;) {
  173285. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  173286. if (hdr_ptr != NULL)
  173287. break;
  173288. slop /= 2;
  173289. if (slop < MIN_SLOP) /* give up when it gets real small */
  173290. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  173291. }
  173292. mem->total_space_allocated += min_request + slop;
  173293. /* Success, initialize the new pool header and add to end of list */
  173294. hdr_ptr->hdr.next = NULL;
  173295. hdr_ptr->hdr.bytes_used = 0;
  173296. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  173297. if (prev_hdr_ptr == NULL) /* first pool in class? */
  173298. mem->small_list[pool_id] = hdr_ptr;
  173299. else
  173300. prev_hdr_ptr->hdr.next = hdr_ptr;
  173301. }
  173302. /* OK, allocate the object from the current pool */
  173303. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  173304. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  173305. hdr_ptr->hdr.bytes_used += sizeofobject;
  173306. hdr_ptr->hdr.bytes_left -= sizeofobject;
  173307. return (void *) data_ptr;
  173308. }
  173309. /*
  173310. * Allocation of "large" objects.
  173311. *
  173312. * The external semantics of these are the same as "small" objects,
  173313. * except that FAR pointers are used on 80x86. However the pool
  173314. * management heuristics are quite different. We assume that each
  173315. * request is large enough that it may as well be passed directly to
  173316. * jpeg_get_large; the pool management just links everything together
  173317. * so that we can free it all on demand.
  173318. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  173319. * structures. The routines that create these structures (see below)
  173320. * deliberately bunch rows together to ensure a large request size.
  173321. */
  173322. METHODDEF(void FAR *)
  173323. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  173324. /* Allocate a "large" object */
  173325. {
  173326. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  173327. large_pool_ptr hdr_ptr;
  173328. size_t odd_bytes;
  173329. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  173330. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  173331. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  173332. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  173333. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  173334. if (odd_bytes > 0)
  173335. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  173336. /* Always make a new pool */
  173337. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  173338. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  173339. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  173340. SIZEOF(large_pool_hdr));
  173341. if (hdr_ptr == NULL)
  173342. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  173343. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  173344. /* Success, initialize the new pool header and add to list */
  173345. hdr_ptr->hdr.next = mem->large_list[pool_id];
  173346. /* We maintain space counts in each pool header for statistical purposes,
  173347. * even though they are not needed for allocation.
  173348. */
  173349. hdr_ptr->hdr.bytes_used = sizeofobject;
  173350. hdr_ptr->hdr.bytes_left = 0;
  173351. mem->large_list[pool_id] = hdr_ptr;
  173352. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  173353. }
  173354. /*
  173355. * Creation of 2-D sample arrays.
  173356. * The pointers are in near heap, the samples themselves in FAR heap.
  173357. *
  173358. * To minimize allocation overhead and to allow I/O of large contiguous
  173359. * blocks, we allocate the sample rows in groups of as many rows as possible
  173360. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  173361. * NB: the virtual array control routines, later in this file, know about
  173362. * this chunking of rows. The rowsperchunk value is left in the mem manager
  173363. * object so that it can be saved away if this sarray is the workspace for
  173364. * a virtual array.
  173365. */
  173366. METHODDEF(JSAMPARRAY)
  173367. alloc_sarray (j_common_ptr cinfo, int pool_id,
  173368. JDIMENSION samplesperrow, JDIMENSION numrows)
  173369. /* Allocate a 2-D sample array */
  173370. {
  173371. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  173372. JSAMPARRAY result;
  173373. JSAMPROW workspace;
  173374. JDIMENSION rowsperchunk, currow, i;
  173375. long ltemp;
  173376. /* Calculate max # of rows allowed in one allocation chunk */
  173377. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  173378. ((long) samplesperrow * SIZEOF(JSAMPLE));
  173379. if (ltemp <= 0)
  173380. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  173381. if (ltemp < (long) numrows)
  173382. rowsperchunk = (JDIMENSION) ltemp;
  173383. else
  173384. rowsperchunk = numrows;
  173385. mem->last_rowsperchunk = rowsperchunk;
  173386. /* Get space for row pointers (small object) */
  173387. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  173388. (size_t) (numrows * SIZEOF(JSAMPROW)));
  173389. /* Get the rows themselves (large objects) */
  173390. currow = 0;
  173391. while (currow < numrows) {
  173392. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  173393. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  173394. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  173395. * SIZEOF(JSAMPLE)));
  173396. for (i = rowsperchunk; i > 0; i--) {
  173397. result[currow++] = workspace;
  173398. workspace += samplesperrow;
  173399. }
  173400. }
  173401. return result;
  173402. }
  173403. /*
  173404. * Creation of 2-D coefficient-block arrays.
  173405. * This is essentially the same as the code for sample arrays, above.
  173406. */
  173407. METHODDEF(JBLOCKARRAY)
  173408. alloc_barray (j_common_ptr cinfo, int pool_id,
  173409. JDIMENSION blocksperrow, JDIMENSION numrows)
  173410. /* Allocate a 2-D coefficient-block array */
  173411. {
  173412. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  173413. JBLOCKARRAY result;
  173414. JBLOCKROW workspace;
  173415. JDIMENSION rowsperchunk, currow, i;
  173416. long ltemp;
  173417. /* Calculate max # of rows allowed in one allocation chunk */
  173418. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  173419. ((long) blocksperrow * SIZEOF(JBLOCK));
  173420. if (ltemp <= 0)
  173421. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  173422. if (ltemp < (long) numrows)
  173423. rowsperchunk = (JDIMENSION) ltemp;
  173424. else
  173425. rowsperchunk = numrows;
  173426. mem->last_rowsperchunk = rowsperchunk;
  173427. /* Get space for row pointers (small object) */
  173428. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  173429. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  173430. /* Get the rows themselves (large objects) */
  173431. currow = 0;
  173432. while (currow < numrows) {
  173433. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  173434. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  173435. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  173436. * SIZEOF(JBLOCK)));
  173437. for (i = rowsperchunk; i > 0; i--) {
  173438. result[currow++] = workspace;
  173439. workspace += blocksperrow;
  173440. }
  173441. }
  173442. return result;
  173443. }
  173444. /*
  173445. * About virtual array management:
  173446. *
  173447. * The above "normal" array routines are only used to allocate strip buffers
  173448. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  173449. * are handled as "virtual" arrays. The array is still accessed a strip at a
  173450. * time, but the memory manager must save the whole array for repeated
  173451. * accesses. The intended implementation is that there is a strip buffer in
  173452. * memory (as high as is possible given the desired memory limit), plus a
  173453. * backing file that holds the rest of the array.
  173454. *
  173455. * The request_virt_array routines are told the total size of the image and
  173456. * the maximum number of rows that will be accessed at once. The in-memory
  173457. * buffer must be at least as large as the maxaccess value.
  173458. *
  173459. * The request routines create control blocks but not the in-memory buffers.
  173460. * That is postponed until realize_virt_arrays is called. At that time the
  173461. * total amount of space needed is known (approximately, anyway), so free
  173462. * memory can be divided up fairly.
  173463. *
  173464. * The access_virt_array routines are responsible for making a specific strip
  173465. * area accessible (after reading or writing the backing file, if necessary).
  173466. * Note that the access routines are told whether the caller intends to modify
  173467. * the accessed strip; during a read-only pass this saves having to rewrite
  173468. * data to disk. The access routines are also responsible for pre-zeroing
  173469. * any newly accessed rows, if pre-zeroing was requested.
  173470. *
  173471. * In current usage, the access requests are usually for nonoverlapping
  173472. * strips; that is, successive access start_row numbers differ by exactly
  173473. * num_rows = maxaccess. This means we can get good performance with simple
  173474. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  173475. * of the access height; then there will never be accesses across bufferload
  173476. * boundaries. The code will still work with overlapping access requests,
  173477. * but it doesn't handle bufferload overlaps very efficiently.
  173478. */
  173479. METHODDEF(jvirt_sarray_ptr)
  173480. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  173481. JDIMENSION samplesperrow, JDIMENSION numrows,
  173482. JDIMENSION maxaccess)
  173483. /* Request a virtual 2-D sample array */
  173484. {
  173485. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  173486. jvirt_sarray_ptr result;
  173487. /* Only IMAGE-lifetime virtual arrays are currently supported */
  173488. if (pool_id != JPOOL_IMAGE)
  173489. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  173490. /* get control block */
  173491. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  173492. SIZEOF(struct jvirt_sarray_control));
  173493. result->mem_buffer = NULL; /* marks array not yet realized */
  173494. result->rows_in_array = numrows;
  173495. result->samplesperrow = samplesperrow;
  173496. result->maxaccess = maxaccess;
  173497. result->pre_zero = pre_zero;
  173498. result->b_s_open = FALSE; /* no associated backing-store object */
  173499. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  173500. mem->virt_sarray_list = result;
  173501. return result;
  173502. }
  173503. METHODDEF(jvirt_barray_ptr)
  173504. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  173505. JDIMENSION blocksperrow, JDIMENSION numrows,
  173506. JDIMENSION maxaccess)
  173507. /* Request a virtual 2-D coefficient-block array */
  173508. {
  173509. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  173510. jvirt_barray_ptr result;
  173511. /* Only IMAGE-lifetime virtual arrays are currently supported */
  173512. if (pool_id != JPOOL_IMAGE)
  173513. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  173514. /* get control block */
  173515. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  173516. SIZEOF(struct jvirt_barray_control));
  173517. result->mem_buffer = NULL; /* marks array not yet realized */
  173518. result->rows_in_array = numrows;
  173519. result->blocksperrow = blocksperrow;
  173520. result->maxaccess = maxaccess;
  173521. result->pre_zero = pre_zero;
  173522. result->b_s_open = FALSE; /* no associated backing-store object */
  173523. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  173524. mem->virt_barray_list = result;
  173525. return result;
  173526. }
  173527. METHODDEF(void)
  173528. realize_virt_arrays (j_common_ptr cinfo)
  173529. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  173530. {
  173531. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  173532. long space_per_minheight, maximum_space, avail_mem;
  173533. long minheights, max_minheights;
  173534. jvirt_sarray_ptr sptr;
  173535. jvirt_barray_ptr bptr;
  173536. /* Compute the minimum space needed (maxaccess rows in each buffer)
  173537. * and the maximum space needed (full image height in each buffer).
  173538. * These may be of use to the system-dependent jpeg_mem_available routine.
  173539. */
  173540. space_per_minheight = 0;
  173541. maximum_space = 0;
  173542. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  173543. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  173544. space_per_minheight += (long) sptr->maxaccess *
  173545. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  173546. maximum_space += (long) sptr->rows_in_array *
  173547. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  173548. }
  173549. }
  173550. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  173551. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  173552. space_per_minheight += (long) bptr->maxaccess *
  173553. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  173554. maximum_space += (long) bptr->rows_in_array *
  173555. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  173556. }
  173557. }
  173558. if (space_per_minheight <= 0)
  173559. return; /* no unrealized arrays, no work */
  173560. /* Determine amount of memory to actually use; this is system-dependent. */
  173561. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  173562. mem->total_space_allocated);
  173563. /* If the maximum space needed is available, make all the buffers full
  173564. * height; otherwise parcel it out with the same number of minheights
  173565. * in each buffer.
  173566. */
  173567. if (avail_mem >= maximum_space)
  173568. max_minheights = 1000000000L;
  173569. else {
  173570. max_minheights = avail_mem / space_per_minheight;
  173571. /* If there doesn't seem to be enough space, try to get the minimum
  173572. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  173573. */
  173574. if (max_minheights <= 0)
  173575. max_minheights = 1;
  173576. }
  173577. /* Allocate the in-memory buffers and initialize backing store as needed. */
  173578. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  173579. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  173580. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  173581. if (minheights <= max_minheights) {
  173582. /* This buffer fits in memory */
  173583. sptr->rows_in_mem = sptr->rows_in_array;
  173584. } else {
  173585. /* It doesn't fit in memory, create backing store. */
  173586. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  173587. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  173588. (long) sptr->rows_in_array *
  173589. (long) sptr->samplesperrow *
  173590. (long) SIZEOF(JSAMPLE));
  173591. sptr->b_s_open = TRUE;
  173592. }
  173593. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  173594. sptr->samplesperrow, sptr->rows_in_mem);
  173595. sptr->rowsperchunk = mem->last_rowsperchunk;
  173596. sptr->cur_start_row = 0;
  173597. sptr->first_undef_row = 0;
  173598. sptr->dirty = FALSE;
  173599. }
  173600. }
  173601. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  173602. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  173603. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  173604. if (minheights <= max_minheights) {
  173605. /* This buffer fits in memory */
  173606. bptr->rows_in_mem = bptr->rows_in_array;
  173607. } else {
  173608. /* It doesn't fit in memory, create backing store. */
  173609. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  173610. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  173611. (long) bptr->rows_in_array *
  173612. (long) bptr->blocksperrow *
  173613. (long) SIZEOF(JBLOCK));
  173614. bptr->b_s_open = TRUE;
  173615. }
  173616. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  173617. bptr->blocksperrow, bptr->rows_in_mem);
  173618. bptr->rowsperchunk = mem->last_rowsperchunk;
  173619. bptr->cur_start_row = 0;
  173620. bptr->first_undef_row = 0;
  173621. bptr->dirty = FALSE;
  173622. }
  173623. }
  173624. }
  173625. LOCAL(void)
  173626. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  173627. /* Do backing store read or write of a virtual sample array */
  173628. {
  173629. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  173630. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  173631. file_offset = ptr->cur_start_row * bytesperrow;
  173632. /* Loop to read or write each allocation chunk in mem_buffer */
  173633. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  173634. /* One chunk, but check for short chunk at end of buffer */
  173635. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  173636. /* Transfer no more than is currently defined */
  173637. thisrow = (long) ptr->cur_start_row + i;
  173638. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  173639. /* Transfer no more than fits in file */
  173640. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  173641. if (rows <= 0) /* this chunk might be past end of file! */
  173642. break;
  173643. byte_count = rows * bytesperrow;
  173644. if (writing)
  173645. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  173646. (void FAR *) ptr->mem_buffer[i],
  173647. file_offset, byte_count);
  173648. else
  173649. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  173650. (void FAR *) ptr->mem_buffer[i],
  173651. file_offset, byte_count);
  173652. file_offset += byte_count;
  173653. }
  173654. }
  173655. LOCAL(void)
  173656. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  173657. /* Do backing store read or write of a virtual coefficient-block array */
  173658. {
  173659. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  173660. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  173661. file_offset = ptr->cur_start_row * bytesperrow;
  173662. /* Loop to read or write each allocation chunk in mem_buffer */
  173663. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  173664. /* One chunk, but check for short chunk at end of buffer */
  173665. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  173666. /* Transfer no more than is currently defined */
  173667. thisrow = (long) ptr->cur_start_row + i;
  173668. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  173669. /* Transfer no more than fits in file */
  173670. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  173671. if (rows <= 0) /* this chunk might be past end of file! */
  173672. break;
  173673. byte_count = rows * bytesperrow;
  173674. if (writing)
  173675. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  173676. (void FAR *) ptr->mem_buffer[i],
  173677. file_offset, byte_count);
  173678. else
  173679. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  173680. (void FAR *) ptr->mem_buffer[i],
  173681. file_offset, byte_count);
  173682. file_offset += byte_count;
  173683. }
  173684. }
  173685. METHODDEF(JSAMPARRAY)
  173686. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  173687. JDIMENSION start_row, JDIMENSION num_rows,
  173688. boolean writable)
  173689. /* Access the part of a virtual sample array starting at start_row */
  173690. /* and extending for num_rows rows. writable is true if */
  173691. /* caller intends to modify the accessed area. */
  173692. {
  173693. JDIMENSION end_row = start_row + num_rows;
  173694. JDIMENSION undef_row;
  173695. /* debugging check */
  173696. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  173697. ptr->mem_buffer == NULL)
  173698. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  173699. /* Make the desired part of the virtual array accessible */
  173700. if (start_row < ptr->cur_start_row ||
  173701. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  173702. if (! ptr->b_s_open)
  173703. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  173704. /* Flush old buffer contents if necessary */
  173705. if (ptr->dirty) {
  173706. do_sarray_io(cinfo, ptr, TRUE);
  173707. ptr->dirty = FALSE;
  173708. }
  173709. /* Decide what part of virtual array to access.
  173710. * Algorithm: if target address > current window, assume forward scan,
  173711. * load starting at target address. If target address < current window,
  173712. * assume backward scan, load so that target area is top of window.
  173713. * Note that when switching from forward write to forward read, will have
  173714. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  173715. */
  173716. if (start_row > ptr->cur_start_row) {
  173717. ptr->cur_start_row = start_row;
  173718. } else {
  173719. /* use long arithmetic here to avoid overflow & unsigned problems */
  173720. long ltemp;
  173721. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  173722. if (ltemp < 0)
  173723. ltemp = 0; /* don't fall off front end of file */
  173724. ptr->cur_start_row = (JDIMENSION) ltemp;
  173725. }
  173726. /* Read in the selected part of the array.
  173727. * During the initial write pass, we will do no actual read
  173728. * because the selected part is all undefined.
  173729. */
  173730. do_sarray_io(cinfo, ptr, FALSE);
  173731. }
  173732. /* Ensure the accessed part of the array is defined; prezero if needed.
  173733. * To improve locality of access, we only prezero the part of the array
  173734. * that the caller is about to access, not the entire in-memory array.
  173735. */
  173736. if (ptr->first_undef_row < end_row) {
  173737. if (ptr->first_undef_row < start_row) {
  173738. if (writable) /* writer skipped over a section of array */
  173739. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  173740. undef_row = start_row; /* but reader is allowed to read ahead */
  173741. } else {
  173742. undef_row = ptr->first_undef_row;
  173743. }
  173744. if (writable)
  173745. ptr->first_undef_row = end_row;
  173746. if (ptr->pre_zero) {
  173747. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  173748. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  173749. end_row -= ptr->cur_start_row;
  173750. while (undef_row < end_row) {
  173751. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  173752. undef_row++;
  173753. }
  173754. } else {
  173755. if (! writable) /* reader looking at undefined data */
  173756. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  173757. }
  173758. }
  173759. /* Flag the buffer dirty if caller will write in it */
  173760. if (writable)
  173761. ptr->dirty = TRUE;
  173762. /* Return address of proper part of the buffer */
  173763. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  173764. }
  173765. METHODDEF(JBLOCKARRAY)
  173766. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  173767. JDIMENSION start_row, JDIMENSION num_rows,
  173768. boolean writable)
  173769. /* Access the part of a virtual block array starting at start_row */
  173770. /* and extending for num_rows rows. writable is true if */
  173771. /* caller intends to modify the accessed area. */
  173772. {
  173773. JDIMENSION end_row = start_row + num_rows;
  173774. JDIMENSION undef_row;
  173775. /* debugging check */
  173776. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  173777. ptr->mem_buffer == NULL)
  173778. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  173779. /* Make the desired part of the virtual array accessible */
  173780. if (start_row < ptr->cur_start_row ||
  173781. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  173782. if (! ptr->b_s_open)
  173783. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  173784. /* Flush old buffer contents if necessary */
  173785. if (ptr->dirty) {
  173786. do_barray_io(cinfo, ptr, TRUE);
  173787. ptr->dirty = FALSE;
  173788. }
  173789. /* Decide what part of virtual array to access.
  173790. * Algorithm: if target address > current window, assume forward scan,
  173791. * load starting at target address. If target address < current window,
  173792. * assume backward scan, load so that target area is top of window.
  173793. * Note that when switching from forward write to forward read, will have
  173794. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  173795. */
  173796. if (start_row > ptr->cur_start_row) {
  173797. ptr->cur_start_row = start_row;
  173798. } else {
  173799. /* use long arithmetic here to avoid overflow & unsigned problems */
  173800. long ltemp;
  173801. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  173802. if (ltemp < 0)
  173803. ltemp = 0; /* don't fall off front end of file */
  173804. ptr->cur_start_row = (JDIMENSION) ltemp;
  173805. }
  173806. /* Read in the selected part of the array.
  173807. * During the initial write pass, we will do no actual read
  173808. * because the selected part is all undefined.
  173809. */
  173810. do_barray_io(cinfo, ptr, FALSE);
  173811. }
  173812. /* Ensure the accessed part of the array is defined; prezero if needed.
  173813. * To improve locality of access, we only prezero the part of the array
  173814. * that the caller is about to access, not the entire in-memory array.
  173815. */
  173816. if (ptr->first_undef_row < end_row) {
  173817. if (ptr->first_undef_row < start_row) {
  173818. if (writable) /* writer skipped over a section of array */
  173819. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  173820. undef_row = start_row; /* but reader is allowed to read ahead */
  173821. } else {
  173822. undef_row = ptr->first_undef_row;
  173823. }
  173824. if (writable)
  173825. ptr->first_undef_row = end_row;
  173826. if (ptr->pre_zero) {
  173827. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  173828. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  173829. end_row -= ptr->cur_start_row;
  173830. while (undef_row < end_row) {
  173831. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  173832. undef_row++;
  173833. }
  173834. } else {
  173835. if (! writable) /* reader looking at undefined data */
  173836. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  173837. }
  173838. }
  173839. /* Flag the buffer dirty if caller will write in it */
  173840. if (writable)
  173841. ptr->dirty = TRUE;
  173842. /* Return address of proper part of the buffer */
  173843. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  173844. }
  173845. /*
  173846. * Release all objects belonging to a specified pool.
  173847. */
  173848. METHODDEF(void)
  173849. free_pool (j_common_ptr cinfo, int pool_id)
  173850. {
  173851. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  173852. small_pool_ptr shdr_ptr;
  173853. large_pool_ptr lhdr_ptr;
  173854. size_t space_freed;
  173855. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  173856. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  173857. #ifdef MEM_STATS
  173858. if (cinfo->err->trace_level > 1)
  173859. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  173860. #endif
  173861. /* If freeing IMAGE pool, close any virtual arrays first */
  173862. if (pool_id == JPOOL_IMAGE) {
  173863. jvirt_sarray_ptr sptr;
  173864. jvirt_barray_ptr bptr;
  173865. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  173866. if (sptr->b_s_open) { /* there may be no backing store */
  173867. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  173868. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  173869. }
  173870. }
  173871. mem->virt_sarray_list = NULL;
  173872. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  173873. if (bptr->b_s_open) { /* there may be no backing store */
  173874. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  173875. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  173876. }
  173877. }
  173878. mem->virt_barray_list = NULL;
  173879. }
  173880. /* Release large objects */
  173881. lhdr_ptr = mem->large_list[pool_id];
  173882. mem->large_list[pool_id] = NULL;
  173883. while (lhdr_ptr != NULL) {
  173884. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  173885. space_freed = lhdr_ptr->hdr.bytes_used +
  173886. lhdr_ptr->hdr.bytes_left +
  173887. SIZEOF(large_pool_hdr);
  173888. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  173889. mem->total_space_allocated -= space_freed;
  173890. lhdr_ptr = next_lhdr_ptr;
  173891. }
  173892. /* Release small objects */
  173893. shdr_ptr = mem->small_list[pool_id];
  173894. mem->small_list[pool_id] = NULL;
  173895. while (shdr_ptr != NULL) {
  173896. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  173897. space_freed = shdr_ptr->hdr.bytes_used +
  173898. shdr_ptr->hdr.bytes_left +
  173899. SIZEOF(small_pool_hdr);
  173900. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  173901. mem->total_space_allocated -= space_freed;
  173902. shdr_ptr = next_shdr_ptr;
  173903. }
  173904. }
  173905. /*
  173906. * Close up shop entirely.
  173907. * Note that this cannot be called unless cinfo->mem is non-NULL.
  173908. */
  173909. METHODDEF(void)
  173910. self_destruct (j_common_ptr cinfo)
  173911. {
  173912. int pool;
  173913. /* Close all backing store, release all memory.
  173914. * Releasing pools in reverse order might help avoid fragmentation
  173915. * with some (brain-damaged) malloc libraries.
  173916. */
  173917. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  173918. free_pool(cinfo, pool);
  173919. }
  173920. /* Release the memory manager control block too. */
  173921. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  173922. cinfo->mem = NULL; /* ensures I will be called only once */
  173923. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  173924. }
  173925. /*
  173926. * Memory manager initialization.
  173927. * When this is called, only the error manager pointer is valid in cinfo!
  173928. */
  173929. GLOBAL(void)
  173930. jinit_memory_mgr (j_common_ptr cinfo)
  173931. {
  173932. my_mem_ptr mem;
  173933. long max_to_use;
  173934. int pool;
  173935. size_t test_mac;
  173936. cinfo->mem = NULL; /* for safety if init fails */
  173937. /* Check for configuration errors.
  173938. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  173939. * doesn't reflect any real hardware alignment requirement.
  173940. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  173941. * in common if and only if X is a power of 2, ie has only one one-bit.
  173942. * Some compilers may give an "unreachable code" warning here; ignore it.
  173943. */
  173944. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  173945. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  173946. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  173947. * a multiple of SIZEOF(ALIGN_TYPE).
  173948. * Again, an "unreachable code" warning may be ignored here.
  173949. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  173950. */
  173951. test_mac = (size_t) MAX_ALLOC_CHUNK;
  173952. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  173953. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  173954. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  173955. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  173956. /* Attempt to allocate memory manager's control block */
  173957. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  173958. if (mem == NULL) {
  173959. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  173960. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  173961. }
  173962. /* OK, fill in the method pointers */
  173963. mem->pub.alloc_small = alloc_small;
  173964. mem->pub.alloc_large = alloc_large;
  173965. mem->pub.alloc_sarray = alloc_sarray;
  173966. mem->pub.alloc_barray = alloc_barray;
  173967. mem->pub.request_virt_sarray = request_virt_sarray;
  173968. mem->pub.request_virt_barray = request_virt_barray;
  173969. mem->pub.realize_virt_arrays = realize_virt_arrays;
  173970. mem->pub.access_virt_sarray = access_virt_sarray;
  173971. mem->pub.access_virt_barray = access_virt_barray;
  173972. mem->pub.free_pool = free_pool;
  173973. mem->pub.self_destruct = self_destruct;
  173974. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  173975. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  173976. /* Initialize working state */
  173977. mem->pub.max_memory_to_use = max_to_use;
  173978. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  173979. mem->small_list[pool] = NULL;
  173980. mem->large_list[pool] = NULL;
  173981. }
  173982. mem->virt_sarray_list = NULL;
  173983. mem->virt_barray_list = NULL;
  173984. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  173985. /* Declare ourselves open for business */
  173986. cinfo->mem = & mem->pub;
  173987. /* Check for an environment variable JPEGMEM; if found, override the
  173988. * default max_memory setting from jpeg_mem_init. Note that the
  173989. * surrounding application may again override this value.
  173990. * If your system doesn't support getenv(), define NO_GETENV to disable
  173991. * this feature.
  173992. */
  173993. #ifndef NO_GETENV
  173994. { char * memenv;
  173995. if ((memenv = getenv("JPEGMEM")) != NULL) {
  173996. char ch = 'x';
  173997. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  173998. if (ch == 'm' || ch == 'M')
  173999. max_to_use *= 1000L;
  174000. mem->pub.max_memory_to_use = max_to_use * 1000L;
  174001. }
  174002. }
  174003. }
  174004. #endif
  174005. }
  174006. /*** End of inlined file: jmemmgr.c ***/
  174007. /*** Start of inlined file: jmemnobs.c ***/
  174008. #define JPEG_INTERNALS
  174009. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  174010. extern void * malloc JPP((size_t size));
  174011. extern void free JPP((void *ptr));
  174012. #endif
  174013. /*
  174014. * Memory allocation and freeing are controlled by the regular library
  174015. * routines malloc() and free().
  174016. */
  174017. GLOBAL(void *)
  174018. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  174019. {
  174020. return (void *) malloc(sizeofobject);
  174021. }
  174022. GLOBAL(void)
  174023. jpeg_free_small (j_common_ptr , void * object, size_t)
  174024. {
  174025. free(object);
  174026. }
  174027. /*
  174028. * "Large" objects are treated the same as "small" ones.
  174029. * NB: although we include FAR keywords in the routine declarations,
  174030. * this file won't actually work in 80x86 small/medium model; at least,
  174031. * you probably won't be able to process useful-size images in only 64KB.
  174032. */
  174033. GLOBAL(void FAR *)
  174034. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  174035. {
  174036. return (void FAR *) malloc(sizeofobject);
  174037. }
  174038. GLOBAL(void)
  174039. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  174040. {
  174041. free(object);
  174042. }
  174043. /*
  174044. * This routine computes the total memory space available for allocation.
  174045. * Here we always say, "we got all you want bud!"
  174046. */
  174047. GLOBAL(long)
  174048. jpeg_mem_available (j_common_ptr, long,
  174049. long max_bytes_needed, long)
  174050. {
  174051. return max_bytes_needed;
  174052. }
  174053. /*
  174054. * Backing store (temporary file) management.
  174055. * Since jpeg_mem_available always promised the moon,
  174056. * this should never be called and we can just error out.
  174057. */
  174058. GLOBAL(void)
  174059. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  174060. long )
  174061. {
  174062. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  174063. }
  174064. /*
  174065. * These routines take care of any system-dependent initialization and
  174066. * cleanup required. Here, there isn't any.
  174067. */
  174068. GLOBAL(long)
  174069. jpeg_mem_init (j_common_ptr)
  174070. {
  174071. return 0; /* just set max_memory_to_use to 0 */
  174072. }
  174073. GLOBAL(void)
  174074. jpeg_mem_term (j_common_ptr)
  174075. {
  174076. /* no work */
  174077. }
  174078. /*** End of inlined file: jmemnobs.c ***/
  174079. /*** Start of inlined file: jquant1.c ***/
  174080. #define JPEG_INTERNALS
  174081. #ifdef QUANT_1PASS_SUPPORTED
  174082. /*
  174083. * The main purpose of 1-pass quantization is to provide a fast, if not very
  174084. * high quality, colormapped output capability. A 2-pass quantizer usually
  174085. * gives better visual quality; however, for quantized grayscale output this
  174086. * quantizer is perfectly adequate. Dithering is highly recommended with this
  174087. * quantizer, though you can turn it off if you really want to.
  174088. *
  174089. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  174090. * image. We use a map consisting of all combinations of Ncolors[i] color
  174091. * values for the i'th component. The Ncolors[] values are chosen so that
  174092. * their product, the total number of colors, is no more than that requested.
  174093. * (In most cases, the product will be somewhat less.)
  174094. *
  174095. * Since the colormap is orthogonal, the representative value for each color
  174096. * component can be determined without considering the other components;
  174097. * then these indexes can be combined into a colormap index by a standard
  174098. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  174099. * can be precalculated and stored in the lookup table colorindex[].
  174100. * colorindex[i][j] maps pixel value j in component i to the nearest
  174101. * representative value (grid plane) for that component; this index is
  174102. * multiplied by the array stride for component i, so that the
  174103. * index of the colormap entry closest to a given pixel value is just
  174104. * sum( colorindex[component-number][pixel-component-value] )
  174105. * Aside from being fast, this scheme allows for variable spacing between
  174106. * representative values with no additional lookup cost.
  174107. *
  174108. * If gamma correction has been applied in color conversion, it might be wise
  174109. * to adjust the color grid spacing so that the representative colors are
  174110. * equidistant in linear space. At this writing, gamma correction is not
  174111. * implemented by jdcolor, so nothing is done here.
  174112. */
  174113. /* Declarations for ordered dithering.
  174114. *
  174115. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  174116. * dithering is described in many references, for instance Dale Schumacher's
  174117. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  174118. * In place of Schumacher's comparisons against a "threshold" value, we add a
  174119. * "dither" value to the input pixel and then round the result to the nearest
  174120. * output value. The dither value is equivalent to (0.5 - threshold) times
  174121. * the distance between output values. For ordered dithering, we assume that
  174122. * the output colors are equally spaced; if not, results will probably be
  174123. * worse, since the dither may be too much or too little at a given point.
  174124. *
  174125. * The normal calculation would be to form pixel value + dither, range-limit
  174126. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  174127. * We can skip the separate range-limiting step by extending the colorindex
  174128. * table in both directions.
  174129. */
  174130. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  174131. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  174132. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  174133. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  174134. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  174135. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  174136. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  174137. /* Bayer's order-4 dither array. Generated by the code given in
  174138. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  174139. * The values in this array must range from 0 to ODITHER_CELLS-1.
  174140. */
  174141. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  174142. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  174143. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  174144. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  174145. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  174146. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  174147. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  174148. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  174149. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  174150. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  174151. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  174152. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  174153. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  174154. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  174155. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  174156. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  174157. };
  174158. /* Declarations for Floyd-Steinberg dithering.
  174159. *
  174160. * Errors are accumulated into the array fserrors[], at a resolution of
  174161. * 1/16th of a pixel count. The error at a given pixel is propagated
  174162. * to its not-yet-processed neighbors using the standard F-S fractions,
  174163. * ... (here) 7/16
  174164. * 3/16 5/16 1/16
  174165. * We work left-to-right on even rows, right-to-left on odd rows.
  174166. *
  174167. * We can get away with a single array (holding one row's worth of errors)
  174168. * by using it to store the current row's errors at pixel columns not yet
  174169. * processed, but the next row's errors at columns already processed. We
  174170. * need only a few extra variables to hold the errors immediately around the
  174171. * current column. (If we are lucky, those variables are in registers, but
  174172. * even if not, they're probably cheaper to access than array elements are.)
  174173. *
  174174. * The fserrors[] array is indexed [component#][position].
  174175. * We provide (#columns + 2) entries per component; the extra entry at each
  174176. * end saves us from special-casing the first and last pixels.
  174177. *
  174178. * Note: on a wide image, we might not have enough room in a PC's near data
  174179. * segment to hold the error array; so it is allocated with alloc_large.
  174180. */
  174181. #if BITS_IN_JSAMPLE == 8
  174182. typedef INT16 FSERROR; /* 16 bits should be enough */
  174183. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  174184. #else
  174185. typedef INT32 FSERROR; /* may need more than 16 bits */
  174186. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  174187. #endif
  174188. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  174189. /* Private subobject */
  174190. #define MAX_Q_COMPS 4 /* max components I can handle */
  174191. typedef struct {
  174192. struct jpeg_color_quantizer pub; /* public fields */
  174193. /* Initially allocated colormap is saved here */
  174194. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  174195. int sv_actual; /* number of entries in use */
  174196. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  174197. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  174198. * premultiplied as described above. Since colormap indexes must fit into
  174199. * JSAMPLEs, the entries of this array will too.
  174200. */
  174201. boolean is_padded; /* is the colorindex padded for odither? */
  174202. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  174203. /* Variables for ordered dithering */
  174204. int row_index; /* cur row's vertical index in dither matrix */
  174205. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  174206. /* Variables for Floyd-Steinberg dithering */
  174207. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  174208. boolean on_odd_row; /* flag to remember which row we are on */
  174209. } my_cquantizer;
  174210. typedef my_cquantizer * my_cquantize_ptr;
  174211. /*
  174212. * Policy-making subroutines for create_colormap and create_colorindex.
  174213. * These routines determine the colormap to be used. The rest of the module
  174214. * only assumes that the colormap is orthogonal.
  174215. *
  174216. * * select_ncolors decides how to divvy up the available colors
  174217. * among the components.
  174218. * * output_value defines the set of representative values for a component.
  174219. * * largest_input_value defines the mapping from input values to
  174220. * representative values for a component.
  174221. * Note that the latter two routines may impose different policies for
  174222. * different components, though this is not currently done.
  174223. */
  174224. LOCAL(int)
  174225. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  174226. /* Determine allocation of desired colors to components, */
  174227. /* and fill in Ncolors[] array to indicate choice. */
  174228. /* Return value is total number of colors (product of Ncolors[] values). */
  174229. {
  174230. int nc = cinfo->out_color_components; /* number of color components */
  174231. int max_colors = cinfo->desired_number_of_colors;
  174232. int total_colors, iroot, i, j;
  174233. boolean changed;
  174234. long temp;
  174235. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  174236. /* We can allocate at least the nc'th root of max_colors per component. */
  174237. /* Compute floor(nc'th root of max_colors). */
  174238. iroot = 1;
  174239. do {
  174240. iroot++;
  174241. temp = iroot; /* set temp = iroot ** nc */
  174242. for (i = 1; i < nc; i++)
  174243. temp *= iroot;
  174244. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  174245. iroot--; /* now iroot = floor(root) */
  174246. /* Must have at least 2 color values per component */
  174247. if (iroot < 2)
  174248. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  174249. /* Initialize to iroot color values for each component */
  174250. total_colors = 1;
  174251. for (i = 0; i < nc; i++) {
  174252. Ncolors[i] = iroot;
  174253. total_colors *= iroot;
  174254. }
  174255. /* We may be able to increment the count for one or more components without
  174256. * exceeding max_colors, though we know not all can be incremented.
  174257. * Sometimes, the first component can be incremented more than once!
  174258. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  174259. * In RGB colorspace, try to increment G first, then R, then B.
  174260. */
  174261. do {
  174262. changed = FALSE;
  174263. for (i = 0; i < nc; i++) {
  174264. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  174265. /* calculate new total_colors if Ncolors[j] is incremented */
  174266. temp = total_colors / Ncolors[j];
  174267. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  174268. if (temp > (long) max_colors)
  174269. break; /* won't fit, done with this pass */
  174270. Ncolors[j]++; /* OK, apply the increment */
  174271. total_colors = (int) temp;
  174272. changed = TRUE;
  174273. }
  174274. } while (changed);
  174275. return total_colors;
  174276. }
  174277. LOCAL(int)
  174278. output_value (j_decompress_ptr, int, int j, int maxj)
  174279. /* Return j'th output value, where j will range from 0 to maxj */
  174280. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  174281. {
  174282. /* We always provide values 0 and MAXJSAMPLE for each component;
  174283. * any additional values are equally spaced between these limits.
  174284. * (Forcing the upper and lower values to the limits ensures that
  174285. * dithering can't produce a color outside the selected gamut.)
  174286. */
  174287. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  174288. }
  174289. LOCAL(int)
  174290. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  174291. /* Return largest input value that should map to j'th output value */
  174292. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  174293. {
  174294. /* Breakpoints are halfway between values returned by output_value */
  174295. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  174296. }
  174297. /*
  174298. * Create the colormap.
  174299. */
  174300. LOCAL(void)
  174301. create_colormap (j_decompress_ptr cinfo)
  174302. {
  174303. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  174304. JSAMPARRAY colormap; /* Created colormap */
  174305. int total_colors; /* Number of distinct output colors */
  174306. int i,j,k, nci, blksize, blkdist, ptr, val;
  174307. /* Select number of colors for each component */
  174308. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  174309. /* Report selected color counts */
  174310. if (cinfo->out_color_components == 3)
  174311. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  174312. total_colors, cquantize->Ncolors[0],
  174313. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  174314. else
  174315. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  174316. /* Allocate and fill in the colormap. */
  174317. /* The colors are ordered in the map in standard row-major order, */
  174318. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  174319. colormap = (*cinfo->mem->alloc_sarray)
  174320. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174321. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  174322. /* blksize is number of adjacent repeated entries for a component */
  174323. /* blkdist is distance between groups of identical entries for a component */
  174324. blkdist = total_colors;
  174325. for (i = 0; i < cinfo->out_color_components; i++) {
  174326. /* fill in colormap entries for i'th color component */
  174327. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  174328. blksize = blkdist / nci;
  174329. for (j = 0; j < nci; j++) {
  174330. /* Compute j'th output value (out of nci) for component */
  174331. val = output_value(cinfo, i, j, nci-1);
  174332. /* Fill in all colormap entries that have this value of this component */
  174333. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  174334. /* fill in blksize entries beginning at ptr */
  174335. for (k = 0; k < blksize; k++)
  174336. colormap[i][ptr+k] = (JSAMPLE) val;
  174337. }
  174338. }
  174339. blkdist = blksize; /* blksize of this color is blkdist of next */
  174340. }
  174341. /* Save the colormap in private storage,
  174342. * where it will survive color quantization mode changes.
  174343. */
  174344. cquantize->sv_colormap = colormap;
  174345. cquantize->sv_actual = total_colors;
  174346. }
  174347. /*
  174348. * Create the color index table.
  174349. */
  174350. LOCAL(void)
  174351. create_colorindex (j_decompress_ptr cinfo)
  174352. {
  174353. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  174354. JSAMPROW indexptr;
  174355. int i,j,k, nci, blksize, val, pad;
  174356. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  174357. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  174358. * This is not necessary in the other dithering modes. However, we
  174359. * flag whether it was done in case user changes dithering mode.
  174360. */
  174361. if (cinfo->dither_mode == JDITHER_ORDERED) {
  174362. pad = MAXJSAMPLE*2;
  174363. cquantize->is_padded = TRUE;
  174364. } else {
  174365. pad = 0;
  174366. cquantize->is_padded = FALSE;
  174367. }
  174368. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  174369. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174370. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  174371. (JDIMENSION) cinfo->out_color_components);
  174372. /* blksize is number of adjacent repeated entries for a component */
  174373. blksize = cquantize->sv_actual;
  174374. for (i = 0; i < cinfo->out_color_components; i++) {
  174375. /* fill in colorindex entries for i'th color component */
  174376. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  174377. blksize = blksize / nci;
  174378. /* adjust colorindex pointers to provide padding at negative indexes. */
  174379. if (pad)
  174380. cquantize->colorindex[i] += MAXJSAMPLE;
  174381. /* in loop, val = index of current output value, */
  174382. /* and k = largest j that maps to current val */
  174383. indexptr = cquantize->colorindex[i];
  174384. val = 0;
  174385. k = largest_input_value(cinfo, i, 0, nci-1);
  174386. for (j = 0; j <= MAXJSAMPLE; j++) {
  174387. while (j > k) /* advance val if past boundary */
  174388. k = largest_input_value(cinfo, i, ++val, nci-1);
  174389. /* premultiply so that no multiplication needed in main processing */
  174390. indexptr[j] = (JSAMPLE) (val * blksize);
  174391. }
  174392. /* Pad at both ends if necessary */
  174393. if (pad)
  174394. for (j = 1; j <= MAXJSAMPLE; j++) {
  174395. indexptr[-j] = indexptr[0];
  174396. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  174397. }
  174398. }
  174399. }
  174400. /*
  174401. * Create an ordered-dither array for a component having ncolors
  174402. * distinct output values.
  174403. */
  174404. LOCAL(ODITHER_MATRIX_PTR)
  174405. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  174406. {
  174407. ODITHER_MATRIX_PTR odither;
  174408. int j,k;
  174409. INT32 num,den;
  174410. odither = (ODITHER_MATRIX_PTR)
  174411. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174412. SIZEOF(ODITHER_MATRIX));
  174413. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  174414. * Hence the dither value for the matrix cell with fill order f
  174415. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  174416. * On 16-bit-int machine, be careful to avoid overflow.
  174417. */
  174418. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  174419. for (j = 0; j < ODITHER_SIZE; j++) {
  174420. for (k = 0; k < ODITHER_SIZE; k++) {
  174421. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  174422. * MAXJSAMPLE;
  174423. /* Ensure round towards zero despite C's lack of consistency
  174424. * about rounding negative values in integer division...
  174425. */
  174426. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  174427. }
  174428. }
  174429. return odither;
  174430. }
  174431. /*
  174432. * Create the ordered-dither tables.
  174433. * Components having the same number of representative colors may
  174434. * share a dither table.
  174435. */
  174436. LOCAL(void)
  174437. create_odither_tables (j_decompress_ptr cinfo)
  174438. {
  174439. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  174440. ODITHER_MATRIX_PTR odither;
  174441. int i, j, nci;
  174442. for (i = 0; i < cinfo->out_color_components; i++) {
  174443. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  174444. odither = NULL; /* search for matching prior component */
  174445. for (j = 0; j < i; j++) {
  174446. if (nci == cquantize->Ncolors[j]) {
  174447. odither = cquantize->odither[j];
  174448. break;
  174449. }
  174450. }
  174451. if (odither == NULL) /* need a new table? */
  174452. odither = make_odither_array(cinfo, nci);
  174453. cquantize->odither[i] = odither;
  174454. }
  174455. }
  174456. /*
  174457. * Map some rows of pixels to the output colormapped representation.
  174458. */
  174459. METHODDEF(void)
  174460. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  174461. JSAMPARRAY output_buf, int num_rows)
  174462. /* General case, no dithering */
  174463. {
  174464. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  174465. JSAMPARRAY colorindex = cquantize->colorindex;
  174466. register int pixcode, ci;
  174467. register JSAMPROW ptrin, ptrout;
  174468. int row;
  174469. JDIMENSION col;
  174470. JDIMENSION width = cinfo->output_width;
  174471. register int nc = cinfo->out_color_components;
  174472. for (row = 0; row < num_rows; row++) {
  174473. ptrin = input_buf[row];
  174474. ptrout = output_buf[row];
  174475. for (col = width; col > 0; col--) {
  174476. pixcode = 0;
  174477. for (ci = 0; ci < nc; ci++) {
  174478. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  174479. }
  174480. *ptrout++ = (JSAMPLE) pixcode;
  174481. }
  174482. }
  174483. }
  174484. METHODDEF(void)
  174485. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  174486. JSAMPARRAY output_buf, int num_rows)
  174487. /* Fast path for out_color_components==3, no dithering */
  174488. {
  174489. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  174490. register int pixcode;
  174491. register JSAMPROW ptrin, ptrout;
  174492. JSAMPROW colorindex0 = cquantize->colorindex[0];
  174493. JSAMPROW colorindex1 = cquantize->colorindex[1];
  174494. JSAMPROW colorindex2 = cquantize->colorindex[2];
  174495. int row;
  174496. JDIMENSION col;
  174497. JDIMENSION width = cinfo->output_width;
  174498. for (row = 0; row < num_rows; row++) {
  174499. ptrin = input_buf[row];
  174500. ptrout = output_buf[row];
  174501. for (col = width; col > 0; col--) {
  174502. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  174503. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  174504. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  174505. *ptrout++ = (JSAMPLE) pixcode;
  174506. }
  174507. }
  174508. }
  174509. METHODDEF(void)
  174510. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  174511. JSAMPARRAY output_buf, int num_rows)
  174512. /* General case, with ordered dithering */
  174513. {
  174514. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  174515. register JSAMPROW input_ptr;
  174516. register JSAMPROW output_ptr;
  174517. JSAMPROW colorindex_ci;
  174518. int * dither; /* points to active row of dither matrix */
  174519. int row_index, col_index; /* current indexes into dither matrix */
  174520. int nc = cinfo->out_color_components;
  174521. int ci;
  174522. int row;
  174523. JDIMENSION col;
  174524. JDIMENSION width = cinfo->output_width;
  174525. for (row = 0; row < num_rows; row++) {
  174526. /* Initialize output values to 0 so can process components separately */
  174527. jzero_far((void FAR *) output_buf[row],
  174528. (size_t) (width * SIZEOF(JSAMPLE)));
  174529. row_index = cquantize->row_index;
  174530. for (ci = 0; ci < nc; ci++) {
  174531. input_ptr = input_buf[row] + ci;
  174532. output_ptr = output_buf[row];
  174533. colorindex_ci = cquantize->colorindex[ci];
  174534. dither = cquantize->odither[ci][row_index];
  174535. col_index = 0;
  174536. for (col = width; col > 0; col--) {
  174537. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  174538. * select output value, accumulate into output code for this pixel.
  174539. * Range-limiting need not be done explicitly, as we have extended
  174540. * the colorindex table to produce the right answers for out-of-range
  174541. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  174542. * required amount of padding.
  174543. */
  174544. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  174545. input_ptr += nc;
  174546. output_ptr++;
  174547. col_index = (col_index + 1) & ODITHER_MASK;
  174548. }
  174549. }
  174550. /* Advance row index for next row */
  174551. row_index = (row_index + 1) & ODITHER_MASK;
  174552. cquantize->row_index = row_index;
  174553. }
  174554. }
  174555. METHODDEF(void)
  174556. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  174557. JSAMPARRAY output_buf, int num_rows)
  174558. /* Fast path for out_color_components==3, with ordered dithering */
  174559. {
  174560. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  174561. register int pixcode;
  174562. register JSAMPROW input_ptr;
  174563. register JSAMPROW output_ptr;
  174564. JSAMPROW colorindex0 = cquantize->colorindex[0];
  174565. JSAMPROW colorindex1 = cquantize->colorindex[1];
  174566. JSAMPROW colorindex2 = cquantize->colorindex[2];
  174567. int * dither0; /* points to active row of dither matrix */
  174568. int * dither1;
  174569. int * dither2;
  174570. int row_index, col_index; /* current indexes into dither matrix */
  174571. int row;
  174572. JDIMENSION col;
  174573. JDIMENSION width = cinfo->output_width;
  174574. for (row = 0; row < num_rows; row++) {
  174575. row_index = cquantize->row_index;
  174576. input_ptr = input_buf[row];
  174577. output_ptr = output_buf[row];
  174578. dither0 = cquantize->odither[0][row_index];
  174579. dither1 = cquantize->odither[1][row_index];
  174580. dither2 = cquantize->odither[2][row_index];
  174581. col_index = 0;
  174582. for (col = width; col > 0; col--) {
  174583. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  174584. dither0[col_index]]);
  174585. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  174586. dither1[col_index]]);
  174587. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  174588. dither2[col_index]]);
  174589. *output_ptr++ = (JSAMPLE) pixcode;
  174590. col_index = (col_index + 1) & ODITHER_MASK;
  174591. }
  174592. row_index = (row_index + 1) & ODITHER_MASK;
  174593. cquantize->row_index = row_index;
  174594. }
  174595. }
  174596. METHODDEF(void)
  174597. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  174598. JSAMPARRAY output_buf, int num_rows)
  174599. /* General case, with Floyd-Steinberg dithering */
  174600. {
  174601. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  174602. register LOCFSERROR cur; /* current error or pixel value */
  174603. LOCFSERROR belowerr; /* error for pixel below cur */
  174604. LOCFSERROR bpreverr; /* error for below/prev col */
  174605. LOCFSERROR bnexterr; /* error for below/next col */
  174606. LOCFSERROR delta;
  174607. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  174608. register JSAMPROW input_ptr;
  174609. register JSAMPROW output_ptr;
  174610. JSAMPROW colorindex_ci;
  174611. JSAMPROW colormap_ci;
  174612. int pixcode;
  174613. int nc = cinfo->out_color_components;
  174614. int dir; /* 1 for left-to-right, -1 for right-to-left */
  174615. int dirnc; /* dir * nc */
  174616. int ci;
  174617. int row;
  174618. JDIMENSION col;
  174619. JDIMENSION width = cinfo->output_width;
  174620. JSAMPLE *range_limit = cinfo->sample_range_limit;
  174621. SHIFT_TEMPS
  174622. for (row = 0; row < num_rows; row++) {
  174623. /* Initialize output values to 0 so can process components separately */
  174624. jzero_far((void FAR *) output_buf[row],
  174625. (size_t) (width * SIZEOF(JSAMPLE)));
  174626. for (ci = 0; ci < nc; ci++) {
  174627. input_ptr = input_buf[row] + ci;
  174628. output_ptr = output_buf[row];
  174629. if (cquantize->on_odd_row) {
  174630. /* work right to left in this row */
  174631. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  174632. output_ptr += width-1;
  174633. dir = -1;
  174634. dirnc = -nc;
  174635. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  174636. } else {
  174637. /* work left to right in this row */
  174638. dir = 1;
  174639. dirnc = nc;
  174640. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  174641. }
  174642. colorindex_ci = cquantize->colorindex[ci];
  174643. colormap_ci = cquantize->sv_colormap[ci];
  174644. /* Preset error values: no error propagated to first pixel from left */
  174645. cur = 0;
  174646. /* and no error propagated to row below yet */
  174647. belowerr = bpreverr = 0;
  174648. for (col = width; col > 0; col--) {
  174649. /* cur holds the error propagated from the previous pixel on the
  174650. * current line. Add the error propagated from the previous line
  174651. * to form the complete error correction term for this pixel, and
  174652. * round the error term (which is expressed * 16) to an integer.
  174653. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  174654. * for either sign of the error value.
  174655. * Note: errorptr points to *previous* column's array entry.
  174656. */
  174657. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  174658. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  174659. * The maximum error is +- MAXJSAMPLE; this sets the required size
  174660. * of the range_limit array.
  174661. */
  174662. cur += GETJSAMPLE(*input_ptr);
  174663. cur = GETJSAMPLE(range_limit[cur]);
  174664. /* Select output value, accumulate into output code for this pixel */
  174665. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  174666. *output_ptr += (JSAMPLE) pixcode;
  174667. /* Compute actual representation error at this pixel */
  174668. /* Note: we can do this even though we don't have the final */
  174669. /* pixel code, because the colormap is orthogonal. */
  174670. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  174671. /* Compute error fractions to be propagated to adjacent pixels.
  174672. * Add these into the running sums, and simultaneously shift the
  174673. * next-line error sums left by 1 column.
  174674. */
  174675. bnexterr = cur;
  174676. delta = cur * 2;
  174677. cur += delta; /* form error * 3 */
  174678. errorptr[0] = (FSERROR) (bpreverr + cur);
  174679. cur += delta; /* form error * 5 */
  174680. bpreverr = belowerr + cur;
  174681. belowerr = bnexterr;
  174682. cur += delta; /* form error * 7 */
  174683. /* At this point cur contains the 7/16 error value to be propagated
  174684. * to the next pixel on the current line, and all the errors for the
  174685. * next line have been shifted over. We are therefore ready to move on.
  174686. */
  174687. input_ptr += dirnc; /* advance input ptr to next column */
  174688. output_ptr += dir; /* advance output ptr to next column */
  174689. errorptr += dir; /* advance errorptr to current column */
  174690. }
  174691. /* Post-loop cleanup: we must unload the final error value into the
  174692. * final fserrors[] entry. Note we need not unload belowerr because
  174693. * it is for the dummy column before or after the actual array.
  174694. */
  174695. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  174696. }
  174697. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  174698. }
  174699. }
  174700. /*
  174701. * Allocate workspace for Floyd-Steinberg errors.
  174702. */
  174703. LOCAL(void)
  174704. alloc_fs_workspace (j_decompress_ptr cinfo)
  174705. {
  174706. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  174707. size_t arraysize;
  174708. int i;
  174709. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  174710. for (i = 0; i < cinfo->out_color_components; i++) {
  174711. cquantize->fserrors[i] = (FSERRPTR)
  174712. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  174713. }
  174714. }
  174715. /*
  174716. * Initialize for one-pass color quantization.
  174717. */
  174718. METHODDEF(void)
  174719. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  174720. {
  174721. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  174722. size_t arraysize;
  174723. int i;
  174724. /* Install my colormap. */
  174725. cinfo->colormap = cquantize->sv_colormap;
  174726. cinfo->actual_number_of_colors = cquantize->sv_actual;
  174727. /* Initialize for desired dithering mode. */
  174728. switch (cinfo->dither_mode) {
  174729. case JDITHER_NONE:
  174730. if (cinfo->out_color_components == 3)
  174731. cquantize->pub.color_quantize = color_quantize3;
  174732. else
  174733. cquantize->pub.color_quantize = color_quantize;
  174734. break;
  174735. case JDITHER_ORDERED:
  174736. if (cinfo->out_color_components == 3)
  174737. cquantize->pub.color_quantize = quantize3_ord_dither;
  174738. else
  174739. cquantize->pub.color_quantize = quantize_ord_dither;
  174740. cquantize->row_index = 0; /* initialize state for ordered dither */
  174741. /* If user changed to ordered dither from another mode,
  174742. * we must recreate the color index table with padding.
  174743. * This will cost extra space, but probably isn't very likely.
  174744. */
  174745. if (! cquantize->is_padded)
  174746. create_colorindex(cinfo);
  174747. /* Create ordered-dither tables if we didn't already. */
  174748. if (cquantize->odither[0] == NULL)
  174749. create_odither_tables(cinfo);
  174750. break;
  174751. case JDITHER_FS:
  174752. cquantize->pub.color_quantize = quantize_fs_dither;
  174753. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  174754. /* Allocate Floyd-Steinberg workspace if didn't already. */
  174755. if (cquantize->fserrors[0] == NULL)
  174756. alloc_fs_workspace(cinfo);
  174757. /* Initialize the propagated errors to zero. */
  174758. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  174759. for (i = 0; i < cinfo->out_color_components; i++)
  174760. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  174761. break;
  174762. default:
  174763. ERREXIT(cinfo, JERR_NOT_COMPILED);
  174764. break;
  174765. }
  174766. }
  174767. /*
  174768. * Finish up at the end of the pass.
  174769. */
  174770. METHODDEF(void)
  174771. finish_pass_1_quant (j_decompress_ptr)
  174772. {
  174773. /* no work in 1-pass case */
  174774. }
  174775. /*
  174776. * Switch to a new external colormap between output passes.
  174777. * Shouldn't get to this module!
  174778. */
  174779. METHODDEF(void)
  174780. new_color_map_1_quant (j_decompress_ptr cinfo)
  174781. {
  174782. ERREXIT(cinfo, JERR_MODE_CHANGE);
  174783. }
  174784. /*
  174785. * Module initialization routine for 1-pass color quantization.
  174786. */
  174787. GLOBAL(void)
  174788. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  174789. {
  174790. my_cquantize_ptr cquantize;
  174791. cquantize = (my_cquantize_ptr)
  174792. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174793. SIZEOF(my_cquantizer));
  174794. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  174795. cquantize->pub.start_pass = start_pass_1_quant;
  174796. cquantize->pub.finish_pass = finish_pass_1_quant;
  174797. cquantize->pub.new_color_map = new_color_map_1_quant;
  174798. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  174799. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  174800. /* Make sure my internal arrays won't overflow */
  174801. if (cinfo->out_color_components > MAX_Q_COMPS)
  174802. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  174803. /* Make sure colormap indexes can be represented by JSAMPLEs */
  174804. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  174805. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  174806. /* Create the colormap and color index table. */
  174807. create_colormap(cinfo);
  174808. create_colorindex(cinfo);
  174809. /* Allocate Floyd-Steinberg workspace now if requested.
  174810. * We do this now since it is FAR storage and may affect the memory
  174811. * manager's space calculations. If the user changes to FS dither
  174812. * mode in a later pass, we will allocate the space then, and will
  174813. * possibly overrun the max_memory_to_use setting.
  174814. */
  174815. if (cinfo->dither_mode == JDITHER_FS)
  174816. alloc_fs_workspace(cinfo);
  174817. }
  174818. #endif /* QUANT_1PASS_SUPPORTED */
  174819. /*** End of inlined file: jquant1.c ***/
  174820. /*** Start of inlined file: jquant2.c ***/
  174821. #define JPEG_INTERNALS
  174822. #ifdef QUANT_2PASS_SUPPORTED
  174823. /*
  174824. * This module implements the well-known Heckbert paradigm for color
  174825. * quantization. Most of the ideas used here can be traced back to
  174826. * Heckbert's seminal paper
  174827. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  174828. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  174829. *
  174830. * In the first pass over the image, we accumulate a histogram showing the
  174831. * usage count of each possible color. To keep the histogram to a reasonable
  174832. * size, we reduce the precision of the input; typical practice is to retain
  174833. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  174834. * in the same histogram cell.
  174835. *
  174836. * Next, the color-selection step begins with a box representing the whole
  174837. * color space, and repeatedly splits the "largest" remaining box until we
  174838. * have as many boxes as desired colors. Then the mean color in each
  174839. * remaining box becomes one of the possible output colors.
  174840. *
  174841. * The second pass over the image maps each input pixel to the closest output
  174842. * color (optionally after applying a Floyd-Steinberg dithering correction).
  174843. * This mapping is logically trivial, but making it go fast enough requires
  174844. * considerable care.
  174845. *
  174846. * Heckbert-style quantizers vary a good deal in their policies for choosing
  174847. * the "largest" box and deciding where to cut it. The particular policies
  174848. * used here have proved out well in experimental comparisons, but better ones
  174849. * may yet be found.
  174850. *
  174851. * In earlier versions of the IJG code, this module quantized in YCbCr color
  174852. * space, processing the raw upsampled data without a color conversion step.
  174853. * This allowed the color conversion math to be done only once per colormap
  174854. * entry, not once per pixel. However, that optimization precluded other
  174855. * useful optimizations (such as merging color conversion with upsampling)
  174856. * and it also interfered with desired capabilities such as quantizing to an
  174857. * externally-supplied colormap. We have therefore abandoned that approach.
  174858. * The present code works in the post-conversion color space, typically RGB.
  174859. *
  174860. * To improve the visual quality of the results, we actually work in scaled
  174861. * RGB space, giving G distances more weight than R, and R in turn more than
  174862. * B. To do everything in integer math, we must use integer scale factors.
  174863. * The 2/3/1 scale factors used here correspond loosely to the relative
  174864. * weights of the colors in the NTSC grayscale equation.
  174865. * If you want to use this code to quantize a non-RGB color space, you'll
  174866. * probably need to change these scale factors.
  174867. */
  174868. #define R_SCALE 2 /* scale R distances by this much */
  174869. #define G_SCALE 3 /* scale G distances by this much */
  174870. #define B_SCALE 1 /* and B by this much */
  174871. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  174872. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  174873. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  174874. * you'll get compile errors until you extend this logic. In that case
  174875. * you'll probably want to tweak the histogram sizes too.
  174876. */
  174877. #if RGB_RED == 0
  174878. #define C0_SCALE R_SCALE
  174879. #endif
  174880. #if RGB_BLUE == 0
  174881. #define C0_SCALE B_SCALE
  174882. #endif
  174883. #if RGB_GREEN == 1
  174884. #define C1_SCALE G_SCALE
  174885. #endif
  174886. #if RGB_RED == 2
  174887. #define C2_SCALE R_SCALE
  174888. #endif
  174889. #if RGB_BLUE == 2
  174890. #define C2_SCALE B_SCALE
  174891. #endif
  174892. /*
  174893. * First we have the histogram data structure and routines for creating it.
  174894. *
  174895. * The number of bits of precision can be adjusted by changing these symbols.
  174896. * We recommend keeping 6 bits for G and 5 each for R and B.
  174897. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  174898. * better results; if you are short of memory, 5 bits all around will save
  174899. * some space but degrade the results.
  174900. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  174901. * (preferably unsigned long) for each cell. In practice this is overkill;
  174902. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  174903. * and clamping those that do overflow to the maximum value will give close-
  174904. * enough results. This reduces the recommended histogram size from 256Kb
  174905. * to 128Kb, which is a useful savings on PC-class machines.
  174906. * (In the second pass the histogram space is re-used for pixel mapping data;
  174907. * in that capacity, each cell must be able to store zero to the number of
  174908. * desired colors. 16 bits/cell is plenty for that too.)
  174909. * Since the JPEG code is intended to run in small memory model on 80x86
  174910. * machines, we can't just allocate the histogram in one chunk. Instead
  174911. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  174912. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  174913. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  174914. * on 80x86 machines, the pointer row is in near memory but the actual
  174915. * arrays are in far memory (same arrangement as we use for image arrays).
  174916. */
  174917. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  174918. /* These will do the right thing for either R,G,B or B,G,R color order,
  174919. * but you may not like the results for other color orders.
  174920. */
  174921. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  174922. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  174923. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  174924. /* Number of elements along histogram axes. */
  174925. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  174926. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  174927. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  174928. /* These are the amounts to shift an input value to get a histogram index. */
  174929. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  174930. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  174931. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  174932. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  174933. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  174934. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  174935. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  174936. typedef hist2d * hist3d; /* type for top-level pointer */
  174937. /* Declarations for Floyd-Steinberg dithering.
  174938. *
  174939. * Errors are accumulated into the array fserrors[], at a resolution of
  174940. * 1/16th of a pixel count. The error at a given pixel is propagated
  174941. * to its not-yet-processed neighbors using the standard F-S fractions,
  174942. * ... (here) 7/16
  174943. * 3/16 5/16 1/16
  174944. * We work left-to-right on even rows, right-to-left on odd rows.
  174945. *
  174946. * We can get away with a single array (holding one row's worth of errors)
  174947. * by using it to store the current row's errors at pixel columns not yet
  174948. * processed, but the next row's errors at columns already processed. We
  174949. * need only a few extra variables to hold the errors immediately around the
  174950. * current column. (If we are lucky, those variables are in registers, but
  174951. * even if not, they're probably cheaper to access than array elements are.)
  174952. *
  174953. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  174954. * each end saves us from special-casing the first and last pixels.
  174955. * Each entry is three values long, one value for each color component.
  174956. *
  174957. * Note: on a wide image, we might not have enough room in a PC's near data
  174958. * segment to hold the error array; so it is allocated with alloc_large.
  174959. */
  174960. #if BITS_IN_JSAMPLE == 8
  174961. typedef INT16 FSERROR; /* 16 bits should be enough */
  174962. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  174963. #else
  174964. typedef INT32 FSERROR; /* may need more than 16 bits */
  174965. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  174966. #endif
  174967. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  174968. /* Private subobject */
  174969. typedef struct {
  174970. struct jpeg_color_quantizer pub; /* public fields */
  174971. /* Space for the eventually created colormap is stashed here */
  174972. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  174973. int desired; /* desired # of colors = size of colormap */
  174974. /* Variables for accumulating image statistics */
  174975. hist3d histogram; /* pointer to the histogram */
  174976. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  174977. /* Variables for Floyd-Steinberg dithering */
  174978. FSERRPTR fserrors; /* accumulated errors */
  174979. boolean on_odd_row; /* flag to remember which row we are on */
  174980. int * error_limiter; /* table for clamping the applied error */
  174981. } my_cquantizer2;
  174982. typedef my_cquantizer2 * my_cquantize_ptr2;
  174983. /*
  174984. * Prescan some rows of pixels.
  174985. * In this module the prescan simply updates the histogram, which has been
  174986. * initialized to zeroes by start_pass.
  174987. * An output_buf parameter is required by the method signature, but no data
  174988. * is actually output (in fact the buffer controller is probably passing a
  174989. * NULL pointer).
  174990. */
  174991. METHODDEF(void)
  174992. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  174993. JSAMPARRAY, int num_rows)
  174994. {
  174995. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174996. register JSAMPROW ptr;
  174997. register histptr histp;
  174998. register hist3d histogram = cquantize->histogram;
  174999. int row;
  175000. JDIMENSION col;
  175001. JDIMENSION width = cinfo->output_width;
  175002. for (row = 0; row < num_rows; row++) {
  175003. ptr = input_buf[row];
  175004. for (col = width; col > 0; col--) {
  175005. /* get pixel value and index into the histogram */
  175006. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  175007. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  175008. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  175009. /* increment, check for overflow and undo increment if so. */
  175010. if (++(*histp) <= 0)
  175011. (*histp)--;
  175012. ptr += 3;
  175013. }
  175014. }
  175015. }
  175016. /*
  175017. * Next we have the really interesting routines: selection of a colormap
  175018. * given the completed histogram.
  175019. * These routines work with a list of "boxes", each representing a rectangular
  175020. * subset of the input color space (to histogram precision).
  175021. */
  175022. typedef struct {
  175023. /* The bounds of the box (inclusive); expressed as histogram indexes */
  175024. int c0min, c0max;
  175025. int c1min, c1max;
  175026. int c2min, c2max;
  175027. /* The volume (actually 2-norm) of the box */
  175028. INT32 volume;
  175029. /* The number of nonzero histogram cells within this box */
  175030. long colorcount;
  175031. } box;
  175032. typedef box * boxptr;
  175033. LOCAL(boxptr)
  175034. find_biggest_color_pop (boxptr boxlist, int numboxes)
  175035. /* Find the splittable box with the largest color population */
  175036. /* Returns NULL if no splittable boxes remain */
  175037. {
  175038. register boxptr boxp;
  175039. register int i;
  175040. register long maxc = 0;
  175041. boxptr which = NULL;
  175042. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  175043. if (boxp->colorcount > maxc && boxp->volume > 0) {
  175044. which = boxp;
  175045. maxc = boxp->colorcount;
  175046. }
  175047. }
  175048. return which;
  175049. }
  175050. LOCAL(boxptr)
  175051. find_biggest_volume (boxptr boxlist, int numboxes)
  175052. /* Find the splittable box with the largest (scaled) volume */
  175053. /* Returns NULL if no splittable boxes remain */
  175054. {
  175055. register boxptr boxp;
  175056. register int i;
  175057. register INT32 maxv = 0;
  175058. boxptr which = NULL;
  175059. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  175060. if (boxp->volume > maxv) {
  175061. which = boxp;
  175062. maxv = boxp->volume;
  175063. }
  175064. }
  175065. return which;
  175066. }
  175067. LOCAL(void)
  175068. update_box (j_decompress_ptr cinfo, boxptr boxp)
  175069. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  175070. /* and recompute its volume and population */
  175071. {
  175072. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  175073. hist3d histogram = cquantize->histogram;
  175074. histptr histp;
  175075. int c0,c1,c2;
  175076. int c0min,c0max,c1min,c1max,c2min,c2max;
  175077. INT32 dist0,dist1,dist2;
  175078. long ccount;
  175079. c0min = boxp->c0min; c0max = boxp->c0max;
  175080. c1min = boxp->c1min; c1max = boxp->c1max;
  175081. c2min = boxp->c2min; c2max = boxp->c2max;
  175082. if (c0max > c0min)
  175083. for (c0 = c0min; c0 <= c0max; c0++)
  175084. for (c1 = c1min; c1 <= c1max; c1++) {
  175085. histp = & histogram[c0][c1][c2min];
  175086. for (c2 = c2min; c2 <= c2max; c2++)
  175087. if (*histp++ != 0) {
  175088. boxp->c0min = c0min = c0;
  175089. goto have_c0min;
  175090. }
  175091. }
  175092. have_c0min:
  175093. if (c0max > c0min)
  175094. for (c0 = c0max; c0 >= c0min; c0--)
  175095. for (c1 = c1min; c1 <= c1max; c1++) {
  175096. histp = & histogram[c0][c1][c2min];
  175097. for (c2 = c2min; c2 <= c2max; c2++)
  175098. if (*histp++ != 0) {
  175099. boxp->c0max = c0max = c0;
  175100. goto have_c0max;
  175101. }
  175102. }
  175103. have_c0max:
  175104. if (c1max > c1min)
  175105. for (c1 = c1min; c1 <= c1max; c1++)
  175106. for (c0 = c0min; c0 <= c0max; c0++) {
  175107. histp = & histogram[c0][c1][c2min];
  175108. for (c2 = c2min; c2 <= c2max; c2++)
  175109. if (*histp++ != 0) {
  175110. boxp->c1min = c1min = c1;
  175111. goto have_c1min;
  175112. }
  175113. }
  175114. have_c1min:
  175115. if (c1max > c1min)
  175116. for (c1 = c1max; c1 >= c1min; c1--)
  175117. for (c0 = c0min; c0 <= c0max; c0++) {
  175118. histp = & histogram[c0][c1][c2min];
  175119. for (c2 = c2min; c2 <= c2max; c2++)
  175120. if (*histp++ != 0) {
  175121. boxp->c1max = c1max = c1;
  175122. goto have_c1max;
  175123. }
  175124. }
  175125. have_c1max:
  175126. if (c2max > c2min)
  175127. for (c2 = c2min; c2 <= c2max; c2++)
  175128. for (c0 = c0min; c0 <= c0max; c0++) {
  175129. histp = & histogram[c0][c1min][c2];
  175130. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  175131. if (*histp != 0) {
  175132. boxp->c2min = c2min = c2;
  175133. goto have_c2min;
  175134. }
  175135. }
  175136. have_c2min:
  175137. if (c2max > c2min)
  175138. for (c2 = c2max; c2 >= c2min; c2--)
  175139. for (c0 = c0min; c0 <= c0max; c0++) {
  175140. histp = & histogram[c0][c1min][c2];
  175141. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  175142. if (*histp != 0) {
  175143. boxp->c2max = c2max = c2;
  175144. goto have_c2max;
  175145. }
  175146. }
  175147. have_c2max:
  175148. /* Update box volume.
  175149. * We use 2-norm rather than real volume here; this biases the method
  175150. * against making long narrow boxes, and it has the side benefit that
  175151. * a box is splittable iff norm > 0.
  175152. * Since the differences are expressed in histogram-cell units,
  175153. * we have to shift back to JSAMPLE units to get consistent distances;
  175154. * after which, we scale according to the selected distance scale factors.
  175155. */
  175156. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  175157. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  175158. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  175159. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  175160. /* Now scan remaining volume of box and compute population */
  175161. ccount = 0;
  175162. for (c0 = c0min; c0 <= c0max; c0++)
  175163. for (c1 = c1min; c1 <= c1max; c1++) {
  175164. histp = & histogram[c0][c1][c2min];
  175165. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  175166. if (*histp != 0) {
  175167. ccount++;
  175168. }
  175169. }
  175170. boxp->colorcount = ccount;
  175171. }
  175172. LOCAL(int)
  175173. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  175174. int desired_colors)
  175175. /* Repeatedly select and split the largest box until we have enough boxes */
  175176. {
  175177. int n,lb;
  175178. int c0,c1,c2,cmax;
  175179. register boxptr b1,b2;
  175180. while (numboxes < desired_colors) {
  175181. /* Select box to split.
  175182. * Current algorithm: by population for first half, then by volume.
  175183. */
  175184. if (numboxes*2 <= desired_colors) {
  175185. b1 = find_biggest_color_pop(boxlist, numboxes);
  175186. } else {
  175187. b1 = find_biggest_volume(boxlist, numboxes);
  175188. }
  175189. if (b1 == NULL) /* no splittable boxes left! */
  175190. break;
  175191. b2 = &boxlist[numboxes]; /* where new box will go */
  175192. /* Copy the color bounds to the new box. */
  175193. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  175194. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  175195. /* Choose which axis to split the box on.
  175196. * Current algorithm: longest scaled axis.
  175197. * See notes in update_box about scaling distances.
  175198. */
  175199. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  175200. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  175201. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  175202. /* We want to break any ties in favor of green, then red, blue last.
  175203. * This code does the right thing for R,G,B or B,G,R color orders only.
  175204. */
  175205. #if RGB_RED == 0
  175206. cmax = c1; n = 1;
  175207. if (c0 > cmax) { cmax = c0; n = 0; }
  175208. if (c2 > cmax) { n = 2; }
  175209. #else
  175210. cmax = c1; n = 1;
  175211. if (c2 > cmax) { cmax = c2; n = 2; }
  175212. if (c0 > cmax) { n = 0; }
  175213. #endif
  175214. /* Choose split point along selected axis, and update box bounds.
  175215. * Current algorithm: split at halfway point.
  175216. * (Since the box has been shrunk to minimum volume,
  175217. * any split will produce two nonempty subboxes.)
  175218. * Note that lb value is max for lower box, so must be < old max.
  175219. */
  175220. switch (n) {
  175221. case 0:
  175222. lb = (b1->c0max + b1->c0min) / 2;
  175223. b1->c0max = lb;
  175224. b2->c0min = lb+1;
  175225. break;
  175226. case 1:
  175227. lb = (b1->c1max + b1->c1min) / 2;
  175228. b1->c1max = lb;
  175229. b2->c1min = lb+1;
  175230. break;
  175231. case 2:
  175232. lb = (b1->c2max + b1->c2min) / 2;
  175233. b1->c2max = lb;
  175234. b2->c2min = lb+1;
  175235. break;
  175236. }
  175237. /* Update stats for boxes */
  175238. update_box(cinfo, b1);
  175239. update_box(cinfo, b2);
  175240. numboxes++;
  175241. }
  175242. return numboxes;
  175243. }
  175244. LOCAL(void)
  175245. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  175246. /* Compute representative color for a box, put it in colormap[icolor] */
  175247. {
  175248. /* Current algorithm: mean weighted by pixels (not colors) */
  175249. /* Note it is important to get the rounding correct! */
  175250. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  175251. hist3d histogram = cquantize->histogram;
  175252. histptr histp;
  175253. int c0,c1,c2;
  175254. int c0min,c0max,c1min,c1max,c2min,c2max;
  175255. long count;
  175256. long total = 0;
  175257. long c0total = 0;
  175258. long c1total = 0;
  175259. long c2total = 0;
  175260. c0min = boxp->c0min; c0max = boxp->c0max;
  175261. c1min = boxp->c1min; c1max = boxp->c1max;
  175262. c2min = boxp->c2min; c2max = boxp->c2max;
  175263. for (c0 = c0min; c0 <= c0max; c0++)
  175264. for (c1 = c1min; c1 <= c1max; c1++) {
  175265. histp = & histogram[c0][c1][c2min];
  175266. for (c2 = c2min; c2 <= c2max; c2++) {
  175267. if ((count = *histp++) != 0) {
  175268. total += count;
  175269. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  175270. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  175271. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  175272. }
  175273. }
  175274. }
  175275. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  175276. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  175277. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  175278. }
  175279. LOCAL(void)
  175280. select_colors (j_decompress_ptr cinfo, int desired_colors)
  175281. /* Master routine for color selection */
  175282. {
  175283. boxptr boxlist;
  175284. int numboxes;
  175285. int i;
  175286. /* Allocate workspace for box list */
  175287. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  175288. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  175289. /* Initialize one box containing whole space */
  175290. numboxes = 1;
  175291. boxlist[0].c0min = 0;
  175292. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  175293. boxlist[0].c1min = 0;
  175294. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  175295. boxlist[0].c2min = 0;
  175296. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  175297. /* Shrink it to actually-used volume and set its statistics */
  175298. update_box(cinfo, & boxlist[0]);
  175299. /* Perform median-cut to produce final box list */
  175300. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  175301. /* Compute the representative color for each box, fill colormap */
  175302. for (i = 0; i < numboxes; i++)
  175303. compute_color(cinfo, & boxlist[i], i);
  175304. cinfo->actual_number_of_colors = numboxes;
  175305. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  175306. }
  175307. /*
  175308. * These routines are concerned with the time-critical task of mapping input
  175309. * colors to the nearest color in the selected colormap.
  175310. *
  175311. * We re-use the histogram space as an "inverse color map", essentially a
  175312. * cache for the results of nearest-color searches. All colors within a
  175313. * histogram cell will be mapped to the same colormap entry, namely the one
  175314. * closest to the cell's center. This may not be quite the closest entry to
  175315. * the actual input color, but it's almost as good. A zero in the cache
  175316. * indicates we haven't found the nearest color for that cell yet; the array
  175317. * is cleared to zeroes before starting the mapping pass. When we find the
  175318. * nearest color for a cell, its colormap index plus one is recorded in the
  175319. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  175320. * when they need to use an unfilled entry in the cache.
  175321. *
  175322. * Our method of efficiently finding nearest colors is based on the "locally
  175323. * sorted search" idea described by Heckbert and on the incremental distance
  175324. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  175325. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  175326. * the distances from a given colormap entry to each cell of the histogram can
  175327. * be computed quickly using an incremental method: the differences between
  175328. * distances to adjacent cells themselves differ by a constant. This allows a
  175329. * fairly fast implementation of the "brute force" approach of computing the
  175330. * distance from every colormap entry to every histogram cell. Unfortunately,
  175331. * it needs a work array to hold the best-distance-so-far for each histogram
  175332. * cell (because the inner loop has to be over cells, not colormap entries).
  175333. * The work array elements have to be INT32s, so the work array would need
  175334. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  175335. *
  175336. * To get around these problems, we apply Thomas' method to compute the
  175337. * nearest colors for only the cells within a small subbox of the histogram.
  175338. * The work array need be only as big as the subbox, so the memory usage
  175339. * problem is solved. Furthermore, we need not fill subboxes that are never
  175340. * referenced in pass2; many images use only part of the color gamut, so a
  175341. * fair amount of work is saved. An additional advantage of this
  175342. * approach is that we can apply Heckbert's locality criterion to quickly
  175343. * eliminate colormap entries that are far away from the subbox; typically
  175344. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  175345. * and we need not compute their distances to individual cells in the subbox.
  175346. * The speed of this approach is heavily influenced by the subbox size: too
  175347. * small means too much overhead, too big loses because Heckbert's criterion
  175348. * can't eliminate as many colormap entries. Empirically the best subbox
  175349. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  175350. *
  175351. * Thomas' article also describes a refined method which is asymptotically
  175352. * faster than the brute-force method, but it is also far more complex and
  175353. * cannot efficiently be applied to small subboxes. It is therefore not
  175354. * useful for programs intended to be portable to DOS machines. On machines
  175355. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  175356. * refined method might be faster than the present code --- but then again,
  175357. * it might not be any faster, and it's certainly more complicated.
  175358. */
  175359. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  175360. #define BOX_C0_LOG (HIST_C0_BITS-3)
  175361. #define BOX_C1_LOG (HIST_C1_BITS-3)
  175362. #define BOX_C2_LOG (HIST_C2_BITS-3)
  175363. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  175364. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  175365. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  175366. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  175367. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  175368. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  175369. /*
  175370. * The next three routines implement inverse colormap filling. They could
  175371. * all be folded into one big routine, but splitting them up this way saves
  175372. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  175373. * and may allow some compilers to produce better code by registerizing more
  175374. * inner-loop variables.
  175375. */
  175376. LOCAL(int)
  175377. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  175378. JSAMPLE colorlist[])
  175379. /* Locate the colormap entries close enough to an update box to be candidates
  175380. * for the nearest entry to some cell(s) in the update box. The update box
  175381. * is specified by the center coordinates of its first cell. The number of
  175382. * candidate colormap entries is returned, and their colormap indexes are
  175383. * placed in colorlist[].
  175384. * This routine uses Heckbert's "locally sorted search" criterion to select
  175385. * the colors that need further consideration.
  175386. */
  175387. {
  175388. int numcolors = cinfo->actual_number_of_colors;
  175389. int maxc0, maxc1, maxc2;
  175390. int centerc0, centerc1, centerc2;
  175391. int i, x, ncolors;
  175392. INT32 minmaxdist, min_dist, max_dist, tdist;
  175393. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  175394. /* Compute true coordinates of update box's upper corner and center.
  175395. * Actually we compute the coordinates of the center of the upper-corner
  175396. * histogram cell, which are the upper bounds of the volume we care about.
  175397. * Note that since ">>" rounds down, the "center" values may be closer to
  175398. * min than to max; hence comparisons to them must be "<=", not "<".
  175399. */
  175400. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  175401. centerc0 = (minc0 + maxc0) >> 1;
  175402. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  175403. centerc1 = (minc1 + maxc1) >> 1;
  175404. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  175405. centerc2 = (minc2 + maxc2) >> 1;
  175406. /* For each color in colormap, find:
  175407. * 1. its minimum squared-distance to any point in the update box
  175408. * (zero if color is within update box);
  175409. * 2. its maximum squared-distance to any point in the update box.
  175410. * Both of these can be found by considering only the corners of the box.
  175411. * We save the minimum distance for each color in mindist[];
  175412. * only the smallest maximum distance is of interest.
  175413. */
  175414. minmaxdist = 0x7FFFFFFFL;
  175415. for (i = 0; i < numcolors; i++) {
  175416. /* We compute the squared-c0-distance term, then add in the other two. */
  175417. x = GETJSAMPLE(cinfo->colormap[0][i]);
  175418. if (x < minc0) {
  175419. tdist = (x - minc0) * C0_SCALE;
  175420. min_dist = tdist*tdist;
  175421. tdist = (x - maxc0) * C0_SCALE;
  175422. max_dist = tdist*tdist;
  175423. } else if (x > maxc0) {
  175424. tdist = (x - maxc0) * C0_SCALE;
  175425. min_dist = tdist*tdist;
  175426. tdist = (x - minc0) * C0_SCALE;
  175427. max_dist = tdist*tdist;
  175428. } else {
  175429. /* within cell range so no contribution to min_dist */
  175430. min_dist = 0;
  175431. if (x <= centerc0) {
  175432. tdist = (x - maxc0) * C0_SCALE;
  175433. max_dist = tdist*tdist;
  175434. } else {
  175435. tdist = (x - minc0) * C0_SCALE;
  175436. max_dist = tdist*tdist;
  175437. }
  175438. }
  175439. x = GETJSAMPLE(cinfo->colormap[1][i]);
  175440. if (x < minc1) {
  175441. tdist = (x - minc1) * C1_SCALE;
  175442. min_dist += tdist*tdist;
  175443. tdist = (x - maxc1) * C1_SCALE;
  175444. max_dist += tdist*tdist;
  175445. } else if (x > maxc1) {
  175446. tdist = (x - maxc1) * C1_SCALE;
  175447. min_dist += tdist*tdist;
  175448. tdist = (x - minc1) * C1_SCALE;
  175449. max_dist += tdist*tdist;
  175450. } else {
  175451. /* within cell range so no contribution to min_dist */
  175452. if (x <= centerc1) {
  175453. tdist = (x - maxc1) * C1_SCALE;
  175454. max_dist += tdist*tdist;
  175455. } else {
  175456. tdist = (x - minc1) * C1_SCALE;
  175457. max_dist += tdist*tdist;
  175458. }
  175459. }
  175460. x = GETJSAMPLE(cinfo->colormap[2][i]);
  175461. if (x < minc2) {
  175462. tdist = (x - minc2) * C2_SCALE;
  175463. min_dist += tdist*tdist;
  175464. tdist = (x - maxc2) * C2_SCALE;
  175465. max_dist += tdist*tdist;
  175466. } else if (x > maxc2) {
  175467. tdist = (x - maxc2) * C2_SCALE;
  175468. min_dist += tdist*tdist;
  175469. tdist = (x - minc2) * C2_SCALE;
  175470. max_dist += tdist*tdist;
  175471. } else {
  175472. /* within cell range so no contribution to min_dist */
  175473. if (x <= centerc2) {
  175474. tdist = (x - maxc2) * C2_SCALE;
  175475. max_dist += tdist*tdist;
  175476. } else {
  175477. tdist = (x - minc2) * C2_SCALE;
  175478. max_dist += tdist*tdist;
  175479. }
  175480. }
  175481. mindist[i] = min_dist; /* save away the results */
  175482. if (max_dist < minmaxdist)
  175483. minmaxdist = max_dist;
  175484. }
  175485. /* Now we know that no cell in the update box is more than minmaxdist
  175486. * away from some colormap entry. Therefore, only colors that are
  175487. * within minmaxdist of some part of the box need be considered.
  175488. */
  175489. ncolors = 0;
  175490. for (i = 0; i < numcolors; i++) {
  175491. if (mindist[i] <= minmaxdist)
  175492. colorlist[ncolors++] = (JSAMPLE) i;
  175493. }
  175494. return ncolors;
  175495. }
  175496. LOCAL(void)
  175497. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  175498. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  175499. /* Find the closest colormap entry for each cell in the update box,
  175500. * given the list of candidate colors prepared by find_nearby_colors.
  175501. * Return the indexes of the closest entries in the bestcolor[] array.
  175502. * This routine uses Thomas' incremental distance calculation method to
  175503. * find the distance from a colormap entry to successive cells in the box.
  175504. */
  175505. {
  175506. int ic0, ic1, ic2;
  175507. int i, icolor;
  175508. register INT32 * bptr; /* pointer into bestdist[] array */
  175509. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  175510. INT32 dist0, dist1; /* initial distance values */
  175511. register INT32 dist2; /* current distance in inner loop */
  175512. INT32 xx0, xx1; /* distance increments */
  175513. register INT32 xx2;
  175514. INT32 inc0, inc1, inc2; /* initial values for increments */
  175515. /* This array holds the distance to the nearest-so-far color for each cell */
  175516. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  175517. /* Initialize best-distance for each cell of the update box */
  175518. bptr = bestdist;
  175519. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  175520. *bptr++ = 0x7FFFFFFFL;
  175521. /* For each color selected by find_nearby_colors,
  175522. * compute its distance to the center of each cell in the box.
  175523. * If that's less than best-so-far, update best distance and color number.
  175524. */
  175525. /* Nominal steps between cell centers ("x" in Thomas article) */
  175526. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  175527. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  175528. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  175529. for (i = 0; i < numcolors; i++) {
  175530. icolor = GETJSAMPLE(colorlist[i]);
  175531. /* Compute (square of) distance from minc0/c1/c2 to this color */
  175532. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  175533. dist0 = inc0*inc0;
  175534. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  175535. dist0 += inc1*inc1;
  175536. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  175537. dist0 += inc2*inc2;
  175538. /* Form the initial difference increments */
  175539. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  175540. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  175541. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  175542. /* Now loop over all cells in box, updating distance per Thomas method */
  175543. bptr = bestdist;
  175544. cptr = bestcolor;
  175545. xx0 = inc0;
  175546. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  175547. dist1 = dist0;
  175548. xx1 = inc1;
  175549. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  175550. dist2 = dist1;
  175551. xx2 = inc2;
  175552. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  175553. if (dist2 < *bptr) {
  175554. *bptr = dist2;
  175555. *cptr = (JSAMPLE) icolor;
  175556. }
  175557. dist2 += xx2;
  175558. xx2 += 2 * STEP_C2 * STEP_C2;
  175559. bptr++;
  175560. cptr++;
  175561. }
  175562. dist1 += xx1;
  175563. xx1 += 2 * STEP_C1 * STEP_C1;
  175564. }
  175565. dist0 += xx0;
  175566. xx0 += 2 * STEP_C0 * STEP_C0;
  175567. }
  175568. }
  175569. }
  175570. LOCAL(void)
  175571. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  175572. /* Fill the inverse-colormap entries in the update box that contains */
  175573. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  175574. /* we can fill as many others as we wish.) */
  175575. {
  175576. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  175577. hist3d histogram = cquantize->histogram;
  175578. int minc0, minc1, minc2; /* lower left corner of update box */
  175579. int ic0, ic1, ic2;
  175580. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  175581. register histptr cachep; /* pointer into main cache array */
  175582. /* This array lists the candidate colormap indexes. */
  175583. JSAMPLE colorlist[MAXNUMCOLORS];
  175584. int numcolors; /* number of candidate colors */
  175585. /* This array holds the actually closest colormap index for each cell. */
  175586. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  175587. /* Convert cell coordinates to update box ID */
  175588. c0 >>= BOX_C0_LOG;
  175589. c1 >>= BOX_C1_LOG;
  175590. c2 >>= BOX_C2_LOG;
  175591. /* Compute true coordinates of update box's origin corner.
  175592. * Actually we compute the coordinates of the center of the corner
  175593. * histogram cell, which are the lower bounds of the volume we care about.
  175594. */
  175595. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  175596. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  175597. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  175598. /* Determine which colormap entries are close enough to be candidates
  175599. * for the nearest entry to some cell in the update box.
  175600. */
  175601. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  175602. /* Determine the actually nearest colors. */
  175603. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  175604. bestcolor);
  175605. /* Save the best color numbers (plus 1) in the main cache array */
  175606. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  175607. c1 <<= BOX_C1_LOG;
  175608. c2 <<= BOX_C2_LOG;
  175609. cptr = bestcolor;
  175610. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  175611. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  175612. cachep = & histogram[c0+ic0][c1+ic1][c2];
  175613. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  175614. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  175615. }
  175616. }
  175617. }
  175618. }
  175619. /*
  175620. * Map some rows of pixels to the output colormapped representation.
  175621. */
  175622. METHODDEF(void)
  175623. pass2_no_dither (j_decompress_ptr cinfo,
  175624. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  175625. /* This version performs no dithering */
  175626. {
  175627. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  175628. hist3d histogram = cquantize->histogram;
  175629. register JSAMPROW inptr, outptr;
  175630. register histptr cachep;
  175631. register int c0, c1, c2;
  175632. int row;
  175633. JDIMENSION col;
  175634. JDIMENSION width = cinfo->output_width;
  175635. for (row = 0; row < num_rows; row++) {
  175636. inptr = input_buf[row];
  175637. outptr = output_buf[row];
  175638. for (col = width; col > 0; col--) {
  175639. /* get pixel value and index into the cache */
  175640. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  175641. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  175642. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  175643. cachep = & histogram[c0][c1][c2];
  175644. /* If we have not seen this color before, find nearest colormap entry */
  175645. /* and update the cache */
  175646. if (*cachep == 0)
  175647. fill_inverse_cmap(cinfo, c0,c1,c2);
  175648. /* Now emit the colormap index for this cell */
  175649. *outptr++ = (JSAMPLE) (*cachep - 1);
  175650. }
  175651. }
  175652. }
  175653. METHODDEF(void)
  175654. pass2_fs_dither (j_decompress_ptr cinfo,
  175655. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  175656. /* This version performs Floyd-Steinberg dithering */
  175657. {
  175658. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  175659. hist3d histogram = cquantize->histogram;
  175660. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  175661. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  175662. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  175663. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  175664. JSAMPROW inptr; /* => current input pixel */
  175665. JSAMPROW outptr; /* => current output pixel */
  175666. histptr cachep;
  175667. int dir; /* +1 or -1 depending on direction */
  175668. int dir3; /* 3*dir, for advancing inptr & errorptr */
  175669. int row;
  175670. JDIMENSION col;
  175671. JDIMENSION width = cinfo->output_width;
  175672. JSAMPLE *range_limit = cinfo->sample_range_limit;
  175673. int *error_limit = cquantize->error_limiter;
  175674. JSAMPROW colormap0 = cinfo->colormap[0];
  175675. JSAMPROW colormap1 = cinfo->colormap[1];
  175676. JSAMPROW colormap2 = cinfo->colormap[2];
  175677. SHIFT_TEMPS
  175678. for (row = 0; row < num_rows; row++) {
  175679. inptr = input_buf[row];
  175680. outptr = output_buf[row];
  175681. if (cquantize->on_odd_row) {
  175682. /* work right to left in this row */
  175683. inptr += (width-1) * 3; /* so point to rightmost pixel */
  175684. outptr += width-1;
  175685. dir = -1;
  175686. dir3 = -3;
  175687. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  175688. cquantize->on_odd_row = FALSE; /* flip for next time */
  175689. } else {
  175690. /* work left to right in this row */
  175691. dir = 1;
  175692. dir3 = 3;
  175693. errorptr = cquantize->fserrors; /* => entry before first real column */
  175694. cquantize->on_odd_row = TRUE; /* flip for next time */
  175695. }
  175696. /* Preset error values: no error propagated to first pixel from left */
  175697. cur0 = cur1 = cur2 = 0;
  175698. /* and no error propagated to row below yet */
  175699. belowerr0 = belowerr1 = belowerr2 = 0;
  175700. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  175701. for (col = width; col > 0; col--) {
  175702. /* curN holds the error propagated from the previous pixel on the
  175703. * current line. Add the error propagated from the previous line
  175704. * to form the complete error correction term for this pixel, and
  175705. * round the error term (which is expressed * 16) to an integer.
  175706. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  175707. * for either sign of the error value.
  175708. * Note: errorptr points to *previous* column's array entry.
  175709. */
  175710. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  175711. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  175712. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  175713. /* Limit the error using transfer function set by init_error_limit.
  175714. * See comments with init_error_limit for rationale.
  175715. */
  175716. cur0 = error_limit[cur0];
  175717. cur1 = error_limit[cur1];
  175718. cur2 = error_limit[cur2];
  175719. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  175720. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  175721. * this sets the required size of the range_limit array.
  175722. */
  175723. cur0 += GETJSAMPLE(inptr[0]);
  175724. cur1 += GETJSAMPLE(inptr[1]);
  175725. cur2 += GETJSAMPLE(inptr[2]);
  175726. cur0 = GETJSAMPLE(range_limit[cur0]);
  175727. cur1 = GETJSAMPLE(range_limit[cur1]);
  175728. cur2 = GETJSAMPLE(range_limit[cur2]);
  175729. /* Index into the cache with adjusted pixel value */
  175730. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  175731. /* If we have not seen this color before, find nearest colormap */
  175732. /* entry and update the cache */
  175733. if (*cachep == 0)
  175734. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  175735. /* Now emit the colormap index for this cell */
  175736. { register int pixcode = *cachep - 1;
  175737. *outptr = (JSAMPLE) pixcode;
  175738. /* Compute representation error for this pixel */
  175739. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  175740. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  175741. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  175742. }
  175743. /* Compute error fractions to be propagated to adjacent pixels.
  175744. * Add these into the running sums, and simultaneously shift the
  175745. * next-line error sums left by 1 column.
  175746. */
  175747. { register LOCFSERROR bnexterr, delta;
  175748. bnexterr = cur0; /* Process component 0 */
  175749. delta = cur0 * 2;
  175750. cur0 += delta; /* form error * 3 */
  175751. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  175752. cur0 += delta; /* form error * 5 */
  175753. bpreverr0 = belowerr0 + cur0;
  175754. belowerr0 = bnexterr;
  175755. cur0 += delta; /* form error * 7 */
  175756. bnexterr = cur1; /* Process component 1 */
  175757. delta = cur1 * 2;
  175758. cur1 += delta; /* form error * 3 */
  175759. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  175760. cur1 += delta; /* form error * 5 */
  175761. bpreverr1 = belowerr1 + cur1;
  175762. belowerr1 = bnexterr;
  175763. cur1 += delta; /* form error * 7 */
  175764. bnexterr = cur2; /* Process component 2 */
  175765. delta = cur2 * 2;
  175766. cur2 += delta; /* form error * 3 */
  175767. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  175768. cur2 += delta; /* form error * 5 */
  175769. bpreverr2 = belowerr2 + cur2;
  175770. belowerr2 = bnexterr;
  175771. cur2 += delta; /* form error * 7 */
  175772. }
  175773. /* At this point curN contains the 7/16 error value to be propagated
  175774. * to the next pixel on the current line, and all the errors for the
  175775. * next line have been shifted over. We are therefore ready to move on.
  175776. */
  175777. inptr += dir3; /* Advance pixel pointers to next column */
  175778. outptr += dir;
  175779. errorptr += dir3; /* advance errorptr to current column */
  175780. }
  175781. /* Post-loop cleanup: we must unload the final error values into the
  175782. * final fserrors[] entry. Note we need not unload belowerrN because
  175783. * it is for the dummy column before or after the actual array.
  175784. */
  175785. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  175786. errorptr[1] = (FSERROR) bpreverr1;
  175787. errorptr[2] = (FSERROR) bpreverr2;
  175788. }
  175789. }
  175790. /*
  175791. * Initialize the error-limiting transfer function (lookup table).
  175792. * The raw F-S error computation can potentially compute error values of up to
  175793. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  175794. * much less, otherwise obviously wrong pixels will be created. (Typical
  175795. * effects include weird fringes at color-area boundaries, isolated bright
  175796. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  175797. * is to ensure that the "corners" of the color cube are allocated as output
  175798. * colors; then repeated errors in the same direction cannot cause cascading
  175799. * error buildup. However, that only prevents the error from getting
  175800. * completely out of hand; Aaron Giles reports that error limiting improves
  175801. * the results even with corner colors allocated.
  175802. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  175803. * well, but the smoother transfer function used below is even better. Thanks
  175804. * to Aaron Giles for this idea.
  175805. */
  175806. LOCAL(void)
  175807. init_error_limit (j_decompress_ptr cinfo)
  175808. /* Allocate and fill in the error_limiter table */
  175809. {
  175810. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  175811. int * table;
  175812. int in, out;
  175813. table = (int *) (*cinfo->mem->alloc_small)
  175814. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  175815. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  175816. cquantize->error_limiter = table;
  175817. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  175818. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  175819. out = 0;
  175820. for (in = 0; in < STEPSIZE; in++, out++) {
  175821. table[in] = out; table[-in] = -out;
  175822. }
  175823. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  175824. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  175825. table[in] = out; table[-in] = -out;
  175826. }
  175827. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  175828. for (; in <= MAXJSAMPLE; in++) {
  175829. table[in] = out; table[-in] = -out;
  175830. }
  175831. #undef STEPSIZE
  175832. }
  175833. /*
  175834. * Finish up at the end of each pass.
  175835. */
  175836. METHODDEF(void)
  175837. finish_pass1 (j_decompress_ptr cinfo)
  175838. {
  175839. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  175840. /* Select the representative colors and fill in cinfo->colormap */
  175841. cinfo->colormap = cquantize->sv_colormap;
  175842. select_colors(cinfo, cquantize->desired);
  175843. /* Force next pass to zero the color index table */
  175844. cquantize->needs_zeroed = TRUE;
  175845. }
  175846. METHODDEF(void)
  175847. finish_pass2 (j_decompress_ptr)
  175848. {
  175849. /* no work */
  175850. }
  175851. /*
  175852. * Initialize for each processing pass.
  175853. */
  175854. METHODDEF(void)
  175855. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  175856. {
  175857. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  175858. hist3d histogram = cquantize->histogram;
  175859. int i;
  175860. /* Only F-S dithering or no dithering is supported. */
  175861. /* If user asks for ordered dither, give him F-S. */
  175862. if (cinfo->dither_mode != JDITHER_NONE)
  175863. cinfo->dither_mode = JDITHER_FS;
  175864. if (is_pre_scan) {
  175865. /* Set up method pointers */
  175866. cquantize->pub.color_quantize = prescan_quantize;
  175867. cquantize->pub.finish_pass = finish_pass1;
  175868. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  175869. } else {
  175870. /* Set up method pointers */
  175871. if (cinfo->dither_mode == JDITHER_FS)
  175872. cquantize->pub.color_quantize = pass2_fs_dither;
  175873. else
  175874. cquantize->pub.color_quantize = pass2_no_dither;
  175875. cquantize->pub.finish_pass = finish_pass2;
  175876. /* Make sure color count is acceptable */
  175877. i = cinfo->actual_number_of_colors;
  175878. if (i < 1)
  175879. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  175880. if (i > MAXNUMCOLORS)
  175881. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  175882. if (cinfo->dither_mode == JDITHER_FS) {
  175883. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  175884. (3 * SIZEOF(FSERROR)));
  175885. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  175886. if (cquantize->fserrors == NULL)
  175887. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  175888. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  175889. /* Initialize the propagated errors to zero. */
  175890. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  175891. /* Make the error-limit table if we didn't already. */
  175892. if (cquantize->error_limiter == NULL)
  175893. init_error_limit(cinfo);
  175894. cquantize->on_odd_row = FALSE;
  175895. }
  175896. }
  175897. /* Zero the histogram or inverse color map, if necessary */
  175898. if (cquantize->needs_zeroed) {
  175899. for (i = 0; i < HIST_C0_ELEMS; i++) {
  175900. jzero_far((void FAR *) histogram[i],
  175901. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  175902. }
  175903. cquantize->needs_zeroed = FALSE;
  175904. }
  175905. }
  175906. /*
  175907. * Switch to a new external colormap between output passes.
  175908. */
  175909. METHODDEF(void)
  175910. new_color_map_2_quant (j_decompress_ptr cinfo)
  175911. {
  175912. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  175913. /* Reset the inverse color map */
  175914. cquantize->needs_zeroed = TRUE;
  175915. }
  175916. /*
  175917. * Module initialization routine for 2-pass color quantization.
  175918. */
  175919. GLOBAL(void)
  175920. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  175921. {
  175922. my_cquantize_ptr2 cquantize;
  175923. int i;
  175924. cquantize = (my_cquantize_ptr2)
  175925. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  175926. SIZEOF(my_cquantizer2));
  175927. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  175928. cquantize->pub.start_pass = start_pass_2_quant;
  175929. cquantize->pub.new_color_map = new_color_map_2_quant;
  175930. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  175931. cquantize->error_limiter = NULL;
  175932. /* Make sure jdmaster didn't give me a case I can't handle */
  175933. if (cinfo->out_color_components != 3)
  175934. ERREXIT(cinfo, JERR_NOTIMPL);
  175935. /* Allocate the histogram/inverse colormap storage */
  175936. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  175937. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  175938. for (i = 0; i < HIST_C0_ELEMS; i++) {
  175939. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  175940. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  175941. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  175942. }
  175943. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  175944. /* Allocate storage for the completed colormap, if required.
  175945. * We do this now since it is FAR storage and may affect
  175946. * the memory manager's space calculations.
  175947. */
  175948. if (cinfo->enable_2pass_quant) {
  175949. /* Make sure color count is acceptable */
  175950. int desired = cinfo->desired_number_of_colors;
  175951. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  175952. if (desired < 8)
  175953. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  175954. /* Make sure colormap indexes can be represented by JSAMPLEs */
  175955. if (desired > MAXNUMCOLORS)
  175956. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  175957. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  175958. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  175959. cquantize->desired = desired;
  175960. } else
  175961. cquantize->sv_colormap = NULL;
  175962. /* Only F-S dithering or no dithering is supported. */
  175963. /* If user asks for ordered dither, give him F-S. */
  175964. if (cinfo->dither_mode != JDITHER_NONE)
  175965. cinfo->dither_mode = JDITHER_FS;
  175966. /* Allocate Floyd-Steinberg workspace if necessary.
  175967. * This isn't really needed until pass 2, but again it is FAR storage.
  175968. * Although we will cope with a later change in dither_mode,
  175969. * we do not promise to honor max_memory_to_use if dither_mode changes.
  175970. */
  175971. if (cinfo->dither_mode == JDITHER_FS) {
  175972. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  175973. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  175974. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  175975. /* Might as well create the error-limiting table too. */
  175976. init_error_limit(cinfo);
  175977. }
  175978. }
  175979. #endif /* QUANT_2PASS_SUPPORTED */
  175980. /*** End of inlined file: jquant2.c ***/
  175981. /*** Start of inlined file: jutils.c ***/
  175982. #define JPEG_INTERNALS
  175983. /*
  175984. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  175985. * of a DCT block read in natural order (left to right, top to bottom).
  175986. */
  175987. #if 0 /* This table is not actually needed in v6a */
  175988. const int jpeg_zigzag_order[DCTSIZE2] = {
  175989. 0, 1, 5, 6, 14, 15, 27, 28,
  175990. 2, 4, 7, 13, 16, 26, 29, 42,
  175991. 3, 8, 12, 17, 25, 30, 41, 43,
  175992. 9, 11, 18, 24, 31, 40, 44, 53,
  175993. 10, 19, 23, 32, 39, 45, 52, 54,
  175994. 20, 22, 33, 38, 46, 51, 55, 60,
  175995. 21, 34, 37, 47, 50, 56, 59, 61,
  175996. 35, 36, 48, 49, 57, 58, 62, 63
  175997. };
  175998. #endif
  175999. /*
  176000. * jpeg_natural_order[i] is the natural-order position of the i'th element
  176001. * of zigzag order.
  176002. *
  176003. * When reading corrupted data, the Huffman decoders could attempt
  176004. * to reference an entry beyond the end of this array (if the decoded
  176005. * zero run length reaches past the end of the block). To prevent
  176006. * wild stores without adding an inner-loop test, we put some extra
  176007. * "63"s after the real entries. This will cause the extra coefficient
  176008. * to be stored in location 63 of the block, not somewhere random.
  176009. * The worst case would be a run-length of 15, which means we need 16
  176010. * fake entries.
  176011. */
  176012. const int jpeg_natural_order[DCTSIZE2+16] = {
  176013. 0, 1, 8, 16, 9, 2, 3, 10,
  176014. 17, 24, 32, 25, 18, 11, 4, 5,
  176015. 12, 19, 26, 33, 40, 48, 41, 34,
  176016. 27, 20, 13, 6, 7, 14, 21, 28,
  176017. 35, 42, 49, 56, 57, 50, 43, 36,
  176018. 29, 22, 15, 23, 30, 37, 44, 51,
  176019. 58, 59, 52, 45, 38, 31, 39, 46,
  176020. 53, 60, 61, 54, 47, 55, 62, 63,
  176021. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  176022. 63, 63, 63, 63, 63, 63, 63, 63
  176023. };
  176024. /*
  176025. * Arithmetic utilities
  176026. */
  176027. GLOBAL(long)
  176028. jdiv_round_up (long a, long b)
  176029. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  176030. /* Assumes a >= 0, b > 0 */
  176031. {
  176032. return (a + b - 1L) / b;
  176033. }
  176034. GLOBAL(long)
  176035. jround_up (long a, long b)
  176036. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  176037. /* Assumes a >= 0, b > 0 */
  176038. {
  176039. a += b - 1L;
  176040. return a - (a % b);
  176041. }
  176042. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  176043. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  176044. * are FAR and we're assuming a small-pointer memory model. However, some
  176045. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  176046. * in the small-model libraries. These will be used if USE_FMEM is defined.
  176047. * Otherwise, the routines below do it the hard way. (The performance cost
  176048. * is not all that great, because these routines aren't very heavily used.)
  176049. */
  176050. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  176051. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  176052. #define FMEMZERO(target,size) MEMZERO(target,size)
  176053. #else /* 80x86 case, define if we can */
  176054. #ifdef USE_FMEM
  176055. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  176056. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  176057. #endif
  176058. #endif
  176059. GLOBAL(void)
  176060. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  176061. JSAMPARRAY output_array, int dest_row,
  176062. int num_rows, JDIMENSION num_cols)
  176063. /* Copy some rows of samples from one place to another.
  176064. * num_rows rows are copied from input_array[source_row++]
  176065. * to output_array[dest_row++]; these areas may overlap for duplication.
  176066. * The source and destination arrays must be at least as wide as num_cols.
  176067. */
  176068. {
  176069. register JSAMPROW inptr, outptr;
  176070. #ifdef FMEMCOPY
  176071. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  176072. #else
  176073. register JDIMENSION count;
  176074. #endif
  176075. register int row;
  176076. input_array += source_row;
  176077. output_array += dest_row;
  176078. for (row = num_rows; row > 0; row--) {
  176079. inptr = *input_array++;
  176080. outptr = *output_array++;
  176081. #ifdef FMEMCOPY
  176082. FMEMCOPY(outptr, inptr, count);
  176083. #else
  176084. for (count = num_cols; count > 0; count--)
  176085. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  176086. #endif
  176087. }
  176088. }
  176089. GLOBAL(void)
  176090. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  176091. JDIMENSION num_blocks)
  176092. /* Copy a row of coefficient blocks from one place to another. */
  176093. {
  176094. #ifdef FMEMCOPY
  176095. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  176096. #else
  176097. register JCOEFPTR inptr, outptr;
  176098. register long count;
  176099. inptr = (JCOEFPTR) input_row;
  176100. outptr = (JCOEFPTR) output_row;
  176101. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  176102. *outptr++ = *inptr++;
  176103. }
  176104. #endif
  176105. }
  176106. GLOBAL(void)
  176107. jzero_far (void FAR * target, size_t bytestozero)
  176108. /* Zero out a chunk of FAR memory. */
  176109. /* This might be sample-array data, block-array data, or alloc_large data. */
  176110. {
  176111. #ifdef FMEMZERO
  176112. FMEMZERO(target, bytestozero);
  176113. #else
  176114. register char FAR * ptr = (char FAR *) target;
  176115. register size_t count;
  176116. for (count = bytestozero; count > 0; count--) {
  176117. *ptr++ = 0;
  176118. }
  176119. #endif
  176120. }
  176121. /*** End of inlined file: jutils.c ***/
  176122. /*** Start of inlined file: transupp.c ***/
  176123. /* Although this file really shouldn't have access to the library internals,
  176124. * it's helpful to let it call jround_up() and jcopy_block_row().
  176125. */
  176126. #define JPEG_INTERNALS
  176127. /*** Start of inlined file: transupp.h ***/
  176128. /* If you happen not to want the image transform support, disable it here */
  176129. #ifndef TRANSFORMS_SUPPORTED
  176130. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  176131. #endif
  176132. /* Short forms of external names for systems with brain-damaged linkers. */
  176133. #ifdef NEED_SHORT_EXTERNAL_NAMES
  176134. #define jtransform_request_workspace jTrRequest
  176135. #define jtransform_adjust_parameters jTrAdjust
  176136. #define jtransform_execute_transformation jTrExec
  176137. #define jcopy_markers_setup jCMrkSetup
  176138. #define jcopy_markers_execute jCMrkExec
  176139. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  176140. /*
  176141. * Codes for supported types of image transformations.
  176142. */
  176143. typedef enum {
  176144. JXFORM_NONE, /* no transformation */
  176145. JXFORM_FLIP_H, /* horizontal flip */
  176146. JXFORM_FLIP_V, /* vertical flip */
  176147. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  176148. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  176149. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  176150. JXFORM_ROT_180, /* 180-degree rotation */
  176151. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  176152. } JXFORM_CODE;
  176153. /*
  176154. * Although rotating and flipping data expressed as DCT coefficients is not
  176155. * hard, there is an asymmetry in the JPEG format specification for images
  176156. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  176157. * image edges are padded out to the next iMCU boundary with junk data; but
  176158. * no padding is possible at the top and left edges. If we were to flip
  176159. * the whole image including the pad data, then pad garbage would become
  176160. * visible at the top and/or left, and real pixels would disappear into the
  176161. * pad margins --- perhaps permanently, since encoders & decoders may not
  176162. * bother to preserve DCT blocks that appear to be completely outside the
  176163. * nominal image area. So, we have to exclude any partial iMCUs from the
  176164. * basic transformation.
  176165. *
  176166. * Transpose is the only transformation that can handle partial iMCUs at the
  176167. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  176168. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  176169. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  176170. * The other transforms are defined as combinations of these basic transforms
  176171. * and process edge blocks in a way that preserves the equivalence.
  176172. *
  176173. * The "trim" option causes untransformable partial iMCUs to be dropped;
  176174. * this is not strictly lossless, but it usually gives the best-looking
  176175. * result for odd-size images. Note that when this option is active,
  176176. * the expected mathematical equivalences between the transforms may not hold.
  176177. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  176178. * followed by -rot 180 -trim trims both edges.)
  176179. *
  176180. * We also offer a "force to grayscale" option, which simply discards the
  176181. * chrominance channels of a YCbCr image. This is lossless in the sense that
  176182. * the luminance channel is preserved exactly. It's not the same kind of
  176183. * thing as the rotate/flip transformations, but it's convenient to handle it
  176184. * as part of this package, mainly because the transformation routines have to
  176185. * be aware of the option to know how many components to work on.
  176186. */
  176187. typedef struct {
  176188. /* Options: set by caller */
  176189. JXFORM_CODE transform; /* image transform operator */
  176190. boolean trim; /* if TRUE, trim partial MCUs as needed */
  176191. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  176192. /* Internal workspace: caller should not touch these */
  176193. int num_components; /* # of components in workspace */
  176194. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  176195. } jpeg_transform_info;
  176196. #if TRANSFORMS_SUPPORTED
  176197. /* Request any required workspace */
  176198. EXTERN(void) jtransform_request_workspace
  176199. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  176200. /* Adjust output image parameters */
  176201. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  176202. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  176203. jvirt_barray_ptr *src_coef_arrays,
  176204. jpeg_transform_info *info));
  176205. /* Execute the actual transformation, if any */
  176206. EXTERN(void) jtransform_execute_transformation
  176207. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  176208. jvirt_barray_ptr *src_coef_arrays,
  176209. jpeg_transform_info *info));
  176210. #endif /* TRANSFORMS_SUPPORTED */
  176211. /*
  176212. * Support for copying optional markers from source to destination file.
  176213. */
  176214. typedef enum {
  176215. JCOPYOPT_NONE, /* copy no optional markers */
  176216. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  176217. JCOPYOPT_ALL /* copy all optional markers */
  176218. } JCOPY_OPTION;
  176219. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  176220. /* Setup decompression object to save desired markers in memory */
  176221. EXTERN(void) jcopy_markers_setup
  176222. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  176223. /* Copy markers saved in the given source object to the destination object */
  176224. EXTERN(void) jcopy_markers_execute
  176225. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  176226. JCOPY_OPTION option));
  176227. /*** End of inlined file: transupp.h ***/
  176228. /* My own external interface */
  176229. #if TRANSFORMS_SUPPORTED
  176230. /*
  176231. * Lossless image transformation routines. These routines work on DCT
  176232. * coefficient arrays and thus do not require any lossy decompression
  176233. * or recompression of the image.
  176234. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  176235. *
  176236. * Horizontal flipping is done in-place, using a single top-to-bottom
  176237. * pass through the virtual source array. It will thus be much the
  176238. * fastest option for images larger than main memory.
  176239. *
  176240. * The other routines require a set of destination virtual arrays, so they
  176241. * need twice as much memory as jpegtran normally does. The destination
  176242. * arrays are always written in normal scan order (top to bottom) because
  176243. * the virtual array manager expects this. The source arrays will be scanned
  176244. * in the corresponding order, which means multiple passes through the source
  176245. * arrays for most of the transforms. That could result in much thrashing
  176246. * if the image is larger than main memory.
  176247. *
  176248. * Some notes about the operating environment of the individual transform
  176249. * routines:
  176250. * 1. Both the source and destination virtual arrays are allocated from the
  176251. * source JPEG object, and therefore should be manipulated by calling the
  176252. * source's memory manager.
  176253. * 2. The destination's component count should be used. It may be smaller
  176254. * than the source's when forcing to grayscale.
  176255. * 3. Likewise the destination's sampling factors should be used. When
  176256. * forcing to grayscale the destination's sampling factors will be all 1,
  176257. * and we may as well take that as the effective iMCU size.
  176258. * 4. When "trim" is in effect, the destination's dimensions will be the
  176259. * trimmed values but the source's will be untrimmed.
  176260. * 5. All the routines assume that the source and destination buffers are
  176261. * padded out to a full iMCU boundary. This is true, although for the
  176262. * source buffer it is an undocumented property of jdcoefct.c.
  176263. * Notes 2,3,4 boil down to this: generally we should use the destination's
  176264. * dimensions and ignore the source's.
  176265. */
  176266. LOCAL(void)
  176267. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  176268. jvirt_barray_ptr *src_coef_arrays)
  176269. /* Horizontal flip; done in-place, so no separate dest array is required */
  176270. {
  176271. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  176272. int ci, k, offset_y;
  176273. JBLOCKARRAY buffer;
  176274. JCOEFPTR ptr1, ptr2;
  176275. JCOEF temp1, temp2;
  176276. jpeg_component_info *compptr;
  176277. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  176278. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  176279. * mirroring by changing the signs of odd-numbered columns.
  176280. * Partial iMCUs at the right edge are left untouched.
  176281. */
  176282. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  176283. for (ci = 0; ci < dstinfo->num_components; ci++) {
  176284. compptr = dstinfo->comp_info + ci;
  176285. comp_width = MCU_cols * compptr->h_samp_factor;
  176286. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  176287. blk_y += compptr->v_samp_factor) {
  176288. buffer = (*srcinfo->mem->access_virt_barray)
  176289. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  176290. (JDIMENSION) compptr->v_samp_factor, TRUE);
  176291. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  176292. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  176293. ptr1 = buffer[offset_y][blk_x];
  176294. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  176295. /* this unrolled loop doesn't need to know which row it's on... */
  176296. for (k = 0; k < DCTSIZE2; k += 2) {
  176297. temp1 = *ptr1; /* swap even column */
  176298. temp2 = *ptr2;
  176299. *ptr1++ = temp2;
  176300. *ptr2++ = temp1;
  176301. temp1 = *ptr1; /* swap odd column with sign change */
  176302. temp2 = *ptr2;
  176303. *ptr1++ = -temp2;
  176304. *ptr2++ = -temp1;
  176305. }
  176306. }
  176307. }
  176308. }
  176309. }
  176310. }
  176311. LOCAL(void)
  176312. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  176313. jvirt_barray_ptr *src_coef_arrays,
  176314. jvirt_barray_ptr *dst_coef_arrays)
  176315. /* Vertical flip */
  176316. {
  176317. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  176318. int ci, i, j, offset_y;
  176319. JBLOCKARRAY src_buffer, dst_buffer;
  176320. JBLOCKROW src_row_ptr, dst_row_ptr;
  176321. JCOEFPTR src_ptr, dst_ptr;
  176322. jpeg_component_info *compptr;
  176323. /* We output into a separate array because we can't touch different
  176324. * rows of the source virtual array simultaneously. Otherwise, this
  176325. * is a pretty straightforward analog of horizontal flip.
  176326. * Within a DCT block, vertical mirroring is done by changing the signs
  176327. * of odd-numbered rows.
  176328. * Partial iMCUs at the bottom edge are copied verbatim.
  176329. */
  176330. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  176331. for (ci = 0; ci < dstinfo->num_components; ci++) {
  176332. compptr = dstinfo->comp_info + ci;
  176333. comp_height = MCU_rows * compptr->v_samp_factor;
  176334. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  176335. dst_blk_y += compptr->v_samp_factor) {
  176336. dst_buffer = (*srcinfo->mem->access_virt_barray)
  176337. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  176338. (JDIMENSION) compptr->v_samp_factor, TRUE);
  176339. if (dst_blk_y < comp_height) {
  176340. /* Row is within the mirrorable area. */
  176341. src_buffer = (*srcinfo->mem->access_virt_barray)
  176342. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  176343. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  176344. (JDIMENSION) compptr->v_samp_factor, FALSE);
  176345. } else {
  176346. /* Bottom-edge blocks will be copied verbatim. */
  176347. src_buffer = (*srcinfo->mem->access_virt_barray)
  176348. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  176349. (JDIMENSION) compptr->v_samp_factor, FALSE);
  176350. }
  176351. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  176352. if (dst_blk_y < comp_height) {
  176353. /* Row is within the mirrorable area. */
  176354. dst_row_ptr = dst_buffer[offset_y];
  176355. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  176356. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  176357. dst_blk_x++) {
  176358. dst_ptr = dst_row_ptr[dst_blk_x];
  176359. src_ptr = src_row_ptr[dst_blk_x];
  176360. for (i = 0; i < DCTSIZE; i += 2) {
  176361. /* copy even row */
  176362. for (j = 0; j < DCTSIZE; j++)
  176363. *dst_ptr++ = *src_ptr++;
  176364. /* copy odd row with sign change */
  176365. for (j = 0; j < DCTSIZE; j++)
  176366. *dst_ptr++ = - *src_ptr++;
  176367. }
  176368. }
  176369. } else {
  176370. /* Just copy row verbatim. */
  176371. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  176372. compptr->width_in_blocks);
  176373. }
  176374. }
  176375. }
  176376. }
  176377. }
  176378. LOCAL(void)
  176379. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  176380. jvirt_barray_ptr *src_coef_arrays,
  176381. jvirt_barray_ptr *dst_coef_arrays)
  176382. /* Transpose source into destination */
  176383. {
  176384. JDIMENSION dst_blk_x, dst_blk_y;
  176385. int ci, i, j, offset_x, offset_y;
  176386. JBLOCKARRAY src_buffer, dst_buffer;
  176387. JCOEFPTR src_ptr, dst_ptr;
  176388. jpeg_component_info *compptr;
  176389. /* Transposing pixels within a block just requires transposing the
  176390. * DCT coefficients.
  176391. * Partial iMCUs at the edges require no special treatment; we simply
  176392. * process all the available DCT blocks for every component.
  176393. */
  176394. for (ci = 0; ci < dstinfo->num_components; ci++) {
  176395. compptr = dstinfo->comp_info + ci;
  176396. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  176397. dst_blk_y += compptr->v_samp_factor) {
  176398. dst_buffer = (*srcinfo->mem->access_virt_barray)
  176399. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  176400. (JDIMENSION) compptr->v_samp_factor, TRUE);
  176401. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  176402. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  176403. dst_blk_x += compptr->h_samp_factor) {
  176404. src_buffer = (*srcinfo->mem->access_virt_barray)
  176405. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  176406. (JDIMENSION) compptr->h_samp_factor, FALSE);
  176407. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  176408. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  176409. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  176410. for (i = 0; i < DCTSIZE; i++)
  176411. for (j = 0; j < DCTSIZE; j++)
  176412. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  176413. }
  176414. }
  176415. }
  176416. }
  176417. }
  176418. }
  176419. LOCAL(void)
  176420. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  176421. jvirt_barray_ptr *src_coef_arrays,
  176422. jvirt_barray_ptr *dst_coef_arrays)
  176423. /* 90 degree rotation is equivalent to
  176424. * 1. Transposing the image;
  176425. * 2. Horizontal mirroring.
  176426. * These two steps are merged into a single processing routine.
  176427. */
  176428. {
  176429. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  176430. int ci, i, j, offset_x, offset_y;
  176431. JBLOCKARRAY src_buffer, dst_buffer;
  176432. JCOEFPTR src_ptr, dst_ptr;
  176433. jpeg_component_info *compptr;
  176434. /* Because of the horizontal mirror step, we can't process partial iMCUs
  176435. * at the (output) right edge properly. They just get transposed and
  176436. * not mirrored.
  176437. */
  176438. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  176439. for (ci = 0; ci < dstinfo->num_components; ci++) {
  176440. compptr = dstinfo->comp_info + ci;
  176441. comp_width = MCU_cols * compptr->h_samp_factor;
  176442. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  176443. dst_blk_y += compptr->v_samp_factor) {
  176444. dst_buffer = (*srcinfo->mem->access_virt_barray)
  176445. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  176446. (JDIMENSION) compptr->v_samp_factor, TRUE);
  176447. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  176448. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  176449. dst_blk_x += compptr->h_samp_factor) {
  176450. src_buffer = (*srcinfo->mem->access_virt_barray)
  176451. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  176452. (JDIMENSION) compptr->h_samp_factor, FALSE);
  176453. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  176454. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  176455. if (dst_blk_x < comp_width) {
  176456. /* Block is within the mirrorable area. */
  176457. dst_ptr = dst_buffer[offset_y]
  176458. [comp_width - dst_blk_x - offset_x - 1];
  176459. for (i = 0; i < DCTSIZE; i++) {
  176460. for (j = 0; j < DCTSIZE; j++)
  176461. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  176462. i++;
  176463. for (j = 0; j < DCTSIZE; j++)
  176464. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  176465. }
  176466. } else {
  176467. /* Edge blocks are transposed but not mirrored. */
  176468. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  176469. for (i = 0; i < DCTSIZE; i++)
  176470. for (j = 0; j < DCTSIZE; j++)
  176471. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  176472. }
  176473. }
  176474. }
  176475. }
  176476. }
  176477. }
  176478. }
  176479. LOCAL(void)
  176480. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  176481. jvirt_barray_ptr *src_coef_arrays,
  176482. jvirt_barray_ptr *dst_coef_arrays)
  176483. /* 270 degree rotation is equivalent to
  176484. * 1. Horizontal mirroring;
  176485. * 2. Transposing the image.
  176486. * These two steps are merged into a single processing routine.
  176487. */
  176488. {
  176489. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  176490. int ci, i, j, offset_x, offset_y;
  176491. JBLOCKARRAY src_buffer, dst_buffer;
  176492. JCOEFPTR src_ptr, dst_ptr;
  176493. jpeg_component_info *compptr;
  176494. /* Because of the horizontal mirror step, we can't process partial iMCUs
  176495. * at the (output) bottom edge properly. They just get transposed and
  176496. * not mirrored.
  176497. */
  176498. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  176499. for (ci = 0; ci < dstinfo->num_components; ci++) {
  176500. compptr = dstinfo->comp_info + ci;
  176501. comp_height = MCU_rows * compptr->v_samp_factor;
  176502. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  176503. dst_blk_y += compptr->v_samp_factor) {
  176504. dst_buffer = (*srcinfo->mem->access_virt_barray)
  176505. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  176506. (JDIMENSION) compptr->v_samp_factor, TRUE);
  176507. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  176508. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  176509. dst_blk_x += compptr->h_samp_factor) {
  176510. src_buffer = (*srcinfo->mem->access_virt_barray)
  176511. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  176512. (JDIMENSION) compptr->h_samp_factor, FALSE);
  176513. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  176514. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  176515. if (dst_blk_y < comp_height) {
  176516. /* Block is within the mirrorable area. */
  176517. src_ptr = src_buffer[offset_x]
  176518. [comp_height - dst_blk_y - offset_y - 1];
  176519. for (i = 0; i < DCTSIZE; i++) {
  176520. for (j = 0; j < DCTSIZE; j++) {
  176521. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  176522. j++;
  176523. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  176524. }
  176525. }
  176526. } else {
  176527. /* Edge blocks are transposed but not mirrored. */
  176528. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  176529. for (i = 0; i < DCTSIZE; i++)
  176530. for (j = 0; j < DCTSIZE; j++)
  176531. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  176532. }
  176533. }
  176534. }
  176535. }
  176536. }
  176537. }
  176538. }
  176539. LOCAL(void)
  176540. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  176541. jvirt_barray_ptr *src_coef_arrays,
  176542. jvirt_barray_ptr *dst_coef_arrays)
  176543. /* 180 degree rotation is equivalent to
  176544. * 1. Vertical mirroring;
  176545. * 2. Horizontal mirroring.
  176546. * These two steps are merged into a single processing routine.
  176547. */
  176548. {
  176549. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  176550. int ci, i, j, offset_y;
  176551. JBLOCKARRAY src_buffer, dst_buffer;
  176552. JBLOCKROW src_row_ptr, dst_row_ptr;
  176553. JCOEFPTR src_ptr, dst_ptr;
  176554. jpeg_component_info *compptr;
  176555. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  176556. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  176557. for (ci = 0; ci < dstinfo->num_components; ci++) {
  176558. compptr = dstinfo->comp_info + ci;
  176559. comp_width = MCU_cols * compptr->h_samp_factor;
  176560. comp_height = MCU_rows * compptr->v_samp_factor;
  176561. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  176562. dst_blk_y += compptr->v_samp_factor) {
  176563. dst_buffer = (*srcinfo->mem->access_virt_barray)
  176564. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  176565. (JDIMENSION) compptr->v_samp_factor, TRUE);
  176566. if (dst_blk_y < comp_height) {
  176567. /* Row is within the vertically mirrorable area. */
  176568. src_buffer = (*srcinfo->mem->access_virt_barray)
  176569. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  176570. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  176571. (JDIMENSION) compptr->v_samp_factor, FALSE);
  176572. } else {
  176573. /* Bottom-edge rows are only mirrored horizontally. */
  176574. src_buffer = (*srcinfo->mem->access_virt_barray)
  176575. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  176576. (JDIMENSION) compptr->v_samp_factor, FALSE);
  176577. }
  176578. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  176579. if (dst_blk_y < comp_height) {
  176580. /* Row is within the mirrorable area. */
  176581. dst_row_ptr = dst_buffer[offset_y];
  176582. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  176583. /* Process the blocks that can be mirrored both ways. */
  176584. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  176585. dst_ptr = dst_row_ptr[dst_blk_x];
  176586. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  176587. for (i = 0; i < DCTSIZE; i += 2) {
  176588. /* For even row, negate every odd column. */
  176589. for (j = 0; j < DCTSIZE; j += 2) {
  176590. *dst_ptr++ = *src_ptr++;
  176591. *dst_ptr++ = - *src_ptr++;
  176592. }
  176593. /* For odd row, negate every even column. */
  176594. for (j = 0; j < DCTSIZE; j += 2) {
  176595. *dst_ptr++ = - *src_ptr++;
  176596. *dst_ptr++ = *src_ptr++;
  176597. }
  176598. }
  176599. }
  176600. /* Any remaining right-edge blocks are only mirrored vertically. */
  176601. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  176602. dst_ptr = dst_row_ptr[dst_blk_x];
  176603. src_ptr = src_row_ptr[dst_blk_x];
  176604. for (i = 0; i < DCTSIZE; i += 2) {
  176605. for (j = 0; j < DCTSIZE; j++)
  176606. *dst_ptr++ = *src_ptr++;
  176607. for (j = 0; j < DCTSIZE; j++)
  176608. *dst_ptr++ = - *src_ptr++;
  176609. }
  176610. }
  176611. } else {
  176612. /* Remaining rows are just mirrored horizontally. */
  176613. dst_row_ptr = dst_buffer[offset_y];
  176614. src_row_ptr = src_buffer[offset_y];
  176615. /* Process the blocks that can be mirrored. */
  176616. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  176617. dst_ptr = dst_row_ptr[dst_blk_x];
  176618. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  176619. for (i = 0; i < DCTSIZE2; i += 2) {
  176620. *dst_ptr++ = *src_ptr++;
  176621. *dst_ptr++ = - *src_ptr++;
  176622. }
  176623. }
  176624. /* Any remaining right-edge blocks are only copied. */
  176625. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  176626. dst_ptr = dst_row_ptr[dst_blk_x];
  176627. src_ptr = src_row_ptr[dst_blk_x];
  176628. for (i = 0; i < DCTSIZE2; i++)
  176629. *dst_ptr++ = *src_ptr++;
  176630. }
  176631. }
  176632. }
  176633. }
  176634. }
  176635. }
  176636. LOCAL(void)
  176637. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  176638. jvirt_barray_ptr *src_coef_arrays,
  176639. jvirt_barray_ptr *dst_coef_arrays)
  176640. /* Transverse transpose is equivalent to
  176641. * 1. 180 degree rotation;
  176642. * 2. Transposition;
  176643. * or
  176644. * 1. Horizontal mirroring;
  176645. * 2. Transposition;
  176646. * 3. Horizontal mirroring.
  176647. * These steps are merged into a single processing routine.
  176648. */
  176649. {
  176650. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  176651. int ci, i, j, offset_x, offset_y;
  176652. JBLOCKARRAY src_buffer, dst_buffer;
  176653. JCOEFPTR src_ptr, dst_ptr;
  176654. jpeg_component_info *compptr;
  176655. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  176656. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  176657. for (ci = 0; ci < dstinfo->num_components; ci++) {
  176658. compptr = dstinfo->comp_info + ci;
  176659. comp_width = MCU_cols * compptr->h_samp_factor;
  176660. comp_height = MCU_rows * compptr->v_samp_factor;
  176661. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  176662. dst_blk_y += compptr->v_samp_factor) {
  176663. dst_buffer = (*srcinfo->mem->access_virt_barray)
  176664. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  176665. (JDIMENSION) compptr->v_samp_factor, TRUE);
  176666. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  176667. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  176668. dst_blk_x += compptr->h_samp_factor) {
  176669. src_buffer = (*srcinfo->mem->access_virt_barray)
  176670. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  176671. (JDIMENSION) compptr->h_samp_factor, FALSE);
  176672. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  176673. if (dst_blk_y < comp_height) {
  176674. src_ptr = src_buffer[offset_x]
  176675. [comp_height - dst_blk_y - offset_y - 1];
  176676. if (dst_blk_x < comp_width) {
  176677. /* Block is within the mirrorable area. */
  176678. dst_ptr = dst_buffer[offset_y]
  176679. [comp_width - dst_blk_x - offset_x - 1];
  176680. for (i = 0; i < DCTSIZE; i++) {
  176681. for (j = 0; j < DCTSIZE; j++) {
  176682. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  176683. j++;
  176684. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  176685. }
  176686. i++;
  176687. for (j = 0; j < DCTSIZE; j++) {
  176688. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  176689. j++;
  176690. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  176691. }
  176692. }
  176693. } else {
  176694. /* Right-edge blocks are mirrored in y only */
  176695. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  176696. for (i = 0; i < DCTSIZE; i++) {
  176697. for (j = 0; j < DCTSIZE; j++) {
  176698. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  176699. j++;
  176700. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  176701. }
  176702. }
  176703. }
  176704. } else {
  176705. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  176706. if (dst_blk_x < comp_width) {
  176707. /* Bottom-edge blocks are mirrored in x only */
  176708. dst_ptr = dst_buffer[offset_y]
  176709. [comp_width - dst_blk_x - offset_x - 1];
  176710. for (i = 0; i < DCTSIZE; i++) {
  176711. for (j = 0; j < DCTSIZE; j++)
  176712. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  176713. i++;
  176714. for (j = 0; j < DCTSIZE; j++)
  176715. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  176716. }
  176717. } else {
  176718. /* At lower right corner, just transpose, no mirroring */
  176719. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  176720. for (i = 0; i < DCTSIZE; i++)
  176721. for (j = 0; j < DCTSIZE; j++)
  176722. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  176723. }
  176724. }
  176725. }
  176726. }
  176727. }
  176728. }
  176729. }
  176730. }
  176731. /* Request any required workspace.
  176732. *
  176733. * We allocate the workspace virtual arrays from the source decompression
  176734. * object, so that all the arrays (both the original data and the workspace)
  176735. * will be taken into account while making memory management decisions.
  176736. * Hence, this routine must be called after jpeg_read_header (which reads
  176737. * the image dimensions) and before jpeg_read_coefficients (which realizes
  176738. * the source's virtual arrays).
  176739. */
  176740. GLOBAL(void)
  176741. jtransform_request_workspace (j_decompress_ptr srcinfo,
  176742. jpeg_transform_info *info)
  176743. {
  176744. jvirt_barray_ptr *coef_arrays = NULL;
  176745. jpeg_component_info *compptr;
  176746. int ci;
  176747. if (info->force_grayscale &&
  176748. srcinfo->jpeg_color_space == JCS_YCbCr &&
  176749. srcinfo->num_components == 3) {
  176750. /* We'll only process the first component */
  176751. info->num_components = 1;
  176752. } else {
  176753. /* Process all the components */
  176754. info->num_components = srcinfo->num_components;
  176755. }
  176756. switch (info->transform) {
  176757. case JXFORM_NONE:
  176758. case JXFORM_FLIP_H:
  176759. /* Don't need a workspace array */
  176760. break;
  176761. case JXFORM_FLIP_V:
  176762. case JXFORM_ROT_180:
  176763. /* Need workspace arrays having same dimensions as source image.
  176764. * Note that we allocate arrays padded out to the next iMCU boundary,
  176765. * so that transform routines need not worry about missing edge blocks.
  176766. */
  176767. coef_arrays = (jvirt_barray_ptr *)
  176768. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  176769. SIZEOF(jvirt_barray_ptr) * info->num_components);
  176770. for (ci = 0; ci < info->num_components; ci++) {
  176771. compptr = srcinfo->comp_info + ci;
  176772. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  176773. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  176774. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  176775. (long) compptr->h_samp_factor),
  176776. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  176777. (long) compptr->v_samp_factor),
  176778. (JDIMENSION) compptr->v_samp_factor);
  176779. }
  176780. break;
  176781. case JXFORM_TRANSPOSE:
  176782. case JXFORM_TRANSVERSE:
  176783. case JXFORM_ROT_90:
  176784. case JXFORM_ROT_270:
  176785. /* Need workspace arrays having transposed dimensions.
  176786. * Note that we allocate arrays padded out to the next iMCU boundary,
  176787. * so that transform routines need not worry about missing edge blocks.
  176788. */
  176789. coef_arrays = (jvirt_barray_ptr *)
  176790. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  176791. SIZEOF(jvirt_barray_ptr) * info->num_components);
  176792. for (ci = 0; ci < info->num_components; ci++) {
  176793. compptr = srcinfo->comp_info + ci;
  176794. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  176795. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  176796. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  176797. (long) compptr->v_samp_factor),
  176798. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  176799. (long) compptr->h_samp_factor),
  176800. (JDIMENSION) compptr->h_samp_factor);
  176801. }
  176802. break;
  176803. }
  176804. info->workspace_coef_arrays = coef_arrays;
  176805. }
  176806. /* Transpose destination image parameters */
  176807. LOCAL(void)
  176808. transpose_critical_parameters (j_compress_ptr dstinfo)
  176809. {
  176810. int tblno, i, j, ci, itemp;
  176811. jpeg_component_info *compptr;
  176812. JQUANT_TBL *qtblptr;
  176813. JDIMENSION dtemp;
  176814. UINT16 qtemp;
  176815. /* Transpose basic image dimensions */
  176816. dtemp = dstinfo->image_width;
  176817. dstinfo->image_width = dstinfo->image_height;
  176818. dstinfo->image_height = dtemp;
  176819. /* Transpose sampling factors */
  176820. for (ci = 0; ci < dstinfo->num_components; ci++) {
  176821. compptr = dstinfo->comp_info + ci;
  176822. itemp = compptr->h_samp_factor;
  176823. compptr->h_samp_factor = compptr->v_samp_factor;
  176824. compptr->v_samp_factor = itemp;
  176825. }
  176826. /* Transpose quantization tables */
  176827. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  176828. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  176829. if (qtblptr != NULL) {
  176830. for (i = 0; i < DCTSIZE; i++) {
  176831. for (j = 0; j < i; j++) {
  176832. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  176833. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  176834. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  176835. }
  176836. }
  176837. }
  176838. }
  176839. }
  176840. /* Trim off any partial iMCUs on the indicated destination edge */
  176841. LOCAL(void)
  176842. trim_right_edge (j_compress_ptr dstinfo)
  176843. {
  176844. int ci, max_h_samp_factor;
  176845. JDIMENSION MCU_cols;
  176846. /* We have to compute max_h_samp_factor ourselves,
  176847. * because it hasn't been set yet in the destination
  176848. * (and we don't want to use the source's value).
  176849. */
  176850. max_h_samp_factor = 1;
  176851. for (ci = 0; ci < dstinfo->num_components; ci++) {
  176852. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  176853. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  176854. }
  176855. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  176856. if (MCU_cols > 0) /* can't trim to 0 pixels */
  176857. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  176858. }
  176859. LOCAL(void)
  176860. trim_bottom_edge (j_compress_ptr dstinfo)
  176861. {
  176862. int ci, max_v_samp_factor;
  176863. JDIMENSION MCU_rows;
  176864. /* We have to compute max_v_samp_factor ourselves,
  176865. * because it hasn't been set yet in the destination
  176866. * (and we don't want to use the source's value).
  176867. */
  176868. max_v_samp_factor = 1;
  176869. for (ci = 0; ci < dstinfo->num_components; ci++) {
  176870. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  176871. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  176872. }
  176873. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  176874. if (MCU_rows > 0) /* can't trim to 0 pixels */
  176875. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  176876. }
  176877. /* Adjust output image parameters as needed.
  176878. *
  176879. * This must be called after jpeg_copy_critical_parameters()
  176880. * and before jpeg_write_coefficients().
  176881. *
  176882. * The return value is the set of virtual coefficient arrays to be written
  176883. * (either the ones allocated by jtransform_request_workspace, or the
  176884. * original source data arrays). The caller will need to pass this value
  176885. * to jpeg_write_coefficients().
  176886. */
  176887. GLOBAL(jvirt_barray_ptr *)
  176888. jtransform_adjust_parameters (j_decompress_ptr,
  176889. j_compress_ptr dstinfo,
  176890. jvirt_barray_ptr *src_coef_arrays,
  176891. jpeg_transform_info *info)
  176892. {
  176893. /* If force-to-grayscale is requested, adjust destination parameters */
  176894. if (info->force_grayscale) {
  176895. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  176896. * properly. Among other things, the target h_samp_factor & v_samp_factor
  176897. * will get set to 1, which typically won't match the source.
  176898. * In fact we do this even if the source is already grayscale; that
  176899. * provides an easy way of coercing a grayscale JPEG with funny sampling
  176900. * factors to the customary 1,1. (Some decoders fail on other factors.)
  176901. */
  176902. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  176903. dstinfo->num_components == 3) ||
  176904. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  176905. dstinfo->num_components == 1)) {
  176906. /* We have to preserve the source's quantization table number. */
  176907. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  176908. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  176909. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  176910. } else {
  176911. /* Sorry, can't do it */
  176912. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  176913. }
  176914. }
  176915. /* Correct the destination's image dimensions etc if necessary */
  176916. switch (info->transform) {
  176917. case JXFORM_NONE:
  176918. /* Nothing to do */
  176919. break;
  176920. case JXFORM_FLIP_H:
  176921. if (info->trim)
  176922. trim_right_edge(dstinfo);
  176923. break;
  176924. case JXFORM_FLIP_V:
  176925. if (info->trim)
  176926. trim_bottom_edge(dstinfo);
  176927. break;
  176928. case JXFORM_TRANSPOSE:
  176929. transpose_critical_parameters(dstinfo);
  176930. /* transpose does NOT have to trim anything */
  176931. break;
  176932. case JXFORM_TRANSVERSE:
  176933. transpose_critical_parameters(dstinfo);
  176934. if (info->trim) {
  176935. trim_right_edge(dstinfo);
  176936. trim_bottom_edge(dstinfo);
  176937. }
  176938. break;
  176939. case JXFORM_ROT_90:
  176940. transpose_critical_parameters(dstinfo);
  176941. if (info->trim)
  176942. trim_right_edge(dstinfo);
  176943. break;
  176944. case JXFORM_ROT_180:
  176945. if (info->trim) {
  176946. trim_right_edge(dstinfo);
  176947. trim_bottom_edge(dstinfo);
  176948. }
  176949. break;
  176950. case JXFORM_ROT_270:
  176951. transpose_critical_parameters(dstinfo);
  176952. if (info->trim)
  176953. trim_bottom_edge(dstinfo);
  176954. break;
  176955. }
  176956. /* Return the appropriate output data set */
  176957. if (info->workspace_coef_arrays != NULL)
  176958. return info->workspace_coef_arrays;
  176959. return src_coef_arrays;
  176960. }
  176961. /* Execute the actual transformation, if any.
  176962. *
  176963. * This must be called *after* jpeg_write_coefficients, because it depends
  176964. * on jpeg_write_coefficients to have computed subsidiary values such as
  176965. * the per-component width and height fields in the destination object.
  176966. *
  176967. * Note that some transformations will modify the source data arrays!
  176968. */
  176969. GLOBAL(void)
  176970. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  176971. j_compress_ptr dstinfo,
  176972. jvirt_barray_ptr *src_coef_arrays,
  176973. jpeg_transform_info *info)
  176974. {
  176975. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  176976. switch (info->transform) {
  176977. case JXFORM_NONE:
  176978. break;
  176979. case JXFORM_FLIP_H:
  176980. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  176981. break;
  176982. case JXFORM_FLIP_V:
  176983. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  176984. break;
  176985. case JXFORM_TRANSPOSE:
  176986. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  176987. break;
  176988. case JXFORM_TRANSVERSE:
  176989. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  176990. break;
  176991. case JXFORM_ROT_90:
  176992. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  176993. break;
  176994. case JXFORM_ROT_180:
  176995. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  176996. break;
  176997. case JXFORM_ROT_270:
  176998. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  176999. break;
  177000. }
  177001. }
  177002. #endif /* TRANSFORMS_SUPPORTED */
  177003. /* Setup decompression object to save desired markers in memory.
  177004. * This must be called before jpeg_read_header() to have the desired effect.
  177005. */
  177006. GLOBAL(void)
  177007. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  177008. {
  177009. #ifdef SAVE_MARKERS_SUPPORTED
  177010. int m;
  177011. /* Save comments except under NONE option */
  177012. if (option != JCOPYOPT_NONE) {
  177013. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  177014. }
  177015. /* Save all types of APPn markers iff ALL option */
  177016. if (option == JCOPYOPT_ALL) {
  177017. for (m = 0; m < 16; m++)
  177018. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  177019. }
  177020. #endif /* SAVE_MARKERS_SUPPORTED */
  177021. }
  177022. /* Copy markers saved in the given source object to the destination object.
  177023. * This should be called just after jpeg_start_compress() or
  177024. * jpeg_write_coefficients().
  177025. * Note that those routines will have written the SOI, and also the
  177026. * JFIF APP0 or Adobe APP14 markers if selected.
  177027. */
  177028. GLOBAL(void)
  177029. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  177030. JCOPY_OPTION)
  177031. {
  177032. jpeg_saved_marker_ptr marker;
  177033. /* In the current implementation, we don't actually need to examine the
  177034. * option flag here; we just copy everything that got saved.
  177035. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  177036. * if the encoder library already wrote one.
  177037. */
  177038. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  177039. if (dstinfo->write_JFIF_header &&
  177040. marker->marker == JPEG_APP0 &&
  177041. marker->data_length >= 5 &&
  177042. GETJOCTET(marker->data[0]) == 0x4A &&
  177043. GETJOCTET(marker->data[1]) == 0x46 &&
  177044. GETJOCTET(marker->data[2]) == 0x49 &&
  177045. GETJOCTET(marker->data[3]) == 0x46 &&
  177046. GETJOCTET(marker->data[4]) == 0)
  177047. continue; /* reject duplicate JFIF */
  177048. if (dstinfo->write_Adobe_marker &&
  177049. marker->marker == JPEG_APP0+14 &&
  177050. marker->data_length >= 5 &&
  177051. GETJOCTET(marker->data[0]) == 0x41 &&
  177052. GETJOCTET(marker->data[1]) == 0x64 &&
  177053. GETJOCTET(marker->data[2]) == 0x6F &&
  177054. GETJOCTET(marker->data[3]) == 0x62 &&
  177055. GETJOCTET(marker->data[4]) == 0x65)
  177056. continue; /* reject duplicate Adobe */
  177057. #ifdef NEED_FAR_POINTERS
  177058. /* We could use jpeg_write_marker if the data weren't FAR... */
  177059. {
  177060. unsigned int i;
  177061. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  177062. for (i = 0; i < marker->data_length; i++)
  177063. jpeg_write_m_byte(dstinfo, marker->data[i]);
  177064. }
  177065. #else
  177066. jpeg_write_marker(dstinfo, marker->marker,
  177067. marker->data, marker->data_length);
  177068. #endif
  177069. }
  177070. }
  177071. /*** End of inlined file: transupp.c ***/
  177072. }
  177073. #else
  177074. #define JPEG_INTERNALS
  177075. #undef FAR
  177076. #include <jpeglib.h>
  177077. #endif
  177078. }
  177079. #undef max
  177080. #undef min
  177081. #if JUCE_MSVC
  177082. #pragma warning (pop)
  177083. #endif
  177084. BEGIN_JUCE_NAMESPACE
  177085. namespace JPEGHelpers
  177086. {
  177087. using namespace jpeglibNamespace;
  177088. #if ! JUCE_MSVC
  177089. using jpeglibNamespace::boolean;
  177090. #endif
  177091. struct JPEGDecodingFailure {};
  177092. static void fatalErrorHandler (j_common_ptr)
  177093. {
  177094. throw JPEGDecodingFailure();
  177095. }
  177096. static void silentErrorCallback1 (j_common_ptr) {}
  177097. static void silentErrorCallback2 (j_common_ptr, int) {}
  177098. static void silentErrorCallback3 (j_common_ptr, char*) {}
  177099. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  177100. {
  177101. zerostruct (err);
  177102. err.error_exit = fatalErrorHandler;
  177103. err.emit_message = silentErrorCallback2;
  177104. err.output_message = silentErrorCallback1;
  177105. err.format_message = silentErrorCallback3;
  177106. err.reset_error_mgr = silentErrorCallback1;
  177107. }
  177108. static void dummyCallback1 (j_decompress_ptr)
  177109. {
  177110. }
  177111. static void jpegSkip (j_decompress_ptr decompStruct, long num)
  177112. {
  177113. decompStruct->src->next_input_byte += num;
  177114. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  177115. decompStruct->src->bytes_in_buffer -= num;
  177116. }
  177117. static boolean jpegFill (j_decompress_ptr)
  177118. {
  177119. return 0;
  177120. }
  177121. static const int jpegBufferSize = 512;
  177122. struct JuceJpegDest : public jpeg_destination_mgr
  177123. {
  177124. OutputStream* output;
  177125. char* buffer;
  177126. };
  177127. static void jpegWriteInit (j_compress_ptr)
  177128. {
  177129. }
  177130. static void jpegWriteTerminate (j_compress_ptr cinfo)
  177131. {
  177132. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  177133. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  177134. dest->output->write (dest->buffer, (int) numToWrite);
  177135. }
  177136. static boolean jpegWriteFlush (j_compress_ptr cinfo)
  177137. {
  177138. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  177139. const int numToWrite = jpegBufferSize;
  177140. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  177141. dest->free_in_buffer = jpegBufferSize;
  177142. return dest->output->write (dest->buffer, numToWrite);
  177143. }
  177144. }
  177145. JPEGImageFormat::JPEGImageFormat()
  177146. : quality (-1.0f)
  177147. {
  177148. }
  177149. JPEGImageFormat::~JPEGImageFormat() {}
  177150. void JPEGImageFormat::setQuality (const float newQuality)
  177151. {
  177152. quality = newQuality;
  177153. }
  177154. const String JPEGImageFormat::getFormatName()
  177155. {
  177156. return "JPEG";
  177157. }
  177158. bool JPEGImageFormat::canUnderstand (InputStream& in)
  177159. {
  177160. const int bytesNeeded = 10;
  177161. uint8 header [bytesNeeded];
  177162. if (in.read (header, bytesNeeded) == bytesNeeded)
  177163. {
  177164. return header[0] == 0xff
  177165. && header[1] == 0xd8
  177166. && header[2] == 0xff
  177167. && (header[3] == 0xe0 || header[3] == 0xe1);
  177168. }
  177169. return false;
  177170. }
  177171. Image* JPEGImageFormat::decodeImage (InputStream& in)
  177172. {
  177173. using namespace jpeglibNamespace;
  177174. using namespace JPEGHelpers;
  177175. MemoryBlock mb;
  177176. in.readIntoMemoryBlock (mb);
  177177. Image* image = 0;
  177178. if (mb.getSize() > 16)
  177179. {
  177180. struct jpeg_decompress_struct jpegDecompStruct;
  177181. struct jpeg_error_mgr jerr;
  177182. setupSilentErrorHandler (jerr);
  177183. jpegDecompStruct.err = &jerr;
  177184. jpeg_create_decompress (&jpegDecompStruct);
  177185. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  177186. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  177187. jpegDecompStruct.src->init_source = dummyCallback1;
  177188. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  177189. jpegDecompStruct.src->skip_input_data = jpegSkip;
  177190. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  177191. jpegDecompStruct.src->term_source = dummyCallback1;
  177192. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  177193. jpegDecompStruct.src->bytes_in_buffer = mb.getSize();
  177194. try
  177195. {
  177196. jpeg_read_header (&jpegDecompStruct, TRUE);
  177197. jpeg_calc_output_dimensions (&jpegDecompStruct);
  177198. const int width = jpegDecompStruct.output_width;
  177199. const int height = jpegDecompStruct.output_height;
  177200. jpegDecompStruct.out_color_space = JCS_RGB;
  177201. JSAMPARRAY buffer
  177202. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  177203. JPOOL_IMAGE,
  177204. width * 3, 1);
  177205. if (jpeg_start_decompress (&jpegDecompStruct))
  177206. {
  177207. image = Image::createNativeImage (Image::RGB, width, height, false);
  177208. const bool hasAlphaChan = image->hasAlphaChannel();
  177209. const Image::BitmapData destData (*image, 0, 0, width, height, true);
  177210. for (int y = 0; y < height; ++y)
  177211. {
  177212. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  177213. const uint8* src = *buffer;
  177214. uint8* dest = destData.getLinePointer (y);
  177215. if (hasAlphaChan)
  177216. {
  177217. for (int i = width; --i >= 0;)
  177218. {
  177219. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  177220. ((PixelARGB*) dest)->premultiply();
  177221. dest += destData.pixelStride;
  177222. src += 3;
  177223. }
  177224. }
  177225. else
  177226. {
  177227. for (int i = width; --i >= 0;)
  177228. {
  177229. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  177230. dest += destData.pixelStride;
  177231. src += 3;
  177232. }
  177233. }
  177234. }
  177235. jpeg_finish_decompress (&jpegDecompStruct);
  177236. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  177237. }
  177238. jpeg_destroy_decompress (&jpegDecompStruct);
  177239. }
  177240. catch (...)
  177241. {}
  177242. }
  177243. return image;
  177244. }
  177245. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  177246. {
  177247. using namespace jpeglibNamespace;
  177248. using namespace JPEGHelpers;
  177249. if (image.hasAlphaChannel())
  177250. {
  177251. // this method could fill the background in white and still save the image..
  177252. jassertfalse
  177253. return true;
  177254. }
  177255. struct jpeg_compress_struct jpegCompStruct;
  177256. struct jpeg_error_mgr jerr;
  177257. setupSilentErrorHandler (jerr);
  177258. jpegCompStruct.err = &jerr;
  177259. jpeg_create_compress (&jpegCompStruct);
  177260. JuceJpegDest dest;
  177261. jpegCompStruct.dest = &dest;
  177262. dest.output = &out;
  177263. HeapBlock <char> tempBuffer (jpegBufferSize);
  177264. dest.buffer = tempBuffer;
  177265. dest.next_output_byte = (JOCTET*) dest.buffer;
  177266. dest.free_in_buffer = jpegBufferSize;
  177267. dest.init_destination = jpegWriteInit;
  177268. dest.empty_output_buffer = jpegWriteFlush;
  177269. dest.term_destination = jpegWriteTerminate;
  177270. jpegCompStruct.image_width = image.getWidth();
  177271. jpegCompStruct.image_height = image.getHeight();
  177272. jpegCompStruct.input_components = 3;
  177273. jpegCompStruct.in_color_space = JCS_RGB;
  177274. jpegCompStruct.write_JFIF_header = 1;
  177275. jpegCompStruct.X_density = 72;
  177276. jpegCompStruct.Y_density = 72;
  177277. jpeg_set_defaults (&jpegCompStruct);
  177278. jpegCompStruct.dct_method = JDCT_FLOAT;
  177279. jpegCompStruct.optimize_coding = 1;
  177280. //jpegCompStruct.smoothing_factor = 10;
  177281. if (quality < 0.0f)
  177282. quality = 0.85f;
  177283. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  177284. jpeg_start_compress (&jpegCompStruct, TRUE);
  177285. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  177286. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  177287. JPOOL_IMAGE, strideBytes, 1);
  177288. const Image::BitmapData srcData (image, 0, 0, jpegCompStruct.image_width, jpegCompStruct.image_height);
  177289. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  177290. {
  177291. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  177292. uint8* dst = *buffer;
  177293. for (int i = jpegCompStruct.image_width; --i >= 0;)
  177294. {
  177295. *dst++ = ((const PixelRGB*) src)->getRed();
  177296. *dst++ = ((const PixelRGB*) src)->getGreen();
  177297. *dst++ = ((const PixelRGB*) src)->getBlue();
  177298. src += srcData.pixelStride;
  177299. }
  177300. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  177301. }
  177302. jpeg_finish_compress (&jpegCompStruct);
  177303. jpeg_destroy_compress (&jpegCompStruct);
  177304. out.flush();
  177305. return true;
  177306. }
  177307. END_JUCE_NAMESPACE
  177308. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  177309. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  177310. #if JUCE_MSVC
  177311. #pragma warning (push)
  177312. #pragma warning (disable: 4390 4611)
  177313. #endif
  177314. namespace zlibNamespace
  177315. {
  177316. #if JUCE_INCLUDE_ZLIB_CODE
  177317. #undef OS_CODE
  177318. #undef fdopen
  177319. #undef OS_CODE
  177320. #else
  177321. #include <zlib.h>
  177322. #endif
  177323. }
  177324. namespace pnglibNamespace
  177325. {
  177326. using namespace zlibNamespace;
  177327. #if JUCE_INCLUDE_PNGLIB_CODE
  177328. #if _MSC_VER != 1310
  177329. using ::calloc; // (causes conflict in VS.NET 2003)
  177330. using ::malloc;
  177331. using ::free;
  177332. #endif
  177333. extern "C"
  177334. {
  177335. using ::abs;
  177336. #define PNG_INTERNAL
  177337. #define NO_DUMMY_DECL
  177338. #define PNG_SETJMP_NOT_SUPPORTED
  177339. /*** Start of inlined file: png.h ***/
  177340. /* png.h - header file for PNG reference library
  177341. *
  177342. * libpng version 1.2.21 - October 4, 2007
  177343. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  177344. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  177345. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  177346. *
  177347. * Authors and maintainers:
  177348. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  177349. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  177350. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  177351. * See also "Contributing Authors", below.
  177352. *
  177353. * Note about libpng version numbers:
  177354. *
  177355. * Due to various miscommunications, unforeseen code incompatibilities
  177356. * and occasional factors outside the authors' control, version numbering
  177357. * on the library has not always been consistent and straightforward.
  177358. * The following table summarizes matters since version 0.89c, which was
  177359. * the first widely used release:
  177360. *
  177361. * source png.h png.h shared-lib
  177362. * version string int version
  177363. * ------- ------ ----- ----------
  177364. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  177365. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  177366. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  177367. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  177368. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  177369. * 0.97c 0.97 97 2.0.97
  177370. * 0.98 0.98 98 2.0.98
  177371. * 0.99 0.99 98 2.0.99
  177372. * 0.99a-m 0.99 99 2.0.99
  177373. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  177374. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  177375. * 1.0.1 png.h string is 10001 2.1.0
  177376. * 1.0.1a-e identical to the 10002 from here on, the shared library
  177377. * 1.0.2 source version) 10002 is 2.V where V is the source code
  177378. * 1.0.2a-b 10003 version, except as noted.
  177379. * 1.0.3 10003
  177380. * 1.0.3a-d 10004
  177381. * 1.0.4 10004
  177382. * 1.0.4a-f 10005
  177383. * 1.0.5 (+ 2 patches) 10005
  177384. * 1.0.5a-d 10006
  177385. * 1.0.5e-r 10100 (not source compatible)
  177386. * 1.0.5s-v 10006 (not binary compatible)
  177387. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  177388. * 1.0.6d-f 10007 (still binary incompatible)
  177389. * 1.0.6g 10007
  177390. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  177391. * 1.0.6i 10007 10.6i
  177392. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  177393. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  177394. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  177395. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  177396. * 1.0.7 1 10007 (still compatible)
  177397. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  177398. * 1.0.8rc1 1 10008 2.1.0.8rc1
  177399. * 1.0.8 1 10008 2.1.0.8
  177400. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  177401. * 1.0.9rc1 1 10009 2.1.0.9rc1
  177402. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  177403. * 1.0.9rc2 1 10009 2.1.0.9rc2
  177404. * 1.0.9 1 10009 2.1.0.9
  177405. * 1.0.10beta1 1 10010 2.1.0.10beta1
  177406. * 1.0.10rc1 1 10010 2.1.0.10rc1
  177407. * 1.0.10 1 10010 2.1.0.10
  177408. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  177409. * 1.0.11rc1 1 10011 2.1.0.11rc1
  177410. * 1.0.11 1 10011 2.1.0.11
  177411. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  177412. * 1.0.12rc1 2 10012 2.1.0.12rc1
  177413. * 1.0.12 2 10012 2.1.0.12
  177414. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  177415. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  177416. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  177417. * 1.2.0rc1 3 10200 3.1.2.0rc1
  177418. * 1.2.0 3 10200 3.1.2.0
  177419. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  177420. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  177421. * 1.2.1 3 10201 3.1.2.1
  177422. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  177423. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  177424. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  177425. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  177426. * 1.0.13 10 10013 10.so.0.1.0.13
  177427. * 1.2.2 12 10202 12.so.0.1.2.2
  177428. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  177429. * 1.2.3 12 10203 12.so.0.1.2.3
  177430. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  177431. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  177432. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  177433. * 1.0.14 10 10014 10.so.0.1.0.14
  177434. * 1.2.4 13 10204 12.so.0.1.2.4
  177435. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  177436. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  177437. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  177438. * 1.0.15 10 10015 10.so.0.1.0.15
  177439. * 1.2.5 13 10205 12.so.0.1.2.5
  177440. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  177441. * 1.0.16 10 10016 10.so.0.1.0.16
  177442. * 1.2.6 13 10206 12.so.0.1.2.6
  177443. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  177444. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  177445. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  177446. * 1.0.17 10 10017 10.so.0.1.0.17
  177447. * 1.2.7 13 10207 12.so.0.1.2.7
  177448. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  177449. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  177450. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  177451. * 1.0.18 10 10018 10.so.0.1.0.18
  177452. * 1.2.8 13 10208 12.so.0.1.2.8
  177453. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  177454. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  177455. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  177456. * 1.2.9 13 10209 12.so.0.9[.0]
  177457. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  177458. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  177459. * 1.2.10 13 10210 12.so.0.10[.0]
  177460. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  177461. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  177462. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  177463. * 1.0.19 10 10019 10.so.0.19[.0]
  177464. * 1.2.11 13 10211 12.so.0.11[.0]
  177465. * 1.0.20 10 10020 10.so.0.20[.0]
  177466. * 1.2.12 13 10212 12.so.0.12[.0]
  177467. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  177468. * 1.0.21 10 10021 10.so.0.21[.0]
  177469. * 1.2.13 13 10213 12.so.0.13[.0]
  177470. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  177471. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  177472. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  177473. * 1.0.22 10 10022 10.so.0.22[.0]
  177474. * 1.2.14 13 10214 12.so.0.14[.0]
  177475. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  177476. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  177477. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  177478. * 1.0.23 10 10023 10.so.0.23[.0]
  177479. * 1.2.15 13 10215 12.so.0.15[.0]
  177480. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  177481. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  177482. * 1.0.24 10 10024 10.so.0.24[.0]
  177483. * 1.2.16 13 10216 12.so.0.16[.0]
  177484. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  177485. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  177486. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  177487. * 1.0.25 10 10025 10.so.0.25[.0]
  177488. * 1.2.17 13 10217 12.so.0.17[.0]
  177489. * 1.0.26 10 10026 10.so.0.26[.0]
  177490. * 1.2.18 13 10218 12.so.0.18[.0]
  177491. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  177492. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  177493. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  177494. * 1.0.27 10 10027 10.so.0.27[.0]
  177495. * 1.2.19 13 10219 12.so.0.19[.0]
  177496. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  177497. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  177498. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  177499. * 1.0.28 10 10028 10.so.0.28[.0]
  177500. * 1.2.20 13 10220 12.so.0.20[.0]
  177501. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  177502. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  177503. * 1.0.29 10 10029 10.so.0.29[.0]
  177504. * 1.2.21 13 10221 12.so.0.21[.0]
  177505. *
  177506. * Henceforth the source version will match the shared-library major
  177507. * and minor numbers; the shared-library major version number will be
  177508. * used for changes in backward compatibility, as it is intended. The
  177509. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  177510. * for applications, is an unsigned integer of the form xyyzz corresponding
  177511. * to the source version x.y.z (leading zeros in y and z). Beta versions
  177512. * were given the previous public release number plus a letter, until
  177513. * version 1.0.6j; from then on they were given the upcoming public
  177514. * release number plus "betaNN" or "rcN".
  177515. *
  177516. * Binary incompatibility exists only when applications make direct access
  177517. * to the info_ptr or png_ptr members through png.h, and the compiled
  177518. * application is loaded with a different version of the library.
  177519. *
  177520. * DLLNUM will change each time there are forward or backward changes
  177521. * in binary compatibility (e.g., when a new feature is added).
  177522. *
  177523. * See libpng.txt or libpng.3 for more information. The PNG specification
  177524. * is available as a W3C Recommendation and as an ISO Specification,
  177525. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  177526. */
  177527. /*
  177528. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  177529. *
  177530. * If you modify libpng you may insert additional notices immediately following
  177531. * this sentence.
  177532. *
  177533. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  177534. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  177535. * distributed according to the same disclaimer and license as libpng-1.2.5
  177536. * with the following individual added to the list of Contributing Authors:
  177537. *
  177538. * Cosmin Truta
  177539. *
  177540. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  177541. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  177542. * distributed according to the same disclaimer and license as libpng-1.0.6
  177543. * with the following individuals added to the list of Contributing Authors:
  177544. *
  177545. * Simon-Pierre Cadieux
  177546. * Eric S. Raymond
  177547. * Gilles Vollant
  177548. *
  177549. * and with the following additions to the disclaimer:
  177550. *
  177551. * There is no warranty against interference with your enjoyment of the
  177552. * library or against infringement. There is no warranty that our
  177553. * efforts or the library will fulfill any of your particular purposes
  177554. * or needs. This library is provided with all faults, and the entire
  177555. * risk of satisfactory quality, performance, accuracy, and effort is with
  177556. * the user.
  177557. *
  177558. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  177559. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  177560. * distributed according to the same disclaimer and license as libpng-0.96,
  177561. * with the following individuals added to the list of Contributing Authors:
  177562. *
  177563. * Tom Lane
  177564. * Glenn Randers-Pehrson
  177565. * Willem van Schaik
  177566. *
  177567. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  177568. * Copyright (c) 1996, 1997 Andreas Dilger
  177569. * Distributed according to the same disclaimer and license as libpng-0.88,
  177570. * with the following individuals added to the list of Contributing Authors:
  177571. *
  177572. * John Bowler
  177573. * Kevin Bracey
  177574. * Sam Bushell
  177575. * Magnus Holmgren
  177576. * Greg Roelofs
  177577. * Tom Tanner
  177578. *
  177579. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  177580. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  177581. *
  177582. * For the purposes of this copyright and license, "Contributing Authors"
  177583. * is defined as the following set of individuals:
  177584. *
  177585. * Andreas Dilger
  177586. * Dave Martindale
  177587. * Guy Eric Schalnat
  177588. * Paul Schmidt
  177589. * Tim Wegner
  177590. *
  177591. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  177592. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  177593. * including, without limitation, the warranties of merchantability and of
  177594. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  177595. * assume no liability for direct, indirect, incidental, special, exemplary,
  177596. * or consequential damages, which may result from the use of the PNG
  177597. * Reference Library, even if advised of the possibility of such damage.
  177598. *
  177599. * Permission is hereby granted to use, copy, modify, and distribute this
  177600. * source code, or portions hereof, for any purpose, without fee, subject
  177601. * to the following restrictions:
  177602. *
  177603. * 1. The origin of this source code must not be misrepresented.
  177604. *
  177605. * 2. Altered versions must be plainly marked as such and
  177606. * must not be misrepresented as being the original source.
  177607. *
  177608. * 3. This Copyright notice may not be removed or altered from
  177609. * any source or altered source distribution.
  177610. *
  177611. * The Contributing Authors and Group 42, Inc. specifically permit, without
  177612. * fee, and encourage the use of this source code as a component to
  177613. * supporting the PNG file format in commercial products. If you use this
  177614. * source code in a product, acknowledgment is not required but would be
  177615. * appreciated.
  177616. */
  177617. /*
  177618. * A "png_get_copyright" function is available, for convenient use in "about"
  177619. * boxes and the like:
  177620. *
  177621. * printf("%s",png_get_copyright(NULL));
  177622. *
  177623. * Also, the PNG logo (in PNG format, of course) is supplied in the
  177624. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  177625. */
  177626. /*
  177627. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  177628. * certification mark of the Open Source Initiative.
  177629. */
  177630. /*
  177631. * The contributing authors would like to thank all those who helped
  177632. * with testing, bug fixes, and patience. This wouldn't have been
  177633. * possible without all of you.
  177634. *
  177635. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  177636. */
  177637. /*
  177638. * Y2K compliance in libpng:
  177639. * =========================
  177640. *
  177641. * October 4, 2007
  177642. *
  177643. * Since the PNG Development group is an ad-hoc body, we can't make
  177644. * an official declaration.
  177645. *
  177646. * This is your unofficial assurance that libpng from version 0.71 and
  177647. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  177648. * versions were also Y2K compliant.
  177649. *
  177650. * Libpng only has three year fields. One is a 2-byte unsigned integer
  177651. * that will hold years up to 65535. The other two hold the date in text
  177652. * format, and will hold years up to 9999.
  177653. *
  177654. * The integer is
  177655. * "png_uint_16 year" in png_time_struct.
  177656. *
  177657. * The strings are
  177658. * "png_charp time_buffer" in png_struct and
  177659. * "near_time_buffer", which is a local character string in png.c.
  177660. *
  177661. * There are seven time-related functions:
  177662. * png.c: png_convert_to_rfc_1123() in png.c
  177663. * (formerly png_convert_to_rfc_1152() in error)
  177664. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  177665. * png_convert_from_time_t() in pngwrite.c
  177666. * png_get_tIME() in pngget.c
  177667. * png_handle_tIME() in pngrutil.c, called in pngread.c
  177668. * png_set_tIME() in pngset.c
  177669. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  177670. *
  177671. * All handle dates properly in a Y2K environment. The
  177672. * png_convert_from_time_t() function calls gmtime() to convert from system
  177673. * clock time, which returns (year - 1900), which we properly convert to
  177674. * the full 4-digit year. There is a possibility that applications using
  177675. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  177676. * function, or that they are incorrectly passing only a 2-digit year
  177677. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  177678. * but this is not under our control. The libpng documentation has always
  177679. * stated that it works with 4-digit years, and the APIs have been
  177680. * documented as such.
  177681. *
  177682. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  177683. * integer to hold the year, and can hold years as large as 65535.
  177684. *
  177685. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  177686. * no date-related code.
  177687. *
  177688. * Glenn Randers-Pehrson
  177689. * libpng maintainer
  177690. * PNG Development Group
  177691. */
  177692. #ifndef PNG_H
  177693. #define PNG_H
  177694. /* This is not the place to learn how to use libpng. The file libpng.txt
  177695. * describes how to use libpng, and the file example.c summarizes it
  177696. * with some code on which to build. This file is useful for looking
  177697. * at the actual function definitions and structure components.
  177698. */
  177699. /* Version information for png.h - this should match the version in png.c */
  177700. #define PNG_LIBPNG_VER_STRING "1.2.21"
  177701. #define PNG_HEADER_VERSION_STRING \
  177702. " libpng version 1.2.21 - October 4, 2007\n"
  177703. #define PNG_LIBPNG_VER_SONUM 0
  177704. #define PNG_LIBPNG_VER_DLLNUM 13
  177705. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  177706. #define PNG_LIBPNG_VER_MAJOR 1
  177707. #define PNG_LIBPNG_VER_MINOR 2
  177708. #define PNG_LIBPNG_VER_RELEASE 21
  177709. /* This should match the numeric part of the final component of
  177710. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  177711. #define PNG_LIBPNG_VER_BUILD 0
  177712. /* Release Status */
  177713. #define PNG_LIBPNG_BUILD_ALPHA 1
  177714. #define PNG_LIBPNG_BUILD_BETA 2
  177715. #define PNG_LIBPNG_BUILD_RC 3
  177716. #define PNG_LIBPNG_BUILD_STABLE 4
  177717. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  177718. /* Release-Specific Flags */
  177719. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  177720. PNG_LIBPNG_BUILD_STABLE only */
  177721. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  177722. PNG_LIBPNG_BUILD_SPECIAL */
  177723. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  177724. PNG_LIBPNG_BUILD_PRIVATE */
  177725. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  177726. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  177727. * We must not include leading zeros.
  177728. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  177729. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  177730. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  177731. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  177732. #ifndef PNG_VERSION_INFO_ONLY
  177733. /* include the compression library's header */
  177734. #endif
  177735. /* include all user configurable info, including optional assembler routines */
  177736. /*** Start of inlined file: pngconf.h ***/
  177737. /* pngconf.h - machine configurable file for libpng
  177738. *
  177739. * libpng version 1.2.21 - October 4, 2007
  177740. * For conditions of distribution and use, see copyright notice in png.h
  177741. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  177742. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  177743. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  177744. */
  177745. /* Any machine specific code is near the front of this file, so if you
  177746. * are configuring libpng for a machine, you may want to read the section
  177747. * starting here down to where it starts to typedef png_color, png_text,
  177748. * and png_info.
  177749. */
  177750. #ifndef PNGCONF_H
  177751. #define PNGCONF_H
  177752. #define PNG_1_2_X
  177753. // These are some Juce config settings that should remove any unnecessary code bloat..
  177754. #define PNG_NO_STDIO 1
  177755. #define PNG_DEBUG 0
  177756. #define PNG_NO_WARNINGS 1
  177757. #define PNG_NO_ERROR_TEXT 1
  177758. #define PNG_NO_ERROR_NUMBERS 1
  177759. #define PNG_NO_USER_MEM 1
  177760. #define PNG_NO_READ_iCCP 1
  177761. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  177762. #define PNG_NO_READ_USER_CHUNKS 1
  177763. #define PNG_NO_READ_iTXt 1
  177764. #define PNG_NO_READ_sCAL 1
  177765. #define PNG_NO_READ_sPLT 1
  177766. #define png_error(a, b) png_err(a)
  177767. #define png_warning(a, b)
  177768. #define png_chunk_error(a, b) png_err(a)
  177769. #define png_chunk_warning(a, b)
  177770. /*
  177771. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  177772. * includes the resource compiler for Windows DLL configurations.
  177773. */
  177774. #ifdef PNG_USER_CONFIG
  177775. # ifndef PNG_USER_PRIVATEBUILD
  177776. # define PNG_USER_PRIVATEBUILD
  177777. # endif
  177778. #include "pngusr.h"
  177779. #endif
  177780. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  177781. #ifdef PNG_CONFIGURE_LIBPNG
  177782. #ifdef HAVE_CONFIG_H
  177783. #include "config.h"
  177784. #endif
  177785. #endif
  177786. /*
  177787. * Added at libpng-1.2.8
  177788. *
  177789. * If you create a private DLL you need to define in "pngusr.h" the followings:
  177790. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  177791. * the DLL was built>
  177792. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  177793. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  177794. * distinguish your DLL from those of the official release. These
  177795. * correspond to the trailing letters that come after the version
  177796. * number and must match your private DLL name>
  177797. * e.g. // private DLL "libpng13gx.dll"
  177798. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  177799. *
  177800. * The following macros are also at your disposal if you want to complete the
  177801. * DLL VERSIONINFO structure.
  177802. * - PNG_USER_VERSIONINFO_COMMENTS
  177803. * - PNG_USER_VERSIONINFO_COMPANYNAME
  177804. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  177805. */
  177806. #ifdef __STDC__
  177807. #ifdef SPECIALBUILD
  177808. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  177809. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  177810. #endif
  177811. #ifdef PRIVATEBUILD
  177812. # pragma message("PRIVATEBUILD is deprecated.\
  177813. Use PNG_USER_PRIVATEBUILD instead.")
  177814. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  177815. #endif
  177816. #endif /* __STDC__ */
  177817. #ifndef PNG_VERSION_INFO_ONLY
  177818. /* End of material added to libpng-1.2.8 */
  177819. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  177820. Restored at libpng-1.2.21 */
  177821. # define PNG_WARN_UNINITIALIZED_ROW 1
  177822. /* End of material added at libpng-1.2.19/1.2.21 */
  177823. /* This is the size of the compression buffer, and thus the size of
  177824. * an IDAT chunk. Make this whatever size you feel is best for your
  177825. * machine. One of these will be allocated per png_struct. When this
  177826. * is full, it writes the data to the disk, and does some other
  177827. * calculations. Making this an extremely small size will slow
  177828. * the library down, but you may want to experiment to determine
  177829. * where it becomes significant, if you are concerned with memory
  177830. * usage. Note that zlib allocates at least 32Kb also. For readers,
  177831. * this describes the size of the buffer available to read the data in.
  177832. * Unless this gets smaller than the size of a row (compressed),
  177833. * it should not make much difference how big this is.
  177834. */
  177835. #ifndef PNG_ZBUF_SIZE
  177836. # define PNG_ZBUF_SIZE 8192
  177837. #endif
  177838. /* Enable if you want a write-only libpng */
  177839. #ifndef PNG_NO_READ_SUPPORTED
  177840. # define PNG_READ_SUPPORTED
  177841. #endif
  177842. /* Enable if you want a read-only libpng */
  177843. #ifndef PNG_NO_WRITE_SUPPORTED
  177844. # define PNG_WRITE_SUPPORTED
  177845. #endif
  177846. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  177847. support PNGs that are embedded in MNG datastreams */
  177848. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  177849. # ifndef PNG_MNG_FEATURES_SUPPORTED
  177850. # define PNG_MNG_FEATURES_SUPPORTED
  177851. # endif
  177852. #endif
  177853. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  177854. # ifndef PNG_FLOATING_POINT_SUPPORTED
  177855. # define PNG_FLOATING_POINT_SUPPORTED
  177856. # endif
  177857. #endif
  177858. /* If you are running on a machine where you cannot allocate more
  177859. * than 64K of memory at once, uncomment this. While libpng will not
  177860. * normally need that much memory in a chunk (unless you load up a very
  177861. * large file), zlib needs to know how big of a chunk it can use, and
  177862. * libpng thus makes sure to check any memory allocation to verify it
  177863. * will fit into memory.
  177864. #define PNG_MAX_MALLOC_64K
  177865. */
  177866. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  177867. # define PNG_MAX_MALLOC_64K
  177868. #endif
  177869. /* Special munging to support doing things the 'cygwin' way:
  177870. * 'Normal' png-on-win32 defines/defaults:
  177871. * PNG_BUILD_DLL -- building dll
  177872. * PNG_USE_DLL -- building an application, linking to dll
  177873. * (no define) -- building static library, or building an
  177874. * application and linking to the static lib
  177875. * 'Cygwin' defines/defaults:
  177876. * PNG_BUILD_DLL -- (ignored) building the dll
  177877. * (no define) -- (ignored) building an application, linking to the dll
  177878. * PNG_STATIC -- (ignored) building the static lib, or building an
  177879. * application that links to the static lib.
  177880. * ALL_STATIC -- (ignored) building various static libs, or building an
  177881. * application that links to the static libs.
  177882. * Thus,
  177883. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  177884. * this bit of #ifdefs will define the 'correct' config variables based on
  177885. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  177886. * unnecessary.
  177887. *
  177888. * Also, the precedence order is:
  177889. * ALL_STATIC (since we can't #undef something outside our namespace)
  177890. * PNG_BUILD_DLL
  177891. * PNG_STATIC
  177892. * (nothing) == PNG_USE_DLL
  177893. *
  177894. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  177895. * of auto-import in binutils, we no longer need to worry about
  177896. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  177897. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  177898. * to __declspec() stuff. However, we DO need to worry about
  177899. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  177900. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  177901. */
  177902. #if defined(__CYGWIN__)
  177903. # if defined(ALL_STATIC)
  177904. # if defined(PNG_BUILD_DLL)
  177905. # undef PNG_BUILD_DLL
  177906. # endif
  177907. # if defined(PNG_USE_DLL)
  177908. # undef PNG_USE_DLL
  177909. # endif
  177910. # if defined(PNG_DLL)
  177911. # undef PNG_DLL
  177912. # endif
  177913. # if !defined(PNG_STATIC)
  177914. # define PNG_STATIC
  177915. # endif
  177916. # else
  177917. # if defined (PNG_BUILD_DLL)
  177918. # if defined(PNG_STATIC)
  177919. # undef PNG_STATIC
  177920. # endif
  177921. # if defined(PNG_USE_DLL)
  177922. # undef PNG_USE_DLL
  177923. # endif
  177924. # if !defined(PNG_DLL)
  177925. # define PNG_DLL
  177926. # endif
  177927. # else
  177928. # if defined(PNG_STATIC)
  177929. # if defined(PNG_USE_DLL)
  177930. # undef PNG_USE_DLL
  177931. # endif
  177932. # if defined(PNG_DLL)
  177933. # undef PNG_DLL
  177934. # endif
  177935. # else
  177936. # if !defined(PNG_USE_DLL)
  177937. # define PNG_USE_DLL
  177938. # endif
  177939. # if !defined(PNG_DLL)
  177940. # define PNG_DLL
  177941. # endif
  177942. # endif
  177943. # endif
  177944. # endif
  177945. #endif
  177946. /* This protects us against compilers that run on a windowing system
  177947. * and thus don't have or would rather us not use the stdio types:
  177948. * stdin, stdout, and stderr. The only one currently used is stderr
  177949. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  177950. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  177951. * will also prevent these, plus will prevent the entire set of stdio
  177952. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  177953. * unless (PNG_DEBUG > 0) has been #defined.
  177954. *
  177955. * #define PNG_NO_CONSOLE_IO
  177956. * #define PNG_NO_STDIO
  177957. */
  177958. #if defined(_WIN32_WCE)
  177959. # include <windows.h>
  177960. /* Console I/O functions are not supported on WindowsCE */
  177961. # define PNG_NO_CONSOLE_IO
  177962. # ifdef PNG_DEBUG
  177963. # undef PNG_DEBUG
  177964. # endif
  177965. #endif
  177966. #ifdef PNG_BUILD_DLL
  177967. # ifndef PNG_CONSOLE_IO_SUPPORTED
  177968. # ifndef PNG_NO_CONSOLE_IO
  177969. # define PNG_NO_CONSOLE_IO
  177970. # endif
  177971. # endif
  177972. #endif
  177973. # ifdef PNG_NO_STDIO
  177974. # ifndef PNG_NO_CONSOLE_IO
  177975. # define PNG_NO_CONSOLE_IO
  177976. # endif
  177977. # ifdef PNG_DEBUG
  177978. # if (PNG_DEBUG > 0)
  177979. # include <stdio.h>
  177980. # endif
  177981. # endif
  177982. # else
  177983. # if !defined(_WIN32_WCE)
  177984. /* "stdio.h" functions are not supported on WindowsCE */
  177985. # include <stdio.h>
  177986. # endif
  177987. # endif
  177988. /* This macro protects us against machines that don't have function
  177989. * prototypes (ie K&R style headers). If your compiler does not handle
  177990. * function prototypes, define this macro and use the included ansi2knr.
  177991. * I've always been able to use _NO_PROTO as the indicator, but you may
  177992. * need to drag the empty declaration out in front of here, or change the
  177993. * ifdef to suit your own needs.
  177994. */
  177995. #ifndef PNGARG
  177996. #ifdef OF /* zlib prototype munger */
  177997. # define PNGARG(arglist) OF(arglist)
  177998. #else
  177999. #ifdef _NO_PROTO
  178000. # define PNGARG(arglist) ()
  178001. # ifndef PNG_TYPECAST_NULL
  178002. # define PNG_TYPECAST_NULL
  178003. # endif
  178004. #else
  178005. # define PNGARG(arglist) arglist
  178006. #endif /* _NO_PROTO */
  178007. #endif /* OF */
  178008. #endif /* PNGARG */
  178009. /* Try to determine if we are compiling on a Mac. Note that testing for
  178010. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  178011. * on non-Mac platforms.
  178012. */
  178013. #ifndef MACOS
  178014. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  178015. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  178016. # define MACOS
  178017. # endif
  178018. #endif
  178019. /* enough people need this for various reasons to include it here */
  178020. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  178021. # include <sys/types.h>
  178022. #endif
  178023. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  178024. # define PNG_SETJMP_SUPPORTED
  178025. #endif
  178026. #ifdef PNG_SETJMP_SUPPORTED
  178027. /* This is an attempt to force a single setjmp behaviour on Linux. If
  178028. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  178029. */
  178030. # ifdef __linux__
  178031. # ifdef _BSD_SOURCE
  178032. # define PNG_SAVE_BSD_SOURCE
  178033. # undef _BSD_SOURCE
  178034. # endif
  178035. # ifdef _SETJMP_H
  178036. /* If you encounter a compiler error here, see the explanation
  178037. * near the end of INSTALL.
  178038. */
  178039. __png.h__ already includes setjmp.h;
  178040. __dont__ include it again.;
  178041. # endif
  178042. # endif /* __linux__ */
  178043. /* include setjmp.h for error handling */
  178044. # include <setjmp.h>
  178045. # ifdef __linux__
  178046. # ifdef PNG_SAVE_BSD_SOURCE
  178047. # define _BSD_SOURCE
  178048. # undef PNG_SAVE_BSD_SOURCE
  178049. # endif
  178050. # endif /* __linux__ */
  178051. #endif /* PNG_SETJMP_SUPPORTED */
  178052. #ifdef BSD
  178053. #if ! JUCE_MAC
  178054. # include <strings.h>
  178055. #endif
  178056. #else
  178057. # include <string.h>
  178058. #endif
  178059. /* Other defines for things like memory and the like can go here. */
  178060. #ifdef PNG_INTERNAL
  178061. #include <stdlib.h>
  178062. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  178063. * aren't usually used outside the library (as far as I know), so it is
  178064. * debatable if they should be exported at all. In the future, when it is
  178065. * possible to have run-time registry of chunk-handling functions, some of
  178066. * these will be made available again.
  178067. #define PNG_EXTERN extern
  178068. */
  178069. #define PNG_EXTERN
  178070. /* Other defines specific to compilers can go here. Try to keep
  178071. * them inside an appropriate ifdef/endif pair for portability.
  178072. */
  178073. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  178074. # if defined(MACOS)
  178075. /* We need to check that <math.h> hasn't already been included earlier
  178076. * as it seems it doesn't agree with <fp.h>, yet we should really use
  178077. * <fp.h> if possible.
  178078. */
  178079. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  178080. # include <fp.h>
  178081. # endif
  178082. # else
  178083. # include <math.h>
  178084. # endif
  178085. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  178086. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  178087. * MATH=68881
  178088. */
  178089. # include <m68881.h>
  178090. # endif
  178091. #endif
  178092. /* Codewarrior on NT has linking problems without this. */
  178093. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  178094. # define PNG_ALWAYS_EXTERN
  178095. #endif
  178096. /* This provides the non-ANSI (far) memory allocation routines. */
  178097. #if defined(__TURBOC__) && defined(__MSDOS__)
  178098. # include <mem.h>
  178099. # include <alloc.h>
  178100. #endif
  178101. /* I have no idea why is this necessary... */
  178102. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  178103. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  178104. # include <malloc.h>
  178105. #endif
  178106. /* This controls how fine the dithering gets. As this allocates
  178107. * a largish chunk of memory (32K), those who are not as concerned
  178108. * with dithering quality can decrease some or all of these.
  178109. */
  178110. #ifndef PNG_DITHER_RED_BITS
  178111. # define PNG_DITHER_RED_BITS 5
  178112. #endif
  178113. #ifndef PNG_DITHER_GREEN_BITS
  178114. # define PNG_DITHER_GREEN_BITS 5
  178115. #endif
  178116. #ifndef PNG_DITHER_BLUE_BITS
  178117. # define PNG_DITHER_BLUE_BITS 5
  178118. #endif
  178119. /* This controls how fine the gamma correction becomes when you
  178120. * are only interested in 8 bits anyway. Increasing this value
  178121. * results in more memory being used, and more pow() functions
  178122. * being called to fill in the gamma tables. Don't set this value
  178123. * less then 8, and even that may not work (I haven't tested it).
  178124. */
  178125. #ifndef PNG_MAX_GAMMA_8
  178126. # define PNG_MAX_GAMMA_8 11
  178127. #endif
  178128. /* This controls how much a difference in gamma we can tolerate before
  178129. * we actually start doing gamma conversion.
  178130. */
  178131. #ifndef PNG_GAMMA_THRESHOLD
  178132. # define PNG_GAMMA_THRESHOLD 0.05
  178133. #endif
  178134. #endif /* PNG_INTERNAL */
  178135. /* The following uses const char * instead of char * for error
  178136. * and warning message functions, so some compilers won't complain.
  178137. * If you do not want to use const, define PNG_NO_CONST here.
  178138. */
  178139. #ifndef PNG_NO_CONST
  178140. # define PNG_CONST const
  178141. #else
  178142. # define PNG_CONST
  178143. #endif
  178144. /* The following defines give you the ability to remove code from the
  178145. * library that you will not be using. I wish I could figure out how to
  178146. * automate this, but I can't do that without making it seriously hard
  178147. * on the users. So if you are not using an ability, change the #define
  178148. * to and #undef, and that part of the library will not be compiled. If
  178149. * your linker can't find a function, you may want to make sure the
  178150. * ability is defined here. Some of these depend upon some others being
  178151. * defined. I haven't figured out all the interactions here, so you may
  178152. * have to experiment awhile to get everything to compile. If you are
  178153. * creating or using a shared library, you probably shouldn't touch this,
  178154. * as it will affect the size of the structures, and this will cause bad
  178155. * things to happen if the library and/or application ever change.
  178156. */
  178157. /* Any features you will not be using can be undef'ed here */
  178158. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  178159. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  178160. * on the compile line, then pick and choose which ones to define without
  178161. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  178162. * if you only want to have a png-compliant reader/writer but don't need
  178163. * any of the extra transformations. This saves about 80 kbytes in a
  178164. * typical installation of the library. (PNG_NO_* form added in version
  178165. * 1.0.1c, for consistency)
  178166. */
  178167. /* The size of the png_text structure changed in libpng-1.0.6 when
  178168. * iTXt support was added. iTXt support was turned off by default through
  178169. * libpng-1.2.x, to support old apps that malloc the png_text structure
  178170. * instead of calling png_set_text() and letting libpng malloc it. It
  178171. * was turned on by default in libpng-1.3.0.
  178172. */
  178173. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178174. # ifndef PNG_NO_iTXt_SUPPORTED
  178175. # define PNG_NO_iTXt_SUPPORTED
  178176. # endif
  178177. # ifndef PNG_NO_READ_iTXt
  178178. # define PNG_NO_READ_iTXt
  178179. # endif
  178180. # ifndef PNG_NO_WRITE_iTXt
  178181. # define PNG_NO_WRITE_iTXt
  178182. # endif
  178183. #endif
  178184. #if !defined(PNG_NO_iTXt_SUPPORTED)
  178185. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  178186. # define PNG_READ_iTXt
  178187. # endif
  178188. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  178189. # define PNG_WRITE_iTXt
  178190. # endif
  178191. #endif
  178192. /* The following support, added after version 1.0.0, can be turned off here en
  178193. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  178194. * with old applications that require the length of png_struct and png_info
  178195. * to remain unchanged.
  178196. */
  178197. #ifdef PNG_LEGACY_SUPPORTED
  178198. # define PNG_NO_FREE_ME
  178199. # define PNG_NO_READ_UNKNOWN_CHUNKS
  178200. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  178201. # define PNG_NO_READ_USER_CHUNKS
  178202. # define PNG_NO_READ_iCCP
  178203. # define PNG_NO_WRITE_iCCP
  178204. # define PNG_NO_READ_iTXt
  178205. # define PNG_NO_WRITE_iTXt
  178206. # define PNG_NO_READ_sCAL
  178207. # define PNG_NO_WRITE_sCAL
  178208. # define PNG_NO_READ_sPLT
  178209. # define PNG_NO_WRITE_sPLT
  178210. # define PNG_NO_INFO_IMAGE
  178211. # define PNG_NO_READ_RGB_TO_GRAY
  178212. # define PNG_NO_READ_USER_TRANSFORM
  178213. # define PNG_NO_WRITE_USER_TRANSFORM
  178214. # define PNG_NO_USER_MEM
  178215. # define PNG_NO_READ_EMPTY_PLTE
  178216. # define PNG_NO_MNG_FEATURES
  178217. # define PNG_NO_FIXED_POINT_SUPPORTED
  178218. #endif
  178219. /* Ignore attempt to turn off both floating and fixed point support */
  178220. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  178221. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  178222. # define PNG_FIXED_POINT_SUPPORTED
  178223. #endif
  178224. #ifndef PNG_NO_FREE_ME
  178225. # define PNG_FREE_ME_SUPPORTED
  178226. #endif
  178227. #if defined(PNG_READ_SUPPORTED)
  178228. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  178229. !defined(PNG_NO_READ_TRANSFORMS)
  178230. # define PNG_READ_TRANSFORMS_SUPPORTED
  178231. #endif
  178232. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  178233. # ifndef PNG_NO_READ_EXPAND
  178234. # define PNG_READ_EXPAND_SUPPORTED
  178235. # endif
  178236. # ifndef PNG_NO_READ_SHIFT
  178237. # define PNG_READ_SHIFT_SUPPORTED
  178238. # endif
  178239. # ifndef PNG_NO_READ_PACK
  178240. # define PNG_READ_PACK_SUPPORTED
  178241. # endif
  178242. # ifndef PNG_NO_READ_BGR
  178243. # define PNG_READ_BGR_SUPPORTED
  178244. # endif
  178245. # ifndef PNG_NO_READ_SWAP
  178246. # define PNG_READ_SWAP_SUPPORTED
  178247. # endif
  178248. # ifndef PNG_NO_READ_PACKSWAP
  178249. # define PNG_READ_PACKSWAP_SUPPORTED
  178250. # endif
  178251. # ifndef PNG_NO_READ_INVERT
  178252. # define PNG_READ_INVERT_SUPPORTED
  178253. # endif
  178254. # ifndef PNG_NO_READ_DITHER
  178255. # define PNG_READ_DITHER_SUPPORTED
  178256. # endif
  178257. # ifndef PNG_NO_READ_BACKGROUND
  178258. # define PNG_READ_BACKGROUND_SUPPORTED
  178259. # endif
  178260. # ifndef PNG_NO_READ_16_TO_8
  178261. # define PNG_READ_16_TO_8_SUPPORTED
  178262. # endif
  178263. # ifndef PNG_NO_READ_FILLER
  178264. # define PNG_READ_FILLER_SUPPORTED
  178265. # endif
  178266. # ifndef PNG_NO_READ_GAMMA
  178267. # define PNG_READ_GAMMA_SUPPORTED
  178268. # endif
  178269. # ifndef PNG_NO_READ_GRAY_TO_RGB
  178270. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  178271. # endif
  178272. # ifndef PNG_NO_READ_SWAP_ALPHA
  178273. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  178274. # endif
  178275. # ifndef PNG_NO_READ_INVERT_ALPHA
  178276. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  178277. # endif
  178278. # ifndef PNG_NO_READ_STRIP_ALPHA
  178279. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  178280. # endif
  178281. # ifndef PNG_NO_READ_USER_TRANSFORM
  178282. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  178283. # endif
  178284. # ifndef PNG_NO_READ_RGB_TO_GRAY
  178285. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  178286. # endif
  178287. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  178288. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  178289. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  178290. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  178291. #endif /* about interlacing capability! You'll */
  178292. /* still have interlacing unless you change the following line: */
  178293. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  178294. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  178295. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  178296. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  178297. # endif
  178298. #endif
  178299. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178300. /* Deprecated, will be removed from version 2.0.0.
  178301. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  178302. #ifndef PNG_NO_READ_EMPTY_PLTE
  178303. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  178304. #endif
  178305. #endif
  178306. #endif /* PNG_READ_SUPPORTED */
  178307. #if defined(PNG_WRITE_SUPPORTED)
  178308. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  178309. !defined(PNG_NO_WRITE_TRANSFORMS)
  178310. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  178311. #endif
  178312. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  178313. # ifndef PNG_NO_WRITE_SHIFT
  178314. # define PNG_WRITE_SHIFT_SUPPORTED
  178315. # endif
  178316. # ifndef PNG_NO_WRITE_PACK
  178317. # define PNG_WRITE_PACK_SUPPORTED
  178318. # endif
  178319. # ifndef PNG_NO_WRITE_BGR
  178320. # define PNG_WRITE_BGR_SUPPORTED
  178321. # endif
  178322. # ifndef PNG_NO_WRITE_SWAP
  178323. # define PNG_WRITE_SWAP_SUPPORTED
  178324. # endif
  178325. # ifndef PNG_NO_WRITE_PACKSWAP
  178326. # define PNG_WRITE_PACKSWAP_SUPPORTED
  178327. # endif
  178328. # ifndef PNG_NO_WRITE_INVERT
  178329. # define PNG_WRITE_INVERT_SUPPORTED
  178330. # endif
  178331. # ifndef PNG_NO_WRITE_FILLER
  178332. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  178333. # endif
  178334. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  178335. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  178336. # endif
  178337. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  178338. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  178339. # endif
  178340. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  178341. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  178342. # endif
  178343. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  178344. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  178345. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  178346. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  178347. encoders, but can cause trouble
  178348. if left undefined */
  178349. #endif
  178350. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  178351. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  178352. defined(PNG_FLOATING_POINT_SUPPORTED)
  178353. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  178354. #endif
  178355. #ifndef PNG_NO_WRITE_FLUSH
  178356. # define PNG_WRITE_FLUSH_SUPPORTED
  178357. #endif
  178358. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178359. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  178360. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  178361. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  178362. #endif
  178363. #endif
  178364. #endif /* PNG_WRITE_SUPPORTED */
  178365. #ifndef PNG_1_0_X
  178366. # ifndef PNG_NO_ERROR_NUMBERS
  178367. # define PNG_ERROR_NUMBERS_SUPPORTED
  178368. # endif
  178369. #endif /* PNG_1_0_X */
  178370. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  178371. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  178372. # ifndef PNG_NO_USER_TRANSFORM_PTR
  178373. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  178374. # endif
  178375. #endif
  178376. #ifndef PNG_NO_STDIO
  178377. # define PNG_TIME_RFC1123_SUPPORTED
  178378. #endif
  178379. /* This adds extra functions in pngget.c for accessing data from the
  178380. * info pointer (added in version 0.99)
  178381. * png_get_image_width()
  178382. * png_get_image_height()
  178383. * png_get_bit_depth()
  178384. * png_get_color_type()
  178385. * png_get_compression_type()
  178386. * png_get_filter_type()
  178387. * png_get_interlace_type()
  178388. * png_get_pixel_aspect_ratio()
  178389. * png_get_pixels_per_meter()
  178390. * png_get_x_offset_pixels()
  178391. * png_get_y_offset_pixels()
  178392. * png_get_x_offset_microns()
  178393. * png_get_y_offset_microns()
  178394. */
  178395. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  178396. # define PNG_EASY_ACCESS_SUPPORTED
  178397. #endif
  178398. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  178399. * and removed from version 1.2.20. The following will be removed
  178400. * from libpng-1.4.0
  178401. */
  178402. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  178403. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  178404. # define PNG_OPTIMIZED_CODE_SUPPORTED
  178405. # endif
  178406. #endif
  178407. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  178408. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  178409. # define PNG_ASSEMBLER_CODE_SUPPORTED
  178410. # endif
  178411. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  178412. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  178413. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  178414. # define PNG_NO_MMX_CODE
  178415. # endif
  178416. # endif
  178417. # if defined(__APPLE__)
  178418. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  178419. # define PNG_NO_MMX_CODE
  178420. # endif
  178421. # endif
  178422. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  178423. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  178424. # define PNG_NO_MMX_CODE
  178425. # endif
  178426. # endif
  178427. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  178428. # define PNG_MMX_CODE_SUPPORTED
  178429. # endif
  178430. #endif
  178431. /* end of obsolete code to be removed from libpng-1.4.0 */
  178432. #if !defined(PNG_1_0_X)
  178433. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  178434. # define PNG_USER_MEM_SUPPORTED
  178435. #endif
  178436. #endif /* PNG_1_0_X */
  178437. /* Added at libpng-1.2.6 */
  178438. #if !defined(PNG_1_0_X)
  178439. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  178440. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  178441. # define PNG_SET_USER_LIMITS_SUPPORTED
  178442. #endif
  178443. #endif
  178444. #endif /* PNG_1_0_X */
  178445. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  178446. * how large, set these limits to 0x7fffffffL
  178447. */
  178448. #ifndef PNG_USER_WIDTH_MAX
  178449. # define PNG_USER_WIDTH_MAX 1000000L
  178450. #endif
  178451. #ifndef PNG_USER_HEIGHT_MAX
  178452. # define PNG_USER_HEIGHT_MAX 1000000L
  178453. #endif
  178454. /* These are currently experimental features, define them if you want */
  178455. /* very little testing */
  178456. /*
  178457. #ifdef PNG_READ_SUPPORTED
  178458. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  178459. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  178460. # endif
  178461. #endif
  178462. */
  178463. /* This is only for PowerPC big-endian and 680x0 systems */
  178464. /* some testing */
  178465. /*
  178466. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  178467. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  178468. #endif
  178469. */
  178470. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  178471. /*
  178472. #define PNG_NO_POINTER_INDEXING
  178473. */
  178474. /* These functions are turned off by default, as they will be phased out. */
  178475. /*
  178476. #define PNG_USELESS_TESTS_SUPPORTED
  178477. #define PNG_CORRECT_PALETTE_SUPPORTED
  178478. */
  178479. /* Any chunks you are not interested in, you can undef here. The
  178480. * ones that allocate memory may be expecially important (hIST,
  178481. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  178482. * a bit smaller.
  178483. */
  178484. #if defined(PNG_READ_SUPPORTED) && \
  178485. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  178486. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  178487. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  178488. #endif
  178489. #if defined(PNG_WRITE_SUPPORTED) && \
  178490. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  178491. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  178492. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  178493. #endif
  178494. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  178495. #ifdef PNG_NO_READ_TEXT
  178496. # define PNG_NO_READ_iTXt
  178497. # define PNG_NO_READ_tEXt
  178498. # define PNG_NO_READ_zTXt
  178499. #endif
  178500. #ifndef PNG_NO_READ_bKGD
  178501. # define PNG_READ_bKGD_SUPPORTED
  178502. # define PNG_bKGD_SUPPORTED
  178503. #endif
  178504. #ifndef PNG_NO_READ_cHRM
  178505. # define PNG_READ_cHRM_SUPPORTED
  178506. # define PNG_cHRM_SUPPORTED
  178507. #endif
  178508. #ifndef PNG_NO_READ_gAMA
  178509. # define PNG_READ_gAMA_SUPPORTED
  178510. # define PNG_gAMA_SUPPORTED
  178511. #endif
  178512. #ifndef PNG_NO_READ_hIST
  178513. # define PNG_READ_hIST_SUPPORTED
  178514. # define PNG_hIST_SUPPORTED
  178515. #endif
  178516. #ifndef PNG_NO_READ_iCCP
  178517. # define PNG_READ_iCCP_SUPPORTED
  178518. # define PNG_iCCP_SUPPORTED
  178519. #endif
  178520. #ifndef PNG_NO_READ_iTXt
  178521. # ifndef PNG_READ_iTXt_SUPPORTED
  178522. # define PNG_READ_iTXt_SUPPORTED
  178523. # endif
  178524. # ifndef PNG_iTXt_SUPPORTED
  178525. # define PNG_iTXt_SUPPORTED
  178526. # endif
  178527. #endif
  178528. #ifndef PNG_NO_READ_oFFs
  178529. # define PNG_READ_oFFs_SUPPORTED
  178530. # define PNG_oFFs_SUPPORTED
  178531. #endif
  178532. #ifndef PNG_NO_READ_pCAL
  178533. # define PNG_READ_pCAL_SUPPORTED
  178534. # define PNG_pCAL_SUPPORTED
  178535. #endif
  178536. #ifndef PNG_NO_READ_sCAL
  178537. # define PNG_READ_sCAL_SUPPORTED
  178538. # define PNG_sCAL_SUPPORTED
  178539. #endif
  178540. #ifndef PNG_NO_READ_pHYs
  178541. # define PNG_READ_pHYs_SUPPORTED
  178542. # define PNG_pHYs_SUPPORTED
  178543. #endif
  178544. #ifndef PNG_NO_READ_sBIT
  178545. # define PNG_READ_sBIT_SUPPORTED
  178546. # define PNG_sBIT_SUPPORTED
  178547. #endif
  178548. #ifndef PNG_NO_READ_sPLT
  178549. # define PNG_READ_sPLT_SUPPORTED
  178550. # define PNG_sPLT_SUPPORTED
  178551. #endif
  178552. #ifndef PNG_NO_READ_sRGB
  178553. # define PNG_READ_sRGB_SUPPORTED
  178554. # define PNG_sRGB_SUPPORTED
  178555. #endif
  178556. #ifndef PNG_NO_READ_tEXt
  178557. # define PNG_READ_tEXt_SUPPORTED
  178558. # define PNG_tEXt_SUPPORTED
  178559. #endif
  178560. #ifndef PNG_NO_READ_tIME
  178561. # define PNG_READ_tIME_SUPPORTED
  178562. # define PNG_tIME_SUPPORTED
  178563. #endif
  178564. #ifndef PNG_NO_READ_tRNS
  178565. # define PNG_READ_tRNS_SUPPORTED
  178566. # define PNG_tRNS_SUPPORTED
  178567. #endif
  178568. #ifndef PNG_NO_READ_zTXt
  178569. # define PNG_READ_zTXt_SUPPORTED
  178570. # define PNG_zTXt_SUPPORTED
  178571. #endif
  178572. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  178573. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  178574. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  178575. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  178576. # endif
  178577. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  178578. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  178579. # endif
  178580. #endif
  178581. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  178582. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  178583. # define PNG_READ_USER_CHUNKS_SUPPORTED
  178584. # define PNG_USER_CHUNKS_SUPPORTED
  178585. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  178586. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  178587. # endif
  178588. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  178589. # undef PNG_NO_HANDLE_AS_UNKNOWN
  178590. # endif
  178591. #endif
  178592. #ifndef PNG_NO_READ_OPT_PLTE
  178593. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  178594. #endif /* optional PLTE chunk in RGB and RGBA images */
  178595. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  178596. defined(PNG_READ_zTXt_SUPPORTED)
  178597. # define PNG_READ_TEXT_SUPPORTED
  178598. # define PNG_TEXT_SUPPORTED
  178599. #endif
  178600. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  178601. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  178602. #ifdef PNG_NO_WRITE_TEXT
  178603. # define PNG_NO_WRITE_iTXt
  178604. # define PNG_NO_WRITE_tEXt
  178605. # define PNG_NO_WRITE_zTXt
  178606. #endif
  178607. #ifndef PNG_NO_WRITE_bKGD
  178608. # define PNG_WRITE_bKGD_SUPPORTED
  178609. # ifndef PNG_bKGD_SUPPORTED
  178610. # define PNG_bKGD_SUPPORTED
  178611. # endif
  178612. #endif
  178613. #ifndef PNG_NO_WRITE_cHRM
  178614. # define PNG_WRITE_cHRM_SUPPORTED
  178615. # ifndef PNG_cHRM_SUPPORTED
  178616. # define PNG_cHRM_SUPPORTED
  178617. # endif
  178618. #endif
  178619. #ifndef PNG_NO_WRITE_gAMA
  178620. # define PNG_WRITE_gAMA_SUPPORTED
  178621. # ifndef PNG_gAMA_SUPPORTED
  178622. # define PNG_gAMA_SUPPORTED
  178623. # endif
  178624. #endif
  178625. #ifndef PNG_NO_WRITE_hIST
  178626. # define PNG_WRITE_hIST_SUPPORTED
  178627. # ifndef PNG_hIST_SUPPORTED
  178628. # define PNG_hIST_SUPPORTED
  178629. # endif
  178630. #endif
  178631. #ifndef PNG_NO_WRITE_iCCP
  178632. # define PNG_WRITE_iCCP_SUPPORTED
  178633. # ifndef PNG_iCCP_SUPPORTED
  178634. # define PNG_iCCP_SUPPORTED
  178635. # endif
  178636. #endif
  178637. #ifndef PNG_NO_WRITE_iTXt
  178638. # ifndef PNG_WRITE_iTXt_SUPPORTED
  178639. # define PNG_WRITE_iTXt_SUPPORTED
  178640. # endif
  178641. # ifndef PNG_iTXt_SUPPORTED
  178642. # define PNG_iTXt_SUPPORTED
  178643. # endif
  178644. #endif
  178645. #ifndef PNG_NO_WRITE_oFFs
  178646. # define PNG_WRITE_oFFs_SUPPORTED
  178647. # ifndef PNG_oFFs_SUPPORTED
  178648. # define PNG_oFFs_SUPPORTED
  178649. # endif
  178650. #endif
  178651. #ifndef PNG_NO_WRITE_pCAL
  178652. # define PNG_WRITE_pCAL_SUPPORTED
  178653. # ifndef PNG_pCAL_SUPPORTED
  178654. # define PNG_pCAL_SUPPORTED
  178655. # endif
  178656. #endif
  178657. #ifndef PNG_NO_WRITE_sCAL
  178658. # define PNG_WRITE_sCAL_SUPPORTED
  178659. # ifndef PNG_sCAL_SUPPORTED
  178660. # define PNG_sCAL_SUPPORTED
  178661. # endif
  178662. #endif
  178663. #ifndef PNG_NO_WRITE_pHYs
  178664. # define PNG_WRITE_pHYs_SUPPORTED
  178665. # ifndef PNG_pHYs_SUPPORTED
  178666. # define PNG_pHYs_SUPPORTED
  178667. # endif
  178668. #endif
  178669. #ifndef PNG_NO_WRITE_sBIT
  178670. # define PNG_WRITE_sBIT_SUPPORTED
  178671. # ifndef PNG_sBIT_SUPPORTED
  178672. # define PNG_sBIT_SUPPORTED
  178673. # endif
  178674. #endif
  178675. #ifndef PNG_NO_WRITE_sPLT
  178676. # define PNG_WRITE_sPLT_SUPPORTED
  178677. # ifndef PNG_sPLT_SUPPORTED
  178678. # define PNG_sPLT_SUPPORTED
  178679. # endif
  178680. #endif
  178681. #ifndef PNG_NO_WRITE_sRGB
  178682. # define PNG_WRITE_sRGB_SUPPORTED
  178683. # ifndef PNG_sRGB_SUPPORTED
  178684. # define PNG_sRGB_SUPPORTED
  178685. # endif
  178686. #endif
  178687. #ifndef PNG_NO_WRITE_tEXt
  178688. # define PNG_WRITE_tEXt_SUPPORTED
  178689. # ifndef PNG_tEXt_SUPPORTED
  178690. # define PNG_tEXt_SUPPORTED
  178691. # endif
  178692. #endif
  178693. #ifndef PNG_NO_WRITE_tIME
  178694. # define PNG_WRITE_tIME_SUPPORTED
  178695. # ifndef PNG_tIME_SUPPORTED
  178696. # define PNG_tIME_SUPPORTED
  178697. # endif
  178698. #endif
  178699. #ifndef PNG_NO_WRITE_tRNS
  178700. # define PNG_WRITE_tRNS_SUPPORTED
  178701. # ifndef PNG_tRNS_SUPPORTED
  178702. # define PNG_tRNS_SUPPORTED
  178703. # endif
  178704. #endif
  178705. #ifndef PNG_NO_WRITE_zTXt
  178706. # define PNG_WRITE_zTXt_SUPPORTED
  178707. # ifndef PNG_zTXt_SUPPORTED
  178708. # define PNG_zTXt_SUPPORTED
  178709. # endif
  178710. #endif
  178711. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  178712. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  178713. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  178714. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  178715. # endif
  178716. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  178717. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  178718. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  178719. # endif
  178720. # endif
  178721. #endif
  178722. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  178723. defined(PNG_WRITE_zTXt_SUPPORTED)
  178724. # define PNG_WRITE_TEXT_SUPPORTED
  178725. # ifndef PNG_TEXT_SUPPORTED
  178726. # define PNG_TEXT_SUPPORTED
  178727. # endif
  178728. #endif
  178729. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  178730. /* Turn this off to disable png_read_png() and
  178731. * png_write_png() and leave the row_pointers member
  178732. * out of the info structure.
  178733. */
  178734. #ifndef PNG_NO_INFO_IMAGE
  178735. # define PNG_INFO_IMAGE_SUPPORTED
  178736. #endif
  178737. /* need the time information for reading tIME chunks */
  178738. #if defined(PNG_tIME_SUPPORTED)
  178739. # if !defined(_WIN32_WCE)
  178740. /* "time.h" functions are not supported on WindowsCE */
  178741. # include <time.h>
  178742. # endif
  178743. #endif
  178744. /* Some typedefs to get us started. These should be safe on most of the
  178745. * common platforms. The typedefs should be at least as large as the
  178746. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  178747. * don't have to be exactly that size. Some compilers dislike passing
  178748. * unsigned shorts as function parameters, so you may be better off using
  178749. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  178750. * want to have unsigned int for png_uint_32 instead of unsigned long.
  178751. */
  178752. typedef unsigned long png_uint_32;
  178753. typedef long png_int_32;
  178754. typedef unsigned short png_uint_16;
  178755. typedef short png_int_16;
  178756. typedef unsigned char png_byte;
  178757. /* This is usually size_t. It is typedef'ed just in case you need it to
  178758. change (I'm not sure if you will or not, so I thought I'd be safe) */
  178759. #ifdef PNG_SIZE_T
  178760. typedef PNG_SIZE_T png_size_t;
  178761. # define png_sizeof(x) png_convert_size(sizeof (x))
  178762. #else
  178763. typedef size_t png_size_t;
  178764. # define png_sizeof(x) sizeof (x)
  178765. #endif
  178766. /* The following is needed for medium model support. It cannot be in the
  178767. * PNG_INTERNAL section. Needs modification for other compilers besides
  178768. * MSC. Model independent support declares all arrays and pointers to be
  178769. * large using the far keyword. The zlib version used must also support
  178770. * model independent data. As of version zlib 1.0.4, the necessary changes
  178771. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  178772. * changes that are needed. (Tim Wegner)
  178773. */
  178774. /* Separate compiler dependencies (problem here is that zlib.h always
  178775. defines FAR. (SJT) */
  178776. #ifdef __BORLANDC__
  178777. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  178778. # define LDATA 1
  178779. # else
  178780. # define LDATA 0
  178781. # endif
  178782. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  178783. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  178784. # define PNG_MAX_MALLOC_64K
  178785. # if (LDATA != 1)
  178786. # ifndef FAR
  178787. # define FAR __far
  178788. # endif
  178789. # define USE_FAR_KEYWORD
  178790. # endif /* LDATA != 1 */
  178791. /* Possibly useful for moving data out of default segment.
  178792. * Uncomment it if you want. Could also define FARDATA as
  178793. * const if your compiler supports it. (SJT)
  178794. # define FARDATA FAR
  178795. */
  178796. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  178797. #endif /* __BORLANDC__ */
  178798. /* Suggest testing for specific compiler first before testing for
  178799. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  178800. * making reliance oncertain keywords suspect. (SJT)
  178801. */
  178802. /* MSC Medium model */
  178803. #if defined(FAR)
  178804. # if defined(M_I86MM)
  178805. # define USE_FAR_KEYWORD
  178806. # define FARDATA FAR
  178807. # include <dos.h>
  178808. # endif
  178809. #endif
  178810. /* SJT: default case */
  178811. #ifndef FAR
  178812. # define FAR
  178813. #endif
  178814. /* At this point FAR is always defined */
  178815. #ifndef FARDATA
  178816. # define FARDATA
  178817. #endif
  178818. /* Typedef for floating-point numbers that are converted
  178819. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  178820. typedef png_int_32 png_fixed_point;
  178821. /* Add typedefs for pointers */
  178822. typedef void FAR * png_voidp;
  178823. typedef png_byte FAR * png_bytep;
  178824. typedef png_uint_32 FAR * png_uint_32p;
  178825. typedef png_int_32 FAR * png_int_32p;
  178826. typedef png_uint_16 FAR * png_uint_16p;
  178827. typedef png_int_16 FAR * png_int_16p;
  178828. typedef PNG_CONST char FAR * png_const_charp;
  178829. typedef char FAR * png_charp;
  178830. typedef png_fixed_point FAR * png_fixed_point_p;
  178831. #ifndef PNG_NO_STDIO
  178832. #if defined(_WIN32_WCE)
  178833. typedef HANDLE png_FILE_p;
  178834. #else
  178835. typedef FILE * png_FILE_p;
  178836. #endif
  178837. #endif
  178838. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178839. typedef double FAR * png_doublep;
  178840. #endif
  178841. /* Pointers to pointers; i.e. arrays */
  178842. typedef png_byte FAR * FAR * png_bytepp;
  178843. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  178844. typedef png_int_32 FAR * FAR * png_int_32pp;
  178845. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  178846. typedef png_int_16 FAR * FAR * png_int_16pp;
  178847. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  178848. typedef char FAR * FAR * png_charpp;
  178849. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  178850. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178851. typedef double FAR * FAR * png_doublepp;
  178852. #endif
  178853. /* Pointers to pointers to pointers; i.e., pointer to array */
  178854. typedef char FAR * FAR * FAR * png_charppp;
  178855. #if 0
  178856. /* SPC - Is this stuff deprecated? */
  178857. /* It'll be removed as of libpng-1.3.0 - GR-P */
  178858. /* libpng typedefs for types in zlib. If zlib changes
  178859. * or another compression library is used, then change these.
  178860. * Eliminates need to change all the source files.
  178861. */
  178862. typedef charf * png_zcharp;
  178863. typedef charf * FAR * png_zcharpp;
  178864. typedef z_stream FAR * png_zstreamp;
  178865. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  178866. /*
  178867. * Define PNG_BUILD_DLL if the module being built is a Windows
  178868. * LIBPNG DLL.
  178869. *
  178870. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  178871. * It is equivalent to Microsoft predefined macro _DLL that is
  178872. * automatically defined when you compile using the share
  178873. * version of the CRT (C Run-Time library)
  178874. *
  178875. * The cygwin mods make this behavior a little different:
  178876. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  178877. * Define PNG_STATIC if you are building a static library for use with cygwin,
  178878. * -or- if you are building an application that you want to link to the
  178879. * static library.
  178880. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  178881. * the other flags is defined.
  178882. */
  178883. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  178884. # define PNG_DLL
  178885. #endif
  178886. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  178887. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  178888. * command-line override
  178889. */
  178890. #if defined(__CYGWIN__)
  178891. # if !defined(PNG_STATIC)
  178892. # if defined(PNG_USE_GLOBAL_ARRAYS)
  178893. # undef PNG_USE_GLOBAL_ARRAYS
  178894. # endif
  178895. # if !defined(PNG_USE_LOCAL_ARRAYS)
  178896. # define PNG_USE_LOCAL_ARRAYS
  178897. # endif
  178898. # else
  178899. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  178900. # if defined(PNG_USE_GLOBAL_ARRAYS)
  178901. # undef PNG_USE_GLOBAL_ARRAYS
  178902. # endif
  178903. # endif
  178904. # endif
  178905. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  178906. # define PNG_USE_LOCAL_ARRAYS
  178907. # endif
  178908. #endif
  178909. /* Do not use global arrays (helps with building DLL's)
  178910. * They are no longer used in libpng itself, since version 1.0.5c,
  178911. * but might be required for some pre-1.0.5c applications.
  178912. */
  178913. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  178914. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  178915. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  178916. # define PNG_USE_LOCAL_ARRAYS
  178917. # else
  178918. # define PNG_USE_GLOBAL_ARRAYS
  178919. # endif
  178920. #endif
  178921. #if defined(__CYGWIN__)
  178922. # undef PNGAPI
  178923. # define PNGAPI __cdecl
  178924. # undef PNG_IMPEXP
  178925. # define PNG_IMPEXP
  178926. #endif
  178927. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  178928. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  178929. * Don't ignore those warnings; you must also reset the default calling
  178930. * convention in your compiler to match your PNGAPI, and you must build
  178931. * zlib and your applications the same way you build libpng.
  178932. */
  178933. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  178934. # ifndef PNG_NO_MODULEDEF
  178935. # define PNG_NO_MODULEDEF
  178936. # endif
  178937. #endif
  178938. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  178939. # define PNG_IMPEXP
  178940. #endif
  178941. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  178942. (( defined(_Windows) || defined(_WINDOWS) || \
  178943. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  178944. # ifndef PNGAPI
  178945. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  178946. # define PNGAPI __cdecl
  178947. # else
  178948. # define PNGAPI _cdecl
  178949. # endif
  178950. # endif
  178951. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  178952. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  178953. # define PNG_IMPEXP
  178954. # endif
  178955. # if !defined(PNG_IMPEXP)
  178956. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  178957. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  178958. /* Borland/Microsoft */
  178959. # if defined(_MSC_VER) || defined(__BORLANDC__)
  178960. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  178961. # define PNG_EXPORT PNG_EXPORT_TYPE1
  178962. # else
  178963. # define PNG_EXPORT PNG_EXPORT_TYPE2
  178964. # if defined(PNG_BUILD_DLL)
  178965. # define PNG_IMPEXP __export
  178966. # else
  178967. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  178968. VC++ */
  178969. # endif /* Exists in Borland C++ for
  178970. C++ classes (== huge) */
  178971. # endif
  178972. # endif
  178973. # if !defined(PNG_IMPEXP)
  178974. # if defined(PNG_BUILD_DLL)
  178975. # define PNG_IMPEXP __declspec(dllexport)
  178976. # else
  178977. # define PNG_IMPEXP __declspec(dllimport)
  178978. # endif
  178979. # endif
  178980. # endif /* PNG_IMPEXP */
  178981. #else /* !(DLL || non-cygwin WINDOWS) */
  178982. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  178983. # ifndef PNGAPI
  178984. # define PNGAPI _System
  178985. # endif
  178986. # else
  178987. # if 0 /* ... other platforms, with other meanings */
  178988. # endif
  178989. # endif
  178990. #endif
  178991. #ifndef PNGAPI
  178992. # define PNGAPI
  178993. #endif
  178994. #ifndef PNG_IMPEXP
  178995. # define PNG_IMPEXP
  178996. #endif
  178997. #ifdef PNG_BUILDSYMS
  178998. # ifndef PNG_EXPORT
  178999. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  179000. # endif
  179001. # ifdef PNG_USE_GLOBAL_ARRAYS
  179002. # ifndef PNG_EXPORT_VAR
  179003. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  179004. # endif
  179005. # endif
  179006. #endif
  179007. #ifndef PNG_EXPORT
  179008. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  179009. #endif
  179010. #ifdef PNG_USE_GLOBAL_ARRAYS
  179011. # ifndef PNG_EXPORT_VAR
  179012. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  179013. # endif
  179014. #endif
  179015. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  179016. * functions that are passed far data must be model independent.
  179017. */
  179018. #ifndef PNG_ABORT
  179019. # define PNG_ABORT() abort()
  179020. #endif
  179021. #ifdef PNG_SETJMP_SUPPORTED
  179022. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  179023. #else
  179024. # define png_jmpbuf(png_ptr) \
  179025. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  179026. #endif
  179027. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  179028. /* use this to make far-to-near assignments */
  179029. # define CHECK 1
  179030. # define NOCHECK 0
  179031. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  179032. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  179033. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  179034. # define png_strcpy _fstrcpy
  179035. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  179036. # define png_strlen _fstrlen
  179037. # define png_memcmp _fmemcmp /* SJT: added */
  179038. # define png_memcpy _fmemcpy
  179039. # define png_memset _fmemset
  179040. #else /* use the usual functions */
  179041. # define CVT_PTR(ptr) (ptr)
  179042. # define CVT_PTR_NOCHECK(ptr) (ptr)
  179043. # ifndef PNG_NO_SNPRINTF
  179044. # ifdef _MSC_VER
  179045. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  179046. # define png_snprintf2 _snprintf
  179047. # define png_snprintf6 _snprintf
  179048. # else
  179049. # define png_snprintf snprintf /* Added to v 1.2.19 */
  179050. # define png_snprintf2 snprintf
  179051. # define png_snprintf6 snprintf
  179052. # endif
  179053. # else
  179054. /* You don't have or don't want to use snprintf(). Caution: Using
  179055. * sprintf instead of snprintf exposes your application to accidental
  179056. * or malevolent buffer overflows. If you don't have snprintf()
  179057. * as a general rule you should provide one (you can get one from
  179058. * Portable OpenSSH). */
  179059. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  179060. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  179061. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  179062. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  179063. # endif
  179064. # define png_strcpy strcpy
  179065. # define png_strncpy strncpy /* Added to v 1.2.6 */
  179066. # define png_strlen strlen
  179067. # define png_memcmp memcmp /* SJT: added */
  179068. # define png_memcpy memcpy
  179069. # define png_memset memset
  179070. #endif
  179071. /* End of memory model independent support */
  179072. /* Just a little check that someone hasn't tried to define something
  179073. * contradictory.
  179074. */
  179075. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  179076. # undef PNG_ZBUF_SIZE
  179077. # define PNG_ZBUF_SIZE 65536L
  179078. #endif
  179079. /* Added at libpng-1.2.8 */
  179080. #endif /* PNG_VERSION_INFO_ONLY */
  179081. #endif /* PNGCONF_H */
  179082. /*** End of inlined file: pngconf.h ***/
  179083. #ifdef _MSC_VER
  179084. #pragma warning (disable: 4996 4100)
  179085. #endif
  179086. /*
  179087. * Added at libpng-1.2.8 */
  179088. /* Ref MSDN: Private as priority over Special
  179089. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  179090. * procedures. If this value is given, the StringFileInfo block must
  179091. * contain a PrivateBuild string.
  179092. *
  179093. * VS_FF_SPECIALBUILD File *was* built by the original company using
  179094. * standard release procedures but is a variation of the standard
  179095. * file of the same version number. If this value is given, the
  179096. * StringFileInfo block must contain a SpecialBuild string.
  179097. */
  179098. #if defined(PNG_USER_PRIVATEBUILD)
  179099. # define PNG_LIBPNG_BUILD_TYPE \
  179100. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  179101. #else
  179102. # if defined(PNG_LIBPNG_SPECIALBUILD)
  179103. # define PNG_LIBPNG_BUILD_TYPE \
  179104. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  179105. # else
  179106. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  179107. # endif
  179108. #endif
  179109. #ifndef PNG_VERSION_INFO_ONLY
  179110. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  179111. #ifdef __cplusplus
  179112. extern "C" {
  179113. #endif /* __cplusplus */
  179114. /* This file is arranged in several sections. The first section contains
  179115. * structure and type definitions. The second section contains the external
  179116. * library functions, while the third has the internal library functions,
  179117. * which applications aren't expected to use directly.
  179118. */
  179119. #ifndef PNG_NO_TYPECAST_NULL
  179120. #define int_p_NULL (int *)NULL
  179121. #define png_bytep_NULL (png_bytep)NULL
  179122. #define png_bytepp_NULL (png_bytepp)NULL
  179123. #define png_doublep_NULL (png_doublep)NULL
  179124. #define png_error_ptr_NULL (png_error_ptr)NULL
  179125. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  179126. #define png_free_ptr_NULL (png_free_ptr)NULL
  179127. #define png_infopp_NULL (png_infopp)NULL
  179128. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  179129. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  179130. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  179131. #define png_structp_NULL (png_structp)NULL
  179132. #define png_uint_16p_NULL (png_uint_16p)NULL
  179133. #define png_voidp_NULL (png_voidp)NULL
  179134. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  179135. #else
  179136. #define int_p_NULL NULL
  179137. #define png_bytep_NULL NULL
  179138. #define png_bytepp_NULL NULL
  179139. #define png_doublep_NULL NULL
  179140. #define png_error_ptr_NULL NULL
  179141. #define png_flush_ptr_NULL NULL
  179142. #define png_free_ptr_NULL NULL
  179143. #define png_infopp_NULL NULL
  179144. #define png_malloc_ptr_NULL NULL
  179145. #define png_read_status_ptr_NULL NULL
  179146. #define png_rw_ptr_NULL NULL
  179147. #define png_structp_NULL NULL
  179148. #define png_uint_16p_NULL NULL
  179149. #define png_voidp_NULL NULL
  179150. #define png_write_status_ptr_NULL NULL
  179151. #endif
  179152. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  179153. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  179154. /* Version information for C files, stored in png.c. This had better match
  179155. * the version above.
  179156. */
  179157. #ifdef PNG_USE_GLOBAL_ARRAYS
  179158. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  179159. /* need room for 99.99.99beta99z */
  179160. #else
  179161. #define png_libpng_ver png_get_header_ver(NULL)
  179162. #endif
  179163. #ifdef PNG_USE_GLOBAL_ARRAYS
  179164. /* This was removed in version 1.0.5c */
  179165. /* Structures to facilitate easy interlacing. See png.c for more details */
  179166. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  179167. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  179168. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  179169. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  179170. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  179171. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  179172. /* This isn't currently used. If you need it, see png.c for more details.
  179173. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  179174. */
  179175. #endif
  179176. #endif /* PNG_NO_EXTERN */
  179177. /* Three color definitions. The order of the red, green, and blue, (and the
  179178. * exact size) is not important, although the size of the fields need to
  179179. * be png_byte or png_uint_16 (as defined below).
  179180. */
  179181. typedef struct png_color_struct
  179182. {
  179183. png_byte red;
  179184. png_byte green;
  179185. png_byte blue;
  179186. } png_color;
  179187. typedef png_color FAR * png_colorp;
  179188. typedef png_color FAR * FAR * png_colorpp;
  179189. typedef struct png_color_16_struct
  179190. {
  179191. png_byte index; /* used for palette files */
  179192. png_uint_16 red; /* for use in red green blue files */
  179193. png_uint_16 green;
  179194. png_uint_16 blue;
  179195. png_uint_16 gray; /* for use in grayscale files */
  179196. } png_color_16;
  179197. typedef png_color_16 FAR * png_color_16p;
  179198. typedef png_color_16 FAR * FAR * png_color_16pp;
  179199. typedef struct png_color_8_struct
  179200. {
  179201. png_byte red; /* for use in red green blue files */
  179202. png_byte green;
  179203. png_byte blue;
  179204. png_byte gray; /* for use in grayscale files */
  179205. png_byte alpha; /* for alpha channel files */
  179206. } png_color_8;
  179207. typedef png_color_8 FAR * png_color_8p;
  179208. typedef png_color_8 FAR * FAR * png_color_8pp;
  179209. /*
  179210. * The following two structures are used for the in-core representation
  179211. * of sPLT chunks.
  179212. */
  179213. typedef struct png_sPLT_entry_struct
  179214. {
  179215. png_uint_16 red;
  179216. png_uint_16 green;
  179217. png_uint_16 blue;
  179218. png_uint_16 alpha;
  179219. png_uint_16 frequency;
  179220. } png_sPLT_entry;
  179221. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  179222. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  179223. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  179224. * occupy the LSB of their respective members, and the MSB of each member
  179225. * is zero-filled. The frequency member always occupies the full 16 bits.
  179226. */
  179227. typedef struct png_sPLT_struct
  179228. {
  179229. png_charp name; /* palette name */
  179230. png_byte depth; /* depth of palette samples */
  179231. png_sPLT_entryp entries; /* palette entries */
  179232. png_int_32 nentries; /* number of palette entries */
  179233. } png_sPLT_t;
  179234. typedef png_sPLT_t FAR * png_sPLT_tp;
  179235. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  179236. #ifdef PNG_TEXT_SUPPORTED
  179237. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  179238. * and whether that contents is compressed or not. The "key" field
  179239. * points to a regular zero-terminated C string. The "text", "lang", and
  179240. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  179241. * However, the * structure returned by png_get_text() will always contain
  179242. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  179243. * so they can be safely used in printf() and other string-handling functions.
  179244. */
  179245. typedef struct png_text_struct
  179246. {
  179247. int compression; /* compression value:
  179248. -1: tEXt, none
  179249. 0: zTXt, deflate
  179250. 1: iTXt, none
  179251. 2: iTXt, deflate */
  179252. png_charp key; /* keyword, 1-79 character description of "text" */
  179253. png_charp text; /* comment, may be an empty string (ie "")
  179254. or a NULL pointer */
  179255. png_size_t text_length; /* length of the text string */
  179256. #ifdef PNG_iTXt_SUPPORTED
  179257. png_size_t itxt_length; /* length of the itxt string */
  179258. png_charp lang; /* language code, 0-79 characters
  179259. or a NULL pointer */
  179260. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  179261. chars or a NULL pointer */
  179262. #endif
  179263. } png_text;
  179264. typedef png_text FAR * png_textp;
  179265. typedef png_text FAR * FAR * png_textpp;
  179266. #endif
  179267. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  179268. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  179269. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  179270. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  179271. #define PNG_TEXT_COMPRESSION_NONE -1
  179272. #define PNG_TEXT_COMPRESSION_zTXt 0
  179273. #define PNG_ITXT_COMPRESSION_NONE 1
  179274. #define PNG_ITXT_COMPRESSION_zTXt 2
  179275. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  179276. /* png_time is a way to hold the time in an machine independent way.
  179277. * Two conversions are provided, both from time_t and struct tm. There
  179278. * is no portable way to convert to either of these structures, as far
  179279. * as I know. If you know of a portable way, send it to me. As a side
  179280. * note - PNG has always been Year 2000 compliant!
  179281. */
  179282. typedef struct png_time_struct
  179283. {
  179284. png_uint_16 year; /* full year, as in, 1995 */
  179285. png_byte month; /* month of year, 1 - 12 */
  179286. png_byte day; /* day of month, 1 - 31 */
  179287. png_byte hour; /* hour of day, 0 - 23 */
  179288. png_byte minute; /* minute of hour, 0 - 59 */
  179289. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  179290. } png_time;
  179291. typedef png_time FAR * png_timep;
  179292. typedef png_time FAR * FAR * png_timepp;
  179293. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  179294. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  179295. * no specific support. The idea is that we can use this to queue
  179296. * up private chunks for output even though the library doesn't actually
  179297. * know about their semantics.
  179298. */
  179299. typedef struct png_unknown_chunk_t
  179300. {
  179301. png_byte name[5];
  179302. png_byte *data;
  179303. png_size_t size;
  179304. /* libpng-using applications should NOT directly modify this byte. */
  179305. png_byte location; /* mode of operation at read time */
  179306. }
  179307. png_unknown_chunk;
  179308. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  179309. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  179310. #endif
  179311. /* png_info is a structure that holds the information in a PNG file so
  179312. * that the application can find out the characteristics of the image.
  179313. * If you are reading the file, this structure will tell you what is
  179314. * in the PNG file. If you are writing the file, fill in the information
  179315. * you want to put into the PNG file, then call png_write_info().
  179316. * The names chosen should be very close to the PNG specification, so
  179317. * consult that document for information about the meaning of each field.
  179318. *
  179319. * With libpng < 0.95, it was only possible to directly set and read the
  179320. * the values in the png_info_struct, which meant that the contents and
  179321. * order of the values had to remain fixed. With libpng 0.95 and later,
  179322. * however, there are now functions that abstract the contents of
  179323. * png_info_struct from the application, so this makes it easier to use
  179324. * libpng with dynamic libraries, and even makes it possible to use
  179325. * libraries that don't have all of the libpng ancillary chunk-handing
  179326. * functionality.
  179327. *
  179328. * In any case, the order of the parameters in png_info_struct should NOT
  179329. * be changed for as long as possible to keep compatibility with applications
  179330. * that use the old direct-access method with png_info_struct.
  179331. *
  179332. * The following members may have allocated storage attached that should be
  179333. * cleaned up before the structure is discarded: palette, trans, text,
  179334. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  179335. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  179336. * are automatically freed when the info structure is deallocated, if they were
  179337. * allocated internally by libpng. This behavior can be changed by means
  179338. * of the png_data_freer() function.
  179339. *
  179340. * More allocation details: all the chunk-reading functions that
  179341. * change these members go through the corresponding png_set_*
  179342. * functions. A function to clear these members is available: see
  179343. * png_free_data(). The png_set_* functions do not depend on being
  179344. * able to point info structure members to any of the storage they are
  179345. * passed (they make their own copies), EXCEPT that the png_set_text
  179346. * functions use the same storage passed to them in the text_ptr or
  179347. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  179348. * functions do not make their own copies.
  179349. */
  179350. typedef struct png_info_struct
  179351. {
  179352. /* the following are necessary for every PNG file */
  179353. png_uint_32 width; /* width of image in pixels (from IHDR) */
  179354. png_uint_32 height; /* height of image in pixels (from IHDR) */
  179355. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  179356. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  179357. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  179358. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  179359. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  179360. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  179361. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  179362. /* The following three should have been named *_method not *_type */
  179363. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  179364. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  179365. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  179366. /* The following is informational only on read, and not used on writes. */
  179367. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  179368. png_byte pixel_depth; /* number of bits per pixel */
  179369. png_byte spare_byte; /* to align the data, and for future use */
  179370. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  179371. /* The rest of the data is optional. If you are reading, check the
  179372. * valid field to see if the information in these are valid. If you
  179373. * are writing, set the valid field to those chunks you want written,
  179374. * and initialize the appropriate fields below.
  179375. */
  179376. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  179377. /* The gAMA chunk describes the gamma characteristics of the system
  179378. * on which the image was created, normally in the range [1.0, 2.5].
  179379. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  179380. */
  179381. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  179382. #endif
  179383. #if defined(PNG_sRGB_SUPPORTED)
  179384. /* GR-P, 0.96a */
  179385. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  179386. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  179387. #endif
  179388. #if defined(PNG_TEXT_SUPPORTED)
  179389. /* The tEXt, and zTXt chunks contain human-readable textual data in
  179390. * uncompressed, compressed, and optionally compressed forms, respectively.
  179391. * The data in "text" is an array of pointers to uncompressed,
  179392. * null-terminated C strings. Each chunk has a keyword that describes the
  179393. * textual data contained in that chunk. Keywords are not required to be
  179394. * unique, and the text string may be empty. Any number of text chunks may
  179395. * be in an image.
  179396. */
  179397. int num_text; /* number of comments read/to write */
  179398. int max_text; /* current size of text array */
  179399. png_textp text; /* array of comments read/to write */
  179400. #endif /* PNG_TEXT_SUPPORTED */
  179401. #if defined(PNG_tIME_SUPPORTED)
  179402. /* The tIME chunk holds the last time the displayed image data was
  179403. * modified. See the png_time struct for the contents of this struct.
  179404. */
  179405. png_time mod_time;
  179406. #endif
  179407. #if defined(PNG_sBIT_SUPPORTED)
  179408. /* The sBIT chunk specifies the number of significant high-order bits
  179409. * in the pixel data. Values are in the range [1, bit_depth], and are
  179410. * only specified for the channels in the pixel data. The contents of
  179411. * the low-order bits is not specified. Data is valid if
  179412. * (valid & PNG_INFO_sBIT) is non-zero.
  179413. */
  179414. png_color_8 sig_bit; /* significant bits in color channels */
  179415. #endif
  179416. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  179417. defined(PNG_READ_BACKGROUND_SUPPORTED)
  179418. /* The tRNS chunk supplies transparency data for paletted images and
  179419. * other image types that don't need a full alpha channel. There are
  179420. * "num_trans" transparency values for a paletted image, stored in the
  179421. * same order as the palette colors, starting from index 0. Values
  179422. * for the data are in the range [0, 255], ranging from fully transparent
  179423. * to fully opaque, respectively. For non-paletted images, there is a
  179424. * single color specified that should be treated as fully transparent.
  179425. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  179426. */
  179427. png_bytep trans; /* transparent values for paletted image */
  179428. png_color_16 trans_values; /* transparent color for non-palette image */
  179429. #endif
  179430. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  179431. /* The bKGD chunk gives the suggested image background color if the
  179432. * display program does not have its own background color and the image
  179433. * is needs to composited onto a background before display. The colors
  179434. * in "background" are normally in the same color space/depth as the
  179435. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  179436. */
  179437. png_color_16 background;
  179438. #endif
  179439. #if defined(PNG_oFFs_SUPPORTED)
  179440. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  179441. * and downwards from the top-left corner of the display, page, or other
  179442. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  179443. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  179444. */
  179445. png_int_32 x_offset; /* x offset on page */
  179446. png_int_32 y_offset; /* y offset on page */
  179447. png_byte offset_unit_type; /* offset units type */
  179448. #endif
  179449. #if defined(PNG_pHYs_SUPPORTED)
  179450. /* The pHYs chunk gives the physical pixel density of the image for
  179451. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  179452. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  179453. */
  179454. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  179455. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  179456. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  179457. #endif
  179458. #if defined(PNG_hIST_SUPPORTED)
  179459. /* The hIST chunk contains the relative frequency or importance of the
  179460. * various palette entries, so that a viewer can intelligently select a
  179461. * reduced-color palette, if required. Data is an array of "num_palette"
  179462. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  179463. * is non-zero.
  179464. */
  179465. png_uint_16p hist;
  179466. #endif
  179467. #ifdef PNG_cHRM_SUPPORTED
  179468. /* The cHRM chunk describes the CIE color characteristics of the monitor
  179469. * on which the PNG was created. This data allows the viewer to do gamut
  179470. * mapping of the input image to ensure that the viewer sees the same
  179471. * colors in the image as the creator. Values are in the range
  179472. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  179473. */
  179474. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179475. float x_white;
  179476. float y_white;
  179477. float x_red;
  179478. float y_red;
  179479. float x_green;
  179480. float y_green;
  179481. float x_blue;
  179482. float y_blue;
  179483. #endif
  179484. #endif
  179485. #if defined(PNG_pCAL_SUPPORTED)
  179486. /* The pCAL chunk describes a transformation between the stored pixel
  179487. * values and original physical data values used to create the image.
  179488. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  179489. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  179490. * (possibly non-linear) transformation function given by "pcal_type"
  179491. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  179492. * defines below, and the PNG-Group's PNG extensions document for a
  179493. * complete description of the transformations and how they should be
  179494. * implemented, and for a description of the ASCII parameter strings.
  179495. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  179496. */
  179497. png_charp pcal_purpose; /* pCAL chunk description string */
  179498. png_int_32 pcal_X0; /* minimum value */
  179499. png_int_32 pcal_X1; /* maximum value */
  179500. png_charp pcal_units; /* Latin-1 string giving physical units */
  179501. png_charpp pcal_params; /* ASCII strings containing parameter values */
  179502. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  179503. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  179504. #endif
  179505. /* New members added in libpng-1.0.6 */
  179506. #ifdef PNG_FREE_ME_SUPPORTED
  179507. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  179508. #endif
  179509. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  179510. /* storage for unknown chunks that the library doesn't recognize. */
  179511. png_unknown_chunkp unknown_chunks;
  179512. png_size_t unknown_chunks_num;
  179513. #endif
  179514. #if defined(PNG_iCCP_SUPPORTED)
  179515. /* iCCP chunk data. */
  179516. png_charp iccp_name; /* profile name */
  179517. png_charp iccp_profile; /* International Color Consortium profile data */
  179518. /* Note to maintainer: should be png_bytep */
  179519. png_uint_32 iccp_proflen; /* ICC profile data length */
  179520. png_byte iccp_compression; /* Always zero */
  179521. #endif
  179522. #if defined(PNG_sPLT_SUPPORTED)
  179523. /* data on sPLT chunks (there may be more than one). */
  179524. png_sPLT_tp splt_palettes;
  179525. png_uint_32 splt_palettes_num;
  179526. #endif
  179527. #if defined(PNG_sCAL_SUPPORTED)
  179528. /* The sCAL chunk describes the actual physical dimensions of the
  179529. * subject matter of the graphic. The chunk contains a unit specification
  179530. * a byte value, and two ASCII strings representing floating-point
  179531. * values. The values are width and height corresponsing to one pixel
  179532. * in the image. This external representation is converted to double
  179533. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  179534. */
  179535. png_byte scal_unit; /* unit of physical scale */
  179536. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179537. double scal_pixel_width; /* width of one pixel */
  179538. double scal_pixel_height; /* height of one pixel */
  179539. #endif
  179540. #ifdef PNG_FIXED_POINT_SUPPORTED
  179541. png_charp scal_s_width; /* string containing height */
  179542. png_charp scal_s_height; /* string containing width */
  179543. #endif
  179544. #endif
  179545. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  179546. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  179547. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  179548. png_bytepp row_pointers; /* the image bits */
  179549. #endif
  179550. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  179551. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  179552. #endif
  179553. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  179554. png_fixed_point int_x_white;
  179555. png_fixed_point int_y_white;
  179556. png_fixed_point int_x_red;
  179557. png_fixed_point int_y_red;
  179558. png_fixed_point int_x_green;
  179559. png_fixed_point int_y_green;
  179560. png_fixed_point int_x_blue;
  179561. png_fixed_point int_y_blue;
  179562. #endif
  179563. } png_info;
  179564. typedef png_info FAR * png_infop;
  179565. typedef png_info FAR * FAR * png_infopp;
  179566. /* Maximum positive integer used in PNG is (2^31)-1 */
  179567. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  179568. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  179569. #define PNG_SIZE_MAX ((png_size_t)(-1))
  179570. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  179571. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  179572. #define PNG_MAX_UINT PNG_UINT_31_MAX
  179573. #endif
  179574. /* These describe the color_type field in png_info. */
  179575. /* color type masks */
  179576. #define PNG_COLOR_MASK_PALETTE 1
  179577. #define PNG_COLOR_MASK_COLOR 2
  179578. #define PNG_COLOR_MASK_ALPHA 4
  179579. /* color types. Note that not all combinations are legal */
  179580. #define PNG_COLOR_TYPE_GRAY 0
  179581. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  179582. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  179583. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  179584. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  179585. /* aliases */
  179586. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  179587. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  179588. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  179589. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  179590. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  179591. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  179592. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  179593. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  179594. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  179595. /* These are for the interlacing type. These values should NOT be changed. */
  179596. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  179597. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  179598. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  179599. /* These are for the oFFs chunk. These values should NOT be changed. */
  179600. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  179601. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  179602. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  179603. /* These are for the pCAL chunk. These values should NOT be changed. */
  179604. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  179605. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  179606. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  179607. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  179608. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  179609. /* These are for the sCAL chunk. These values should NOT be changed. */
  179610. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  179611. #define PNG_SCALE_METER 1 /* meters per pixel */
  179612. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  179613. #define PNG_SCALE_LAST 3 /* Not a valid value */
  179614. /* These are for the pHYs chunk. These values should NOT be changed. */
  179615. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  179616. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  179617. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  179618. /* These are for the sRGB chunk. These values should NOT be changed. */
  179619. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  179620. #define PNG_sRGB_INTENT_RELATIVE 1
  179621. #define PNG_sRGB_INTENT_SATURATION 2
  179622. #define PNG_sRGB_INTENT_ABSOLUTE 3
  179623. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  179624. /* This is for text chunks */
  179625. #define PNG_KEYWORD_MAX_LENGTH 79
  179626. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  179627. #define PNG_MAX_PALETTE_LENGTH 256
  179628. /* These determine if an ancillary chunk's data has been successfully read
  179629. * from the PNG header, or if the application has filled in the corresponding
  179630. * data in the info_struct to be written into the output file. The values
  179631. * of the PNG_INFO_<chunk> defines should NOT be changed.
  179632. */
  179633. #define PNG_INFO_gAMA 0x0001
  179634. #define PNG_INFO_sBIT 0x0002
  179635. #define PNG_INFO_cHRM 0x0004
  179636. #define PNG_INFO_PLTE 0x0008
  179637. #define PNG_INFO_tRNS 0x0010
  179638. #define PNG_INFO_bKGD 0x0020
  179639. #define PNG_INFO_hIST 0x0040
  179640. #define PNG_INFO_pHYs 0x0080
  179641. #define PNG_INFO_oFFs 0x0100
  179642. #define PNG_INFO_tIME 0x0200
  179643. #define PNG_INFO_pCAL 0x0400
  179644. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  179645. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  179646. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  179647. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  179648. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  179649. /* This is used for the transformation routines, as some of them
  179650. * change these values for the row. It also should enable using
  179651. * the routines for other purposes.
  179652. */
  179653. typedef struct png_row_info_struct
  179654. {
  179655. png_uint_32 width; /* width of row */
  179656. png_uint_32 rowbytes; /* number of bytes in row */
  179657. png_byte color_type; /* color type of row */
  179658. png_byte bit_depth; /* bit depth of row */
  179659. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  179660. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  179661. } png_row_info;
  179662. typedef png_row_info FAR * png_row_infop;
  179663. typedef png_row_info FAR * FAR * png_row_infopp;
  179664. /* These are the function types for the I/O functions and for the functions
  179665. * that allow the user to override the default I/O functions with his or her
  179666. * own. The png_error_ptr type should match that of user-supplied warning
  179667. * and error functions, while the png_rw_ptr type should match that of the
  179668. * user read/write data functions.
  179669. */
  179670. typedef struct png_struct_def png_struct;
  179671. typedef png_struct FAR * png_structp;
  179672. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  179673. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  179674. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  179675. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  179676. int));
  179677. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  179678. int));
  179679. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  179680. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  179681. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  179682. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  179683. png_uint_32, int));
  179684. #endif
  179685. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  179686. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  179687. defined(PNG_LEGACY_SUPPORTED)
  179688. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  179689. png_row_infop, png_bytep));
  179690. #endif
  179691. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  179692. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  179693. #endif
  179694. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  179695. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  179696. #endif
  179697. /* Transform masks for the high-level interface */
  179698. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  179699. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  179700. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  179701. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  179702. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  179703. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  179704. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  179705. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  179706. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  179707. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  179708. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  179709. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  179710. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  179711. /* Flags for MNG supported features */
  179712. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  179713. #define PNG_FLAG_MNG_FILTER_64 0x04
  179714. #define PNG_ALL_MNG_FEATURES 0x05
  179715. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  179716. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  179717. /* The structure that holds the information to read and write PNG files.
  179718. * The only people who need to care about what is inside of this are the
  179719. * people who will be modifying the library for their own special needs.
  179720. * It should NOT be accessed directly by an application, except to store
  179721. * the jmp_buf.
  179722. */
  179723. struct png_struct_def
  179724. {
  179725. #ifdef PNG_SETJMP_SUPPORTED
  179726. jmp_buf jmpbuf; /* used in png_error */
  179727. #endif
  179728. png_error_ptr error_fn; /* function for printing errors and aborting */
  179729. png_error_ptr warning_fn; /* function for printing warnings */
  179730. png_voidp error_ptr; /* user supplied struct for error functions */
  179731. png_rw_ptr write_data_fn; /* function for writing output data */
  179732. png_rw_ptr read_data_fn; /* function for reading input data */
  179733. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  179734. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  179735. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  179736. #endif
  179737. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  179738. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  179739. #endif
  179740. /* These were added in libpng-1.0.2 */
  179741. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  179742. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  179743. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  179744. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  179745. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  179746. png_byte user_transform_channels; /* channels in user transformed pixels */
  179747. #endif
  179748. #endif
  179749. png_uint_32 mode; /* tells us where we are in the PNG file */
  179750. png_uint_32 flags; /* flags indicating various things to libpng */
  179751. png_uint_32 transformations; /* which transformations to perform */
  179752. z_stream zstream; /* pointer to decompression structure (below) */
  179753. png_bytep zbuf; /* buffer for zlib */
  179754. png_size_t zbuf_size; /* size of zbuf */
  179755. int zlib_level; /* holds zlib compression level */
  179756. int zlib_method; /* holds zlib compression method */
  179757. int zlib_window_bits; /* holds zlib compression window bits */
  179758. int zlib_mem_level; /* holds zlib compression memory level */
  179759. int zlib_strategy; /* holds zlib compression strategy */
  179760. png_uint_32 width; /* width of image in pixels */
  179761. png_uint_32 height; /* height of image in pixels */
  179762. png_uint_32 num_rows; /* number of rows in current pass */
  179763. png_uint_32 usr_width; /* width of row at start of write */
  179764. png_uint_32 rowbytes; /* size of row in bytes */
  179765. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  179766. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  179767. png_uint_32 row_number; /* current row in interlace pass */
  179768. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  179769. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  179770. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  179771. png_bytep up_row; /* buffer to save "up" row when filtering */
  179772. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  179773. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  179774. png_row_info row_info; /* used for transformation routines */
  179775. png_uint_32 idat_size; /* current IDAT size for read */
  179776. png_uint_32 crc; /* current chunk CRC value */
  179777. png_colorp palette; /* palette from the input file */
  179778. png_uint_16 num_palette; /* number of color entries in palette */
  179779. png_uint_16 num_trans; /* number of transparency values */
  179780. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  179781. png_byte compression; /* file compression type (always 0) */
  179782. png_byte filter; /* file filter type (always 0) */
  179783. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  179784. png_byte pass; /* current interlace pass (0 - 6) */
  179785. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  179786. png_byte color_type; /* color type of file */
  179787. png_byte bit_depth; /* bit depth of file */
  179788. png_byte usr_bit_depth; /* bit depth of users row */
  179789. png_byte pixel_depth; /* number of bits per pixel */
  179790. png_byte channels; /* number of channels in file */
  179791. png_byte usr_channels; /* channels at start of write */
  179792. png_byte sig_bytes; /* magic bytes read/written from start of file */
  179793. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  179794. #ifdef PNG_LEGACY_SUPPORTED
  179795. png_byte filler; /* filler byte for pixel expansion */
  179796. #else
  179797. png_uint_16 filler; /* filler bytes for pixel expansion */
  179798. #endif
  179799. #endif
  179800. #if defined(PNG_bKGD_SUPPORTED)
  179801. png_byte background_gamma_type;
  179802. # ifdef PNG_FLOATING_POINT_SUPPORTED
  179803. float background_gamma;
  179804. # endif
  179805. png_color_16 background; /* background color in screen gamma space */
  179806. #if defined(PNG_READ_GAMMA_SUPPORTED)
  179807. png_color_16 background_1; /* background normalized to gamma 1.0 */
  179808. #endif
  179809. #endif /* PNG_bKGD_SUPPORTED */
  179810. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  179811. png_flush_ptr output_flush_fn;/* Function for flushing output */
  179812. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  179813. png_uint_32 flush_rows; /* number of rows written since last flush */
  179814. #endif
  179815. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  179816. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  179817. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179818. float gamma; /* file gamma value */
  179819. float screen_gamma; /* screen gamma value (display_exponent) */
  179820. #endif
  179821. #endif
  179822. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  179823. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  179824. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  179825. png_bytep gamma_to_1; /* converts from file to 1.0 */
  179826. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  179827. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  179828. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  179829. #endif
  179830. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  179831. png_color_8 sig_bit; /* significant bits in each available channel */
  179832. #endif
  179833. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  179834. png_color_8 shift; /* shift for significant bit tranformation */
  179835. #endif
  179836. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  179837. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  179838. png_bytep trans; /* transparency values for paletted files */
  179839. png_color_16 trans_values; /* transparency values for non-paletted files */
  179840. #endif
  179841. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  179842. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  179843. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  179844. png_progressive_info_ptr info_fn; /* called after header data fully read */
  179845. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  179846. png_progressive_end_ptr end_fn; /* called after image is complete */
  179847. png_bytep save_buffer_ptr; /* current location in save_buffer */
  179848. png_bytep save_buffer; /* buffer for previously read data */
  179849. png_bytep current_buffer_ptr; /* current location in current_buffer */
  179850. png_bytep current_buffer; /* buffer for recently used data */
  179851. png_uint_32 push_length; /* size of current input chunk */
  179852. png_uint_32 skip_length; /* bytes to skip in input data */
  179853. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  179854. png_size_t save_buffer_max; /* total size of save_buffer */
  179855. png_size_t buffer_size; /* total amount of available input data */
  179856. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  179857. int process_mode; /* what push library is currently doing */
  179858. int cur_palette; /* current push library palette index */
  179859. # if defined(PNG_TEXT_SUPPORTED)
  179860. png_size_t current_text_size; /* current size of text input data */
  179861. png_size_t current_text_left; /* how much text left to read in input */
  179862. png_charp current_text; /* current text chunk buffer */
  179863. png_charp current_text_ptr; /* current location in current_text */
  179864. # endif /* PNG_TEXT_SUPPORTED */
  179865. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  179866. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  179867. /* for the Borland special 64K segment handler */
  179868. png_bytepp offset_table_ptr;
  179869. png_bytep offset_table;
  179870. png_uint_16 offset_table_number;
  179871. png_uint_16 offset_table_count;
  179872. png_uint_16 offset_table_count_free;
  179873. #endif
  179874. #if defined(PNG_READ_DITHER_SUPPORTED)
  179875. png_bytep palette_lookup; /* lookup table for dithering */
  179876. png_bytep dither_index; /* index translation for palette files */
  179877. #endif
  179878. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  179879. png_uint_16p hist; /* histogram */
  179880. #endif
  179881. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  179882. png_byte heuristic_method; /* heuristic for row filter selection */
  179883. png_byte num_prev_filters; /* number of weights for previous rows */
  179884. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  179885. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  179886. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  179887. png_uint_16p filter_costs; /* relative filter calculation cost */
  179888. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  179889. #endif
  179890. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  179891. png_charp time_buffer; /* String to hold RFC 1123 time text */
  179892. #endif
  179893. /* New members added in libpng-1.0.6 */
  179894. #ifdef PNG_FREE_ME_SUPPORTED
  179895. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  179896. #endif
  179897. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  179898. png_voidp user_chunk_ptr;
  179899. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  179900. #endif
  179901. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  179902. int num_chunk_list;
  179903. png_bytep chunk_list;
  179904. #endif
  179905. /* New members added in libpng-1.0.3 */
  179906. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  179907. png_byte rgb_to_gray_status;
  179908. /* These were changed from png_byte in libpng-1.0.6 */
  179909. png_uint_16 rgb_to_gray_red_coeff;
  179910. png_uint_16 rgb_to_gray_green_coeff;
  179911. png_uint_16 rgb_to_gray_blue_coeff;
  179912. #endif
  179913. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  179914. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  179915. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  179916. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  179917. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  179918. #ifdef PNG_1_0_X
  179919. png_byte mng_features_permitted;
  179920. #else
  179921. png_uint_32 mng_features_permitted;
  179922. #endif /* PNG_1_0_X */
  179923. #endif
  179924. /* New member added in libpng-1.0.7 */
  179925. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  179926. png_fixed_point int_gamma;
  179927. #endif
  179928. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  179929. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  179930. png_byte filter_type;
  179931. #endif
  179932. #if defined(PNG_1_0_X)
  179933. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  179934. png_uint_32 row_buf_size;
  179935. #endif
  179936. /* New members added in libpng-1.2.0 */
  179937. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  179938. # if !defined(PNG_1_0_X)
  179939. # if defined(PNG_MMX_CODE_SUPPORTED)
  179940. png_byte mmx_bitdepth_threshold;
  179941. png_uint_32 mmx_rowbytes_threshold;
  179942. # endif
  179943. png_uint_32 asm_flags;
  179944. # endif
  179945. #endif
  179946. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  179947. #ifdef PNG_USER_MEM_SUPPORTED
  179948. png_voidp mem_ptr; /* user supplied struct for mem functions */
  179949. png_malloc_ptr malloc_fn; /* function for allocating memory */
  179950. png_free_ptr free_fn; /* function for freeing memory */
  179951. #endif
  179952. /* New member added in libpng-1.0.13 and 1.2.0 */
  179953. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  179954. #if defined(PNG_READ_DITHER_SUPPORTED)
  179955. /* The following three members were added at version 1.0.14 and 1.2.4 */
  179956. png_bytep dither_sort; /* working sort array */
  179957. png_bytep index_to_palette; /* where the original index currently is */
  179958. /* in the palette */
  179959. png_bytep palette_to_index; /* which original index points to this */
  179960. /* palette color */
  179961. #endif
  179962. /* New members added in libpng-1.0.16 and 1.2.6 */
  179963. png_byte compression_type;
  179964. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  179965. png_uint_32 user_width_max;
  179966. png_uint_32 user_height_max;
  179967. #endif
  179968. /* New member added in libpng-1.0.25 and 1.2.17 */
  179969. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  179970. /* storage for unknown chunk that the library doesn't recognize. */
  179971. png_unknown_chunk unknown_chunk;
  179972. #endif
  179973. };
  179974. /* This triggers a compiler error in png.c, if png.c and png.h
  179975. * do not agree upon the version number.
  179976. */
  179977. typedef png_structp version_1_2_21;
  179978. typedef png_struct FAR * FAR * png_structpp;
  179979. /* Here are the function definitions most commonly used. This is not
  179980. * the place to find out how to use libpng. See libpng.txt for the
  179981. * full explanation, see example.c for the summary. This just provides
  179982. * a simple one line description of the use of each function.
  179983. */
  179984. /* Returns the version number of the library */
  179985. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  179986. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  179987. * Handling more than 8 bytes from the beginning of the file is an error.
  179988. */
  179989. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  179990. int num_bytes));
  179991. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  179992. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  179993. * signature, and non-zero otherwise. Having num_to_check == 0 or
  179994. * start > 7 will always fail (ie return non-zero).
  179995. */
  179996. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  179997. png_size_t num_to_check));
  179998. /* Simple signature checking function. This is the same as calling
  179999. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  180000. */
  180001. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  180002. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  180003. extern PNG_EXPORT(png_structp,png_create_read_struct)
  180004. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  180005. png_error_ptr error_fn, png_error_ptr warn_fn));
  180006. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  180007. extern PNG_EXPORT(png_structp,png_create_write_struct)
  180008. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  180009. png_error_ptr error_fn, png_error_ptr warn_fn));
  180010. #ifdef PNG_WRITE_SUPPORTED
  180011. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  180012. PNGARG((png_structp png_ptr));
  180013. #endif
  180014. #ifdef PNG_WRITE_SUPPORTED
  180015. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  180016. PNGARG((png_structp png_ptr, png_uint_32 size));
  180017. #endif
  180018. /* Reset the compression stream */
  180019. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  180020. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  180021. #ifdef PNG_USER_MEM_SUPPORTED
  180022. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  180023. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  180024. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  180025. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  180026. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  180027. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  180028. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  180029. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  180030. #endif
  180031. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  180032. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  180033. png_bytep chunk_name, png_bytep data, png_size_t length));
  180034. /* Write the start of a PNG chunk - length and chunk name. */
  180035. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  180036. png_bytep chunk_name, png_uint_32 length));
  180037. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  180038. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  180039. png_bytep data, png_size_t length));
  180040. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  180041. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  180042. /* Allocate and initialize the info structure */
  180043. extern PNG_EXPORT(png_infop,png_create_info_struct)
  180044. PNGARG((png_structp png_ptr));
  180045. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180046. /* Initialize the info structure (old interface - DEPRECATED) */
  180047. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  180048. #undef png_info_init
  180049. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  180050. png_sizeof(png_info));
  180051. #endif
  180052. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  180053. png_size_t png_info_struct_size));
  180054. /* Writes all the PNG information before the image. */
  180055. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  180056. png_infop info_ptr));
  180057. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  180058. png_infop info_ptr));
  180059. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  180060. /* read the information before the actual image data. */
  180061. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  180062. png_infop info_ptr));
  180063. #endif
  180064. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  180065. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  180066. PNGARG((png_structp png_ptr, png_timep ptime));
  180067. #endif
  180068. #if !defined(_WIN32_WCE)
  180069. /* "time.h" functions are not supported on WindowsCE */
  180070. #if defined(PNG_WRITE_tIME_SUPPORTED)
  180071. /* convert from a struct tm to png_time */
  180072. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  180073. struct tm FAR * ttime));
  180074. /* convert from time_t to png_time. Uses gmtime() */
  180075. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  180076. time_t ttime));
  180077. #endif /* PNG_WRITE_tIME_SUPPORTED */
  180078. #endif /* _WIN32_WCE */
  180079. #if defined(PNG_READ_EXPAND_SUPPORTED)
  180080. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  180081. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  180082. #if !defined(PNG_1_0_X)
  180083. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  180084. png_ptr));
  180085. #endif
  180086. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  180087. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  180088. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180089. /* Deprecated */
  180090. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  180091. #endif
  180092. #endif
  180093. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  180094. /* Use blue, green, red order for pixels. */
  180095. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  180096. #endif
  180097. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  180098. /* Expand the grayscale to 24-bit RGB if necessary. */
  180099. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  180100. #endif
  180101. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  180102. /* Reduce RGB to grayscale. */
  180103. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180104. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  180105. int error_action, double red, double green ));
  180106. #endif
  180107. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  180108. int error_action, png_fixed_point red, png_fixed_point green ));
  180109. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  180110. png_ptr));
  180111. #endif
  180112. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  180113. png_colorp palette));
  180114. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  180115. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  180116. #endif
  180117. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  180118. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  180119. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  180120. #endif
  180121. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  180122. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  180123. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  180124. #endif
  180125. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  180126. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  180127. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  180128. png_uint_32 filler, int flags));
  180129. /* The values of the PNG_FILLER_ defines should NOT be changed */
  180130. #define PNG_FILLER_BEFORE 0
  180131. #define PNG_FILLER_AFTER 1
  180132. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  180133. #if !defined(PNG_1_0_X)
  180134. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  180135. png_uint_32 filler, int flags));
  180136. #endif
  180137. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  180138. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  180139. /* Swap bytes in 16-bit depth files. */
  180140. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  180141. #endif
  180142. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  180143. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  180144. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  180145. #endif
  180146. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  180147. /* Swap packing order of pixels in bytes. */
  180148. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  180149. #endif
  180150. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  180151. /* Converts files to legal bit depths. */
  180152. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  180153. png_color_8p true_bits));
  180154. #endif
  180155. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  180156. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  180157. /* Have the code handle the interlacing. Returns the number of passes. */
  180158. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  180159. #endif
  180160. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  180161. /* Invert monochrome files */
  180162. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  180163. #endif
  180164. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  180165. /* Handle alpha and tRNS by replacing with a background color. */
  180166. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180167. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  180168. png_color_16p background_color, int background_gamma_code,
  180169. int need_expand, double background_gamma));
  180170. #endif
  180171. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  180172. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  180173. #define PNG_BACKGROUND_GAMMA_FILE 2
  180174. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  180175. #endif
  180176. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  180177. /* strip the second byte of information from a 16-bit depth file. */
  180178. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  180179. #endif
  180180. #if defined(PNG_READ_DITHER_SUPPORTED)
  180181. /* Turn on dithering, and reduce the palette to the number of colors available. */
  180182. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  180183. png_colorp palette, int num_palette, int maximum_colors,
  180184. png_uint_16p histogram, int full_dither));
  180185. #endif
  180186. #if defined(PNG_READ_GAMMA_SUPPORTED)
  180187. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  180188. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180189. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  180190. double screen_gamma, double default_file_gamma));
  180191. #endif
  180192. #endif
  180193. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180194. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  180195. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  180196. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  180197. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  180198. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  180199. int empty_plte_permitted));
  180200. #endif
  180201. #endif
  180202. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  180203. /* Set how many lines between output flushes - 0 for no flushing */
  180204. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  180205. /* Flush the current PNG output buffer */
  180206. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  180207. #endif
  180208. /* optional update palette with requested transformations */
  180209. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  180210. /* optional call to update the users info structure */
  180211. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  180212. png_infop info_ptr));
  180213. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  180214. /* read one or more rows of image data. */
  180215. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  180216. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  180217. #endif
  180218. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  180219. /* read a row of data. */
  180220. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  180221. png_bytep row,
  180222. png_bytep display_row));
  180223. #endif
  180224. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  180225. /* read the whole image into memory at once. */
  180226. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  180227. png_bytepp image));
  180228. #endif
  180229. /* write a row of image data */
  180230. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  180231. png_bytep row));
  180232. /* write a few rows of image data */
  180233. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  180234. png_bytepp row, png_uint_32 num_rows));
  180235. /* write the image data */
  180236. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  180237. png_bytepp image));
  180238. /* writes the end of the PNG file. */
  180239. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  180240. png_infop info_ptr));
  180241. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  180242. /* read the end of the PNG file. */
  180243. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  180244. png_infop info_ptr));
  180245. #endif
  180246. /* free any memory associated with the png_info_struct */
  180247. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  180248. png_infopp info_ptr_ptr));
  180249. /* free any memory associated with the png_struct and the png_info_structs */
  180250. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  180251. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  180252. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  180253. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  180254. png_infop end_info_ptr));
  180255. /* free any memory associated with the png_struct and the png_info_structs */
  180256. extern PNG_EXPORT(void,png_destroy_write_struct)
  180257. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  180258. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  180259. extern void png_write_destroy PNGARG((png_structp png_ptr));
  180260. /* set the libpng method of handling chunk CRC errors */
  180261. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  180262. int crit_action, int ancil_action));
  180263. /* Values for png_set_crc_action() to say how to handle CRC errors in
  180264. * ancillary and critical chunks, and whether to use the data contained
  180265. * therein. Note that it is impossible to "discard" data in a critical
  180266. * chunk. For versions prior to 0.90, the action was always error/quit,
  180267. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  180268. * chunks is warn/discard. These values should NOT be changed.
  180269. *
  180270. * value action:critical action:ancillary
  180271. */
  180272. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  180273. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  180274. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  180275. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  180276. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  180277. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  180278. /* These functions give the user control over the scan-line filtering in
  180279. * libpng and the compression methods used by zlib. These functions are
  180280. * mainly useful for testing, as the defaults should work with most users.
  180281. * Those users who are tight on memory or want faster performance at the
  180282. * expense of compression can modify them. See the compression library
  180283. * header file (zlib.h) for an explination of the compression functions.
  180284. */
  180285. /* set the filtering method(s) used by libpng. Currently, the only valid
  180286. * value for "method" is 0.
  180287. */
  180288. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  180289. int filters));
  180290. /* Flags for png_set_filter() to say which filters to use. The flags
  180291. * are chosen so that they don't conflict with real filter types
  180292. * below, in case they are supplied instead of the #defined constants.
  180293. * These values should NOT be changed.
  180294. */
  180295. #define PNG_NO_FILTERS 0x00
  180296. #define PNG_FILTER_NONE 0x08
  180297. #define PNG_FILTER_SUB 0x10
  180298. #define PNG_FILTER_UP 0x20
  180299. #define PNG_FILTER_AVG 0x40
  180300. #define PNG_FILTER_PAETH 0x80
  180301. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  180302. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  180303. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  180304. * These defines should NOT be changed.
  180305. */
  180306. #define PNG_FILTER_VALUE_NONE 0
  180307. #define PNG_FILTER_VALUE_SUB 1
  180308. #define PNG_FILTER_VALUE_UP 2
  180309. #define PNG_FILTER_VALUE_AVG 3
  180310. #define PNG_FILTER_VALUE_PAETH 4
  180311. #define PNG_FILTER_VALUE_LAST 5
  180312. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  180313. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  180314. * defines, either the default (minimum-sum-of-absolute-differences), or
  180315. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  180316. *
  180317. * Weights are factors >= 1.0, indicating how important it is to keep the
  180318. * filter type consistent between rows. Larger numbers mean the current
  180319. * filter is that many times as likely to be the same as the "num_weights"
  180320. * previous filters. This is cumulative for each previous row with a weight.
  180321. * There needs to be "num_weights" values in "filter_weights", or it can be
  180322. * NULL if the weights aren't being specified. Weights have no influence on
  180323. * the selection of the first row filter. Well chosen weights can (in theory)
  180324. * improve the compression for a given image.
  180325. *
  180326. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  180327. * filter type. Higher costs indicate more decoding expense, and are
  180328. * therefore less likely to be selected over a filter with lower computational
  180329. * costs. There needs to be a value in "filter_costs" for each valid filter
  180330. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  180331. * setting the costs. Costs try to improve the speed of decompression without
  180332. * unduly increasing the compressed image size.
  180333. *
  180334. * A negative weight or cost indicates the default value is to be used, and
  180335. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  180336. * The default values for both weights and costs are currently 1.0, but may
  180337. * change if good general weighting/cost heuristics can be found. If both
  180338. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  180339. * to the UNWEIGHTED method, but with added encoding time/computation.
  180340. */
  180341. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180342. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  180343. int heuristic_method, int num_weights, png_doublep filter_weights,
  180344. png_doublep filter_costs));
  180345. #endif
  180346. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  180347. /* Heuristic used for row filter selection. These defines should NOT be
  180348. * changed.
  180349. */
  180350. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  180351. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  180352. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  180353. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  180354. /* Set the library compression level. Currently, valid values range from
  180355. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  180356. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  180357. * shown that zlib compression levels 3-6 usually perform as well as level 9
  180358. * for PNG images, and do considerably fewer caclulations. In the future,
  180359. * these values may not correspond directly to the zlib compression levels.
  180360. */
  180361. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  180362. int level));
  180363. extern PNG_EXPORT(void,png_set_compression_mem_level)
  180364. PNGARG((png_structp png_ptr, int mem_level));
  180365. extern PNG_EXPORT(void,png_set_compression_strategy)
  180366. PNGARG((png_structp png_ptr, int strategy));
  180367. extern PNG_EXPORT(void,png_set_compression_window_bits)
  180368. PNGARG((png_structp png_ptr, int window_bits));
  180369. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  180370. int method));
  180371. /* These next functions are called for input/output, memory, and error
  180372. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  180373. * and call standard C I/O routines such as fread(), fwrite(), and
  180374. * fprintf(). These functions can be made to use other I/O routines
  180375. * at run time for those applications that need to handle I/O in a
  180376. * different manner by calling png_set_???_fn(). See libpng.txt for
  180377. * more information.
  180378. */
  180379. #if !defined(PNG_NO_STDIO)
  180380. /* Initialize the input/output for the PNG file to the default functions. */
  180381. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  180382. #endif
  180383. /* Replace the (error and abort), and warning functions with user
  180384. * supplied functions. If no messages are to be printed you must still
  180385. * write and use replacement functions. The replacement error_fn should
  180386. * still do a longjmp to the last setjmp location if you are using this
  180387. * method of error handling. If error_fn or warning_fn is NULL, the
  180388. * default function will be used.
  180389. */
  180390. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  180391. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  180392. /* Return the user pointer associated with the error functions */
  180393. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  180394. /* Replace the default data output functions with a user supplied one(s).
  180395. * If buffered output is not used, then output_flush_fn can be set to NULL.
  180396. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  180397. * output_flush_fn will be ignored (and thus can be NULL).
  180398. */
  180399. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  180400. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  180401. /* Replace the default data input function with a user supplied one. */
  180402. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  180403. png_voidp io_ptr, png_rw_ptr read_data_fn));
  180404. /* Return the user pointer associated with the I/O functions */
  180405. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  180406. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  180407. png_read_status_ptr read_row_fn));
  180408. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  180409. png_write_status_ptr write_row_fn));
  180410. #ifdef PNG_USER_MEM_SUPPORTED
  180411. /* Replace the default memory allocation functions with user supplied one(s). */
  180412. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  180413. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  180414. /* Return the user pointer associated with the memory functions */
  180415. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  180416. #endif
  180417. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  180418. defined(PNG_LEGACY_SUPPORTED)
  180419. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  180420. png_ptr, png_user_transform_ptr read_user_transform_fn));
  180421. #endif
  180422. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  180423. defined(PNG_LEGACY_SUPPORTED)
  180424. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  180425. png_ptr, png_user_transform_ptr write_user_transform_fn));
  180426. #endif
  180427. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  180428. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  180429. defined(PNG_LEGACY_SUPPORTED)
  180430. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  180431. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  180432. int user_transform_channels));
  180433. /* Return the user pointer associated with the user transform functions */
  180434. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  180435. PNGARG((png_structp png_ptr));
  180436. #endif
  180437. #ifdef PNG_USER_CHUNKS_SUPPORTED
  180438. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  180439. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  180440. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  180441. png_ptr));
  180442. #endif
  180443. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  180444. /* Sets the function callbacks for the push reader, and a pointer to a
  180445. * user-defined structure available to the callback functions.
  180446. */
  180447. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  180448. png_voidp progressive_ptr,
  180449. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  180450. png_progressive_end_ptr end_fn));
  180451. /* returns the user pointer associated with the push read functions */
  180452. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  180453. PNGARG((png_structp png_ptr));
  180454. /* function to be called when data becomes available */
  180455. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  180456. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  180457. /* function that combines rows. Not very much different than the
  180458. * png_combine_row() call. Is this even used?????
  180459. */
  180460. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  180461. png_bytep old_row, png_bytep new_row));
  180462. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  180463. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  180464. png_uint_32 size));
  180465. #if defined(PNG_1_0_X)
  180466. # define png_malloc_warn png_malloc
  180467. #else
  180468. /* Added at libpng version 1.2.4 */
  180469. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  180470. png_uint_32 size));
  180471. #endif
  180472. /* frees a pointer allocated by png_malloc() */
  180473. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  180474. #if defined(PNG_1_0_X)
  180475. /* Function to allocate memory for zlib. */
  180476. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  180477. uInt size));
  180478. /* Function to free memory for zlib */
  180479. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  180480. #endif
  180481. /* Free data that was allocated internally */
  180482. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  180483. png_infop info_ptr, png_uint_32 free_me, int num));
  180484. #ifdef PNG_FREE_ME_SUPPORTED
  180485. /* Reassign responsibility for freeing existing data, whether allocated
  180486. * by libpng or by the application */
  180487. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  180488. png_infop info_ptr, int freer, png_uint_32 mask));
  180489. #endif
  180490. /* assignments for png_data_freer */
  180491. #define PNG_DESTROY_WILL_FREE_DATA 1
  180492. #define PNG_SET_WILL_FREE_DATA 1
  180493. #define PNG_USER_WILL_FREE_DATA 2
  180494. /* Flags for png_ptr->free_me and info_ptr->free_me */
  180495. #define PNG_FREE_HIST 0x0008
  180496. #define PNG_FREE_ICCP 0x0010
  180497. #define PNG_FREE_SPLT 0x0020
  180498. #define PNG_FREE_ROWS 0x0040
  180499. #define PNG_FREE_PCAL 0x0080
  180500. #define PNG_FREE_SCAL 0x0100
  180501. #define PNG_FREE_UNKN 0x0200
  180502. #define PNG_FREE_LIST 0x0400
  180503. #define PNG_FREE_PLTE 0x1000
  180504. #define PNG_FREE_TRNS 0x2000
  180505. #define PNG_FREE_TEXT 0x4000
  180506. #define PNG_FREE_ALL 0x7fff
  180507. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  180508. #ifdef PNG_USER_MEM_SUPPORTED
  180509. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  180510. png_uint_32 size));
  180511. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  180512. png_voidp ptr));
  180513. #endif
  180514. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  180515. png_voidp s1, png_voidp s2, png_uint_32 size));
  180516. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  180517. png_voidp s1, int value, png_uint_32 size));
  180518. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  180519. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  180520. int check));
  180521. #endif /* USE_FAR_KEYWORD */
  180522. #ifndef PNG_NO_ERROR_TEXT
  180523. /* Fatal error in PNG image of libpng - can't continue */
  180524. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  180525. png_const_charp error_message));
  180526. /* The same, but the chunk name is prepended to the error string. */
  180527. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  180528. png_const_charp error_message));
  180529. #else
  180530. /* Fatal error in PNG image of libpng - can't continue */
  180531. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  180532. #endif
  180533. #ifndef PNG_NO_WARNINGS
  180534. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  180535. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  180536. png_const_charp warning_message));
  180537. #ifdef PNG_READ_SUPPORTED
  180538. /* Non-fatal error in libpng, chunk name is prepended to message. */
  180539. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  180540. png_const_charp warning_message));
  180541. #endif /* PNG_READ_SUPPORTED */
  180542. #endif /* PNG_NO_WARNINGS */
  180543. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  180544. * Similarly, the png_get_<chunk> calls are used to read values from the
  180545. * png_info_struct, either storing the parameters in the passed variables, or
  180546. * setting pointers into the png_info_struct where the data is stored. The
  180547. * png_get_<chunk> functions return a non-zero value if the data was available
  180548. * in info_ptr, or return zero and do not change any of the parameters if the
  180549. * data was not available.
  180550. *
  180551. * These functions should be used instead of directly accessing png_info
  180552. * to avoid problems with future changes in the size and internal layout of
  180553. * png_info_struct.
  180554. */
  180555. /* Returns "flag" if chunk data is valid in info_ptr. */
  180556. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  180557. png_infop info_ptr, png_uint_32 flag));
  180558. /* Returns number of bytes needed to hold a transformed row. */
  180559. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  180560. png_infop info_ptr));
  180561. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  180562. /* Returns row_pointers, which is an array of pointers to scanlines that was
  180563. returned from png_read_png(). */
  180564. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  180565. png_infop info_ptr));
  180566. /* Set row_pointers, which is an array of pointers to scanlines for use
  180567. by png_write_png(). */
  180568. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  180569. png_infop info_ptr, png_bytepp row_pointers));
  180570. #endif
  180571. /* Returns number of color channels in image. */
  180572. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  180573. png_infop info_ptr));
  180574. #ifdef PNG_EASY_ACCESS_SUPPORTED
  180575. /* Returns image width in pixels. */
  180576. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  180577. png_ptr, png_infop info_ptr));
  180578. /* Returns image height in pixels. */
  180579. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  180580. png_ptr, png_infop info_ptr));
  180581. /* Returns image bit_depth. */
  180582. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  180583. png_ptr, png_infop info_ptr));
  180584. /* Returns image color_type. */
  180585. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  180586. png_ptr, png_infop info_ptr));
  180587. /* Returns image filter_type. */
  180588. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  180589. png_ptr, png_infop info_ptr));
  180590. /* Returns image interlace_type. */
  180591. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  180592. png_ptr, png_infop info_ptr));
  180593. /* Returns image compression_type. */
  180594. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  180595. png_ptr, png_infop info_ptr));
  180596. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  180597. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  180598. png_ptr, png_infop info_ptr));
  180599. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  180600. png_ptr, png_infop info_ptr));
  180601. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  180602. png_ptr, png_infop info_ptr));
  180603. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  180604. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180605. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  180606. png_ptr, png_infop info_ptr));
  180607. #endif
  180608. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  180609. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  180610. png_ptr, png_infop info_ptr));
  180611. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  180612. png_ptr, png_infop info_ptr));
  180613. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  180614. png_ptr, png_infop info_ptr));
  180615. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  180616. png_ptr, png_infop info_ptr));
  180617. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  180618. /* Returns pointer to signature string read from PNG header */
  180619. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  180620. png_infop info_ptr));
  180621. #if defined(PNG_bKGD_SUPPORTED)
  180622. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  180623. png_infop info_ptr, png_color_16p *background));
  180624. #endif
  180625. #if defined(PNG_bKGD_SUPPORTED)
  180626. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  180627. png_infop info_ptr, png_color_16p background));
  180628. #endif
  180629. #if defined(PNG_cHRM_SUPPORTED)
  180630. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180631. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  180632. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  180633. double *red_y, double *green_x, double *green_y, double *blue_x,
  180634. double *blue_y));
  180635. #endif
  180636. #ifdef PNG_FIXED_POINT_SUPPORTED
  180637. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  180638. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  180639. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  180640. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  180641. *int_blue_x, png_fixed_point *int_blue_y));
  180642. #endif
  180643. #endif
  180644. #if defined(PNG_cHRM_SUPPORTED)
  180645. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180646. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  180647. png_infop info_ptr, double white_x, double white_y, double red_x,
  180648. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  180649. #endif
  180650. #ifdef PNG_FIXED_POINT_SUPPORTED
  180651. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  180652. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  180653. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  180654. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  180655. png_fixed_point int_blue_y));
  180656. #endif
  180657. #endif
  180658. #if defined(PNG_gAMA_SUPPORTED)
  180659. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180660. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  180661. png_infop info_ptr, double *file_gamma));
  180662. #endif
  180663. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  180664. png_infop info_ptr, png_fixed_point *int_file_gamma));
  180665. #endif
  180666. #if defined(PNG_gAMA_SUPPORTED)
  180667. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180668. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  180669. png_infop info_ptr, double file_gamma));
  180670. #endif
  180671. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  180672. png_infop info_ptr, png_fixed_point int_file_gamma));
  180673. #endif
  180674. #if defined(PNG_hIST_SUPPORTED)
  180675. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  180676. png_infop info_ptr, png_uint_16p *hist));
  180677. #endif
  180678. #if defined(PNG_hIST_SUPPORTED)
  180679. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  180680. png_infop info_ptr, png_uint_16p hist));
  180681. #endif
  180682. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  180683. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  180684. int *bit_depth, int *color_type, int *interlace_method,
  180685. int *compression_method, int *filter_method));
  180686. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  180687. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  180688. int color_type, int interlace_method, int compression_method,
  180689. int filter_method));
  180690. #if defined(PNG_oFFs_SUPPORTED)
  180691. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  180692. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  180693. int *unit_type));
  180694. #endif
  180695. #if defined(PNG_oFFs_SUPPORTED)
  180696. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  180697. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  180698. int unit_type));
  180699. #endif
  180700. #if defined(PNG_pCAL_SUPPORTED)
  180701. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  180702. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  180703. int *type, int *nparams, png_charp *units, png_charpp *params));
  180704. #endif
  180705. #if defined(PNG_pCAL_SUPPORTED)
  180706. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  180707. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  180708. int type, int nparams, png_charp units, png_charpp params));
  180709. #endif
  180710. #if defined(PNG_pHYs_SUPPORTED)
  180711. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  180712. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  180713. #endif
  180714. #if defined(PNG_pHYs_SUPPORTED)
  180715. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  180716. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  180717. #endif
  180718. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  180719. png_infop info_ptr, png_colorp *palette, int *num_palette));
  180720. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  180721. png_infop info_ptr, png_colorp palette, int num_palette));
  180722. #if defined(PNG_sBIT_SUPPORTED)
  180723. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  180724. png_infop info_ptr, png_color_8p *sig_bit));
  180725. #endif
  180726. #if defined(PNG_sBIT_SUPPORTED)
  180727. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  180728. png_infop info_ptr, png_color_8p sig_bit));
  180729. #endif
  180730. #if defined(PNG_sRGB_SUPPORTED)
  180731. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  180732. png_infop info_ptr, int *intent));
  180733. #endif
  180734. #if defined(PNG_sRGB_SUPPORTED)
  180735. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  180736. png_infop info_ptr, int intent));
  180737. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  180738. png_infop info_ptr, int intent));
  180739. #endif
  180740. #if defined(PNG_iCCP_SUPPORTED)
  180741. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  180742. png_infop info_ptr, png_charpp name, int *compression_type,
  180743. png_charpp profile, png_uint_32 *proflen));
  180744. /* Note to maintainer: profile should be png_bytepp */
  180745. #endif
  180746. #if defined(PNG_iCCP_SUPPORTED)
  180747. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  180748. png_infop info_ptr, png_charp name, int compression_type,
  180749. png_charp profile, png_uint_32 proflen));
  180750. /* Note to maintainer: profile should be png_bytep */
  180751. #endif
  180752. #if defined(PNG_sPLT_SUPPORTED)
  180753. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  180754. png_infop info_ptr, png_sPLT_tpp entries));
  180755. #endif
  180756. #if defined(PNG_sPLT_SUPPORTED)
  180757. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  180758. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  180759. #endif
  180760. #if defined(PNG_TEXT_SUPPORTED)
  180761. /* png_get_text also returns the number of text chunks in *num_text */
  180762. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  180763. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  180764. #endif
  180765. /*
  180766. * Note while png_set_text() will accept a structure whose text,
  180767. * language, and translated keywords are NULL pointers, the structure
  180768. * returned by png_get_text will always contain regular
  180769. * zero-terminated C strings. They might be empty strings but
  180770. * they will never be NULL pointers.
  180771. */
  180772. #if defined(PNG_TEXT_SUPPORTED)
  180773. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  180774. png_infop info_ptr, png_textp text_ptr, int num_text));
  180775. #endif
  180776. #if defined(PNG_tIME_SUPPORTED)
  180777. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  180778. png_infop info_ptr, png_timep *mod_time));
  180779. #endif
  180780. #if defined(PNG_tIME_SUPPORTED)
  180781. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  180782. png_infop info_ptr, png_timep mod_time));
  180783. #endif
  180784. #if defined(PNG_tRNS_SUPPORTED)
  180785. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  180786. png_infop info_ptr, png_bytep *trans, int *num_trans,
  180787. png_color_16p *trans_values));
  180788. #endif
  180789. #if defined(PNG_tRNS_SUPPORTED)
  180790. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  180791. png_infop info_ptr, png_bytep trans, int num_trans,
  180792. png_color_16p trans_values));
  180793. #endif
  180794. #if defined(PNG_tRNS_SUPPORTED)
  180795. #endif
  180796. #if defined(PNG_sCAL_SUPPORTED)
  180797. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180798. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  180799. png_infop info_ptr, int *unit, double *width, double *height));
  180800. #else
  180801. #ifdef PNG_FIXED_POINT_SUPPORTED
  180802. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  180803. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  180804. #endif
  180805. #endif
  180806. #endif /* PNG_sCAL_SUPPORTED */
  180807. #if defined(PNG_sCAL_SUPPORTED)
  180808. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180809. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  180810. png_infop info_ptr, int unit, double width, double height));
  180811. #else
  180812. #ifdef PNG_FIXED_POINT_SUPPORTED
  180813. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  180814. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  180815. #endif
  180816. #endif
  180817. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  180818. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  180819. /* provide a list of chunks and how they are to be handled, if the built-in
  180820. handling or default unknown chunk handling is not desired. Any chunks not
  180821. listed will be handled in the default manner. The IHDR and IEND chunks
  180822. must not be listed.
  180823. keep = 0: follow default behaviour
  180824. = 1: do not keep
  180825. = 2: keep only if safe-to-copy
  180826. = 3: keep even if unsafe-to-copy
  180827. */
  180828. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  180829. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  180830. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  180831. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  180832. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  180833. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  180834. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  180835. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  180836. #endif
  180837. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  180838. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  180839. chunk_name));
  180840. #endif
  180841. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  180842. If you need to turn it off for a chunk that your application has freed,
  180843. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  180844. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  180845. png_infop info_ptr, int mask));
  180846. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  180847. /* The "params" pointer is currently not used and is for future expansion. */
  180848. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  180849. png_infop info_ptr,
  180850. int transforms,
  180851. png_voidp params));
  180852. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  180853. png_infop info_ptr,
  180854. int transforms,
  180855. png_voidp params));
  180856. #endif
  180857. /* Define PNG_DEBUG at compile time for debugging information. Higher
  180858. * numbers for PNG_DEBUG mean more debugging information. This has
  180859. * only been added since version 0.95 so it is not implemented throughout
  180860. * libpng yet, but more support will be added as needed.
  180861. */
  180862. #ifdef PNG_DEBUG
  180863. #if (PNG_DEBUG > 0)
  180864. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  180865. #include <crtdbg.h>
  180866. #if (PNG_DEBUG > 1)
  180867. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  180868. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  180869. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  180870. #endif
  180871. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  180872. #ifndef PNG_DEBUG_FILE
  180873. #define PNG_DEBUG_FILE stderr
  180874. #endif /* PNG_DEBUG_FILE */
  180875. #if (PNG_DEBUG > 1)
  180876. #define png_debug(l,m) \
  180877. { \
  180878. int num_tabs=l; \
  180879. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  180880. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  180881. }
  180882. #define png_debug1(l,m,p1) \
  180883. { \
  180884. int num_tabs=l; \
  180885. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  180886. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  180887. }
  180888. #define png_debug2(l,m,p1,p2) \
  180889. { \
  180890. int num_tabs=l; \
  180891. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  180892. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  180893. }
  180894. #endif /* (PNG_DEBUG > 1) */
  180895. #endif /* _MSC_VER */
  180896. #endif /* (PNG_DEBUG > 0) */
  180897. #endif /* PNG_DEBUG */
  180898. #ifndef png_debug
  180899. #define png_debug(l, m)
  180900. #endif
  180901. #ifndef png_debug1
  180902. #define png_debug1(l, m, p1)
  180903. #endif
  180904. #ifndef png_debug2
  180905. #define png_debug2(l, m, p1, p2)
  180906. #endif
  180907. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  180908. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  180909. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  180910. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  180911. #ifdef PNG_MNG_FEATURES_SUPPORTED
  180912. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  180913. png_ptr, png_uint_32 mng_features_permitted));
  180914. #endif
  180915. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  180916. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  180917. #define PNG_HANDLE_CHUNK_NEVER 1
  180918. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  180919. #define PNG_HANDLE_CHUNK_ALWAYS 3
  180920. /* Added to version 1.2.0 */
  180921. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  180922. #if defined(PNG_MMX_CODE_SUPPORTED)
  180923. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  180924. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  180925. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  180926. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  180927. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  180928. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  180929. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  180930. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  180931. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  180932. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  180933. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  180934. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  180935. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  180936. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  180937. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  180938. #define PNG_MMX_WRITE_FLAGS ( 0 )
  180939. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  180940. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  180941. | PNG_MMX_READ_FLAGS \
  180942. | PNG_MMX_WRITE_FLAGS )
  180943. #define PNG_SELECT_READ 1
  180944. #define PNG_SELECT_WRITE 2
  180945. #endif /* PNG_MMX_CODE_SUPPORTED */
  180946. #if !defined(PNG_1_0_X)
  180947. /* pngget.c */
  180948. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  180949. PNGARG((int flag_select, int *compilerID));
  180950. /* pngget.c */
  180951. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  180952. PNGARG((int flag_select));
  180953. /* pngget.c */
  180954. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  180955. PNGARG((png_structp png_ptr));
  180956. /* pngget.c */
  180957. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  180958. PNGARG((png_structp png_ptr));
  180959. /* pngget.c */
  180960. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  180961. PNGARG((png_structp png_ptr));
  180962. /* pngset.c */
  180963. extern PNG_EXPORT(void,png_set_asm_flags)
  180964. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  180965. /* pngset.c */
  180966. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  180967. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  180968. png_uint_32 mmx_rowbytes_threshold));
  180969. #endif /* PNG_1_0_X */
  180970. #if !defined(PNG_1_0_X)
  180971. /* png.c, pnggccrd.c, or pngvcrd.c */
  180972. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  180973. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  180974. /* Strip the prepended error numbers ("#nnn ") from error and warning
  180975. * messages before passing them to the error or warning handler. */
  180976. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  180977. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  180978. png_ptr, png_uint_32 strip_mode));
  180979. #endif
  180980. #endif /* PNG_1_0_X */
  180981. /* Added at libpng-1.2.6 */
  180982. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  180983. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  180984. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  180985. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  180986. png_ptr));
  180987. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  180988. png_ptr));
  180989. #endif
  180990. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  180991. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  180992. /* With these routines we avoid an integer divide, which will be slower on
  180993. * most machines. However, it does take more operations than the corresponding
  180994. * divide method, so it may be slower on a few RISC systems. There are two
  180995. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  180996. *
  180997. * Note that the rounding factors are NOT supposed to be the same! 128 and
  180998. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  180999. * standard method.
  181000. *
  181001. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  181002. */
  181003. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  181004. # define png_composite(composite, fg, alpha, bg) \
  181005. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  181006. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  181007. (png_uint_16)(alpha)) + (png_uint_16)128); \
  181008. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  181009. # define png_composite_16(composite, fg, alpha, bg) \
  181010. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  181011. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  181012. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  181013. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  181014. #else /* standard method using integer division */
  181015. # define png_composite(composite, fg, alpha, bg) \
  181016. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  181017. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  181018. (png_uint_16)127) / 255)
  181019. # define png_composite_16(composite, fg, alpha, bg) \
  181020. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  181021. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  181022. (png_uint_32)32767) / (png_uint_32)65535L)
  181023. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  181024. /* Inline macros to do direct reads of bytes from the input buffer. These
  181025. * require that you are using an architecture that uses PNG byte ordering
  181026. * (MSB first) and supports unaligned data storage. I think that PowerPC
  181027. * in big-endian mode and 680x0 are the only ones that will support this.
  181028. * The x86 line of processors definitely do not. The png_get_int_32()
  181029. * routine also assumes we are using two's complement format for negative
  181030. * values, which is almost certainly true.
  181031. */
  181032. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  181033. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  181034. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  181035. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  181036. #else
  181037. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  181038. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  181039. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  181040. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  181041. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  181042. PNGARG((png_structp png_ptr, png_bytep buf));
  181043. /* No png_get_int_16 -- may be added if there's a real need for it. */
  181044. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  181045. */
  181046. extern PNG_EXPORT(void,png_save_uint_32)
  181047. PNGARG((png_bytep buf, png_uint_32 i));
  181048. extern PNG_EXPORT(void,png_save_int_32)
  181049. PNGARG((png_bytep buf, png_int_32 i));
  181050. /* Place a 16-bit number into a buffer in PNG byte order.
  181051. * The parameter is declared unsigned int, not png_uint_16,
  181052. * just to avoid potential problems on pre-ANSI C compilers.
  181053. */
  181054. extern PNG_EXPORT(void,png_save_uint_16)
  181055. PNGARG((png_bytep buf, unsigned int i));
  181056. /* No png_save_int_16 -- may be added if there's a real need for it. */
  181057. /* ************************************************************************* */
  181058. /* These next functions are used internally in the code. They generally
  181059. * shouldn't be used unless you are writing code to add or replace some
  181060. * functionality in libpng. More information about most functions can
  181061. * be found in the files where the functions are located.
  181062. */
  181063. /* Various modes of operation, that are visible to applications because
  181064. * they are used for unknown chunk location.
  181065. */
  181066. #define PNG_HAVE_IHDR 0x01
  181067. #define PNG_HAVE_PLTE 0x02
  181068. #define PNG_HAVE_IDAT 0x04
  181069. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  181070. #define PNG_HAVE_IEND 0x10
  181071. #if defined(PNG_INTERNAL)
  181072. /* More modes of operation. Note that after an init, mode is set to
  181073. * zero automatically when the structure is created.
  181074. */
  181075. #define PNG_HAVE_gAMA 0x20
  181076. #define PNG_HAVE_cHRM 0x40
  181077. #define PNG_HAVE_sRGB 0x80
  181078. #define PNG_HAVE_CHUNK_HEADER 0x100
  181079. #define PNG_WROTE_tIME 0x200
  181080. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  181081. #define PNG_BACKGROUND_IS_GRAY 0x800
  181082. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  181083. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  181084. /* flags for the transformations the PNG library does on the image data */
  181085. #define PNG_BGR 0x0001
  181086. #define PNG_INTERLACE 0x0002
  181087. #define PNG_PACK 0x0004
  181088. #define PNG_SHIFT 0x0008
  181089. #define PNG_SWAP_BYTES 0x0010
  181090. #define PNG_INVERT_MONO 0x0020
  181091. #define PNG_DITHER 0x0040
  181092. #define PNG_BACKGROUND 0x0080
  181093. #define PNG_BACKGROUND_EXPAND 0x0100
  181094. /* 0x0200 unused */
  181095. #define PNG_16_TO_8 0x0400
  181096. #define PNG_RGBA 0x0800
  181097. #define PNG_EXPAND 0x1000
  181098. #define PNG_GAMMA 0x2000
  181099. #define PNG_GRAY_TO_RGB 0x4000
  181100. #define PNG_FILLER 0x8000L
  181101. #define PNG_PACKSWAP 0x10000L
  181102. #define PNG_SWAP_ALPHA 0x20000L
  181103. #define PNG_STRIP_ALPHA 0x40000L
  181104. #define PNG_INVERT_ALPHA 0x80000L
  181105. #define PNG_USER_TRANSFORM 0x100000L
  181106. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  181107. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  181108. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  181109. /* 0x800000L Unused */
  181110. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  181111. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  181112. /* 0x4000000L unused */
  181113. /* 0x8000000L unused */
  181114. /* 0x10000000L unused */
  181115. /* 0x20000000L unused */
  181116. /* 0x40000000L unused */
  181117. /* flags for png_create_struct */
  181118. #define PNG_STRUCT_PNG 0x0001
  181119. #define PNG_STRUCT_INFO 0x0002
  181120. /* Scaling factor for filter heuristic weighting calculations */
  181121. #define PNG_WEIGHT_SHIFT 8
  181122. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  181123. #define PNG_COST_SHIFT 3
  181124. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  181125. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  181126. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  181127. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  181128. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  181129. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  181130. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  181131. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  181132. #define PNG_FLAG_ROW_INIT 0x0040
  181133. #define PNG_FLAG_FILLER_AFTER 0x0080
  181134. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  181135. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  181136. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  181137. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  181138. #define PNG_FLAG_FREE_PLTE 0x1000
  181139. #define PNG_FLAG_FREE_TRNS 0x2000
  181140. #define PNG_FLAG_FREE_HIST 0x4000
  181141. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  181142. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  181143. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  181144. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  181145. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  181146. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  181147. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  181148. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  181149. /* 0x800000L unused */
  181150. /* 0x1000000L unused */
  181151. /* 0x2000000L unused */
  181152. /* 0x4000000L unused */
  181153. /* 0x8000000L unused */
  181154. /* 0x10000000L unused */
  181155. /* 0x20000000L unused */
  181156. /* 0x40000000L unused */
  181157. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  181158. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  181159. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  181160. PNG_FLAG_CRC_CRITICAL_IGNORE)
  181161. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  181162. PNG_FLAG_CRC_CRITICAL_MASK)
  181163. /* save typing and make code easier to understand */
  181164. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  181165. abs((int)((c1).green) - (int)((c2).green)) + \
  181166. abs((int)((c1).blue) - (int)((c2).blue)))
  181167. /* Added to libpng-1.2.6 JB */
  181168. #define PNG_ROWBYTES(pixel_bits, width) \
  181169. ((pixel_bits) >= 8 ? \
  181170. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  181171. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  181172. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  181173. ideal-delta..ideal+delta. Each argument is evaluated twice.
  181174. "ideal" and "delta" should be constants, normally simple
  181175. integers, "value" a variable. Added to libpng-1.2.6 JB */
  181176. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  181177. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  181178. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  181179. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  181180. /* place to hold the signature string for a PNG file. */
  181181. #ifdef PNG_USE_GLOBAL_ARRAYS
  181182. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  181183. #else
  181184. #endif
  181185. #endif /* PNG_NO_EXTERN */
  181186. /* Constant strings for known chunk types. If you need to add a chunk,
  181187. * define the name here, and add an invocation of the macro in png.c and
  181188. * wherever it's needed.
  181189. */
  181190. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  181191. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  181192. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  181193. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  181194. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  181195. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  181196. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  181197. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  181198. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  181199. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  181200. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  181201. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  181202. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  181203. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  181204. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  181205. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  181206. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  181207. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  181208. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  181209. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  181210. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  181211. #ifdef PNG_USE_GLOBAL_ARRAYS
  181212. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  181213. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  181214. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  181215. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  181216. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  181217. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  181218. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  181219. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  181220. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  181221. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  181222. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  181223. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  181224. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  181225. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  181226. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  181227. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  181228. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  181229. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  181230. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  181231. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  181232. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  181233. #endif /* PNG_USE_GLOBAL_ARRAYS */
  181234. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181235. /* Initialize png_ptr struct for reading, and allocate any other memory.
  181236. * (old interface - DEPRECATED - use png_create_read_struct instead).
  181237. */
  181238. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  181239. #undef png_read_init
  181240. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  181241. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  181242. #endif
  181243. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  181244. png_const_charp user_png_ver, png_size_t png_struct_size));
  181245. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181246. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  181247. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  181248. png_info_size));
  181249. #endif
  181250. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181251. /* Initialize png_ptr struct for writing, and allocate any other memory.
  181252. * (old interface - DEPRECATED - use png_create_write_struct instead).
  181253. */
  181254. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  181255. #undef png_write_init
  181256. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  181257. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  181258. #endif
  181259. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  181260. png_const_charp user_png_ver, png_size_t png_struct_size));
  181261. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  181262. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  181263. png_info_size));
  181264. /* Allocate memory for an internal libpng struct */
  181265. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  181266. /* Free memory from internal libpng struct */
  181267. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  181268. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  181269. malloc_fn, png_voidp mem_ptr));
  181270. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  181271. png_free_ptr free_fn, png_voidp mem_ptr));
  181272. /* Free any memory that info_ptr points to and reset struct. */
  181273. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  181274. png_infop info_ptr));
  181275. #ifndef PNG_1_0_X
  181276. /* Function to allocate memory for zlib. */
  181277. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  181278. /* Function to free memory for zlib */
  181279. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  181280. #ifdef PNG_SIZE_T
  181281. /* Function to convert a sizeof an item to png_sizeof item */
  181282. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  181283. #endif
  181284. /* Next four functions are used internally as callbacks. PNGAPI is required
  181285. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  181286. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  181287. png_bytep data, png_size_t length));
  181288. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  181289. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  181290. png_bytep buffer, png_size_t length));
  181291. #endif
  181292. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  181293. png_bytep data, png_size_t length));
  181294. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  181295. #if !defined(PNG_NO_STDIO)
  181296. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  181297. #endif
  181298. #endif
  181299. #else /* PNG_1_0_X */
  181300. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  181301. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  181302. png_bytep buffer, png_size_t length));
  181303. #endif
  181304. #endif /* PNG_1_0_X */
  181305. /* Reset the CRC variable */
  181306. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  181307. /* Write the "data" buffer to whatever output you are using. */
  181308. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  181309. png_size_t length));
  181310. /* Read data from whatever input you are using into the "data" buffer */
  181311. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  181312. png_size_t length));
  181313. /* Read bytes into buf, and update png_ptr->crc */
  181314. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  181315. png_size_t length));
  181316. /* Decompress data in a chunk that uses compression */
  181317. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  181318. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  181319. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  181320. int comp_type, png_charp chunkdata, png_size_t chunklength,
  181321. png_size_t prefix_length, png_size_t *data_length));
  181322. #endif
  181323. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  181324. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  181325. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  181326. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  181327. /* Calculate the CRC over a section of data. Note that we are only
  181328. * passing a maximum of 64K on systems that have this as a memory limit,
  181329. * since this is the maximum buffer size we can specify.
  181330. */
  181331. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  181332. png_size_t length));
  181333. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  181334. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  181335. #endif
  181336. /* simple function to write the signature */
  181337. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  181338. /* write various chunks */
  181339. /* Write the IHDR chunk, and update the png_struct with the necessary
  181340. * information.
  181341. */
  181342. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  181343. png_uint_32 height,
  181344. int bit_depth, int color_type, int compression_method, int filter_method,
  181345. int interlace_method));
  181346. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  181347. png_uint_32 num_pal));
  181348. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  181349. png_size_t length));
  181350. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  181351. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  181352. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181353. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  181354. #endif
  181355. #ifdef PNG_FIXED_POINT_SUPPORTED
  181356. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  181357. file_gamma));
  181358. #endif
  181359. #endif
  181360. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  181361. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  181362. int color_type));
  181363. #endif
  181364. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  181365. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181366. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  181367. double white_x, double white_y,
  181368. double red_x, double red_y, double green_x, double green_y,
  181369. double blue_x, double blue_y));
  181370. #endif
  181371. #ifdef PNG_FIXED_POINT_SUPPORTED
  181372. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  181373. png_fixed_point int_white_x, png_fixed_point int_white_y,
  181374. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  181375. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  181376. png_fixed_point int_blue_y));
  181377. #endif
  181378. #endif
  181379. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  181380. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  181381. int intent));
  181382. #endif
  181383. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  181384. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  181385. png_charp name, int compression_type,
  181386. png_charp profile, int proflen));
  181387. /* Note to maintainer: profile should be png_bytep */
  181388. #endif
  181389. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  181390. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  181391. png_sPLT_tp palette));
  181392. #endif
  181393. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  181394. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  181395. png_color_16p values, int number, int color_type));
  181396. #endif
  181397. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  181398. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  181399. png_color_16p values, int color_type));
  181400. #endif
  181401. #if defined(PNG_WRITE_hIST_SUPPORTED)
  181402. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  181403. int num_hist));
  181404. #endif
  181405. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  181406. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  181407. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  181408. png_charp key, png_charpp new_key));
  181409. #endif
  181410. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  181411. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  181412. png_charp text, png_size_t text_len));
  181413. #endif
  181414. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  181415. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  181416. png_charp text, png_size_t text_len, int compression));
  181417. #endif
  181418. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  181419. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  181420. int compression, png_charp key, png_charp lang, png_charp lang_key,
  181421. png_charp text));
  181422. #endif
  181423. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  181424. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  181425. png_infop info_ptr, png_textp text_ptr, int num_text));
  181426. #endif
  181427. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  181428. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  181429. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  181430. #endif
  181431. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  181432. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  181433. png_int_32 X0, png_int_32 X1, int type, int nparams,
  181434. png_charp units, png_charpp params));
  181435. #endif
  181436. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  181437. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  181438. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  181439. int unit_type));
  181440. #endif
  181441. #if defined(PNG_WRITE_tIME_SUPPORTED)
  181442. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  181443. png_timep mod_time));
  181444. #endif
  181445. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  181446. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  181447. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  181448. int unit, double width, double height));
  181449. #else
  181450. #ifdef PNG_FIXED_POINT_SUPPORTED
  181451. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  181452. int unit, png_charp width, png_charp height));
  181453. #endif
  181454. #endif
  181455. #endif
  181456. /* Called when finished processing a row of data */
  181457. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  181458. /* Internal use only. Called before first row of data */
  181459. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  181460. #if defined(PNG_READ_GAMMA_SUPPORTED)
  181461. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  181462. #endif
  181463. /* combine a row of data, dealing with alpha, etc. if requested */
  181464. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  181465. int mask));
  181466. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  181467. /* expand an interlaced row */
  181468. /* OLD pre-1.0.9 interface:
  181469. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  181470. png_bytep row, int pass, png_uint_32 transformations));
  181471. */
  181472. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  181473. #endif
  181474. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  181475. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  181476. /* grab pixels out of a row for an interlaced pass */
  181477. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  181478. png_bytep row, int pass));
  181479. #endif
  181480. /* unfilter a row */
  181481. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  181482. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  181483. /* Choose the best filter to use and filter the row data */
  181484. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  181485. png_row_infop row_info));
  181486. /* Write out the filtered row. */
  181487. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  181488. png_bytep filtered_row));
  181489. /* finish a row while reading, dealing with interlacing passes, etc. */
  181490. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  181491. /* initialize the row buffers, etc. */
  181492. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  181493. /* optional call to update the users info structure */
  181494. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  181495. png_infop info_ptr));
  181496. /* these are the functions that do the transformations */
  181497. #if defined(PNG_READ_FILLER_SUPPORTED)
  181498. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  181499. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  181500. #endif
  181501. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  181502. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  181503. png_bytep row));
  181504. #endif
  181505. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  181506. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  181507. png_bytep row));
  181508. #endif
  181509. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  181510. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  181511. png_bytep row));
  181512. #endif
  181513. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  181514. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  181515. png_bytep row));
  181516. #endif
  181517. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  181518. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  181519. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  181520. png_bytep row, png_uint_32 flags));
  181521. #endif
  181522. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  181523. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  181524. #endif
  181525. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  181526. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  181527. #endif
  181528. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  181529. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  181530. row_info, png_bytep row));
  181531. #endif
  181532. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  181533. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  181534. png_bytep row));
  181535. #endif
  181536. #if defined(PNG_READ_PACK_SUPPORTED)
  181537. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  181538. #endif
  181539. #if defined(PNG_READ_SHIFT_SUPPORTED)
  181540. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  181541. png_color_8p sig_bits));
  181542. #endif
  181543. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  181544. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  181545. #endif
  181546. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  181547. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  181548. #endif
  181549. #if defined(PNG_READ_DITHER_SUPPORTED)
  181550. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  181551. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  181552. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  181553. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  181554. png_colorp palette, int num_palette));
  181555. # endif
  181556. #endif
  181557. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  181558. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  181559. #endif
  181560. #if defined(PNG_WRITE_PACK_SUPPORTED)
  181561. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  181562. png_bytep row, png_uint_32 bit_depth));
  181563. #endif
  181564. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  181565. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  181566. png_color_8p bit_depth));
  181567. #endif
  181568. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  181569. #if defined(PNG_READ_GAMMA_SUPPORTED)
  181570. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  181571. png_color_16p trans_values, png_color_16p background,
  181572. png_color_16p background_1,
  181573. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  181574. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  181575. png_uint_16pp gamma_16_to_1, int gamma_shift));
  181576. #else
  181577. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  181578. png_color_16p trans_values, png_color_16p background));
  181579. #endif
  181580. #endif
  181581. #if defined(PNG_READ_GAMMA_SUPPORTED)
  181582. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  181583. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  181584. int gamma_shift));
  181585. #endif
  181586. #if defined(PNG_READ_EXPAND_SUPPORTED)
  181587. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  181588. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  181589. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  181590. png_bytep row, png_color_16p trans_value));
  181591. #endif
  181592. /* The following decodes the appropriate chunks, and does error correction,
  181593. * then calls the appropriate callback for the chunk if it is valid.
  181594. */
  181595. /* decode the IHDR chunk */
  181596. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  181597. png_uint_32 length));
  181598. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  181599. png_uint_32 length));
  181600. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  181601. png_uint_32 length));
  181602. #if defined(PNG_READ_bKGD_SUPPORTED)
  181603. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  181604. png_uint_32 length));
  181605. #endif
  181606. #if defined(PNG_READ_cHRM_SUPPORTED)
  181607. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  181608. png_uint_32 length));
  181609. #endif
  181610. #if defined(PNG_READ_gAMA_SUPPORTED)
  181611. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  181612. png_uint_32 length));
  181613. #endif
  181614. #if defined(PNG_READ_hIST_SUPPORTED)
  181615. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  181616. png_uint_32 length));
  181617. #endif
  181618. #if defined(PNG_READ_iCCP_SUPPORTED)
  181619. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  181620. png_uint_32 length));
  181621. #endif /* PNG_READ_iCCP_SUPPORTED */
  181622. #if defined(PNG_READ_iTXt_SUPPORTED)
  181623. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  181624. png_uint_32 length));
  181625. #endif
  181626. #if defined(PNG_READ_oFFs_SUPPORTED)
  181627. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  181628. png_uint_32 length));
  181629. #endif
  181630. #if defined(PNG_READ_pCAL_SUPPORTED)
  181631. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  181632. png_uint_32 length));
  181633. #endif
  181634. #if defined(PNG_READ_pHYs_SUPPORTED)
  181635. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  181636. png_uint_32 length));
  181637. #endif
  181638. #if defined(PNG_READ_sBIT_SUPPORTED)
  181639. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  181640. png_uint_32 length));
  181641. #endif
  181642. #if defined(PNG_READ_sCAL_SUPPORTED)
  181643. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  181644. png_uint_32 length));
  181645. #endif
  181646. #if defined(PNG_READ_sPLT_SUPPORTED)
  181647. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  181648. png_uint_32 length));
  181649. #endif /* PNG_READ_sPLT_SUPPORTED */
  181650. #if defined(PNG_READ_sRGB_SUPPORTED)
  181651. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  181652. png_uint_32 length));
  181653. #endif
  181654. #if defined(PNG_READ_tEXt_SUPPORTED)
  181655. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  181656. png_uint_32 length));
  181657. #endif
  181658. #if defined(PNG_READ_tIME_SUPPORTED)
  181659. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  181660. png_uint_32 length));
  181661. #endif
  181662. #if defined(PNG_READ_tRNS_SUPPORTED)
  181663. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  181664. png_uint_32 length));
  181665. #endif
  181666. #if defined(PNG_READ_zTXt_SUPPORTED)
  181667. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  181668. png_uint_32 length));
  181669. #endif
  181670. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  181671. png_infop info_ptr, png_uint_32 length));
  181672. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  181673. png_bytep chunk_name));
  181674. /* handle the transformations for reading and writing */
  181675. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  181676. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  181677. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  181678. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  181679. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  181680. png_infop info_ptr));
  181681. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  181682. png_infop info_ptr));
  181683. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  181684. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  181685. png_uint_32 length));
  181686. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  181687. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  181688. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  181689. png_bytep buffer, png_size_t buffer_length));
  181690. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  181691. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  181692. png_bytep buffer, png_size_t buffer_length));
  181693. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  181694. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  181695. png_infop info_ptr, png_uint_32 length));
  181696. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  181697. png_infop info_ptr));
  181698. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  181699. png_infop info_ptr));
  181700. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  181701. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  181702. png_infop info_ptr));
  181703. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  181704. png_infop info_ptr));
  181705. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  181706. #if defined(PNG_READ_tEXt_SUPPORTED)
  181707. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  181708. png_infop info_ptr, png_uint_32 length));
  181709. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  181710. png_infop info_ptr));
  181711. #endif
  181712. #if defined(PNG_READ_zTXt_SUPPORTED)
  181713. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  181714. png_infop info_ptr, png_uint_32 length));
  181715. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  181716. png_infop info_ptr));
  181717. #endif
  181718. #if defined(PNG_READ_iTXt_SUPPORTED)
  181719. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  181720. png_infop info_ptr, png_uint_32 length));
  181721. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  181722. png_infop info_ptr));
  181723. #endif
  181724. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  181725. #ifdef PNG_MNG_FEATURES_SUPPORTED
  181726. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  181727. png_bytep row));
  181728. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  181729. png_bytep row));
  181730. #endif
  181731. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  181732. #if defined(PNG_MMX_CODE_SUPPORTED)
  181733. /* png.c */ /* PRIVATE */
  181734. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  181735. #endif
  181736. #endif
  181737. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  181738. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  181739. png_infop info_ptr));
  181740. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  181741. png_infop info_ptr));
  181742. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  181743. png_infop info_ptr));
  181744. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  181745. png_infop info_ptr));
  181746. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  181747. png_infop info_ptr));
  181748. #if defined(PNG_pHYs_SUPPORTED)
  181749. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  181750. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  181751. #endif /* PNG_pHYs_SUPPORTED */
  181752. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  181753. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  181754. #endif /* PNG_INTERNAL */
  181755. #ifdef __cplusplus
  181756. }
  181757. #endif
  181758. #endif /* PNG_VERSION_INFO_ONLY */
  181759. /* do not put anything past this line */
  181760. #endif /* PNG_H */
  181761. /*** End of inlined file: png.h ***/
  181762. #define PNG_NO_EXTERN
  181763. /*** Start of inlined file: png.c ***/
  181764. /* png.c - location for general purpose libpng functions
  181765. *
  181766. * Last changed in libpng 1.2.21 [October 4, 2007]
  181767. * For conditions of distribution and use, see copyright notice in png.h
  181768. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  181769. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  181770. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  181771. */
  181772. #define PNG_INTERNAL
  181773. #define PNG_NO_EXTERN
  181774. /* Generate a compiler error if there is an old png.h in the search path. */
  181775. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  181776. /* Version information for C files. This had better match the version
  181777. * string defined in png.h. */
  181778. #ifdef PNG_USE_GLOBAL_ARRAYS
  181779. /* png_libpng_ver was changed to a function in version 1.0.5c */
  181780. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  181781. #ifdef PNG_READ_SUPPORTED
  181782. /* png_sig was changed to a function in version 1.0.5c */
  181783. /* Place to hold the signature string for a PNG file. */
  181784. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  181785. #endif /* PNG_READ_SUPPORTED */
  181786. /* Invoke global declarations for constant strings for known chunk types */
  181787. PNG_IHDR;
  181788. PNG_IDAT;
  181789. PNG_IEND;
  181790. PNG_PLTE;
  181791. PNG_bKGD;
  181792. PNG_cHRM;
  181793. PNG_gAMA;
  181794. PNG_hIST;
  181795. PNG_iCCP;
  181796. PNG_iTXt;
  181797. PNG_oFFs;
  181798. PNG_pCAL;
  181799. PNG_sCAL;
  181800. PNG_pHYs;
  181801. PNG_sBIT;
  181802. PNG_sPLT;
  181803. PNG_sRGB;
  181804. PNG_tEXt;
  181805. PNG_tIME;
  181806. PNG_tRNS;
  181807. PNG_zTXt;
  181808. #ifdef PNG_READ_SUPPORTED
  181809. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  181810. /* start of interlace block */
  181811. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  181812. /* offset to next interlace block */
  181813. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  181814. /* start of interlace block in the y direction */
  181815. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  181816. /* offset to next interlace block in the y direction */
  181817. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  181818. /* Height of interlace block. This is not currently used - if you need
  181819. * it, uncomment it here and in png.h
  181820. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  181821. */
  181822. /* Mask to determine which pixels are valid in a pass */
  181823. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  181824. /* Mask to determine which pixels to overwrite while displaying */
  181825. PNG_CONST int FARDATA png_pass_dsp_mask[]
  181826. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  181827. #endif /* PNG_READ_SUPPORTED */
  181828. #endif /* PNG_USE_GLOBAL_ARRAYS */
  181829. /* Tells libpng that we have already handled the first "num_bytes" bytes
  181830. * of the PNG file signature. If the PNG data is embedded into another
  181831. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  181832. * or write any of the magic bytes before it starts on the IHDR.
  181833. */
  181834. #ifdef PNG_READ_SUPPORTED
  181835. void PNGAPI
  181836. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  181837. {
  181838. if(png_ptr == NULL) return;
  181839. png_debug(1, "in png_set_sig_bytes\n");
  181840. if (num_bytes > 8)
  181841. png_error(png_ptr, "Too many bytes for PNG signature.");
  181842. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  181843. }
  181844. /* Checks whether the supplied bytes match the PNG signature. We allow
  181845. * checking less than the full 8-byte signature so that those apps that
  181846. * already read the first few bytes of a file to determine the file type
  181847. * can simply check the remaining bytes for extra assurance. Returns
  181848. * an integer less than, equal to, or greater than zero if sig is found,
  181849. * respectively, to be less than, to match, or be greater than the correct
  181850. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  181851. */
  181852. int PNGAPI
  181853. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  181854. {
  181855. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  181856. if (num_to_check > 8)
  181857. num_to_check = 8;
  181858. else if (num_to_check < 1)
  181859. return (-1);
  181860. if (start > 7)
  181861. return (-1);
  181862. if (start + num_to_check > 8)
  181863. num_to_check = 8 - start;
  181864. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  181865. }
  181866. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  181867. /* (Obsolete) function to check signature bytes. It does not allow one
  181868. * to check a partial signature. This function might be removed in the
  181869. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  181870. */
  181871. int PNGAPI
  181872. png_check_sig(png_bytep sig, int num)
  181873. {
  181874. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  181875. }
  181876. #endif
  181877. #endif /* PNG_READ_SUPPORTED */
  181878. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  181879. /* Function to allocate memory for zlib and clear it to 0. */
  181880. #ifdef PNG_1_0_X
  181881. voidpf PNGAPI
  181882. #else
  181883. voidpf /* private */
  181884. #endif
  181885. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  181886. {
  181887. png_voidp ptr;
  181888. png_structp p=(png_structp)png_ptr;
  181889. png_uint_32 save_flags=p->flags;
  181890. png_uint_32 num_bytes;
  181891. if(png_ptr == NULL) return (NULL);
  181892. if (items > PNG_UINT_32_MAX/size)
  181893. {
  181894. png_warning (p, "Potential overflow in png_zalloc()");
  181895. return (NULL);
  181896. }
  181897. num_bytes = (png_uint_32)items * size;
  181898. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  181899. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  181900. p->flags=save_flags;
  181901. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  181902. if (ptr == NULL)
  181903. return ((voidpf)ptr);
  181904. if (num_bytes > (png_uint_32)0x8000L)
  181905. {
  181906. png_memset(ptr, 0, (png_size_t)0x8000L);
  181907. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  181908. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  181909. }
  181910. else
  181911. {
  181912. png_memset(ptr, 0, (png_size_t)num_bytes);
  181913. }
  181914. #endif
  181915. return ((voidpf)ptr);
  181916. }
  181917. /* function to free memory for zlib */
  181918. #ifdef PNG_1_0_X
  181919. void PNGAPI
  181920. #else
  181921. void /* private */
  181922. #endif
  181923. png_zfree(voidpf png_ptr, voidpf ptr)
  181924. {
  181925. png_free((png_structp)png_ptr, (png_voidp)ptr);
  181926. }
  181927. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  181928. * in case CRC is > 32 bits to leave the top bits 0.
  181929. */
  181930. void /* PRIVATE */
  181931. png_reset_crc(png_structp png_ptr)
  181932. {
  181933. png_ptr->crc = crc32(0, Z_NULL, 0);
  181934. }
  181935. /* Calculate the CRC over a section of data. We can only pass as
  181936. * much data to this routine as the largest single buffer size. We
  181937. * also check that this data will actually be used before going to the
  181938. * trouble of calculating it.
  181939. */
  181940. void /* PRIVATE */
  181941. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  181942. {
  181943. int need_crc = 1;
  181944. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  181945. {
  181946. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  181947. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  181948. need_crc = 0;
  181949. }
  181950. else /* critical */
  181951. {
  181952. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  181953. need_crc = 0;
  181954. }
  181955. if (need_crc)
  181956. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  181957. }
  181958. /* Allocate the memory for an info_struct for the application. We don't
  181959. * really need the png_ptr, but it could potentially be useful in the
  181960. * future. This should be used in favour of malloc(png_sizeof(png_info))
  181961. * and png_info_init() so that applications that want to use a shared
  181962. * libpng don't have to be recompiled if png_info changes size.
  181963. */
  181964. png_infop PNGAPI
  181965. png_create_info_struct(png_structp png_ptr)
  181966. {
  181967. png_infop info_ptr;
  181968. png_debug(1, "in png_create_info_struct\n");
  181969. if(png_ptr == NULL) return (NULL);
  181970. #ifdef PNG_USER_MEM_SUPPORTED
  181971. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  181972. png_ptr->malloc_fn, png_ptr->mem_ptr);
  181973. #else
  181974. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  181975. #endif
  181976. if (info_ptr != NULL)
  181977. png_info_init_3(&info_ptr, png_sizeof(png_info));
  181978. return (info_ptr);
  181979. }
  181980. /* This function frees the memory associated with a single info struct.
  181981. * Normally, one would use either png_destroy_read_struct() or
  181982. * png_destroy_write_struct() to free an info struct, but this may be
  181983. * useful for some applications.
  181984. */
  181985. void PNGAPI
  181986. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  181987. {
  181988. png_infop info_ptr = NULL;
  181989. if(png_ptr == NULL) return;
  181990. png_debug(1, "in png_destroy_info_struct\n");
  181991. if (info_ptr_ptr != NULL)
  181992. info_ptr = *info_ptr_ptr;
  181993. if (info_ptr != NULL)
  181994. {
  181995. png_info_destroy(png_ptr, info_ptr);
  181996. #ifdef PNG_USER_MEM_SUPPORTED
  181997. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  181998. png_ptr->mem_ptr);
  181999. #else
  182000. png_destroy_struct((png_voidp)info_ptr);
  182001. #endif
  182002. *info_ptr_ptr = NULL;
  182003. }
  182004. }
  182005. /* Initialize the info structure. This is now an internal function (0.89)
  182006. * and applications using it are urged to use png_create_info_struct()
  182007. * instead.
  182008. */
  182009. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  182010. #undef png_info_init
  182011. void PNGAPI
  182012. png_info_init(png_infop info_ptr)
  182013. {
  182014. /* We only come here via pre-1.0.12-compiled applications */
  182015. png_info_init_3(&info_ptr, 0);
  182016. }
  182017. #endif
  182018. void PNGAPI
  182019. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  182020. {
  182021. png_infop info_ptr = *ptr_ptr;
  182022. if(info_ptr == NULL) return;
  182023. png_debug(1, "in png_info_init_3\n");
  182024. if(png_sizeof(png_info) > png_info_struct_size)
  182025. {
  182026. png_destroy_struct(info_ptr);
  182027. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  182028. *ptr_ptr = info_ptr;
  182029. }
  182030. /* set everything to 0 */
  182031. png_memset(info_ptr, 0, png_sizeof (png_info));
  182032. }
  182033. #ifdef PNG_FREE_ME_SUPPORTED
  182034. void PNGAPI
  182035. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  182036. int freer, png_uint_32 mask)
  182037. {
  182038. png_debug(1, "in png_data_freer\n");
  182039. if (png_ptr == NULL || info_ptr == NULL)
  182040. return;
  182041. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  182042. info_ptr->free_me |= mask;
  182043. else if(freer == PNG_USER_WILL_FREE_DATA)
  182044. info_ptr->free_me &= ~mask;
  182045. else
  182046. png_warning(png_ptr,
  182047. "Unknown freer parameter in png_data_freer.");
  182048. }
  182049. #endif
  182050. void PNGAPI
  182051. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  182052. int num)
  182053. {
  182054. png_debug(1, "in png_free_data\n");
  182055. if (png_ptr == NULL || info_ptr == NULL)
  182056. return;
  182057. #if defined(PNG_TEXT_SUPPORTED)
  182058. /* free text item num or (if num == -1) all text items */
  182059. #ifdef PNG_FREE_ME_SUPPORTED
  182060. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  182061. #else
  182062. if (mask & PNG_FREE_TEXT)
  182063. #endif
  182064. {
  182065. if (num != -1)
  182066. {
  182067. if (info_ptr->text && info_ptr->text[num].key)
  182068. {
  182069. png_free(png_ptr, info_ptr->text[num].key);
  182070. info_ptr->text[num].key = NULL;
  182071. }
  182072. }
  182073. else
  182074. {
  182075. int i;
  182076. for (i = 0; i < info_ptr->num_text; i++)
  182077. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  182078. png_free(png_ptr, info_ptr->text);
  182079. info_ptr->text = NULL;
  182080. info_ptr->num_text=0;
  182081. }
  182082. }
  182083. #endif
  182084. #if defined(PNG_tRNS_SUPPORTED)
  182085. /* free any tRNS entry */
  182086. #ifdef PNG_FREE_ME_SUPPORTED
  182087. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  182088. #else
  182089. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  182090. #endif
  182091. {
  182092. png_free(png_ptr, info_ptr->trans);
  182093. info_ptr->valid &= ~PNG_INFO_tRNS;
  182094. #ifndef PNG_FREE_ME_SUPPORTED
  182095. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  182096. #endif
  182097. info_ptr->trans = NULL;
  182098. }
  182099. #endif
  182100. #if defined(PNG_sCAL_SUPPORTED)
  182101. /* free any sCAL entry */
  182102. #ifdef PNG_FREE_ME_SUPPORTED
  182103. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  182104. #else
  182105. if (mask & PNG_FREE_SCAL)
  182106. #endif
  182107. {
  182108. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  182109. png_free(png_ptr, info_ptr->scal_s_width);
  182110. png_free(png_ptr, info_ptr->scal_s_height);
  182111. info_ptr->scal_s_width = NULL;
  182112. info_ptr->scal_s_height = NULL;
  182113. #endif
  182114. info_ptr->valid &= ~PNG_INFO_sCAL;
  182115. }
  182116. #endif
  182117. #if defined(PNG_pCAL_SUPPORTED)
  182118. /* free any pCAL entry */
  182119. #ifdef PNG_FREE_ME_SUPPORTED
  182120. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  182121. #else
  182122. if (mask & PNG_FREE_PCAL)
  182123. #endif
  182124. {
  182125. png_free(png_ptr, info_ptr->pcal_purpose);
  182126. png_free(png_ptr, info_ptr->pcal_units);
  182127. info_ptr->pcal_purpose = NULL;
  182128. info_ptr->pcal_units = NULL;
  182129. if (info_ptr->pcal_params != NULL)
  182130. {
  182131. int i;
  182132. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  182133. {
  182134. png_free(png_ptr, info_ptr->pcal_params[i]);
  182135. info_ptr->pcal_params[i]=NULL;
  182136. }
  182137. png_free(png_ptr, info_ptr->pcal_params);
  182138. info_ptr->pcal_params = NULL;
  182139. }
  182140. info_ptr->valid &= ~PNG_INFO_pCAL;
  182141. }
  182142. #endif
  182143. #if defined(PNG_iCCP_SUPPORTED)
  182144. /* free any iCCP entry */
  182145. #ifdef PNG_FREE_ME_SUPPORTED
  182146. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  182147. #else
  182148. if (mask & PNG_FREE_ICCP)
  182149. #endif
  182150. {
  182151. png_free(png_ptr, info_ptr->iccp_name);
  182152. png_free(png_ptr, info_ptr->iccp_profile);
  182153. info_ptr->iccp_name = NULL;
  182154. info_ptr->iccp_profile = NULL;
  182155. info_ptr->valid &= ~PNG_INFO_iCCP;
  182156. }
  182157. #endif
  182158. #if defined(PNG_sPLT_SUPPORTED)
  182159. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  182160. #ifdef PNG_FREE_ME_SUPPORTED
  182161. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  182162. #else
  182163. if (mask & PNG_FREE_SPLT)
  182164. #endif
  182165. {
  182166. if (num != -1)
  182167. {
  182168. if(info_ptr->splt_palettes)
  182169. {
  182170. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  182171. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  182172. info_ptr->splt_palettes[num].name = NULL;
  182173. info_ptr->splt_palettes[num].entries = NULL;
  182174. }
  182175. }
  182176. else
  182177. {
  182178. if(info_ptr->splt_palettes_num)
  182179. {
  182180. int i;
  182181. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  182182. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  182183. png_free(png_ptr, info_ptr->splt_palettes);
  182184. info_ptr->splt_palettes = NULL;
  182185. info_ptr->splt_palettes_num = 0;
  182186. }
  182187. info_ptr->valid &= ~PNG_INFO_sPLT;
  182188. }
  182189. }
  182190. #endif
  182191. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182192. if(png_ptr->unknown_chunk.data)
  182193. {
  182194. png_free(png_ptr, png_ptr->unknown_chunk.data);
  182195. png_ptr->unknown_chunk.data = NULL;
  182196. }
  182197. #ifdef PNG_FREE_ME_SUPPORTED
  182198. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  182199. #else
  182200. if (mask & PNG_FREE_UNKN)
  182201. #endif
  182202. {
  182203. if (num != -1)
  182204. {
  182205. if(info_ptr->unknown_chunks)
  182206. {
  182207. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  182208. info_ptr->unknown_chunks[num].data = NULL;
  182209. }
  182210. }
  182211. else
  182212. {
  182213. int i;
  182214. if(info_ptr->unknown_chunks_num)
  182215. {
  182216. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  182217. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  182218. png_free(png_ptr, info_ptr->unknown_chunks);
  182219. info_ptr->unknown_chunks = NULL;
  182220. info_ptr->unknown_chunks_num = 0;
  182221. }
  182222. }
  182223. }
  182224. #endif
  182225. #if defined(PNG_hIST_SUPPORTED)
  182226. /* free any hIST entry */
  182227. #ifdef PNG_FREE_ME_SUPPORTED
  182228. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  182229. #else
  182230. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  182231. #endif
  182232. {
  182233. png_free(png_ptr, info_ptr->hist);
  182234. info_ptr->hist = NULL;
  182235. info_ptr->valid &= ~PNG_INFO_hIST;
  182236. #ifndef PNG_FREE_ME_SUPPORTED
  182237. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  182238. #endif
  182239. }
  182240. #endif
  182241. /* free any PLTE entry that was internally allocated */
  182242. #ifdef PNG_FREE_ME_SUPPORTED
  182243. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  182244. #else
  182245. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  182246. #endif
  182247. {
  182248. png_zfree(png_ptr, info_ptr->palette);
  182249. info_ptr->palette = NULL;
  182250. info_ptr->valid &= ~PNG_INFO_PLTE;
  182251. #ifndef PNG_FREE_ME_SUPPORTED
  182252. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  182253. #endif
  182254. info_ptr->num_palette = 0;
  182255. }
  182256. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182257. /* free any image bits attached to the info structure */
  182258. #ifdef PNG_FREE_ME_SUPPORTED
  182259. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  182260. #else
  182261. if (mask & PNG_FREE_ROWS)
  182262. #endif
  182263. {
  182264. if(info_ptr->row_pointers)
  182265. {
  182266. int row;
  182267. for (row = 0; row < (int)info_ptr->height; row++)
  182268. {
  182269. png_free(png_ptr, info_ptr->row_pointers[row]);
  182270. info_ptr->row_pointers[row]=NULL;
  182271. }
  182272. png_free(png_ptr, info_ptr->row_pointers);
  182273. info_ptr->row_pointers=NULL;
  182274. }
  182275. info_ptr->valid &= ~PNG_INFO_IDAT;
  182276. }
  182277. #endif
  182278. #ifdef PNG_FREE_ME_SUPPORTED
  182279. if(num == -1)
  182280. info_ptr->free_me &= ~mask;
  182281. else
  182282. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  182283. #endif
  182284. }
  182285. /* This is an internal routine to free any memory that the info struct is
  182286. * pointing to before re-using it or freeing the struct itself. Recall
  182287. * that png_free() checks for NULL pointers for us.
  182288. */
  182289. void /* PRIVATE */
  182290. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  182291. {
  182292. png_debug(1, "in png_info_destroy\n");
  182293. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  182294. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182295. if (png_ptr->num_chunk_list)
  182296. {
  182297. png_free(png_ptr, png_ptr->chunk_list);
  182298. png_ptr->chunk_list=NULL;
  182299. png_ptr->num_chunk_list=0;
  182300. }
  182301. #endif
  182302. png_info_init_3(&info_ptr, png_sizeof(png_info));
  182303. }
  182304. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  182305. /* This function returns a pointer to the io_ptr associated with the user
  182306. * functions. The application should free any memory associated with this
  182307. * pointer before png_write_destroy() or png_read_destroy() are called.
  182308. */
  182309. png_voidp PNGAPI
  182310. png_get_io_ptr(png_structp png_ptr)
  182311. {
  182312. if(png_ptr == NULL) return (NULL);
  182313. return (png_ptr->io_ptr);
  182314. }
  182315. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  182316. #if !defined(PNG_NO_STDIO)
  182317. /* Initialize the default input/output functions for the PNG file. If you
  182318. * use your own read or write routines, you can call either png_set_read_fn()
  182319. * or png_set_write_fn() instead of png_init_io(). If you have defined
  182320. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  182321. * necessarily available.
  182322. */
  182323. void PNGAPI
  182324. png_init_io(png_structp png_ptr, png_FILE_p fp)
  182325. {
  182326. png_debug(1, "in png_init_io\n");
  182327. if(png_ptr == NULL) return;
  182328. png_ptr->io_ptr = (png_voidp)fp;
  182329. }
  182330. #endif
  182331. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182332. /* Convert the supplied time into an RFC 1123 string suitable for use in
  182333. * a "Creation Time" or other text-based time string.
  182334. */
  182335. png_charp PNGAPI
  182336. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  182337. {
  182338. static PNG_CONST char short_months[12][4] =
  182339. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  182340. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  182341. if(png_ptr == NULL) return (NULL);
  182342. if (png_ptr->time_buffer == NULL)
  182343. {
  182344. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  182345. png_sizeof(char)));
  182346. }
  182347. #if defined(_WIN32_WCE)
  182348. {
  182349. wchar_t time_buf[29];
  182350. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  182351. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  182352. ptime->year, ptime->hour % 24, ptime->minute % 60,
  182353. ptime->second % 61);
  182354. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  182355. NULL, NULL);
  182356. }
  182357. #else
  182358. #ifdef USE_FAR_KEYWORD
  182359. {
  182360. char near_time_buf[29];
  182361. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  182362. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  182363. ptime->year, ptime->hour % 24, ptime->minute % 60,
  182364. ptime->second % 61);
  182365. png_memcpy(png_ptr->time_buffer, near_time_buf,
  182366. 29*png_sizeof(char));
  182367. }
  182368. #else
  182369. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  182370. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  182371. ptime->year, ptime->hour % 24, ptime->minute % 60,
  182372. ptime->second % 61);
  182373. #endif
  182374. #endif /* _WIN32_WCE */
  182375. return ((png_charp)png_ptr->time_buffer);
  182376. }
  182377. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  182378. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  182379. png_charp PNGAPI
  182380. png_get_copyright(png_structp png_ptr)
  182381. {
  182382. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  182383. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  182384. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  182385. Copyright (c) 1996-1997 Andreas Dilger\n\
  182386. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  182387. }
  182388. /* The following return the library version as a short string in the
  182389. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  182390. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  182391. * is defined in png.h.
  182392. * Note: now there is no difference between png_get_libpng_ver() and
  182393. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  182394. * it is guaranteed that png.c uses the correct version of png.h.
  182395. */
  182396. png_charp PNGAPI
  182397. png_get_libpng_ver(png_structp png_ptr)
  182398. {
  182399. /* Version of *.c files used when building libpng */
  182400. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  182401. return ((png_charp) PNG_LIBPNG_VER_STRING);
  182402. }
  182403. png_charp PNGAPI
  182404. png_get_header_ver(png_structp png_ptr)
  182405. {
  182406. /* Version of *.h files used when building libpng */
  182407. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  182408. return ((png_charp) PNG_LIBPNG_VER_STRING);
  182409. }
  182410. png_charp PNGAPI
  182411. png_get_header_version(png_structp png_ptr)
  182412. {
  182413. /* Returns longer string containing both version and date */
  182414. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  182415. return ((png_charp) PNG_HEADER_VERSION_STRING
  182416. #ifndef PNG_READ_SUPPORTED
  182417. " (NO READ SUPPORT)"
  182418. #endif
  182419. "\n");
  182420. }
  182421. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  182422. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  182423. int PNGAPI
  182424. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  182425. {
  182426. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  182427. int i;
  182428. png_bytep p;
  182429. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  182430. return 0;
  182431. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  182432. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  182433. if (!png_memcmp(chunk_name, p, 4))
  182434. return ((int)*(p+4));
  182435. return 0;
  182436. }
  182437. #endif
  182438. /* This function, added to libpng-1.0.6g, is untested. */
  182439. int PNGAPI
  182440. png_reset_zstream(png_structp png_ptr)
  182441. {
  182442. if (png_ptr == NULL) return Z_STREAM_ERROR;
  182443. return (inflateReset(&png_ptr->zstream));
  182444. }
  182445. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  182446. /* This function was added to libpng-1.0.7 */
  182447. png_uint_32 PNGAPI
  182448. png_access_version_number(void)
  182449. {
  182450. /* Version of *.c files used when building libpng */
  182451. return((png_uint_32) PNG_LIBPNG_VER);
  182452. }
  182453. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  182454. #if !defined(PNG_1_0_X)
  182455. /* this function was added to libpng 1.2.0 */
  182456. int PNGAPI
  182457. png_mmx_support(void)
  182458. {
  182459. /* obsolete, to be removed from libpng-1.4.0 */
  182460. return -1;
  182461. }
  182462. #endif /* PNG_1_0_X */
  182463. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  182464. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  182465. #ifdef PNG_SIZE_T
  182466. /* Added at libpng version 1.2.6 */
  182467. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  182468. png_size_t PNGAPI
  182469. png_convert_size(size_t size)
  182470. {
  182471. if (size > (png_size_t)-1)
  182472. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  182473. return ((png_size_t)size);
  182474. }
  182475. #endif /* PNG_SIZE_T */
  182476. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  182477. /*** End of inlined file: png.c ***/
  182478. /*** Start of inlined file: pngerror.c ***/
  182479. /* pngerror.c - stub functions for i/o and memory allocation
  182480. *
  182481. * Last changed in libpng 1.2.20 October 4, 2007
  182482. * For conditions of distribution and use, see copyright notice in png.h
  182483. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  182484. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  182485. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  182486. *
  182487. * This file provides a location for all error handling. Users who
  182488. * need special error handling are expected to write replacement functions
  182489. * and use png_set_error_fn() to use those functions. See the instructions
  182490. * at each function.
  182491. */
  182492. #define PNG_INTERNAL
  182493. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  182494. static void /* PRIVATE */
  182495. png_default_error PNGARG((png_structp png_ptr,
  182496. png_const_charp error_message));
  182497. #ifndef PNG_NO_WARNINGS
  182498. static void /* PRIVATE */
  182499. png_default_warning PNGARG((png_structp png_ptr,
  182500. png_const_charp warning_message));
  182501. #endif /* PNG_NO_WARNINGS */
  182502. /* This function is called whenever there is a fatal error. This function
  182503. * should not be changed. If there is a need to handle errors differently,
  182504. * you should supply a replacement error function and use png_set_error_fn()
  182505. * to replace the error function at run-time.
  182506. */
  182507. #ifndef PNG_NO_ERROR_TEXT
  182508. void PNGAPI
  182509. png_error(png_structp png_ptr, png_const_charp error_message)
  182510. {
  182511. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182512. char msg[16];
  182513. if (png_ptr != NULL)
  182514. {
  182515. if (png_ptr->flags&
  182516. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  182517. {
  182518. if (*error_message == '#')
  182519. {
  182520. int offset;
  182521. for (offset=1; offset<15; offset++)
  182522. if (*(error_message+offset) == ' ')
  182523. break;
  182524. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  182525. {
  182526. int i;
  182527. for (i=0; i<offset-1; i++)
  182528. msg[i]=error_message[i+1];
  182529. msg[i]='\0';
  182530. error_message=msg;
  182531. }
  182532. else
  182533. error_message+=offset;
  182534. }
  182535. else
  182536. {
  182537. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  182538. {
  182539. msg[0]='0';
  182540. msg[1]='\0';
  182541. error_message=msg;
  182542. }
  182543. }
  182544. }
  182545. }
  182546. #endif
  182547. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  182548. (*(png_ptr->error_fn))(png_ptr, error_message);
  182549. /* If the custom handler doesn't exist, or if it returns,
  182550. use the default handler, which will not return. */
  182551. png_default_error(png_ptr, error_message);
  182552. }
  182553. #else
  182554. void PNGAPI
  182555. png_err(png_structp png_ptr)
  182556. {
  182557. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  182558. (*(png_ptr->error_fn))(png_ptr, '\0');
  182559. /* If the custom handler doesn't exist, or if it returns,
  182560. use the default handler, which will not return. */
  182561. png_default_error(png_ptr, '\0');
  182562. }
  182563. #endif /* PNG_NO_ERROR_TEXT */
  182564. #ifndef PNG_NO_WARNINGS
  182565. /* This function is called whenever there is a non-fatal error. This function
  182566. * should not be changed. If there is a need to handle warnings differently,
  182567. * you should supply a replacement warning function and use
  182568. * png_set_error_fn() to replace the warning function at run-time.
  182569. */
  182570. void PNGAPI
  182571. png_warning(png_structp png_ptr, png_const_charp warning_message)
  182572. {
  182573. int offset = 0;
  182574. if (png_ptr != NULL)
  182575. {
  182576. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182577. if (png_ptr->flags&
  182578. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  182579. #endif
  182580. {
  182581. if (*warning_message == '#')
  182582. {
  182583. for (offset=1; offset<15; offset++)
  182584. if (*(warning_message+offset) == ' ')
  182585. break;
  182586. }
  182587. }
  182588. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  182589. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  182590. }
  182591. else
  182592. png_default_warning(png_ptr, warning_message+offset);
  182593. }
  182594. #endif /* PNG_NO_WARNINGS */
  182595. /* These utilities are used internally to build an error message that relates
  182596. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  182597. * this is used to prefix the message. The message is limited in length
  182598. * to 63 bytes, the name characters are output as hex digits wrapped in []
  182599. * if the character is invalid.
  182600. */
  182601. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  182602. /*static PNG_CONST char png_digit[16] = {
  182603. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  182604. 'A', 'B', 'C', 'D', 'E', 'F'
  182605. };*/
  182606. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  182607. static void /* PRIVATE */
  182608. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  182609. error_message)
  182610. {
  182611. int iout = 0, iin = 0;
  182612. while (iin < 4)
  182613. {
  182614. int c = png_ptr->chunk_name[iin++];
  182615. if (isnonalpha(c))
  182616. {
  182617. buffer[iout++] = '[';
  182618. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  182619. buffer[iout++] = png_digit[c & 0x0f];
  182620. buffer[iout++] = ']';
  182621. }
  182622. else
  182623. {
  182624. buffer[iout++] = (png_byte)c;
  182625. }
  182626. }
  182627. if (error_message == NULL)
  182628. buffer[iout] = 0;
  182629. else
  182630. {
  182631. buffer[iout++] = ':';
  182632. buffer[iout++] = ' ';
  182633. png_strncpy(buffer+iout, error_message, 63);
  182634. buffer[iout+63] = 0;
  182635. }
  182636. }
  182637. #ifdef PNG_READ_SUPPORTED
  182638. void PNGAPI
  182639. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  182640. {
  182641. char msg[18+64];
  182642. if (png_ptr == NULL)
  182643. png_error(png_ptr, error_message);
  182644. else
  182645. {
  182646. png_format_buffer(png_ptr, msg, error_message);
  182647. png_error(png_ptr, msg);
  182648. }
  182649. }
  182650. #endif /* PNG_READ_SUPPORTED */
  182651. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  182652. #ifndef PNG_NO_WARNINGS
  182653. void PNGAPI
  182654. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  182655. {
  182656. char msg[18+64];
  182657. if (png_ptr == NULL)
  182658. png_warning(png_ptr, warning_message);
  182659. else
  182660. {
  182661. png_format_buffer(png_ptr, msg, warning_message);
  182662. png_warning(png_ptr, msg);
  182663. }
  182664. }
  182665. #endif /* PNG_NO_WARNINGS */
  182666. /* This is the default error handling function. Note that replacements for
  182667. * this function MUST NOT RETURN, or the program will likely crash. This
  182668. * function is used by default, or if the program supplies NULL for the
  182669. * error function pointer in png_set_error_fn().
  182670. */
  182671. static void /* PRIVATE */
  182672. png_default_error(png_structp, png_const_charp error_message)
  182673. {
  182674. #ifndef PNG_NO_CONSOLE_IO
  182675. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182676. if (*error_message == '#')
  182677. {
  182678. int offset;
  182679. char error_number[16];
  182680. for (offset=0; offset<15; offset++)
  182681. {
  182682. error_number[offset] = *(error_message+offset+1);
  182683. if (*(error_message+offset) == ' ')
  182684. break;
  182685. }
  182686. if((offset > 1) && (offset < 15))
  182687. {
  182688. error_number[offset-1]='\0';
  182689. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  182690. error_message+offset);
  182691. }
  182692. else
  182693. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  182694. }
  182695. else
  182696. #endif
  182697. fprintf(stderr, "libpng error: %s\n", error_message);
  182698. #endif
  182699. #ifdef PNG_SETJMP_SUPPORTED
  182700. if (png_ptr)
  182701. {
  182702. # ifdef USE_FAR_KEYWORD
  182703. {
  182704. jmp_buf jmpbuf;
  182705. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  182706. longjmp(jmpbuf, 1);
  182707. }
  182708. # else
  182709. longjmp(png_ptr->jmpbuf, 1);
  182710. # endif
  182711. }
  182712. #else
  182713. PNG_ABORT();
  182714. #endif
  182715. #ifdef PNG_NO_CONSOLE_IO
  182716. error_message = error_message; /* make compiler happy */
  182717. #endif
  182718. }
  182719. #ifndef PNG_NO_WARNINGS
  182720. /* This function is called when there is a warning, but the library thinks
  182721. * it can continue anyway. Replacement functions don't have to do anything
  182722. * here if you don't want them to. In the default configuration, png_ptr is
  182723. * not used, but it is passed in case it may be useful.
  182724. */
  182725. static void /* PRIVATE */
  182726. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  182727. {
  182728. #ifndef PNG_NO_CONSOLE_IO
  182729. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182730. if (*warning_message == '#')
  182731. {
  182732. int offset;
  182733. char warning_number[16];
  182734. for (offset=0; offset<15; offset++)
  182735. {
  182736. warning_number[offset]=*(warning_message+offset+1);
  182737. if (*(warning_message+offset) == ' ')
  182738. break;
  182739. }
  182740. if((offset > 1) && (offset < 15))
  182741. {
  182742. warning_number[offset-1]='\0';
  182743. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  182744. warning_message+offset);
  182745. }
  182746. else
  182747. fprintf(stderr, "libpng warning: %s\n", warning_message);
  182748. }
  182749. else
  182750. # endif
  182751. fprintf(stderr, "libpng warning: %s\n", warning_message);
  182752. #else
  182753. warning_message = warning_message; /* make compiler happy */
  182754. #endif
  182755. png_ptr = png_ptr; /* make compiler happy */
  182756. }
  182757. #endif /* PNG_NO_WARNINGS */
  182758. /* This function is called when the application wants to use another method
  182759. * of handling errors and warnings. Note that the error function MUST NOT
  182760. * return to the calling routine or serious problems will occur. The return
  182761. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  182762. */
  182763. void PNGAPI
  182764. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  182765. png_error_ptr error_fn, png_error_ptr warning_fn)
  182766. {
  182767. if (png_ptr == NULL)
  182768. return;
  182769. png_ptr->error_ptr = error_ptr;
  182770. png_ptr->error_fn = error_fn;
  182771. png_ptr->warning_fn = warning_fn;
  182772. }
  182773. /* This function returns a pointer to the error_ptr associated with the user
  182774. * functions. The application should free any memory associated with this
  182775. * pointer before png_write_destroy and png_read_destroy are called.
  182776. */
  182777. png_voidp PNGAPI
  182778. png_get_error_ptr(png_structp png_ptr)
  182779. {
  182780. if (png_ptr == NULL)
  182781. return NULL;
  182782. return ((png_voidp)png_ptr->error_ptr);
  182783. }
  182784. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182785. void PNGAPI
  182786. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  182787. {
  182788. if(png_ptr != NULL)
  182789. {
  182790. png_ptr->flags &=
  182791. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  182792. }
  182793. }
  182794. #endif
  182795. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  182796. /*** End of inlined file: pngerror.c ***/
  182797. /*** Start of inlined file: pngget.c ***/
  182798. /* pngget.c - retrieval of values from info struct
  182799. *
  182800. * Last changed in libpng 1.2.15 January 5, 2007
  182801. * For conditions of distribution and use, see copyright notice in png.h
  182802. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  182803. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  182804. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  182805. */
  182806. #define PNG_INTERNAL
  182807. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  182808. png_uint_32 PNGAPI
  182809. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  182810. {
  182811. if (png_ptr != NULL && info_ptr != NULL)
  182812. return(info_ptr->valid & flag);
  182813. else
  182814. return(0);
  182815. }
  182816. png_uint_32 PNGAPI
  182817. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  182818. {
  182819. if (png_ptr != NULL && info_ptr != NULL)
  182820. return(info_ptr->rowbytes);
  182821. else
  182822. return(0);
  182823. }
  182824. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182825. png_bytepp PNGAPI
  182826. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  182827. {
  182828. if (png_ptr != NULL && info_ptr != NULL)
  182829. return(info_ptr->row_pointers);
  182830. else
  182831. return(0);
  182832. }
  182833. #endif
  182834. #ifdef PNG_EASY_ACCESS_SUPPORTED
  182835. /* easy access to info, added in libpng-0.99 */
  182836. png_uint_32 PNGAPI
  182837. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  182838. {
  182839. if (png_ptr != NULL && info_ptr != NULL)
  182840. {
  182841. return info_ptr->width;
  182842. }
  182843. return (0);
  182844. }
  182845. png_uint_32 PNGAPI
  182846. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  182847. {
  182848. if (png_ptr != NULL && info_ptr != NULL)
  182849. {
  182850. return info_ptr->height;
  182851. }
  182852. return (0);
  182853. }
  182854. png_byte PNGAPI
  182855. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  182856. {
  182857. if (png_ptr != NULL && info_ptr != NULL)
  182858. {
  182859. return info_ptr->bit_depth;
  182860. }
  182861. return (0);
  182862. }
  182863. png_byte PNGAPI
  182864. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  182865. {
  182866. if (png_ptr != NULL && info_ptr != NULL)
  182867. {
  182868. return info_ptr->color_type;
  182869. }
  182870. return (0);
  182871. }
  182872. png_byte PNGAPI
  182873. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  182874. {
  182875. if (png_ptr != NULL && info_ptr != NULL)
  182876. {
  182877. return info_ptr->filter_type;
  182878. }
  182879. return (0);
  182880. }
  182881. png_byte PNGAPI
  182882. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  182883. {
  182884. if (png_ptr != NULL && info_ptr != NULL)
  182885. {
  182886. return info_ptr->interlace_type;
  182887. }
  182888. return (0);
  182889. }
  182890. png_byte PNGAPI
  182891. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  182892. {
  182893. if (png_ptr != NULL && info_ptr != NULL)
  182894. {
  182895. return info_ptr->compression_type;
  182896. }
  182897. return (0);
  182898. }
  182899. png_uint_32 PNGAPI
  182900. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  182901. {
  182902. if (png_ptr != NULL && info_ptr != NULL)
  182903. #if defined(PNG_pHYs_SUPPORTED)
  182904. if (info_ptr->valid & PNG_INFO_pHYs)
  182905. {
  182906. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  182907. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  182908. return (0);
  182909. else return (info_ptr->x_pixels_per_unit);
  182910. }
  182911. #else
  182912. return (0);
  182913. #endif
  182914. return (0);
  182915. }
  182916. png_uint_32 PNGAPI
  182917. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  182918. {
  182919. if (png_ptr != NULL && info_ptr != NULL)
  182920. #if defined(PNG_pHYs_SUPPORTED)
  182921. if (info_ptr->valid & PNG_INFO_pHYs)
  182922. {
  182923. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  182924. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  182925. return (0);
  182926. else return (info_ptr->y_pixels_per_unit);
  182927. }
  182928. #else
  182929. return (0);
  182930. #endif
  182931. return (0);
  182932. }
  182933. png_uint_32 PNGAPI
  182934. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  182935. {
  182936. if (png_ptr != NULL && info_ptr != NULL)
  182937. #if defined(PNG_pHYs_SUPPORTED)
  182938. if (info_ptr->valid & PNG_INFO_pHYs)
  182939. {
  182940. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  182941. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  182942. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  182943. return (0);
  182944. else return (info_ptr->x_pixels_per_unit);
  182945. }
  182946. #else
  182947. return (0);
  182948. #endif
  182949. return (0);
  182950. }
  182951. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182952. float PNGAPI
  182953. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  182954. {
  182955. if (png_ptr != NULL && info_ptr != NULL)
  182956. #if defined(PNG_pHYs_SUPPORTED)
  182957. if (info_ptr->valid & PNG_INFO_pHYs)
  182958. {
  182959. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  182960. if (info_ptr->x_pixels_per_unit == 0)
  182961. return ((float)0.0);
  182962. else
  182963. return ((float)((float)info_ptr->y_pixels_per_unit
  182964. /(float)info_ptr->x_pixels_per_unit));
  182965. }
  182966. #else
  182967. return (0.0);
  182968. #endif
  182969. return ((float)0.0);
  182970. }
  182971. #endif
  182972. png_int_32 PNGAPI
  182973. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  182974. {
  182975. if (png_ptr != NULL && info_ptr != NULL)
  182976. #if defined(PNG_oFFs_SUPPORTED)
  182977. if (info_ptr->valid & PNG_INFO_oFFs)
  182978. {
  182979. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  182980. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  182981. return (0);
  182982. else return (info_ptr->x_offset);
  182983. }
  182984. #else
  182985. return (0);
  182986. #endif
  182987. return (0);
  182988. }
  182989. png_int_32 PNGAPI
  182990. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  182991. {
  182992. if (png_ptr != NULL && info_ptr != NULL)
  182993. #if defined(PNG_oFFs_SUPPORTED)
  182994. if (info_ptr->valid & PNG_INFO_oFFs)
  182995. {
  182996. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  182997. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  182998. return (0);
  182999. else return (info_ptr->y_offset);
  183000. }
  183001. #else
  183002. return (0);
  183003. #endif
  183004. return (0);
  183005. }
  183006. png_int_32 PNGAPI
  183007. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  183008. {
  183009. if (png_ptr != NULL && info_ptr != NULL)
  183010. #if defined(PNG_oFFs_SUPPORTED)
  183011. if (info_ptr->valid & PNG_INFO_oFFs)
  183012. {
  183013. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  183014. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  183015. return (0);
  183016. else return (info_ptr->x_offset);
  183017. }
  183018. #else
  183019. return (0);
  183020. #endif
  183021. return (0);
  183022. }
  183023. png_int_32 PNGAPI
  183024. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  183025. {
  183026. if (png_ptr != NULL && info_ptr != NULL)
  183027. #if defined(PNG_oFFs_SUPPORTED)
  183028. if (info_ptr->valid & PNG_INFO_oFFs)
  183029. {
  183030. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  183031. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  183032. return (0);
  183033. else return (info_ptr->y_offset);
  183034. }
  183035. #else
  183036. return (0);
  183037. #endif
  183038. return (0);
  183039. }
  183040. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  183041. png_uint_32 PNGAPI
  183042. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  183043. {
  183044. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  183045. *.0254 +.5));
  183046. }
  183047. png_uint_32 PNGAPI
  183048. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  183049. {
  183050. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  183051. *.0254 +.5));
  183052. }
  183053. png_uint_32 PNGAPI
  183054. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  183055. {
  183056. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  183057. *.0254 +.5));
  183058. }
  183059. float PNGAPI
  183060. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  183061. {
  183062. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  183063. *.00003937);
  183064. }
  183065. float PNGAPI
  183066. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  183067. {
  183068. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  183069. *.00003937);
  183070. }
  183071. #if defined(PNG_pHYs_SUPPORTED)
  183072. png_uint_32 PNGAPI
  183073. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  183074. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  183075. {
  183076. png_uint_32 retval = 0;
  183077. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  183078. {
  183079. png_debug1(1, "in %s retrieval function\n", "pHYs");
  183080. if (res_x != NULL)
  183081. {
  183082. *res_x = info_ptr->x_pixels_per_unit;
  183083. retval |= PNG_INFO_pHYs;
  183084. }
  183085. if (res_y != NULL)
  183086. {
  183087. *res_y = info_ptr->y_pixels_per_unit;
  183088. retval |= PNG_INFO_pHYs;
  183089. }
  183090. if (unit_type != NULL)
  183091. {
  183092. *unit_type = (int)info_ptr->phys_unit_type;
  183093. retval |= PNG_INFO_pHYs;
  183094. if(*unit_type == 1)
  183095. {
  183096. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  183097. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  183098. }
  183099. }
  183100. }
  183101. return (retval);
  183102. }
  183103. #endif /* PNG_pHYs_SUPPORTED */
  183104. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  183105. /* png_get_channels really belongs in here, too, but it's been around longer */
  183106. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  183107. png_byte PNGAPI
  183108. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  183109. {
  183110. if (png_ptr != NULL && info_ptr != NULL)
  183111. return(info_ptr->channels);
  183112. else
  183113. return (0);
  183114. }
  183115. png_bytep PNGAPI
  183116. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  183117. {
  183118. if (png_ptr != NULL && info_ptr != NULL)
  183119. return(info_ptr->signature);
  183120. else
  183121. return (NULL);
  183122. }
  183123. #if defined(PNG_bKGD_SUPPORTED)
  183124. png_uint_32 PNGAPI
  183125. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  183126. png_color_16p *background)
  183127. {
  183128. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  183129. && background != NULL)
  183130. {
  183131. png_debug1(1, "in %s retrieval function\n", "bKGD");
  183132. *background = &(info_ptr->background);
  183133. return (PNG_INFO_bKGD);
  183134. }
  183135. return (0);
  183136. }
  183137. #endif
  183138. #if defined(PNG_cHRM_SUPPORTED)
  183139. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183140. png_uint_32 PNGAPI
  183141. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  183142. double *white_x, double *white_y, double *red_x, double *red_y,
  183143. double *green_x, double *green_y, double *blue_x, double *blue_y)
  183144. {
  183145. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  183146. {
  183147. png_debug1(1, "in %s retrieval function\n", "cHRM");
  183148. if (white_x != NULL)
  183149. *white_x = (double)info_ptr->x_white;
  183150. if (white_y != NULL)
  183151. *white_y = (double)info_ptr->y_white;
  183152. if (red_x != NULL)
  183153. *red_x = (double)info_ptr->x_red;
  183154. if (red_y != NULL)
  183155. *red_y = (double)info_ptr->y_red;
  183156. if (green_x != NULL)
  183157. *green_x = (double)info_ptr->x_green;
  183158. if (green_y != NULL)
  183159. *green_y = (double)info_ptr->y_green;
  183160. if (blue_x != NULL)
  183161. *blue_x = (double)info_ptr->x_blue;
  183162. if (blue_y != NULL)
  183163. *blue_y = (double)info_ptr->y_blue;
  183164. return (PNG_INFO_cHRM);
  183165. }
  183166. return (0);
  183167. }
  183168. #endif
  183169. #ifdef PNG_FIXED_POINT_SUPPORTED
  183170. png_uint_32 PNGAPI
  183171. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  183172. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  183173. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  183174. png_fixed_point *blue_x, png_fixed_point *blue_y)
  183175. {
  183176. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  183177. {
  183178. png_debug1(1, "in %s retrieval function\n", "cHRM");
  183179. if (white_x != NULL)
  183180. *white_x = info_ptr->int_x_white;
  183181. if (white_y != NULL)
  183182. *white_y = info_ptr->int_y_white;
  183183. if (red_x != NULL)
  183184. *red_x = info_ptr->int_x_red;
  183185. if (red_y != NULL)
  183186. *red_y = info_ptr->int_y_red;
  183187. if (green_x != NULL)
  183188. *green_x = info_ptr->int_x_green;
  183189. if (green_y != NULL)
  183190. *green_y = info_ptr->int_y_green;
  183191. if (blue_x != NULL)
  183192. *blue_x = info_ptr->int_x_blue;
  183193. if (blue_y != NULL)
  183194. *blue_y = info_ptr->int_y_blue;
  183195. return (PNG_INFO_cHRM);
  183196. }
  183197. return (0);
  183198. }
  183199. #endif
  183200. #endif
  183201. #if defined(PNG_gAMA_SUPPORTED)
  183202. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183203. png_uint_32 PNGAPI
  183204. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  183205. {
  183206. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  183207. && file_gamma != NULL)
  183208. {
  183209. png_debug1(1, "in %s retrieval function\n", "gAMA");
  183210. *file_gamma = (double)info_ptr->gamma;
  183211. return (PNG_INFO_gAMA);
  183212. }
  183213. return (0);
  183214. }
  183215. #endif
  183216. #ifdef PNG_FIXED_POINT_SUPPORTED
  183217. png_uint_32 PNGAPI
  183218. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  183219. png_fixed_point *int_file_gamma)
  183220. {
  183221. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  183222. && int_file_gamma != NULL)
  183223. {
  183224. png_debug1(1, "in %s retrieval function\n", "gAMA");
  183225. *int_file_gamma = info_ptr->int_gamma;
  183226. return (PNG_INFO_gAMA);
  183227. }
  183228. return (0);
  183229. }
  183230. #endif
  183231. #endif
  183232. #if defined(PNG_sRGB_SUPPORTED)
  183233. png_uint_32 PNGAPI
  183234. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  183235. {
  183236. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  183237. && file_srgb_intent != NULL)
  183238. {
  183239. png_debug1(1, "in %s retrieval function\n", "sRGB");
  183240. *file_srgb_intent = (int)info_ptr->srgb_intent;
  183241. return (PNG_INFO_sRGB);
  183242. }
  183243. return (0);
  183244. }
  183245. #endif
  183246. #if defined(PNG_iCCP_SUPPORTED)
  183247. png_uint_32 PNGAPI
  183248. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  183249. png_charpp name, int *compression_type,
  183250. png_charpp profile, png_uint_32 *proflen)
  183251. {
  183252. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  183253. && name != NULL && profile != NULL && proflen != NULL)
  183254. {
  183255. png_debug1(1, "in %s retrieval function\n", "iCCP");
  183256. *name = info_ptr->iccp_name;
  183257. *profile = info_ptr->iccp_profile;
  183258. /* compression_type is a dummy so the API won't have to change
  183259. if we introduce multiple compression types later. */
  183260. *proflen = (int)info_ptr->iccp_proflen;
  183261. *compression_type = (int)info_ptr->iccp_compression;
  183262. return (PNG_INFO_iCCP);
  183263. }
  183264. return (0);
  183265. }
  183266. #endif
  183267. #if defined(PNG_sPLT_SUPPORTED)
  183268. png_uint_32 PNGAPI
  183269. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  183270. png_sPLT_tpp spalettes)
  183271. {
  183272. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  183273. {
  183274. *spalettes = info_ptr->splt_palettes;
  183275. return ((png_uint_32)info_ptr->splt_palettes_num);
  183276. }
  183277. return (0);
  183278. }
  183279. #endif
  183280. #if defined(PNG_hIST_SUPPORTED)
  183281. png_uint_32 PNGAPI
  183282. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  183283. {
  183284. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  183285. && hist != NULL)
  183286. {
  183287. png_debug1(1, "in %s retrieval function\n", "hIST");
  183288. *hist = info_ptr->hist;
  183289. return (PNG_INFO_hIST);
  183290. }
  183291. return (0);
  183292. }
  183293. #endif
  183294. png_uint_32 PNGAPI
  183295. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  183296. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  183297. int *color_type, int *interlace_type, int *compression_type,
  183298. int *filter_type)
  183299. {
  183300. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  183301. bit_depth != NULL && color_type != NULL)
  183302. {
  183303. png_debug1(1, "in %s retrieval function\n", "IHDR");
  183304. *width = info_ptr->width;
  183305. *height = info_ptr->height;
  183306. *bit_depth = info_ptr->bit_depth;
  183307. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  183308. png_error(png_ptr, "Invalid bit depth");
  183309. *color_type = info_ptr->color_type;
  183310. if (info_ptr->color_type > 6)
  183311. png_error(png_ptr, "Invalid color type");
  183312. if (compression_type != NULL)
  183313. *compression_type = info_ptr->compression_type;
  183314. if (filter_type != NULL)
  183315. *filter_type = info_ptr->filter_type;
  183316. if (interlace_type != NULL)
  183317. *interlace_type = info_ptr->interlace_type;
  183318. /* check for potential overflow of rowbytes */
  183319. if (*width == 0 || *width > PNG_UINT_31_MAX)
  183320. png_error(png_ptr, "Invalid image width");
  183321. if (*height == 0 || *height > PNG_UINT_31_MAX)
  183322. png_error(png_ptr, "Invalid image height");
  183323. if (info_ptr->width > (PNG_UINT_32_MAX
  183324. >> 3) /* 8-byte RGBA pixels */
  183325. - 64 /* bigrowbuf hack */
  183326. - 1 /* filter byte */
  183327. - 7*8 /* rounding of width to multiple of 8 pixels */
  183328. - 8) /* extra max_pixel_depth pad */
  183329. {
  183330. png_warning(png_ptr,
  183331. "Width too large for libpng to process image data.");
  183332. }
  183333. return (1);
  183334. }
  183335. return (0);
  183336. }
  183337. #if defined(PNG_oFFs_SUPPORTED)
  183338. png_uint_32 PNGAPI
  183339. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  183340. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  183341. {
  183342. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  183343. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  183344. {
  183345. png_debug1(1, "in %s retrieval function\n", "oFFs");
  183346. *offset_x = info_ptr->x_offset;
  183347. *offset_y = info_ptr->y_offset;
  183348. *unit_type = (int)info_ptr->offset_unit_type;
  183349. return (PNG_INFO_oFFs);
  183350. }
  183351. return (0);
  183352. }
  183353. #endif
  183354. #if defined(PNG_pCAL_SUPPORTED)
  183355. png_uint_32 PNGAPI
  183356. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  183357. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  183358. png_charp *units, png_charpp *params)
  183359. {
  183360. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  183361. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  183362. nparams != NULL && units != NULL && params != NULL)
  183363. {
  183364. png_debug1(1, "in %s retrieval function\n", "pCAL");
  183365. *purpose = info_ptr->pcal_purpose;
  183366. *X0 = info_ptr->pcal_X0;
  183367. *X1 = info_ptr->pcal_X1;
  183368. *type = (int)info_ptr->pcal_type;
  183369. *nparams = (int)info_ptr->pcal_nparams;
  183370. *units = info_ptr->pcal_units;
  183371. *params = info_ptr->pcal_params;
  183372. return (PNG_INFO_pCAL);
  183373. }
  183374. return (0);
  183375. }
  183376. #endif
  183377. #if defined(PNG_sCAL_SUPPORTED)
  183378. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183379. png_uint_32 PNGAPI
  183380. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  183381. int *unit, double *width, double *height)
  183382. {
  183383. if (png_ptr != NULL && info_ptr != NULL &&
  183384. (info_ptr->valid & PNG_INFO_sCAL))
  183385. {
  183386. *unit = info_ptr->scal_unit;
  183387. *width = info_ptr->scal_pixel_width;
  183388. *height = info_ptr->scal_pixel_height;
  183389. return (PNG_INFO_sCAL);
  183390. }
  183391. return(0);
  183392. }
  183393. #else
  183394. #ifdef PNG_FIXED_POINT_SUPPORTED
  183395. png_uint_32 PNGAPI
  183396. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  183397. int *unit, png_charpp width, png_charpp height)
  183398. {
  183399. if (png_ptr != NULL && info_ptr != NULL &&
  183400. (info_ptr->valid & PNG_INFO_sCAL))
  183401. {
  183402. *unit = info_ptr->scal_unit;
  183403. *width = info_ptr->scal_s_width;
  183404. *height = info_ptr->scal_s_height;
  183405. return (PNG_INFO_sCAL);
  183406. }
  183407. return(0);
  183408. }
  183409. #endif
  183410. #endif
  183411. #endif
  183412. #if defined(PNG_pHYs_SUPPORTED)
  183413. png_uint_32 PNGAPI
  183414. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  183415. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  183416. {
  183417. png_uint_32 retval = 0;
  183418. if (png_ptr != NULL && info_ptr != NULL &&
  183419. (info_ptr->valid & PNG_INFO_pHYs))
  183420. {
  183421. png_debug1(1, "in %s retrieval function\n", "pHYs");
  183422. if (res_x != NULL)
  183423. {
  183424. *res_x = info_ptr->x_pixels_per_unit;
  183425. retval |= PNG_INFO_pHYs;
  183426. }
  183427. if (res_y != NULL)
  183428. {
  183429. *res_y = info_ptr->y_pixels_per_unit;
  183430. retval |= PNG_INFO_pHYs;
  183431. }
  183432. if (unit_type != NULL)
  183433. {
  183434. *unit_type = (int)info_ptr->phys_unit_type;
  183435. retval |= PNG_INFO_pHYs;
  183436. }
  183437. }
  183438. return (retval);
  183439. }
  183440. #endif
  183441. png_uint_32 PNGAPI
  183442. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  183443. int *num_palette)
  183444. {
  183445. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  183446. && palette != NULL)
  183447. {
  183448. png_debug1(1, "in %s retrieval function\n", "PLTE");
  183449. *palette = info_ptr->palette;
  183450. *num_palette = info_ptr->num_palette;
  183451. png_debug1(3, "num_palette = %d\n", *num_palette);
  183452. return (PNG_INFO_PLTE);
  183453. }
  183454. return (0);
  183455. }
  183456. #if defined(PNG_sBIT_SUPPORTED)
  183457. png_uint_32 PNGAPI
  183458. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  183459. {
  183460. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  183461. && sig_bit != NULL)
  183462. {
  183463. png_debug1(1, "in %s retrieval function\n", "sBIT");
  183464. *sig_bit = &(info_ptr->sig_bit);
  183465. return (PNG_INFO_sBIT);
  183466. }
  183467. return (0);
  183468. }
  183469. #endif
  183470. #if defined(PNG_TEXT_SUPPORTED)
  183471. png_uint_32 PNGAPI
  183472. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  183473. int *num_text)
  183474. {
  183475. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  183476. {
  183477. png_debug1(1, "in %s retrieval function\n",
  183478. (png_ptr->chunk_name[0] == '\0' ? "text"
  183479. : (png_const_charp)png_ptr->chunk_name));
  183480. if (text_ptr != NULL)
  183481. *text_ptr = info_ptr->text;
  183482. if (num_text != NULL)
  183483. *num_text = info_ptr->num_text;
  183484. return ((png_uint_32)info_ptr->num_text);
  183485. }
  183486. if (num_text != NULL)
  183487. *num_text = 0;
  183488. return(0);
  183489. }
  183490. #endif
  183491. #if defined(PNG_tIME_SUPPORTED)
  183492. png_uint_32 PNGAPI
  183493. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  183494. {
  183495. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  183496. && mod_time != NULL)
  183497. {
  183498. png_debug1(1, "in %s retrieval function\n", "tIME");
  183499. *mod_time = &(info_ptr->mod_time);
  183500. return (PNG_INFO_tIME);
  183501. }
  183502. return (0);
  183503. }
  183504. #endif
  183505. #if defined(PNG_tRNS_SUPPORTED)
  183506. png_uint_32 PNGAPI
  183507. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  183508. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  183509. {
  183510. png_uint_32 retval = 0;
  183511. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  183512. {
  183513. png_debug1(1, "in %s retrieval function\n", "tRNS");
  183514. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  183515. {
  183516. if (trans != NULL)
  183517. {
  183518. *trans = info_ptr->trans;
  183519. retval |= PNG_INFO_tRNS;
  183520. }
  183521. if (trans_values != NULL)
  183522. *trans_values = &(info_ptr->trans_values);
  183523. }
  183524. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  183525. {
  183526. if (trans_values != NULL)
  183527. {
  183528. *trans_values = &(info_ptr->trans_values);
  183529. retval |= PNG_INFO_tRNS;
  183530. }
  183531. if(trans != NULL)
  183532. *trans = NULL;
  183533. }
  183534. if(num_trans != NULL)
  183535. {
  183536. *num_trans = info_ptr->num_trans;
  183537. retval |= PNG_INFO_tRNS;
  183538. }
  183539. }
  183540. return (retval);
  183541. }
  183542. #endif
  183543. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183544. png_uint_32 PNGAPI
  183545. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  183546. png_unknown_chunkpp unknowns)
  183547. {
  183548. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  183549. {
  183550. *unknowns = info_ptr->unknown_chunks;
  183551. return ((png_uint_32)info_ptr->unknown_chunks_num);
  183552. }
  183553. return (0);
  183554. }
  183555. #endif
  183556. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  183557. png_byte PNGAPI
  183558. png_get_rgb_to_gray_status (png_structp png_ptr)
  183559. {
  183560. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  183561. }
  183562. #endif
  183563. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  183564. png_voidp PNGAPI
  183565. png_get_user_chunk_ptr(png_structp png_ptr)
  183566. {
  183567. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  183568. }
  183569. #endif
  183570. #ifdef PNG_WRITE_SUPPORTED
  183571. png_uint_32 PNGAPI
  183572. png_get_compression_buffer_size(png_structp png_ptr)
  183573. {
  183574. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  183575. }
  183576. #endif
  183577. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  183578. #ifndef PNG_1_0_X
  183579. /* this function was added to libpng 1.2.0 and should exist by default */
  183580. png_uint_32 PNGAPI
  183581. png_get_asm_flags (png_structp png_ptr)
  183582. {
  183583. /* obsolete, to be removed from libpng-1.4.0 */
  183584. return (png_ptr? 0L: 0L);
  183585. }
  183586. /* this function was added to libpng 1.2.0 and should exist by default */
  183587. png_uint_32 PNGAPI
  183588. png_get_asm_flagmask (int flag_select)
  183589. {
  183590. /* obsolete, to be removed from libpng-1.4.0 */
  183591. flag_select=flag_select;
  183592. return 0L;
  183593. }
  183594. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  183595. /* this function was added to libpng 1.2.0 */
  183596. png_uint_32 PNGAPI
  183597. png_get_mmx_flagmask (int flag_select, int *compilerID)
  183598. {
  183599. /* obsolete, to be removed from libpng-1.4.0 */
  183600. flag_select=flag_select;
  183601. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  183602. return 0L;
  183603. }
  183604. /* this function was added to libpng 1.2.0 */
  183605. png_byte PNGAPI
  183606. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  183607. {
  183608. /* obsolete, to be removed from libpng-1.4.0 */
  183609. return (png_ptr? 0: 0);
  183610. }
  183611. /* this function was added to libpng 1.2.0 */
  183612. png_uint_32 PNGAPI
  183613. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  183614. {
  183615. /* obsolete, to be removed from libpng-1.4.0 */
  183616. return (png_ptr? 0L: 0L);
  183617. }
  183618. #endif /* ?PNG_1_0_X */
  183619. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  183620. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183621. /* these functions were added to libpng 1.2.6 */
  183622. png_uint_32 PNGAPI
  183623. png_get_user_width_max (png_structp png_ptr)
  183624. {
  183625. return (png_ptr? png_ptr->user_width_max : 0);
  183626. }
  183627. png_uint_32 PNGAPI
  183628. png_get_user_height_max (png_structp png_ptr)
  183629. {
  183630. return (png_ptr? png_ptr->user_height_max : 0);
  183631. }
  183632. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  183633. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  183634. /*** End of inlined file: pngget.c ***/
  183635. /*** Start of inlined file: pngmem.c ***/
  183636. /* pngmem.c - stub functions for memory allocation
  183637. *
  183638. * Last changed in libpng 1.2.13 November 13, 2006
  183639. * For conditions of distribution and use, see copyright notice in png.h
  183640. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  183641. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  183642. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  183643. *
  183644. * This file provides a location for all memory allocation. Users who
  183645. * need special memory handling are expected to supply replacement
  183646. * functions for png_malloc() and png_free(), and to use
  183647. * png_create_read_struct_2() and png_create_write_struct_2() to
  183648. * identify the replacement functions.
  183649. */
  183650. #define PNG_INTERNAL
  183651. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  183652. /* Borland DOS special memory handler */
  183653. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  183654. /* if you change this, be sure to change the one in png.h also */
  183655. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  183656. by a single call to calloc() if this is thought to improve performance. */
  183657. png_voidp /* PRIVATE */
  183658. png_create_struct(int type)
  183659. {
  183660. #ifdef PNG_USER_MEM_SUPPORTED
  183661. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  183662. }
  183663. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  183664. png_voidp /* PRIVATE */
  183665. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  183666. {
  183667. #endif /* PNG_USER_MEM_SUPPORTED */
  183668. png_size_t size;
  183669. png_voidp struct_ptr;
  183670. if (type == PNG_STRUCT_INFO)
  183671. size = png_sizeof(png_info);
  183672. else if (type == PNG_STRUCT_PNG)
  183673. size = png_sizeof(png_struct);
  183674. else
  183675. return (png_get_copyright(NULL));
  183676. #ifdef PNG_USER_MEM_SUPPORTED
  183677. if(malloc_fn != NULL)
  183678. {
  183679. png_struct dummy_struct;
  183680. png_structp png_ptr = &dummy_struct;
  183681. png_ptr->mem_ptr=mem_ptr;
  183682. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  183683. }
  183684. else
  183685. #endif /* PNG_USER_MEM_SUPPORTED */
  183686. struct_ptr = (png_voidp)farmalloc(size);
  183687. if (struct_ptr != NULL)
  183688. png_memset(struct_ptr, 0, size);
  183689. return (struct_ptr);
  183690. }
  183691. /* Free memory allocated by a png_create_struct() call */
  183692. void /* PRIVATE */
  183693. png_destroy_struct(png_voidp struct_ptr)
  183694. {
  183695. #ifdef PNG_USER_MEM_SUPPORTED
  183696. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  183697. }
  183698. /* Free memory allocated by a png_create_struct() call */
  183699. void /* PRIVATE */
  183700. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  183701. png_voidp mem_ptr)
  183702. {
  183703. #endif
  183704. if (struct_ptr != NULL)
  183705. {
  183706. #ifdef PNG_USER_MEM_SUPPORTED
  183707. if(free_fn != NULL)
  183708. {
  183709. png_struct dummy_struct;
  183710. png_structp png_ptr = &dummy_struct;
  183711. png_ptr->mem_ptr=mem_ptr;
  183712. (*(free_fn))(png_ptr, struct_ptr);
  183713. return;
  183714. }
  183715. #endif /* PNG_USER_MEM_SUPPORTED */
  183716. farfree (struct_ptr);
  183717. }
  183718. }
  183719. /* Allocate memory. For reasonable files, size should never exceed
  183720. * 64K. However, zlib may allocate more then 64K if you don't tell
  183721. * it not to. See zconf.h and png.h for more information. zlib does
  183722. * need to allocate exactly 64K, so whatever you call here must
  183723. * have the ability to do that.
  183724. *
  183725. * Borland seems to have a problem in DOS mode for exactly 64K.
  183726. * It gives you a segment with an offset of 8 (perhaps to store its
  183727. * memory stuff). zlib doesn't like this at all, so we have to
  183728. * detect and deal with it. This code should not be needed in
  183729. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  183730. * been updated by Alexander Lehmann for version 0.89 to waste less
  183731. * memory.
  183732. *
  183733. * Note that we can't use png_size_t for the "size" declaration,
  183734. * since on some systems a png_size_t is a 16-bit quantity, and as a
  183735. * result, we would be truncating potentially larger memory requests
  183736. * (which should cause a fatal error) and introducing major problems.
  183737. */
  183738. png_voidp PNGAPI
  183739. png_malloc(png_structp png_ptr, png_uint_32 size)
  183740. {
  183741. png_voidp ret;
  183742. if (png_ptr == NULL || size == 0)
  183743. return (NULL);
  183744. #ifdef PNG_USER_MEM_SUPPORTED
  183745. if(png_ptr->malloc_fn != NULL)
  183746. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  183747. else
  183748. ret = (png_malloc_default(png_ptr, size));
  183749. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183750. png_error(png_ptr, "Out of memory!");
  183751. return (ret);
  183752. }
  183753. png_voidp PNGAPI
  183754. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  183755. {
  183756. png_voidp ret;
  183757. #endif /* PNG_USER_MEM_SUPPORTED */
  183758. if (png_ptr == NULL || size == 0)
  183759. return (NULL);
  183760. #ifdef PNG_MAX_MALLOC_64K
  183761. if (size > (png_uint_32)65536L)
  183762. {
  183763. png_warning(png_ptr, "Cannot Allocate > 64K");
  183764. ret = NULL;
  183765. }
  183766. else
  183767. #endif
  183768. if (size != (size_t)size)
  183769. ret = NULL;
  183770. else if (size == (png_uint_32)65536L)
  183771. {
  183772. if (png_ptr->offset_table == NULL)
  183773. {
  183774. /* try to see if we need to do any of this fancy stuff */
  183775. ret = farmalloc(size);
  183776. if (ret == NULL || ((png_size_t)ret & 0xffff))
  183777. {
  183778. int num_blocks;
  183779. png_uint_32 total_size;
  183780. png_bytep table;
  183781. int i;
  183782. png_byte huge * hptr;
  183783. if (ret != NULL)
  183784. {
  183785. farfree(ret);
  183786. ret = NULL;
  183787. }
  183788. if(png_ptr->zlib_window_bits > 14)
  183789. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  183790. else
  183791. num_blocks = 1;
  183792. if (png_ptr->zlib_mem_level >= 7)
  183793. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  183794. else
  183795. num_blocks++;
  183796. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  183797. table = farmalloc(total_size);
  183798. if (table == NULL)
  183799. {
  183800. #ifndef PNG_USER_MEM_SUPPORTED
  183801. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183802. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  183803. else
  183804. png_warning(png_ptr, "Out Of Memory.");
  183805. #endif
  183806. return (NULL);
  183807. }
  183808. if ((png_size_t)table & 0xfff0)
  183809. {
  183810. #ifndef PNG_USER_MEM_SUPPORTED
  183811. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183812. png_error(png_ptr,
  183813. "Farmalloc didn't return normalized pointer");
  183814. else
  183815. png_warning(png_ptr,
  183816. "Farmalloc didn't return normalized pointer");
  183817. #endif
  183818. return (NULL);
  183819. }
  183820. png_ptr->offset_table = table;
  183821. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  183822. png_sizeof (png_bytep));
  183823. if (png_ptr->offset_table_ptr == NULL)
  183824. {
  183825. #ifndef PNG_USER_MEM_SUPPORTED
  183826. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183827. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  183828. else
  183829. png_warning(png_ptr, "Out Of memory.");
  183830. #endif
  183831. return (NULL);
  183832. }
  183833. hptr = (png_byte huge *)table;
  183834. if ((png_size_t)hptr & 0xf)
  183835. {
  183836. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  183837. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  183838. }
  183839. for (i = 0; i < num_blocks; i++)
  183840. {
  183841. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  183842. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  183843. }
  183844. png_ptr->offset_table_number = num_blocks;
  183845. png_ptr->offset_table_count = 0;
  183846. png_ptr->offset_table_count_free = 0;
  183847. }
  183848. }
  183849. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  183850. {
  183851. #ifndef PNG_USER_MEM_SUPPORTED
  183852. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183853. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  183854. else
  183855. png_warning(png_ptr, "Out of Memory.");
  183856. #endif
  183857. return (NULL);
  183858. }
  183859. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  183860. }
  183861. else
  183862. ret = farmalloc(size);
  183863. #ifndef PNG_USER_MEM_SUPPORTED
  183864. if (ret == NULL)
  183865. {
  183866. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183867. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  183868. else
  183869. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  183870. }
  183871. #endif
  183872. return (ret);
  183873. }
  183874. /* free a pointer allocated by png_malloc(). In the default
  183875. configuration, png_ptr is not used, but is passed in case it
  183876. is needed. If ptr is NULL, return without taking any action. */
  183877. void PNGAPI
  183878. png_free(png_structp png_ptr, png_voidp ptr)
  183879. {
  183880. if (png_ptr == NULL || ptr == NULL)
  183881. return;
  183882. #ifdef PNG_USER_MEM_SUPPORTED
  183883. if (png_ptr->free_fn != NULL)
  183884. {
  183885. (*(png_ptr->free_fn))(png_ptr, ptr);
  183886. return;
  183887. }
  183888. else png_free_default(png_ptr, ptr);
  183889. }
  183890. void PNGAPI
  183891. png_free_default(png_structp png_ptr, png_voidp ptr)
  183892. {
  183893. #endif /* PNG_USER_MEM_SUPPORTED */
  183894. if(png_ptr == NULL) return;
  183895. if (png_ptr->offset_table != NULL)
  183896. {
  183897. int i;
  183898. for (i = 0; i < png_ptr->offset_table_count; i++)
  183899. {
  183900. if (ptr == png_ptr->offset_table_ptr[i])
  183901. {
  183902. ptr = NULL;
  183903. png_ptr->offset_table_count_free++;
  183904. break;
  183905. }
  183906. }
  183907. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  183908. {
  183909. farfree(png_ptr->offset_table);
  183910. farfree(png_ptr->offset_table_ptr);
  183911. png_ptr->offset_table = NULL;
  183912. png_ptr->offset_table_ptr = NULL;
  183913. }
  183914. }
  183915. if (ptr != NULL)
  183916. {
  183917. farfree(ptr);
  183918. }
  183919. }
  183920. #else /* Not the Borland DOS special memory handler */
  183921. /* Allocate memory for a png_struct or a png_info. The malloc and
  183922. memset can be replaced by a single call to calloc() if this is thought
  183923. to improve performance noticably. */
  183924. png_voidp /* PRIVATE */
  183925. png_create_struct(int type)
  183926. {
  183927. #ifdef PNG_USER_MEM_SUPPORTED
  183928. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  183929. }
  183930. /* Allocate memory for a png_struct or a png_info. The malloc and
  183931. memset can be replaced by a single call to calloc() if this is thought
  183932. to improve performance noticably. */
  183933. png_voidp /* PRIVATE */
  183934. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  183935. {
  183936. #endif /* PNG_USER_MEM_SUPPORTED */
  183937. png_size_t size;
  183938. png_voidp struct_ptr;
  183939. if (type == PNG_STRUCT_INFO)
  183940. size = png_sizeof(png_info);
  183941. else if (type == PNG_STRUCT_PNG)
  183942. size = png_sizeof(png_struct);
  183943. else
  183944. return (NULL);
  183945. #ifdef PNG_USER_MEM_SUPPORTED
  183946. if(malloc_fn != NULL)
  183947. {
  183948. png_struct dummy_struct;
  183949. png_structp png_ptr = &dummy_struct;
  183950. png_ptr->mem_ptr=mem_ptr;
  183951. struct_ptr = (*(malloc_fn))(png_ptr, size);
  183952. if (struct_ptr != NULL)
  183953. png_memset(struct_ptr, 0, size);
  183954. return (struct_ptr);
  183955. }
  183956. #endif /* PNG_USER_MEM_SUPPORTED */
  183957. #if defined(__TURBOC__) && !defined(__FLAT__)
  183958. struct_ptr = (png_voidp)farmalloc(size);
  183959. #else
  183960. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  183961. struct_ptr = (png_voidp)halloc(size,1);
  183962. # else
  183963. struct_ptr = (png_voidp)malloc(size);
  183964. # endif
  183965. #endif
  183966. if (struct_ptr != NULL)
  183967. png_memset(struct_ptr, 0, size);
  183968. return (struct_ptr);
  183969. }
  183970. /* Free memory allocated by a png_create_struct() call */
  183971. void /* PRIVATE */
  183972. png_destroy_struct(png_voidp struct_ptr)
  183973. {
  183974. #ifdef PNG_USER_MEM_SUPPORTED
  183975. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  183976. }
  183977. /* Free memory allocated by a png_create_struct() call */
  183978. void /* PRIVATE */
  183979. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  183980. png_voidp mem_ptr)
  183981. {
  183982. #endif /* PNG_USER_MEM_SUPPORTED */
  183983. if (struct_ptr != NULL)
  183984. {
  183985. #ifdef PNG_USER_MEM_SUPPORTED
  183986. if(free_fn != NULL)
  183987. {
  183988. png_struct dummy_struct;
  183989. png_structp png_ptr = &dummy_struct;
  183990. png_ptr->mem_ptr=mem_ptr;
  183991. (*(free_fn))(png_ptr, struct_ptr);
  183992. return;
  183993. }
  183994. #endif /* PNG_USER_MEM_SUPPORTED */
  183995. #if defined(__TURBOC__) && !defined(__FLAT__)
  183996. farfree(struct_ptr);
  183997. #else
  183998. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  183999. hfree(struct_ptr);
  184000. # else
  184001. free(struct_ptr);
  184002. # endif
  184003. #endif
  184004. }
  184005. }
  184006. /* Allocate memory. For reasonable files, size should never exceed
  184007. 64K. However, zlib may allocate more then 64K if you don't tell
  184008. it not to. See zconf.h and png.h for more information. zlib does
  184009. need to allocate exactly 64K, so whatever you call here must
  184010. have the ability to do that. */
  184011. png_voidp PNGAPI
  184012. png_malloc(png_structp png_ptr, png_uint_32 size)
  184013. {
  184014. png_voidp ret;
  184015. #ifdef PNG_USER_MEM_SUPPORTED
  184016. if (png_ptr == NULL || size == 0)
  184017. return (NULL);
  184018. if(png_ptr->malloc_fn != NULL)
  184019. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  184020. else
  184021. ret = (png_malloc_default(png_ptr, size));
  184022. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  184023. png_error(png_ptr, "Out of Memory!");
  184024. return (ret);
  184025. }
  184026. png_voidp PNGAPI
  184027. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  184028. {
  184029. png_voidp ret;
  184030. #endif /* PNG_USER_MEM_SUPPORTED */
  184031. if (png_ptr == NULL || size == 0)
  184032. return (NULL);
  184033. #ifdef PNG_MAX_MALLOC_64K
  184034. if (size > (png_uint_32)65536L)
  184035. {
  184036. #ifndef PNG_USER_MEM_SUPPORTED
  184037. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  184038. png_error(png_ptr, "Cannot Allocate > 64K");
  184039. else
  184040. #endif
  184041. return NULL;
  184042. }
  184043. #endif
  184044. /* Check for overflow */
  184045. #if defined(__TURBOC__) && !defined(__FLAT__)
  184046. if (size != (unsigned long)size)
  184047. ret = NULL;
  184048. else
  184049. ret = farmalloc(size);
  184050. #else
  184051. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  184052. if (size != (unsigned long)size)
  184053. ret = NULL;
  184054. else
  184055. ret = halloc(size, 1);
  184056. # else
  184057. if (size != (size_t)size)
  184058. ret = NULL;
  184059. else
  184060. ret = malloc((size_t)size);
  184061. # endif
  184062. #endif
  184063. #ifndef PNG_USER_MEM_SUPPORTED
  184064. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  184065. png_error(png_ptr, "Out of Memory");
  184066. #endif
  184067. return (ret);
  184068. }
  184069. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  184070. without taking any action. */
  184071. void PNGAPI
  184072. png_free(png_structp png_ptr, png_voidp ptr)
  184073. {
  184074. if (png_ptr == NULL || ptr == NULL)
  184075. return;
  184076. #ifdef PNG_USER_MEM_SUPPORTED
  184077. if (png_ptr->free_fn != NULL)
  184078. {
  184079. (*(png_ptr->free_fn))(png_ptr, ptr);
  184080. return;
  184081. }
  184082. else png_free_default(png_ptr, ptr);
  184083. }
  184084. void PNGAPI
  184085. png_free_default(png_structp png_ptr, png_voidp ptr)
  184086. {
  184087. if (png_ptr == NULL || ptr == NULL)
  184088. return;
  184089. #endif /* PNG_USER_MEM_SUPPORTED */
  184090. #if defined(__TURBOC__) && !defined(__FLAT__)
  184091. farfree(ptr);
  184092. #else
  184093. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  184094. hfree(ptr);
  184095. # else
  184096. free(ptr);
  184097. # endif
  184098. #endif
  184099. }
  184100. #endif /* Not Borland DOS special memory handler */
  184101. #if defined(PNG_1_0_X)
  184102. # define png_malloc_warn png_malloc
  184103. #else
  184104. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  184105. * function will set up png_malloc() to issue a png_warning and return NULL
  184106. * instead of issuing a png_error, if it fails to allocate the requested
  184107. * memory.
  184108. */
  184109. png_voidp PNGAPI
  184110. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  184111. {
  184112. png_voidp ptr;
  184113. png_uint_32 save_flags;
  184114. if(png_ptr == NULL) return (NULL);
  184115. save_flags=png_ptr->flags;
  184116. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  184117. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  184118. png_ptr->flags=save_flags;
  184119. return(ptr);
  184120. }
  184121. #endif
  184122. png_voidp PNGAPI
  184123. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  184124. png_uint_32 length)
  184125. {
  184126. png_size_t size;
  184127. size = (png_size_t)length;
  184128. if ((png_uint_32)size != length)
  184129. png_error(png_ptr,"Overflow in png_memcpy_check.");
  184130. return(png_memcpy (s1, s2, size));
  184131. }
  184132. png_voidp PNGAPI
  184133. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  184134. png_uint_32 length)
  184135. {
  184136. png_size_t size;
  184137. size = (png_size_t)length;
  184138. if ((png_uint_32)size != length)
  184139. png_error(png_ptr,"Overflow in png_memset_check.");
  184140. return (png_memset (s1, value, size));
  184141. }
  184142. #ifdef PNG_USER_MEM_SUPPORTED
  184143. /* This function is called when the application wants to use another method
  184144. * of allocating and freeing memory.
  184145. */
  184146. void PNGAPI
  184147. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  184148. malloc_fn, png_free_ptr free_fn)
  184149. {
  184150. if(png_ptr != NULL) {
  184151. png_ptr->mem_ptr = mem_ptr;
  184152. png_ptr->malloc_fn = malloc_fn;
  184153. png_ptr->free_fn = free_fn;
  184154. }
  184155. }
  184156. /* This function returns a pointer to the mem_ptr associated with the user
  184157. * functions. The application should free any memory associated with this
  184158. * pointer before png_write_destroy and png_read_destroy are called.
  184159. */
  184160. png_voidp PNGAPI
  184161. png_get_mem_ptr(png_structp png_ptr)
  184162. {
  184163. if(png_ptr == NULL) return (NULL);
  184164. return ((png_voidp)png_ptr->mem_ptr);
  184165. }
  184166. #endif /* PNG_USER_MEM_SUPPORTED */
  184167. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  184168. /*** End of inlined file: pngmem.c ***/
  184169. /*** Start of inlined file: pngread.c ***/
  184170. /* pngread.c - read a PNG file
  184171. *
  184172. * Last changed in libpng 1.2.20 September 7, 2007
  184173. * For conditions of distribution and use, see copyright notice in png.h
  184174. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184175. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184176. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184177. *
  184178. * This file contains routines that an application calls directly to
  184179. * read a PNG file or stream.
  184180. */
  184181. #define PNG_INTERNAL
  184182. #if defined(PNG_READ_SUPPORTED)
  184183. /* Create a PNG structure for reading, and allocate any memory needed. */
  184184. png_structp PNGAPI
  184185. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  184186. png_error_ptr error_fn, png_error_ptr warn_fn)
  184187. {
  184188. #ifdef PNG_USER_MEM_SUPPORTED
  184189. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  184190. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  184191. }
  184192. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  184193. png_structp PNGAPI
  184194. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  184195. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  184196. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  184197. {
  184198. #endif /* PNG_USER_MEM_SUPPORTED */
  184199. png_structp png_ptr;
  184200. #ifdef PNG_SETJMP_SUPPORTED
  184201. #ifdef USE_FAR_KEYWORD
  184202. jmp_buf jmpbuf;
  184203. #endif
  184204. #endif
  184205. int i;
  184206. png_debug(1, "in png_create_read_struct\n");
  184207. #ifdef PNG_USER_MEM_SUPPORTED
  184208. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  184209. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  184210. #else
  184211. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  184212. #endif
  184213. if (png_ptr == NULL)
  184214. return (NULL);
  184215. /* added at libpng-1.2.6 */
  184216. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  184217. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  184218. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  184219. #endif
  184220. #ifdef PNG_SETJMP_SUPPORTED
  184221. #ifdef USE_FAR_KEYWORD
  184222. if (setjmp(jmpbuf))
  184223. #else
  184224. if (setjmp(png_ptr->jmpbuf))
  184225. #endif
  184226. {
  184227. png_free(png_ptr, png_ptr->zbuf);
  184228. png_ptr->zbuf=NULL;
  184229. #ifdef PNG_USER_MEM_SUPPORTED
  184230. png_destroy_struct_2((png_voidp)png_ptr,
  184231. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  184232. #else
  184233. png_destroy_struct((png_voidp)png_ptr);
  184234. #endif
  184235. return (NULL);
  184236. }
  184237. #ifdef USE_FAR_KEYWORD
  184238. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  184239. #endif
  184240. #endif
  184241. #ifdef PNG_USER_MEM_SUPPORTED
  184242. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  184243. #endif
  184244. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  184245. i=0;
  184246. do
  184247. {
  184248. if(user_png_ver[i] != png_libpng_ver[i])
  184249. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  184250. } while (png_libpng_ver[i++]);
  184251. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  184252. {
  184253. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  184254. * we must recompile any applications that use any older library version.
  184255. * For versions after libpng 1.0, we will be compatible, so we need
  184256. * only check the first digit.
  184257. */
  184258. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  184259. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  184260. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  184261. {
  184262. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  184263. char msg[80];
  184264. if (user_png_ver)
  184265. {
  184266. png_snprintf(msg, 80,
  184267. "Application was compiled with png.h from libpng-%.20s",
  184268. user_png_ver);
  184269. png_warning(png_ptr, msg);
  184270. }
  184271. png_snprintf(msg, 80,
  184272. "Application is running with png.c from libpng-%.20s",
  184273. png_libpng_ver);
  184274. png_warning(png_ptr, msg);
  184275. #endif
  184276. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184277. png_ptr->flags=0;
  184278. #endif
  184279. png_error(png_ptr,
  184280. "Incompatible libpng version in application and library");
  184281. }
  184282. }
  184283. /* initialize zbuf - compression buffer */
  184284. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  184285. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  184286. (png_uint_32)png_ptr->zbuf_size);
  184287. png_ptr->zstream.zalloc = png_zalloc;
  184288. png_ptr->zstream.zfree = png_zfree;
  184289. png_ptr->zstream.opaque = (voidpf)png_ptr;
  184290. switch (inflateInit(&png_ptr->zstream))
  184291. {
  184292. case Z_OK: /* Do nothing */ break;
  184293. case Z_MEM_ERROR:
  184294. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  184295. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  184296. default: png_error(png_ptr, "Unknown zlib error");
  184297. }
  184298. png_ptr->zstream.next_out = png_ptr->zbuf;
  184299. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  184300. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  184301. #ifdef PNG_SETJMP_SUPPORTED
  184302. /* Applications that neglect to set up their own setjmp() and then encounter
  184303. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  184304. abort instead of returning. */
  184305. #ifdef USE_FAR_KEYWORD
  184306. if (setjmp(jmpbuf))
  184307. PNG_ABORT();
  184308. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  184309. #else
  184310. if (setjmp(png_ptr->jmpbuf))
  184311. PNG_ABORT();
  184312. #endif
  184313. #endif
  184314. return (png_ptr);
  184315. }
  184316. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184317. /* Initialize PNG structure for reading, and allocate any memory needed.
  184318. This interface is deprecated in favour of the png_create_read_struct(),
  184319. and it will disappear as of libpng-1.3.0. */
  184320. #undef png_read_init
  184321. void PNGAPI
  184322. png_read_init(png_structp png_ptr)
  184323. {
  184324. /* We only come here via pre-1.0.7-compiled applications */
  184325. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  184326. }
  184327. void PNGAPI
  184328. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  184329. png_size_t png_struct_size, png_size_t png_info_size)
  184330. {
  184331. /* We only come here via pre-1.0.12-compiled applications */
  184332. if(png_ptr == NULL) return;
  184333. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  184334. if(png_sizeof(png_struct) > png_struct_size ||
  184335. png_sizeof(png_info) > png_info_size)
  184336. {
  184337. char msg[80];
  184338. png_ptr->warning_fn=NULL;
  184339. if (user_png_ver)
  184340. {
  184341. png_snprintf(msg, 80,
  184342. "Application was compiled with png.h from libpng-%.20s",
  184343. user_png_ver);
  184344. png_warning(png_ptr, msg);
  184345. }
  184346. png_snprintf(msg, 80,
  184347. "Application is running with png.c from libpng-%.20s",
  184348. png_libpng_ver);
  184349. png_warning(png_ptr, msg);
  184350. }
  184351. #endif
  184352. if(png_sizeof(png_struct) > png_struct_size)
  184353. {
  184354. png_ptr->error_fn=NULL;
  184355. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184356. png_ptr->flags=0;
  184357. #endif
  184358. png_error(png_ptr,
  184359. "The png struct allocated by the application for reading is too small.");
  184360. }
  184361. if(png_sizeof(png_info) > png_info_size)
  184362. {
  184363. png_ptr->error_fn=NULL;
  184364. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184365. png_ptr->flags=0;
  184366. #endif
  184367. png_error(png_ptr,
  184368. "The info struct allocated by application for reading is too small.");
  184369. }
  184370. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  184371. }
  184372. #endif /* PNG_1_0_X || PNG_1_2_X */
  184373. void PNGAPI
  184374. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  184375. png_size_t png_struct_size)
  184376. {
  184377. #ifdef PNG_SETJMP_SUPPORTED
  184378. jmp_buf tmp_jmp; /* to save current jump buffer */
  184379. #endif
  184380. int i=0;
  184381. png_structp png_ptr=*ptr_ptr;
  184382. if(png_ptr == NULL) return;
  184383. do
  184384. {
  184385. if(user_png_ver[i] != png_libpng_ver[i])
  184386. {
  184387. #ifdef PNG_LEGACY_SUPPORTED
  184388. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  184389. #else
  184390. png_ptr->warning_fn=NULL;
  184391. png_warning(png_ptr,
  184392. "Application uses deprecated png_read_init() and should be recompiled.");
  184393. break;
  184394. #endif
  184395. }
  184396. } while (png_libpng_ver[i++]);
  184397. png_debug(1, "in png_read_init_3\n");
  184398. #ifdef PNG_SETJMP_SUPPORTED
  184399. /* save jump buffer and error functions */
  184400. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  184401. #endif
  184402. if(png_sizeof(png_struct) > png_struct_size)
  184403. {
  184404. png_destroy_struct(png_ptr);
  184405. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  184406. png_ptr = *ptr_ptr;
  184407. }
  184408. /* reset all variables to 0 */
  184409. png_memset(png_ptr, 0, png_sizeof (png_struct));
  184410. #ifdef PNG_SETJMP_SUPPORTED
  184411. /* restore jump buffer */
  184412. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  184413. #endif
  184414. /* added at libpng-1.2.6 */
  184415. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  184416. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  184417. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  184418. #endif
  184419. /* initialize zbuf - compression buffer */
  184420. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  184421. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  184422. (png_uint_32)png_ptr->zbuf_size);
  184423. png_ptr->zstream.zalloc = png_zalloc;
  184424. png_ptr->zstream.zfree = png_zfree;
  184425. png_ptr->zstream.opaque = (voidpf)png_ptr;
  184426. switch (inflateInit(&png_ptr->zstream))
  184427. {
  184428. case Z_OK: /* Do nothing */ break;
  184429. case Z_MEM_ERROR:
  184430. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  184431. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  184432. default: png_error(png_ptr, "Unknown zlib error");
  184433. }
  184434. png_ptr->zstream.next_out = png_ptr->zbuf;
  184435. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  184436. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  184437. }
  184438. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  184439. /* Read the information before the actual image data. This has been
  184440. * changed in v0.90 to allow reading a file that already has the magic
  184441. * bytes read from the stream. You can tell libpng how many bytes have
  184442. * been read from the beginning of the stream (up to the maximum of 8)
  184443. * via png_set_sig_bytes(), and we will only check the remaining bytes
  184444. * here. The application can then have access to the signature bytes we
  184445. * read if it is determined that this isn't a valid PNG file.
  184446. */
  184447. void PNGAPI
  184448. png_read_info(png_structp png_ptr, png_infop info_ptr)
  184449. {
  184450. if(png_ptr == NULL) return;
  184451. png_debug(1, "in png_read_info\n");
  184452. /* If we haven't checked all of the PNG signature bytes, do so now. */
  184453. if (png_ptr->sig_bytes < 8)
  184454. {
  184455. png_size_t num_checked = png_ptr->sig_bytes,
  184456. num_to_check = 8 - num_checked;
  184457. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  184458. png_ptr->sig_bytes = 8;
  184459. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  184460. {
  184461. if (num_checked < 4 &&
  184462. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  184463. png_error(png_ptr, "Not a PNG file");
  184464. else
  184465. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  184466. }
  184467. if (num_checked < 3)
  184468. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  184469. }
  184470. for(;;)
  184471. {
  184472. #ifdef PNG_USE_LOCAL_ARRAYS
  184473. PNG_CONST PNG_IHDR;
  184474. PNG_CONST PNG_IDAT;
  184475. PNG_CONST PNG_IEND;
  184476. PNG_CONST PNG_PLTE;
  184477. #if defined(PNG_READ_bKGD_SUPPORTED)
  184478. PNG_CONST PNG_bKGD;
  184479. #endif
  184480. #if defined(PNG_READ_cHRM_SUPPORTED)
  184481. PNG_CONST PNG_cHRM;
  184482. #endif
  184483. #if defined(PNG_READ_gAMA_SUPPORTED)
  184484. PNG_CONST PNG_gAMA;
  184485. #endif
  184486. #if defined(PNG_READ_hIST_SUPPORTED)
  184487. PNG_CONST PNG_hIST;
  184488. #endif
  184489. #if defined(PNG_READ_iCCP_SUPPORTED)
  184490. PNG_CONST PNG_iCCP;
  184491. #endif
  184492. #if defined(PNG_READ_iTXt_SUPPORTED)
  184493. PNG_CONST PNG_iTXt;
  184494. #endif
  184495. #if defined(PNG_READ_oFFs_SUPPORTED)
  184496. PNG_CONST PNG_oFFs;
  184497. #endif
  184498. #if defined(PNG_READ_pCAL_SUPPORTED)
  184499. PNG_CONST PNG_pCAL;
  184500. #endif
  184501. #if defined(PNG_READ_pHYs_SUPPORTED)
  184502. PNG_CONST PNG_pHYs;
  184503. #endif
  184504. #if defined(PNG_READ_sBIT_SUPPORTED)
  184505. PNG_CONST PNG_sBIT;
  184506. #endif
  184507. #if defined(PNG_READ_sCAL_SUPPORTED)
  184508. PNG_CONST PNG_sCAL;
  184509. #endif
  184510. #if defined(PNG_READ_sPLT_SUPPORTED)
  184511. PNG_CONST PNG_sPLT;
  184512. #endif
  184513. #if defined(PNG_READ_sRGB_SUPPORTED)
  184514. PNG_CONST PNG_sRGB;
  184515. #endif
  184516. #if defined(PNG_READ_tEXt_SUPPORTED)
  184517. PNG_CONST PNG_tEXt;
  184518. #endif
  184519. #if defined(PNG_READ_tIME_SUPPORTED)
  184520. PNG_CONST PNG_tIME;
  184521. #endif
  184522. #if defined(PNG_READ_tRNS_SUPPORTED)
  184523. PNG_CONST PNG_tRNS;
  184524. #endif
  184525. #if defined(PNG_READ_zTXt_SUPPORTED)
  184526. PNG_CONST PNG_zTXt;
  184527. #endif
  184528. #endif /* PNG_USE_LOCAL_ARRAYS */
  184529. png_byte chunk_length[4];
  184530. png_uint_32 length;
  184531. png_read_data(png_ptr, chunk_length, 4);
  184532. length = png_get_uint_31(png_ptr,chunk_length);
  184533. png_reset_crc(png_ptr);
  184534. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  184535. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  184536. length);
  184537. /* This should be a binary subdivision search or a hash for
  184538. * matching the chunk name rather than a linear search.
  184539. */
  184540. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184541. if(png_ptr->mode & PNG_AFTER_IDAT)
  184542. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  184543. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  184544. png_handle_IHDR(png_ptr, info_ptr, length);
  184545. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  184546. png_handle_IEND(png_ptr, info_ptr, length);
  184547. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  184548. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  184549. {
  184550. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184551. png_ptr->mode |= PNG_HAVE_IDAT;
  184552. png_handle_unknown(png_ptr, info_ptr, length);
  184553. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  184554. png_ptr->mode |= PNG_HAVE_PLTE;
  184555. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184556. {
  184557. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  184558. png_error(png_ptr, "Missing IHDR before IDAT");
  184559. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  184560. !(png_ptr->mode & PNG_HAVE_PLTE))
  184561. png_error(png_ptr, "Missing PLTE before IDAT");
  184562. break;
  184563. }
  184564. }
  184565. #endif
  184566. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  184567. png_handle_PLTE(png_ptr, info_ptr, length);
  184568. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184569. {
  184570. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  184571. png_error(png_ptr, "Missing IHDR before IDAT");
  184572. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  184573. !(png_ptr->mode & PNG_HAVE_PLTE))
  184574. png_error(png_ptr, "Missing PLTE before IDAT");
  184575. png_ptr->idat_size = length;
  184576. png_ptr->mode |= PNG_HAVE_IDAT;
  184577. break;
  184578. }
  184579. #if defined(PNG_READ_bKGD_SUPPORTED)
  184580. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  184581. png_handle_bKGD(png_ptr, info_ptr, length);
  184582. #endif
  184583. #if defined(PNG_READ_cHRM_SUPPORTED)
  184584. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  184585. png_handle_cHRM(png_ptr, info_ptr, length);
  184586. #endif
  184587. #if defined(PNG_READ_gAMA_SUPPORTED)
  184588. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  184589. png_handle_gAMA(png_ptr, info_ptr, length);
  184590. #endif
  184591. #if defined(PNG_READ_hIST_SUPPORTED)
  184592. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  184593. png_handle_hIST(png_ptr, info_ptr, length);
  184594. #endif
  184595. #if defined(PNG_READ_oFFs_SUPPORTED)
  184596. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  184597. png_handle_oFFs(png_ptr, info_ptr, length);
  184598. #endif
  184599. #if defined(PNG_READ_pCAL_SUPPORTED)
  184600. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  184601. png_handle_pCAL(png_ptr, info_ptr, length);
  184602. #endif
  184603. #if defined(PNG_READ_sCAL_SUPPORTED)
  184604. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  184605. png_handle_sCAL(png_ptr, info_ptr, length);
  184606. #endif
  184607. #if defined(PNG_READ_pHYs_SUPPORTED)
  184608. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  184609. png_handle_pHYs(png_ptr, info_ptr, length);
  184610. #endif
  184611. #if defined(PNG_READ_sBIT_SUPPORTED)
  184612. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  184613. png_handle_sBIT(png_ptr, info_ptr, length);
  184614. #endif
  184615. #if defined(PNG_READ_sRGB_SUPPORTED)
  184616. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  184617. png_handle_sRGB(png_ptr, info_ptr, length);
  184618. #endif
  184619. #if defined(PNG_READ_iCCP_SUPPORTED)
  184620. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  184621. png_handle_iCCP(png_ptr, info_ptr, length);
  184622. #endif
  184623. #if defined(PNG_READ_sPLT_SUPPORTED)
  184624. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  184625. png_handle_sPLT(png_ptr, info_ptr, length);
  184626. #endif
  184627. #if defined(PNG_READ_tEXt_SUPPORTED)
  184628. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  184629. png_handle_tEXt(png_ptr, info_ptr, length);
  184630. #endif
  184631. #if defined(PNG_READ_tIME_SUPPORTED)
  184632. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  184633. png_handle_tIME(png_ptr, info_ptr, length);
  184634. #endif
  184635. #if defined(PNG_READ_tRNS_SUPPORTED)
  184636. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  184637. png_handle_tRNS(png_ptr, info_ptr, length);
  184638. #endif
  184639. #if defined(PNG_READ_zTXt_SUPPORTED)
  184640. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  184641. png_handle_zTXt(png_ptr, info_ptr, length);
  184642. #endif
  184643. #if defined(PNG_READ_iTXt_SUPPORTED)
  184644. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  184645. png_handle_iTXt(png_ptr, info_ptr, length);
  184646. #endif
  184647. else
  184648. png_handle_unknown(png_ptr, info_ptr, length);
  184649. }
  184650. }
  184651. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  184652. /* optional call to update the users info_ptr structure */
  184653. void PNGAPI
  184654. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  184655. {
  184656. png_debug(1, "in png_read_update_info\n");
  184657. if(png_ptr == NULL) return;
  184658. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  184659. png_read_start_row(png_ptr);
  184660. else
  184661. png_warning(png_ptr,
  184662. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  184663. png_read_transform_info(png_ptr, info_ptr);
  184664. }
  184665. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  184666. /* Initialize palette, background, etc, after transformations
  184667. * are set, but before any reading takes place. This allows
  184668. * the user to obtain a gamma-corrected palette, for example.
  184669. * If the user doesn't call this, we will do it ourselves.
  184670. */
  184671. void PNGAPI
  184672. png_start_read_image(png_structp png_ptr)
  184673. {
  184674. png_debug(1, "in png_start_read_image\n");
  184675. if(png_ptr == NULL) return;
  184676. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  184677. png_read_start_row(png_ptr);
  184678. }
  184679. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  184680. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  184681. void PNGAPI
  184682. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  184683. {
  184684. #ifdef PNG_USE_LOCAL_ARRAYS
  184685. PNG_CONST PNG_IDAT;
  184686. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  184687. 0xff};
  184688. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184689. #endif
  184690. int ret;
  184691. if(png_ptr == NULL) return;
  184692. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  184693. png_ptr->row_number, png_ptr->pass);
  184694. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  184695. png_read_start_row(png_ptr);
  184696. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  184697. {
  184698. /* check for transforms that have been set but were defined out */
  184699. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  184700. if (png_ptr->transformations & PNG_INVERT_MONO)
  184701. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  184702. #endif
  184703. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  184704. if (png_ptr->transformations & PNG_FILLER)
  184705. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  184706. #endif
  184707. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  184708. if (png_ptr->transformations & PNG_PACKSWAP)
  184709. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  184710. #endif
  184711. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  184712. if (png_ptr->transformations & PNG_PACK)
  184713. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  184714. #endif
  184715. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  184716. if (png_ptr->transformations & PNG_SHIFT)
  184717. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  184718. #endif
  184719. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  184720. if (png_ptr->transformations & PNG_BGR)
  184721. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  184722. #endif
  184723. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  184724. if (png_ptr->transformations & PNG_SWAP_BYTES)
  184725. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  184726. #endif
  184727. }
  184728. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184729. /* if interlaced and we do not need a new row, combine row and return */
  184730. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  184731. {
  184732. switch (png_ptr->pass)
  184733. {
  184734. case 0:
  184735. if (png_ptr->row_number & 0x07)
  184736. {
  184737. if (dsp_row != NULL)
  184738. png_combine_row(png_ptr, dsp_row,
  184739. png_pass_dsp_mask[png_ptr->pass]);
  184740. png_read_finish_row(png_ptr);
  184741. return;
  184742. }
  184743. break;
  184744. case 1:
  184745. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  184746. {
  184747. if (dsp_row != NULL)
  184748. png_combine_row(png_ptr, dsp_row,
  184749. png_pass_dsp_mask[png_ptr->pass]);
  184750. png_read_finish_row(png_ptr);
  184751. return;
  184752. }
  184753. break;
  184754. case 2:
  184755. if ((png_ptr->row_number & 0x07) != 4)
  184756. {
  184757. if (dsp_row != NULL && (png_ptr->row_number & 4))
  184758. png_combine_row(png_ptr, dsp_row,
  184759. png_pass_dsp_mask[png_ptr->pass]);
  184760. png_read_finish_row(png_ptr);
  184761. return;
  184762. }
  184763. break;
  184764. case 3:
  184765. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  184766. {
  184767. if (dsp_row != NULL)
  184768. png_combine_row(png_ptr, dsp_row,
  184769. png_pass_dsp_mask[png_ptr->pass]);
  184770. png_read_finish_row(png_ptr);
  184771. return;
  184772. }
  184773. break;
  184774. case 4:
  184775. if ((png_ptr->row_number & 3) != 2)
  184776. {
  184777. if (dsp_row != NULL && (png_ptr->row_number & 2))
  184778. png_combine_row(png_ptr, dsp_row,
  184779. png_pass_dsp_mask[png_ptr->pass]);
  184780. png_read_finish_row(png_ptr);
  184781. return;
  184782. }
  184783. break;
  184784. case 5:
  184785. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  184786. {
  184787. if (dsp_row != NULL)
  184788. png_combine_row(png_ptr, dsp_row,
  184789. png_pass_dsp_mask[png_ptr->pass]);
  184790. png_read_finish_row(png_ptr);
  184791. return;
  184792. }
  184793. break;
  184794. case 6:
  184795. if (!(png_ptr->row_number & 1))
  184796. {
  184797. png_read_finish_row(png_ptr);
  184798. return;
  184799. }
  184800. break;
  184801. }
  184802. }
  184803. #endif
  184804. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  184805. png_error(png_ptr, "Invalid attempt to read row data");
  184806. png_ptr->zstream.next_out = png_ptr->row_buf;
  184807. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  184808. do
  184809. {
  184810. if (!(png_ptr->zstream.avail_in))
  184811. {
  184812. while (!png_ptr->idat_size)
  184813. {
  184814. png_byte chunk_length[4];
  184815. png_crc_finish(png_ptr, 0);
  184816. png_read_data(png_ptr, chunk_length, 4);
  184817. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  184818. png_reset_crc(png_ptr);
  184819. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  184820. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184821. png_error(png_ptr, "Not enough image data");
  184822. }
  184823. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  184824. png_ptr->zstream.next_in = png_ptr->zbuf;
  184825. if (png_ptr->zbuf_size > png_ptr->idat_size)
  184826. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  184827. png_crc_read(png_ptr, png_ptr->zbuf,
  184828. (png_size_t)png_ptr->zstream.avail_in);
  184829. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  184830. }
  184831. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  184832. if (ret == Z_STREAM_END)
  184833. {
  184834. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  184835. png_ptr->idat_size)
  184836. png_error(png_ptr, "Extra compressed data");
  184837. png_ptr->mode |= PNG_AFTER_IDAT;
  184838. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  184839. break;
  184840. }
  184841. if (ret != Z_OK)
  184842. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  184843. "Decompression error");
  184844. } while (png_ptr->zstream.avail_out);
  184845. png_ptr->row_info.color_type = png_ptr->color_type;
  184846. png_ptr->row_info.width = png_ptr->iwidth;
  184847. png_ptr->row_info.channels = png_ptr->channels;
  184848. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  184849. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  184850. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  184851. png_ptr->row_info.width);
  184852. if(png_ptr->row_buf[0])
  184853. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  184854. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  184855. (int)(png_ptr->row_buf[0]));
  184856. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  184857. png_ptr->rowbytes + 1);
  184858. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  184859. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  184860. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  184861. {
  184862. /* Intrapixel differencing */
  184863. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  184864. }
  184865. #endif
  184866. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  184867. png_do_read_transformations(png_ptr);
  184868. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184869. /* blow up interlaced rows to full size */
  184870. if (png_ptr->interlaced &&
  184871. (png_ptr->transformations & PNG_INTERLACE))
  184872. {
  184873. if (png_ptr->pass < 6)
  184874. /* old interface (pre-1.0.9):
  184875. png_do_read_interlace(&(png_ptr->row_info),
  184876. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  184877. */
  184878. png_do_read_interlace(png_ptr);
  184879. if (dsp_row != NULL)
  184880. png_combine_row(png_ptr, dsp_row,
  184881. png_pass_dsp_mask[png_ptr->pass]);
  184882. if (row != NULL)
  184883. png_combine_row(png_ptr, row,
  184884. png_pass_mask[png_ptr->pass]);
  184885. }
  184886. else
  184887. #endif
  184888. {
  184889. if (row != NULL)
  184890. png_combine_row(png_ptr, row, 0xff);
  184891. if (dsp_row != NULL)
  184892. png_combine_row(png_ptr, dsp_row, 0xff);
  184893. }
  184894. png_read_finish_row(png_ptr);
  184895. if (png_ptr->read_row_fn != NULL)
  184896. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  184897. }
  184898. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  184899. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  184900. /* Read one or more rows of image data. If the image is interlaced,
  184901. * and png_set_interlace_handling() has been called, the rows need to
  184902. * contain the contents of the rows from the previous pass. If the
  184903. * image has alpha or transparency, and png_handle_alpha()[*] has been
  184904. * called, the rows contents must be initialized to the contents of the
  184905. * screen.
  184906. *
  184907. * "row" holds the actual image, and pixels are placed in it
  184908. * as they arrive. If the image is displayed after each pass, it will
  184909. * appear to "sparkle" in. "display_row" can be used to display a
  184910. * "chunky" progressive image, with finer detail added as it becomes
  184911. * available. If you do not want this "chunky" display, you may pass
  184912. * NULL for display_row. If you do not want the sparkle display, and
  184913. * you have not called png_handle_alpha(), you may pass NULL for rows.
  184914. * If you have called png_handle_alpha(), and the image has either an
  184915. * alpha channel or a transparency chunk, you must provide a buffer for
  184916. * rows. In this case, you do not have to provide a display_row buffer
  184917. * also, but you may. If the image is not interlaced, or if you have
  184918. * not called png_set_interlace_handling(), the display_row buffer will
  184919. * be ignored, so pass NULL to it.
  184920. *
  184921. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  184922. */
  184923. void PNGAPI
  184924. png_read_rows(png_structp png_ptr, png_bytepp row,
  184925. png_bytepp display_row, png_uint_32 num_rows)
  184926. {
  184927. png_uint_32 i;
  184928. png_bytepp rp;
  184929. png_bytepp dp;
  184930. png_debug(1, "in png_read_rows\n");
  184931. if(png_ptr == NULL) return;
  184932. rp = row;
  184933. dp = display_row;
  184934. if (rp != NULL && dp != NULL)
  184935. for (i = 0; i < num_rows; i++)
  184936. {
  184937. png_bytep rptr = *rp++;
  184938. png_bytep dptr = *dp++;
  184939. png_read_row(png_ptr, rptr, dptr);
  184940. }
  184941. else if(rp != NULL)
  184942. for (i = 0; i < num_rows; i++)
  184943. {
  184944. png_bytep rptr = *rp;
  184945. png_read_row(png_ptr, rptr, png_bytep_NULL);
  184946. rp++;
  184947. }
  184948. else if(dp != NULL)
  184949. for (i = 0; i < num_rows; i++)
  184950. {
  184951. png_bytep dptr = *dp;
  184952. png_read_row(png_ptr, png_bytep_NULL, dptr);
  184953. dp++;
  184954. }
  184955. }
  184956. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  184957. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  184958. /* Read the entire image. If the image has an alpha channel or a tRNS
  184959. * chunk, and you have called png_handle_alpha()[*], you will need to
  184960. * initialize the image to the current image that PNG will be overlaying.
  184961. * We set the num_rows again here, in case it was incorrectly set in
  184962. * png_read_start_row() by a call to png_read_update_info() or
  184963. * png_start_read_image() if png_set_interlace_handling() wasn't called
  184964. * prior to either of these functions like it should have been. You can
  184965. * only call this function once. If you desire to have an image for
  184966. * each pass of a interlaced image, use png_read_rows() instead.
  184967. *
  184968. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  184969. */
  184970. void PNGAPI
  184971. png_read_image(png_structp png_ptr, png_bytepp image)
  184972. {
  184973. png_uint_32 i,image_height;
  184974. int pass, j;
  184975. png_bytepp rp;
  184976. png_debug(1, "in png_read_image\n");
  184977. if(png_ptr == NULL) return;
  184978. #ifdef PNG_READ_INTERLACING_SUPPORTED
  184979. pass = png_set_interlace_handling(png_ptr);
  184980. #else
  184981. if (png_ptr->interlaced)
  184982. png_error(png_ptr,
  184983. "Cannot read interlaced image -- interlace handler disabled.");
  184984. pass = 1;
  184985. #endif
  184986. image_height=png_ptr->height;
  184987. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  184988. for (j = 0; j < pass; j++)
  184989. {
  184990. rp = image;
  184991. for (i = 0; i < image_height; i++)
  184992. {
  184993. png_read_row(png_ptr, *rp, png_bytep_NULL);
  184994. rp++;
  184995. }
  184996. }
  184997. }
  184998. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  184999. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  185000. /* Read the end of the PNG file. Will not read past the end of the
  185001. * file, will verify the end is accurate, and will read any comments
  185002. * or time information at the end of the file, if info is not NULL.
  185003. */
  185004. void PNGAPI
  185005. png_read_end(png_structp png_ptr, png_infop info_ptr)
  185006. {
  185007. png_byte chunk_length[4];
  185008. png_uint_32 length;
  185009. png_debug(1, "in png_read_end\n");
  185010. if(png_ptr == NULL) return;
  185011. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  185012. do
  185013. {
  185014. #ifdef PNG_USE_LOCAL_ARRAYS
  185015. PNG_CONST PNG_IHDR;
  185016. PNG_CONST PNG_IDAT;
  185017. PNG_CONST PNG_IEND;
  185018. PNG_CONST PNG_PLTE;
  185019. #if defined(PNG_READ_bKGD_SUPPORTED)
  185020. PNG_CONST PNG_bKGD;
  185021. #endif
  185022. #if defined(PNG_READ_cHRM_SUPPORTED)
  185023. PNG_CONST PNG_cHRM;
  185024. #endif
  185025. #if defined(PNG_READ_gAMA_SUPPORTED)
  185026. PNG_CONST PNG_gAMA;
  185027. #endif
  185028. #if defined(PNG_READ_hIST_SUPPORTED)
  185029. PNG_CONST PNG_hIST;
  185030. #endif
  185031. #if defined(PNG_READ_iCCP_SUPPORTED)
  185032. PNG_CONST PNG_iCCP;
  185033. #endif
  185034. #if defined(PNG_READ_iTXt_SUPPORTED)
  185035. PNG_CONST PNG_iTXt;
  185036. #endif
  185037. #if defined(PNG_READ_oFFs_SUPPORTED)
  185038. PNG_CONST PNG_oFFs;
  185039. #endif
  185040. #if defined(PNG_READ_pCAL_SUPPORTED)
  185041. PNG_CONST PNG_pCAL;
  185042. #endif
  185043. #if defined(PNG_READ_pHYs_SUPPORTED)
  185044. PNG_CONST PNG_pHYs;
  185045. #endif
  185046. #if defined(PNG_READ_sBIT_SUPPORTED)
  185047. PNG_CONST PNG_sBIT;
  185048. #endif
  185049. #if defined(PNG_READ_sCAL_SUPPORTED)
  185050. PNG_CONST PNG_sCAL;
  185051. #endif
  185052. #if defined(PNG_READ_sPLT_SUPPORTED)
  185053. PNG_CONST PNG_sPLT;
  185054. #endif
  185055. #if defined(PNG_READ_sRGB_SUPPORTED)
  185056. PNG_CONST PNG_sRGB;
  185057. #endif
  185058. #if defined(PNG_READ_tEXt_SUPPORTED)
  185059. PNG_CONST PNG_tEXt;
  185060. #endif
  185061. #if defined(PNG_READ_tIME_SUPPORTED)
  185062. PNG_CONST PNG_tIME;
  185063. #endif
  185064. #if defined(PNG_READ_tRNS_SUPPORTED)
  185065. PNG_CONST PNG_tRNS;
  185066. #endif
  185067. #if defined(PNG_READ_zTXt_SUPPORTED)
  185068. PNG_CONST PNG_zTXt;
  185069. #endif
  185070. #endif /* PNG_USE_LOCAL_ARRAYS */
  185071. png_read_data(png_ptr, chunk_length, 4);
  185072. length = png_get_uint_31(png_ptr,chunk_length);
  185073. png_reset_crc(png_ptr);
  185074. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  185075. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  185076. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  185077. png_handle_IHDR(png_ptr, info_ptr, length);
  185078. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  185079. png_handle_IEND(png_ptr, info_ptr, length);
  185080. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  185081. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  185082. {
  185083. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  185084. {
  185085. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  185086. png_error(png_ptr, "Too many IDAT's found");
  185087. }
  185088. png_handle_unknown(png_ptr, info_ptr, length);
  185089. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  185090. png_ptr->mode |= PNG_HAVE_PLTE;
  185091. }
  185092. #endif
  185093. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  185094. {
  185095. /* Zero length IDATs are legal after the last IDAT has been
  185096. * read, but not after other chunks have been read.
  185097. */
  185098. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  185099. png_error(png_ptr, "Too many IDAT's found");
  185100. png_crc_finish(png_ptr, length);
  185101. }
  185102. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  185103. png_handle_PLTE(png_ptr, info_ptr, length);
  185104. #if defined(PNG_READ_bKGD_SUPPORTED)
  185105. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  185106. png_handle_bKGD(png_ptr, info_ptr, length);
  185107. #endif
  185108. #if defined(PNG_READ_cHRM_SUPPORTED)
  185109. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  185110. png_handle_cHRM(png_ptr, info_ptr, length);
  185111. #endif
  185112. #if defined(PNG_READ_gAMA_SUPPORTED)
  185113. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  185114. png_handle_gAMA(png_ptr, info_ptr, length);
  185115. #endif
  185116. #if defined(PNG_READ_hIST_SUPPORTED)
  185117. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  185118. png_handle_hIST(png_ptr, info_ptr, length);
  185119. #endif
  185120. #if defined(PNG_READ_oFFs_SUPPORTED)
  185121. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  185122. png_handle_oFFs(png_ptr, info_ptr, length);
  185123. #endif
  185124. #if defined(PNG_READ_pCAL_SUPPORTED)
  185125. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  185126. png_handle_pCAL(png_ptr, info_ptr, length);
  185127. #endif
  185128. #if defined(PNG_READ_sCAL_SUPPORTED)
  185129. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  185130. png_handle_sCAL(png_ptr, info_ptr, length);
  185131. #endif
  185132. #if defined(PNG_READ_pHYs_SUPPORTED)
  185133. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  185134. png_handle_pHYs(png_ptr, info_ptr, length);
  185135. #endif
  185136. #if defined(PNG_READ_sBIT_SUPPORTED)
  185137. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  185138. png_handle_sBIT(png_ptr, info_ptr, length);
  185139. #endif
  185140. #if defined(PNG_READ_sRGB_SUPPORTED)
  185141. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  185142. png_handle_sRGB(png_ptr, info_ptr, length);
  185143. #endif
  185144. #if defined(PNG_READ_iCCP_SUPPORTED)
  185145. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  185146. png_handle_iCCP(png_ptr, info_ptr, length);
  185147. #endif
  185148. #if defined(PNG_READ_sPLT_SUPPORTED)
  185149. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  185150. png_handle_sPLT(png_ptr, info_ptr, length);
  185151. #endif
  185152. #if defined(PNG_READ_tEXt_SUPPORTED)
  185153. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  185154. png_handle_tEXt(png_ptr, info_ptr, length);
  185155. #endif
  185156. #if defined(PNG_READ_tIME_SUPPORTED)
  185157. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  185158. png_handle_tIME(png_ptr, info_ptr, length);
  185159. #endif
  185160. #if defined(PNG_READ_tRNS_SUPPORTED)
  185161. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  185162. png_handle_tRNS(png_ptr, info_ptr, length);
  185163. #endif
  185164. #if defined(PNG_READ_zTXt_SUPPORTED)
  185165. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  185166. png_handle_zTXt(png_ptr, info_ptr, length);
  185167. #endif
  185168. #if defined(PNG_READ_iTXt_SUPPORTED)
  185169. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  185170. png_handle_iTXt(png_ptr, info_ptr, length);
  185171. #endif
  185172. else
  185173. png_handle_unknown(png_ptr, info_ptr, length);
  185174. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  185175. }
  185176. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  185177. /* free all memory used by the read */
  185178. void PNGAPI
  185179. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  185180. png_infopp end_info_ptr_ptr)
  185181. {
  185182. png_structp png_ptr = NULL;
  185183. png_infop info_ptr = NULL, end_info_ptr = NULL;
  185184. #ifdef PNG_USER_MEM_SUPPORTED
  185185. png_free_ptr free_fn;
  185186. png_voidp mem_ptr;
  185187. #endif
  185188. png_debug(1, "in png_destroy_read_struct\n");
  185189. if (png_ptr_ptr != NULL)
  185190. png_ptr = *png_ptr_ptr;
  185191. if (info_ptr_ptr != NULL)
  185192. info_ptr = *info_ptr_ptr;
  185193. if (end_info_ptr_ptr != NULL)
  185194. end_info_ptr = *end_info_ptr_ptr;
  185195. #ifdef PNG_USER_MEM_SUPPORTED
  185196. free_fn = png_ptr->free_fn;
  185197. mem_ptr = png_ptr->mem_ptr;
  185198. #endif
  185199. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  185200. if (info_ptr != NULL)
  185201. {
  185202. #if defined(PNG_TEXT_SUPPORTED)
  185203. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  185204. #endif
  185205. #ifdef PNG_USER_MEM_SUPPORTED
  185206. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  185207. (png_voidp)mem_ptr);
  185208. #else
  185209. png_destroy_struct((png_voidp)info_ptr);
  185210. #endif
  185211. *info_ptr_ptr = NULL;
  185212. }
  185213. if (end_info_ptr != NULL)
  185214. {
  185215. #if defined(PNG_READ_TEXT_SUPPORTED)
  185216. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  185217. #endif
  185218. #ifdef PNG_USER_MEM_SUPPORTED
  185219. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  185220. (png_voidp)mem_ptr);
  185221. #else
  185222. png_destroy_struct((png_voidp)end_info_ptr);
  185223. #endif
  185224. *end_info_ptr_ptr = NULL;
  185225. }
  185226. if (png_ptr != NULL)
  185227. {
  185228. #ifdef PNG_USER_MEM_SUPPORTED
  185229. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  185230. (png_voidp)mem_ptr);
  185231. #else
  185232. png_destroy_struct((png_voidp)png_ptr);
  185233. #endif
  185234. *png_ptr_ptr = NULL;
  185235. }
  185236. }
  185237. /* free all memory used by the read (old method) */
  185238. void /* PRIVATE */
  185239. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  185240. {
  185241. #ifdef PNG_SETJMP_SUPPORTED
  185242. jmp_buf tmp_jmp;
  185243. #endif
  185244. png_error_ptr error_fn;
  185245. png_error_ptr warning_fn;
  185246. png_voidp error_ptr;
  185247. #ifdef PNG_USER_MEM_SUPPORTED
  185248. png_free_ptr free_fn;
  185249. #endif
  185250. png_debug(1, "in png_read_destroy\n");
  185251. if (info_ptr != NULL)
  185252. png_info_destroy(png_ptr, info_ptr);
  185253. if (end_info_ptr != NULL)
  185254. png_info_destroy(png_ptr, end_info_ptr);
  185255. png_free(png_ptr, png_ptr->zbuf);
  185256. png_free(png_ptr, png_ptr->big_row_buf);
  185257. png_free(png_ptr, png_ptr->prev_row);
  185258. #if defined(PNG_READ_DITHER_SUPPORTED)
  185259. png_free(png_ptr, png_ptr->palette_lookup);
  185260. png_free(png_ptr, png_ptr->dither_index);
  185261. #endif
  185262. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185263. png_free(png_ptr, png_ptr->gamma_table);
  185264. #endif
  185265. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  185266. png_free(png_ptr, png_ptr->gamma_from_1);
  185267. png_free(png_ptr, png_ptr->gamma_to_1);
  185268. #endif
  185269. #ifdef PNG_FREE_ME_SUPPORTED
  185270. if (png_ptr->free_me & PNG_FREE_PLTE)
  185271. png_zfree(png_ptr, png_ptr->palette);
  185272. png_ptr->free_me &= ~PNG_FREE_PLTE;
  185273. #else
  185274. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  185275. png_zfree(png_ptr, png_ptr->palette);
  185276. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  185277. #endif
  185278. #if defined(PNG_tRNS_SUPPORTED) || \
  185279. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  185280. #ifdef PNG_FREE_ME_SUPPORTED
  185281. if (png_ptr->free_me & PNG_FREE_TRNS)
  185282. png_free(png_ptr, png_ptr->trans);
  185283. png_ptr->free_me &= ~PNG_FREE_TRNS;
  185284. #else
  185285. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  185286. png_free(png_ptr, png_ptr->trans);
  185287. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  185288. #endif
  185289. #endif
  185290. #if defined(PNG_READ_hIST_SUPPORTED)
  185291. #ifdef PNG_FREE_ME_SUPPORTED
  185292. if (png_ptr->free_me & PNG_FREE_HIST)
  185293. png_free(png_ptr, png_ptr->hist);
  185294. png_ptr->free_me &= ~PNG_FREE_HIST;
  185295. #else
  185296. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  185297. png_free(png_ptr, png_ptr->hist);
  185298. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  185299. #endif
  185300. #endif
  185301. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185302. if (png_ptr->gamma_16_table != NULL)
  185303. {
  185304. int i;
  185305. int istop = (1 << (8 - png_ptr->gamma_shift));
  185306. for (i = 0; i < istop; i++)
  185307. {
  185308. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  185309. }
  185310. png_free(png_ptr, png_ptr->gamma_16_table);
  185311. }
  185312. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  185313. if (png_ptr->gamma_16_from_1 != NULL)
  185314. {
  185315. int i;
  185316. int istop = (1 << (8 - png_ptr->gamma_shift));
  185317. for (i = 0; i < istop; i++)
  185318. {
  185319. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  185320. }
  185321. png_free(png_ptr, png_ptr->gamma_16_from_1);
  185322. }
  185323. if (png_ptr->gamma_16_to_1 != NULL)
  185324. {
  185325. int i;
  185326. int istop = (1 << (8 - png_ptr->gamma_shift));
  185327. for (i = 0; i < istop; i++)
  185328. {
  185329. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  185330. }
  185331. png_free(png_ptr, png_ptr->gamma_16_to_1);
  185332. }
  185333. #endif
  185334. #endif
  185335. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  185336. png_free(png_ptr, png_ptr->time_buffer);
  185337. #endif
  185338. inflateEnd(&png_ptr->zstream);
  185339. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  185340. png_free(png_ptr, png_ptr->save_buffer);
  185341. #endif
  185342. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  185343. #ifdef PNG_TEXT_SUPPORTED
  185344. png_free(png_ptr, png_ptr->current_text);
  185345. #endif /* PNG_TEXT_SUPPORTED */
  185346. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  185347. /* Save the important info out of the png_struct, in case it is
  185348. * being used again.
  185349. */
  185350. #ifdef PNG_SETJMP_SUPPORTED
  185351. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  185352. #endif
  185353. error_fn = png_ptr->error_fn;
  185354. warning_fn = png_ptr->warning_fn;
  185355. error_ptr = png_ptr->error_ptr;
  185356. #ifdef PNG_USER_MEM_SUPPORTED
  185357. free_fn = png_ptr->free_fn;
  185358. #endif
  185359. png_memset(png_ptr, 0, png_sizeof (png_struct));
  185360. png_ptr->error_fn = error_fn;
  185361. png_ptr->warning_fn = warning_fn;
  185362. png_ptr->error_ptr = error_ptr;
  185363. #ifdef PNG_USER_MEM_SUPPORTED
  185364. png_ptr->free_fn = free_fn;
  185365. #endif
  185366. #ifdef PNG_SETJMP_SUPPORTED
  185367. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  185368. #endif
  185369. }
  185370. void PNGAPI
  185371. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  185372. {
  185373. if(png_ptr == NULL) return;
  185374. png_ptr->read_row_fn = read_row_fn;
  185375. }
  185376. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  185377. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185378. void PNGAPI
  185379. png_read_png(png_structp png_ptr, png_infop info_ptr,
  185380. int transforms,
  185381. voidp params)
  185382. {
  185383. int row;
  185384. if(png_ptr == NULL) return;
  185385. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  185386. /* invert the alpha channel from opacity to transparency
  185387. */
  185388. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  185389. png_set_invert_alpha(png_ptr);
  185390. #endif
  185391. /* png_read_info() gives us all of the information from the
  185392. * PNG file before the first IDAT (image data chunk).
  185393. */
  185394. png_read_info(png_ptr, info_ptr);
  185395. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  185396. png_error(png_ptr,"Image is too high to process with png_read_png()");
  185397. /* -------------- image transformations start here ------------------- */
  185398. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  185399. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  185400. */
  185401. if (transforms & PNG_TRANSFORM_STRIP_16)
  185402. png_set_strip_16(png_ptr);
  185403. #endif
  185404. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  185405. /* Strip alpha bytes from the input data without combining with
  185406. * the background (not recommended).
  185407. */
  185408. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  185409. png_set_strip_alpha(png_ptr);
  185410. #endif
  185411. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  185412. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  185413. * byte into separate bytes (useful for paletted and grayscale images).
  185414. */
  185415. if (transforms & PNG_TRANSFORM_PACKING)
  185416. png_set_packing(png_ptr);
  185417. #endif
  185418. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  185419. /* Change the order of packed pixels to least significant bit first
  185420. * (not useful if you are using png_set_packing).
  185421. */
  185422. if (transforms & PNG_TRANSFORM_PACKSWAP)
  185423. png_set_packswap(png_ptr);
  185424. #endif
  185425. #if defined(PNG_READ_EXPAND_SUPPORTED)
  185426. /* Expand paletted colors into true RGB triplets
  185427. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  185428. * Expand paletted or RGB images with transparency to full alpha
  185429. * channels so the data will be available as RGBA quartets.
  185430. */
  185431. if (transforms & PNG_TRANSFORM_EXPAND)
  185432. if ((png_ptr->bit_depth < 8) ||
  185433. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  185434. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  185435. png_set_expand(png_ptr);
  185436. #endif
  185437. /* We don't handle background color or gamma transformation or dithering.
  185438. */
  185439. #if defined(PNG_READ_INVERT_SUPPORTED)
  185440. /* invert monochrome files to have 0 as white and 1 as black
  185441. */
  185442. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  185443. png_set_invert_mono(png_ptr);
  185444. #endif
  185445. #if defined(PNG_READ_SHIFT_SUPPORTED)
  185446. /* If you want to shift the pixel values from the range [0,255] or
  185447. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  185448. * colors were originally in:
  185449. */
  185450. if ((transforms & PNG_TRANSFORM_SHIFT)
  185451. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  185452. {
  185453. png_color_8p sig_bit;
  185454. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  185455. png_set_shift(png_ptr, sig_bit);
  185456. }
  185457. #endif
  185458. #if defined(PNG_READ_BGR_SUPPORTED)
  185459. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  185460. */
  185461. if (transforms & PNG_TRANSFORM_BGR)
  185462. png_set_bgr(png_ptr);
  185463. #endif
  185464. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  185465. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  185466. */
  185467. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  185468. png_set_swap_alpha(png_ptr);
  185469. #endif
  185470. #if defined(PNG_READ_SWAP_SUPPORTED)
  185471. /* swap bytes of 16 bit files to least significant byte first
  185472. */
  185473. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  185474. png_set_swap(png_ptr);
  185475. #endif
  185476. /* We don't handle adding filler bytes */
  185477. /* Optional call to gamma correct and add the background to the palette
  185478. * and update info structure. REQUIRED if you are expecting libpng to
  185479. * update the palette for you (i.e., you selected such a transform above).
  185480. */
  185481. png_read_update_info(png_ptr, info_ptr);
  185482. /* -------------- image transformations end here ------------------- */
  185483. #ifdef PNG_FREE_ME_SUPPORTED
  185484. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  185485. #endif
  185486. if(info_ptr->row_pointers == NULL)
  185487. {
  185488. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  185489. info_ptr->height * png_sizeof(png_bytep));
  185490. #ifdef PNG_FREE_ME_SUPPORTED
  185491. info_ptr->free_me |= PNG_FREE_ROWS;
  185492. #endif
  185493. for (row = 0; row < (int)info_ptr->height; row++)
  185494. {
  185495. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  185496. png_get_rowbytes(png_ptr, info_ptr));
  185497. }
  185498. }
  185499. png_read_image(png_ptr, info_ptr->row_pointers);
  185500. info_ptr->valid |= PNG_INFO_IDAT;
  185501. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  185502. png_read_end(png_ptr, info_ptr);
  185503. transforms = transforms; /* quiet compiler warnings */
  185504. params = params;
  185505. }
  185506. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  185507. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  185508. #endif /* PNG_READ_SUPPORTED */
  185509. /*** End of inlined file: pngread.c ***/
  185510. /*** Start of inlined file: pngpread.c ***/
  185511. /* pngpread.c - read a png file in push mode
  185512. *
  185513. * Last changed in libpng 1.2.21 October 4, 2007
  185514. * For conditions of distribution and use, see copyright notice in png.h
  185515. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185516. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185517. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185518. */
  185519. #define PNG_INTERNAL
  185520. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  185521. /* push model modes */
  185522. #define PNG_READ_SIG_MODE 0
  185523. #define PNG_READ_CHUNK_MODE 1
  185524. #define PNG_READ_IDAT_MODE 2
  185525. #define PNG_SKIP_MODE 3
  185526. #define PNG_READ_tEXt_MODE 4
  185527. #define PNG_READ_zTXt_MODE 5
  185528. #define PNG_READ_DONE_MODE 6
  185529. #define PNG_READ_iTXt_MODE 7
  185530. #define PNG_ERROR_MODE 8
  185531. void PNGAPI
  185532. png_process_data(png_structp png_ptr, png_infop info_ptr,
  185533. png_bytep buffer, png_size_t buffer_size)
  185534. {
  185535. if(png_ptr == NULL) return;
  185536. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  185537. while (png_ptr->buffer_size)
  185538. {
  185539. png_process_some_data(png_ptr, info_ptr);
  185540. }
  185541. }
  185542. /* What we do with the incoming data depends on what we were previously
  185543. * doing before we ran out of data...
  185544. */
  185545. void /* PRIVATE */
  185546. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  185547. {
  185548. if(png_ptr == NULL) return;
  185549. switch (png_ptr->process_mode)
  185550. {
  185551. case PNG_READ_SIG_MODE:
  185552. {
  185553. png_push_read_sig(png_ptr, info_ptr);
  185554. break;
  185555. }
  185556. case PNG_READ_CHUNK_MODE:
  185557. {
  185558. png_push_read_chunk(png_ptr, info_ptr);
  185559. break;
  185560. }
  185561. case PNG_READ_IDAT_MODE:
  185562. {
  185563. png_push_read_IDAT(png_ptr);
  185564. break;
  185565. }
  185566. #if defined(PNG_READ_tEXt_SUPPORTED)
  185567. case PNG_READ_tEXt_MODE:
  185568. {
  185569. png_push_read_tEXt(png_ptr, info_ptr);
  185570. break;
  185571. }
  185572. #endif
  185573. #if defined(PNG_READ_zTXt_SUPPORTED)
  185574. case PNG_READ_zTXt_MODE:
  185575. {
  185576. png_push_read_zTXt(png_ptr, info_ptr);
  185577. break;
  185578. }
  185579. #endif
  185580. #if defined(PNG_READ_iTXt_SUPPORTED)
  185581. case PNG_READ_iTXt_MODE:
  185582. {
  185583. png_push_read_iTXt(png_ptr, info_ptr);
  185584. break;
  185585. }
  185586. #endif
  185587. case PNG_SKIP_MODE:
  185588. {
  185589. png_push_crc_finish(png_ptr);
  185590. break;
  185591. }
  185592. default:
  185593. {
  185594. png_ptr->buffer_size = 0;
  185595. break;
  185596. }
  185597. }
  185598. }
  185599. /* Read any remaining signature bytes from the stream and compare them with
  185600. * the correct PNG signature. It is possible that this routine is called
  185601. * with bytes already read from the signature, either because they have been
  185602. * checked by the calling application, or because of multiple calls to this
  185603. * routine.
  185604. */
  185605. void /* PRIVATE */
  185606. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  185607. {
  185608. png_size_t num_checked = png_ptr->sig_bytes,
  185609. num_to_check = 8 - num_checked;
  185610. if (png_ptr->buffer_size < num_to_check)
  185611. {
  185612. num_to_check = png_ptr->buffer_size;
  185613. }
  185614. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  185615. num_to_check);
  185616. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  185617. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  185618. {
  185619. if (num_checked < 4 &&
  185620. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  185621. png_error(png_ptr, "Not a PNG file");
  185622. else
  185623. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  185624. }
  185625. else
  185626. {
  185627. if (png_ptr->sig_bytes >= 8)
  185628. {
  185629. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  185630. }
  185631. }
  185632. }
  185633. void /* PRIVATE */
  185634. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  185635. {
  185636. #ifdef PNG_USE_LOCAL_ARRAYS
  185637. PNG_CONST PNG_IHDR;
  185638. PNG_CONST PNG_IDAT;
  185639. PNG_CONST PNG_IEND;
  185640. PNG_CONST PNG_PLTE;
  185641. #if defined(PNG_READ_bKGD_SUPPORTED)
  185642. PNG_CONST PNG_bKGD;
  185643. #endif
  185644. #if defined(PNG_READ_cHRM_SUPPORTED)
  185645. PNG_CONST PNG_cHRM;
  185646. #endif
  185647. #if defined(PNG_READ_gAMA_SUPPORTED)
  185648. PNG_CONST PNG_gAMA;
  185649. #endif
  185650. #if defined(PNG_READ_hIST_SUPPORTED)
  185651. PNG_CONST PNG_hIST;
  185652. #endif
  185653. #if defined(PNG_READ_iCCP_SUPPORTED)
  185654. PNG_CONST PNG_iCCP;
  185655. #endif
  185656. #if defined(PNG_READ_iTXt_SUPPORTED)
  185657. PNG_CONST PNG_iTXt;
  185658. #endif
  185659. #if defined(PNG_READ_oFFs_SUPPORTED)
  185660. PNG_CONST PNG_oFFs;
  185661. #endif
  185662. #if defined(PNG_READ_pCAL_SUPPORTED)
  185663. PNG_CONST PNG_pCAL;
  185664. #endif
  185665. #if defined(PNG_READ_pHYs_SUPPORTED)
  185666. PNG_CONST PNG_pHYs;
  185667. #endif
  185668. #if defined(PNG_READ_sBIT_SUPPORTED)
  185669. PNG_CONST PNG_sBIT;
  185670. #endif
  185671. #if defined(PNG_READ_sCAL_SUPPORTED)
  185672. PNG_CONST PNG_sCAL;
  185673. #endif
  185674. #if defined(PNG_READ_sRGB_SUPPORTED)
  185675. PNG_CONST PNG_sRGB;
  185676. #endif
  185677. #if defined(PNG_READ_sPLT_SUPPORTED)
  185678. PNG_CONST PNG_sPLT;
  185679. #endif
  185680. #if defined(PNG_READ_tEXt_SUPPORTED)
  185681. PNG_CONST PNG_tEXt;
  185682. #endif
  185683. #if defined(PNG_READ_tIME_SUPPORTED)
  185684. PNG_CONST PNG_tIME;
  185685. #endif
  185686. #if defined(PNG_READ_tRNS_SUPPORTED)
  185687. PNG_CONST PNG_tRNS;
  185688. #endif
  185689. #if defined(PNG_READ_zTXt_SUPPORTED)
  185690. PNG_CONST PNG_zTXt;
  185691. #endif
  185692. #endif /* PNG_USE_LOCAL_ARRAYS */
  185693. /* First we make sure we have enough data for the 4 byte chunk name
  185694. * and the 4 byte chunk length before proceeding with decoding the
  185695. * chunk data. To fully decode each of these chunks, we also make
  185696. * sure we have enough data in the buffer for the 4 byte CRC at the
  185697. * end of every chunk (except IDAT, which is handled separately).
  185698. */
  185699. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  185700. {
  185701. png_byte chunk_length[4];
  185702. if (png_ptr->buffer_size < 8)
  185703. {
  185704. png_push_save_buffer(png_ptr);
  185705. return;
  185706. }
  185707. png_push_fill_buffer(png_ptr, chunk_length, 4);
  185708. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  185709. png_reset_crc(png_ptr);
  185710. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  185711. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  185712. }
  185713. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  185714. if(png_ptr->mode & PNG_AFTER_IDAT)
  185715. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  185716. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  185717. {
  185718. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185719. {
  185720. png_push_save_buffer(png_ptr);
  185721. return;
  185722. }
  185723. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  185724. }
  185725. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  185726. {
  185727. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185728. {
  185729. png_push_save_buffer(png_ptr);
  185730. return;
  185731. }
  185732. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  185733. png_ptr->process_mode = PNG_READ_DONE_MODE;
  185734. png_push_have_end(png_ptr, info_ptr);
  185735. }
  185736. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  185737. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  185738. {
  185739. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185740. {
  185741. png_push_save_buffer(png_ptr);
  185742. return;
  185743. }
  185744. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  185745. png_ptr->mode |= PNG_HAVE_IDAT;
  185746. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  185747. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  185748. png_ptr->mode |= PNG_HAVE_PLTE;
  185749. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  185750. {
  185751. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  185752. png_error(png_ptr, "Missing IHDR before IDAT");
  185753. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  185754. !(png_ptr->mode & PNG_HAVE_PLTE))
  185755. png_error(png_ptr, "Missing PLTE before IDAT");
  185756. }
  185757. }
  185758. #endif
  185759. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  185760. {
  185761. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185762. {
  185763. png_push_save_buffer(png_ptr);
  185764. return;
  185765. }
  185766. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  185767. }
  185768. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  185769. {
  185770. /* If we reach an IDAT chunk, this means we have read all of the
  185771. * header chunks, and we can start reading the image (or if this
  185772. * is called after the image has been read - we have an error).
  185773. */
  185774. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  185775. png_error(png_ptr, "Missing IHDR before IDAT");
  185776. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  185777. !(png_ptr->mode & PNG_HAVE_PLTE))
  185778. png_error(png_ptr, "Missing PLTE before IDAT");
  185779. if (png_ptr->mode & PNG_HAVE_IDAT)
  185780. {
  185781. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  185782. if (png_ptr->push_length == 0)
  185783. return;
  185784. if (png_ptr->mode & PNG_AFTER_IDAT)
  185785. png_error(png_ptr, "Too many IDAT's found");
  185786. }
  185787. png_ptr->idat_size = png_ptr->push_length;
  185788. png_ptr->mode |= PNG_HAVE_IDAT;
  185789. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  185790. png_push_have_info(png_ptr, info_ptr);
  185791. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  185792. png_ptr->zstream.next_out = png_ptr->row_buf;
  185793. return;
  185794. }
  185795. #if defined(PNG_READ_gAMA_SUPPORTED)
  185796. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  185797. {
  185798. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185799. {
  185800. png_push_save_buffer(png_ptr);
  185801. return;
  185802. }
  185803. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  185804. }
  185805. #endif
  185806. #if defined(PNG_READ_sBIT_SUPPORTED)
  185807. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  185808. {
  185809. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185810. {
  185811. png_push_save_buffer(png_ptr);
  185812. return;
  185813. }
  185814. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  185815. }
  185816. #endif
  185817. #if defined(PNG_READ_cHRM_SUPPORTED)
  185818. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  185819. {
  185820. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185821. {
  185822. png_push_save_buffer(png_ptr);
  185823. return;
  185824. }
  185825. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  185826. }
  185827. #endif
  185828. #if defined(PNG_READ_sRGB_SUPPORTED)
  185829. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  185830. {
  185831. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185832. {
  185833. png_push_save_buffer(png_ptr);
  185834. return;
  185835. }
  185836. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  185837. }
  185838. #endif
  185839. #if defined(PNG_READ_iCCP_SUPPORTED)
  185840. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  185841. {
  185842. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185843. {
  185844. png_push_save_buffer(png_ptr);
  185845. return;
  185846. }
  185847. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  185848. }
  185849. #endif
  185850. #if defined(PNG_READ_sPLT_SUPPORTED)
  185851. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  185852. {
  185853. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185854. {
  185855. png_push_save_buffer(png_ptr);
  185856. return;
  185857. }
  185858. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  185859. }
  185860. #endif
  185861. #if defined(PNG_READ_tRNS_SUPPORTED)
  185862. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  185863. {
  185864. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185865. {
  185866. png_push_save_buffer(png_ptr);
  185867. return;
  185868. }
  185869. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  185870. }
  185871. #endif
  185872. #if defined(PNG_READ_bKGD_SUPPORTED)
  185873. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  185874. {
  185875. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185876. {
  185877. png_push_save_buffer(png_ptr);
  185878. return;
  185879. }
  185880. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  185881. }
  185882. #endif
  185883. #if defined(PNG_READ_hIST_SUPPORTED)
  185884. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  185885. {
  185886. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185887. {
  185888. png_push_save_buffer(png_ptr);
  185889. return;
  185890. }
  185891. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  185892. }
  185893. #endif
  185894. #if defined(PNG_READ_pHYs_SUPPORTED)
  185895. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  185896. {
  185897. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185898. {
  185899. png_push_save_buffer(png_ptr);
  185900. return;
  185901. }
  185902. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  185903. }
  185904. #endif
  185905. #if defined(PNG_READ_oFFs_SUPPORTED)
  185906. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  185907. {
  185908. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185909. {
  185910. png_push_save_buffer(png_ptr);
  185911. return;
  185912. }
  185913. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  185914. }
  185915. #endif
  185916. #if defined(PNG_READ_pCAL_SUPPORTED)
  185917. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  185918. {
  185919. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185920. {
  185921. png_push_save_buffer(png_ptr);
  185922. return;
  185923. }
  185924. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  185925. }
  185926. #endif
  185927. #if defined(PNG_READ_sCAL_SUPPORTED)
  185928. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  185929. {
  185930. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185931. {
  185932. png_push_save_buffer(png_ptr);
  185933. return;
  185934. }
  185935. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  185936. }
  185937. #endif
  185938. #if defined(PNG_READ_tIME_SUPPORTED)
  185939. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  185940. {
  185941. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185942. {
  185943. png_push_save_buffer(png_ptr);
  185944. return;
  185945. }
  185946. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  185947. }
  185948. #endif
  185949. #if defined(PNG_READ_tEXt_SUPPORTED)
  185950. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  185951. {
  185952. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185953. {
  185954. png_push_save_buffer(png_ptr);
  185955. return;
  185956. }
  185957. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  185958. }
  185959. #endif
  185960. #if defined(PNG_READ_zTXt_SUPPORTED)
  185961. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  185962. {
  185963. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185964. {
  185965. png_push_save_buffer(png_ptr);
  185966. return;
  185967. }
  185968. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  185969. }
  185970. #endif
  185971. #if defined(PNG_READ_iTXt_SUPPORTED)
  185972. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  185973. {
  185974. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185975. {
  185976. png_push_save_buffer(png_ptr);
  185977. return;
  185978. }
  185979. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  185980. }
  185981. #endif
  185982. else
  185983. {
  185984. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185985. {
  185986. png_push_save_buffer(png_ptr);
  185987. return;
  185988. }
  185989. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  185990. }
  185991. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  185992. }
  185993. void /* PRIVATE */
  185994. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  185995. {
  185996. png_ptr->process_mode = PNG_SKIP_MODE;
  185997. png_ptr->skip_length = skip;
  185998. }
  185999. void /* PRIVATE */
  186000. png_push_crc_finish(png_structp png_ptr)
  186001. {
  186002. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  186003. {
  186004. png_size_t save_size;
  186005. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  186006. save_size = (png_size_t)png_ptr->skip_length;
  186007. else
  186008. save_size = png_ptr->save_buffer_size;
  186009. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  186010. png_ptr->skip_length -= save_size;
  186011. png_ptr->buffer_size -= save_size;
  186012. png_ptr->save_buffer_size -= save_size;
  186013. png_ptr->save_buffer_ptr += save_size;
  186014. }
  186015. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  186016. {
  186017. png_size_t save_size;
  186018. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  186019. save_size = (png_size_t)png_ptr->skip_length;
  186020. else
  186021. save_size = png_ptr->current_buffer_size;
  186022. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  186023. png_ptr->skip_length -= save_size;
  186024. png_ptr->buffer_size -= save_size;
  186025. png_ptr->current_buffer_size -= save_size;
  186026. png_ptr->current_buffer_ptr += save_size;
  186027. }
  186028. if (!png_ptr->skip_length)
  186029. {
  186030. if (png_ptr->buffer_size < 4)
  186031. {
  186032. png_push_save_buffer(png_ptr);
  186033. return;
  186034. }
  186035. png_crc_finish(png_ptr, 0);
  186036. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  186037. }
  186038. }
  186039. void PNGAPI
  186040. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  186041. {
  186042. png_bytep ptr;
  186043. if(png_ptr == NULL) return;
  186044. ptr = buffer;
  186045. if (png_ptr->save_buffer_size)
  186046. {
  186047. png_size_t save_size;
  186048. if (length < png_ptr->save_buffer_size)
  186049. save_size = length;
  186050. else
  186051. save_size = png_ptr->save_buffer_size;
  186052. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  186053. length -= save_size;
  186054. ptr += save_size;
  186055. png_ptr->buffer_size -= save_size;
  186056. png_ptr->save_buffer_size -= save_size;
  186057. png_ptr->save_buffer_ptr += save_size;
  186058. }
  186059. if (length && png_ptr->current_buffer_size)
  186060. {
  186061. png_size_t save_size;
  186062. if (length < png_ptr->current_buffer_size)
  186063. save_size = length;
  186064. else
  186065. save_size = png_ptr->current_buffer_size;
  186066. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  186067. png_ptr->buffer_size -= save_size;
  186068. png_ptr->current_buffer_size -= save_size;
  186069. png_ptr->current_buffer_ptr += save_size;
  186070. }
  186071. }
  186072. void /* PRIVATE */
  186073. png_push_save_buffer(png_structp png_ptr)
  186074. {
  186075. if (png_ptr->save_buffer_size)
  186076. {
  186077. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  186078. {
  186079. png_size_t i,istop;
  186080. png_bytep sp;
  186081. png_bytep dp;
  186082. istop = png_ptr->save_buffer_size;
  186083. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  186084. i < istop; i++, sp++, dp++)
  186085. {
  186086. *dp = *sp;
  186087. }
  186088. }
  186089. }
  186090. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  186091. png_ptr->save_buffer_max)
  186092. {
  186093. png_size_t new_max;
  186094. png_bytep old_buffer;
  186095. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  186096. (png_ptr->current_buffer_size + 256))
  186097. {
  186098. png_error(png_ptr, "Potential overflow of save_buffer");
  186099. }
  186100. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  186101. old_buffer = png_ptr->save_buffer;
  186102. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  186103. (png_uint_32)new_max);
  186104. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  186105. png_free(png_ptr, old_buffer);
  186106. png_ptr->save_buffer_max = new_max;
  186107. }
  186108. if (png_ptr->current_buffer_size)
  186109. {
  186110. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  186111. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  186112. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  186113. png_ptr->current_buffer_size = 0;
  186114. }
  186115. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  186116. png_ptr->buffer_size = 0;
  186117. }
  186118. void /* PRIVATE */
  186119. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  186120. png_size_t buffer_length)
  186121. {
  186122. png_ptr->current_buffer = buffer;
  186123. png_ptr->current_buffer_size = buffer_length;
  186124. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  186125. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  186126. }
  186127. void /* PRIVATE */
  186128. png_push_read_IDAT(png_structp png_ptr)
  186129. {
  186130. #ifdef PNG_USE_LOCAL_ARRAYS
  186131. PNG_CONST PNG_IDAT;
  186132. #endif
  186133. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  186134. {
  186135. png_byte chunk_length[4];
  186136. if (png_ptr->buffer_size < 8)
  186137. {
  186138. png_push_save_buffer(png_ptr);
  186139. return;
  186140. }
  186141. png_push_fill_buffer(png_ptr, chunk_length, 4);
  186142. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  186143. png_reset_crc(png_ptr);
  186144. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  186145. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  186146. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186147. {
  186148. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  186149. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  186150. png_error(png_ptr, "Not enough compressed data");
  186151. return;
  186152. }
  186153. png_ptr->idat_size = png_ptr->push_length;
  186154. }
  186155. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  186156. {
  186157. png_size_t save_size;
  186158. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  186159. {
  186160. save_size = (png_size_t)png_ptr->idat_size;
  186161. /* check for overflow */
  186162. if((png_uint_32)save_size != png_ptr->idat_size)
  186163. png_error(png_ptr, "save_size overflowed in pngpread");
  186164. }
  186165. else
  186166. save_size = png_ptr->save_buffer_size;
  186167. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  186168. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  186169. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  186170. png_ptr->idat_size -= save_size;
  186171. png_ptr->buffer_size -= save_size;
  186172. png_ptr->save_buffer_size -= save_size;
  186173. png_ptr->save_buffer_ptr += save_size;
  186174. }
  186175. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  186176. {
  186177. png_size_t save_size;
  186178. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  186179. {
  186180. save_size = (png_size_t)png_ptr->idat_size;
  186181. /* check for overflow */
  186182. if((png_uint_32)save_size != png_ptr->idat_size)
  186183. png_error(png_ptr, "save_size overflowed in pngpread");
  186184. }
  186185. else
  186186. save_size = png_ptr->current_buffer_size;
  186187. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  186188. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  186189. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  186190. png_ptr->idat_size -= save_size;
  186191. png_ptr->buffer_size -= save_size;
  186192. png_ptr->current_buffer_size -= save_size;
  186193. png_ptr->current_buffer_ptr += save_size;
  186194. }
  186195. if (!png_ptr->idat_size)
  186196. {
  186197. if (png_ptr->buffer_size < 4)
  186198. {
  186199. png_push_save_buffer(png_ptr);
  186200. return;
  186201. }
  186202. png_crc_finish(png_ptr, 0);
  186203. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  186204. png_ptr->mode |= PNG_AFTER_IDAT;
  186205. }
  186206. }
  186207. void /* PRIVATE */
  186208. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  186209. png_size_t buffer_length)
  186210. {
  186211. int ret;
  186212. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  186213. png_error(png_ptr, "Extra compression data");
  186214. png_ptr->zstream.next_in = buffer;
  186215. png_ptr->zstream.avail_in = (uInt)buffer_length;
  186216. for(;;)
  186217. {
  186218. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  186219. if (ret != Z_OK)
  186220. {
  186221. if (ret == Z_STREAM_END)
  186222. {
  186223. if (png_ptr->zstream.avail_in)
  186224. png_error(png_ptr, "Extra compressed data");
  186225. if (!(png_ptr->zstream.avail_out))
  186226. {
  186227. png_push_process_row(png_ptr);
  186228. }
  186229. png_ptr->mode |= PNG_AFTER_IDAT;
  186230. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  186231. break;
  186232. }
  186233. else if (ret == Z_BUF_ERROR)
  186234. break;
  186235. else
  186236. png_error(png_ptr, "Decompression Error");
  186237. }
  186238. if (!(png_ptr->zstream.avail_out))
  186239. {
  186240. if ((
  186241. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  186242. png_ptr->interlaced && png_ptr->pass > 6) ||
  186243. (!png_ptr->interlaced &&
  186244. #endif
  186245. png_ptr->row_number == png_ptr->num_rows))
  186246. {
  186247. if (png_ptr->zstream.avail_in)
  186248. {
  186249. png_warning(png_ptr, "Too much data in IDAT chunks");
  186250. }
  186251. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  186252. break;
  186253. }
  186254. png_push_process_row(png_ptr);
  186255. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  186256. png_ptr->zstream.next_out = png_ptr->row_buf;
  186257. }
  186258. else
  186259. break;
  186260. }
  186261. }
  186262. void /* PRIVATE */
  186263. png_push_process_row(png_structp png_ptr)
  186264. {
  186265. png_ptr->row_info.color_type = png_ptr->color_type;
  186266. png_ptr->row_info.width = png_ptr->iwidth;
  186267. png_ptr->row_info.channels = png_ptr->channels;
  186268. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  186269. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  186270. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  186271. png_ptr->row_info.width);
  186272. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  186273. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  186274. (int)(png_ptr->row_buf[0]));
  186275. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  186276. png_ptr->rowbytes + 1);
  186277. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  186278. png_do_read_transformations(png_ptr);
  186279. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  186280. /* blow up interlaced rows to full size */
  186281. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  186282. {
  186283. if (png_ptr->pass < 6)
  186284. /* old interface (pre-1.0.9):
  186285. png_do_read_interlace(&(png_ptr->row_info),
  186286. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  186287. */
  186288. png_do_read_interlace(png_ptr);
  186289. switch (png_ptr->pass)
  186290. {
  186291. case 0:
  186292. {
  186293. int i;
  186294. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  186295. {
  186296. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  186297. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  186298. }
  186299. if (png_ptr->pass == 2) /* pass 1 might be empty */
  186300. {
  186301. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  186302. {
  186303. png_push_have_row(png_ptr, png_bytep_NULL);
  186304. png_read_push_finish_row(png_ptr);
  186305. }
  186306. }
  186307. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  186308. {
  186309. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  186310. {
  186311. png_push_have_row(png_ptr, png_bytep_NULL);
  186312. png_read_push_finish_row(png_ptr);
  186313. }
  186314. }
  186315. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  186316. {
  186317. png_push_have_row(png_ptr, png_bytep_NULL);
  186318. png_read_push_finish_row(png_ptr);
  186319. }
  186320. break;
  186321. }
  186322. case 1:
  186323. {
  186324. int i;
  186325. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  186326. {
  186327. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  186328. png_read_push_finish_row(png_ptr);
  186329. }
  186330. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  186331. {
  186332. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  186333. {
  186334. png_push_have_row(png_ptr, png_bytep_NULL);
  186335. png_read_push_finish_row(png_ptr);
  186336. }
  186337. }
  186338. break;
  186339. }
  186340. case 2:
  186341. {
  186342. int i;
  186343. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  186344. {
  186345. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  186346. png_read_push_finish_row(png_ptr);
  186347. }
  186348. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  186349. {
  186350. png_push_have_row(png_ptr, png_bytep_NULL);
  186351. png_read_push_finish_row(png_ptr);
  186352. }
  186353. if (png_ptr->pass == 4) /* pass 3 might be empty */
  186354. {
  186355. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  186356. {
  186357. png_push_have_row(png_ptr, png_bytep_NULL);
  186358. png_read_push_finish_row(png_ptr);
  186359. }
  186360. }
  186361. break;
  186362. }
  186363. case 3:
  186364. {
  186365. int i;
  186366. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  186367. {
  186368. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  186369. png_read_push_finish_row(png_ptr);
  186370. }
  186371. if (png_ptr->pass == 4) /* skip top two generated rows */
  186372. {
  186373. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  186374. {
  186375. png_push_have_row(png_ptr, png_bytep_NULL);
  186376. png_read_push_finish_row(png_ptr);
  186377. }
  186378. }
  186379. break;
  186380. }
  186381. case 4:
  186382. {
  186383. int i;
  186384. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  186385. {
  186386. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  186387. png_read_push_finish_row(png_ptr);
  186388. }
  186389. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  186390. {
  186391. png_push_have_row(png_ptr, png_bytep_NULL);
  186392. png_read_push_finish_row(png_ptr);
  186393. }
  186394. if (png_ptr->pass == 6) /* pass 5 might be empty */
  186395. {
  186396. png_push_have_row(png_ptr, png_bytep_NULL);
  186397. png_read_push_finish_row(png_ptr);
  186398. }
  186399. break;
  186400. }
  186401. case 5:
  186402. {
  186403. int i;
  186404. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  186405. {
  186406. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  186407. png_read_push_finish_row(png_ptr);
  186408. }
  186409. if (png_ptr->pass == 6) /* skip top generated row */
  186410. {
  186411. png_push_have_row(png_ptr, png_bytep_NULL);
  186412. png_read_push_finish_row(png_ptr);
  186413. }
  186414. break;
  186415. }
  186416. case 6:
  186417. {
  186418. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  186419. png_read_push_finish_row(png_ptr);
  186420. if (png_ptr->pass != 6)
  186421. break;
  186422. png_push_have_row(png_ptr, png_bytep_NULL);
  186423. png_read_push_finish_row(png_ptr);
  186424. }
  186425. }
  186426. }
  186427. else
  186428. #endif
  186429. {
  186430. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  186431. png_read_push_finish_row(png_ptr);
  186432. }
  186433. }
  186434. void /* PRIVATE */
  186435. png_read_push_finish_row(png_structp png_ptr)
  186436. {
  186437. #ifdef PNG_USE_LOCAL_ARRAYS
  186438. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  186439. /* start of interlace block */
  186440. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  186441. /* offset to next interlace block */
  186442. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  186443. /* start of interlace block in the y direction */
  186444. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  186445. /* offset to next interlace block in the y direction */
  186446. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  186447. /* Height of interlace block. This is not currently used - if you need
  186448. * it, uncomment it here and in png.h
  186449. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  186450. */
  186451. #endif
  186452. png_ptr->row_number++;
  186453. if (png_ptr->row_number < png_ptr->num_rows)
  186454. return;
  186455. if (png_ptr->interlaced)
  186456. {
  186457. png_ptr->row_number = 0;
  186458. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  186459. png_ptr->rowbytes + 1);
  186460. do
  186461. {
  186462. png_ptr->pass++;
  186463. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  186464. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  186465. (png_ptr->pass == 5 && png_ptr->width < 2))
  186466. png_ptr->pass++;
  186467. if (png_ptr->pass > 7)
  186468. png_ptr->pass--;
  186469. if (png_ptr->pass >= 7)
  186470. break;
  186471. png_ptr->iwidth = (png_ptr->width +
  186472. png_pass_inc[png_ptr->pass] - 1 -
  186473. png_pass_start[png_ptr->pass]) /
  186474. png_pass_inc[png_ptr->pass];
  186475. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  186476. png_ptr->iwidth) + 1;
  186477. if (png_ptr->transformations & PNG_INTERLACE)
  186478. break;
  186479. png_ptr->num_rows = (png_ptr->height +
  186480. png_pass_yinc[png_ptr->pass] - 1 -
  186481. png_pass_ystart[png_ptr->pass]) /
  186482. png_pass_yinc[png_ptr->pass];
  186483. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  186484. }
  186485. }
  186486. #if defined(PNG_READ_tEXt_SUPPORTED)
  186487. void /* PRIVATE */
  186488. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  186489. length)
  186490. {
  186491. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  186492. {
  186493. png_error(png_ptr, "Out of place tEXt");
  186494. info_ptr = info_ptr; /* to quiet some compiler warnings */
  186495. }
  186496. #ifdef PNG_MAX_MALLOC_64K
  186497. png_ptr->skip_length = 0; /* This may not be necessary */
  186498. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  186499. {
  186500. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  186501. png_ptr->skip_length = length - (png_uint_32)65535L;
  186502. length = (png_uint_32)65535L;
  186503. }
  186504. #endif
  186505. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  186506. (png_uint_32)(length+1));
  186507. png_ptr->current_text[length] = '\0';
  186508. png_ptr->current_text_ptr = png_ptr->current_text;
  186509. png_ptr->current_text_size = (png_size_t)length;
  186510. png_ptr->current_text_left = (png_size_t)length;
  186511. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  186512. }
  186513. void /* PRIVATE */
  186514. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  186515. {
  186516. if (png_ptr->buffer_size && png_ptr->current_text_left)
  186517. {
  186518. png_size_t text_size;
  186519. if (png_ptr->buffer_size < png_ptr->current_text_left)
  186520. text_size = png_ptr->buffer_size;
  186521. else
  186522. text_size = png_ptr->current_text_left;
  186523. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  186524. png_ptr->current_text_left -= text_size;
  186525. png_ptr->current_text_ptr += text_size;
  186526. }
  186527. if (!(png_ptr->current_text_left))
  186528. {
  186529. png_textp text_ptr;
  186530. png_charp text;
  186531. png_charp key;
  186532. int ret;
  186533. if (png_ptr->buffer_size < 4)
  186534. {
  186535. png_push_save_buffer(png_ptr);
  186536. return;
  186537. }
  186538. png_push_crc_finish(png_ptr);
  186539. #if defined(PNG_MAX_MALLOC_64K)
  186540. if (png_ptr->skip_length)
  186541. return;
  186542. #endif
  186543. key = png_ptr->current_text;
  186544. for (text = key; *text; text++)
  186545. /* empty loop */ ;
  186546. if (text < key + png_ptr->current_text_size)
  186547. text++;
  186548. text_ptr = (png_textp)png_malloc(png_ptr,
  186549. (png_uint_32)png_sizeof(png_text));
  186550. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  186551. text_ptr->key = key;
  186552. #ifdef PNG_iTXt_SUPPORTED
  186553. text_ptr->lang = NULL;
  186554. text_ptr->lang_key = NULL;
  186555. #endif
  186556. text_ptr->text = text;
  186557. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  186558. png_free(png_ptr, key);
  186559. png_free(png_ptr, text_ptr);
  186560. png_ptr->current_text = NULL;
  186561. if (ret)
  186562. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  186563. }
  186564. }
  186565. #endif
  186566. #if defined(PNG_READ_zTXt_SUPPORTED)
  186567. void /* PRIVATE */
  186568. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  186569. length)
  186570. {
  186571. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  186572. {
  186573. png_error(png_ptr, "Out of place zTXt");
  186574. info_ptr = info_ptr; /* to quiet some compiler warnings */
  186575. }
  186576. #ifdef PNG_MAX_MALLOC_64K
  186577. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  186578. * to be able to store the uncompressed data. Actually, the threshold
  186579. * is probably around 32K, but it isn't as definite as 64K is.
  186580. */
  186581. if (length > (png_uint_32)65535L)
  186582. {
  186583. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  186584. png_push_crc_skip(png_ptr, length);
  186585. return;
  186586. }
  186587. #endif
  186588. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  186589. (png_uint_32)(length+1));
  186590. png_ptr->current_text[length] = '\0';
  186591. png_ptr->current_text_ptr = png_ptr->current_text;
  186592. png_ptr->current_text_size = (png_size_t)length;
  186593. png_ptr->current_text_left = (png_size_t)length;
  186594. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  186595. }
  186596. void /* PRIVATE */
  186597. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  186598. {
  186599. if (png_ptr->buffer_size && png_ptr->current_text_left)
  186600. {
  186601. png_size_t text_size;
  186602. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  186603. text_size = png_ptr->buffer_size;
  186604. else
  186605. text_size = png_ptr->current_text_left;
  186606. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  186607. png_ptr->current_text_left -= text_size;
  186608. png_ptr->current_text_ptr += text_size;
  186609. }
  186610. if (!(png_ptr->current_text_left))
  186611. {
  186612. png_textp text_ptr;
  186613. png_charp text;
  186614. png_charp key;
  186615. int ret;
  186616. png_size_t text_size, key_size;
  186617. if (png_ptr->buffer_size < 4)
  186618. {
  186619. png_push_save_buffer(png_ptr);
  186620. return;
  186621. }
  186622. png_push_crc_finish(png_ptr);
  186623. key = png_ptr->current_text;
  186624. for (text = key; *text; text++)
  186625. /* empty loop */ ;
  186626. /* zTXt can't have zero text */
  186627. if (text >= key + png_ptr->current_text_size)
  186628. {
  186629. png_ptr->current_text = NULL;
  186630. png_free(png_ptr, key);
  186631. return;
  186632. }
  186633. text++;
  186634. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  186635. {
  186636. png_ptr->current_text = NULL;
  186637. png_free(png_ptr, key);
  186638. return;
  186639. }
  186640. text++;
  186641. png_ptr->zstream.next_in = (png_bytep )text;
  186642. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  186643. (text - key));
  186644. png_ptr->zstream.next_out = png_ptr->zbuf;
  186645. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  186646. key_size = text - key;
  186647. text_size = 0;
  186648. text = NULL;
  186649. ret = Z_STREAM_END;
  186650. while (png_ptr->zstream.avail_in)
  186651. {
  186652. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  186653. if (ret != Z_OK && ret != Z_STREAM_END)
  186654. {
  186655. inflateReset(&png_ptr->zstream);
  186656. png_ptr->zstream.avail_in = 0;
  186657. png_ptr->current_text = NULL;
  186658. png_free(png_ptr, key);
  186659. png_free(png_ptr, text);
  186660. return;
  186661. }
  186662. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  186663. {
  186664. if (text == NULL)
  186665. {
  186666. text = (png_charp)png_malloc(png_ptr,
  186667. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  186668. + key_size + 1));
  186669. png_memcpy(text + key_size, png_ptr->zbuf,
  186670. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  186671. png_memcpy(text, key, key_size);
  186672. text_size = key_size + png_ptr->zbuf_size -
  186673. png_ptr->zstream.avail_out;
  186674. *(text + text_size) = '\0';
  186675. }
  186676. else
  186677. {
  186678. png_charp tmp;
  186679. tmp = text;
  186680. text = (png_charp)png_malloc(png_ptr, text_size +
  186681. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  186682. + 1));
  186683. png_memcpy(text, tmp, text_size);
  186684. png_free(png_ptr, tmp);
  186685. png_memcpy(text + text_size, png_ptr->zbuf,
  186686. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  186687. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  186688. *(text + text_size) = '\0';
  186689. }
  186690. if (ret != Z_STREAM_END)
  186691. {
  186692. png_ptr->zstream.next_out = png_ptr->zbuf;
  186693. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  186694. }
  186695. }
  186696. else
  186697. {
  186698. break;
  186699. }
  186700. if (ret == Z_STREAM_END)
  186701. break;
  186702. }
  186703. inflateReset(&png_ptr->zstream);
  186704. png_ptr->zstream.avail_in = 0;
  186705. if (ret != Z_STREAM_END)
  186706. {
  186707. png_ptr->current_text = NULL;
  186708. png_free(png_ptr, key);
  186709. png_free(png_ptr, text);
  186710. return;
  186711. }
  186712. png_ptr->current_text = NULL;
  186713. png_free(png_ptr, key);
  186714. key = text;
  186715. text += key_size;
  186716. text_ptr = (png_textp)png_malloc(png_ptr,
  186717. (png_uint_32)png_sizeof(png_text));
  186718. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  186719. text_ptr->key = key;
  186720. #ifdef PNG_iTXt_SUPPORTED
  186721. text_ptr->lang = NULL;
  186722. text_ptr->lang_key = NULL;
  186723. #endif
  186724. text_ptr->text = text;
  186725. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  186726. png_free(png_ptr, key);
  186727. png_free(png_ptr, text_ptr);
  186728. if (ret)
  186729. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  186730. }
  186731. }
  186732. #endif
  186733. #if defined(PNG_READ_iTXt_SUPPORTED)
  186734. void /* PRIVATE */
  186735. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  186736. length)
  186737. {
  186738. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  186739. {
  186740. png_error(png_ptr, "Out of place iTXt");
  186741. info_ptr = info_ptr; /* to quiet some compiler warnings */
  186742. }
  186743. #ifdef PNG_MAX_MALLOC_64K
  186744. png_ptr->skip_length = 0; /* This may not be necessary */
  186745. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  186746. {
  186747. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  186748. png_ptr->skip_length = length - (png_uint_32)65535L;
  186749. length = (png_uint_32)65535L;
  186750. }
  186751. #endif
  186752. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  186753. (png_uint_32)(length+1));
  186754. png_ptr->current_text[length] = '\0';
  186755. png_ptr->current_text_ptr = png_ptr->current_text;
  186756. png_ptr->current_text_size = (png_size_t)length;
  186757. png_ptr->current_text_left = (png_size_t)length;
  186758. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  186759. }
  186760. void /* PRIVATE */
  186761. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  186762. {
  186763. if (png_ptr->buffer_size && png_ptr->current_text_left)
  186764. {
  186765. png_size_t text_size;
  186766. if (png_ptr->buffer_size < png_ptr->current_text_left)
  186767. text_size = png_ptr->buffer_size;
  186768. else
  186769. text_size = png_ptr->current_text_left;
  186770. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  186771. png_ptr->current_text_left -= text_size;
  186772. png_ptr->current_text_ptr += text_size;
  186773. }
  186774. if (!(png_ptr->current_text_left))
  186775. {
  186776. png_textp text_ptr;
  186777. png_charp key;
  186778. int comp_flag;
  186779. png_charp lang;
  186780. png_charp lang_key;
  186781. png_charp text;
  186782. int ret;
  186783. if (png_ptr->buffer_size < 4)
  186784. {
  186785. png_push_save_buffer(png_ptr);
  186786. return;
  186787. }
  186788. png_push_crc_finish(png_ptr);
  186789. #if defined(PNG_MAX_MALLOC_64K)
  186790. if (png_ptr->skip_length)
  186791. return;
  186792. #endif
  186793. key = png_ptr->current_text;
  186794. for (lang = key; *lang; lang++)
  186795. /* empty loop */ ;
  186796. if (lang < key + png_ptr->current_text_size - 3)
  186797. lang++;
  186798. comp_flag = *lang++;
  186799. lang++; /* skip comp_type, always zero */
  186800. for (lang_key = lang; *lang_key; lang_key++)
  186801. /* empty loop */ ;
  186802. lang_key++; /* skip NUL separator */
  186803. text=lang_key;
  186804. if (lang_key < key + png_ptr->current_text_size - 1)
  186805. {
  186806. for (; *text; text++)
  186807. /* empty loop */ ;
  186808. }
  186809. if (text < key + png_ptr->current_text_size)
  186810. text++;
  186811. text_ptr = (png_textp)png_malloc(png_ptr,
  186812. (png_uint_32)png_sizeof(png_text));
  186813. text_ptr->compression = comp_flag + 2;
  186814. text_ptr->key = key;
  186815. text_ptr->lang = lang;
  186816. text_ptr->lang_key = lang_key;
  186817. text_ptr->text = text;
  186818. text_ptr->text_length = 0;
  186819. text_ptr->itxt_length = png_strlen(text);
  186820. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  186821. png_ptr->current_text = NULL;
  186822. png_free(png_ptr, text_ptr);
  186823. if (ret)
  186824. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  186825. }
  186826. }
  186827. #endif
  186828. /* This function is called when we haven't found a handler for this
  186829. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  186830. * name or a critical chunk), the chunk is (currently) silently ignored.
  186831. */
  186832. void /* PRIVATE */
  186833. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  186834. length)
  186835. {
  186836. png_uint_32 skip=0;
  186837. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  186838. if (!(png_ptr->chunk_name[0] & 0x20))
  186839. {
  186840. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  186841. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  186842. PNG_HANDLE_CHUNK_ALWAYS
  186843. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  186844. && png_ptr->read_user_chunk_fn == NULL
  186845. #endif
  186846. )
  186847. #endif
  186848. png_chunk_error(png_ptr, "unknown critical chunk");
  186849. info_ptr = info_ptr; /* to quiet some compiler warnings */
  186850. }
  186851. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  186852. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  186853. {
  186854. #ifdef PNG_MAX_MALLOC_64K
  186855. if (length > (png_uint_32)65535L)
  186856. {
  186857. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  186858. skip = length - (png_uint_32)65535L;
  186859. length = (png_uint_32)65535L;
  186860. }
  186861. #endif
  186862. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  186863. (png_charp)png_ptr->chunk_name, 5);
  186864. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  186865. png_ptr->unknown_chunk.size = (png_size_t)length;
  186866. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  186867. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  186868. if(png_ptr->read_user_chunk_fn != NULL)
  186869. {
  186870. /* callback to user unknown chunk handler */
  186871. int ret;
  186872. ret = (*(png_ptr->read_user_chunk_fn))
  186873. (png_ptr, &png_ptr->unknown_chunk);
  186874. if (ret < 0)
  186875. png_chunk_error(png_ptr, "error in user chunk");
  186876. if (ret == 0)
  186877. {
  186878. if (!(png_ptr->chunk_name[0] & 0x20))
  186879. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  186880. PNG_HANDLE_CHUNK_ALWAYS)
  186881. png_chunk_error(png_ptr, "unknown critical chunk");
  186882. png_set_unknown_chunks(png_ptr, info_ptr,
  186883. &png_ptr->unknown_chunk, 1);
  186884. }
  186885. }
  186886. #else
  186887. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  186888. #endif
  186889. png_free(png_ptr, png_ptr->unknown_chunk.data);
  186890. png_ptr->unknown_chunk.data = NULL;
  186891. }
  186892. else
  186893. #endif
  186894. skip=length;
  186895. png_push_crc_skip(png_ptr, skip);
  186896. }
  186897. void /* PRIVATE */
  186898. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  186899. {
  186900. if (png_ptr->info_fn != NULL)
  186901. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  186902. }
  186903. void /* PRIVATE */
  186904. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  186905. {
  186906. if (png_ptr->end_fn != NULL)
  186907. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  186908. }
  186909. void /* PRIVATE */
  186910. png_push_have_row(png_structp png_ptr, png_bytep row)
  186911. {
  186912. if (png_ptr->row_fn != NULL)
  186913. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  186914. (int)png_ptr->pass);
  186915. }
  186916. void PNGAPI
  186917. png_progressive_combine_row (png_structp png_ptr,
  186918. png_bytep old_row, png_bytep new_row)
  186919. {
  186920. #ifdef PNG_USE_LOCAL_ARRAYS
  186921. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  186922. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  186923. #endif
  186924. if(png_ptr == NULL) return;
  186925. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  186926. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  186927. }
  186928. void PNGAPI
  186929. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  186930. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  186931. png_progressive_end_ptr end_fn)
  186932. {
  186933. if(png_ptr == NULL) return;
  186934. png_ptr->info_fn = info_fn;
  186935. png_ptr->row_fn = row_fn;
  186936. png_ptr->end_fn = end_fn;
  186937. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  186938. }
  186939. png_voidp PNGAPI
  186940. png_get_progressive_ptr(png_structp png_ptr)
  186941. {
  186942. if(png_ptr == NULL) return (NULL);
  186943. return png_ptr->io_ptr;
  186944. }
  186945. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  186946. /*** End of inlined file: pngpread.c ***/
  186947. /*** Start of inlined file: pngrio.c ***/
  186948. /* pngrio.c - functions for data input
  186949. *
  186950. * Last changed in libpng 1.2.13 November 13, 2006
  186951. * For conditions of distribution and use, see copyright notice in png.h
  186952. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  186953. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186954. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186955. *
  186956. * This file provides a location for all input. Users who need
  186957. * special handling are expected to write a function that has the same
  186958. * arguments as this and performs a similar function, but that possibly
  186959. * has a different input method. Note that you shouldn't change this
  186960. * function, but rather write a replacement function and then make
  186961. * libpng use it at run time with png_set_read_fn(...).
  186962. */
  186963. #define PNG_INTERNAL
  186964. #if defined(PNG_READ_SUPPORTED)
  186965. /* Read the data from whatever input you are using. The default routine
  186966. reads from a file pointer. Note that this routine sometimes gets called
  186967. with very small lengths, so you should implement some kind of simple
  186968. buffering if you are using unbuffered reads. This should never be asked
  186969. to read more then 64K on a 16 bit machine. */
  186970. void /* PRIVATE */
  186971. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  186972. {
  186973. png_debug1(4,"reading %d bytes\n", (int)length);
  186974. if (png_ptr->read_data_fn != NULL)
  186975. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  186976. else
  186977. png_error(png_ptr, "Call to NULL read function");
  186978. }
  186979. #if !defined(PNG_NO_STDIO)
  186980. /* This is the function that does the actual reading of data. If you are
  186981. not reading from a standard C stream, you should create a replacement
  186982. read_data function and use it at run time with png_set_read_fn(), rather
  186983. than changing the library. */
  186984. #ifndef USE_FAR_KEYWORD
  186985. void PNGAPI
  186986. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  186987. {
  186988. png_size_t check;
  186989. if(png_ptr == NULL) return;
  186990. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  186991. * instead of an int, which is what fread() actually returns.
  186992. */
  186993. #if defined(_WIN32_WCE)
  186994. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  186995. check = 0;
  186996. #else
  186997. check = (png_size_t)fread(data, (png_size_t)1, length,
  186998. (png_FILE_p)png_ptr->io_ptr);
  186999. #endif
  187000. if (check != length)
  187001. png_error(png_ptr, "Read Error");
  187002. }
  187003. #else
  187004. /* this is the model-independent version. Since the standard I/O library
  187005. can't handle far buffers in the medium and small models, we have to copy
  187006. the data.
  187007. */
  187008. #define NEAR_BUF_SIZE 1024
  187009. #define MIN(a,b) (a <= b ? a : b)
  187010. static void PNGAPI
  187011. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  187012. {
  187013. int check;
  187014. png_byte *n_data;
  187015. png_FILE_p io_ptr;
  187016. if(png_ptr == NULL) return;
  187017. /* Check if data really is near. If so, use usual code. */
  187018. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  187019. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  187020. if ((png_bytep)n_data == data)
  187021. {
  187022. #if defined(_WIN32_WCE)
  187023. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  187024. check = 0;
  187025. #else
  187026. check = fread(n_data, 1, length, io_ptr);
  187027. #endif
  187028. }
  187029. else
  187030. {
  187031. png_byte buf[NEAR_BUF_SIZE];
  187032. png_size_t read, remaining, err;
  187033. check = 0;
  187034. remaining = length;
  187035. do
  187036. {
  187037. read = MIN(NEAR_BUF_SIZE, remaining);
  187038. #if defined(_WIN32_WCE)
  187039. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  187040. err = 0;
  187041. #else
  187042. err = fread(buf, (png_size_t)1, read, io_ptr);
  187043. #endif
  187044. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  187045. if(err != read)
  187046. break;
  187047. else
  187048. check += err;
  187049. data += read;
  187050. remaining -= read;
  187051. }
  187052. while (remaining != 0);
  187053. }
  187054. if ((png_uint_32)check != (png_uint_32)length)
  187055. png_error(png_ptr, "read Error");
  187056. }
  187057. #endif
  187058. #endif
  187059. /* This function allows the application to supply a new input function
  187060. for libpng if standard C streams aren't being used.
  187061. This function takes as its arguments:
  187062. png_ptr - pointer to a png input data structure
  187063. io_ptr - pointer to user supplied structure containing info about
  187064. the input functions. May be NULL.
  187065. read_data_fn - pointer to a new input function that takes as its
  187066. arguments a pointer to a png_struct, a pointer to
  187067. a location where input data can be stored, and a 32-bit
  187068. unsigned int that is the number of bytes to be read.
  187069. To exit and output any fatal error messages the new write
  187070. function should call png_error(png_ptr, "Error msg"). */
  187071. void PNGAPI
  187072. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  187073. png_rw_ptr read_data_fn)
  187074. {
  187075. if(png_ptr == NULL) return;
  187076. png_ptr->io_ptr = io_ptr;
  187077. #if !defined(PNG_NO_STDIO)
  187078. if (read_data_fn != NULL)
  187079. png_ptr->read_data_fn = read_data_fn;
  187080. else
  187081. png_ptr->read_data_fn = png_default_read_data;
  187082. #else
  187083. png_ptr->read_data_fn = read_data_fn;
  187084. #endif
  187085. /* It is an error to write to a read device */
  187086. if (png_ptr->write_data_fn != NULL)
  187087. {
  187088. png_ptr->write_data_fn = NULL;
  187089. png_warning(png_ptr,
  187090. "It's an error to set both read_data_fn and write_data_fn in the ");
  187091. png_warning(png_ptr,
  187092. "same structure. Resetting write_data_fn to NULL.");
  187093. }
  187094. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  187095. png_ptr->output_flush_fn = NULL;
  187096. #endif
  187097. }
  187098. #endif /* PNG_READ_SUPPORTED */
  187099. /*** End of inlined file: pngrio.c ***/
  187100. /*** Start of inlined file: pngrtran.c ***/
  187101. /* pngrtran.c - transforms the data in a row for PNG readers
  187102. *
  187103. * Last changed in libpng 1.2.21 [October 4, 2007]
  187104. * For conditions of distribution and use, see copyright notice in png.h
  187105. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  187106. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  187107. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  187108. *
  187109. * This file contains functions optionally called by an application
  187110. * in order to tell libpng how to handle data when reading a PNG.
  187111. * Transformations that are used in both reading and writing are
  187112. * in pngtrans.c.
  187113. */
  187114. #define PNG_INTERNAL
  187115. #if defined(PNG_READ_SUPPORTED)
  187116. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  187117. void PNGAPI
  187118. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  187119. {
  187120. png_debug(1, "in png_set_crc_action\n");
  187121. /* Tell libpng how we react to CRC errors in critical chunks */
  187122. if(png_ptr == NULL) return;
  187123. switch (crit_action)
  187124. {
  187125. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  187126. break;
  187127. case PNG_CRC_WARN_USE: /* warn/use data */
  187128. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  187129. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  187130. break;
  187131. case PNG_CRC_QUIET_USE: /* quiet/use data */
  187132. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  187133. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  187134. PNG_FLAG_CRC_CRITICAL_IGNORE;
  187135. break;
  187136. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  187137. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  187138. case PNG_CRC_ERROR_QUIT: /* error/quit */
  187139. case PNG_CRC_DEFAULT:
  187140. default:
  187141. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  187142. break;
  187143. }
  187144. switch (ancil_action)
  187145. {
  187146. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  187147. break;
  187148. case PNG_CRC_WARN_USE: /* warn/use data */
  187149. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  187150. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  187151. break;
  187152. case PNG_CRC_QUIET_USE: /* quiet/use data */
  187153. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  187154. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  187155. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  187156. break;
  187157. case PNG_CRC_ERROR_QUIT: /* error/quit */
  187158. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  187159. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  187160. break;
  187161. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  187162. case PNG_CRC_DEFAULT:
  187163. default:
  187164. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  187165. break;
  187166. }
  187167. }
  187168. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  187169. defined(PNG_FLOATING_POINT_SUPPORTED)
  187170. /* handle alpha and tRNS via a background color */
  187171. void PNGAPI
  187172. png_set_background(png_structp png_ptr,
  187173. png_color_16p background_color, int background_gamma_code,
  187174. int need_expand, double background_gamma)
  187175. {
  187176. png_debug(1, "in png_set_background\n");
  187177. if(png_ptr == NULL) return;
  187178. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  187179. {
  187180. png_warning(png_ptr, "Application must supply a known background gamma");
  187181. return;
  187182. }
  187183. png_ptr->transformations |= PNG_BACKGROUND;
  187184. png_memcpy(&(png_ptr->background), background_color,
  187185. png_sizeof(png_color_16));
  187186. png_ptr->background_gamma = (float)background_gamma;
  187187. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  187188. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  187189. }
  187190. #endif
  187191. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  187192. /* strip 16 bit depth files to 8 bit depth */
  187193. void PNGAPI
  187194. png_set_strip_16(png_structp png_ptr)
  187195. {
  187196. png_debug(1, "in png_set_strip_16\n");
  187197. if(png_ptr == NULL) return;
  187198. png_ptr->transformations |= PNG_16_TO_8;
  187199. }
  187200. #endif
  187201. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  187202. void PNGAPI
  187203. png_set_strip_alpha(png_structp png_ptr)
  187204. {
  187205. png_debug(1, "in png_set_strip_alpha\n");
  187206. if(png_ptr == NULL) return;
  187207. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  187208. }
  187209. #endif
  187210. #if defined(PNG_READ_DITHER_SUPPORTED)
  187211. /* Dither file to 8 bit. Supply a palette, the current number
  187212. * of elements in the palette, the maximum number of elements
  187213. * allowed, and a histogram if possible. If the current number
  187214. * of colors is greater then the maximum number, the palette will be
  187215. * modified to fit in the maximum number. "full_dither" indicates
  187216. * whether we need a dithering cube set up for RGB images, or if we
  187217. * simply are reducing the number of colors in a paletted image.
  187218. */
  187219. typedef struct png_dsort_struct
  187220. {
  187221. struct png_dsort_struct FAR * next;
  187222. png_byte left;
  187223. png_byte right;
  187224. } png_dsort;
  187225. typedef png_dsort FAR * png_dsortp;
  187226. typedef png_dsort FAR * FAR * png_dsortpp;
  187227. void PNGAPI
  187228. png_set_dither(png_structp png_ptr, png_colorp palette,
  187229. int num_palette, int maximum_colors, png_uint_16p histogram,
  187230. int full_dither)
  187231. {
  187232. png_debug(1, "in png_set_dither\n");
  187233. if(png_ptr == NULL) return;
  187234. png_ptr->transformations |= PNG_DITHER;
  187235. if (!full_dither)
  187236. {
  187237. int i;
  187238. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  187239. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  187240. for (i = 0; i < num_palette; i++)
  187241. png_ptr->dither_index[i] = (png_byte)i;
  187242. }
  187243. if (num_palette > maximum_colors)
  187244. {
  187245. if (histogram != NULL)
  187246. {
  187247. /* This is easy enough, just throw out the least used colors.
  187248. Perhaps not the best solution, but good enough. */
  187249. int i;
  187250. /* initialize an array to sort colors */
  187251. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  187252. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  187253. /* initialize the dither_sort array */
  187254. for (i = 0; i < num_palette; i++)
  187255. png_ptr->dither_sort[i] = (png_byte)i;
  187256. /* Find the least used palette entries by starting a
  187257. bubble sort, and running it until we have sorted
  187258. out enough colors. Note that we don't care about
  187259. sorting all the colors, just finding which are
  187260. least used. */
  187261. for (i = num_palette - 1; i >= maximum_colors; i--)
  187262. {
  187263. int done; /* to stop early if the list is pre-sorted */
  187264. int j;
  187265. done = 1;
  187266. for (j = 0; j < i; j++)
  187267. {
  187268. if (histogram[png_ptr->dither_sort[j]]
  187269. < histogram[png_ptr->dither_sort[j + 1]])
  187270. {
  187271. png_byte t;
  187272. t = png_ptr->dither_sort[j];
  187273. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  187274. png_ptr->dither_sort[j + 1] = t;
  187275. done = 0;
  187276. }
  187277. }
  187278. if (done)
  187279. break;
  187280. }
  187281. /* swap the palette around, and set up a table, if necessary */
  187282. if (full_dither)
  187283. {
  187284. int j = num_palette;
  187285. /* put all the useful colors within the max, but don't
  187286. move the others */
  187287. for (i = 0; i < maximum_colors; i++)
  187288. {
  187289. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  187290. {
  187291. do
  187292. j--;
  187293. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  187294. palette[i] = palette[j];
  187295. }
  187296. }
  187297. }
  187298. else
  187299. {
  187300. int j = num_palette;
  187301. /* move all the used colors inside the max limit, and
  187302. develop a translation table */
  187303. for (i = 0; i < maximum_colors; i++)
  187304. {
  187305. /* only move the colors we need to */
  187306. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  187307. {
  187308. png_color tmp_color;
  187309. do
  187310. j--;
  187311. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  187312. tmp_color = palette[j];
  187313. palette[j] = palette[i];
  187314. palette[i] = tmp_color;
  187315. /* indicate where the color went */
  187316. png_ptr->dither_index[j] = (png_byte)i;
  187317. png_ptr->dither_index[i] = (png_byte)j;
  187318. }
  187319. }
  187320. /* find closest color for those colors we are not using */
  187321. for (i = 0; i < num_palette; i++)
  187322. {
  187323. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  187324. {
  187325. int min_d, k, min_k, d_index;
  187326. /* find the closest color to one we threw out */
  187327. d_index = png_ptr->dither_index[i];
  187328. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  187329. for (k = 1, min_k = 0; k < maximum_colors; k++)
  187330. {
  187331. int d;
  187332. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  187333. if (d < min_d)
  187334. {
  187335. min_d = d;
  187336. min_k = k;
  187337. }
  187338. }
  187339. /* point to closest color */
  187340. png_ptr->dither_index[i] = (png_byte)min_k;
  187341. }
  187342. }
  187343. }
  187344. png_free(png_ptr, png_ptr->dither_sort);
  187345. png_ptr->dither_sort=NULL;
  187346. }
  187347. else
  187348. {
  187349. /* This is much harder to do simply (and quickly). Perhaps
  187350. we need to go through a median cut routine, but those
  187351. don't always behave themselves with only a few colors
  187352. as input. So we will just find the closest two colors,
  187353. and throw out one of them (chosen somewhat randomly).
  187354. [We don't understand this at all, so if someone wants to
  187355. work on improving it, be our guest - AED, GRP]
  187356. */
  187357. int i;
  187358. int max_d;
  187359. int num_new_palette;
  187360. png_dsortp t;
  187361. png_dsortpp hash;
  187362. t=NULL;
  187363. /* initialize palette index arrays */
  187364. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  187365. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  187366. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  187367. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  187368. /* initialize the sort array */
  187369. for (i = 0; i < num_palette; i++)
  187370. {
  187371. png_ptr->index_to_palette[i] = (png_byte)i;
  187372. png_ptr->palette_to_index[i] = (png_byte)i;
  187373. }
  187374. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  187375. png_sizeof (png_dsortp)));
  187376. for (i = 0; i < 769; i++)
  187377. hash[i] = NULL;
  187378. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  187379. num_new_palette = num_palette;
  187380. /* initial wild guess at how far apart the farthest pixel
  187381. pair we will be eliminating will be. Larger
  187382. numbers mean more areas will be allocated, Smaller
  187383. numbers run the risk of not saving enough data, and
  187384. having to do this all over again.
  187385. I have not done extensive checking on this number.
  187386. */
  187387. max_d = 96;
  187388. while (num_new_palette > maximum_colors)
  187389. {
  187390. for (i = 0; i < num_new_palette - 1; i++)
  187391. {
  187392. int j;
  187393. for (j = i + 1; j < num_new_palette; j++)
  187394. {
  187395. int d;
  187396. d = PNG_COLOR_DIST(palette[i], palette[j]);
  187397. if (d <= max_d)
  187398. {
  187399. t = (png_dsortp)png_malloc_warn(png_ptr,
  187400. (png_uint_32)(png_sizeof(png_dsort)));
  187401. if (t == NULL)
  187402. break;
  187403. t->next = hash[d];
  187404. t->left = (png_byte)i;
  187405. t->right = (png_byte)j;
  187406. hash[d] = t;
  187407. }
  187408. }
  187409. if (t == NULL)
  187410. break;
  187411. }
  187412. if (t != NULL)
  187413. for (i = 0; i <= max_d; i++)
  187414. {
  187415. if (hash[i] != NULL)
  187416. {
  187417. png_dsortp p;
  187418. for (p = hash[i]; p; p = p->next)
  187419. {
  187420. if ((int)png_ptr->index_to_palette[p->left]
  187421. < num_new_palette &&
  187422. (int)png_ptr->index_to_palette[p->right]
  187423. < num_new_palette)
  187424. {
  187425. int j, next_j;
  187426. if (num_new_palette & 0x01)
  187427. {
  187428. j = p->left;
  187429. next_j = p->right;
  187430. }
  187431. else
  187432. {
  187433. j = p->right;
  187434. next_j = p->left;
  187435. }
  187436. num_new_palette--;
  187437. palette[png_ptr->index_to_palette[j]]
  187438. = palette[num_new_palette];
  187439. if (!full_dither)
  187440. {
  187441. int k;
  187442. for (k = 0; k < num_palette; k++)
  187443. {
  187444. if (png_ptr->dither_index[k] ==
  187445. png_ptr->index_to_palette[j])
  187446. png_ptr->dither_index[k] =
  187447. png_ptr->index_to_palette[next_j];
  187448. if ((int)png_ptr->dither_index[k] ==
  187449. num_new_palette)
  187450. png_ptr->dither_index[k] =
  187451. png_ptr->index_to_palette[j];
  187452. }
  187453. }
  187454. png_ptr->index_to_palette[png_ptr->palette_to_index
  187455. [num_new_palette]] = png_ptr->index_to_palette[j];
  187456. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  187457. = png_ptr->palette_to_index[num_new_palette];
  187458. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  187459. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  187460. }
  187461. if (num_new_palette <= maximum_colors)
  187462. break;
  187463. }
  187464. if (num_new_palette <= maximum_colors)
  187465. break;
  187466. }
  187467. }
  187468. for (i = 0; i < 769; i++)
  187469. {
  187470. if (hash[i] != NULL)
  187471. {
  187472. png_dsortp p = hash[i];
  187473. while (p)
  187474. {
  187475. t = p->next;
  187476. png_free(png_ptr, p);
  187477. p = t;
  187478. }
  187479. }
  187480. hash[i] = 0;
  187481. }
  187482. max_d += 96;
  187483. }
  187484. png_free(png_ptr, hash);
  187485. png_free(png_ptr, png_ptr->palette_to_index);
  187486. png_free(png_ptr, png_ptr->index_to_palette);
  187487. png_ptr->palette_to_index=NULL;
  187488. png_ptr->index_to_palette=NULL;
  187489. }
  187490. num_palette = maximum_colors;
  187491. }
  187492. if (png_ptr->palette == NULL)
  187493. {
  187494. png_ptr->palette = palette;
  187495. }
  187496. png_ptr->num_palette = (png_uint_16)num_palette;
  187497. if (full_dither)
  187498. {
  187499. int i;
  187500. png_bytep distance;
  187501. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  187502. PNG_DITHER_BLUE_BITS;
  187503. int num_red = (1 << PNG_DITHER_RED_BITS);
  187504. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  187505. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  187506. png_size_t num_entries = ((png_size_t)1 << total_bits);
  187507. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  187508. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  187509. png_memset(png_ptr->palette_lookup, 0, num_entries *
  187510. png_sizeof (png_byte));
  187511. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  187512. png_sizeof(png_byte)));
  187513. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  187514. for (i = 0; i < num_palette; i++)
  187515. {
  187516. int ir, ig, ib;
  187517. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  187518. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  187519. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  187520. for (ir = 0; ir < num_red; ir++)
  187521. {
  187522. /* int dr = abs(ir - r); */
  187523. int dr = ((ir > r) ? ir - r : r - ir);
  187524. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  187525. for (ig = 0; ig < num_green; ig++)
  187526. {
  187527. /* int dg = abs(ig - g); */
  187528. int dg = ((ig > g) ? ig - g : g - ig);
  187529. int dt = dr + dg;
  187530. int dm = ((dr > dg) ? dr : dg);
  187531. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  187532. for (ib = 0; ib < num_blue; ib++)
  187533. {
  187534. int d_index = index_g | ib;
  187535. /* int db = abs(ib - b); */
  187536. int db = ((ib > b) ? ib - b : b - ib);
  187537. int dmax = ((dm > db) ? dm : db);
  187538. int d = dmax + dt + db;
  187539. if (d < (int)distance[d_index])
  187540. {
  187541. distance[d_index] = (png_byte)d;
  187542. png_ptr->palette_lookup[d_index] = (png_byte)i;
  187543. }
  187544. }
  187545. }
  187546. }
  187547. }
  187548. png_free(png_ptr, distance);
  187549. }
  187550. }
  187551. #endif
  187552. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  187553. /* Transform the image from the file_gamma to the screen_gamma. We
  187554. * only do transformations on images where the file_gamma and screen_gamma
  187555. * are not close reciprocals, otherwise it slows things down slightly, and
  187556. * also needlessly introduces small errors.
  187557. *
  187558. * We will turn off gamma transformation later if no semitransparent entries
  187559. * are present in the tRNS array for palette images. We can't do it here
  187560. * because we don't necessarily have the tRNS chunk yet.
  187561. */
  187562. void PNGAPI
  187563. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  187564. {
  187565. png_debug(1, "in png_set_gamma\n");
  187566. if(png_ptr == NULL) return;
  187567. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  187568. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  187569. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  187570. png_ptr->transformations |= PNG_GAMMA;
  187571. png_ptr->gamma = (float)file_gamma;
  187572. png_ptr->screen_gamma = (float)scrn_gamma;
  187573. }
  187574. #endif
  187575. #if defined(PNG_READ_EXPAND_SUPPORTED)
  187576. /* Expand paletted images to RGB, expand grayscale images of
  187577. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  187578. * to alpha channels.
  187579. */
  187580. void PNGAPI
  187581. png_set_expand(png_structp png_ptr)
  187582. {
  187583. png_debug(1, "in png_set_expand\n");
  187584. if(png_ptr == NULL) return;
  187585. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  187586. #ifdef PNG_WARN_UNINITIALIZED_ROW
  187587. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  187588. #endif
  187589. }
  187590. /* GRR 19990627: the following three functions currently are identical
  187591. * to png_set_expand(). However, it is entirely reasonable that someone
  187592. * might wish to expand an indexed image to RGB but *not* expand a single,
  187593. * fully transparent palette entry to a full alpha channel--perhaps instead
  187594. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  187595. * the transparent color with a particular RGB value, or drop tRNS entirely.
  187596. * IOW, a future version of the library may make the transformations flag
  187597. * a bit more fine-grained, with separate bits for each of these three
  187598. * functions.
  187599. *
  187600. * More to the point, these functions make it obvious what libpng will be
  187601. * doing, whereas "expand" can (and does) mean any number of things.
  187602. *
  187603. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  187604. * to expand only the sample depth but not to expand the tRNS to alpha.
  187605. */
  187606. /* Expand paletted images to RGB. */
  187607. void PNGAPI
  187608. png_set_palette_to_rgb(png_structp png_ptr)
  187609. {
  187610. png_debug(1, "in png_set_palette_to_rgb\n");
  187611. if(png_ptr == NULL) return;
  187612. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  187613. #ifdef PNG_WARN_UNINITIALIZED_ROW
  187614. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  187615. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  187616. #endif
  187617. }
  187618. #if !defined(PNG_1_0_X)
  187619. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  187620. void PNGAPI
  187621. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  187622. {
  187623. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  187624. if(png_ptr == NULL) return;
  187625. png_ptr->transformations |= PNG_EXPAND;
  187626. #ifdef PNG_WARN_UNINITIALIZED_ROW
  187627. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  187628. #endif
  187629. }
  187630. #endif
  187631. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  187632. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  187633. /* Deprecated as of libpng-1.2.9 */
  187634. void PNGAPI
  187635. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  187636. {
  187637. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  187638. if(png_ptr == NULL) return;
  187639. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  187640. }
  187641. #endif
  187642. /* Expand tRNS chunks to alpha channels. */
  187643. void PNGAPI
  187644. png_set_tRNS_to_alpha(png_structp png_ptr)
  187645. {
  187646. png_debug(1, "in png_set_tRNS_to_alpha\n");
  187647. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  187648. #ifdef PNG_WARN_UNINITIALIZED_ROW
  187649. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  187650. #endif
  187651. }
  187652. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  187653. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  187654. void PNGAPI
  187655. png_set_gray_to_rgb(png_structp png_ptr)
  187656. {
  187657. png_debug(1, "in png_set_gray_to_rgb\n");
  187658. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  187659. #ifdef PNG_WARN_UNINITIALIZED_ROW
  187660. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  187661. #endif
  187662. }
  187663. #endif
  187664. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  187665. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  187666. /* Convert a RGB image to a grayscale of the same width. This allows us,
  187667. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  187668. */
  187669. void PNGAPI
  187670. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  187671. double green)
  187672. {
  187673. int red_fixed = (int)((float)red*100000.0 + 0.5);
  187674. int green_fixed = (int)((float)green*100000.0 + 0.5);
  187675. if(png_ptr == NULL) return;
  187676. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  187677. }
  187678. #endif
  187679. void PNGAPI
  187680. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  187681. png_fixed_point red, png_fixed_point green)
  187682. {
  187683. png_debug(1, "in png_set_rgb_to_gray\n");
  187684. if(png_ptr == NULL) return;
  187685. switch(error_action)
  187686. {
  187687. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  187688. break;
  187689. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  187690. break;
  187691. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  187692. }
  187693. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  187694. #if defined(PNG_READ_EXPAND_SUPPORTED)
  187695. png_ptr->transformations |= PNG_EXPAND;
  187696. #else
  187697. {
  187698. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  187699. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  187700. }
  187701. #endif
  187702. {
  187703. png_uint_16 red_int, green_int;
  187704. if(red < 0 || green < 0)
  187705. {
  187706. red_int = 6968; /* .212671 * 32768 + .5 */
  187707. green_int = 23434; /* .715160 * 32768 + .5 */
  187708. }
  187709. else if(red + green < 100000L)
  187710. {
  187711. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  187712. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  187713. }
  187714. else
  187715. {
  187716. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  187717. red_int = 6968;
  187718. green_int = 23434;
  187719. }
  187720. png_ptr->rgb_to_gray_red_coeff = red_int;
  187721. png_ptr->rgb_to_gray_green_coeff = green_int;
  187722. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  187723. }
  187724. }
  187725. #endif
  187726. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  187727. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  187728. defined(PNG_LEGACY_SUPPORTED)
  187729. void PNGAPI
  187730. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  187731. read_user_transform_fn)
  187732. {
  187733. png_debug(1, "in png_set_read_user_transform_fn\n");
  187734. if(png_ptr == NULL) return;
  187735. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  187736. png_ptr->transformations |= PNG_USER_TRANSFORM;
  187737. png_ptr->read_user_transform_fn = read_user_transform_fn;
  187738. #endif
  187739. #ifdef PNG_LEGACY_SUPPORTED
  187740. if(read_user_transform_fn)
  187741. png_warning(png_ptr,
  187742. "This version of libpng does not support user transforms");
  187743. #endif
  187744. }
  187745. #endif
  187746. /* Initialize everything needed for the read. This includes modifying
  187747. * the palette.
  187748. */
  187749. void /* PRIVATE */
  187750. png_init_read_transformations(png_structp png_ptr)
  187751. {
  187752. png_debug(1, "in png_init_read_transformations\n");
  187753. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187754. if(png_ptr != NULL)
  187755. #endif
  187756. {
  187757. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  187758. || defined(PNG_READ_GAMMA_SUPPORTED)
  187759. int color_type = png_ptr->color_type;
  187760. #endif
  187761. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  187762. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  187763. /* Detect gray background and attempt to enable optimization
  187764. * for gray --> RGB case */
  187765. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  187766. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  187767. * background color might actually be gray yet not be flagged as such.
  187768. * This is not a problem for the current code, which uses
  187769. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  187770. * png_do_gray_to_rgb() transformation.
  187771. */
  187772. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  187773. !(color_type & PNG_COLOR_MASK_COLOR))
  187774. {
  187775. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  187776. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  187777. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  187778. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  187779. png_ptr->background.red == png_ptr->background.green &&
  187780. png_ptr->background.red == png_ptr->background.blue)
  187781. {
  187782. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  187783. png_ptr->background.gray = png_ptr->background.red;
  187784. }
  187785. #endif
  187786. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  187787. (png_ptr->transformations & PNG_EXPAND))
  187788. {
  187789. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  187790. {
  187791. /* expand background and tRNS chunks */
  187792. switch (png_ptr->bit_depth)
  187793. {
  187794. case 1:
  187795. png_ptr->background.gray *= (png_uint_16)0xff;
  187796. png_ptr->background.red = png_ptr->background.green
  187797. = png_ptr->background.blue = png_ptr->background.gray;
  187798. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  187799. {
  187800. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  187801. png_ptr->trans_values.red = png_ptr->trans_values.green
  187802. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  187803. }
  187804. break;
  187805. case 2:
  187806. png_ptr->background.gray *= (png_uint_16)0x55;
  187807. png_ptr->background.red = png_ptr->background.green
  187808. = png_ptr->background.blue = png_ptr->background.gray;
  187809. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  187810. {
  187811. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  187812. png_ptr->trans_values.red = png_ptr->trans_values.green
  187813. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  187814. }
  187815. break;
  187816. case 4:
  187817. png_ptr->background.gray *= (png_uint_16)0x11;
  187818. png_ptr->background.red = png_ptr->background.green
  187819. = png_ptr->background.blue = png_ptr->background.gray;
  187820. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  187821. {
  187822. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  187823. png_ptr->trans_values.red = png_ptr->trans_values.green
  187824. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  187825. }
  187826. break;
  187827. case 8:
  187828. case 16:
  187829. png_ptr->background.red = png_ptr->background.green
  187830. = png_ptr->background.blue = png_ptr->background.gray;
  187831. break;
  187832. }
  187833. }
  187834. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  187835. {
  187836. png_ptr->background.red =
  187837. png_ptr->palette[png_ptr->background.index].red;
  187838. png_ptr->background.green =
  187839. png_ptr->palette[png_ptr->background.index].green;
  187840. png_ptr->background.blue =
  187841. png_ptr->palette[png_ptr->background.index].blue;
  187842. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  187843. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  187844. {
  187845. #if defined(PNG_READ_EXPAND_SUPPORTED)
  187846. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  187847. #endif
  187848. {
  187849. /* invert the alpha channel (in tRNS) unless the pixels are
  187850. going to be expanded, in which case leave it for later */
  187851. int i,istop;
  187852. istop=(int)png_ptr->num_trans;
  187853. for (i=0; i<istop; i++)
  187854. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  187855. }
  187856. }
  187857. #endif
  187858. }
  187859. }
  187860. #endif
  187861. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  187862. png_ptr->background_1 = png_ptr->background;
  187863. #endif
  187864. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  187865. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  187866. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  187867. < PNG_GAMMA_THRESHOLD))
  187868. {
  187869. int i,k;
  187870. k=0;
  187871. for (i=0; i<png_ptr->num_trans; i++)
  187872. {
  187873. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  187874. k=1; /* partial transparency is present */
  187875. }
  187876. if (k == 0)
  187877. png_ptr->transformations &= (~PNG_GAMMA);
  187878. }
  187879. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  187880. png_ptr->gamma != 0.0)
  187881. {
  187882. png_build_gamma_table(png_ptr);
  187883. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187884. if (png_ptr->transformations & PNG_BACKGROUND)
  187885. {
  187886. if (color_type == PNG_COLOR_TYPE_PALETTE)
  187887. {
  187888. /* could skip if no transparency and
  187889. */
  187890. png_color back, back_1;
  187891. png_colorp palette = png_ptr->palette;
  187892. int num_palette = png_ptr->num_palette;
  187893. int i;
  187894. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  187895. {
  187896. back.red = png_ptr->gamma_table[png_ptr->background.red];
  187897. back.green = png_ptr->gamma_table[png_ptr->background.green];
  187898. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  187899. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  187900. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  187901. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  187902. }
  187903. else
  187904. {
  187905. double g, gs;
  187906. switch (png_ptr->background_gamma_type)
  187907. {
  187908. case PNG_BACKGROUND_GAMMA_SCREEN:
  187909. g = (png_ptr->screen_gamma);
  187910. gs = 1.0;
  187911. break;
  187912. case PNG_BACKGROUND_GAMMA_FILE:
  187913. g = 1.0 / (png_ptr->gamma);
  187914. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  187915. break;
  187916. case PNG_BACKGROUND_GAMMA_UNIQUE:
  187917. g = 1.0 / (png_ptr->background_gamma);
  187918. gs = 1.0 / (png_ptr->background_gamma *
  187919. png_ptr->screen_gamma);
  187920. break;
  187921. default:
  187922. g = 1.0; /* back_1 */
  187923. gs = 1.0; /* back */
  187924. }
  187925. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  187926. {
  187927. back.red = (png_byte)png_ptr->background.red;
  187928. back.green = (png_byte)png_ptr->background.green;
  187929. back.blue = (png_byte)png_ptr->background.blue;
  187930. }
  187931. else
  187932. {
  187933. back.red = (png_byte)(pow(
  187934. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  187935. back.green = (png_byte)(pow(
  187936. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  187937. back.blue = (png_byte)(pow(
  187938. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  187939. }
  187940. back_1.red = (png_byte)(pow(
  187941. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  187942. back_1.green = (png_byte)(pow(
  187943. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  187944. back_1.blue = (png_byte)(pow(
  187945. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  187946. }
  187947. for (i = 0; i < num_palette; i++)
  187948. {
  187949. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  187950. {
  187951. if (png_ptr->trans[i] == 0)
  187952. {
  187953. palette[i] = back;
  187954. }
  187955. else /* if (png_ptr->trans[i] != 0xff) */
  187956. {
  187957. png_byte v, w;
  187958. v = png_ptr->gamma_to_1[palette[i].red];
  187959. png_composite(w, v, png_ptr->trans[i], back_1.red);
  187960. palette[i].red = png_ptr->gamma_from_1[w];
  187961. v = png_ptr->gamma_to_1[palette[i].green];
  187962. png_composite(w, v, png_ptr->trans[i], back_1.green);
  187963. palette[i].green = png_ptr->gamma_from_1[w];
  187964. v = png_ptr->gamma_to_1[palette[i].blue];
  187965. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  187966. palette[i].blue = png_ptr->gamma_from_1[w];
  187967. }
  187968. }
  187969. else
  187970. {
  187971. palette[i].red = png_ptr->gamma_table[palette[i].red];
  187972. palette[i].green = png_ptr->gamma_table[palette[i].green];
  187973. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  187974. }
  187975. }
  187976. }
  187977. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  187978. else
  187979. /* color_type != PNG_COLOR_TYPE_PALETTE */
  187980. {
  187981. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  187982. double g = 1.0;
  187983. double gs = 1.0;
  187984. switch (png_ptr->background_gamma_type)
  187985. {
  187986. case PNG_BACKGROUND_GAMMA_SCREEN:
  187987. g = (png_ptr->screen_gamma);
  187988. gs = 1.0;
  187989. break;
  187990. case PNG_BACKGROUND_GAMMA_FILE:
  187991. g = 1.0 / (png_ptr->gamma);
  187992. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  187993. break;
  187994. case PNG_BACKGROUND_GAMMA_UNIQUE:
  187995. g = 1.0 / (png_ptr->background_gamma);
  187996. gs = 1.0 / (png_ptr->background_gamma *
  187997. png_ptr->screen_gamma);
  187998. break;
  187999. }
  188000. png_ptr->background_1.gray = (png_uint_16)(pow(
  188001. (double)png_ptr->background.gray / m, g) * m + .5);
  188002. png_ptr->background.gray = (png_uint_16)(pow(
  188003. (double)png_ptr->background.gray / m, gs) * m + .5);
  188004. if ((png_ptr->background.red != png_ptr->background.green) ||
  188005. (png_ptr->background.red != png_ptr->background.blue) ||
  188006. (png_ptr->background.red != png_ptr->background.gray))
  188007. {
  188008. /* RGB or RGBA with color background */
  188009. png_ptr->background_1.red = (png_uint_16)(pow(
  188010. (double)png_ptr->background.red / m, g) * m + .5);
  188011. png_ptr->background_1.green = (png_uint_16)(pow(
  188012. (double)png_ptr->background.green / m, g) * m + .5);
  188013. png_ptr->background_1.blue = (png_uint_16)(pow(
  188014. (double)png_ptr->background.blue / m, g) * m + .5);
  188015. png_ptr->background.red = (png_uint_16)(pow(
  188016. (double)png_ptr->background.red / m, gs) * m + .5);
  188017. png_ptr->background.green = (png_uint_16)(pow(
  188018. (double)png_ptr->background.green / m, gs) * m + .5);
  188019. png_ptr->background.blue = (png_uint_16)(pow(
  188020. (double)png_ptr->background.blue / m, gs) * m + .5);
  188021. }
  188022. else
  188023. {
  188024. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  188025. png_ptr->background_1.red = png_ptr->background_1.green
  188026. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  188027. png_ptr->background.red = png_ptr->background.green
  188028. = png_ptr->background.blue = png_ptr->background.gray;
  188029. }
  188030. }
  188031. }
  188032. else
  188033. /* transformation does not include PNG_BACKGROUND */
  188034. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  188035. if (color_type == PNG_COLOR_TYPE_PALETTE)
  188036. {
  188037. png_colorp palette = png_ptr->palette;
  188038. int num_palette = png_ptr->num_palette;
  188039. int i;
  188040. for (i = 0; i < num_palette; i++)
  188041. {
  188042. palette[i].red = png_ptr->gamma_table[palette[i].red];
  188043. palette[i].green = png_ptr->gamma_table[palette[i].green];
  188044. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  188045. }
  188046. }
  188047. }
  188048. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188049. else
  188050. #endif
  188051. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  188052. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188053. /* No GAMMA transformation */
  188054. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  188055. (color_type == PNG_COLOR_TYPE_PALETTE))
  188056. {
  188057. int i;
  188058. int istop = (int)png_ptr->num_trans;
  188059. png_color back;
  188060. png_colorp palette = png_ptr->palette;
  188061. back.red = (png_byte)png_ptr->background.red;
  188062. back.green = (png_byte)png_ptr->background.green;
  188063. back.blue = (png_byte)png_ptr->background.blue;
  188064. for (i = 0; i < istop; i++)
  188065. {
  188066. if (png_ptr->trans[i] == 0)
  188067. {
  188068. palette[i] = back;
  188069. }
  188070. else if (png_ptr->trans[i] != 0xff)
  188071. {
  188072. /* The png_composite() macro is defined in png.h */
  188073. png_composite(palette[i].red, palette[i].red,
  188074. png_ptr->trans[i], back.red);
  188075. png_composite(palette[i].green, palette[i].green,
  188076. png_ptr->trans[i], back.green);
  188077. png_composite(palette[i].blue, palette[i].blue,
  188078. png_ptr->trans[i], back.blue);
  188079. }
  188080. }
  188081. }
  188082. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  188083. #if defined(PNG_READ_SHIFT_SUPPORTED)
  188084. if ((png_ptr->transformations & PNG_SHIFT) &&
  188085. (color_type == PNG_COLOR_TYPE_PALETTE))
  188086. {
  188087. png_uint_16 i;
  188088. png_uint_16 istop = png_ptr->num_palette;
  188089. int sr = 8 - png_ptr->sig_bit.red;
  188090. int sg = 8 - png_ptr->sig_bit.green;
  188091. int sb = 8 - png_ptr->sig_bit.blue;
  188092. if (sr < 0 || sr > 8)
  188093. sr = 0;
  188094. if (sg < 0 || sg > 8)
  188095. sg = 0;
  188096. if (sb < 0 || sb > 8)
  188097. sb = 0;
  188098. for (i = 0; i < istop; i++)
  188099. {
  188100. png_ptr->palette[i].red >>= sr;
  188101. png_ptr->palette[i].green >>= sg;
  188102. png_ptr->palette[i].blue >>= sb;
  188103. }
  188104. }
  188105. #endif /* PNG_READ_SHIFT_SUPPORTED */
  188106. }
  188107. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  188108. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  188109. if(png_ptr)
  188110. return;
  188111. #endif
  188112. }
  188113. /* Modify the info structure to reflect the transformations. The
  188114. * info should be updated so a PNG file could be written with it,
  188115. * assuming the transformations result in valid PNG data.
  188116. */
  188117. void /* PRIVATE */
  188118. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  188119. {
  188120. png_debug(1, "in png_read_transform_info\n");
  188121. #if defined(PNG_READ_EXPAND_SUPPORTED)
  188122. if (png_ptr->transformations & PNG_EXPAND)
  188123. {
  188124. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  188125. {
  188126. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  188127. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  188128. else
  188129. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  188130. info_ptr->bit_depth = 8;
  188131. info_ptr->num_trans = 0;
  188132. }
  188133. else
  188134. {
  188135. if (png_ptr->num_trans)
  188136. {
  188137. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  188138. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  188139. else
  188140. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  188141. }
  188142. if (info_ptr->bit_depth < 8)
  188143. info_ptr->bit_depth = 8;
  188144. info_ptr->num_trans = 0;
  188145. }
  188146. }
  188147. #endif
  188148. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188149. if (png_ptr->transformations & PNG_BACKGROUND)
  188150. {
  188151. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  188152. info_ptr->num_trans = 0;
  188153. info_ptr->background = png_ptr->background;
  188154. }
  188155. #endif
  188156. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188157. if (png_ptr->transformations & PNG_GAMMA)
  188158. {
  188159. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188160. info_ptr->gamma = png_ptr->gamma;
  188161. #endif
  188162. #ifdef PNG_FIXED_POINT_SUPPORTED
  188163. info_ptr->int_gamma = png_ptr->int_gamma;
  188164. #endif
  188165. }
  188166. #endif
  188167. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  188168. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  188169. info_ptr->bit_depth = 8;
  188170. #endif
  188171. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  188172. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  188173. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  188174. #endif
  188175. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  188176. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  188177. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  188178. #endif
  188179. #if defined(PNG_READ_DITHER_SUPPORTED)
  188180. if (png_ptr->transformations & PNG_DITHER)
  188181. {
  188182. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  188183. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  188184. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  188185. {
  188186. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  188187. }
  188188. }
  188189. #endif
  188190. #if defined(PNG_READ_PACK_SUPPORTED)
  188191. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  188192. info_ptr->bit_depth = 8;
  188193. #endif
  188194. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  188195. info_ptr->channels = 1;
  188196. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  188197. info_ptr->channels = 3;
  188198. else
  188199. info_ptr->channels = 1;
  188200. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  188201. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  188202. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  188203. #endif
  188204. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  188205. info_ptr->channels++;
  188206. #if defined(PNG_READ_FILLER_SUPPORTED)
  188207. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  188208. if ((png_ptr->transformations & PNG_FILLER) &&
  188209. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  188210. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  188211. {
  188212. info_ptr->channels++;
  188213. /* if adding a true alpha channel not just filler */
  188214. #if !defined(PNG_1_0_X)
  188215. if (png_ptr->transformations & PNG_ADD_ALPHA)
  188216. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  188217. #endif
  188218. }
  188219. #endif
  188220. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  188221. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  188222. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  188223. {
  188224. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  188225. info_ptr->bit_depth = png_ptr->user_transform_depth;
  188226. if(info_ptr->channels < png_ptr->user_transform_channels)
  188227. info_ptr->channels = png_ptr->user_transform_channels;
  188228. }
  188229. #endif
  188230. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  188231. info_ptr->bit_depth);
  188232. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  188233. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  188234. if(png_ptr)
  188235. return;
  188236. #endif
  188237. }
  188238. /* Transform the row. The order of transformations is significant,
  188239. * and is very touchy. If you add a transformation, take care to
  188240. * decide how it fits in with the other transformations here.
  188241. */
  188242. void /* PRIVATE */
  188243. png_do_read_transformations(png_structp png_ptr)
  188244. {
  188245. png_debug(1, "in png_do_read_transformations\n");
  188246. if (png_ptr->row_buf == NULL)
  188247. {
  188248. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  188249. char msg[50];
  188250. png_snprintf2(msg, 50,
  188251. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  188252. png_ptr->pass);
  188253. png_error(png_ptr, msg);
  188254. #else
  188255. png_error(png_ptr, "NULL row buffer");
  188256. #endif
  188257. }
  188258. #ifdef PNG_WARN_UNINITIALIZED_ROW
  188259. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  188260. /* Application has failed to call either png_read_start_image()
  188261. * or png_read_update_info() after setting transforms that expand
  188262. * pixels. This check added to libpng-1.2.19 */
  188263. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  188264. png_error(png_ptr, "Uninitialized row");
  188265. #else
  188266. png_warning(png_ptr, "Uninitialized row");
  188267. #endif
  188268. #endif
  188269. #if defined(PNG_READ_EXPAND_SUPPORTED)
  188270. if (png_ptr->transformations & PNG_EXPAND)
  188271. {
  188272. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  188273. {
  188274. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  188275. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  188276. }
  188277. else
  188278. {
  188279. if (png_ptr->num_trans &&
  188280. (png_ptr->transformations & PNG_EXPAND_tRNS))
  188281. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  188282. &(png_ptr->trans_values));
  188283. else
  188284. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  188285. NULL);
  188286. }
  188287. }
  188288. #endif
  188289. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  188290. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  188291. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  188292. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  188293. #endif
  188294. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  188295. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  188296. {
  188297. int rgb_error =
  188298. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  188299. if(rgb_error)
  188300. {
  188301. png_ptr->rgb_to_gray_status=1;
  188302. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  188303. PNG_RGB_TO_GRAY_WARN)
  188304. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  188305. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  188306. PNG_RGB_TO_GRAY_ERR)
  188307. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  188308. }
  188309. }
  188310. #endif
  188311. /*
  188312. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  188313. In most cases, the "simple transparency" should be done prior to doing
  188314. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  188315. pixel is transparent. You would also need to make sure that the
  188316. transparency information is upgraded to RGB.
  188317. To summarize, the current flow is:
  188318. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  188319. with background "in place" if transparent,
  188320. convert to RGB if necessary
  188321. - Gray + alpha -> composite with gray background and remove alpha bytes,
  188322. convert to RGB if necessary
  188323. To support RGB backgrounds for gray images we need:
  188324. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  188325. 3 or 6 bytes and composite with background
  188326. "in place" if transparent (3x compare/pixel
  188327. compared to doing composite with gray bkgrnd)
  188328. - Gray + alpha -> convert to RGB + alpha, composite with background and
  188329. remove alpha bytes (3x float operations/pixel
  188330. compared with composite on gray background)
  188331. Greg's change will do this. The reason it wasn't done before is for
  188332. performance, as this increases the per-pixel operations. If we would check
  188333. in advance if the background was gray or RGB, and position the gray-to-RGB
  188334. transform appropriately, then it would save a lot of work/time.
  188335. */
  188336. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  188337. /* if gray -> RGB, do so now only if background is non-gray; else do later
  188338. * for performance reasons */
  188339. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  188340. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  188341. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  188342. #endif
  188343. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188344. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  188345. ((png_ptr->num_trans != 0 ) ||
  188346. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  188347. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  188348. &(png_ptr->trans_values), &(png_ptr->background)
  188349. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188350. , &(png_ptr->background_1),
  188351. png_ptr->gamma_table, png_ptr->gamma_from_1,
  188352. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  188353. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  188354. png_ptr->gamma_shift
  188355. #endif
  188356. );
  188357. #endif
  188358. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188359. if ((png_ptr->transformations & PNG_GAMMA) &&
  188360. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188361. !((png_ptr->transformations & PNG_BACKGROUND) &&
  188362. ((png_ptr->num_trans != 0) ||
  188363. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  188364. #endif
  188365. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  188366. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  188367. png_ptr->gamma_table, png_ptr->gamma_16_table,
  188368. png_ptr->gamma_shift);
  188369. #endif
  188370. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  188371. if (png_ptr->transformations & PNG_16_TO_8)
  188372. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  188373. #endif
  188374. #if defined(PNG_READ_DITHER_SUPPORTED)
  188375. if (png_ptr->transformations & PNG_DITHER)
  188376. {
  188377. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  188378. png_ptr->palette_lookup, png_ptr->dither_index);
  188379. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  188380. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  188381. }
  188382. #endif
  188383. #if defined(PNG_READ_INVERT_SUPPORTED)
  188384. if (png_ptr->transformations & PNG_INVERT_MONO)
  188385. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  188386. #endif
  188387. #if defined(PNG_READ_SHIFT_SUPPORTED)
  188388. if (png_ptr->transformations & PNG_SHIFT)
  188389. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  188390. &(png_ptr->shift));
  188391. #endif
  188392. #if defined(PNG_READ_PACK_SUPPORTED)
  188393. if (png_ptr->transformations & PNG_PACK)
  188394. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  188395. #endif
  188396. #if defined(PNG_READ_BGR_SUPPORTED)
  188397. if (png_ptr->transformations & PNG_BGR)
  188398. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  188399. #endif
  188400. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  188401. if (png_ptr->transformations & PNG_PACKSWAP)
  188402. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  188403. #endif
  188404. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  188405. /* if gray -> RGB, do so now only if we did not do so above */
  188406. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  188407. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  188408. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  188409. #endif
  188410. #if defined(PNG_READ_FILLER_SUPPORTED)
  188411. if (png_ptr->transformations & PNG_FILLER)
  188412. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  188413. (png_uint_32)png_ptr->filler, png_ptr->flags);
  188414. #endif
  188415. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  188416. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  188417. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  188418. #endif
  188419. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  188420. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  188421. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  188422. #endif
  188423. #if defined(PNG_READ_SWAP_SUPPORTED)
  188424. if (png_ptr->transformations & PNG_SWAP_BYTES)
  188425. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  188426. #endif
  188427. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  188428. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  188429. {
  188430. if(png_ptr->read_user_transform_fn != NULL)
  188431. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  188432. (png_ptr, /* png_ptr */
  188433. &(png_ptr->row_info), /* row_info: */
  188434. /* png_uint_32 width; width of row */
  188435. /* png_uint_32 rowbytes; number of bytes in row */
  188436. /* png_byte color_type; color type of pixels */
  188437. /* png_byte bit_depth; bit depth of samples */
  188438. /* png_byte channels; number of channels (1-4) */
  188439. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  188440. png_ptr->row_buf + 1); /* start of pixel data for row */
  188441. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  188442. if(png_ptr->user_transform_depth)
  188443. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  188444. if(png_ptr->user_transform_channels)
  188445. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  188446. #endif
  188447. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  188448. png_ptr->row_info.channels);
  188449. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  188450. png_ptr->row_info.width);
  188451. }
  188452. #endif
  188453. }
  188454. #if defined(PNG_READ_PACK_SUPPORTED)
  188455. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  188456. * without changing the actual values. Thus, if you had a row with
  188457. * a bit depth of 1, you would end up with bytes that only contained
  188458. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  188459. * png_do_shift() after this.
  188460. */
  188461. void /* PRIVATE */
  188462. png_do_unpack(png_row_infop row_info, png_bytep row)
  188463. {
  188464. png_debug(1, "in png_do_unpack\n");
  188465. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188466. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  188467. #else
  188468. if (row_info->bit_depth < 8)
  188469. #endif
  188470. {
  188471. png_uint_32 i;
  188472. png_uint_32 row_width=row_info->width;
  188473. switch (row_info->bit_depth)
  188474. {
  188475. case 1:
  188476. {
  188477. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  188478. png_bytep dp = row + (png_size_t)row_width - 1;
  188479. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  188480. for (i = 0; i < row_width; i++)
  188481. {
  188482. *dp = (png_byte)((*sp >> shift) & 0x01);
  188483. if (shift == 7)
  188484. {
  188485. shift = 0;
  188486. sp--;
  188487. }
  188488. else
  188489. shift++;
  188490. dp--;
  188491. }
  188492. break;
  188493. }
  188494. case 2:
  188495. {
  188496. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  188497. png_bytep dp = row + (png_size_t)row_width - 1;
  188498. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  188499. for (i = 0; i < row_width; i++)
  188500. {
  188501. *dp = (png_byte)((*sp >> shift) & 0x03);
  188502. if (shift == 6)
  188503. {
  188504. shift = 0;
  188505. sp--;
  188506. }
  188507. else
  188508. shift += 2;
  188509. dp--;
  188510. }
  188511. break;
  188512. }
  188513. case 4:
  188514. {
  188515. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  188516. png_bytep dp = row + (png_size_t)row_width - 1;
  188517. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  188518. for (i = 0; i < row_width; i++)
  188519. {
  188520. *dp = (png_byte)((*sp >> shift) & 0x0f);
  188521. if (shift == 4)
  188522. {
  188523. shift = 0;
  188524. sp--;
  188525. }
  188526. else
  188527. shift = 4;
  188528. dp--;
  188529. }
  188530. break;
  188531. }
  188532. }
  188533. row_info->bit_depth = 8;
  188534. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  188535. row_info->rowbytes = row_width * row_info->channels;
  188536. }
  188537. }
  188538. #endif
  188539. #if defined(PNG_READ_SHIFT_SUPPORTED)
  188540. /* Reverse the effects of png_do_shift. This routine merely shifts the
  188541. * pixels back to their significant bits values. Thus, if you have
  188542. * a row of bit depth 8, but only 5 are significant, this will shift
  188543. * the values back to 0 through 31.
  188544. */
  188545. void /* PRIVATE */
  188546. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  188547. {
  188548. png_debug(1, "in png_do_unshift\n");
  188549. if (
  188550. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188551. row != NULL && row_info != NULL && sig_bits != NULL &&
  188552. #endif
  188553. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  188554. {
  188555. int shift[4];
  188556. int channels = 0;
  188557. int c;
  188558. png_uint_16 value = 0;
  188559. png_uint_32 row_width = row_info->width;
  188560. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  188561. {
  188562. shift[channels++] = row_info->bit_depth - sig_bits->red;
  188563. shift[channels++] = row_info->bit_depth - sig_bits->green;
  188564. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  188565. }
  188566. else
  188567. {
  188568. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  188569. }
  188570. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  188571. {
  188572. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  188573. }
  188574. for (c = 0; c < channels; c++)
  188575. {
  188576. if (shift[c] <= 0)
  188577. shift[c] = 0;
  188578. else
  188579. value = 1;
  188580. }
  188581. if (!value)
  188582. return;
  188583. switch (row_info->bit_depth)
  188584. {
  188585. case 2:
  188586. {
  188587. png_bytep bp;
  188588. png_uint_32 i;
  188589. png_uint_32 istop = row_info->rowbytes;
  188590. for (bp = row, i = 0; i < istop; i++)
  188591. {
  188592. *bp >>= 1;
  188593. *bp++ &= 0x55;
  188594. }
  188595. break;
  188596. }
  188597. case 4:
  188598. {
  188599. png_bytep bp = row;
  188600. png_uint_32 i;
  188601. png_uint_32 istop = row_info->rowbytes;
  188602. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  188603. (png_byte)((int)0xf >> shift[0]));
  188604. for (i = 0; i < istop; i++)
  188605. {
  188606. *bp >>= shift[0];
  188607. *bp++ &= mask;
  188608. }
  188609. break;
  188610. }
  188611. case 8:
  188612. {
  188613. png_bytep bp = row;
  188614. png_uint_32 i;
  188615. png_uint_32 istop = row_width * channels;
  188616. for (i = 0; i < istop; i++)
  188617. {
  188618. *bp++ >>= shift[i%channels];
  188619. }
  188620. break;
  188621. }
  188622. case 16:
  188623. {
  188624. png_bytep bp = row;
  188625. png_uint_32 i;
  188626. png_uint_32 istop = channels * row_width;
  188627. for (i = 0; i < istop; i++)
  188628. {
  188629. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  188630. value >>= shift[i%channels];
  188631. *bp++ = (png_byte)(value >> 8);
  188632. *bp++ = (png_byte)(value & 0xff);
  188633. }
  188634. break;
  188635. }
  188636. }
  188637. }
  188638. }
  188639. #endif
  188640. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  188641. /* chop rows of bit depth 16 down to 8 */
  188642. void /* PRIVATE */
  188643. png_do_chop(png_row_infop row_info, png_bytep row)
  188644. {
  188645. png_debug(1, "in png_do_chop\n");
  188646. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188647. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  188648. #else
  188649. if (row_info->bit_depth == 16)
  188650. #endif
  188651. {
  188652. png_bytep sp = row;
  188653. png_bytep dp = row;
  188654. png_uint_32 i;
  188655. png_uint_32 istop = row_info->width * row_info->channels;
  188656. for (i = 0; i<istop; i++, sp += 2, dp++)
  188657. {
  188658. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  188659. /* This does a more accurate scaling of the 16-bit color
  188660. * value, rather than a simple low-byte truncation.
  188661. *
  188662. * What the ideal calculation should be:
  188663. * *dp = (((((png_uint_32)(*sp) << 8) |
  188664. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  188665. *
  188666. * GRR: no, I think this is what it really should be:
  188667. * *dp = (((((png_uint_32)(*sp) << 8) |
  188668. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  188669. *
  188670. * GRR: here's the exact calculation with shifts:
  188671. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  188672. * *dp = (temp - (temp >> 8)) >> 8;
  188673. *
  188674. * Approximate calculation with shift/add instead of multiply/divide:
  188675. * *dp = ((((png_uint_32)(*sp) << 8) |
  188676. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  188677. *
  188678. * What we actually do to avoid extra shifting and conversion:
  188679. */
  188680. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  188681. #else
  188682. /* Simply discard the low order byte */
  188683. *dp = *sp;
  188684. #endif
  188685. }
  188686. row_info->bit_depth = 8;
  188687. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  188688. row_info->rowbytes = row_info->width * row_info->channels;
  188689. }
  188690. }
  188691. #endif
  188692. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  188693. void /* PRIVATE */
  188694. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  188695. {
  188696. png_debug(1, "in png_do_read_swap_alpha\n");
  188697. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188698. if (row != NULL && row_info != NULL)
  188699. #endif
  188700. {
  188701. png_uint_32 row_width = row_info->width;
  188702. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  188703. {
  188704. /* This converts from RGBA to ARGB */
  188705. if (row_info->bit_depth == 8)
  188706. {
  188707. png_bytep sp = row + row_info->rowbytes;
  188708. png_bytep dp = sp;
  188709. png_byte save;
  188710. png_uint_32 i;
  188711. for (i = 0; i < row_width; i++)
  188712. {
  188713. save = *(--sp);
  188714. *(--dp) = *(--sp);
  188715. *(--dp) = *(--sp);
  188716. *(--dp) = *(--sp);
  188717. *(--dp) = save;
  188718. }
  188719. }
  188720. /* This converts from RRGGBBAA to AARRGGBB */
  188721. else
  188722. {
  188723. png_bytep sp = row + row_info->rowbytes;
  188724. png_bytep dp = sp;
  188725. png_byte save[2];
  188726. png_uint_32 i;
  188727. for (i = 0; i < row_width; i++)
  188728. {
  188729. save[0] = *(--sp);
  188730. save[1] = *(--sp);
  188731. *(--dp) = *(--sp);
  188732. *(--dp) = *(--sp);
  188733. *(--dp) = *(--sp);
  188734. *(--dp) = *(--sp);
  188735. *(--dp) = *(--sp);
  188736. *(--dp) = *(--sp);
  188737. *(--dp) = save[0];
  188738. *(--dp) = save[1];
  188739. }
  188740. }
  188741. }
  188742. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  188743. {
  188744. /* This converts from GA to AG */
  188745. if (row_info->bit_depth == 8)
  188746. {
  188747. png_bytep sp = row + row_info->rowbytes;
  188748. png_bytep dp = sp;
  188749. png_byte save;
  188750. png_uint_32 i;
  188751. for (i = 0; i < row_width; i++)
  188752. {
  188753. save = *(--sp);
  188754. *(--dp) = *(--sp);
  188755. *(--dp) = save;
  188756. }
  188757. }
  188758. /* This converts from GGAA to AAGG */
  188759. else
  188760. {
  188761. png_bytep sp = row + row_info->rowbytes;
  188762. png_bytep dp = sp;
  188763. png_byte save[2];
  188764. png_uint_32 i;
  188765. for (i = 0; i < row_width; i++)
  188766. {
  188767. save[0] = *(--sp);
  188768. save[1] = *(--sp);
  188769. *(--dp) = *(--sp);
  188770. *(--dp) = *(--sp);
  188771. *(--dp) = save[0];
  188772. *(--dp) = save[1];
  188773. }
  188774. }
  188775. }
  188776. }
  188777. }
  188778. #endif
  188779. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  188780. void /* PRIVATE */
  188781. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  188782. {
  188783. png_debug(1, "in png_do_read_invert_alpha\n");
  188784. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188785. if (row != NULL && row_info != NULL)
  188786. #endif
  188787. {
  188788. png_uint_32 row_width = row_info->width;
  188789. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  188790. {
  188791. /* This inverts the alpha channel in RGBA */
  188792. if (row_info->bit_depth == 8)
  188793. {
  188794. png_bytep sp = row + row_info->rowbytes;
  188795. png_bytep dp = sp;
  188796. png_uint_32 i;
  188797. for (i = 0; i < row_width; i++)
  188798. {
  188799. *(--dp) = (png_byte)(255 - *(--sp));
  188800. /* This does nothing:
  188801. *(--dp) = *(--sp);
  188802. *(--dp) = *(--sp);
  188803. *(--dp) = *(--sp);
  188804. We can replace it with:
  188805. */
  188806. sp-=3;
  188807. dp=sp;
  188808. }
  188809. }
  188810. /* This inverts the alpha channel in RRGGBBAA */
  188811. else
  188812. {
  188813. png_bytep sp = row + row_info->rowbytes;
  188814. png_bytep dp = sp;
  188815. png_uint_32 i;
  188816. for (i = 0; i < row_width; i++)
  188817. {
  188818. *(--dp) = (png_byte)(255 - *(--sp));
  188819. *(--dp) = (png_byte)(255 - *(--sp));
  188820. /* This does nothing:
  188821. *(--dp) = *(--sp);
  188822. *(--dp) = *(--sp);
  188823. *(--dp) = *(--sp);
  188824. *(--dp) = *(--sp);
  188825. *(--dp) = *(--sp);
  188826. *(--dp) = *(--sp);
  188827. We can replace it with:
  188828. */
  188829. sp-=6;
  188830. dp=sp;
  188831. }
  188832. }
  188833. }
  188834. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  188835. {
  188836. /* This inverts the alpha channel in GA */
  188837. if (row_info->bit_depth == 8)
  188838. {
  188839. png_bytep sp = row + row_info->rowbytes;
  188840. png_bytep dp = sp;
  188841. png_uint_32 i;
  188842. for (i = 0; i < row_width; i++)
  188843. {
  188844. *(--dp) = (png_byte)(255 - *(--sp));
  188845. *(--dp) = *(--sp);
  188846. }
  188847. }
  188848. /* This inverts the alpha channel in GGAA */
  188849. else
  188850. {
  188851. png_bytep sp = row + row_info->rowbytes;
  188852. png_bytep dp = sp;
  188853. png_uint_32 i;
  188854. for (i = 0; i < row_width; i++)
  188855. {
  188856. *(--dp) = (png_byte)(255 - *(--sp));
  188857. *(--dp) = (png_byte)(255 - *(--sp));
  188858. /*
  188859. *(--dp) = *(--sp);
  188860. *(--dp) = *(--sp);
  188861. */
  188862. sp-=2;
  188863. dp=sp;
  188864. }
  188865. }
  188866. }
  188867. }
  188868. }
  188869. #endif
  188870. #if defined(PNG_READ_FILLER_SUPPORTED)
  188871. /* Add filler channel if we have RGB color */
  188872. void /* PRIVATE */
  188873. png_do_read_filler(png_row_infop row_info, png_bytep row,
  188874. png_uint_32 filler, png_uint_32 flags)
  188875. {
  188876. png_uint_32 i;
  188877. png_uint_32 row_width = row_info->width;
  188878. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  188879. png_byte lo_filler = (png_byte)(filler & 0xff);
  188880. png_debug(1, "in png_do_read_filler\n");
  188881. if (
  188882. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188883. row != NULL && row_info != NULL &&
  188884. #endif
  188885. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  188886. {
  188887. if(row_info->bit_depth == 8)
  188888. {
  188889. /* This changes the data from G to GX */
  188890. if (flags & PNG_FLAG_FILLER_AFTER)
  188891. {
  188892. png_bytep sp = row + (png_size_t)row_width;
  188893. png_bytep dp = sp + (png_size_t)row_width;
  188894. for (i = 1; i < row_width; i++)
  188895. {
  188896. *(--dp) = lo_filler;
  188897. *(--dp) = *(--sp);
  188898. }
  188899. *(--dp) = lo_filler;
  188900. row_info->channels = 2;
  188901. row_info->pixel_depth = 16;
  188902. row_info->rowbytes = row_width * 2;
  188903. }
  188904. /* This changes the data from G to XG */
  188905. else
  188906. {
  188907. png_bytep sp = row + (png_size_t)row_width;
  188908. png_bytep dp = sp + (png_size_t)row_width;
  188909. for (i = 0; i < row_width; i++)
  188910. {
  188911. *(--dp) = *(--sp);
  188912. *(--dp) = lo_filler;
  188913. }
  188914. row_info->channels = 2;
  188915. row_info->pixel_depth = 16;
  188916. row_info->rowbytes = row_width * 2;
  188917. }
  188918. }
  188919. else if(row_info->bit_depth == 16)
  188920. {
  188921. /* This changes the data from GG to GGXX */
  188922. if (flags & PNG_FLAG_FILLER_AFTER)
  188923. {
  188924. png_bytep sp = row + (png_size_t)row_width * 2;
  188925. png_bytep dp = sp + (png_size_t)row_width * 2;
  188926. for (i = 1; i < row_width; i++)
  188927. {
  188928. *(--dp) = hi_filler;
  188929. *(--dp) = lo_filler;
  188930. *(--dp) = *(--sp);
  188931. *(--dp) = *(--sp);
  188932. }
  188933. *(--dp) = hi_filler;
  188934. *(--dp) = lo_filler;
  188935. row_info->channels = 2;
  188936. row_info->pixel_depth = 32;
  188937. row_info->rowbytes = row_width * 4;
  188938. }
  188939. /* This changes the data from GG to XXGG */
  188940. else
  188941. {
  188942. png_bytep sp = row + (png_size_t)row_width * 2;
  188943. png_bytep dp = sp + (png_size_t)row_width * 2;
  188944. for (i = 0; i < row_width; i++)
  188945. {
  188946. *(--dp) = *(--sp);
  188947. *(--dp) = *(--sp);
  188948. *(--dp) = hi_filler;
  188949. *(--dp) = lo_filler;
  188950. }
  188951. row_info->channels = 2;
  188952. row_info->pixel_depth = 32;
  188953. row_info->rowbytes = row_width * 4;
  188954. }
  188955. }
  188956. } /* COLOR_TYPE == GRAY */
  188957. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  188958. {
  188959. if(row_info->bit_depth == 8)
  188960. {
  188961. /* This changes the data from RGB to RGBX */
  188962. if (flags & PNG_FLAG_FILLER_AFTER)
  188963. {
  188964. png_bytep sp = row + (png_size_t)row_width * 3;
  188965. png_bytep dp = sp + (png_size_t)row_width;
  188966. for (i = 1; i < row_width; i++)
  188967. {
  188968. *(--dp) = lo_filler;
  188969. *(--dp) = *(--sp);
  188970. *(--dp) = *(--sp);
  188971. *(--dp) = *(--sp);
  188972. }
  188973. *(--dp) = lo_filler;
  188974. row_info->channels = 4;
  188975. row_info->pixel_depth = 32;
  188976. row_info->rowbytes = row_width * 4;
  188977. }
  188978. /* This changes the data from RGB to XRGB */
  188979. else
  188980. {
  188981. png_bytep sp = row + (png_size_t)row_width * 3;
  188982. png_bytep dp = sp + (png_size_t)row_width;
  188983. for (i = 0; i < row_width; i++)
  188984. {
  188985. *(--dp) = *(--sp);
  188986. *(--dp) = *(--sp);
  188987. *(--dp) = *(--sp);
  188988. *(--dp) = lo_filler;
  188989. }
  188990. row_info->channels = 4;
  188991. row_info->pixel_depth = 32;
  188992. row_info->rowbytes = row_width * 4;
  188993. }
  188994. }
  188995. else if(row_info->bit_depth == 16)
  188996. {
  188997. /* This changes the data from RRGGBB to RRGGBBXX */
  188998. if (flags & PNG_FLAG_FILLER_AFTER)
  188999. {
  189000. png_bytep sp = row + (png_size_t)row_width * 6;
  189001. png_bytep dp = sp + (png_size_t)row_width * 2;
  189002. for (i = 1; i < row_width; i++)
  189003. {
  189004. *(--dp) = hi_filler;
  189005. *(--dp) = lo_filler;
  189006. *(--dp) = *(--sp);
  189007. *(--dp) = *(--sp);
  189008. *(--dp) = *(--sp);
  189009. *(--dp) = *(--sp);
  189010. *(--dp) = *(--sp);
  189011. *(--dp) = *(--sp);
  189012. }
  189013. *(--dp) = hi_filler;
  189014. *(--dp) = lo_filler;
  189015. row_info->channels = 4;
  189016. row_info->pixel_depth = 64;
  189017. row_info->rowbytes = row_width * 8;
  189018. }
  189019. /* This changes the data from RRGGBB to XXRRGGBB */
  189020. else
  189021. {
  189022. png_bytep sp = row + (png_size_t)row_width * 6;
  189023. png_bytep dp = sp + (png_size_t)row_width * 2;
  189024. for (i = 0; i < row_width; i++)
  189025. {
  189026. *(--dp) = *(--sp);
  189027. *(--dp) = *(--sp);
  189028. *(--dp) = *(--sp);
  189029. *(--dp) = *(--sp);
  189030. *(--dp) = *(--sp);
  189031. *(--dp) = *(--sp);
  189032. *(--dp) = hi_filler;
  189033. *(--dp) = lo_filler;
  189034. }
  189035. row_info->channels = 4;
  189036. row_info->pixel_depth = 64;
  189037. row_info->rowbytes = row_width * 8;
  189038. }
  189039. }
  189040. } /* COLOR_TYPE == RGB */
  189041. }
  189042. #endif
  189043. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  189044. /* expand grayscale files to RGB, with or without alpha */
  189045. void /* PRIVATE */
  189046. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  189047. {
  189048. png_uint_32 i;
  189049. png_uint_32 row_width = row_info->width;
  189050. png_debug(1, "in png_do_gray_to_rgb\n");
  189051. if (row_info->bit_depth >= 8 &&
  189052. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  189053. row != NULL && row_info != NULL &&
  189054. #endif
  189055. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  189056. {
  189057. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  189058. {
  189059. if (row_info->bit_depth == 8)
  189060. {
  189061. png_bytep sp = row + (png_size_t)row_width - 1;
  189062. png_bytep dp = sp + (png_size_t)row_width * 2;
  189063. for (i = 0; i < row_width; i++)
  189064. {
  189065. *(dp--) = *sp;
  189066. *(dp--) = *sp;
  189067. *(dp--) = *(sp--);
  189068. }
  189069. }
  189070. else
  189071. {
  189072. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  189073. png_bytep dp = sp + (png_size_t)row_width * 4;
  189074. for (i = 0; i < row_width; i++)
  189075. {
  189076. *(dp--) = *sp;
  189077. *(dp--) = *(sp - 1);
  189078. *(dp--) = *sp;
  189079. *(dp--) = *(sp - 1);
  189080. *(dp--) = *(sp--);
  189081. *(dp--) = *(sp--);
  189082. }
  189083. }
  189084. }
  189085. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  189086. {
  189087. if (row_info->bit_depth == 8)
  189088. {
  189089. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  189090. png_bytep dp = sp + (png_size_t)row_width * 2;
  189091. for (i = 0; i < row_width; i++)
  189092. {
  189093. *(dp--) = *(sp--);
  189094. *(dp--) = *sp;
  189095. *(dp--) = *sp;
  189096. *(dp--) = *(sp--);
  189097. }
  189098. }
  189099. else
  189100. {
  189101. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  189102. png_bytep dp = sp + (png_size_t)row_width * 4;
  189103. for (i = 0; i < row_width; i++)
  189104. {
  189105. *(dp--) = *(sp--);
  189106. *(dp--) = *(sp--);
  189107. *(dp--) = *sp;
  189108. *(dp--) = *(sp - 1);
  189109. *(dp--) = *sp;
  189110. *(dp--) = *(sp - 1);
  189111. *(dp--) = *(sp--);
  189112. *(dp--) = *(sp--);
  189113. }
  189114. }
  189115. }
  189116. row_info->channels += (png_byte)2;
  189117. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  189118. row_info->pixel_depth = (png_byte)(row_info->channels *
  189119. row_info->bit_depth);
  189120. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  189121. }
  189122. }
  189123. #endif
  189124. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  189125. /* reduce RGB files to grayscale, with or without alpha
  189126. * using the equation given in Poynton's ColorFAQ at
  189127. * <http://www.inforamp.net/~poynton/>
  189128. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  189129. *
  189130. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  189131. *
  189132. * We approximate this with
  189133. *
  189134. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  189135. *
  189136. * which can be expressed with integers as
  189137. *
  189138. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  189139. *
  189140. * The calculation is to be done in a linear colorspace.
  189141. *
  189142. * Other integer coefficents can be used via png_set_rgb_to_gray().
  189143. */
  189144. int /* PRIVATE */
  189145. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  189146. {
  189147. png_uint_32 i;
  189148. png_uint_32 row_width = row_info->width;
  189149. int rgb_error = 0;
  189150. png_debug(1, "in png_do_rgb_to_gray\n");
  189151. if (
  189152. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  189153. row != NULL && row_info != NULL &&
  189154. #endif
  189155. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  189156. {
  189157. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  189158. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  189159. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  189160. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  189161. {
  189162. if (row_info->bit_depth == 8)
  189163. {
  189164. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  189165. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  189166. {
  189167. png_bytep sp = row;
  189168. png_bytep dp = row;
  189169. for (i = 0; i < row_width; i++)
  189170. {
  189171. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  189172. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  189173. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  189174. if(red != green || red != blue)
  189175. {
  189176. rgb_error |= 1;
  189177. *(dp++) = png_ptr->gamma_from_1[
  189178. (rc*red+gc*green+bc*blue)>>15];
  189179. }
  189180. else
  189181. *(dp++) = *(sp-1);
  189182. }
  189183. }
  189184. else
  189185. #endif
  189186. {
  189187. png_bytep sp = row;
  189188. png_bytep dp = row;
  189189. for (i = 0; i < row_width; i++)
  189190. {
  189191. png_byte red = *(sp++);
  189192. png_byte green = *(sp++);
  189193. png_byte blue = *(sp++);
  189194. if(red != green || red != blue)
  189195. {
  189196. rgb_error |= 1;
  189197. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  189198. }
  189199. else
  189200. *(dp++) = *(sp-1);
  189201. }
  189202. }
  189203. }
  189204. else /* RGB bit_depth == 16 */
  189205. {
  189206. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  189207. if (png_ptr->gamma_16_to_1 != NULL &&
  189208. png_ptr->gamma_16_from_1 != NULL)
  189209. {
  189210. png_bytep sp = row;
  189211. png_bytep dp = row;
  189212. for (i = 0; i < row_width; i++)
  189213. {
  189214. png_uint_16 red, green, blue, w;
  189215. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  189216. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  189217. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  189218. if(red == green && red == blue)
  189219. w = red;
  189220. else
  189221. {
  189222. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  189223. png_ptr->gamma_shift][red>>8];
  189224. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  189225. png_ptr->gamma_shift][green>>8];
  189226. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  189227. png_ptr->gamma_shift][blue>>8];
  189228. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  189229. + bc*blue_1)>>15);
  189230. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  189231. png_ptr->gamma_shift][gray16 >> 8];
  189232. rgb_error |= 1;
  189233. }
  189234. *(dp++) = (png_byte)((w>>8) & 0xff);
  189235. *(dp++) = (png_byte)(w & 0xff);
  189236. }
  189237. }
  189238. else
  189239. #endif
  189240. {
  189241. png_bytep sp = row;
  189242. png_bytep dp = row;
  189243. for (i = 0; i < row_width; i++)
  189244. {
  189245. png_uint_16 red, green, blue, gray16;
  189246. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  189247. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  189248. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  189249. if(red != green || red != blue)
  189250. rgb_error |= 1;
  189251. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  189252. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  189253. *(dp++) = (png_byte)(gray16 & 0xff);
  189254. }
  189255. }
  189256. }
  189257. }
  189258. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  189259. {
  189260. if (row_info->bit_depth == 8)
  189261. {
  189262. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  189263. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  189264. {
  189265. png_bytep sp = row;
  189266. png_bytep dp = row;
  189267. for (i = 0; i < row_width; i++)
  189268. {
  189269. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  189270. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  189271. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  189272. if(red != green || red != blue)
  189273. rgb_error |= 1;
  189274. *(dp++) = png_ptr->gamma_from_1
  189275. [(rc*red + gc*green + bc*blue)>>15];
  189276. *(dp++) = *(sp++); /* alpha */
  189277. }
  189278. }
  189279. else
  189280. #endif
  189281. {
  189282. png_bytep sp = row;
  189283. png_bytep dp = row;
  189284. for (i = 0; i < row_width; i++)
  189285. {
  189286. png_byte red = *(sp++);
  189287. png_byte green = *(sp++);
  189288. png_byte blue = *(sp++);
  189289. if(red != green || red != blue)
  189290. rgb_error |= 1;
  189291. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  189292. *(dp++) = *(sp++); /* alpha */
  189293. }
  189294. }
  189295. }
  189296. else /* RGBA bit_depth == 16 */
  189297. {
  189298. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  189299. if (png_ptr->gamma_16_to_1 != NULL &&
  189300. png_ptr->gamma_16_from_1 != NULL)
  189301. {
  189302. png_bytep sp = row;
  189303. png_bytep dp = row;
  189304. for (i = 0; i < row_width; i++)
  189305. {
  189306. png_uint_16 red, green, blue, w;
  189307. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  189308. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  189309. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  189310. if(red == green && red == blue)
  189311. w = red;
  189312. else
  189313. {
  189314. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  189315. png_ptr->gamma_shift][red>>8];
  189316. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  189317. png_ptr->gamma_shift][green>>8];
  189318. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  189319. png_ptr->gamma_shift][blue>>8];
  189320. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  189321. + gc * green_1 + bc * blue_1)>>15);
  189322. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  189323. png_ptr->gamma_shift][gray16 >> 8];
  189324. rgb_error |= 1;
  189325. }
  189326. *(dp++) = (png_byte)((w>>8) & 0xff);
  189327. *(dp++) = (png_byte)(w & 0xff);
  189328. *(dp++) = *(sp++); /* alpha */
  189329. *(dp++) = *(sp++);
  189330. }
  189331. }
  189332. else
  189333. #endif
  189334. {
  189335. png_bytep sp = row;
  189336. png_bytep dp = row;
  189337. for (i = 0; i < row_width; i++)
  189338. {
  189339. png_uint_16 red, green, blue, gray16;
  189340. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  189341. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  189342. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  189343. if(red != green || red != blue)
  189344. rgb_error |= 1;
  189345. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  189346. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  189347. *(dp++) = (png_byte)(gray16 & 0xff);
  189348. *(dp++) = *(sp++); /* alpha */
  189349. *(dp++) = *(sp++);
  189350. }
  189351. }
  189352. }
  189353. }
  189354. row_info->channels -= (png_byte)2;
  189355. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  189356. row_info->pixel_depth = (png_byte)(row_info->channels *
  189357. row_info->bit_depth);
  189358. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  189359. }
  189360. return rgb_error;
  189361. }
  189362. #endif
  189363. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  189364. * large of png_color. This lets grayscale images be treated as
  189365. * paletted. Most useful for gamma correction and simplification
  189366. * of code.
  189367. */
  189368. void PNGAPI
  189369. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  189370. {
  189371. int num_palette;
  189372. int color_inc;
  189373. int i;
  189374. int v;
  189375. png_debug(1, "in png_do_build_grayscale_palette\n");
  189376. if (palette == NULL)
  189377. return;
  189378. switch (bit_depth)
  189379. {
  189380. case 1:
  189381. num_palette = 2;
  189382. color_inc = 0xff;
  189383. break;
  189384. case 2:
  189385. num_palette = 4;
  189386. color_inc = 0x55;
  189387. break;
  189388. case 4:
  189389. num_palette = 16;
  189390. color_inc = 0x11;
  189391. break;
  189392. case 8:
  189393. num_palette = 256;
  189394. color_inc = 1;
  189395. break;
  189396. default:
  189397. num_palette = 0;
  189398. color_inc = 0;
  189399. break;
  189400. }
  189401. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  189402. {
  189403. palette[i].red = (png_byte)v;
  189404. palette[i].green = (png_byte)v;
  189405. palette[i].blue = (png_byte)v;
  189406. }
  189407. }
  189408. /* This function is currently unused. Do we really need it? */
  189409. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  189410. void /* PRIVATE */
  189411. png_correct_palette(png_structp png_ptr, png_colorp palette,
  189412. int num_palette)
  189413. {
  189414. png_debug(1, "in png_correct_palette\n");
  189415. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  189416. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  189417. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  189418. {
  189419. png_color back, back_1;
  189420. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  189421. {
  189422. back.red = png_ptr->gamma_table[png_ptr->background.red];
  189423. back.green = png_ptr->gamma_table[png_ptr->background.green];
  189424. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  189425. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  189426. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  189427. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  189428. }
  189429. else
  189430. {
  189431. double g;
  189432. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  189433. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  189434. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  189435. {
  189436. back.red = png_ptr->background.red;
  189437. back.green = png_ptr->background.green;
  189438. back.blue = png_ptr->background.blue;
  189439. }
  189440. else
  189441. {
  189442. back.red =
  189443. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  189444. 255.0 + 0.5);
  189445. back.green =
  189446. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  189447. 255.0 + 0.5);
  189448. back.blue =
  189449. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  189450. 255.0 + 0.5);
  189451. }
  189452. g = 1.0 / png_ptr->background_gamma;
  189453. back_1.red =
  189454. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  189455. 255.0 + 0.5);
  189456. back_1.green =
  189457. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  189458. 255.0 + 0.5);
  189459. back_1.blue =
  189460. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  189461. 255.0 + 0.5);
  189462. }
  189463. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189464. {
  189465. png_uint_32 i;
  189466. for (i = 0; i < (png_uint_32)num_palette; i++)
  189467. {
  189468. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  189469. {
  189470. palette[i] = back;
  189471. }
  189472. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  189473. {
  189474. png_byte v, w;
  189475. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  189476. png_composite(w, v, png_ptr->trans[i], back_1.red);
  189477. palette[i].red = png_ptr->gamma_from_1[w];
  189478. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  189479. png_composite(w, v, png_ptr->trans[i], back_1.green);
  189480. palette[i].green = png_ptr->gamma_from_1[w];
  189481. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  189482. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  189483. palette[i].blue = png_ptr->gamma_from_1[w];
  189484. }
  189485. else
  189486. {
  189487. palette[i].red = png_ptr->gamma_table[palette[i].red];
  189488. palette[i].green = png_ptr->gamma_table[palette[i].green];
  189489. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  189490. }
  189491. }
  189492. }
  189493. else
  189494. {
  189495. int i;
  189496. for (i = 0; i < num_palette; i++)
  189497. {
  189498. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  189499. {
  189500. palette[i] = back;
  189501. }
  189502. else
  189503. {
  189504. palette[i].red = png_ptr->gamma_table[palette[i].red];
  189505. palette[i].green = png_ptr->gamma_table[palette[i].green];
  189506. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  189507. }
  189508. }
  189509. }
  189510. }
  189511. else
  189512. #endif
  189513. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189514. if (png_ptr->transformations & PNG_GAMMA)
  189515. {
  189516. int i;
  189517. for (i = 0; i < num_palette; i++)
  189518. {
  189519. palette[i].red = png_ptr->gamma_table[palette[i].red];
  189520. palette[i].green = png_ptr->gamma_table[palette[i].green];
  189521. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  189522. }
  189523. }
  189524. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  189525. else
  189526. #endif
  189527. #endif
  189528. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  189529. if (png_ptr->transformations & PNG_BACKGROUND)
  189530. {
  189531. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189532. {
  189533. png_color back;
  189534. back.red = (png_byte)png_ptr->background.red;
  189535. back.green = (png_byte)png_ptr->background.green;
  189536. back.blue = (png_byte)png_ptr->background.blue;
  189537. for (i = 0; i < (int)png_ptr->num_trans; i++)
  189538. {
  189539. if (png_ptr->trans[i] == 0)
  189540. {
  189541. palette[i].red = back.red;
  189542. palette[i].green = back.green;
  189543. palette[i].blue = back.blue;
  189544. }
  189545. else if (png_ptr->trans[i] != 0xff)
  189546. {
  189547. png_composite(palette[i].red, png_ptr->palette[i].red,
  189548. png_ptr->trans[i], back.red);
  189549. png_composite(palette[i].green, png_ptr->palette[i].green,
  189550. png_ptr->trans[i], back.green);
  189551. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  189552. png_ptr->trans[i], back.blue);
  189553. }
  189554. }
  189555. }
  189556. else /* assume grayscale palette (what else could it be?) */
  189557. {
  189558. int i;
  189559. for (i = 0; i < num_palette; i++)
  189560. {
  189561. if (i == (png_byte)png_ptr->trans_values.gray)
  189562. {
  189563. palette[i].red = (png_byte)png_ptr->background.red;
  189564. palette[i].green = (png_byte)png_ptr->background.green;
  189565. palette[i].blue = (png_byte)png_ptr->background.blue;
  189566. }
  189567. }
  189568. }
  189569. }
  189570. #endif
  189571. }
  189572. #endif
  189573. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  189574. /* Replace any alpha or transparency with the supplied background color.
  189575. * "background" is already in the screen gamma, while "background_1" is
  189576. * at a gamma of 1.0. Paletted files have already been taken care of.
  189577. */
  189578. void /* PRIVATE */
  189579. png_do_background(png_row_infop row_info, png_bytep row,
  189580. png_color_16p trans_values, png_color_16p background
  189581. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189582. , png_color_16p background_1,
  189583. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  189584. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  189585. png_uint_16pp gamma_16_to_1, int gamma_shift
  189586. #endif
  189587. )
  189588. {
  189589. png_bytep sp, dp;
  189590. png_uint_32 i;
  189591. png_uint_32 row_width=row_info->width;
  189592. int shift;
  189593. png_debug(1, "in png_do_background\n");
  189594. if (background != NULL &&
  189595. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  189596. row != NULL && row_info != NULL &&
  189597. #endif
  189598. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  189599. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  189600. {
  189601. switch (row_info->color_type)
  189602. {
  189603. case PNG_COLOR_TYPE_GRAY:
  189604. {
  189605. switch (row_info->bit_depth)
  189606. {
  189607. case 1:
  189608. {
  189609. sp = row;
  189610. shift = 7;
  189611. for (i = 0; i < row_width; i++)
  189612. {
  189613. if ((png_uint_16)((*sp >> shift) & 0x01)
  189614. == trans_values->gray)
  189615. {
  189616. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  189617. *sp |= (png_byte)(background->gray << shift);
  189618. }
  189619. if (!shift)
  189620. {
  189621. shift = 7;
  189622. sp++;
  189623. }
  189624. else
  189625. shift--;
  189626. }
  189627. break;
  189628. }
  189629. case 2:
  189630. {
  189631. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189632. if (gamma_table != NULL)
  189633. {
  189634. sp = row;
  189635. shift = 6;
  189636. for (i = 0; i < row_width; i++)
  189637. {
  189638. if ((png_uint_16)((*sp >> shift) & 0x03)
  189639. == trans_values->gray)
  189640. {
  189641. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  189642. *sp |= (png_byte)(background->gray << shift);
  189643. }
  189644. else
  189645. {
  189646. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  189647. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  189648. (p << 4) | (p << 6)] >> 6) & 0x03);
  189649. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  189650. *sp |= (png_byte)(g << shift);
  189651. }
  189652. if (!shift)
  189653. {
  189654. shift = 6;
  189655. sp++;
  189656. }
  189657. else
  189658. shift -= 2;
  189659. }
  189660. }
  189661. else
  189662. #endif
  189663. {
  189664. sp = row;
  189665. shift = 6;
  189666. for (i = 0; i < row_width; i++)
  189667. {
  189668. if ((png_uint_16)((*sp >> shift) & 0x03)
  189669. == trans_values->gray)
  189670. {
  189671. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  189672. *sp |= (png_byte)(background->gray << shift);
  189673. }
  189674. if (!shift)
  189675. {
  189676. shift = 6;
  189677. sp++;
  189678. }
  189679. else
  189680. shift -= 2;
  189681. }
  189682. }
  189683. break;
  189684. }
  189685. case 4:
  189686. {
  189687. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189688. if (gamma_table != NULL)
  189689. {
  189690. sp = row;
  189691. shift = 4;
  189692. for (i = 0; i < row_width; i++)
  189693. {
  189694. if ((png_uint_16)((*sp >> shift) & 0x0f)
  189695. == trans_values->gray)
  189696. {
  189697. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  189698. *sp |= (png_byte)(background->gray << shift);
  189699. }
  189700. else
  189701. {
  189702. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  189703. png_byte g = (png_byte)((gamma_table[p |
  189704. (p << 4)] >> 4) & 0x0f);
  189705. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  189706. *sp |= (png_byte)(g << shift);
  189707. }
  189708. if (!shift)
  189709. {
  189710. shift = 4;
  189711. sp++;
  189712. }
  189713. else
  189714. shift -= 4;
  189715. }
  189716. }
  189717. else
  189718. #endif
  189719. {
  189720. sp = row;
  189721. shift = 4;
  189722. for (i = 0; i < row_width; i++)
  189723. {
  189724. if ((png_uint_16)((*sp >> shift) & 0x0f)
  189725. == trans_values->gray)
  189726. {
  189727. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  189728. *sp |= (png_byte)(background->gray << shift);
  189729. }
  189730. if (!shift)
  189731. {
  189732. shift = 4;
  189733. sp++;
  189734. }
  189735. else
  189736. shift -= 4;
  189737. }
  189738. }
  189739. break;
  189740. }
  189741. case 8:
  189742. {
  189743. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189744. if (gamma_table != NULL)
  189745. {
  189746. sp = row;
  189747. for (i = 0; i < row_width; i++, sp++)
  189748. {
  189749. if (*sp == trans_values->gray)
  189750. {
  189751. *sp = (png_byte)background->gray;
  189752. }
  189753. else
  189754. {
  189755. *sp = gamma_table[*sp];
  189756. }
  189757. }
  189758. }
  189759. else
  189760. #endif
  189761. {
  189762. sp = row;
  189763. for (i = 0; i < row_width; i++, sp++)
  189764. {
  189765. if (*sp == trans_values->gray)
  189766. {
  189767. *sp = (png_byte)background->gray;
  189768. }
  189769. }
  189770. }
  189771. break;
  189772. }
  189773. case 16:
  189774. {
  189775. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189776. if (gamma_16 != NULL)
  189777. {
  189778. sp = row;
  189779. for (i = 0; i < row_width; i++, sp += 2)
  189780. {
  189781. png_uint_16 v;
  189782. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  189783. if (v == trans_values->gray)
  189784. {
  189785. /* background is already in screen gamma */
  189786. *sp = (png_byte)((background->gray >> 8) & 0xff);
  189787. *(sp + 1) = (png_byte)(background->gray & 0xff);
  189788. }
  189789. else
  189790. {
  189791. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  189792. *sp = (png_byte)((v >> 8) & 0xff);
  189793. *(sp + 1) = (png_byte)(v & 0xff);
  189794. }
  189795. }
  189796. }
  189797. else
  189798. #endif
  189799. {
  189800. sp = row;
  189801. for (i = 0; i < row_width; i++, sp += 2)
  189802. {
  189803. png_uint_16 v;
  189804. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  189805. if (v == trans_values->gray)
  189806. {
  189807. *sp = (png_byte)((background->gray >> 8) & 0xff);
  189808. *(sp + 1) = (png_byte)(background->gray & 0xff);
  189809. }
  189810. }
  189811. }
  189812. break;
  189813. }
  189814. }
  189815. break;
  189816. }
  189817. case PNG_COLOR_TYPE_RGB:
  189818. {
  189819. if (row_info->bit_depth == 8)
  189820. {
  189821. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189822. if (gamma_table != NULL)
  189823. {
  189824. sp = row;
  189825. for (i = 0; i < row_width; i++, sp += 3)
  189826. {
  189827. if (*sp == trans_values->red &&
  189828. *(sp + 1) == trans_values->green &&
  189829. *(sp + 2) == trans_values->blue)
  189830. {
  189831. *sp = (png_byte)background->red;
  189832. *(sp + 1) = (png_byte)background->green;
  189833. *(sp + 2) = (png_byte)background->blue;
  189834. }
  189835. else
  189836. {
  189837. *sp = gamma_table[*sp];
  189838. *(sp + 1) = gamma_table[*(sp + 1)];
  189839. *(sp + 2) = gamma_table[*(sp + 2)];
  189840. }
  189841. }
  189842. }
  189843. else
  189844. #endif
  189845. {
  189846. sp = row;
  189847. for (i = 0; i < row_width; i++, sp += 3)
  189848. {
  189849. if (*sp == trans_values->red &&
  189850. *(sp + 1) == trans_values->green &&
  189851. *(sp + 2) == trans_values->blue)
  189852. {
  189853. *sp = (png_byte)background->red;
  189854. *(sp + 1) = (png_byte)background->green;
  189855. *(sp + 2) = (png_byte)background->blue;
  189856. }
  189857. }
  189858. }
  189859. }
  189860. else /* if (row_info->bit_depth == 16) */
  189861. {
  189862. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189863. if (gamma_16 != NULL)
  189864. {
  189865. sp = row;
  189866. for (i = 0; i < row_width; i++, sp += 6)
  189867. {
  189868. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  189869. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  189870. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  189871. if (r == trans_values->red && g == trans_values->green &&
  189872. b == trans_values->blue)
  189873. {
  189874. /* background is already in screen gamma */
  189875. *sp = (png_byte)((background->red >> 8) & 0xff);
  189876. *(sp + 1) = (png_byte)(background->red & 0xff);
  189877. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  189878. *(sp + 3) = (png_byte)(background->green & 0xff);
  189879. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  189880. *(sp + 5) = (png_byte)(background->blue & 0xff);
  189881. }
  189882. else
  189883. {
  189884. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  189885. *sp = (png_byte)((v >> 8) & 0xff);
  189886. *(sp + 1) = (png_byte)(v & 0xff);
  189887. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  189888. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  189889. *(sp + 3) = (png_byte)(v & 0xff);
  189890. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  189891. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  189892. *(sp + 5) = (png_byte)(v & 0xff);
  189893. }
  189894. }
  189895. }
  189896. else
  189897. #endif
  189898. {
  189899. sp = row;
  189900. for (i = 0; i < row_width; i++, sp += 6)
  189901. {
  189902. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  189903. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  189904. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  189905. if (r == trans_values->red && g == trans_values->green &&
  189906. b == trans_values->blue)
  189907. {
  189908. *sp = (png_byte)((background->red >> 8) & 0xff);
  189909. *(sp + 1) = (png_byte)(background->red & 0xff);
  189910. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  189911. *(sp + 3) = (png_byte)(background->green & 0xff);
  189912. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  189913. *(sp + 5) = (png_byte)(background->blue & 0xff);
  189914. }
  189915. }
  189916. }
  189917. }
  189918. break;
  189919. }
  189920. case PNG_COLOR_TYPE_GRAY_ALPHA:
  189921. {
  189922. if (row_info->bit_depth == 8)
  189923. {
  189924. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189925. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  189926. gamma_table != NULL)
  189927. {
  189928. sp = row;
  189929. dp = row;
  189930. for (i = 0; i < row_width; i++, sp += 2, dp++)
  189931. {
  189932. png_uint_16 a = *(sp + 1);
  189933. if (a == 0xff)
  189934. {
  189935. *dp = gamma_table[*sp];
  189936. }
  189937. else if (a == 0)
  189938. {
  189939. /* background is already in screen gamma */
  189940. *dp = (png_byte)background->gray;
  189941. }
  189942. else
  189943. {
  189944. png_byte v, w;
  189945. v = gamma_to_1[*sp];
  189946. png_composite(w, v, a, background_1->gray);
  189947. *dp = gamma_from_1[w];
  189948. }
  189949. }
  189950. }
  189951. else
  189952. #endif
  189953. {
  189954. sp = row;
  189955. dp = row;
  189956. for (i = 0; i < row_width; i++, sp += 2, dp++)
  189957. {
  189958. png_byte a = *(sp + 1);
  189959. if (a == 0xff)
  189960. {
  189961. *dp = *sp;
  189962. }
  189963. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189964. else if (a == 0)
  189965. {
  189966. *dp = (png_byte)background->gray;
  189967. }
  189968. else
  189969. {
  189970. png_composite(*dp, *sp, a, background_1->gray);
  189971. }
  189972. #else
  189973. *dp = (png_byte)background->gray;
  189974. #endif
  189975. }
  189976. }
  189977. }
  189978. else /* if (png_ptr->bit_depth == 16) */
  189979. {
  189980. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189981. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  189982. gamma_16_to_1 != NULL)
  189983. {
  189984. sp = row;
  189985. dp = row;
  189986. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  189987. {
  189988. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  189989. if (a == (png_uint_16)0xffff)
  189990. {
  189991. png_uint_16 v;
  189992. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  189993. *dp = (png_byte)((v >> 8) & 0xff);
  189994. *(dp + 1) = (png_byte)(v & 0xff);
  189995. }
  189996. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189997. else if (a == 0)
  189998. #else
  189999. else
  190000. #endif
  190001. {
  190002. /* background is already in screen gamma */
  190003. *dp = (png_byte)((background->gray >> 8) & 0xff);
  190004. *(dp + 1) = (png_byte)(background->gray & 0xff);
  190005. }
  190006. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190007. else
  190008. {
  190009. png_uint_16 g, v, w;
  190010. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  190011. png_composite_16(v, g, a, background_1->gray);
  190012. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  190013. *dp = (png_byte)((w >> 8) & 0xff);
  190014. *(dp + 1) = (png_byte)(w & 0xff);
  190015. }
  190016. #endif
  190017. }
  190018. }
  190019. else
  190020. #endif
  190021. {
  190022. sp = row;
  190023. dp = row;
  190024. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  190025. {
  190026. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  190027. if (a == (png_uint_16)0xffff)
  190028. {
  190029. png_memcpy(dp, sp, 2);
  190030. }
  190031. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190032. else if (a == 0)
  190033. #else
  190034. else
  190035. #endif
  190036. {
  190037. *dp = (png_byte)((background->gray >> 8) & 0xff);
  190038. *(dp + 1) = (png_byte)(background->gray & 0xff);
  190039. }
  190040. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190041. else
  190042. {
  190043. png_uint_16 g, v;
  190044. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  190045. png_composite_16(v, g, a, background_1->gray);
  190046. *dp = (png_byte)((v >> 8) & 0xff);
  190047. *(dp + 1) = (png_byte)(v & 0xff);
  190048. }
  190049. #endif
  190050. }
  190051. }
  190052. }
  190053. break;
  190054. }
  190055. case PNG_COLOR_TYPE_RGB_ALPHA:
  190056. {
  190057. if (row_info->bit_depth == 8)
  190058. {
  190059. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190060. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  190061. gamma_table != NULL)
  190062. {
  190063. sp = row;
  190064. dp = row;
  190065. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  190066. {
  190067. png_byte a = *(sp + 3);
  190068. if (a == 0xff)
  190069. {
  190070. *dp = gamma_table[*sp];
  190071. *(dp + 1) = gamma_table[*(sp + 1)];
  190072. *(dp + 2) = gamma_table[*(sp + 2)];
  190073. }
  190074. else if (a == 0)
  190075. {
  190076. /* background is already in screen gamma */
  190077. *dp = (png_byte)background->red;
  190078. *(dp + 1) = (png_byte)background->green;
  190079. *(dp + 2) = (png_byte)background->blue;
  190080. }
  190081. else
  190082. {
  190083. png_byte v, w;
  190084. v = gamma_to_1[*sp];
  190085. png_composite(w, v, a, background_1->red);
  190086. *dp = gamma_from_1[w];
  190087. v = gamma_to_1[*(sp + 1)];
  190088. png_composite(w, v, a, background_1->green);
  190089. *(dp + 1) = gamma_from_1[w];
  190090. v = gamma_to_1[*(sp + 2)];
  190091. png_composite(w, v, a, background_1->blue);
  190092. *(dp + 2) = gamma_from_1[w];
  190093. }
  190094. }
  190095. }
  190096. else
  190097. #endif
  190098. {
  190099. sp = row;
  190100. dp = row;
  190101. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  190102. {
  190103. png_byte a = *(sp + 3);
  190104. if (a == 0xff)
  190105. {
  190106. *dp = *sp;
  190107. *(dp + 1) = *(sp + 1);
  190108. *(dp + 2) = *(sp + 2);
  190109. }
  190110. else if (a == 0)
  190111. {
  190112. *dp = (png_byte)background->red;
  190113. *(dp + 1) = (png_byte)background->green;
  190114. *(dp + 2) = (png_byte)background->blue;
  190115. }
  190116. else
  190117. {
  190118. png_composite(*dp, *sp, a, background->red);
  190119. png_composite(*(dp + 1), *(sp + 1), a,
  190120. background->green);
  190121. png_composite(*(dp + 2), *(sp + 2), a,
  190122. background->blue);
  190123. }
  190124. }
  190125. }
  190126. }
  190127. else /* if (row_info->bit_depth == 16) */
  190128. {
  190129. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190130. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  190131. gamma_16_to_1 != NULL)
  190132. {
  190133. sp = row;
  190134. dp = row;
  190135. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  190136. {
  190137. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  190138. << 8) + (png_uint_16)(*(sp + 7)));
  190139. if (a == (png_uint_16)0xffff)
  190140. {
  190141. png_uint_16 v;
  190142. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  190143. *dp = (png_byte)((v >> 8) & 0xff);
  190144. *(dp + 1) = (png_byte)(v & 0xff);
  190145. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  190146. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  190147. *(dp + 3) = (png_byte)(v & 0xff);
  190148. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  190149. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  190150. *(dp + 5) = (png_byte)(v & 0xff);
  190151. }
  190152. else if (a == 0)
  190153. {
  190154. /* background is already in screen gamma */
  190155. *dp = (png_byte)((background->red >> 8) & 0xff);
  190156. *(dp + 1) = (png_byte)(background->red & 0xff);
  190157. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  190158. *(dp + 3) = (png_byte)(background->green & 0xff);
  190159. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  190160. *(dp + 5) = (png_byte)(background->blue & 0xff);
  190161. }
  190162. else
  190163. {
  190164. png_uint_16 v, w, x;
  190165. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  190166. png_composite_16(w, v, a, background_1->red);
  190167. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  190168. *dp = (png_byte)((x >> 8) & 0xff);
  190169. *(dp + 1) = (png_byte)(x & 0xff);
  190170. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  190171. png_composite_16(w, v, a, background_1->green);
  190172. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  190173. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  190174. *(dp + 3) = (png_byte)(x & 0xff);
  190175. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  190176. png_composite_16(w, v, a, background_1->blue);
  190177. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  190178. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  190179. *(dp + 5) = (png_byte)(x & 0xff);
  190180. }
  190181. }
  190182. }
  190183. else
  190184. #endif
  190185. {
  190186. sp = row;
  190187. dp = row;
  190188. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  190189. {
  190190. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  190191. << 8) + (png_uint_16)(*(sp + 7)));
  190192. if (a == (png_uint_16)0xffff)
  190193. {
  190194. png_memcpy(dp, sp, 6);
  190195. }
  190196. else if (a == 0)
  190197. {
  190198. *dp = (png_byte)((background->red >> 8) & 0xff);
  190199. *(dp + 1) = (png_byte)(background->red & 0xff);
  190200. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  190201. *(dp + 3) = (png_byte)(background->green & 0xff);
  190202. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  190203. *(dp + 5) = (png_byte)(background->blue & 0xff);
  190204. }
  190205. else
  190206. {
  190207. png_uint_16 v;
  190208. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  190209. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  190210. + *(sp + 3));
  190211. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  190212. + *(sp + 5));
  190213. png_composite_16(v, r, a, background->red);
  190214. *dp = (png_byte)((v >> 8) & 0xff);
  190215. *(dp + 1) = (png_byte)(v & 0xff);
  190216. png_composite_16(v, g, a, background->green);
  190217. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  190218. *(dp + 3) = (png_byte)(v & 0xff);
  190219. png_composite_16(v, b, a, background->blue);
  190220. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  190221. *(dp + 5) = (png_byte)(v & 0xff);
  190222. }
  190223. }
  190224. }
  190225. }
  190226. break;
  190227. }
  190228. }
  190229. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  190230. {
  190231. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190232. row_info->channels--;
  190233. row_info->pixel_depth = (png_byte)(row_info->channels *
  190234. row_info->bit_depth);
  190235. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  190236. }
  190237. }
  190238. }
  190239. #endif
  190240. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190241. /* Gamma correct the image, avoiding the alpha channel. Make sure
  190242. * you do this after you deal with the transparency issue on grayscale
  190243. * or RGB images. If your bit depth is 8, use gamma_table, if it
  190244. * is 16, use gamma_16_table and gamma_shift. Build these with
  190245. * build_gamma_table().
  190246. */
  190247. void /* PRIVATE */
  190248. png_do_gamma(png_row_infop row_info, png_bytep row,
  190249. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  190250. int gamma_shift)
  190251. {
  190252. png_bytep sp;
  190253. png_uint_32 i;
  190254. png_uint_32 row_width=row_info->width;
  190255. png_debug(1, "in png_do_gamma\n");
  190256. if (
  190257. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190258. row != NULL && row_info != NULL &&
  190259. #endif
  190260. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  190261. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  190262. {
  190263. switch (row_info->color_type)
  190264. {
  190265. case PNG_COLOR_TYPE_RGB:
  190266. {
  190267. if (row_info->bit_depth == 8)
  190268. {
  190269. sp = row;
  190270. for (i = 0; i < row_width; i++)
  190271. {
  190272. *sp = gamma_table[*sp];
  190273. sp++;
  190274. *sp = gamma_table[*sp];
  190275. sp++;
  190276. *sp = gamma_table[*sp];
  190277. sp++;
  190278. }
  190279. }
  190280. else /* if (row_info->bit_depth == 16) */
  190281. {
  190282. sp = row;
  190283. for (i = 0; i < row_width; i++)
  190284. {
  190285. png_uint_16 v;
  190286. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  190287. *sp = (png_byte)((v >> 8) & 0xff);
  190288. *(sp + 1) = (png_byte)(v & 0xff);
  190289. sp += 2;
  190290. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  190291. *sp = (png_byte)((v >> 8) & 0xff);
  190292. *(sp + 1) = (png_byte)(v & 0xff);
  190293. sp += 2;
  190294. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  190295. *sp = (png_byte)((v >> 8) & 0xff);
  190296. *(sp + 1) = (png_byte)(v & 0xff);
  190297. sp += 2;
  190298. }
  190299. }
  190300. break;
  190301. }
  190302. case PNG_COLOR_TYPE_RGB_ALPHA:
  190303. {
  190304. if (row_info->bit_depth == 8)
  190305. {
  190306. sp = row;
  190307. for (i = 0; i < row_width; i++)
  190308. {
  190309. *sp = gamma_table[*sp];
  190310. sp++;
  190311. *sp = gamma_table[*sp];
  190312. sp++;
  190313. *sp = gamma_table[*sp];
  190314. sp++;
  190315. sp++;
  190316. }
  190317. }
  190318. else /* if (row_info->bit_depth == 16) */
  190319. {
  190320. sp = row;
  190321. for (i = 0; i < row_width; i++)
  190322. {
  190323. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  190324. *sp = (png_byte)((v >> 8) & 0xff);
  190325. *(sp + 1) = (png_byte)(v & 0xff);
  190326. sp += 2;
  190327. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  190328. *sp = (png_byte)((v >> 8) & 0xff);
  190329. *(sp + 1) = (png_byte)(v & 0xff);
  190330. sp += 2;
  190331. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  190332. *sp = (png_byte)((v >> 8) & 0xff);
  190333. *(sp + 1) = (png_byte)(v & 0xff);
  190334. sp += 4;
  190335. }
  190336. }
  190337. break;
  190338. }
  190339. case PNG_COLOR_TYPE_GRAY_ALPHA:
  190340. {
  190341. if (row_info->bit_depth == 8)
  190342. {
  190343. sp = row;
  190344. for (i = 0; i < row_width; i++)
  190345. {
  190346. *sp = gamma_table[*sp];
  190347. sp += 2;
  190348. }
  190349. }
  190350. else /* if (row_info->bit_depth == 16) */
  190351. {
  190352. sp = row;
  190353. for (i = 0; i < row_width; i++)
  190354. {
  190355. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  190356. *sp = (png_byte)((v >> 8) & 0xff);
  190357. *(sp + 1) = (png_byte)(v & 0xff);
  190358. sp += 4;
  190359. }
  190360. }
  190361. break;
  190362. }
  190363. case PNG_COLOR_TYPE_GRAY:
  190364. {
  190365. if (row_info->bit_depth == 2)
  190366. {
  190367. sp = row;
  190368. for (i = 0; i < row_width; i += 4)
  190369. {
  190370. int a = *sp & 0xc0;
  190371. int b = *sp & 0x30;
  190372. int c = *sp & 0x0c;
  190373. int d = *sp & 0x03;
  190374. *sp = (png_byte)(
  190375. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  190376. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  190377. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  190378. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  190379. sp++;
  190380. }
  190381. }
  190382. if (row_info->bit_depth == 4)
  190383. {
  190384. sp = row;
  190385. for (i = 0; i < row_width; i += 2)
  190386. {
  190387. int msb = *sp & 0xf0;
  190388. int lsb = *sp & 0x0f;
  190389. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  190390. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  190391. sp++;
  190392. }
  190393. }
  190394. else if (row_info->bit_depth == 8)
  190395. {
  190396. sp = row;
  190397. for (i = 0; i < row_width; i++)
  190398. {
  190399. *sp = gamma_table[*sp];
  190400. sp++;
  190401. }
  190402. }
  190403. else if (row_info->bit_depth == 16)
  190404. {
  190405. sp = row;
  190406. for (i = 0; i < row_width; i++)
  190407. {
  190408. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  190409. *sp = (png_byte)((v >> 8) & 0xff);
  190410. *(sp + 1) = (png_byte)(v & 0xff);
  190411. sp += 2;
  190412. }
  190413. }
  190414. break;
  190415. }
  190416. }
  190417. }
  190418. }
  190419. #endif
  190420. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190421. /* Expands a palette row to an RGB or RGBA row depending
  190422. * upon whether you supply trans and num_trans.
  190423. */
  190424. void /* PRIVATE */
  190425. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  190426. png_colorp palette, png_bytep trans, int num_trans)
  190427. {
  190428. int shift, value;
  190429. png_bytep sp, dp;
  190430. png_uint_32 i;
  190431. png_uint_32 row_width=row_info->width;
  190432. png_debug(1, "in png_do_expand_palette\n");
  190433. if (
  190434. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190435. row != NULL && row_info != NULL &&
  190436. #endif
  190437. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  190438. {
  190439. if (row_info->bit_depth < 8)
  190440. {
  190441. switch (row_info->bit_depth)
  190442. {
  190443. case 1:
  190444. {
  190445. sp = row + (png_size_t)((row_width - 1) >> 3);
  190446. dp = row + (png_size_t)row_width - 1;
  190447. shift = 7 - (int)((row_width + 7) & 0x07);
  190448. for (i = 0; i < row_width; i++)
  190449. {
  190450. if ((*sp >> shift) & 0x01)
  190451. *dp = 1;
  190452. else
  190453. *dp = 0;
  190454. if (shift == 7)
  190455. {
  190456. shift = 0;
  190457. sp--;
  190458. }
  190459. else
  190460. shift++;
  190461. dp--;
  190462. }
  190463. break;
  190464. }
  190465. case 2:
  190466. {
  190467. sp = row + (png_size_t)((row_width - 1) >> 2);
  190468. dp = row + (png_size_t)row_width - 1;
  190469. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  190470. for (i = 0; i < row_width; i++)
  190471. {
  190472. value = (*sp >> shift) & 0x03;
  190473. *dp = (png_byte)value;
  190474. if (shift == 6)
  190475. {
  190476. shift = 0;
  190477. sp--;
  190478. }
  190479. else
  190480. shift += 2;
  190481. dp--;
  190482. }
  190483. break;
  190484. }
  190485. case 4:
  190486. {
  190487. sp = row + (png_size_t)((row_width - 1) >> 1);
  190488. dp = row + (png_size_t)row_width - 1;
  190489. shift = (int)((row_width & 0x01) << 2);
  190490. for (i = 0; i < row_width; i++)
  190491. {
  190492. value = (*sp >> shift) & 0x0f;
  190493. *dp = (png_byte)value;
  190494. if (shift == 4)
  190495. {
  190496. shift = 0;
  190497. sp--;
  190498. }
  190499. else
  190500. shift += 4;
  190501. dp--;
  190502. }
  190503. break;
  190504. }
  190505. }
  190506. row_info->bit_depth = 8;
  190507. row_info->pixel_depth = 8;
  190508. row_info->rowbytes = row_width;
  190509. }
  190510. switch (row_info->bit_depth)
  190511. {
  190512. case 8:
  190513. {
  190514. if (trans != NULL)
  190515. {
  190516. sp = row + (png_size_t)row_width - 1;
  190517. dp = row + (png_size_t)(row_width << 2) - 1;
  190518. for (i = 0; i < row_width; i++)
  190519. {
  190520. if ((int)(*sp) >= num_trans)
  190521. *dp-- = 0xff;
  190522. else
  190523. *dp-- = trans[*sp];
  190524. *dp-- = palette[*sp].blue;
  190525. *dp-- = palette[*sp].green;
  190526. *dp-- = palette[*sp].red;
  190527. sp--;
  190528. }
  190529. row_info->bit_depth = 8;
  190530. row_info->pixel_depth = 32;
  190531. row_info->rowbytes = row_width * 4;
  190532. row_info->color_type = 6;
  190533. row_info->channels = 4;
  190534. }
  190535. else
  190536. {
  190537. sp = row + (png_size_t)row_width - 1;
  190538. dp = row + (png_size_t)(row_width * 3) - 1;
  190539. for (i = 0; i < row_width; i++)
  190540. {
  190541. *dp-- = palette[*sp].blue;
  190542. *dp-- = palette[*sp].green;
  190543. *dp-- = palette[*sp].red;
  190544. sp--;
  190545. }
  190546. row_info->bit_depth = 8;
  190547. row_info->pixel_depth = 24;
  190548. row_info->rowbytes = row_width * 3;
  190549. row_info->color_type = 2;
  190550. row_info->channels = 3;
  190551. }
  190552. break;
  190553. }
  190554. }
  190555. }
  190556. }
  190557. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  190558. * expanded transparency value is supplied, an alpha channel is built.
  190559. */
  190560. void /* PRIVATE */
  190561. png_do_expand(png_row_infop row_info, png_bytep row,
  190562. png_color_16p trans_value)
  190563. {
  190564. int shift, value;
  190565. png_bytep sp, dp;
  190566. png_uint_32 i;
  190567. png_uint_32 row_width=row_info->width;
  190568. png_debug(1, "in png_do_expand\n");
  190569. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190570. if (row != NULL && row_info != NULL)
  190571. #endif
  190572. {
  190573. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  190574. {
  190575. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  190576. if (row_info->bit_depth < 8)
  190577. {
  190578. switch (row_info->bit_depth)
  190579. {
  190580. case 1:
  190581. {
  190582. gray = (png_uint_16)((gray&0x01)*0xff);
  190583. sp = row + (png_size_t)((row_width - 1) >> 3);
  190584. dp = row + (png_size_t)row_width - 1;
  190585. shift = 7 - (int)((row_width + 7) & 0x07);
  190586. for (i = 0; i < row_width; i++)
  190587. {
  190588. if ((*sp >> shift) & 0x01)
  190589. *dp = 0xff;
  190590. else
  190591. *dp = 0;
  190592. if (shift == 7)
  190593. {
  190594. shift = 0;
  190595. sp--;
  190596. }
  190597. else
  190598. shift++;
  190599. dp--;
  190600. }
  190601. break;
  190602. }
  190603. case 2:
  190604. {
  190605. gray = (png_uint_16)((gray&0x03)*0x55);
  190606. sp = row + (png_size_t)((row_width - 1) >> 2);
  190607. dp = row + (png_size_t)row_width - 1;
  190608. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  190609. for (i = 0; i < row_width; i++)
  190610. {
  190611. value = (*sp >> shift) & 0x03;
  190612. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  190613. (value << 6));
  190614. if (shift == 6)
  190615. {
  190616. shift = 0;
  190617. sp--;
  190618. }
  190619. else
  190620. shift += 2;
  190621. dp--;
  190622. }
  190623. break;
  190624. }
  190625. case 4:
  190626. {
  190627. gray = (png_uint_16)((gray&0x0f)*0x11);
  190628. sp = row + (png_size_t)((row_width - 1) >> 1);
  190629. dp = row + (png_size_t)row_width - 1;
  190630. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  190631. for (i = 0; i < row_width; i++)
  190632. {
  190633. value = (*sp >> shift) & 0x0f;
  190634. *dp = (png_byte)(value | (value << 4));
  190635. if (shift == 4)
  190636. {
  190637. shift = 0;
  190638. sp--;
  190639. }
  190640. else
  190641. shift = 4;
  190642. dp--;
  190643. }
  190644. break;
  190645. }
  190646. }
  190647. row_info->bit_depth = 8;
  190648. row_info->pixel_depth = 8;
  190649. row_info->rowbytes = row_width;
  190650. }
  190651. if (trans_value != NULL)
  190652. {
  190653. if (row_info->bit_depth == 8)
  190654. {
  190655. gray = gray & 0xff;
  190656. sp = row + (png_size_t)row_width - 1;
  190657. dp = row + (png_size_t)(row_width << 1) - 1;
  190658. for (i = 0; i < row_width; i++)
  190659. {
  190660. if (*sp == gray)
  190661. *dp-- = 0;
  190662. else
  190663. *dp-- = 0xff;
  190664. *dp-- = *sp--;
  190665. }
  190666. }
  190667. else if (row_info->bit_depth == 16)
  190668. {
  190669. png_byte gray_high = (gray >> 8) & 0xff;
  190670. png_byte gray_low = gray & 0xff;
  190671. sp = row + row_info->rowbytes - 1;
  190672. dp = row + (row_info->rowbytes << 1) - 1;
  190673. for (i = 0; i < row_width; i++)
  190674. {
  190675. if (*(sp-1) == gray_high && *(sp) == gray_low)
  190676. {
  190677. *dp-- = 0;
  190678. *dp-- = 0;
  190679. }
  190680. else
  190681. {
  190682. *dp-- = 0xff;
  190683. *dp-- = 0xff;
  190684. }
  190685. *dp-- = *sp--;
  190686. *dp-- = *sp--;
  190687. }
  190688. }
  190689. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  190690. row_info->channels = 2;
  190691. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  190692. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  190693. row_width);
  190694. }
  190695. }
  190696. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  190697. {
  190698. if (row_info->bit_depth == 8)
  190699. {
  190700. png_byte red = trans_value->red & 0xff;
  190701. png_byte green = trans_value->green & 0xff;
  190702. png_byte blue = trans_value->blue & 0xff;
  190703. sp = row + (png_size_t)row_info->rowbytes - 1;
  190704. dp = row + (png_size_t)(row_width << 2) - 1;
  190705. for (i = 0; i < row_width; i++)
  190706. {
  190707. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  190708. *dp-- = 0;
  190709. else
  190710. *dp-- = 0xff;
  190711. *dp-- = *sp--;
  190712. *dp-- = *sp--;
  190713. *dp-- = *sp--;
  190714. }
  190715. }
  190716. else if (row_info->bit_depth == 16)
  190717. {
  190718. png_byte red_high = (trans_value->red >> 8) & 0xff;
  190719. png_byte green_high = (trans_value->green >> 8) & 0xff;
  190720. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  190721. png_byte red_low = trans_value->red & 0xff;
  190722. png_byte green_low = trans_value->green & 0xff;
  190723. png_byte blue_low = trans_value->blue & 0xff;
  190724. sp = row + row_info->rowbytes - 1;
  190725. dp = row + (png_size_t)(row_width << 3) - 1;
  190726. for (i = 0; i < row_width; i++)
  190727. {
  190728. if (*(sp - 5) == red_high &&
  190729. *(sp - 4) == red_low &&
  190730. *(sp - 3) == green_high &&
  190731. *(sp - 2) == green_low &&
  190732. *(sp - 1) == blue_high &&
  190733. *(sp ) == blue_low)
  190734. {
  190735. *dp-- = 0;
  190736. *dp-- = 0;
  190737. }
  190738. else
  190739. {
  190740. *dp-- = 0xff;
  190741. *dp-- = 0xff;
  190742. }
  190743. *dp-- = *sp--;
  190744. *dp-- = *sp--;
  190745. *dp-- = *sp--;
  190746. *dp-- = *sp--;
  190747. *dp-- = *sp--;
  190748. *dp-- = *sp--;
  190749. }
  190750. }
  190751. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  190752. row_info->channels = 4;
  190753. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  190754. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  190755. }
  190756. }
  190757. }
  190758. #endif
  190759. #if defined(PNG_READ_DITHER_SUPPORTED)
  190760. void /* PRIVATE */
  190761. png_do_dither(png_row_infop row_info, png_bytep row,
  190762. png_bytep palette_lookup, png_bytep dither_lookup)
  190763. {
  190764. png_bytep sp, dp;
  190765. png_uint_32 i;
  190766. png_uint_32 row_width=row_info->width;
  190767. png_debug(1, "in png_do_dither\n");
  190768. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190769. if (row != NULL && row_info != NULL)
  190770. #endif
  190771. {
  190772. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  190773. palette_lookup && row_info->bit_depth == 8)
  190774. {
  190775. int r, g, b, p;
  190776. sp = row;
  190777. dp = row;
  190778. for (i = 0; i < row_width; i++)
  190779. {
  190780. r = *sp++;
  190781. g = *sp++;
  190782. b = *sp++;
  190783. /* this looks real messy, but the compiler will reduce
  190784. it down to a reasonable formula. For example, with
  190785. 5 bits per color, we get:
  190786. p = (((r >> 3) & 0x1f) << 10) |
  190787. (((g >> 3) & 0x1f) << 5) |
  190788. ((b >> 3) & 0x1f);
  190789. */
  190790. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  190791. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  190792. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  190793. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  190794. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  190795. (PNG_DITHER_BLUE_BITS)) |
  190796. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  190797. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  190798. *dp++ = palette_lookup[p];
  190799. }
  190800. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  190801. row_info->channels = 1;
  190802. row_info->pixel_depth = row_info->bit_depth;
  190803. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  190804. }
  190805. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  190806. palette_lookup != NULL && row_info->bit_depth == 8)
  190807. {
  190808. int r, g, b, p;
  190809. sp = row;
  190810. dp = row;
  190811. for (i = 0; i < row_width; i++)
  190812. {
  190813. r = *sp++;
  190814. g = *sp++;
  190815. b = *sp++;
  190816. sp++;
  190817. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  190818. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  190819. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  190820. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  190821. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  190822. (PNG_DITHER_BLUE_BITS)) |
  190823. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  190824. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  190825. *dp++ = palette_lookup[p];
  190826. }
  190827. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  190828. row_info->channels = 1;
  190829. row_info->pixel_depth = row_info->bit_depth;
  190830. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  190831. }
  190832. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  190833. dither_lookup && row_info->bit_depth == 8)
  190834. {
  190835. sp = row;
  190836. for (i = 0; i < row_width; i++, sp++)
  190837. {
  190838. *sp = dither_lookup[*sp];
  190839. }
  190840. }
  190841. }
  190842. }
  190843. #endif
  190844. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190845. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190846. static PNG_CONST int png_gamma_shift[] =
  190847. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  190848. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  190849. * tables, we don't make a full table if we are reducing to 8-bit in
  190850. * the future. Note also how the gamma_16 tables are segmented so that
  190851. * we don't need to allocate > 64K chunks for a full 16-bit table.
  190852. */
  190853. void /* PRIVATE */
  190854. png_build_gamma_table(png_structp png_ptr)
  190855. {
  190856. png_debug(1, "in png_build_gamma_table\n");
  190857. if (png_ptr->bit_depth <= 8)
  190858. {
  190859. int i;
  190860. double g;
  190861. if (png_ptr->screen_gamma > .000001)
  190862. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190863. else
  190864. g = 1.0;
  190865. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  190866. (png_uint_32)256);
  190867. for (i = 0; i < 256; i++)
  190868. {
  190869. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  190870. g) * 255.0 + .5);
  190871. }
  190872. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  190873. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190874. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  190875. {
  190876. g = 1.0 / (png_ptr->gamma);
  190877. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  190878. (png_uint_32)256);
  190879. for (i = 0; i < 256; i++)
  190880. {
  190881. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  190882. g) * 255.0 + .5);
  190883. }
  190884. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  190885. (png_uint_32)256);
  190886. if(png_ptr->screen_gamma > 0.000001)
  190887. g = 1.0 / png_ptr->screen_gamma;
  190888. else
  190889. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  190890. for (i = 0; i < 256; i++)
  190891. {
  190892. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  190893. g) * 255.0 + .5);
  190894. }
  190895. }
  190896. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  190897. }
  190898. else
  190899. {
  190900. double g;
  190901. int i, j, shift, num;
  190902. int sig_bit;
  190903. png_uint_32 ig;
  190904. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190905. {
  190906. sig_bit = (int)png_ptr->sig_bit.red;
  190907. if ((int)png_ptr->sig_bit.green > sig_bit)
  190908. sig_bit = png_ptr->sig_bit.green;
  190909. if ((int)png_ptr->sig_bit.blue > sig_bit)
  190910. sig_bit = png_ptr->sig_bit.blue;
  190911. }
  190912. else
  190913. {
  190914. sig_bit = (int)png_ptr->sig_bit.gray;
  190915. }
  190916. if (sig_bit > 0)
  190917. shift = 16 - sig_bit;
  190918. else
  190919. shift = 0;
  190920. if (png_ptr->transformations & PNG_16_TO_8)
  190921. {
  190922. if (shift < (16 - PNG_MAX_GAMMA_8))
  190923. shift = (16 - PNG_MAX_GAMMA_8);
  190924. }
  190925. if (shift > 8)
  190926. shift = 8;
  190927. if (shift < 0)
  190928. shift = 0;
  190929. png_ptr->gamma_shift = (png_byte)shift;
  190930. num = (1 << (8 - shift));
  190931. if (png_ptr->screen_gamma > .000001)
  190932. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190933. else
  190934. g = 1.0;
  190935. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  190936. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  190937. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  190938. {
  190939. double fin, fout;
  190940. png_uint_32 last, max;
  190941. for (i = 0; i < num; i++)
  190942. {
  190943. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  190944. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  190945. }
  190946. g = 1.0 / g;
  190947. last = 0;
  190948. for (i = 0; i < 256; i++)
  190949. {
  190950. fout = ((double)i + 0.5) / 256.0;
  190951. fin = pow(fout, g);
  190952. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  190953. while (last <= max)
  190954. {
  190955. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  190956. [(int)(last >> (8 - shift))] = (png_uint_16)(
  190957. (png_uint_16)i | ((png_uint_16)i << 8));
  190958. last++;
  190959. }
  190960. }
  190961. while (last < ((png_uint_32)num << 8))
  190962. {
  190963. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  190964. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  190965. last++;
  190966. }
  190967. }
  190968. else
  190969. {
  190970. for (i = 0; i < num; i++)
  190971. {
  190972. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  190973. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  190974. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  190975. for (j = 0; j < 256; j++)
  190976. {
  190977. png_ptr->gamma_16_table[i][j] =
  190978. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  190979. 65535.0, g) * 65535.0 + .5);
  190980. }
  190981. }
  190982. }
  190983. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  190984. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190985. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  190986. {
  190987. g = 1.0 / (png_ptr->gamma);
  190988. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  190989. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  190990. for (i = 0; i < num; i++)
  190991. {
  190992. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  190993. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  190994. ig = (((png_uint_32)i *
  190995. (png_uint_32)png_gamma_shift[shift]) >> 4);
  190996. for (j = 0; j < 256; j++)
  190997. {
  190998. png_ptr->gamma_16_to_1[i][j] =
  190999. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  191000. 65535.0, g) * 65535.0 + .5);
  191001. }
  191002. }
  191003. if(png_ptr->screen_gamma > 0.000001)
  191004. g = 1.0 / png_ptr->screen_gamma;
  191005. else
  191006. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  191007. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  191008. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  191009. for (i = 0; i < num; i++)
  191010. {
  191011. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  191012. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  191013. ig = (((png_uint_32)i *
  191014. (png_uint_32)png_gamma_shift[shift]) >> 4);
  191015. for (j = 0; j < 256; j++)
  191016. {
  191017. png_ptr->gamma_16_from_1[i][j] =
  191018. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  191019. 65535.0, g) * 65535.0 + .5);
  191020. }
  191021. }
  191022. }
  191023. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  191024. }
  191025. }
  191026. #endif
  191027. /* To do: install integer version of png_build_gamma_table here */
  191028. #endif
  191029. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  191030. /* undoes intrapixel differencing */
  191031. void /* PRIVATE */
  191032. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  191033. {
  191034. png_debug(1, "in png_do_read_intrapixel\n");
  191035. if (
  191036. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191037. row != NULL && row_info != NULL &&
  191038. #endif
  191039. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  191040. {
  191041. int bytes_per_pixel;
  191042. png_uint_32 row_width = row_info->width;
  191043. if (row_info->bit_depth == 8)
  191044. {
  191045. png_bytep rp;
  191046. png_uint_32 i;
  191047. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191048. bytes_per_pixel = 3;
  191049. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191050. bytes_per_pixel = 4;
  191051. else
  191052. return;
  191053. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  191054. {
  191055. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  191056. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  191057. }
  191058. }
  191059. else if (row_info->bit_depth == 16)
  191060. {
  191061. png_bytep rp;
  191062. png_uint_32 i;
  191063. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191064. bytes_per_pixel = 6;
  191065. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191066. bytes_per_pixel = 8;
  191067. else
  191068. return;
  191069. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  191070. {
  191071. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  191072. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  191073. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  191074. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  191075. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  191076. *(rp ) = (png_byte)((red >> 8) & 0xff);
  191077. *(rp+1) = (png_byte)(red & 0xff);
  191078. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  191079. *(rp+5) = (png_byte)(blue & 0xff);
  191080. }
  191081. }
  191082. }
  191083. }
  191084. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  191085. #endif /* PNG_READ_SUPPORTED */
  191086. /*** End of inlined file: pngrtran.c ***/
  191087. /*** Start of inlined file: pngrutil.c ***/
  191088. /* pngrutil.c - utilities to read a PNG file
  191089. *
  191090. * Last changed in libpng 1.2.21 [October 4, 2007]
  191091. * For conditions of distribution and use, see copyright notice in png.h
  191092. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  191093. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  191094. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  191095. *
  191096. * This file contains routines that are only called from within
  191097. * libpng itself during the course of reading an image.
  191098. */
  191099. #define PNG_INTERNAL
  191100. #if defined(PNG_READ_SUPPORTED)
  191101. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  191102. # define WIN32_WCE_OLD
  191103. #endif
  191104. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191105. # if defined(WIN32_WCE_OLD)
  191106. /* strtod() function is not supported on WindowsCE */
  191107. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  191108. {
  191109. double result = 0;
  191110. int len;
  191111. wchar_t *str, *end;
  191112. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  191113. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  191114. if ( NULL != str )
  191115. {
  191116. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  191117. result = wcstod(str, &end);
  191118. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  191119. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  191120. png_free(png_ptr, str);
  191121. }
  191122. return result;
  191123. }
  191124. # else
  191125. # define png_strtod(p,a,b) strtod(a,b)
  191126. # endif
  191127. #endif
  191128. png_uint_32 PNGAPI
  191129. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  191130. {
  191131. png_uint_32 i = png_get_uint_32(buf);
  191132. if (i > PNG_UINT_31_MAX)
  191133. png_error(png_ptr, "PNG unsigned integer out of range.");
  191134. return (i);
  191135. }
  191136. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  191137. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  191138. png_uint_32 PNGAPI
  191139. png_get_uint_32(png_bytep buf)
  191140. {
  191141. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  191142. ((png_uint_32)(*(buf + 1)) << 16) +
  191143. ((png_uint_32)(*(buf + 2)) << 8) +
  191144. (png_uint_32)(*(buf + 3));
  191145. return (i);
  191146. }
  191147. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  191148. * data is stored in the PNG file in two's complement format, and it is
  191149. * assumed that the machine format for signed integers is the same. */
  191150. png_int_32 PNGAPI
  191151. png_get_int_32(png_bytep buf)
  191152. {
  191153. png_int_32 i = ((png_int_32)(*buf) << 24) +
  191154. ((png_int_32)(*(buf + 1)) << 16) +
  191155. ((png_int_32)(*(buf + 2)) << 8) +
  191156. (png_int_32)(*(buf + 3));
  191157. return (i);
  191158. }
  191159. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  191160. png_uint_16 PNGAPI
  191161. png_get_uint_16(png_bytep buf)
  191162. {
  191163. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  191164. (png_uint_16)(*(buf + 1)));
  191165. return (i);
  191166. }
  191167. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  191168. /* Read data, and (optionally) run it through the CRC. */
  191169. void /* PRIVATE */
  191170. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  191171. {
  191172. if(png_ptr == NULL) return;
  191173. png_read_data(png_ptr, buf, length);
  191174. png_calculate_crc(png_ptr, buf, length);
  191175. }
  191176. /* Optionally skip data and then check the CRC. Depending on whether we
  191177. are reading a ancillary or critical chunk, and how the program has set
  191178. things up, we may calculate the CRC on the data and print a message.
  191179. Returns '1' if there was a CRC error, '0' otherwise. */
  191180. int /* PRIVATE */
  191181. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  191182. {
  191183. png_size_t i;
  191184. png_size_t istop = png_ptr->zbuf_size;
  191185. for (i = (png_size_t)skip; i > istop; i -= istop)
  191186. {
  191187. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  191188. }
  191189. if (i)
  191190. {
  191191. png_crc_read(png_ptr, png_ptr->zbuf, i);
  191192. }
  191193. if (png_crc_error(png_ptr))
  191194. {
  191195. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  191196. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  191197. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  191198. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  191199. {
  191200. png_chunk_warning(png_ptr, "CRC error");
  191201. }
  191202. else
  191203. {
  191204. png_chunk_error(png_ptr, "CRC error");
  191205. }
  191206. return (1);
  191207. }
  191208. return (0);
  191209. }
  191210. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  191211. the data it has read thus far. */
  191212. int /* PRIVATE */
  191213. png_crc_error(png_structp png_ptr)
  191214. {
  191215. png_byte crc_bytes[4];
  191216. png_uint_32 crc;
  191217. int need_crc = 1;
  191218. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  191219. {
  191220. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  191221. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  191222. need_crc = 0;
  191223. }
  191224. else /* critical */
  191225. {
  191226. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  191227. need_crc = 0;
  191228. }
  191229. png_read_data(png_ptr, crc_bytes, 4);
  191230. if (need_crc)
  191231. {
  191232. crc = png_get_uint_32(crc_bytes);
  191233. return ((int)(crc != png_ptr->crc));
  191234. }
  191235. else
  191236. return (0);
  191237. }
  191238. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  191239. defined(PNG_READ_iCCP_SUPPORTED)
  191240. /*
  191241. * Decompress trailing data in a chunk. The assumption is that chunkdata
  191242. * points at an allocated area holding the contents of a chunk with a
  191243. * trailing compressed part. What we get back is an allocated area
  191244. * holding the original prefix part and an uncompressed version of the
  191245. * trailing part (the malloc area passed in is freed).
  191246. */
  191247. png_charp /* PRIVATE */
  191248. png_decompress_chunk(png_structp png_ptr, int comp_type,
  191249. png_charp chunkdata, png_size_t chunklength,
  191250. png_size_t prefix_size, png_size_t *newlength)
  191251. {
  191252. static PNG_CONST char msg[] = "Error decoding compressed text";
  191253. png_charp text;
  191254. png_size_t text_size;
  191255. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  191256. {
  191257. int ret = Z_OK;
  191258. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  191259. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  191260. png_ptr->zstream.next_out = png_ptr->zbuf;
  191261. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  191262. text_size = 0;
  191263. text = NULL;
  191264. while (png_ptr->zstream.avail_in)
  191265. {
  191266. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  191267. if (ret != Z_OK && ret != Z_STREAM_END)
  191268. {
  191269. if (png_ptr->zstream.msg != NULL)
  191270. png_warning(png_ptr, png_ptr->zstream.msg);
  191271. else
  191272. png_warning(png_ptr, msg);
  191273. inflateReset(&png_ptr->zstream);
  191274. png_ptr->zstream.avail_in = 0;
  191275. if (text == NULL)
  191276. {
  191277. text_size = prefix_size + png_sizeof(msg) + 1;
  191278. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  191279. if (text == NULL)
  191280. {
  191281. png_free(png_ptr,chunkdata);
  191282. png_error(png_ptr,"Not enough memory to decompress chunk");
  191283. }
  191284. png_memcpy(text, chunkdata, prefix_size);
  191285. }
  191286. text[text_size - 1] = 0x00;
  191287. /* Copy what we can of the error message into the text chunk */
  191288. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  191289. text_size = png_sizeof(msg) > text_size ? text_size :
  191290. png_sizeof(msg);
  191291. png_memcpy(text + prefix_size, msg, text_size + 1);
  191292. break;
  191293. }
  191294. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  191295. {
  191296. if (text == NULL)
  191297. {
  191298. text_size = prefix_size +
  191299. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  191300. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  191301. if (text == NULL)
  191302. {
  191303. png_free(png_ptr,chunkdata);
  191304. png_error(png_ptr,"Not enough memory to decompress chunk.");
  191305. }
  191306. png_memcpy(text + prefix_size, png_ptr->zbuf,
  191307. text_size - prefix_size);
  191308. png_memcpy(text, chunkdata, prefix_size);
  191309. *(text + text_size) = 0x00;
  191310. }
  191311. else
  191312. {
  191313. png_charp tmp;
  191314. tmp = text;
  191315. text = (png_charp)png_malloc_warn(png_ptr,
  191316. (png_uint_32)(text_size +
  191317. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  191318. if (text == NULL)
  191319. {
  191320. png_free(png_ptr, tmp);
  191321. png_free(png_ptr, chunkdata);
  191322. png_error(png_ptr,"Not enough memory to decompress chunk..");
  191323. }
  191324. png_memcpy(text, tmp, text_size);
  191325. png_free(png_ptr, tmp);
  191326. png_memcpy(text + text_size, png_ptr->zbuf,
  191327. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  191328. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  191329. *(text + text_size) = 0x00;
  191330. }
  191331. if (ret == Z_STREAM_END)
  191332. break;
  191333. else
  191334. {
  191335. png_ptr->zstream.next_out = png_ptr->zbuf;
  191336. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  191337. }
  191338. }
  191339. }
  191340. if (ret != Z_STREAM_END)
  191341. {
  191342. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  191343. char umsg[52];
  191344. if (ret == Z_BUF_ERROR)
  191345. png_snprintf(umsg, 52,
  191346. "Buffer error in compressed datastream in %s chunk",
  191347. png_ptr->chunk_name);
  191348. else if (ret == Z_DATA_ERROR)
  191349. png_snprintf(umsg, 52,
  191350. "Data error in compressed datastream in %s chunk",
  191351. png_ptr->chunk_name);
  191352. else
  191353. png_snprintf(umsg, 52,
  191354. "Incomplete compressed datastream in %s chunk",
  191355. png_ptr->chunk_name);
  191356. png_warning(png_ptr, umsg);
  191357. #else
  191358. png_warning(png_ptr,
  191359. "Incomplete compressed datastream in chunk other than IDAT");
  191360. #endif
  191361. text_size=prefix_size;
  191362. if (text == NULL)
  191363. {
  191364. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  191365. if (text == NULL)
  191366. {
  191367. png_free(png_ptr, chunkdata);
  191368. png_error(png_ptr,"Not enough memory for text.");
  191369. }
  191370. png_memcpy(text, chunkdata, prefix_size);
  191371. }
  191372. *(text + text_size) = 0x00;
  191373. }
  191374. inflateReset(&png_ptr->zstream);
  191375. png_ptr->zstream.avail_in = 0;
  191376. png_free(png_ptr, chunkdata);
  191377. chunkdata = text;
  191378. *newlength=text_size;
  191379. }
  191380. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  191381. {
  191382. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  191383. char umsg[50];
  191384. png_snprintf(umsg, 50,
  191385. "Unknown zTXt compression type %d", comp_type);
  191386. png_warning(png_ptr, umsg);
  191387. #else
  191388. png_warning(png_ptr, "Unknown zTXt compression type");
  191389. #endif
  191390. *(chunkdata + prefix_size) = 0x00;
  191391. *newlength=prefix_size;
  191392. }
  191393. return chunkdata;
  191394. }
  191395. #endif
  191396. /* read and check the IDHR chunk */
  191397. void /* PRIVATE */
  191398. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191399. {
  191400. png_byte buf[13];
  191401. png_uint_32 width, height;
  191402. int bit_depth, color_type, compression_type, filter_type;
  191403. int interlace_type;
  191404. png_debug(1, "in png_handle_IHDR\n");
  191405. if (png_ptr->mode & PNG_HAVE_IHDR)
  191406. png_error(png_ptr, "Out of place IHDR");
  191407. /* check the length */
  191408. if (length != 13)
  191409. png_error(png_ptr, "Invalid IHDR chunk");
  191410. png_ptr->mode |= PNG_HAVE_IHDR;
  191411. png_crc_read(png_ptr, buf, 13);
  191412. png_crc_finish(png_ptr, 0);
  191413. width = png_get_uint_31(png_ptr, buf);
  191414. height = png_get_uint_31(png_ptr, buf + 4);
  191415. bit_depth = buf[8];
  191416. color_type = buf[9];
  191417. compression_type = buf[10];
  191418. filter_type = buf[11];
  191419. interlace_type = buf[12];
  191420. /* set internal variables */
  191421. png_ptr->width = width;
  191422. png_ptr->height = height;
  191423. png_ptr->bit_depth = (png_byte)bit_depth;
  191424. png_ptr->interlaced = (png_byte)interlace_type;
  191425. png_ptr->color_type = (png_byte)color_type;
  191426. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  191427. png_ptr->filter_type = (png_byte)filter_type;
  191428. #endif
  191429. png_ptr->compression_type = (png_byte)compression_type;
  191430. /* find number of channels */
  191431. switch (png_ptr->color_type)
  191432. {
  191433. case PNG_COLOR_TYPE_GRAY:
  191434. case PNG_COLOR_TYPE_PALETTE:
  191435. png_ptr->channels = 1;
  191436. break;
  191437. case PNG_COLOR_TYPE_RGB:
  191438. png_ptr->channels = 3;
  191439. break;
  191440. case PNG_COLOR_TYPE_GRAY_ALPHA:
  191441. png_ptr->channels = 2;
  191442. break;
  191443. case PNG_COLOR_TYPE_RGB_ALPHA:
  191444. png_ptr->channels = 4;
  191445. break;
  191446. }
  191447. /* set up other useful info */
  191448. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  191449. png_ptr->channels);
  191450. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  191451. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  191452. png_debug1(3,"channels = %d\n", png_ptr->channels);
  191453. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  191454. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  191455. color_type, interlace_type, compression_type, filter_type);
  191456. }
  191457. /* read and check the palette */
  191458. void /* PRIVATE */
  191459. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191460. {
  191461. png_color palette[PNG_MAX_PALETTE_LENGTH];
  191462. int num, i;
  191463. #ifndef PNG_NO_POINTER_INDEXING
  191464. png_colorp pal_ptr;
  191465. #endif
  191466. png_debug(1, "in png_handle_PLTE\n");
  191467. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191468. png_error(png_ptr, "Missing IHDR before PLTE");
  191469. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191470. {
  191471. png_warning(png_ptr, "Invalid PLTE after IDAT");
  191472. png_crc_finish(png_ptr, length);
  191473. return;
  191474. }
  191475. else if (png_ptr->mode & PNG_HAVE_PLTE)
  191476. png_error(png_ptr, "Duplicate PLTE chunk");
  191477. png_ptr->mode |= PNG_HAVE_PLTE;
  191478. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  191479. {
  191480. png_warning(png_ptr,
  191481. "Ignoring PLTE chunk in grayscale PNG");
  191482. png_crc_finish(png_ptr, length);
  191483. return;
  191484. }
  191485. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  191486. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  191487. {
  191488. png_crc_finish(png_ptr, length);
  191489. return;
  191490. }
  191491. #endif
  191492. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  191493. {
  191494. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  191495. {
  191496. png_warning(png_ptr, "Invalid palette chunk");
  191497. png_crc_finish(png_ptr, length);
  191498. return;
  191499. }
  191500. else
  191501. {
  191502. png_error(png_ptr, "Invalid palette chunk");
  191503. }
  191504. }
  191505. num = (int)length / 3;
  191506. #ifndef PNG_NO_POINTER_INDEXING
  191507. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  191508. {
  191509. png_byte buf[3];
  191510. png_crc_read(png_ptr, buf, 3);
  191511. pal_ptr->red = buf[0];
  191512. pal_ptr->green = buf[1];
  191513. pal_ptr->blue = buf[2];
  191514. }
  191515. #else
  191516. for (i = 0; i < num; i++)
  191517. {
  191518. png_byte buf[3];
  191519. png_crc_read(png_ptr, buf, 3);
  191520. /* don't depend upon png_color being any order */
  191521. palette[i].red = buf[0];
  191522. palette[i].green = buf[1];
  191523. palette[i].blue = buf[2];
  191524. }
  191525. #endif
  191526. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  191527. whatever the normal CRC configuration tells us. However, if we
  191528. have an RGB image, the PLTE can be considered ancillary, so
  191529. we will act as though it is. */
  191530. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  191531. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191532. #endif
  191533. {
  191534. png_crc_finish(png_ptr, 0);
  191535. }
  191536. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  191537. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  191538. {
  191539. /* If we don't want to use the data from an ancillary chunk,
  191540. we have two options: an error abort, or a warning and we
  191541. ignore the data in this chunk (which should be OK, since
  191542. it's considered ancillary for a RGB or RGBA image). */
  191543. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  191544. {
  191545. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  191546. {
  191547. png_chunk_error(png_ptr, "CRC error");
  191548. }
  191549. else
  191550. {
  191551. png_chunk_warning(png_ptr, "CRC error");
  191552. return;
  191553. }
  191554. }
  191555. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  191556. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  191557. {
  191558. png_chunk_warning(png_ptr, "CRC error");
  191559. }
  191560. }
  191561. #endif
  191562. png_set_PLTE(png_ptr, info_ptr, palette, num);
  191563. #if defined(PNG_READ_tRNS_SUPPORTED)
  191564. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191565. {
  191566. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  191567. {
  191568. if (png_ptr->num_trans > (png_uint_16)num)
  191569. {
  191570. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  191571. png_ptr->num_trans = (png_uint_16)num;
  191572. }
  191573. if (info_ptr->num_trans > (png_uint_16)num)
  191574. {
  191575. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  191576. info_ptr->num_trans = (png_uint_16)num;
  191577. }
  191578. }
  191579. }
  191580. #endif
  191581. }
  191582. void /* PRIVATE */
  191583. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191584. {
  191585. png_debug(1, "in png_handle_IEND\n");
  191586. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  191587. {
  191588. png_error(png_ptr, "No image in file");
  191589. }
  191590. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  191591. if (length != 0)
  191592. {
  191593. png_warning(png_ptr, "Incorrect IEND chunk length");
  191594. }
  191595. png_crc_finish(png_ptr, length);
  191596. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  191597. }
  191598. #if defined(PNG_READ_gAMA_SUPPORTED)
  191599. void /* PRIVATE */
  191600. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191601. {
  191602. png_fixed_point igamma;
  191603. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191604. float file_gamma;
  191605. #endif
  191606. png_byte buf[4];
  191607. png_debug(1, "in png_handle_gAMA\n");
  191608. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191609. png_error(png_ptr, "Missing IHDR before gAMA");
  191610. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191611. {
  191612. png_warning(png_ptr, "Invalid gAMA after IDAT");
  191613. png_crc_finish(png_ptr, length);
  191614. return;
  191615. }
  191616. else if (png_ptr->mode & PNG_HAVE_PLTE)
  191617. /* Should be an error, but we can cope with it */
  191618. png_warning(png_ptr, "Out of place gAMA chunk");
  191619. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  191620. #if defined(PNG_READ_sRGB_SUPPORTED)
  191621. && !(info_ptr->valid & PNG_INFO_sRGB)
  191622. #endif
  191623. )
  191624. {
  191625. png_warning(png_ptr, "Duplicate gAMA chunk");
  191626. png_crc_finish(png_ptr, length);
  191627. return;
  191628. }
  191629. if (length != 4)
  191630. {
  191631. png_warning(png_ptr, "Incorrect gAMA chunk length");
  191632. png_crc_finish(png_ptr, length);
  191633. return;
  191634. }
  191635. png_crc_read(png_ptr, buf, 4);
  191636. if (png_crc_finish(png_ptr, 0))
  191637. return;
  191638. igamma = (png_fixed_point)png_get_uint_32(buf);
  191639. /* check for zero gamma */
  191640. if (igamma == 0)
  191641. {
  191642. png_warning(png_ptr,
  191643. "Ignoring gAMA chunk with gamma=0");
  191644. return;
  191645. }
  191646. #if defined(PNG_READ_sRGB_SUPPORTED)
  191647. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  191648. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  191649. {
  191650. png_warning(png_ptr,
  191651. "Ignoring incorrect gAMA value when sRGB is also present");
  191652. #ifndef PNG_NO_CONSOLE_IO
  191653. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  191654. #endif
  191655. return;
  191656. }
  191657. #endif /* PNG_READ_sRGB_SUPPORTED */
  191658. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191659. file_gamma = (float)igamma / (float)100000.0;
  191660. # ifdef PNG_READ_GAMMA_SUPPORTED
  191661. png_ptr->gamma = file_gamma;
  191662. # endif
  191663. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  191664. #endif
  191665. #ifdef PNG_FIXED_POINT_SUPPORTED
  191666. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  191667. #endif
  191668. }
  191669. #endif
  191670. #if defined(PNG_READ_sBIT_SUPPORTED)
  191671. void /* PRIVATE */
  191672. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191673. {
  191674. png_size_t truelen;
  191675. png_byte buf[4];
  191676. png_debug(1, "in png_handle_sBIT\n");
  191677. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  191678. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191679. png_error(png_ptr, "Missing IHDR before sBIT");
  191680. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191681. {
  191682. png_warning(png_ptr, "Invalid sBIT after IDAT");
  191683. png_crc_finish(png_ptr, length);
  191684. return;
  191685. }
  191686. else if (png_ptr->mode & PNG_HAVE_PLTE)
  191687. {
  191688. /* Should be an error, but we can cope with it */
  191689. png_warning(png_ptr, "Out of place sBIT chunk");
  191690. }
  191691. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  191692. {
  191693. png_warning(png_ptr, "Duplicate sBIT chunk");
  191694. png_crc_finish(png_ptr, length);
  191695. return;
  191696. }
  191697. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191698. truelen = 3;
  191699. else
  191700. truelen = (png_size_t)png_ptr->channels;
  191701. if (length != truelen || length > 4)
  191702. {
  191703. png_warning(png_ptr, "Incorrect sBIT chunk length");
  191704. png_crc_finish(png_ptr, length);
  191705. return;
  191706. }
  191707. png_crc_read(png_ptr, buf, truelen);
  191708. if (png_crc_finish(png_ptr, 0))
  191709. return;
  191710. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  191711. {
  191712. png_ptr->sig_bit.red = buf[0];
  191713. png_ptr->sig_bit.green = buf[1];
  191714. png_ptr->sig_bit.blue = buf[2];
  191715. png_ptr->sig_bit.alpha = buf[3];
  191716. }
  191717. else
  191718. {
  191719. png_ptr->sig_bit.gray = buf[0];
  191720. png_ptr->sig_bit.red = buf[0];
  191721. png_ptr->sig_bit.green = buf[0];
  191722. png_ptr->sig_bit.blue = buf[0];
  191723. png_ptr->sig_bit.alpha = buf[1];
  191724. }
  191725. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  191726. }
  191727. #endif
  191728. #if defined(PNG_READ_cHRM_SUPPORTED)
  191729. void /* PRIVATE */
  191730. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191731. {
  191732. png_byte buf[4];
  191733. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191734. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  191735. #endif
  191736. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  191737. int_y_green, int_x_blue, int_y_blue;
  191738. png_uint_32 uint_x, uint_y;
  191739. png_debug(1, "in png_handle_cHRM\n");
  191740. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191741. png_error(png_ptr, "Missing IHDR before cHRM");
  191742. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191743. {
  191744. png_warning(png_ptr, "Invalid cHRM after IDAT");
  191745. png_crc_finish(png_ptr, length);
  191746. return;
  191747. }
  191748. else if (png_ptr->mode & PNG_HAVE_PLTE)
  191749. /* Should be an error, but we can cope with it */
  191750. png_warning(png_ptr, "Missing PLTE before cHRM");
  191751. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  191752. #if defined(PNG_READ_sRGB_SUPPORTED)
  191753. && !(info_ptr->valid & PNG_INFO_sRGB)
  191754. #endif
  191755. )
  191756. {
  191757. png_warning(png_ptr, "Duplicate cHRM chunk");
  191758. png_crc_finish(png_ptr, length);
  191759. return;
  191760. }
  191761. if (length != 32)
  191762. {
  191763. png_warning(png_ptr, "Incorrect cHRM chunk length");
  191764. png_crc_finish(png_ptr, length);
  191765. return;
  191766. }
  191767. png_crc_read(png_ptr, buf, 4);
  191768. uint_x = png_get_uint_32(buf);
  191769. png_crc_read(png_ptr, buf, 4);
  191770. uint_y = png_get_uint_32(buf);
  191771. if (uint_x > 80000L || uint_y > 80000L ||
  191772. uint_x + uint_y > 100000L)
  191773. {
  191774. png_warning(png_ptr, "Invalid cHRM white point");
  191775. png_crc_finish(png_ptr, 24);
  191776. return;
  191777. }
  191778. int_x_white = (png_fixed_point)uint_x;
  191779. int_y_white = (png_fixed_point)uint_y;
  191780. png_crc_read(png_ptr, buf, 4);
  191781. uint_x = png_get_uint_32(buf);
  191782. png_crc_read(png_ptr, buf, 4);
  191783. uint_y = png_get_uint_32(buf);
  191784. if (uint_x + uint_y > 100000L)
  191785. {
  191786. png_warning(png_ptr, "Invalid cHRM red point");
  191787. png_crc_finish(png_ptr, 16);
  191788. return;
  191789. }
  191790. int_x_red = (png_fixed_point)uint_x;
  191791. int_y_red = (png_fixed_point)uint_y;
  191792. png_crc_read(png_ptr, buf, 4);
  191793. uint_x = png_get_uint_32(buf);
  191794. png_crc_read(png_ptr, buf, 4);
  191795. uint_y = png_get_uint_32(buf);
  191796. if (uint_x + uint_y > 100000L)
  191797. {
  191798. png_warning(png_ptr, "Invalid cHRM green point");
  191799. png_crc_finish(png_ptr, 8);
  191800. return;
  191801. }
  191802. int_x_green = (png_fixed_point)uint_x;
  191803. int_y_green = (png_fixed_point)uint_y;
  191804. png_crc_read(png_ptr, buf, 4);
  191805. uint_x = png_get_uint_32(buf);
  191806. png_crc_read(png_ptr, buf, 4);
  191807. uint_y = png_get_uint_32(buf);
  191808. if (uint_x + uint_y > 100000L)
  191809. {
  191810. png_warning(png_ptr, "Invalid cHRM blue point");
  191811. png_crc_finish(png_ptr, 0);
  191812. return;
  191813. }
  191814. int_x_blue = (png_fixed_point)uint_x;
  191815. int_y_blue = (png_fixed_point)uint_y;
  191816. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191817. white_x = (float)int_x_white / (float)100000.0;
  191818. white_y = (float)int_y_white / (float)100000.0;
  191819. red_x = (float)int_x_red / (float)100000.0;
  191820. red_y = (float)int_y_red / (float)100000.0;
  191821. green_x = (float)int_x_green / (float)100000.0;
  191822. green_y = (float)int_y_green / (float)100000.0;
  191823. blue_x = (float)int_x_blue / (float)100000.0;
  191824. blue_y = (float)int_y_blue / (float)100000.0;
  191825. #endif
  191826. #if defined(PNG_READ_sRGB_SUPPORTED)
  191827. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  191828. {
  191829. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  191830. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  191831. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  191832. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  191833. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  191834. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  191835. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  191836. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  191837. {
  191838. png_warning(png_ptr,
  191839. "Ignoring incorrect cHRM value when sRGB is also present");
  191840. #ifndef PNG_NO_CONSOLE_IO
  191841. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191842. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  191843. white_x, white_y, red_x, red_y);
  191844. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  191845. green_x, green_y, blue_x, blue_y);
  191846. #else
  191847. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  191848. int_x_white, int_y_white, int_x_red, int_y_red);
  191849. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  191850. int_x_green, int_y_green, int_x_blue, int_y_blue);
  191851. #endif
  191852. #endif /* PNG_NO_CONSOLE_IO */
  191853. }
  191854. png_crc_finish(png_ptr, 0);
  191855. return;
  191856. }
  191857. #endif /* PNG_READ_sRGB_SUPPORTED */
  191858. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191859. png_set_cHRM(png_ptr, info_ptr,
  191860. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  191861. #endif
  191862. #ifdef PNG_FIXED_POINT_SUPPORTED
  191863. png_set_cHRM_fixed(png_ptr, info_ptr,
  191864. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  191865. int_y_green, int_x_blue, int_y_blue);
  191866. #endif
  191867. if (png_crc_finish(png_ptr, 0))
  191868. return;
  191869. }
  191870. #endif
  191871. #if defined(PNG_READ_sRGB_SUPPORTED)
  191872. void /* PRIVATE */
  191873. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191874. {
  191875. int intent;
  191876. png_byte buf[1];
  191877. png_debug(1, "in png_handle_sRGB\n");
  191878. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191879. png_error(png_ptr, "Missing IHDR before sRGB");
  191880. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191881. {
  191882. png_warning(png_ptr, "Invalid sRGB after IDAT");
  191883. png_crc_finish(png_ptr, length);
  191884. return;
  191885. }
  191886. else if (png_ptr->mode & PNG_HAVE_PLTE)
  191887. /* Should be an error, but we can cope with it */
  191888. png_warning(png_ptr, "Out of place sRGB chunk");
  191889. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  191890. {
  191891. png_warning(png_ptr, "Duplicate sRGB chunk");
  191892. png_crc_finish(png_ptr, length);
  191893. return;
  191894. }
  191895. if (length != 1)
  191896. {
  191897. png_warning(png_ptr, "Incorrect sRGB chunk length");
  191898. png_crc_finish(png_ptr, length);
  191899. return;
  191900. }
  191901. png_crc_read(png_ptr, buf, 1);
  191902. if (png_crc_finish(png_ptr, 0))
  191903. return;
  191904. intent = buf[0];
  191905. /* check for bad intent */
  191906. if (intent >= PNG_sRGB_INTENT_LAST)
  191907. {
  191908. png_warning(png_ptr, "Unknown sRGB intent");
  191909. return;
  191910. }
  191911. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  191912. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  191913. {
  191914. png_fixed_point igamma;
  191915. #ifdef PNG_FIXED_POINT_SUPPORTED
  191916. igamma=info_ptr->int_gamma;
  191917. #else
  191918. # ifdef PNG_FLOATING_POINT_SUPPORTED
  191919. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  191920. # endif
  191921. #endif
  191922. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  191923. {
  191924. png_warning(png_ptr,
  191925. "Ignoring incorrect gAMA value when sRGB is also present");
  191926. #ifndef PNG_NO_CONSOLE_IO
  191927. # ifdef PNG_FIXED_POINT_SUPPORTED
  191928. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  191929. # else
  191930. # ifdef PNG_FLOATING_POINT_SUPPORTED
  191931. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  191932. # endif
  191933. # endif
  191934. #endif
  191935. }
  191936. }
  191937. #endif /* PNG_READ_gAMA_SUPPORTED */
  191938. #ifdef PNG_READ_cHRM_SUPPORTED
  191939. #ifdef PNG_FIXED_POINT_SUPPORTED
  191940. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  191941. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  191942. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  191943. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  191944. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  191945. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  191946. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  191947. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  191948. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  191949. {
  191950. png_warning(png_ptr,
  191951. "Ignoring incorrect cHRM value when sRGB is also present");
  191952. }
  191953. #endif /* PNG_FIXED_POINT_SUPPORTED */
  191954. #endif /* PNG_READ_cHRM_SUPPORTED */
  191955. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  191956. }
  191957. #endif /* PNG_READ_sRGB_SUPPORTED */
  191958. #if defined(PNG_READ_iCCP_SUPPORTED)
  191959. void /* PRIVATE */
  191960. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191961. /* Note: this does not properly handle chunks that are > 64K under DOS */
  191962. {
  191963. png_charp chunkdata;
  191964. png_byte compression_type;
  191965. png_bytep pC;
  191966. png_charp profile;
  191967. png_uint_32 skip = 0;
  191968. png_uint_32 profile_size, profile_length;
  191969. png_size_t slength, prefix_length, data_length;
  191970. png_debug(1, "in png_handle_iCCP\n");
  191971. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191972. png_error(png_ptr, "Missing IHDR before iCCP");
  191973. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191974. {
  191975. png_warning(png_ptr, "Invalid iCCP after IDAT");
  191976. png_crc_finish(png_ptr, length);
  191977. return;
  191978. }
  191979. else if (png_ptr->mode & PNG_HAVE_PLTE)
  191980. /* Should be an error, but we can cope with it */
  191981. png_warning(png_ptr, "Out of place iCCP chunk");
  191982. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  191983. {
  191984. png_warning(png_ptr, "Duplicate iCCP chunk");
  191985. png_crc_finish(png_ptr, length);
  191986. return;
  191987. }
  191988. #ifdef PNG_MAX_MALLOC_64K
  191989. if (length > (png_uint_32)65535L)
  191990. {
  191991. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  191992. skip = length - (png_uint_32)65535L;
  191993. length = (png_uint_32)65535L;
  191994. }
  191995. #endif
  191996. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  191997. slength = (png_size_t)length;
  191998. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  191999. if (png_crc_finish(png_ptr, skip))
  192000. {
  192001. png_free(png_ptr, chunkdata);
  192002. return;
  192003. }
  192004. chunkdata[slength] = 0x00;
  192005. for (profile = chunkdata; *profile; profile++)
  192006. /* empty loop to find end of name */ ;
  192007. ++profile;
  192008. /* there should be at least one zero (the compression type byte)
  192009. following the separator, and we should be on it */
  192010. if ( profile >= chunkdata + slength - 1)
  192011. {
  192012. png_free(png_ptr, chunkdata);
  192013. png_warning(png_ptr, "Malformed iCCP chunk");
  192014. return;
  192015. }
  192016. /* compression_type should always be zero */
  192017. compression_type = *profile++;
  192018. if (compression_type)
  192019. {
  192020. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  192021. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  192022. wrote nonzero) */
  192023. }
  192024. prefix_length = profile - chunkdata;
  192025. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  192026. slength, prefix_length, &data_length);
  192027. profile_length = data_length - prefix_length;
  192028. if ( prefix_length > data_length || profile_length < 4)
  192029. {
  192030. png_free(png_ptr, chunkdata);
  192031. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  192032. return;
  192033. }
  192034. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  192035. pC = (png_bytep)(chunkdata+prefix_length);
  192036. profile_size = ((*(pC ))<<24) |
  192037. ((*(pC+1))<<16) |
  192038. ((*(pC+2))<< 8) |
  192039. ((*(pC+3)) );
  192040. if(profile_size < profile_length)
  192041. profile_length = profile_size;
  192042. if(profile_size > profile_length)
  192043. {
  192044. png_free(png_ptr, chunkdata);
  192045. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  192046. return;
  192047. }
  192048. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  192049. chunkdata + prefix_length, profile_length);
  192050. png_free(png_ptr, chunkdata);
  192051. }
  192052. #endif /* PNG_READ_iCCP_SUPPORTED */
  192053. #if defined(PNG_READ_sPLT_SUPPORTED)
  192054. void /* PRIVATE */
  192055. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192056. /* Note: this does not properly handle chunks that are > 64K under DOS */
  192057. {
  192058. png_bytep chunkdata;
  192059. png_bytep entry_start;
  192060. png_sPLT_t new_palette;
  192061. #ifdef PNG_NO_POINTER_INDEXING
  192062. png_sPLT_entryp pp;
  192063. #endif
  192064. int data_length, entry_size, i;
  192065. png_uint_32 skip = 0;
  192066. png_size_t slength;
  192067. png_debug(1, "in png_handle_sPLT\n");
  192068. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192069. png_error(png_ptr, "Missing IHDR before sPLT");
  192070. else if (png_ptr->mode & PNG_HAVE_IDAT)
  192071. {
  192072. png_warning(png_ptr, "Invalid sPLT after IDAT");
  192073. png_crc_finish(png_ptr, length);
  192074. return;
  192075. }
  192076. #ifdef PNG_MAX_MALLOC_64K
  192077. if (length > (png_uint_32)65535L)
  192078. {
  192079. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  192080. skip = length - (png_uint_32)65535L;
  192081. length = (png_uint_32)65535L;
  192082. }
  192083. #endif
  192084. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  192085. slength = (png_size_t)length;
  192086. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  192087. if (png_crc_finish(png_ptr, skip))
  192088. {
  192089. png_free(png_ptr, chunkdata);
  192090. return;
  192091. }
  192092. chunkdata[slength] = 0x00;
  192093. for (entry_start = chunkdata; *entry_start; entry_start++)
  192094. /* empty loop to find end of name */ ;
  192095. ++entry_start;
  192096. /* a sample depth should follow the separator, and we should be on it */
  192097. if (entry_start > chunkdata + slength - 2)
  192098. {
  192099. png_free(png_ptr, chunkdata);
  192100. png_warning(png_ptr, "malformed sPLT chunk");
  192101. return;
  192102. }
  192103. new_palette.depth = *entry_start++;
  192104. entry_size = (new_palette.depth == 8 ? 6 : 10);
  192105. data_length = (slength - (entry_start - chunkdata));
  192106. /* integrity-check the data length */
  192107. if (data_length % entry_size)
  192108. {
  192109. png_free(png_ptr, chunkdata);
  192110. png_warning(png_ptr, "sPLT chunk has bad length");
  192111. return;
  192112. }
  192113. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  192114. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  192115. png_sizeof(png_sPLT_entry)))
  192116. {
  192117. png_warning(png_ptr, "sPLT chunk too long");
  192118. return;
  192119. }
  192120. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  192121. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  192122. if (new_palette.entries == NULL)
  192123. {
  192124. png_warning(png_ptr, "sPLT chunk requires too much memory");
  192125. return;
  192126. }
  192127. #ifndef PNG_NO_POINTER_INDEXING
  192128. for (i = 0; i < new_palette.nentries; i++)
  192129. {
  192130. png_sPLT_entryp pp = new_palette.entries + i;
  192131. if (new_palette.depth == 8)
  192132. {
  192133. pp->red = *entry_start++;
  192134. pp->green = *entry_start++;
  192135. pp->blue = *entry_start++;
  192136. pp->alpha = *entry_start++;
  192137. }
  192138. else
  192139. {
  192140. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  192141. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  192142. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  192143. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  192144. }
  192145. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  192146. }
  192147. #else
  192148. pp = new_palette.entries;
  192149. for (i = 0; i < new_palette.nentries; i++)
  192150. {
  192151. if (new_palette.depth == 8)
  192152. {
  192153. pp[i].red = *entry_start++;
  192154. pp[i].green = *entry_start++;
  192155. pp[i].blue = *entry_start++;
  192156. pp[i].alpha = *entry_start++;
  192157. }
  192158. else
  192159. {
  192160. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  192161. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  192162. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  192163. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  192164. }
  192165. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  192166. }
  192167. #endif
  192168. /* discard all chunk data except the name and stash that */
  192169. new_palette.name = (png_charp)chunkdata;
  192170. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  192171. png_free(png_ptr, chunkdata);
  192172. png_free(png_ptr, new_palette.entries);
  192173. }
  192174. #endif /* PNG_READ_sPLT_SUPPORTED */
  192175. #if defined(PNG_READ_tRNS_SUPPORTED)
  192176. void /* PRIVATE */
  192177. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192178. {
  192179. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  192180. int bit_mask;
  192181. png_debug(1, "in png_handle_tRNS\n");
  192182. /* For non-indexed color, mask off any bits in the tRNS value that
  192183. * exceed the bit depth. Some creators were writing extra bits there.
  192184. * This is not needed for indexed color. */
  192185. bit_mask = (1 << png_ptr->bit_depth) - 1;
  192186. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192187. png_error(png_ptr, "Missing IHDR before tRNS");
  192188. else if (png_ptr->mode & PNG_HAVE_IDAT)
  192189. {
  192190. png_warning(png_ptr, "Invalid tRNS after IDAT");
  192191. png_crc_finish(png_ptr, length);
  192192. return;
  192193. }
  192194. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  192195. {
  192196. png_warning(png_ptr, "Duplicate tRNS chunk");
  192197. png_crc_finish(png_ptr, length);
  192198. return;
  192199. }
  192200. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  192201. {
  192202. png_byte buf[2];
  192203. if (length != 2)
  192204. {
  192205. png_warning(png_ptr, "Incorrect tRNS chunk length");
  192206. png_crc_finish(png_ptr, length);
  192207. return;
  192208. }
  192209. png_crc_read(png_ptr, buf, 2);
  192210. png_ptr->num_trans = 1;
  192211. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  192212. }
  192213. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  192214. {
  192215. png_byte buf[6];
  192216. if (length != 6)
  192217. {
  192218. png_warning(png_ptr, "Incorrect tRNS chunk length");
  192219. png_crc_finish(png_ptr, length);
  192220. return;
  192221. }
  192222. png_crc_read(png_ptr, buf, (png_size_t)length);
  192223. png_ptr->num_trans = 1;
  192224. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  192225. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  192226. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  192227. }
  192228. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192229. {
  192230. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  192231. {
  192232. /* Should be an error, but we can cope with it. */
  192233. png_warning(png_ptr, "Missing PLTE before tRNS");
  192234. }
  192235. if (length > (png_uint_32)png_ptr->num_palette ||
  192236. length > PNG_MAX_PALETTE_LENGTH)
  192237. {
  192238. png_warning(png_ptr, "Incorrect tRNS chunk length");
  192239. png_crc_finish(png_ptr, length);
  192240. return;
  192241. }
  192242. if (length == 0)
  192243. {
  192244. png_warning(png_ptr, "Zero length tRNS chunk");
  192245. png_crc_finish(png_ptr, length);
  192246. return;
  192247. }
  192248. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  192249. png_ptr->num_trans = (png_uint_16)length;
  192250. }
  192251. else
  192252. {
  192253. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  192254. png_crc_finish(png_ptr, length);
  192255. return;
  192256. }
  192257. if (png_crc_finish(png_ptr, 0))
  192258. {
  192259. png_ptr->num_trans = 0;
  192260. return;
  192261. }
  192262. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  192263. &(png_ptr->trans_values));
  192264. }
  192265. #endif
  192266. #if defined(PNG_READ_bKGD_SUPPORTED)
  192267. void /* PRIVATE */
  192268. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192269. {
  192270. png_size_t truelen;
  192271. png_byte buf[6];
  192272. png_debug(1, "in png_handle_bKGD\n");
  192273. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192274. png_error(png_ptr, "Missing IHDR before bKGD");
  192275. else if (png_ptr->mode & PNG_HAVE_IDAT)
  192276. {
  192277. png_warning(png_ptr, "Invalid bKGD after IDAT");
  192278. png_crc_finish(png_ptr, length);
  192279. return;
  192280. }
  192281. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  192282. !(png_ptr->mode & PNG_HAVE_PLTE))
  192283. {
  192284. png_warning(png_ptr, "Missing PLTE before bKGD");
  192285. png_crc_finish(png_ptr, length);
  192286. return;
  192287. }
  192288. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  192289. {
  192290. png_warning(png_ptr, "Duplicate bKGD chunk");
  192291. png_crc_finish(png_ptr, length);
  192292. return;
  192293. }
  192294. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192295. truelen = 1;
  192296. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  192297. truelen = 6;
  192298. else
  192299. truelen = 2;
  192300. if (length != truelen)
  192301. {
  192302. png_warning(png_ptr, "Incorrect bKGD chunk length");
  192303. png_crc_finish(png_ptr, length);
  192304. return;
  192305. }
  192306. png_crc_read(png_ptr, buf, truelen);
  192307. if (png_crc_finish(png_ptr, 0))
  192308. return;
  192309. /* We convert the index value into RGB components so that we can allow
  192310. * arbitrary RGB values for background when we have transparency, and
  192311. * so it is easy to determine the RGB values of the background color
  192312. * from the info_ptr struct. */
  192313. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192314. {
  192315. png_ptr->background.index = buf[0];
  192316. if(info_ptr->num_palette)
  192317. {
  192318. if(buf[0] > info_ptr->num_palette)
  192319. {
  192320. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  192321. return;
  192322. }
  192323. png_ptr->background.red =
  192324. (png_uint_16)png_ptr->palette[buf[0]].red;
  192325. png_ptr->background.green =
  192326. (png_uint_16)png_ptr->palette[buf[0]].green;
  192327. png_ptr->background.blue =
  192328. (png_uint_16)png_ptr->palette[buf[0]].blue;
  192329. }
  192330. }
  192331. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  192332. {
  192333. png_ptr->background.red =
  192334. png_ptr->background.green =
  192335. png_ptr->background.blue =
  192336. png_ptr->background.gray = png_get_uint_16(buf);
  192337. }
  192338. else
  192339. {
  192340. png_ptr->background.red = png_get_uint_16(buf);
  192341. png_ptr->background.green = png_get_uint_16(buf + 2);
  192342. png_ptr->background.blue = png_get_uint_16(buf + 4);
  192343. }
  192344. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  192345. }
  192346. #endif
  192347. #if defined(PNG_READ_hIST_SUPPORTED)
  192348. void /* PRIVATE */
  192349. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192350. {
  192351. unsigned int num, i;
  192352. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  192353. png_debug(1, "in png_handle_hIST\n");
  192354. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192355. png_error(png_ptr, "Missing IHDR before hIST");
  192356. else if (png_ptr->mode & PNG_HAVE_IDAT)
  192357. {
  192358. png_warning(png_ptr, "Invalid hIST after IDAT");
  192359. png_crc_finish(png_ptr, length);
  192360. return;
  192361. }
  192362. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  192363. {
  192364. png_warning(png_ptr, "Missing PLTE before hIST");
  192365. png_crc_finish(png_ptr, length);
  192366. return;
  192367. }
  192368. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  192369. {
  192370. png_warning(png_ptr, "Duplicate hIST chunk");
  192371. png_crc_finish(png_ptr, length);
  192372. return;
  192373. }
  192374. num = length / 2 ;
  192375. if (num != (unsigned int) png_ptr->num_palette || num >
  192376. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  192377. {
  192378. png_warning(png_ptr, "Incorrect hIST chunk length");
  192379. png_crc_finish(png_ptr, length);
  192380. return;
  192381. }
  192382. for (i = 0; i < num; i++)
  192383. {
  192384. png_byte buf[2];
  192385. png_crc_read(png_ptr, buf, 2);
  192386. readbuf[i] = png_get_uint_16(buf);
  192387. }
  192388. if (png_crc_finish(png_ptr, 0))
  192389. return;
  192390. png_set_hIST(png_ptr, info_ptr, readbuf);
  192391. }
  192392. #endif
  192393. #if defined(PNG_READ_pHYs_SUPPORTED)
  192394. void /* PRIVATE */
  192395. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192396. {
  192397. png_byte buf[9];
  192398. png_uint_32 res_x, res_y;
  192399. int unit_type;
  192400. png_debug(1, "in png_handle_pHYs\n");
  192401. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192402. png_error(png_ptr, "Missing IHDR before pHYs");
  192403. else if (png_ptr->mode & PNG_HAVE_IDAT)
  192404. {
  192405. png_warning(png_ptr, "Invalid pHYs after IDAT");
  192406. png_crc_finish(png_ptr, length);
  192407. return;
  192408. }
  192409. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  192410. {
  192411. png_warning(png_ptr, "Duplicate pHYs chunk");
  192412. png_crc_finish(png_ptr, length);
  192413. return;
  192414. }
  192415. if (length != 9)
  192416. {
  192417. png_warning(png_ptr, "Incorrect pHYs chunk length");
  192418. png_crc_finish(png_ptr, length);
  192419. return;
  192420. }
  192421. png_crc_read(png_ptr, buf, 9);
  192422. if (png_crc_finish(png_ptr, 0))
  192423. return;
  192424. res_x = png_get_uint_32(buf);
  192425. res_y = png_get_uint_32(buf + 4);
  192426. unit_type = buf[8];
  192427. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  192428. }
  192429. #endif
  192430. #if defined(PNG_READ_oFFs_SUPPORTED)
  192431. void /* PRIVATE */
  192432. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192433. {
  192434. png_byte buf[9];
  192435. png_int_32 offset_x, offset_y;
  192436. int unit_type;
  192437. png_debug(1, "in png_handle_oFFs\n");
  192438. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192439. png_error(png_ptr, "Missing IHDR before oFFs");
  192440. else if (png_ptr->mode & PNG_HAVE_IDAT)
  192441. {
  192442. png_warning(png_ptr, "Invalid oFFs after IDAT");
  192443. png_crc_finish(png_ptr, length);
  192444. return;
  192445. }
  192446. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  192447. {
  192448. png_warning(png_ptr, "Duplicate oFFs chunk");
  192449. png_crc_finish(png_ptr, length);
  192450. return;
  192451. }
  192452. if (length != 9)
  192453. {
  192454. png_warning(png_ptr, "Incorrect oFFs chunk length");
  192455. png_crc_finish(png_ptr, length);
  192456. return;
  192457. }
  192458. png_crc_read(png_ptr, buf, 9);
  192459. if (png_crc_finish(png_ptr, 0))
  192460. return;
  192461. offset_x = png_get_int_32(buf);
  192462. offset_y = png_get_int_32(buf + 4);
  192463. unit_type = buf[8];
  192464. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  192465. }
  192466. #endif
  192467. #if defined(PNG_READ_pCAL_SUPPORTED)
  192468. /* read the pCAL chunk (described in the PNG Extensions document) */
  192469. void /* PRIVATE */
  192470. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192471. {
  192472. png_charp purpose;
  192473. png_int_32 X0, X1;
  192474. png_byte type, nparams;
  192475. png_charp buf, units, endptr;
  192476. png_charpp params;
  192477. png_size_t slength;
  192478. int i;
  192479. png_debug(1, "in png_handle_pCAL\n");
  192480. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192481. png_error(png_ptr, "Missing IHDR before pCAL");
  192482. else if (png_ptr->mode & PNG_HAVE_IDAT)
  192483. {
  192484. png_warning(png_ptr, "Invalid pCAL after IDAT");
  192485. png_crc_finish(png_ptr, length);
  192486. return;
  192487. }
  192488. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  192489. {
  192490. png_warning(png_ptr, "Duplicate pCAL chunk");
  192491. png_crc_finish(png_ptr, length);
  192492. return;
  192493. }
  192494. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  192495. length + 1);
  192496. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  192497. if (purpose == NULL)
  192498. {
  192499. png_warning(png_ptr, "No memory for pCAL purpose.");
  192500. return;
  192501. }
  192502. slength = (png_size_t)length;
  192503. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  192504. if (png_crc_finish(png_ptr, 0))
  192505. {
  192506. png_free(png_ptr, purpose);
  192507. return;
  192508. }
  192509. purpose[slength] = 0x00; /* null terminate the last string */
  192510. png_debug(3, "Finding end of pCAL purpose string\n");
  192511. for (buf = purpose; *buf; buf++)
  192512. /* empty loop */ ;
  192513. endptr = purpose + slength;
  192514. /* We need to have at least 12 bytes after the purpose string
  192515. in order to get the parameter information. */
  192516. if (endptr <= buf + 12)
  192517. {
  192518. png_warning(png_ptr, "Invalid pCAL data");
  192519. png_free(png_ptr, purpose);
  192520. return;
  192521. }
  192522. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  192523. X0 = png_get_int_32((png_bytep)buf+1);
  192524. X1 = png_get_int_32((png_bytep)buf+5);
  192525. type = buf[9];
  192526. nparams = buf[10];
  192527. units = buf + 11;
  192528. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  192529. /* Check that we have the right number of parameters for known
  192530. equation types. */
  192531. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  192532. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  192533. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  192534. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  192535. {
  192536. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  192537. png_free(png_ptr, purpose);
  192538. return;
  192539. }
  192540. else if (type >= PNG_EQUATION_LAST)
  192541. {
  192542. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  192543. }
  192544. for (buf = units; *buf; buf++)
  192545. /* Empty loop to move past the units string. */ ;
  192546. png_debug(3, "Allocating pCAL parameters array\n");
  192547. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  192548. *png_sizeof(png_charp))) ;
  192549. if (params == NULL)
  192550. {
  192551. png_free(png_ptr, purpose);
  192552. png_warning(png_ptr, "No memory for pCAL params.");
  192553. return;
  192554. }
  192555. /* Get pointers to the start of each parameter string. */
  192556. for (i = 0; i < (int)nparams; i++)
  192557. {
  192558. buf++; /* Skip the null string terminator from previous parameter. */
  192559. png_debug1(3, "Reading pCAL parameter %d\n", i);
  192560. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  192561. /* Empty loop to move past each parameter string */ ;
  192562. /* Make sure we haven't run out of data yet */
  192563. if (buf > endptr)
  192564. {
  192565. png_warning(png_ptr, "Invalid pCAL data");
  192566. png_free(png_ptr, purpose);
  192567. png_free(png_ptr, params);
  192568. return;
  192569. }
  192570. }
  192571. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  192572. units, params);
  192573. png_free(png_ptr, purpose);
  192574. png_free(png_ptr, params);
  192575. }
  192576. #endif
  192577. #if defined(PNG_READ_sCAL_SUPPORTED)
  192578. /* read the sCAL chunk */
  192579. void /* PRIVATE */
  192580. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192581. {
  192582. png_charp buffer, ep;
  192583. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192584. double width, height;
  192585. png_charp vp;
  192586. #else
  192587. #ifdef PNG_FIXED_POINT_SUPPORTED
  192588. png_charp swidth, sheight;
  192589. #endif
  192590. #endif
  192591. png_size_t slength;
  192592. png_debug(1, "in png_handle_sCAL\n");
  192593. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192594. png_error(png_ptr, "Missing IHDR before sCAL");
  192595. else if (png_ptr->mode & PNG_HAVE_IDAT)
  192596. {
  192597. png_warning(png_ptr, "Invalid sCAL after IDAT");
  192598. png_crc_finish(png_ptr, length);
  192599. return;
  192600. }
  192601. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  192602. {
  192603. png_warning(png_ptr, "Duplicate sCAL chunk");
  192604. png_crc_finish(png_ptr, length);
  192605. return;
  192606. }
  192607. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  192608. length + 1);
  192609. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  192610. if (buffer == NULL)
  192611. {
  192612. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  192613. return;
  192614. }
  192615. slength = (png_size_t)length;
  192616. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  192617. if (png_crc_finish(png_ptr, 0))
  192618. {
  192619. png_free(png_ptr, buffer);
  192620. return;
  192621. }
  192622. buffer[slength] = 0x00; /* null terminate the last string */
  192623. ep = buffer + 1; /* skip unit byte */
  192624. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192625. width = png_strtod(png_ptr, ep, &vp);
  192626. if (*vp)
  192627. {
  192628. png_warning(png_ptr, "malformed width string in sCAL chunk");
  192629. return;
  192630. }
  192631. #else
  192632. #ifdef PNG_FIXED_POINT_SUPPORTED
  192633. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  192634. if (swidth == NULL)
  192635. {
  192636. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  192637. return;
  192638. }
  192639. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  192640. #endif
  192641. #endif
  192642. for (ep = buffer; *ep; ep++)
  192643. /* empty loop */ ;
  192644. ep++;
  192645. if (buffer + slength < ep)
  192646. {
  192647. png_warning(png_ptr, "Truncated sCAL chunk");
  192648. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  192649. !defined(PNG_FLOATING_POINT_SUPPORTED)
  192650. png_free(png_ptr, swidth);
  192651. #endif
  192652. png_free(png_ptr, buffer);
  192653. return;
  192654. }
  192655. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192656. height = png_strtod(png_ptr, ep, &vp);
  192657. if (*vp)
  192658. {
  192659. png_warning(png_ptr, "malformed height string in sCAL chunk");
  192660. return;
  192661. }
  192662. #else
  192663. #ifdef PNG_FIXED_POINT_SUPPORTED
  192664. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  192665. if (swidth == NULL)
  192666. {
  192667. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  192668. return;
  192669. }
  192670. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  192671. #endif
  192672. #endif
  192673. if (buffer + slength < ep
  192674. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192675. || width <= 0. || height <= 0.
  192676. #endif
  192677. )
  192678. {
  192679. png_warning(png_ptr, "Invalid sCAL data");
  192680. png_free(png_ptr, buffer);
  192681. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  192682. png_free(png_ptr, swidth);
  192683. png_free(png_ptr, sheight);
  192684. #endif
  192685. return;
  192686. }
  192687. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192688. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  192689. #else
  192690. #ifdef PNG_FIXED_POINT_SUPPORTED
  192691. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  192692. #endif
  192693. #endif
  192694. png_free(png_ptr, buffer);
  192695. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  192696. png_free(png_ptr, swidth);
  192697. png_free(png_ptr, sheight);
  192698. #endif
  192699. }
  192700. #endif
  192701. #if defined(PNG_READ_tIME_SUPPORTED)
  192702. void /* PRIVATE */
  192703. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192704. {
  192705. png_byte buf[7];
  192706. png_time mod_time;
  192707. png_debug(1, "in png_handle_tIME\n");
  192708. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192709. png_error(png_ptr, "Out of place tIME chunk");
  192710. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  192711. {
  192712. png_warning(png_ptr, "Duplicate tIME chunk");
  192713. png_crc_finish(png_ptr, length);
  192714. return;
  192715. }
  192716. if (png_ptr->mode & PNG_HAVE_IDAT)
  192717. png_ptr->mode |= PNG_AFTER_IDAT;
  192718. if (length != 7)
  192719. {
  192720. png_warning(png_ptr, "Incorrect tIME chunk length");
  192721. png_crc_finish(png_ptr, length);
  192722. return;
  192723. }
  192724. png_crc_read(png_ptr, buf, 7);
  192725. if (png_crc_finish(png_ptr, 0))
  192726. return;
  192727. mod_time.second = buf[6];
  192728. mod_time.minute = buf[5];
  192729. mod_time.hour = buf[4];
  192730. mod_time.day = buf[3];
  192731. mod_time.month = buf[2];
  192732. mod_time.year = png_get_uint_16(buf);
  192733. png_set_tIME(png_ptr, info_ptr, &mod_time);
  192734. }
  192735. #endif
  192736. #if defined(PNG_READ_tEXt_SUPPORTED)
  192737. /* Note: this does not properly handle chunks that are > 64K under DOS */
  192738. void /* PRIVATE */
  192739. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192740. {
  192741. png_textp text_ptr;
  192742. png_charp key;
  192743. png_charp text;
  192744. png_uint_32 skip = 0;
  192745. png_size_t slength;
  192746. int ret;
  192747. png_debug(1, "in png_handle_tEXt\n");
  192748. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192749. png_error(png_ptr, "Missing IHDR before tEXt");
  192750. if (png_ptr->mode & PNG_HAVE_IDAT)
  192751. png_ptr->mode |= PNG_AFTER_IDAT;
  192752. #ifdef PNG_MAX_MALLOC_64K
  192753. if (length > (png_uint_32)65535L)
  192754. {
  192755. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  192756. skip = length - (png_uint_32)65535L;
  192757. length = (png_uint_32)65535L;
  192758. }
  192759. #endif
  192760. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  192761. if (key == NULL)
  192762. {
  192763. png_warning(png_ptr, "No memory to process text chunk.");
  192764. return;
  192765. }
  192766. slength = (png_size_t)length;
  192767. png_crc_read(png_ptr, (png_bytep)key, slength);
  192768. if (png_crc_finish(png_ptr, skip))
  192769. {
  192770. png_free(png_ptr, key);
  192771. return;
  192772. }
  192773. key[slength] = 0x00;
  192774. for (text = key; *text; text++)
  192775. /* empty loop to find end of key */ ;
  192776. if (text != key + slength)
  192777. text++;
  192778. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  192779. (png_uint_32)png_sizeof(png_text));
  192780. if (text_ptr == NULL)
  192781. {
  192782. png_warning(png_ptr, "Not enough memory to process text chunk.");
  192783. png_free(png_ptr, key);
  192784. return;
  192785. }
  192786. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  192787. text_ptr->key = key;
  192788. #ifdef PNG_iTXt_SUPPORTED
  192789. text_ptr->lang = NULL;
  192790. text_ptr->lang_key = NULL;
  192791. text_ptr->itxt_length = 0;
  192792. #endif
  192793. text_ptr->text = text;
  192794. text_ptr->text_length = png_strlen(text);
  192795. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  192796. png_free(png_ptr, key);
  192797. png_free(png_ptr, text_ptr);
  192798. if (ret)
  192799. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  192800. }
  192801. #endif
  192802. #if defined(PNG_READ_zTXt_SUPPORTED)
  192803. /* note: this does not correctly handle chunks that are > 64K under DOS */
  192804. void /* PRIVATE */
  192805. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192806. {
  192807. png_textp text_ptr;
  192808. png_charp chunkdata;
  192809. png_charp text;
  192810. int comp_type;
  192811. int ret;
  192812. png_size_t slength, prefix_len, data_len;
  192813. png_debug(1, "in png_handle_zTXt\n");
  192814. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192815. png_error(png_ptr, "Missing IHDR before zTXt");
  192816. if (png_ptr->mode & PNG_HAVE_IDAT)
  192817. png_ptr->mode |= PNG_AFTER_IDAT;
  192818. #ifdef PNG_MAX_MALLOC_64K
  192819. /* We will no doubt have problems with chunks even half this size, but
  192820. there is no hard and fast rule to tell us where to stop. */
  192821. if (length > (png_uint_32)65535L)
  192822. {
  192823. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  192824. png_crc_finish(png_ptr, length);
  192825. return;
  192826. }
  192827. #endif
  192828. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  192829. if (chunkdata == NULL)
  192830. {
  192831. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  192832. return;
  192833. }
  192834. slength = (png_size_t)length;
  192835. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  192836. if (png_crc_finish(png_ptr, 0))
  192837. {
  192838. png_free(png_ptr, chunkdata);
  192839. return;
  192840. }
  192841. chunkdata[slength] = 0x00;
  192842. for (text = chunkdata; *text; text++)
  192843. /* empty loop */ ;
  192844. /* zTXt must have some text after the chunkdataword */
  192845. if (text >= chunkdata + slength - 2)
  192846. {
  192847. png_warning(png_ptr, "Truncated zTXt chunk");
  192848. png_free(png_ptr, chunkdata);
  192849. return;
  192850. }
  192851. else
  192852. {
  192853. comp_type = *(++text);
  192854. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  192855. {
  192856. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  192857. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  192858. }
  192859. text++; /* skip the compression_method byte */
  192860. }
  192861. prefix_len = text - chunkdata;
  192862. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  192863. (png_size_t)length, prefix_len, &data_len);
  192864. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  192865. (png_uint_32)png_sizeof(png_text));
  192866. if (text_ptr == NULL)
  192867. {
  192868. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  192869. png_free(png_ptr, chunkdata);
  192870. return;
  192871. }
  192872. text_ptr->compression = comp_type;
  192873. text_ptr->key = chunkdata;
  192874. #ifdef PNG_iTXt_SUPPORTED
  192875. text_ptr->lang = NULL;
  192876. text_ptr->lang_key = NULL;
  192877. text_ptr->itxt_length = 0;
  192878. #endif
  192879. text_ptr->text = chunkdata + prefix_len;
  192880. text_ptr->text_length = data_len;
  192881. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  192882. png_free(png_ptr, text_ptr);
  192883. png_free(png_ptr, chunkdata);
  192884. if (ret)
  192885. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  192886. }
  192887. #endif
  192888. #if defined(PNG_READ_iTXt_SUPPORTED)
  192889. /* note: this does not correctly handle chunks that are > 64K under DOS */
  192890. void /* PRIVATE */
  192891. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192892. {
  192893. png_textp text_ptr;
  192894. png_charp chunkdata;
  192895. png_charp key, lang, text, lang_key;
  192896. int comp_flag;
  192897. int comp_type = 0;
  192898. int ret;
  192899. png_size_t slength, prefix_len, data_len;
  192900. png_debug(1, "in png_handle_iTXt\n");
  192901. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192902. png_error(png_ptr, "Missing IHDR before iTXt");
  192903. if (png_ptr->mode & PNG_HAVE_IDAT)
  192904. png_ptr->mode |= PNG_AFTER_IDAT;
  192905. #ifdef PNG_MAX_MALLOC_64K
  192906. /* We will no doubt have problems with chunks even half this size, but
  192907. there is no hard and fast rule to tell us where to stop. */
  192908. if (length > (png_uint_32)65535L)
  192909. {
  192910. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  192911. png_crc_finish(png_ptr, length);
  192912. return;
  192913. }
  192914. #endif
  192915. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  192916. if (chunkdata == NULL)
  192917. {
  192918. png_warning(png_ptr, "No memory to process iTXt chunk.");
  192919. return;
  192920. }
  192921. slength = (png_size_t)length;
  192922. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  192923. if (png_crc_finish(png_ptr, 0))
  192924. {
  192925. png_free(png_ptr, chunkdata);
  192926. return;
  192927. }
  192928. chunkdata[slength] = 0x00;
  192929. for (lang = chunkdata; *lang; lang++)
  192930. /* empty loop */ ;
  192931. lang++; /* skip NUL separator */
  192932. /* iTXt must have a language tag (possibly empty), two compression bytes,
  192933. translated keyword (possibly empty), and possibly some text after the
  192934. keyword */
  192935. if (lang >= chunkdata + slength - 3)
  192936. {
  192937. png_warning(png_ptr, "Truncated iTXt chunk");
  192938. png_free(png_ptr, chunkdata);
  192939. return;
  192940. }
  192941. else
  192942. {
  192943. comp_flag = *lang++;
  192944. comp_type = *lang++;
  192945. }
  192946. for (lang_key = lang; *lang_key; lang_key++)
  192947. /* empty loop */ ;
  192948. lang_key++; /* skip NUL separator */
  192949. if (lang_key >= chunkdata + slength)
  192950. {
  192951. png_warning(png_ptr, "Truncated iTXt chunk");
  192952. png_free(png_ptr, chunkdata);
  192953. return;
  192954. }
  192955. for (text = lang_key; *text; text++)
  192956. /* empty loop */ ;
  192957. text++; /* skip NUL separator */
  192958. if (text >= chunkdata + slength)
  192959. {
  192960. png_warning(png_ptr, "Malformed iTXt chunk");
  192961. png_free(png_ptr, chunkdata);
  192962. return;
  192963. }
  192964. prefix_len = text - chunkdata;
  192965. key=chunkdata;
  192966. if (comp_flag)
  192967. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  192968. (size_t)length, prefix_len, &data_len);
  192969. else
  192970. data_len=png_strlen(chunkdata + prefix_len);
  192971. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  192972. (png_uint_32)png_sizeof(png_text));
  192973. if (text_ptr == NULL)
  192974. {
  192975. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  192976. png_free(png_ptr, chunkdata);
  192977. return;
  192978. }
  192979. text_ptr->compression = (int)comp_flag + 1;
  192980. text_ptr->lang_key = chunkdata+(lang_key-key);
  192981. text_ptr->lang = chunkdata+(lang-key);
  192982. text_ptr->itxt_length = data_len;
  192983. text_ptr->text_length = 0;
  192984. text_ptr->key = chunkdata;
  192985. text_ptr->text = chunkdata + prefix_len;
  192986. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  192987. png_free(png_ptr, text_ptr);
  192988. png_free(png_ptr, chunkdata);
  192989. if (ret)
  192990. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  192991. }
  192992. #endif
  192993. /* This function is called when we haven't found a handler for a
  192994. chunk. If there isn't a problem with the chunk itself (ie bad
  192995. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  192996. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  192997. case it will be saved away to be written out later. */
  192998. void /* PRIVATE */
  192999. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193000. {
  193001. png_uint_32 skip = 0;
  193002. png_debug(1, "in png_handle_unknown\n");
  193003. if (png_ptr->mode & PNG_HAVE_IDAT)
  193004. {
  193005. #ifdef PNG_USE_LOCAL_ARRAYS
  193006. PNG_CONST PNG_IDAT;
  193007. #endif
  193008. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  193009. png_ptr->mode |= PNG_AFTER_IDAT;
  193010. }
  193011. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  193012. if (!(png_ptr->chunk_name[0] & 0x20))
  193013. {
  193014. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  193015. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  193016. PNG_HANDLE_CHUNK_ALWAYS
  193017. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  193018. && png_ptr->read_user_chunk_fn == NULL
  193019. #endif
  193020. )
  193021. #endif
  193022. png_chunk_error(png_ptr, "unknown critical chunk");
  193023. }
  193024. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  193025. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  193026. (png_ptr->read_user_chunk_fn != NULL))
  193027. {
  193028. #ifdef PNG_MAX_MALLOC_64K
  193029. if (length > (png_uint_32)65535L)
  193030. {
  193031. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  193032. skip = length - (png_uint_32)65535L;
  193033. length = (png_uint_32)65535L;
  193034. }
  193035. #endif
  193036. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  193037. (png_charp)png_ptr->chunk_name, 5);
  193038. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  193039. png_ptr->unknown_chunk.size = (png_size_t)length;
  193040. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  193041. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  193042. if(png_ptr->read_user_chunk_fn != NULL)
  193043. {
  193044. /* callback to user unknown chunk handler */
  193045. int ret;
  193046. ret = (*(png_ptr->read_user_chunk_fn))
  193047. (png_ptr, &png_ptr->unknown_chunk);
  193048. if (ret < 0)
  193049. png_chunk_error(png_ptr, "error in user chunk");
  193050. if (ret == 0)
  193051. {
  193052. if (!(png_ptr->chunk_name[0] & 0x20))
  193053. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  193054. PNG_HANDLE_CHUNK_ALWAYS)
  193055. png_chunk_error(png_ptr, "unknown critical chunk");
  193056. png_set_unknown_chunks(png_ptr, info_ptr,
  193057. &png_ptr->unknown_chunk, 1);
  193058. }
  193059. }
  193060. #else
  193061. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  193062. #endif
  193063. png_free(png_ptr, png_ptr->unknown_chunk.data);
  193064. png_ptr->unknown_chunk.data = NULL;
  193065. }
  193066. else
  193067. #endif
  193068. skip = length;
  193069. png_crc_finish(png_ptr, skip);
  193070. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  193071. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  193072. #endif
  193073. }
  193074. /* This function is called to verify that a chunk name is valid.
  193075. This function can't have the "critical chunk check" incorporated
  193076. into it, since in the future we will need to be able to call user
  193077. functions to handle unknown critical chunks after we check that
  193078. the chunk name itself is valid. */
  193079. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  193080. void /* PRIVATE */
  193081. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  193082. {
  193083. png_debug(1, "in png_check_chunk_name\n");
  193084. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  193085. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  193086. {
  193087. png_chunk_error(png_ptr, "invalid chunk type");
  193088. }
  193089. }
  193090. /* Combines the row recently read in with the existing pixels in the
  193091. row. This routine takes care of alpha and transparency if requested.
  193092. This routine also handles the two methods of progressive display
  193093. of interlaced images, depending on the mask value.
  193094. The mask value describes which pixels are to be combined with
  193095. the row. The pattern always repeats every 8 pixels, so just 8
  193096. bits are needed. A one indicates the pixel is to be combined,
  193097. a zero indicates the pixel is to be skipped. This is in addition
  193098. to any alpha or transparency value associated with the pixel. If
  193099. you want all pixels to be combined, pass 0xff (255) in mask. */
  193100. void /* PRIVATE */
  193101. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  193102. {
  193103. png_debug(1,"in png_combine_row\n");
  193104. if (mask == 0xff)
  193105. {
  193106. png_memcpy(row, png_ptr->row_buf + 1,
  193107. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  193108. }
  193109. else
  193110. {
  193111. switch (png_ptr->row_info.pixel_depth)
  193112. {
  193113. case 1:
  193114. {
  193115. png_bytep sp = png_ptr->row_buf + 1;
  193116. png_bytep dp = row;
  193117. int s_inc, s_start, s_end;
  193118. int m = 0x80;
  193119. int shift;
  193120. png_uint_32 i;
  193121. png_uint_32 row_width = png_ptr->width;
  193122. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  193123. if (png_ptr->transformations & PNG_PACKSWAP)
  193124. {
  193125. s_start = 0;
  193126. s_end = 7;
  193127. s_inc = 1;
  193128. }
  193129. else
  193130. #endif
  193131. {
  193132. s_start = 7;
  193133. s_end = 0;
  193134. s_inc = -1;
  193135. }
  193136. shift = s_start;
  193137. for (i = 0; i < row_width; i++)
  193138. {
  193139. if (m & mask)
  193140. {
  193141. int value;
  193142. value = (*sp >> shift) & 0x01;
  193143. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  193144. *dp |= (png_byte)(value << shift);
  193145. }
  193146. if (shift == s_end)
  193147. {
  193148. shift = s_start;
  193149. sp++;
  193150. dp++;
  193151. }
  193152. else
  193153. shift += s_inc;
  193154. if (m == 1)
  193155. m = 0x80;
  193156. else
  193157. m >>= 1;
  193158. }
  193159. break;
  193160. }
  193161. case 2:
  193162. {
  193163. png_bytep sp = png_ptr->row_buf + 1;
  193164. png_bytep dp = row;
  193165. int s_start, s_end, s_inc;
  193166. int m = 0x80;
  193167. int shift;
  193168. png_uint_32 i;
  193169. png_uint_32 row_width = png_ptr->width;
  193170. int value;
  193171. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  193172. if (png_ptr->transformations & PNG_PACKSWAP)
  193173. {
  193174. s_start = 0;
  193175. s_end = 6;
  193176. s_inc = 2;
  193177. }
  193178. else
  193179. #endif
  193180. {
  193181. s_start = 6;
  193182. s_end = 0;
  193183. s_inc = -2;
  193184. }
  193185. shift = s_start;
  193186. for (i = 0; i < row_width; i++)
  193187. {
  193188. if (m & mask)
  193189. {
  193190. value = (*sp >> shift) & 0x03;
  193191. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  193192. *dp |= (png_byte)(value << shift);
  193193. }
  193194. if (shift == s_end)
  193195. {
  193196. shift = s_start;
  193197. sp++;
  193198. dp++;
  193199. }
  193200. else
  193201. shift += s_inc;
  193202. if (m == 1)
  193203. m = 0x80;
  193204. else
  193205. m >>= 1;
  193206. }
  193207. break;
  193208. }
  193209. case 4:
  193210. {
  193211. png_bytep sp = png_ptr->row_buf + 1;
  193212. png_bytep dp = row;
  193213. int s_start, s_end, s_inc;
  193214. int m = 0x80;
  193215. int shift;
  193216. png_uint_32 i;
  193217. png_uint_32 row_width = png_ptr->width;
  193218. int value;
  193219. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  193220. if (png_ptr->transformations & PNG_PACKSWAP)
  193221. {
  193222. s_start = 0;
  193223. s_end = 4;
  193224. s_inc = 4;
  193225. }
  193226. else
  193227. #endif
  193228. {
  193229. s_start = 4;
  193230. s_end = 0;
  193231. s_inc = -4;
  193232. }
  193233. shift = s_start;
  193234. for (i = 0; i < row_width; i++)
  193235. {
  193236. if (m & mask)
  193237. {
  193238. value = (*sp >> shift) & 0xf;
  193239. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  193240. *dp |= (png_byte)(value << shift);
  193241. }
  193242. if (shift == s_end)
  193243. {
  193244. shift = s_start;
  193245. sp++;
  193246. dp++;
  193247. }
  193248. else
  193249. shift += s_inc;
  193250. if (m == 1)
  193251. m = 0x80;
  193252. else
  193253. m >>= 1;
  193254. }
  193255. break;
  193256. }
  193257. default:
  193258. {
  193259. png_bytep sp = png_ptr->row_buf + 1;
  193260. png_bytep dp = row;
  193261. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  193262. png_uint_32 i;
  193263. png_uint_32 row_width = png_ptr->width;
  193264. png_byte m = 0x80;
  193265. for (i = 0; i < row_width; i++)
  193266. {
  193267. if (m & mask)
  193268. {
  193269. png_memcpy(dp, sp, pixel_bytes);
  193270. }
  193271. sp += pixel_bytes;
  193272. dp += pixel_bytes;
  193273. if (m == 1)
  193274. m = 0x80;
  193275. else
  193276. m >>= 1;
  193277. }
  193278. break;
  193279. }
  193280. }
  193281. }
  193282. }
  193283. #ifdef PNG_READ_INTERLACING_SUPPORTED
  193284. /* OLD pre-1.0.9 interface:
  193285. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  193286. png_uint_32 transformations)
  193287. */
  193288. void /* PRIVATE */
  193289. png_do_read_interlace(png_structp png_ptr)
  193290. {
  193291. png_row_infop row_info = &(png_ptr->row_info);
  193292. png_bytep row = png_ptr->row_buf + 1;
  193293. int pass = png_ptr->pass;
  193294. png_uint_32 transformations = png_ptr->transformations;
  193295. #ifdef PNG_USE_LOCAL_ARRAYS
  193296. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  193297. /* offset to next interlace block */
  193298. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  193299. #endif
  193300. png_debug(1,"in png_do_read_interlace\n");
  193301. if (row != NULL && row_info != NULL)
  193302. {
  193303. png_uint_32 final_width;
  193304. final_width = row_info->width * png_pass_inc[pass];
  193305. switch (row_info->pixel_depth)
  193306. {
  193307. case 1:
  193308. {
  193309. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  193310. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  193311. int sshift, dshift;
  193312. int s_start, s_end, s_inc;
  193313. int jstop = png_pass_inc[pass];
  193314. png_byte v;
  193315. png_uint_32 i;
  193316. int j;
  193317. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  193318. if (transformations & PNG_PACKSWAP)
  193319. {
  193320. sshift = (int)((row_info->width + 7) & 0x07);
  193321. dshift = (int)((final_width + 7) & 0x07);
  193322. s_start = 7;
  193323. s_end = 0;
  193324. s_inc = -1;
  193325. }
  193326. else
  193327. #endif
  193328. {
  193329. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  193330. dshift = 7 - (int)((final_width + 7) & 0x07);
  193331. s_start = 0;
  193332. s_end = 7;
  193333. s_inc = 1;
  193334. }
  193335. for (i = 0; i < row_info->width; i++)
  193336. {
  193337. v = (png_byte)((*sp >> sshift) & 0x01);
  193338. for (j = 0; j < jstop; j++)
  193339. {
  193340. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  193341. *dp |= (png_byte)(v << dshift);
  193342. if (dshift == s_end)
  193343. {
  193344. dshift = s_start;
  193345. dp--;
  193346. }
  193347. else
  193348. dshift += s_inc;
  193349. }
  193350. if (sshift == s_end)
  193351. {
  193352. sshift = s_start;
  193353. sp--;
  193354. }
  193355. else
  193356. sshift += s_inc;
  193357. }
  193358. break;
  193359. }
  193360. case 2:
  193361. {
  193362. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  193363. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  193364. int sshift, dshift;
  193365. int s_start, s_end, s_inc;
  193366. int jstop = png_pass_inc[pass];
  193367. png_uint_32 i;
  193368. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  193369. if (transformations & PNG_PACKSWAP)
  193370. {
  193371. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  193372. dshift = (int)(((final_width + 3) & 0x03) << 1);
  193373. s_start = 6;
  193374. s_end = 0;
  193375. s_inc = -2;
  193376. }
  193377. else
  193378. #endif
  193379. {
  193380. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  193381. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  193382. s_start = 0;
  193383. s_end = 6;
  193384. s_inc = 2;
  193385. }
  193386. for (i = 0; i < row_info->width; i++)
  193387. {
  193388. png_byte v;
  193389. int j;
  193390. v = (png_byte)((*sp >> sshift) & 0x03);
  193391. for (j = 0; j < jstop; j++)
  193392. {
  193393. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  193394. *dp |= (png_byte)(v << dshift);
  193395. if (dshift == s_end)
  193396. {
  193397. dshift = s_start;
  193398. dp--;
  193399. }
  193400. else
  193401. dshift += s_inc;
  193402. }
  193403. if (sshift == s_end)
  193404. {
  193405. sshift = s_start;
  193406. sp--;
  193407. }
  193408. else
  193409. sshift += s_inc;
  193410. }
  193411. break;
  193412. }
  193413. case 4:
  193414. {
  193415. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  193416. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  193417. int sshift, dshift;
  193418. int s_start, s_end, s_inc;
  193419. png_uint_32 i;
  193420. int jstop = png_pass_inc[pass];
  193421. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  193422. if (transformations & PNG_PACKSWAP)
  193423. {
  193424. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  193425. dshift = (int)(((final_width + 1) & 0x01) << 2);
  193426. s_start = 4;
  193427. s_end = 0;
  193428. s_inc = -4;
  193429. }
  193430. else
  193431. #endif
  193432. {
  193433. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  193434. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  193435. s_start = 0;
  193436. s_end = 4;
  193437. s_inc = 4;
  193438. }
  193439. for (i = 0; i < row_info->width; i++)
  193440. {
  193441. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  193442. int j;
  193443. for (j = 0; j < jstop; j++)
  193444. {
  193445. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  193446. *dp |= (png_byte)(v << dshift);
  193447. if (dshift == s_end)
  193448. {
  193449. dshift = s_start;
  193450. dp--;
  193451. }
  193452. else
  193453. dshift += s_inc;
  193454. }
  193455. if (sshift == s_end)
  193456. {
  193457. sshift = s_start;
  193458. sp--;
  193459. }
  193460. else
  193461. sshift += s_inc;
  193462. }
  193463. break;
  193464. }
  193465. default:
  193466. {
  193467. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  193468. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  193469. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  193470. int jstop = png_pass_inc[pass];
  193471. png_uint_32 i;
  193472. for (i = 0; i < row_info->width; i++)
  193473. {
  193474. png_byte v[8];
  193475. int j;
  193476. png_memcpy(v, sp, pixel_bytes);
  193477. for (j = 0; j < jstop; j++)
  193478. {
  193479. png_memcpy(dp, v, pixel_bytes);
  193480. dp -= pixel_bytes;
  193481. }
  193482. sp -= pixel_bytes;
  193483. }
  193484. break;
  193485. }
  193486. }
  193487. row_info->width = final_width;
  193488. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  193489. }
  193490. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  193491. transformations = transformations; /* silence compiler warning */
  193492. #endif
  193493. }
  193494. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  193495. void /* PRIVATE */
  193496. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  193497. png_bytep prev_row, int filter)
  193498. {
  193499. png_debug(1, "in png_read_filter_row\n");
  193500. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  193501. switch (filter)
  193502. {
  193503. case PNG_FILTER_VALUE_NONE:
  193504. break;
  193505. case PNG_FILTER_VALUE_SUB:
  193506. {
  193507. png_uint_32 i;
  193508. png_uint_32 istop = row_info->rowbytes;
  193509. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  193510. png_bytep rp = row + bpp;
  193511. png_bytep lp = row;
  193512. for (i = bpp; i < istop; i++)
  193513. {
  193514. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  193515. rp++;
  193516. }
  193517. break;
  193518. }
  193519. case PNG_FILTER_VALUE_UP:
  193520. {
  193521. png_uint_32 i;
  193522. png_uint_32 istop = row_info->rowbytes;
  193523. png_bytep rp = row;
  193524. png_bytep pp = prev_row;
  193525. for (i = 0; i < istop; i++)
  193526. {
  193527. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  193528. rp++;
  193529. }
  193530. break;
  193531. }
  193532. case PNG_FILTER_VALUE_AVG:
  193533. {
  193534. png_uint_32 i;
  193535. png_bytep rp = row;
  193536. png_bytep pp = prev_row;
  193537. png_bytep lp = row;
  193538. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  193539. png_uint_32 istop = row_info->rowbytes - bpp;
  193540. for (i = 0; i < bpp; i++)
  193541. {
  193542. *rp = (png_byte)(((int)(*rp) +
  193543. ((int)(*pp++) / 2 )) & 0xff);
  193544. rp++;
  193545. }
  193546. for (i = 0; i < istop; i++)
  193547. {
  193548. *rp = (png_byte)(((int)(*rp) +
  193549. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  193550. rp++;
  193551. }
  193552. break;
  193553. }
  193554. case PNG_FILTER_VALUE_PAETH:
  193555. {
  193556. png_uint_32 i;
  193557. png_bytep rp = row;
  193558. png_bytep pp = prev_row;
  193559. png_bytep lp = row;
  193560. png_bytep cp = prev_row;
  193561. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  193562. png_uint_32 istop=row_info->rowbytes - bpp;
  193563. for (i = 0; i < bpp; i++)
  193564. {
  193565. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  193566. rp++;
  193567. }
  193568. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  193569. {
  193570. int a, b, c, pa, pb, pc, p;
  193571. a = *lp++;
  193572. b = *pp++;
  193573. c = *cp++;
  193574. p = b - c;
  193575. pc = a - c;
  193576. #ifdef PNG_USE_ABS
  193577. pa = abs(p);
  193578. pb = abs(pc);
  193579. pc = abs(p + pc);
  193580. #else
  193581. pa = p < 0 ? -p : p;
  193582. pb = pc < 0 ? -pc : pc;
  193583. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  193584. #endif
  193585. /*
  193586. if (pa <= pb && pa <= pc)
  193587. p = a;
  193588. else if (pb <= pc)
  193589. p = b;
  193590. else
  193591. p = c;
  193592. */
  193593. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  193594. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  193595. rp++;
  193596. }
  193597. break;
  193598. }
  193599. default:
  193600. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  193601. *row=0;
  193602. break;
  193603. }
  193604. }
  193605. void /* PRIVATE */
  193606. png_read_finish_row(png_structp png_ptr)
  193607. {
  193608. #ifdef PNG_USE_LOCAL_ARRAYS
  193609. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  193610. /* start of interlace block */
  193611. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  193612. /* offset to next interlace block */
  193613. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  193614. /* start of interlace block in the y direction */
  193615. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  193616. /* offset to next interlace block in the y direction */
  193617. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  193618. #endif
  193619. png_debug(1, "in png_read_finish_row\n");
  193620. png_ptr->row_number++;
  193621. if (png_ptr->row_number < png_ptr->num_rows)
  193622. return;
  193623. if (png_ptr->interlaced)
  193624. {
  193625. png_ptr->row_number = 0;
  193626. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  193627. png_ptr->rowbytes + 1);
  193628. do
  193629. {
  193630. png_ptr->pass++;
  193631. if (png_ptr->pass >= 7)
  193632. break;
  193633. png_ptr->iwidth = (png_ptr->width +
  193634. png_pass_inc[png_ptr->pass] - 1 -
  193635. png_pass_start[png_ptr->pass]) /
  193636. png_pass_inc[png_ptr->pass];
  193637. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  193638. png_ptr->iwidth) + 1;
  193639. if (!(png_ptr->transformations & PNG_INTERLACE))
  193640. {
  193641. png_ptr->num_rows = (png_ptr->height +
  193642. png_pass_yinc[png_ptr->pass] - 1 -
  193643. png_pass_ystart[png_ptr->pass]) /
  193644. png_pass_yinc[png_ptr->pass];
  193645. if (!(png_ptr->num_rows))
  193646. continue;
  193647. }
  193648. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  193649. break;
  193650. } while (png_ptr->iwidth == 0);
  193651. if (png_ptr->pass < 7)
  193652. return;
  193653. }
  193654. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  193655. {
  193656. #ifdef PNG_USE_LOCAL_ARRAYS
  193657. PNG_CONST PNG_IDAT;
  193658. #endif
  193659. char extra;
  193660. int ret;
  193661. png_ptr->zstream.next_out = (Bytef *)&extra;
  193662. png_ptr->zstream.avail_out = (uInt)1;
  193663. for(;;)
  193664. {
  193665. if (!(png_ptr->zstream.avail_in))
  193666. {
  193667. while (!png_ptr->idat_size)
  193668. {
  193669. png_byte chunk_length[4];
  193670. png_crc_finish(png_ptr, 0);
  193671. png_read_data(png_ptr, chunk_length, 4);
  193672. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  193673. png_reset_crc(png_ptr);
  193674. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  193675. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  193676. png_error(png_ptr, "Not enough image data");
  193677. }
  193678. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  193679. png_ptr->zstream.next_in = png_ptr->zbuf;
  193680. if (png_ptr->zbuf_size > png_ptr->idat_size)
  193681. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  193682. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  193683. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  193684. }
  193685. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  193686. if (ret == Z_STREAM_END)
  193687. {
  193688. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  193689. png_ptr->idat_size)
  193690. png_warning(png_ptr, "Extra compressed data");
  193691. png_ptr->mode |= PNG_AFTER_IDAT;
  193692. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  193693. break;
  193694. }
  193695. if (ret != Z_OK)
  193696. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  193697. "Decompression Error");
  193698. if (!(png_ptr->zstream.avail_out))
  193699. {
  193700. png_warning(png_ptr, "Extra compressed data.");
  193701. png_ptr->mode |= PNG_AFTER_IDAT;
  193702. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  193703. break;
  193704. }
  193705. }
  193706. png_ptr->zstream.avail_out = 0;
  193707. }
  193708. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  193709. png_warning(png_ptr, "Extra compression data");
  193710. inflateReset(&png_ptr->zstream);
  193711. png_ptr->mode |= PNG_AFTER_IDAT;
  193712. }
  193713. void /* PRIVATE */
  193714. png_read_start_row(png_structp png_ptr)
  193715. {
  193716. #ifdef PNG_USE_LOCAL_ARRAYS
  193717. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  193718. /* start of interlace block */
  193719. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  193720. /* offset to next interlace block */
  193721. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  193722. /* start of interlace block in the y direction */
  193723. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  193724. /* offset to next interlace block in the y direction */
  193725. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  193726. #endif
  193727. int max_pixel_depth;
  193728. png_uint_32 row_bytes;
  193729. png_debug(1, "in png_read_start_row\n");
  193730. png_ptr->zstream.avail_in = 0;
  193731. png_init_read_transformations(png_ptr);
  193732. if (png_ptr->interlaced)
  193733. {
  193734. if (!(png_ptr->transformations & PNG_INTERLACE))
  193735. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  193736. png_pass_ystart[0]) / png_pass_yinc[0];
  193737. else
  193738. png_ptr->num_rows = png_ptr->height;
  193739. png_ptr->iwidth = (png_ptr->width +
  193740. png_pass_inc[png_ptr->pass] - 1 -
  193741. png_pass_start[png_ptr->pass]) /
  193742. png_pass_inc[png_ptr->pass];
  193743. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  193744. png_ptr->irowbytes = (png_size_t)row_bytes;
  193745. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  193746. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  193747. }
  193748. else
  193749. {
  193750. png_ptr->num_rows = png_ptr->height;
  193751. png_ptr->iwidth = png_ptr->width;
  193752. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  193753. }
  193754. max_pixel_depth = png_ptr->pixel_depth;
  193755. #if defined(PNG_READ_PACK_SUPPORTED)
  193756. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  193757. max_pixel_depth = 8;
  193758. #endif
  193759. #if defined(PNG_READ_EXPAND_SUPPORTED)
  193760. if (png_ptr->transformations & PNG_EXPAND)
  193761. {
  193762. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193763. {
  193764. if (png_ptr->num_trans)
  193765. max_pixel_depth = 32;
  193766. else
  193767. max_pixel_depth = 24;
  193768. }
  193769. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  193770. {
  193771. if (max_pixel_depth < 8)
  193772. max_pixel_depth = 8;
  193773. if (png_ptr->num_trans)
  193774. max_pixel_depth *= 2;
  193775. }
  193776. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  193777. {
  193778. if (png_ptr->num_trans)
  193779. {
  193780. max_pixel_depth *= 4;
  193781. max_pixel_depth /= 3;
  193782. }
  193783. }
  193784. }
  193785. #endif
  193786. #if defined(PNG_READ_FILLER_SUPPORTED)
  193787. if (png_ptr->transformations & (PNG_FILLER))
  193788. {
  193789. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193790. max_pixel_depth = 32;
  193791. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  193792. {
  193793. if (max_pixel_depth <= 8)
  193794. max_pixel_depth = 16;
  193795. else
  193796. max_pixel_depth = 32;
  193797. }
  193798. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  193799. {
  193800. if (max_pixel_depth <= 32)
  193801. max_pixel_depth = 32;
  193802. else
  193803. max_pixel_depth = 64;
  193804. }
  193805. }
  193806. #endif
  193807. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  193808. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  193809. {
  193810. if (
  193811. #if defined(PNG_READ_EXPAND_SUPPORTED)
  193812. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  193813. #endif
  193814. #if defined(PNG_READ_FILLER_SUPPORTED)
  193815. (png_ptr->transformations & (PNG_FILLER)) ||
  193816. #endif
  193817. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  193818. {
  193819. if (max_pixel_depth <= 16)
  193820. max_pixel_depth = 32;
  193821. else
  193822. max_pixel_depth = 64;
  193823. }
  193824. else
  193825. {
  193826. if (max_pixel_depth <= 8)
  193827. {
  193828. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193829. max_pixel_depth = 32;
  193830. else
  193831. max_pixel_depth = 24;
  193832. }
  193833. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193834. max_pixel_depth = 64;
  193835. else
  193836. max_pixel_depth = 48;
  193837. }
  193838. }
  193839. #endif
  193840. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  193841. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  193842. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  193843. {
  193844. int user_pixel_depth=png_ptr->user_transform_depth*
  193845. png_ptr->user_transform_channels;
  193846. if(user_pixel_depth > max_pixel_depth)
  193847. max_pixel_depth=user_pixel_depth;
  193848. }
  193849. #endif
  193850. /* align the width on the next larger 8 pixels. Mainly used
  193851. for interlacing */
  193852. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  193853. /* calculate the maximum bytes needed, adding a byte and a pixel
  193854. for safety's sake */
  193855. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  193856. 1 + ((max_pixel_depth + 7) >> 3);
  193857. #ifdef PNG_MAX_MALLOC_64K
  193858. if (row_bytes > (png_uint_32)65536L)
  193859. png_error(png_ptr, "This image requires a row greater than 64KB");
  193860. #endif
  193861. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  193862. png_ptr->row_buf = png_ptr->big_row_buf+32;
  193863. #ifdef PNG_MAX_MALLOC_64K
  193864. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  193865. png_error(png_ptr, "This image requires a row greater than 64KB");
  193866. #endif
  193867. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  193868. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  193869. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  193870. png_ptr->rowbytes + 1));
  193871. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  193872. png_debug1(3, "width = %lu,\n", png_ptr->width);
  193873. png_debug1(3, "height = %lu,\n", png_ptr->height);
  193874. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  193875. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  193876. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  193877. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  193878. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  193879. }
  193880. #endif /* PNG_READ_SUPPORTED */
  193881. /*** End of inlined file: pngrutil.c ***/
  193882. /*** Start of inlined file: pngset.c ***/
  193883. /* pngset.c - storage of image information into info struct
  193884. *
  193885. * Last changed in libpng 1.2.21 [October 4, 2007]
  193886. * For conditions of distribution and use, see copyright notice in png.h
  193887. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193888. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193889. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193890. *
  193891. * The functions here are used during reads to store data from the file
  193892. * into the info struct, and during writes to store application data
  193893. * into the info struct for writing into the file. This abstracts the
  193894. * info struct and allows us to change the structure in the future.
  193895. */
  193896. #define PNG_INTERNAL
  193897. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  193898. #if defined(PNG_bKGD_SUPPORTED)
  193899. void PNGAPI
  193900. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  193901. {
  193902. png_debug1(1, "in %s storage function\n", "bKGD");
  193903. if (png_ptr == NULL || info_ptr == NULL)
  193904. return;
  193905. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  193906. info_ptr->valid |= PNG_INFO_bKGD;
  193907. }
  193908. #endif
  193909. #if defined(PNG_cHRM_SUPPORTED)
  193910. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193911. void PNGAPI
  193912. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  193913. double white_x, double white_y, double red_x, double red_y,
  193914. double green_x, double green_y, double blue_x, double blue_y)
  193915. {
  193916. png_debug1(1, "in %s storage function\n", "cHRM");
  193917. if (png_ptr == NULL || info_ptr == NULL)
  193918. return;
  193919. if (white_x < 0.0 || white_y < 0.0 ||
  193920. red_x < 0.0 || red_y < 0.0 ||
  193921. green_x < 0.0 || green_y < 0.0 ||
  193922. blue_x < 0.0 || blue_y < 0.0)
  193923. {
  193924. png_warning(png_ptr,
  193925. "Ignoring attempt to set negative chromaticity value");
  193926. return;
  193927. }
  193928. if (white_x > 21474.83 || white_y > 21474.83 ||
  193929. red_x > 21474.83 || red_y > 21474.83 ||
  193930. green_x > 21474.83 || green_y > 21474.83 ||
  193931. blue_x > 21474.83 || blue_y > 21474.83)
  193932. {
  193933. png_warning(png_ptr,
  193934. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  193935. return;
  193936. }
  193937. info_ptr->x_white = (float)white_x;
  193938. info_ptr->y_white = (float)white_y;
  193939. info_ptr->x_red = (float)red_x;
  193940. info_ptr->y_red = (float)red_y;
  193941. info_ptr->x_green = (float)green_x;
  193942. info_ptr->y_green = (float)green_y;
  193943. info_ptr->x_blue = (float)blue_x;
  193944. info_ptr->y_blue = (float)blue_y;
  193945. #ifdef PNG_FIXED_POINT_SUPPORTED
  193946. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  193947. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  193948. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  193949. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  193950. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  193951. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  193952. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  193953. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  193954. #endif
  193955. info_ptr->valid |= PNG_INFO_cHRM;
  193956. }
  193957. #endif
  193958. #ifdef PNG_FIXED_POINT_SUPPORTED
  193959. void PNGAPI
  193960. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  193961. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  193962. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  193963. png_fixed_point blue_x, png_fixed_point blue_y)
  193964. {
  193965. png_debug1(1, "in %s storage function\n", "cHRM");
  193966. if (png_ptr == NULL || info_ptr == NULL)
  193967. return;
  193968. if (white_x < 0 || white_y < 0 ||
  193969. red_x < 0 || red_y < 0 ||
  193970. green_x < 0 || green_y < 0 ||
  193971. blue_x < 0 || blue_y < 0)
  193972. {
  193973. png_warning(png_ptr,
  193974. "Ignoring attempt to set negative chromaticity value");
  193975. return;
  193976. }
  193977. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193978. if (white_x > (double) PNG_UINT_31_MAX ||
  193979. white_y > (double) PNG_UINT_31_MAX ||
  193980. red_x > (double) PNG_UINT_31_MAX ||
  193981. red_y > (double) PNG_UINT_31_MAX ||
  193982. green_x > (double) PNG_UINT_31_MAX ||
  193983. green_y > (double) PNG_UINT_31_MAX ||
  193984. blue_x > (double) PNG_UINT_31_MAX ||
  193985. blue_y > (double) PNG_UINT_31_MAX)
  193986. #else
  193987. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  193988. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  193989. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  193990. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  193991. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  193992. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  193993. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  193994. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  193995. #endif
  193996. {
  193997. png_warning(png_ptr,
  193998. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  193999. return;
  194000. }
  194001. info_ptr->int_x_white = white_x;
  194002. info_ptr->int_y_white = white_y;
  194003. info_ptr->int_x_red = red_x;
  194004. info_ptr->int_y_red = red_y;
  194005. info_ptr->int_x_green = green_x;
  194006. info_ptr->int_y_green = green_y;
  194007. info_ptr->int_x_blue = blue_x;
  194008. info_ptr->int_y_blue = blue_y;
  194009. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194010. info_ptr->x_white = (float)(white_x/100000.);
  194011. info_ptr->y_white = (float)(white_y/100000.);
  194012. info_ptr->x_red = (float)( red_x/100000.);
  194013. info_ptr->y_red = (float)( red_y/100000.);
  194014. info_ptr->x_green = (float)(green_x/100000.);
  194015. info_ptr->y_green = (float)(green_y/100000.);
  194016. info_ptr->x_blue = (float)( blue_x/100000.);
  194017. info_ptr->y_blue = (float)( blue_y/100000.);
  194018. #endif
  194019. info_ptr->valid |= PNG_INFO_cHRM;
  194020. }
  194021. #endif
  194022. #endif
  194023. #if defined(PNG_gAMA_SUPPORTED)
  194024. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194025. void PNGAPI
  194026. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  194027. {
  194028. double gamma;
  194029. png_debug1(1, "in %s storage function\n", "gAMA");
  194030. if (png_ptr == NULL || info_ptr == NULL)
  194031. return;
  194032. /* Check for overflow */
  194033. if (file_gamma > 21474.83)
  194034. {
  194035. png_warning(png_ptr, "Limiting gamma to 21474.83");
  194036. gamma=21474.83;
  194037. }
  194038. else
  194039. gamma=file_gamma;
  194040. info_ptr->gamma = (float)gamma;
  194041. #ifdef PNG_FIXED_POINT_SUPPORTED
  194042. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  194043. #endif
  194044. info_ptr->valid |= PNG_INFO_gAMA;
  194045. if(gamma == 0.0)
  194046. png_warning(png_ptr, "Setting gamma=0");
  194047. }
  194048. #endif
  194049. void PNGAPI
  194050. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  194051. int_gamma)
  194052. {
  194053. png_fixed_point gamma;
  194054. png_debug1(1, "in %s storage function\n", "gAMA");
  194055. if (png_ptr == NULL || info_ptr == NULL)
  194056. return;
  194057. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  194058. {
  194059. png_warning(png_ptr, "Limiting gamma to 21474.83");
  194060. gamma=PNG_UINT_31_MAX;
  194061. }
  194062. else
  194063. {
  194064. if (int_gamma < 0)
  194065. {
  194066. png_warning(png_ptr, "Setting negative gamma to zero");
  194067. gamma=0;
  194068. }
  194069. else
  194070. gamma=int_gamma;
  194071. }
  194072. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194073. info_ptr->gamma = (float)(gamma/100000.);
  194074. #endif
  194075. #ifdef PNG_FIXED_POINT_SUPPORTED
  194076. info_ptr->int_gamma = gamma;
  194077. #endif
  194078. info_ptr->valid |= PNG_INFO_gAMA;
  194079. if(gamma == 0)
  194080. png_warning(png_ptr, "Setting gamma=0");
  194081. }
  194082. #endif
  194083. #if defined(PNG_hIST_SUPPORTED)
  194084. void PNGAPI
  194085. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  194086. {
  194087. int i;
  194088. png_debug1(1, "in %s storage function\n", "hIST");
  194089. if (png_ptr == NULL || info_ptr == NULL)
  194090. return;
  194091. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  194092. > PNG_MAX_PALETTE_LENGTH)
  194093. {
  194094. png_warning(png_ptr,
  194095. "Invalid palette size, hIST allocation skipped.");
  194096. return;
  194097. }
  194098. #ifdef PNG_FREE_ME_SUPPORTED
  194099. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  194100. #endif
  194101. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  194102. 1.2.1 */
  194103. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  194104. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  194105. if (png_ptr->hist == NULL)
  194106. {
  194107. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  194108. return;
  194109. }
  194110. for (i = 0; i < info_ptr->num_palette; i++)
  194111. png_ptr->hist[i] = hist[i];
  194112. info_ptr->hist = png_ptr->hist;
  194113. info_ptr->valid |= PNG_INFO_hIST;
  194114. #ifdef PNG_FREE_ME_SUPPORTED
  194115. info_ptr->free_me |= PNG_FREE_HIST;
  194116. #else
  194117. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  194118. #endif
  194119. }
  194120. #endif
  194121. void PNGAPI
  194122. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  194123. png_uint_32 width, png_uint_32 height, int bit_depth,
  194124. int color_type, int interlace_type, int compression_type,
  194125. int filter_type)
  194126. {
  194127. png_debug1(1, "in %s storage function\n", "IHDR");
  194128. if (png_ptr == NULL || info_ptr == NULL)
  194129. return;
  194130. /* check for width and height valid values */
  194131. if (width == 0 || height == 0)
  194132. png_error(png_ptr, "Image width or height is zero in IHDR");
  194133. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  194134. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  194135. png_error(png_ptr, "image size exceeds user limits in IHDR");
  194136. #else
  194137. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  194138. png_error(png_ptr, "image size exceeds user limits in IHDR");
  194139. #endif
  194140. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  194141. png_error(png_ptr, "Invalid image size in IHDR");
  194142. if ( width > (PNG_UINT_32_MAX
  194143. >> 3) /* 8-byte RGBA pixels */
  194144. - 64 /* bigrowbuf hack */
  194145. - 1 /* filter byte */
  194146. - 7*8 /* rounding of width to multiple of 8 pixels */
  194147. - 8) /* extra max_pixel_depth pad */
  194148. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  194149. /* check other values */
  194150. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  194151. bit_depth != 8 && bit_depth != 16)
  194152. png_error(png_ptr, "Invalid bit depth in IHDR");
  194153. if (color_type < 0 || color_type == 1 ||
  194154. color_type == 5 || color_type > 6)
  194155. png_error(png_ptr, "Invalid color type in IHDR");
  194156. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  194157. ((color_type == PNG_COLOR_TYPE_RGB ||
  194158. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  194159. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  194160. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  194161. if (interlace_type >= PNG_INTERLACE_LAST)
  194162. png_error(png_ptr, "Unknown interlace method in IHDR");
  194163. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  194164. png_error(png_ptr, "Unknown compression method in IHDR");
  194165. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194166. /* Accept filter_method 64 (intrapixel differencing) only if
  194167. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  194168. * 2. Libpng did not read a PNG signature (this filter_method is only
  194169. * used in PNG datastreams that are embedded in MNG datastreams) and
  194170. * 3. The application called png_permit_mng_features with a mask that
  194171. * included PNG_FLAG_MNG_FILTER_64 and
  194172. * 4. The filter_method is 64 and
  194173. * 5. The color_type is RGB or RGBA
  194174. */
  194175. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  194176. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  194177. if(filter_type != PNG_FILTER_TYPE_BASE)
  194178. {
  194179. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  194180. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  194181. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  194182. (color_type == PNG_COLOR_TYPE_RGB ||
  194183. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  194184. png_error(png_ptr, "Unknown filter method in IHDR");
  194185. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  194186. png_warning(png_ptr, "Invalid filter method in IHDR");
  194187. }
  194188. #else
  194189. if(filter_type != PNG_FILTER_TYPE_BASE)
  194190. png_error(png_ptr, "Unknown filter method in IHDR");
  194191. #endif
  194192. info_ptr->width = width;
  194193. info_ptr->height = height;
  194194. info_ptr->bit_depth = (png_byte)bit_depth;
  194195. info_ptr->color_type =(png_byte) color_type;
  194196. info_ptr->compression_type = (png_byte)compression_type;
  194197. info_ptr->filter_type = (png_byte)filter_type;
  194198. info_ptr->interlace_type = (png_byte)interlace_type;
  194199. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194200. info_ptr->channels = 1;
  194201. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194202. info_ptr->channels = 3;
  194203. else
  194204. info_ptr->channels = 1;
  194205. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  194206. info_ptr->channels++;
  194207. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  194208. /* check for potential overflow */
  194209. if (width > (PNG_UINT_32_MAX
  194210. >> 3) /* 8-byte RGBA pixels */
  194211. - 64 /* bigrowbuf hack */
  194212. - 1 /* filter byte */
  194213. - 7*8 /* rounding of width to multiple of 8 pixels */
  194214. - 8) /* extra max_pixel_depth pad */
  194215. info_ptr->rowbytes = (png_size_t)0;
  194216. else
  194217. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  194218. }
  194219. #if defined(PNG_oFFs_SUPPORTED)
  194220. void PNGAPI
  194221. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  194222. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  194223. {
  194224. png_debug1(1, "in %s storage function\n", "oFFs");
  194225. if (png_ptr == NULL || info_ptr == NULL)
  194226. return;
  194227. info_ptr->x_offset = offset_x;
  194228. info_ptr->y_offset = offset_y;
  194229. info_ptr->offset_unit_type = (png_byte)unit_type;
  194230. info_ptr->valid |= PNG_INFO_oFFs;
  194231. }
  194232. #endif
  194233. #if defined(PNG_pCAL_SUPPORTED)
  194234. void PNGAPI
  194235. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  194236. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  194237. png_charp units, png_charpp params)
  194238. {
  194239. png_uint_32 length;
  194240. int i;
  194241. png_debug1(1, "in %s storage function\n", "pCAL");
  194242. if (png_ptr == NULL || info_ptr == NULL)
  194243. return;
  194244. length = png_strlen(purpose) + 1;
  194245. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  194246. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  194247. if (info_ptr->pcal_purpose == NULL)
  194248. {
  194249. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  194250. return;
  194251. }
  194252. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  194253. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  194254. info_ptr->pcal_X0 = X0;
  194255. info_ptr->pcal_X1 = X1;
  194256. info_ptr->pcal_type = (png_byte)type;
  194257. info_ptr->pcal_nparams = (png_byte)nparams;
  194258. length = png_strlen(units) + 1;
  194259. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  194260. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  194261. if (info_ptr->pcal_units == NULL)
  194262. {
  194263. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  194264. return;
  194265. }
  194266. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  194267. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  194268. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  194269. if (info_ptr->pcal_params == NULL)
  194270. {
  194271. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  194272. return;
  194273. }
  194274. info_ptr->pcal_params[nparams] = NULL;
  194275. for (i = 0; i < nparams; i++)
  194276. {
  194277. length = png_strlen(params[i]) + 1;
  194278. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  194279. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  194280. if (info_ptr->pcal_params[i] == NULL)
  194281. {
  194282. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  194283. return;
  194284. }
  194285. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  194286. }
  194287. info_ptr->valid |= PNG_INFO_pCAL;
  194288. #ifdef PNG_FREE_ME_SUPPORTED
  194289. info_ptr->free_me |= PNG_FREE_PCAL;
  194290. #endif
  194291. }
  194292. #endif
  194293. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  194294. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194295. void PNGAPI
  194296. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  194297. int unit, double width, double height)
  194298. {
  194299. png_debug1(1, "in %s storage function\n", "sCAL");
  194300. if (png_ptr == NULL || info_ptr == NULL)
  194301. return;
  194302. info_ptr->scal_unit = (png_byte)unit;
  194303. info_ptr->scal_pixel_width = width;
  194304. info_ptr->scal_pixel_height = height;
  194305. info_ptr->valid |= PNG_INFO_sCAL;
  194306. }
  194307. #else
  194308. #ifdef PNG_FIXED_POINT_SUPPORTED
  194309. void PNGAPI
  194310. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  194311. int unit, png_charp swidth, png_charp sheight)
  194312. {
  194313. png_uint_32 length;
  194314. png_debug1(1, "in %s storage function\n", "sCAL");
  194315. if (png_ptr == NULL || info_ptr == NULL)
  194316. return;
  194317. info_ptr->scal_unit = (png_byte)unit;
  194318. length = png_strlen(swidth) + 1;
  194319. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  194320. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  194321. if (info_ptr->scal_s_width == NULL)
  194322. {
  194323. png_warning(png_ptr,
  194324. "Memory allocation failed while processing sCAL.");
  194325. }
  194326. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  194327. length = png_strlen(sheight) + 1;
  194328. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  194329. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  194330. if (info_ptr->scal_s_height == NULL)
  194331. {
  194332. png_free (png_ptr, info_ptr->scal_s_width);
  194333. png_warning(png_ptr,
  194334. "Memory allocation failed while processing sCAL.");
  194335. }
  194336. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  194337. info_ptr->valid |= PNG_INFO_sCAL;
  194338. #ifdef PNG_FREE_ME_SUPPORTED
  194339. info_ptr->free_me |= PNG_FREE_SCAL;
  194340. #endif
  194341. }
  194342. #endif
  194343. #endif
  194344. #endif
  194345. #if defined(PNG_pHYs_SUPPORTED)
  194346. void PNGAPI
  194347. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  194348. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  194349. {
  194350. png_debug1(1, "in %s storage function\n", "pHYs");
  194351. if (png_ptr == NULL || info_ptr == NULL)
  194352. return;
  194353. info_ptr->x_pixels_per_unit = res_x;
  194354. info_ptr->y_pixels_per_unit = res_y;
  194355. info_ptr->phys_unit_type = (png_byte)unit_type;
  194356. info_ptr->valid |= PNG_INFO_pHYs;
  194357. }
  194358. #endif
  194359. void PNGAPI
  194360. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  194361. png_colorp palette, int num_palette)
  194362. {
  194363. png_debug1(1, "in %s storage function\n", "PLTE");
  194364. if (png_ptr == NULL || info_ptr == NULL)
  194365. return;
  194366. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  194367. {
  194368. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194369. png_error(png_ptr, "Invalid palette length");
  194370. else
  194371. {
  194372. png_warning(png_ptr, "Invalid palette length");
  194373. return;
  194374. }
  194375. }
  194376. /*
  194377. * It may not actually be necessary to set png_ptr->palette here;
  194378. * we do it for backward compatibility with the way the png_handle_tRNS
  194379. * function used to do the allocation.
  194380. */
  194381. #ifdef PNG_FREE_ME_SUPPORTED
  194382. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  194383. #endif
  194384. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  194385. of num_palette entries,
  194386. in case of an invalid PNG file that has too-large sample values. */
  194387. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  194388. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  194389. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  194390. png_sizeof(png_color));
  194391. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  194392. info_ptr->palette = png_ptr->palette;
  194393. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  194394. #ifdef PNG_FREE_ME_SUPPORTED
  194395. info_ptr->free_me |= PNG_FREE_PLTE;
  194396. #else
  194397. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  194398. #endif
  194399. info_ptr->valid |= PNG_INFO_PLTE;
  194400. }
  194401. #if defined(PNG_sBIT_SUPPORTED)
  194402. void PNGAPI
  194403. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  194404. png_color_8p sig_bit)
  194405. {
  194406. png_debug1(1, "in %s storage function\n", "sBIT");
  194407. if (png_ptr == NULL || info_ptr == NULL)
  194408. return;
  194409. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  194410. info_ptr->valid |= PNG_INFO_sBIT;
  194411. }
  194412. #endif
  194413. #if defined(PNG_sRGB_SUPPORTED)
  194414. void PNGAPI
  194415. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  194416. {
  194417. png_debug1(1, "in %s storage function\n", "sRGB");
  194418. if (png_ptr == NULL || info_ptr == NULL)
  194419. return;
  194420. info_ptr->srgb_intent = (png_byte)intent;
  194421. info_ptr->valid |= PNG_INFO_sRGB;
  194422. }
  194423. void PNGAPI
  194424. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  194425. int intent)
  194426. {
  194427. #if defined(PNG_gAMA_SUPPORTED)
  194428. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194429. float file_gamma;
  194430. #endif
  194431. #ifdef PNG_FIXED_POINT_SUPPORTED
  194432. png_fixed_point int_file_gamma;
  194433. #endif
  194434. #endif
  194435. #if defined(PNG_cHRM_SUPPORTED)
  194436. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194437. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  194438. #endif
  194439. #ifdef PNG_FIXED_POINT_SUPPORTED
  194440. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  194441. int_green_y, int_blue_x, int_blue_y;
  194442. #endif
  194443. #endif
  194444. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  194445. if (png_ptr == NULL || info_ptr == NULL)
  194446. return;
  194447. png_set_sRGB(png_ptr, info_ptr, intent);
  194448. #if defined(PNG_gAMA_SUPPORTED)
  194449. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194450. file_gamma = (float).45455;
  194451. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  194452. #endif
  194453. #ifdef PNG_FIXED_POINT_SUPPORTED
  194454. int_file_gamma = 45455L;
  194455. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  194456. #endif
  194457. #endif
  194458. #if defined(PNG_cHRM_SUPPORTED)
  194459. #ifdef PNG_FIXED_POINT_SUPPORTED
  194460. int_white_x = 31270L;
  194461. int_white_y = 32900L;
  194462. int_red_x = 64000L;
  194463. int_red_y = 33000L;
  194464. int_green_x = 30000L;
  194465. int_green_y = 60000L;
  194466. int_blue_x = 15000L;
  194467. int_blue_y = 6000L;
  194468. png_set_cHRM_fixed(png_ptr, info_ptr,
  194469. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  194470. int_blue_x, int_blue_y);
  194471. #endif
  194472. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194473. white_x = (float).3127;
  194474. white_y = (float).3290;
  194475. red_x = (float).64;
  194476. red_y = (float).33;
  194477. green_x = (float).30;
  194478. green_y = (float).60;
  194479. blue_x = (float).15;
  194480. blue_y = (float).06;
  194481. png_set_cHRM(png_ptr, info_ptr,
  194482. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  194483. #endif
  194484. #endif
  194485. }
  194486. #endif
  194487. #if defined(PNG_iCCP_SUPPORTED)
  194488. void PNGAPI
  194489. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  194490. png_charp name, int compression_type,
  194491. png_charp profile, png_uint_32 proflen)
  194492. {
  194493. png_charp new_iccp_name;
  194494. png_charp new_iccp_profile;
  194495. png_debug1(1, "in %s storage function\n", "iCCP");
  194496. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  194497. return;
  194498. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  194499. if (new_iccp_name == NULL)
  194500. {
  194501. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  194502. return;
  194503. }
  194504. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  194505. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  194506. if (new_iccp_profile == NULL)
  194507. {
  194508. png_free (png_ptr, new_iccp_name);
  194509. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  194510. return;
  194511. }
  194512. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  194513. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  194514. info_ptr->iccp_proflen = proflen;
  194515. info_ptr->iccp_name = new_iccp_name;
  194516. info_ptr->iccp_profile = new_iccp_profile;
  194517. /* Compression is always zero but is here so the API and info structure
  194518. * does not have to change if we introduce multiple compression types */
  194519. info_ptr->iccp_compression = (png_byte)compression_type;
  194520. #ifdef PNG_FREE_ME_SUPPORTED
  194521. info_ptr->free_me |= PNG_FREE_ICCP;
  194522. #endif
  194523. info_ptr->valid |= PNG_INFO_iCCP;
  194524. }
  194525. #endif
  194526. #if defined(PNG_TEXT_SUPPORTED)
  194527. void PNGAPI
  194528. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  194529. int num_text)
  194530. {
  194531. int ret;
  194532. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  194533. if (ret)
  194534. png_error(png_ptr, "Insufficient memory to store text");
  194535. }
  194536. int /* PRIVATE */
  194537. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  194538. int num_text)
  194539. {
  194540. int i;
  194541. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  194542. "text" : (png_const_charp)png_ptr->chunk_name));
  194543. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  194544. return(0);
  194545. /* Make sure we have enough space in the "text" array in info_struct
  194546. * to hold all of the incoming text_ptr objects.
  194547. */
  194548. if (info_ptr->num_text + num_text > info_ptr->max_text)
  194549. {
  194550. if (info_ptr->text != NULL)
  194551. {
  194552. png_textp old_text;
  194553. int old_max;
  194554. old_max = info_ptr->max_text;
  194555. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  194556. old_text = info_ptr->text;
  194557. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  194558. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  194559. if (info_ptr->text == NULL)
  194560. {
  194561. png_free(png_ptr, old_text);
  194562. return(1);
  194563. }
  194564. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  194565. png_sizeof(png_text)));
  194566. png_free(png_ptr, old_text);
  194567. }
  194568. else
  194569. {
  194570. info_ptr->max_text = num_text + 8;
  194571. info_ptr->num_text = 0;
  194572. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  194573. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  194574. if (info_ptr->text == NULL)
  194575. return(1);
  194576. #ifdef PNG_FREE_ME_SUPPORTED
  194577. info_ptr->free_me |= PNG_FREE_TEXT;
  194578. #endif
  194579. }
  194580. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  194581. info_ptr->max_text);
  194582. }
  194583. for (i = 0; i < num_text; i++)
  194584. {
  194585. png_size_t text_length,key_len;
  194586. png_size_t lang_len,lang_key_len;
  194587. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  194588. if (text_ptr[i].key == NULL)
  194589. continue;
  194590. key_len = png_strlen(text_ptr[i].key);
  194591. if(text_ptr[i].compression <= 0)
  194592. {
  194593. lang_len = 0;
  194594. lang_key_len = 0;
  194595. }
  194596. else
  194597. #ifdef PNG_iTXt_SUPPORTED
  194598. {
  194599. /* set iTXt data */
  194600. if (text_ptr[i].lang != NULL)
  194601. lang_len = png_strlen(text_ptr[i].lang);
  194602. else
  194603. lang_len = 0;
  194604. if (text_ptr[i].lang_key != NULL)
  194605. lang_key_len = png_strlen(text_ptr[i].lang_key);
  194606. else
  194607. lang_key_len = 0;
  194608. }
  194609. #else
  194610. {
  194611. png_warning(png_ptr, "iTXt chunk not supported.");
  194612. continue;
  194613. }
  194614. #endif
  194615. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  194616. {
  194617. text_length = 0;
  194618. #ifdef PNG_iTXt_SUPPORTED
  194619. if(text_ptr[i].compression > 0)
  194620. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  194621. else
  194622. #endif
  194623. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  194624. }
  194625. else
  194626. {
  194627. text_length = png_strlen(text_ptr[i].text);
  194628. textp->compression = text_ptr[i].compression;
  194629. }
  194630. textp->key = (png_charp)png_malloc_warn(png_ptr,
  194631. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  194632. if (textp->key == NULL)
  194633. return(1);
  194634. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  194635. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  194636. (int)textp->key);
  194637. png_memcpy(textp->key, text_ptr[i].key,
  194638. (png_size_t)(key_len));
  194639. *(textp->key+key_len) = '\0';
  194640. #ifdef PNG_iTXt_SUPPORTED
  194641. if (text_ptr[i].compression > 0)
  194642. {
  194643. textp->lang=textp->key + key_len + 1;
  194644. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  194645. *(textp->lang+lang_len) = '\0';
  194646. textp->lang_key=textp->lang + lang_len + 1;
  194647. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  194648. *(textp->lang_key+lang_key_len) = '\0';
  194649. textp->text=textp->lang_key + lang_key_len + 1;
  194650. }
  194651. else
  194652. #endif
  194653. {
  194654. #ifdef PNG_iTXt_SUPPORTED
  194655. textp->lang=NULL;
  194656. textp->lang_key=NULL;
  194657. #endif
  194658. textp->text=textp->key + key_len + 1;
  194659. }
  194660. if(text_length)
  194661. png_memcpy(textp->text, text_ptr[i].text,
  194662. (png_size_t)(text_length));
  194663. *(textp->text+text_length) = '\0';
  194664. #ifdef PNG_iTXt_SUPPORTED
  194665. if(textp->compression > 0)
  194666. {
  194667. textp->text_length = 0;
  194668. textp->itxt_length = text_length;
  194669. }
  194670. else
  194671. #endif
  194672. {
  194673. textp->text_length = text_length;
  194674. #ifdef PNG_iTXt_SUPPORTED
  194675. textp->itxt_length = 0;
  194676. #endif
  194677. }
  194678. info_ptr->num_text++;
  194679. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  194680. }
  194681. return(0);
  194682. }
  194683. #endif
  194684. #if defined(PNG_tIME_SUPPORTED)
  194685. void PNGAPI
  194686. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  194687. {
  194688. png_debug1(1, "in %s storage function\n", "tIME");
  194689. if (png_ptr == NULL || info_ptr == NULL ||
  194690. (png_ptr->mode & PNG_WROTE_tIME))
  194691. return;
  194692. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  194693. info_ptr->valid |= PNG_INFO_tIME;
  194694. }
  194695. #endif
  194696. #if defined(PNG_tRNS_SUPPORTED)
  194697. void PNGAPI
  194698. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  194699. png_bytep trans, int num_trans, png_color_16p trans_values)
  194700. {
  194701. png_debug1(1, "in %s storage function\n", "tRNS");
  194702. if (png_ptr == NULL || info_ptr == NULL)
  194703. return;
  194704. if (trans != NULL)
  194705. {
  194706. /*
  194707. * It may not actually be necessary to set png_ptr->trans here;
  194708. * we do it for backward compatibility with the way the png_handle_tRNS
  194709. * function used to do the allocation.
  194710. */
  194711. #ifdef PNG_FREE_ME_SUPPORTED
  194712. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  194713. #endif
  194714. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  194715. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  194716. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  194717. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  194718. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  194719. #ifdef PNG_FREE_ME_SUPPORTED
  194720. info_ptr->free_me |= PNG_FREE_TRNS;
  194721. #else
  194722. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  194723. #endif
  194724. }
  194725. if (trans_values != NULL)
  194726. {
  194727. png_memcpy(&(info_ptr->trans_values), trans_values,
  194728. png_sizeof(png_color_16));
  194729. if (num_trans == 0)
  194730. num_trans = 1;
  194731. }
  194732. info_ptr->num_trans = (png_uint_16)num_trans;
  194733. info_ptr->valid |= PNG_INFO_tRNS;
  194734. }
  194735. #endif
  194736. #if defined(PNG_sPLT_SUPPORTED)
  194737. void PNGAPI
  194738. png_set_sPLT(png_structp png_ptr,
  194739. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  194740. {
  194741. png_sPLT_tp np;
  194742. int i;
  194743. if (png_ptr == NULL || info_ptr == NULL)
  194744. return;
  194745. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  194746. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  194747. if (np == NULL)
  194748. {
  194749. png_warning(png_ptr, "No memory for sPLT palettes.");
  194750. return;
  194751. }
  194752. png_memcpy(np, info_ptr->splt_palettes,
  194753. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  194754. png_free(png_ptr, info_ptr->splt_palettes);
  194755. info_ptr->splt_palettes=NULL;
  194756. for (i = 0; i < nentries; i++)
  194757. {
  194758. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  194759. png_sPLT_tp from = entries + i;
  194760. to->name = (png_charp)png_malloc_warn(png_ptr,
  194761. png_strlen(from->name) + 1);
  194762. if (to->name == NULL)
  194763. {
  194764. png_warning(png_ptr,
  194765. "Out of memory while processing sPLT chunk");
  194766. }
  194767. /* TODO: use png_malloc_warn */
  194768. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  194769. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  194770. from->nentries * png_sizeof(png_sPLT_entry));
  194771. /* TODO: use png_malloc_warn */
  194772. png_memcpy(to->entries, from->entries,
  194773. from->nentries * png_sizeof(png_sPLT_entry));
  194774. if (to->entries == NULL)
  194775. {
  194776. png_warning(png_ptr,
  194777. "Out of memory while processing sPLT chunk");
  194778. png_free(png_ptr,to->name);
  194779. to->name = NULL;
  194780. }
  194781. to->nentries = from->nentries;
  194782. to->depth = from->depth;
  194783. }
  194784. info_ptr->splt_palettes = np;
  194785. info_ptr->splt_palettes_num += nentries;
  194786. info_ptr->valid |= PNG_INFO_sPLT;
  194787. #ifdef PNG_FREE_ME_SUPPORTED
  194788. info_ptr->free_me |= PNG_FREE_SPLT;
  194789. #endif
  194790. }
  194791. #endif /* PNG_sPLT_SUPPORTED */
  194792. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  194793. void PNGAPI
  194794. png_set_unknown_chunks(png_structp png_ptr,
  194795. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  194796. {
  194797. png_unknown_chunkp np;
  194798. int i;
  194799. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  194800. return;
  194801. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  194802. (info_ptr->unknown_chunks_num + num_unknowns) *
  194803. png_sizeof(png_unknown_chunk));
  194804. if (np == NULL)
  194805. {
  194806. png_warning(png_ptr,
  194807. "Out of memory while processing unknown chunk.");
  194808. return;
  194809. }
  194810. png_memcpy(np, info_ptr->unknown_chunks,
  194811. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  194812. png_free(png_ptr, info_ptr->unknown_chunks);
  194813. info_ptr->unknown_chunks=NULL;
  194814. for (i = 0; i < num_unknowns; i++)
  194815. {
  194816. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  194817. png_unknown_chunkp from = unknowns + i;
  194818. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  194819. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  194820. if (to->data == NULL)
  194821. {
  194822. png_warning(png_ptr,
  194823. "Out of memory while processing unknown chunk.");
  194824. }
  194825. else
  194826. {
  194827. png_memcpy(to->data, from->data, from->size);
  194828. to->size = from->size;
  194829. /* note our location in the read or write sequence */
  194830. to->location = (png_byte)(png_ptr->mode & 0xff);
  194831. }
  194832. }
  194833. info_ptr->unknown_chunks = np;
  194834. info_ptr->unknown_chunks_num += num_unknowns;
  194835. #ifdef PNG_FREE_ME_SUPPORTED
  194836. info_ptr->free_me |= PNG_FREE_UNKN;
  194837. #endif
  194838. }
  194839. void PNGAPI
  194840. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  194841. int chunk, int location)
  194842. {
  194843. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  194844. (int)info_ptr->unknown_chunks_num)
  194845. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  194846. }
  194847. #endif
  194848. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  194849. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  194850. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  194851. void PNGAPI
  194852. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  194853. {
  194854. /* This function is deprecated in favor of png_permit_mng_features()
  194855. and will be removed from libpng-1.3.0 */
  194856. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  194857. if (png_ptr == NULL)
  194858. return;
  194859. png_ptr->mng_features_permitted = (png_byte)
  194860. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  194861. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  194862. }
  194863. #endif
  194864. #endif
  194865. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194866. png_uint_32 PNGAPI
  194867. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  194868. {
  194869. png_debug(1, "in png_permit_mng_features\n");
  194870. if (png_ptr == NULL)
  194871. return (png_uint_32)0;
  194872. png_ptr->mng_features_permitted =
  194873. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  194874. return (png_uint_32)png_ptr->mng_features_permitted;
  194875. }
  194876. #endif
  194877. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  194878. void PNGAPI
  194879. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  194880. chunk_list, int num_chunks)
  194881. {
  194882. png_bytep new_list, p;
  194883. int i, old_num_chunks;
  194884. if (png_ptr == NULL)
  194885. return;
  194886. if (num_chunks == 0)
  194887. {
  194888. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  194889. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  194890. else
  194891. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  194892. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  194893. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  194894. else
  194895. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  194896. return;
  194897. }
  194898. if (chunk_list == NULL)
  194899. return;
  194900. old_num_chunks=png_ptr->num_chunk_list;
  194901. new_list=(png_bytep)png_malloc(png_ptr,
  194902. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  194903. if(png_ptr->chunk_list != NULL)
  194904. {
  194905. png_memcpy(new_list, png_ptr->chunk_list,
  194906. (png_size_t)(5*old_num_chunks));
  194907. png_free(png_ptr, png_ptr->chunk_list);
  194908. png_ptr->chunk_list=NULL;
  194909. }
  194910. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  194911. (png_size_t)(5*num_chunks));
  194912. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  194913. *p=(png_byte)keep;
  194914. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  194915. png_ptr->chunk_list=new_list;
  194916. #ifdef PNG_FREE_ME_SUPPORTED
  194917. png_ptr->free_me |= PNG_FREE_LIST;
  194918. #endif
  194919. }
  194920. #endif
  194921. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  194922. void PNGAPI
  194923. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  194924. png_user_chunk_ptr read_user_chunk_fn)
  194925. {
  194926. png_debug(1, "in png_set_read_user_chunk_fn\n");
  194927. if (png_ptr == NULL)
  194928. return;
  194929. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  194930. png_ptr->user_chunk_ptr = user_chunk_ptr;
  194931. }
  194932. #endif
  194933. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  194934. void PNGAPI
  194935. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  194936. {
  194937. png_debug1(1, "in %s storage function\n", "rows");
  194938. if (png_ptr == NULL || info_ptr == NULL)
  194939. return;
  194940. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  194941. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  194942. info_ptr->row_pointers = row_pointers;
  194943. if(row_pointers)
  194944. info_ptr->valid |= PNG_INFO_IDAT;
  194945. }
  194946. #endif
  194947. #ifdef PNG_WRITE_SUPPORTED
  194948. void PNGAPI
  194949. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  194950. {
  194951. if (png_ptr == NULL)
  194952. return;
  194953. if(png_ptr->zbuf)
  194954. png_free(png_ptr, png_ptr->zbuf);
  194955. png_ptr->zbuf_size = (png_size_t)size;
  194956. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  194957. png_ptr->zstream.next_out = png_ptr->zbuf;
  194958. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194959. }
  194960. #endif
  194961. void PNGAPI
  194962. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  194963. {
  194964. if (png_ptr && info_ptr)
  194965. info_ptr->valid &= ~(mask);
  194966. }
  194967. #ifndef PNG_1_0_X
  194968. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  194969. /* function was added to libpng 1.2.0 and should always exist by default */
  194970. void PNGAPI
  194971. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  194972. {
  194973. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  194974. if (png_ptr != NULL)
  194975. png_ptr->asm_flags = 0;
  194976. }
  194977. /* this function was added to libpng 1.2.0 */
  194978. void PNGAPI
  194979. png_set_mmx_thresholds (png_structp png_ptr,
  194980. png_byte,
  194981. png_uint_32)
  194982. {
  194983. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  194984. if (png_ptr == NULL)
  194985. return;
  194986. }
  194987. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  194988. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  194989. /* this function was added to libpng 1.2.6 */
  194990. void PNGAPI
  194991. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  194992. png_uint_32 user_height_max)
  194993. {
  194994. /* Images with dimensions larger than these limits will be
  194995. * rejected by png_set_IHDR(). To accept any PNG datastream
  194996. * regardless of dimensions, set both limits to 0x7ffffffL.
  194997. */
  194998. if(png_ptr == NULL) return;
  194999. png_ptr->user_width_max = user_width_max;
  195000. png_ptr->user_height_max = user_height_max;
  195001. }
  195002. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  195003. #endif /* ?PNG_1_0_X */
  195004. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  195005. /*** End of inlined file: pngset.c ***/
  195006. /*** Start of inlined file: pngtrans.c ***/
  195007. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  195008. *
  195009. * Last changed in libpng 1.2.17 May 15, 2007
  195010. * For conditions of distribution and use, see copyright notice in png.h
  195011. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  195012. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  195013. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  195014. */
  195015. #define PNG_INTERNAL
  195016. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  195017. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  195018. /* turn on BGR-to-RGB mapping */
  195019. void PNGAPI
  195020. png_set_bgr(png_structp png_ptr)
  195021. {
  195022. png_debug(1, "in png_set_bgr\n");
  195023. if(png_ptr == NULL) return;
  195024. png_ptr->transformations |= PNG_BGR;
  195025. }
  195026. #endif
  195027. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  195028. /* turn on 16 bit byte swapping */
  195029. void PNGAPI
  195030. png_set_swap(png_structp png_ptr)
  195031. {
  195032. png_debug(1, "in png_set_swap\n");
  195033. if(png_ptr == NULL) return;
  195034. if (png_ptr->bit_depth == 16)
  195035. png_ptr->transformations |= PNG_SWAP_BYTES;
  195036. }
  195037. #endif
  195038. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  195039. /* turn on pixel packing */
  195040. void PNGAPI
  195041. png_set_packing(png_structp png_ptr)
  195042. {
  195043. png_debug(1, "in png_set_packing\n");
  195044. if(png_ptr == NULL) return;
  195045. if (png_ptr->bit_depth < 8)
  195046. {
  195047. png_ptr->transformations |= PNG_PACK;
  195048. png_ptr->usr_bit_depth = 8;
  195049. }
  195050. }
  195051. #endif
  195052. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  195053. /* turn on packed pixel swapping */
  195054. void PNGAPI
  195055. png_set_packswap(png_structp png_ptr)
  195056. {
  195057. png_debug(1, "in png_set_packswap\n");
  195058. if(png_ptr == NULL) return;
  195059. if (png_ptr->bit_depth < 8)
  195060. png_ptr->transformations |= PNG_PACKSWAP;
  195061. }
  195062. #endif
  195063. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  195064. void PNGAPI
  195065. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  195066. {
  195067. png_debug(1, "in png_set_shift\n");
  195068. if(png_ptr == NULL) return;
  195069. png_ptr->transformations |= PNG_SHIFT;
  195070. png_ptr->shift = *true_bits;
  195071. }
  195072. #endif
  195073. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  195074. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  195075. int PNGAPI
  195076. png_set_interlace_handling(png_structp png_ptr)
  195077. {
  195078. png_debug(1, "in png_set_interlace handling\n");
  195079. if (png_ptr && png_ptr->interlaced)
  195080. {
  195081. png_ptr->transformations |= PNG_INTERLACE;
  195082. return (7);
  195083. }
  195084. return (1);
  195085. }
  195086. #endif
  195087. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  195088. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  195089. * The filler type has changed in v0.95 to allow future 2-byte fillers
  195090. * for 48-bit input data, as well as to avoid problems with some compilers
  195091. * that don't like bytes as parameters.
  195092. */
  195093. void PNGAPI
  195094. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  195095. {
  195096. png_debug(1, "in png_set_filler\n");
  195097. if(png_ptr == NULL) return;
  195098. png_ptr->transformations |= PNG_FILLER;
  195099. png_ptr->filler = (png_byte)filler;
  195100. if (filler_loc == PNG_FILLER_AFTER)
  195101. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  195102. else
  195103. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  195104. /* This should probably go in the "do_read_filler" routine.
  195105. * I attempted to do that in libpng-1.0.1a but that caused problems
  195106. * so I restored it in libpng-1.0.2a
  195107. */
  195108. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  195109. {
  195110. png_ptr->usr_channels = 4;
  195111. }
  195112. /* Also I added this in libpng-1.0.2a (what happens when we expand
  195113. * a less-than-8-bit grayscale to GA? */
  195114. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  195115. {
  195116. png_ptr->usr_channels = 2;
  195117. }
  195118. }
  195119. #if !defined(PNG_1_0_X)
  195120. /* Added to libpng-1.2.7 */
  195121. void PNGAPI
  195122. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  195123. {
  195124. png_debug(1, "in png_set_add_alpha\n");
  195125. if(png_ptr == NULL) return;
  195126. png_set_filler(png_ptr, filler, filler_loc);
  195127. png_ptr->transformations |= PNG_ADD_ALPHA;
  195128. }
  195129. #endif
  195130. #endif
  195131. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  195132. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  195133. void PNGAPI
  195134. png_set_swap_alpha(png_structp png_ptr)
  195135. {
  195136. png_debug(1, "in png_set_swap_alpha\n");
  195137. if(png_ptr == NULL) return;
  195138. png_ptr->transformations |= PNG_SWAP_ALPHA;
  195139. }
  195140. #endif
  195141. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  195142. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  195143. void PNGAPI
  195144. png_set_invert_alpha(png_structp png_ptr)
  195145. {
  195146. png_debug(1, "in png_set_invert_alpha\n");
  195147. if(png_ptr == NULL) return;
  195148. png_ptr->transformations |= PNG_INVERT_ALPHA;
  195149. }
  195150. #endif
  195151. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  195152. void PNGAPI
  195153. png_set_invert_mono(png_structp png_ptr)
  195154. {
  195155. png_debug(1, "in png_set_invert_mono\n");
  195156. if(png_ptr == NULL) return;
  195157. png_ptr->transformations |= PNG_INVERT_MONO;
  195158. }
  195159. /* invert monochrome grayscale data */
  195160. void /* PRIVATE */
  195161. png_do_invert(png_row_infop row_info, png_bytep row)
  195162. {
  195163. png_debug(1, "in png_do_invert\n");
  195164. /* This test removed from libpng version 1.0.13 and 1.2.0:
  195165. * if (row_info->bit_depth == 1 &&
  195166. */
  195167. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195168. if (row == NULL || row_info == NULL)
  195169. return;
  195170. #endif
  195171. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  195172. {
  195173. png_bytep rp = row;
  195174. png_uint_32 i;
  195175. png_uint_32 istop = row_info->rowbytes;
  195176. for (i = 0; i < istop; i++)
  195177. {
  195178. *rp = (png_byte)(~(*rp));
  195179. rp++;
  195180. }
  195181. }
  195182. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  195183. row_info->bit_depth == 8)
  195184. {
  195185. png_bytep rp = row;
  195186. png_uint_32 i;
  195187. png_uint_32 istop = row_info->rowbytes;
  195188. for (i = 0; i < istop; i+=2)
  195189. {
  195190. *rp = (png_byte)(~(*rp));
  195191. rp+=2;
  195192. }
  195193. }
  195194. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  195195. row_info->bit_depth == 16)
  195196. {
  195197. png_bytep rp = row;
  195198. png_uint_32 i;
  195199. png_uint_32 istop = row_info->rowbytes;
  195200. for (i = 0; i < istop; i+=4)
  195201. {
  195202. *rp = (png_byte)(~(*rp));
  195203. *(rp+1) = (png_byte)(~(*(rp+1)));
  195204. rp+=4;
  195205. }
  195206. }
  195207. }
  195208. #endif
  195209. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  195210. /* swaps byte order on 16 bit depth images */
  195211. void /* PRIVATE */
  195212. png_do_swap(png_row_infop row_info, png_bytep row)
  195213. {
  195214. png_debug(1, "in png_do_swap\n");
  195215. if (
  195216. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195217. row != NULL && row_info != NULL &&
  195218. #endif
  195219. row_info->bit_depth == 16)
  195220. {
  195221. png_bytep rp = row;
  195222. png_uint_32 i;
  195223. png_uint_32 istop= row_info->width * row_info->channels;
  195224. for (i = 0; i < istop; i++, rp += 2)
  195225. {
  195226. png_byte t = *rp;
  195227. *rp = *(rp + 1);
  195228. *(rp + 1) = t;
  195229. }
  195230. }
  195231. }
  195232. #endif
  195233. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  195234. static PNG_CONST png_byte onebppswaptable[256] = {
  195235. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  195236. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  195237. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  195238. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  195239. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  195240. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  195241. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  195242. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  195243. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  195244. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  195245. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  195246. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  195247. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  195248. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  195249. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  195250. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  195251. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  195252. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  195253. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  195254. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  195255. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  195256. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  195257. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  195258. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  195259. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  195260. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  195261. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  195262. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  195263. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  195264. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  195265. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  195266. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  195267. };
  195268. static PNG_CONST png_byte twobppswaptable[256] = {
  195269. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  195270. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  195271. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  195272. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  195273. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  195274. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  195275. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  195276. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  195277. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  195278. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  195279. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  195280. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  195281. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  195282. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  195283. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  195284. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  195285. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  195286. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  195287. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  195288. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  195289. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  195290. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  195291. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  195292. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  195293. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  195294. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  195295. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  195296. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  195297. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  195298. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  195299. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  195300. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  195301. };
  195302. static PNG_CONST png_byte fourbppswaptable[256] = {
  195303. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  195304. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  195305. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  195306. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  195307. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  195308. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  195309. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  195310. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  195311. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  195312. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  195313. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  195314. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  195315. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  195316. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  195317. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  195318. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  195319. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  195320. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  195321. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  195322. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  195323. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  195324. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  195325. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  195326. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  195327. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  195328. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  195329. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  195330. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  195331. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  195332. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  195333. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  195334. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  195335. };
  195336. /* swaps pixel packing order within bytes */
  195337. void /* PRIVATE */
  195338. png_do_packswap(png_row_infop row_info, png_bytep row)
  195339. {
  195340. png_debug(1, "in png_do_packswap\n");
  195341. if (
  195342. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195343. row != NULL && row_info != NULL &&
  195344. #endif
  195345. row_info->bit_depth < 8)
  195346. {
  195347. png_bytep rp, end, table;
  195348. end = row + row_info->rowbytes;
  195349. if (row_info->bit_depth == 1)
  195350. table = (png_bytep)onebppswaptable;
  195351. else if (row_info->bit_depth == 2)
  195352. table = (png_bytep)twobppswaptable;
  195353. else if (row_info->bit_depth == 4)
  195354. table = (png_bytep)fourbppswaptable;
  195355. else
  195356. return;
  195357. for (rp = row; rp < end; rp++)
  195358. *rp = table[*rp];
  195359. }
  195360. }
  195361. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  195362. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  195363. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  195364. /* remove filler or alpha byte(s) */
  195365. void /* PRIVATE */
  195366. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  195367. {
  195368. png_debug(1, "in png_do_strip_filler\n");
  195369. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195370. if (row != NULL && row_info != NULL)
  195371. #endif
  195372. {
  195373. png_bytep sp=row;
  195374. png_bytep dp=row;
  195375. png_uint_32 row_width=row_info->width;
  195376. png_uint_32 i;
  195377. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  195378. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  195379. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  195380. row_info->channels == 4)
  195381. {
  195382. if (row_info->bit_depth == 8)
  195383. {
  195384. /* This converts from RGBX or RGBA to RGB */
  195385. if (flags & PNG_FLAG_FILLER_AFTER)
  195386. {
  195387. dp+=3; sp+=4;
  195388. for (i = 1; i < row_width; i++)
  195389. {
  195390. *dp++ = *sp++;
  195391. *dp++ = *sp++;
  195392. *dp++ = *sp++;
  195393. sp++;
  195394. }
  195395. }
  195396. /* This converts from XRGB or ARGB to RGB */
  195397. else
  195398. {
  195399. for (i = 0; i < row_width; i++)
  195400. {
  195401. sp++;
  195402. *dp++ = *sp++;
  195403. *dp++ = *sp++;
  195404. *dp++ = *sp++;
  195405. }
  195406. }
  195407. row_info->pixel_depth = 24;
  195408. row_info->rowbytes = row_width * 3;
  195409. }
  195410. else /* if (row_info->bit_depth == 16) */
  195411. {
  195412. if (flags & PNG_FLAG_FILLER_AFTER)
  195413. {
  195414. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  195415. sp += 8; dp += 6;
  195416. for (i = 1; i < row_width; i++)
  195417. {
  195418. /* This could be (although png_memcpy is probably slower):
  195419. png_memcpy(dp, sp, 6);
  195420. sp += 8;
  195421. dp += 6;
  195422. */
  195423. *dp++ = *sp++;
  195424. *dp++ = *sp++;
  195425. *dp++ = *sp++;
  195426. *dp++ = *sp++;
  195427. *dp++ = *sp++;
  195428. *dp++ = *sp++;
  195429. sp += 2;
  195430. }
  195431. }
  195432. else
  195433. {
  195434. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  195435. for (i = 0; i < row_width; i++)
  195436. {
  195437. /* This could be (although png_memcpy is probably slower):
  195438. png_memcpy(dp, sp, 6);
  195439. sp += 8;
  195440. dp += 6;
  195441. */
  195442. sp+=2;
  195443. *dp++ = *sp++;
  195444. *dp++ = *sp++;
  195445. *dp++ = *sp++;
  195446. *dp++ = *sp++;
  195447. *dp++ = *sp++;
  195448. *dp++ = *sp++;
  195449. }
  195450. }
  195451. row_info->pixel_depth = 48;
  195452. row_info->rowbytes = row_width * 6;
  195453. }
  195454. row_info->channels = 3;
  195455. }
  195456. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  195457. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  195458. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  195459. row_info->channels == 2)
  195460. {
  195461. if (row_info->bit_depth == 8)
  195462. {
  195463. /* This converts from GX or GA to G */
  195464. if (flags & PNG_FLAG_FILLER_AFTER)
  195465. {
  195466. for (i = 0; i < row_width; i++)
  195467. {
  195468. *dp++ = *sp++;
  195469. sp++;
  195470. }
  195471. }
  195472. /* This converts from XG or AG to G */
  195473. else
  195474. {
  195475. for (i = 0; i < row_width; i++)
  195476. {
  195477. sp++;
  195478. *dp++ = *sp++;
  195479. }
  195480. }
  195481. row_info->pixel_depth = 8;
  195482. row_info->rowbytes = row_width;
  195483. }
  195484. else /* if (row_info->bit_depth == 16) */
  195485. {
  195486. if (flags & PNG_FLAG_FILLER_AFTER)
  195487. {
  195488. /* This converts from GGXX or GGAA to GG */
  195489. sp += 4; dp += 2;
  195490. for (i = 1; i < row_width; i++)
  195491. {
  195492. *dp++ = *sp++;
  195493. *dp++ = *sp++;
  195494. sp += 2;
  195495. }
  195496. }
  195497. else
  195498. {
  195499. /* This converts from XXGG or AAGG to GG */
  195500. for (i = 0; i < row_width; i++)
  195501. {
  195502. sp += 2;
  195503. *dp++ = *sp++;
  195504. *dp++ = *sp++;
  195505. }
  195506. }
  195507. row_info->pixel_depth = 16;
  195508. row_info->rowbytes = row_width * 2;
  195509. }
  195510. row_info->channels = 1;
  195511. }
  195512. if (flags & PNG_FLAG_STRIP_ALPHA)
  195513. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  195514. }
  195515. }
  195516. #endif
  195517. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  195518. /* swaps red and blue bytes within a pixel */
  195519. void /* PRIVATE */
  195520. png_do_bgr(png_row_infop row_info, png_bytep row)
  195521. {
  195522. png_debug(1, "in png_do_bgr\n");
  195523. if (
  195524. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195525. row != NULL && row_info != NULL &&
  195526. #endif
  195527. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  195528. {
  195529. png_uint_32 row_width = row_info->width;
  195530. if (row_info->bit_depth == 8)
  195531. {
  195532. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  195533. {
  195534. png_bytep rp;
  195535. png_uint_32 i;
  195536. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  195537. {
  195538. png_byte save = *rp;
  195539. *rp = *(rp + 2);
  195540. *(rp + 2) = save;
  195541. }
  195542. }
  195543. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  195544. {
  195545. png_bytep rp;
  195546. png_uint_32 i;
  195547. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  195548. {
  195549. png_byte save = *rp;
  195550. *rp = *(rp + 2);
  195551. *(rp + 2) = save;
  195552. }
  195553. }
  195554. }
  195555. else if (row_info->bit_depth == 16)
  195556. {
  195557. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  195558. {
  195559. png_bytep rp;
  195560. png_uint_32 i;
  195561. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  195562. {
  195563. png_byte save = *rp;
  195564. *rp = *(rp + 4);
  195565. *(rp + 4) = save;
  195566. save = *(rp + 1);
  195567. *(rp + 1) = *(rp + 5);
  195568. *(rp + 5) = save;
  195569. }
  195570. }
  195571. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  195572. {
  195573. png_bytep rp;
  195574. png_uint_32 i;
  195575. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  195576. {
  195577. png_byte save = *rp;
  195578. *rp = *(rp + 4);
  195579. *(rp + 4) = save;
  195580. save = *(rp + 1);
  195581. *(rp + 1) = *(rp + 5);
  195582. *(rp + 5) = save;
  195583. }
  195584. }
  195585. }
  195586. }
  195587. }
  195588. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  195589. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  195590. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  195591. defined(PNG_LEGACY_SUPPORTED)
  195592. void PNGAPI
  195593. png_set_user_transform_info(png_structp png_ptr, png_voidp
  195594. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  195595. {
  195596. png_debug(1, "in png_set_user_transform_info\n");
  195597. if(png_ptr == NULL) return;
  195598. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  195599. png_ptr->user_transform_ptr = user_transform_ptr;
  195600. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  195601. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  195602. #else
  195603. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  195604. png_warning(png_ptr,
  195605. "This version of libpng does not support user transform info");
  195606. #endif
  195607. }
  195608. #endif
  195609. /* This function returns a pointer to the user_transform_ptr associated with
  195610. * the user transform functions. The application should free any memory
  195611. * associated with this pointer before png_write_destroy and png_read_destroy
  195612. * are called.
  195613. */
  195614. png_voidp PNGAPI
  195615. png_get_user_transform_ptr(png_structp png_ptr)
  195616. {
  195617. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  195618. if (png_ptr == NULL) return (NULL);
  195619. return ((png_voidp)png_ptr->user_transform_ptr);
  195620. #else
  195621. return (NULL);
  195622. #endif
  195623. }
  195624. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  195625. /*** End of inlined file: pngtrans.c ***/
  195626. /*** Start of inlined file: pngwio.c ***/
  195627. /* pngwio.c - functions for data output
  195628. *
  195629. * Last changed in libpng 1.2.13 November 13, 2006
  195630. * For conditions of distribution and use, see copyright notice in png.h
  195631. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  195632. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  195633. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  195634. *
  195635. * This file provides a location for all output. Users who need
  195636. * special handling are expected to write functions that have the same
  195637. * arguments as these and perform similar functions, but that possibly
  195638. * use different output methods. Note that you shouldn't change these
  195639. * functions, but rather write replacement functions and then change
  195640. * them at run time with png_set_write_fn(...).
  195641. */
  195642. #define PNG_INTERNAL
  195643. #ifdef PNG_WRITE_SUPPORTED
  195644. /* Write the data to whatever output you are using. The default routine
  195645. writes to a file pointer. Note that this routine sometimes gets called
  195646. with very small lengths, so you should implement some kind of simple
  195647. buffering if you are using unbuffered writes. This should never be asked
  195648. to write more than 64K on a 16 bit machine. */
  195649. void /* PRIVATE */
  195650. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  195651. {
  195652. if (png_ptr->write_data_fn != NULL )
  195653. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  195654. else
  195655. png_error(png_ptr, "Call to NULL write function");
  195656. }
  195657. #if !defined(PNG_NO_STDIO)
  195658. /* This is the function that does the actual writing of data. If you are
  195659. not writing to a standard C stream, you should create a replacement
  195660. write_data function and use it at run time with png_set_write_fn(), rather
  195661. than changing the library. */
  195662. #ifndef USE_FAR_KEYWORD
  195663. void PNGAPI
  195664. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  195665. {
  195666. png_uint_32 check;
  195667. if(png_ptr == NULL) return;
  195668. #if defined(_WIN32_WCE)
  195669. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  195670. check = 0;
  195671. #else
  195672. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  195673. #endif
  195674. if (check != length)
  195675. png_error(png_ptr, "Write Error");
  195676. }
  195677. #else
  195678. /* this is the model-independent version. Since the standard I/O library
  195679. can't handle far buffers in the medium and small models, we have to copy
  195680. the data.
  195681. */
  195682. #define NEAR_BUF_SIZE 1024
  195683. #define MIN(a,b) (a <= b ? a : b)
  195684. void PNGAPI
  195685. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  195686. {
  195687. png_uint_32 check;
  195688. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  195689. png_FILE_p io_ptr;
  195690. if(png_ptr == NULL) return;
  195691. /* Check if data really is near. If so, use usual code. */
  195692. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  195693. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  195694. if ((png_bytep)near_data == data)
  195695. {
  195696. #if defined(_WIN32_WCE)
  195697. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  195698. check = 0;
  195699. #else
  195700. check = fwrite(near_data, 1, length, io_ptr);
  195701. #endif
  195702. }
  195703. else
  195704. {
  195705. png_byte buf[NEAR_BUF_SIZE];
  195706. png_size_t written, remaining, err;
  195707. check = 0;
  195708. remaining = length;
  195709. do
  195710. {
  195711. written = MIN(NEAR_BUF_SIZE, remaining);
  195712. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  195713. #if defined(_WIN32_WCE)
  195714. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  195715. err = 0;
  195716. #else
  195717. err = fwrite(buf, 1, written, io_ptr);
  195718. #endif
  195719. if (err != written)
  195720. break;
  195721. else
  195722. check += err;
  195723. data += written;
  195724. remaining -= written;
  195725. }
  195726. while (remaining != 0);
  195727. }
  195728. if (check != length)
  195729. png_error(png_ptr, "Write Error");
  195730. }
  195731. #endif
  195732. #endif
  195733. /* This function is called to output any data pending writing (normally
  195734. to disk). After png_flush is called, there should be no data pending
  195735. writing in any buffers. */
  195736. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  195737. void /* PRIVATE */
  195738. png_flush(png_structp png_ptr)
  195739. {
  195740. if (png_ptr->output_flush_fn != NULL)
  195741. (*(png_ptr->output_flush_fn))(png_ptr);
  195742. }
  195743. #if !defined(PNG_NO_STDIO)
  195744. void PNGAPI
  195745. png_default_flush(png_structp png_ptr)
  195746. {
  195747. #if !defined(_WIN32_WCE)
  195748. png_FILE_p io_ptr;
  195749. #endif
  195750. if(png_ptr == NULL) return;
  195751. #if !defined(_WIN32_WCE)
  195752. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  195753. if (io_ptr != NULL)
  195754. fflush(io_ptr);
  195755. #endif
  195756. }
  195757. #endif
  195758. #endif
  195759. /* This function allows the application to supply new output functions for
  195760. libpng if standard C streams aren't being used.
  195761. This function takes as its arguments:
  195762. png_ptr - pointer to a png output data structure
  195763. io_ptr - pointer to user supplied structure containing info about
  195764. the output functions. May be NULL.
  195765. write_data_fn - pointer to a new output function that takes as its
  195766. arguments a pointer to a png_struct, a pointer to
  195767. data to be written, and a 32-bit unsigned int that is
  195768. the number of bytes to be written. The new write
  195769. function should call png_error(png_ptr, "Error msg")
  195770. to exit and output any fatal error messages.
  195771. flush_data_fn - pointer to a new flush function that takes as its
  195772. arguments a pointer to a png_struct. After a call to
  195773. the flush function, there should be no data in any buffers
  195774. or pending transmission. If the output method doesn't do
  195775. any buffering of ouput, a function prototype must still be
  195776. supplied although it doesn't have to do anything. If
  195777. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  195778. time, output_flush_fn will be ignored, although it must be
  195779. supplied for compatibility. */
  195780. void PNGAPI
  195781. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  195782. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  195783. {
  195784. if(png_ptr == NULL) return;
  195785. png_ptr->io_ptr = io_ptr;
  195786. #if !defined(PNG_NO_STDIO)
  195787. if (write_data_fn != NULL)
  195788. png_ptr->write_data_fn = write_data_fn;
  195789. else
  195790. png_ptr->write_data_fn = png_default_write_data;
  195791. #else
  195792. png_ptr->write_data_fn = write_data_fn;
  195793. #endif
  195794. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  195795. #if !defined(PNG_NO_STDIO)
  195796. if (output_flush_fn != NULL)
  195797. png_ptr->output_flush_fn = output_flush_fn;
  195798. else
  195799. png_ptr->output_flush_fn = png_default_flush;
  195800. #else
  195801. png_ptr->output_flush_fn = output_flush_fn;
  195802. #endif
  195803. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  195804. /* It is an error to read while writing a png file */
  195805. if (png_ptr->read_data_fn != NULL)
  195806. {
  195807. png_ptr->read_data_fn = NULL;
  195808. png_warning(png_ptr,
  195809. "Attempted to set both read_data_fn and write_data_fn in");
  195810. png_warning(png_ptr,
  195811. "the same structure. Resetting read_data_fn to NULL.");
  195812. }
  195813. }
  195814. #if defined(USE_FAR_KEYWORD)
  195815. #if defined(_MSC_VER)
  195816. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  195817. {
  195818. void *near_ptr;
  195819. void FAR *far_ptr;
  195820. FP_OFF(near_ptr) = FP_OFF(ptr);
  195821. far_ptr = (void FAR *)near_ptr;
  195822. if(check != 0)
  195823. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  195824. png_error(png_ptr,"segment lost in conversion");
  195825. return(near_ptr);
  195826. }
  195827. # else
  195828. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  195829. {
  195830. void *near_ptr;
  195831. void FAR *far_ptr;
  195832. near_ptr = (void FAR *)ptr;
  195833. far_ptr = (void FAR *)near_ptr;
  195834. if(check != 0)
  195835. if(far_ptr != ptr)
  195836. png_error(png_ptr,"segment lost in conversion");
  195837. return(near_ptr);
  195838. }
  195839. # endif
  195840. # endif
  195841. #endif /* PNG_WRITE_SUPPORTED */
  195842. /*** End of inlined file: pngwio.c ***/
  195843. /*** Start of inlined file: pngwrite.c ***/
  195844. /* pngwrite.c - general routines to write a PNG file
  195845. *
  195846. * Last changed in libpng 1.2.15 January 5, 2007
  195847. * For conditions of distribution and use, see copyright notice in png.h
  195848. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  195849. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  195850. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  195851. */
  195852. /* get internal access to png.h */
  195853. #define PNG_INTERNAL
  195854. #ifdef PNG_WRITE_SUPPORTED
  195855. /* Writes all the PNG information. This is the suggested way to use the
  195856. * library. If you have a new chunk to add, make a function to write it,
  195857. * and put it in the correct location here. If you want the chunk written
  195858. * after the image data, put it in png_write_end(). I strongly encourage
  195859. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  195860. * the chunk, as that will keep the code from breaking if you want to just
  195861. * write a plain PNG file. If you have long comments, I suggest writing
  195862. * them in png_write_end(), and compressing them.
  195863. */
  195864. void PNGAPI
  195865. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  195866. {
  195867. png_debug(1, "in png_write_info_before_PLTE\n");
  195868. if (png_ptr == NULL || info_ptr == NULL)
  195869. return;
  195870. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  195871. {
  195872. png_write_sig(png_ptr); /* write PNG signature */
  195873. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  195874. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  195875. {
  195876. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  195877. png_ptr->mng_features_permitted=0;
  195878. }
  195879. #endif
  195880. /* write IHDR information. */
  195881. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  195882. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  195883. info_ptr->filter_type,
  195884. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  195885. info_ptr->interlace_type);
  195886. #else
  195887. 0);
  195888. #endif
  195889. /* the rest of these check to see if the valid field has the appropriate
  195890. flag set, and if it does, writes the chunk. */
  195891. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  195892. if (info_ptr->valid & PNG_INFO_gAMA)
  195893. {
  195894. # ifdef PNG_FLOATING_POINT_SUPPORTED
  195895. png_write_gAMA(png_ptr, info_ptr->gamma);
  195896. #else
  195897. #ifdef PNG_FIXED_POINT_SUPPORTED
  195898. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  195899. # endif
  195900. #endif
  195901. }
  195902. #endif
  195903. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  195904. if (info_ptr->valid & PNG_INFO_sRGB)
  195905. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  195906. #endif
  195907. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  195908. if (info_ptr->valid & PNG_INFO_iCCP)
  195909. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  195910. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  195911. #endif
  195912. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  195913. if (info_ptr->valid & PNG_INFO_sBIT)
  195914. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  195915. #endif
  195916. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  195917. if (info_ptr->valid & PNG_INFO_cHRM)
  195918. {
  195919. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195920. png_write_cHRM(png_ptr,
  195921. info_ptr->x_white, info_ptr->y_white,
  195922. info_ptr->x_red, info_ptr->y_red,
  195923. info_ptr->x_green, info_ptr->y_green,
  195924. info_ptr->x_blue, info_ptr->y_blue);
  195925. #else
  195926. # ifdef PNG_FIXED_POINT_SUPPORTED
  195927. png_write_cHRM_fixed(png_ptr,
  195928. info_ptr->int_x_white, info_ptr->int_y_white,
  195929. info_ptr->int_x_red, info_ptr->int_y_red,
  195930. info_ptr->int_x_green, info_ptr->int_y_green,
  195931. info_ptr->int_x_blue, info_ptr->int_y_blue);
  195932. # endif
  195933. #endif
  195934. }
  195935. #endif
  195936. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  195937. if (info_ptr->unknown_chunks_num)
  195938. {
  195939. png_unknown_chunk *up;
  195940. png_debug(5, "writing extra chunks\n");
  195941. for (up = info_ptr->unknown_chunks;
  195942. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  195943. up++)
  195944. {
  195945. int keep=png_handle_as_unknown(png_ptr, up->name);
  195946. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  195947. up->location && !(up->location & PNG_HAVE_PLTE) &&
  195948. !(up->location & PNG_HAVE_IDAT) &&
  195949. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  195950. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  195951. {
  195952. png_write_chunk(png_ptr, up->name, up->data, up->size);
  195953. }
  195954. }
  195955. }
  195956. #endif
  195957. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  195958. }
  195959. }
  195960. void PNGAPI
  195961. png_write_info(png_structp png_ptr, png_infop info_ptr)
  195962. {
  195963. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  195964. int i;
  195965. #endif
  195966. png_debug(1, "in png_write_info\n");
  195967. if (png_ptr == NULL || info_ptr == NULL)
  195968. return;
  195969. png_write_info_before_PLTE(png_ptr, info_ptr);
  195970. if (info_ptr->valid & PNG_INFO_PLTE)
  195971. png_write_PLTE(png_ptr, info_ptr->palette,
  195972. (png_uint_32)info_ptr->num_palette);
  195973. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195974. png_error(png_ptr, "Valid palette required for paletted images");
  195975. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  195976. if (info_ptr->valid & PNG_INFO_tRNS)
  195977. {
  195978. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  195979. /* invert the alpha channel (in tRNS) */
  195980. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  195981. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195982. {
  195983. int j;
  195984. for (j=0; j<(int)info_ptr->num_trans; j++)
  195985. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  195986. }
  195987. #endif
  195988. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  195989. info_ptr->num_trans, info_ptr->color_type);
  195990. }
  195991. #endif
  195992. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  195993. if (info_ptr->valid & PNG_INFO_bKGD)
  195994. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  195995. #endif
  195996. #if defined(PNG_WRITE_hIST_SUPPORTED)
  195997. if (info_ptr->valid & PNG_INFO_hIST)
  195998. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  195999. #endif
  196000. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  196001. if (info_ptr->valid & PNG_INFO_oFFs)
  196002. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  196003. info_ptr->offset_unit_type);
  196004. #endif
  196005. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  196006. if (info_ptr->valid & PNG_INFO_pCAL)
  196007. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  196008. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  196009. info_ptr->pcal_units, info_ptr->pcal_params);
  196010. #endif
  196011. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  196012. if (info_ptr->valid & PNG_INFO_sCAL)
  196013. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  196014. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  196015. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  196016. #else
  196017. #ifdef PNG_FIXED_POINT_SUPPORTED
  196018. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  196019. info_ptr->scal_s_width, info_ptr->scal_s_height);
  196020. #else
  196021. png_warning(png_ptr,
  196022. "png_write_sCAL not supported; sCAL chunk not written.");
  196023. #endif
  196024. #endif
  196025. #endif
  196026. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  196027. if (info_ptr->valid & PNG_INFO_pHYs)
  196028. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  196029. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  196030. #endif
  196031. #if defined(PNG_WRITE_tIME_SUPPORTED)
  196032. if (info_ptr->valid & PNG_INFO_tIME)
  196033. {
  196034. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  196035. png_ptr->mode |= PNG_WROTE_tIME;
  196036. }
  196037. #endif
  196038. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  196039. if (info_ptr->valid & PNG_INFO_sPLT)
  196040. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  196041. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  196042. #endif
  196043. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  196044. /* Check to see if we need to write text chunks */
  196045. for (i = 0; i < info_ptr->num_text; i++)
  196046. {
  196047. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  196048. info_ptr->text[i].compression);
  196049. /* an internationalized chunk? */
  196050. if (info_ptr->text[i].compression > 0)
  196051. {
  196052. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  196053. /* write international chunk */
  196054. png_write_iTXt(png_ptr,
  196055. info_ptr->text[i].compression,
  196056. info_ptr->text[i].key,
  196057. info_ptr->text[i].lang,
  196058. info_ptr->text[i].lang_key,
  196059. info_ptr->text[i].text);
  196060. #else
  196061. png_warning(png_ptr, "Unable to write international text");
  196062. #endif
  196063. /* Mark this chunk as written */
  196064. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  196065. }
  196066. /* If we want a compressed text chunk */
  196067. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  196068. {
  196069. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  196070. /* write compressed chunk */
  196071. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  196072. info_ptr->text[i].text, 0,
  196073. info_ptr->text[i].compression);
  196074. #else
  196075. png_warning(png_ptr, "Unable to write compressed text");
  196076. #endif
  196077. /* Mark this chunk as written */
  196078. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  196079. }
  196080. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  196081. {
  196082. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  196083. /* write uncompressed chunk */
  196084. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  196085. info_ptr->text[i].text,
  196086. 0);
  196087. #else
  196088. png_warning(png_ptr, "Unable to write uncompressed text");
  196089. #endif
  196090. /* Mark this chunk as written */
  196091. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  196092. }
  196093. }
  196094. #endif
  196095. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  196096. if (info_ptr->unknown_chunks_num)
  196097. {
  196098. png_unknown_chunk *up;
  196099. png_debug(5, "writing extra chunks\n");
  196100. for (up = info_ptr->unknown_chunks;
  196101. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  196102. up++)
  196103. {
  196104. int keep=png_handle_as_unknown(png_ptr, up->name);
  196105. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  196106. up->location && (up->location & PNG_HAVE_PLTE) &&
  196107. !(up->location & PNG_HAVE_IDAT) &&
  196108. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  196109. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  196110. {
  196111. png_write_chunk(png_ptr, up->name, up->data, up->size);
  196112. }
  196113. }
  196114. }
  196115. #endif
  196116. }
  196117. /* Writes the end of the PNG file. If you don't want to write comments or
  196118. * time information, you can pass NULL for info. If you already wrote these
  196119. * in png_write_info(), do not write them again here. If you have long
  196120. * comments, I suggest writing them here, and compressing them.
  196121. */
  196122. void PNGAPI
  196123. png_write_end(png_structp png_ptr, png_infop info_ptr)
  196124. {
  196125. png_debug(1, "in png_write_end\n");
  196126. if (png_ptr == NULL)
  196127. return;
  196128. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  196129. png_error(png_ptr, "No IDATs written into file");
  196130. /* see if user wants us to write information chunks */
  196131. if (info_ptr != NULL)
  196132. {
  196133. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  196134. int i; /* local index variable */
  196135. #endif
  196136. #if defined(PNG_WRITE_tIME_SUPPORTED)
  196137. /* check to see if user has supplied a time chunk */
  196138. if ((info_ptr->valid & PNG_INFO_tIME) &&
  196139. !(png_ptr->mode & PNG_WROTE_tIME))
  196140. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  196141. #endif
  196142. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  196143. /* loop through comment chunks */
  196144. for (i = 0; i < info_ptr->num_text; i++)
  196145. {
  196146. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  196147. info_ptr->text[i].compression);
  196148. /* an internationalized chunk? */
  196149. if (info_ptr->text[i].compression > 0)
  196150. {
  196151. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  196152. /* write international chunk */
  196153. png_write_iTXt(png_ptr,
  196154. info_ptr->text[i].compression,
  196155. info_ptr->text[i].key,
  196156. info_ptr->text[i].lang,
  196157. info_ptr->text[i].lang_key,
  196158. info_ptr->text[i].text);
  196159. #else
  196160. png_warning(png_ptr, "Unable to write international text");
  196161. #endif
  196162. /* Mark this chunk as written */
  196163. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  196164. }
  196165. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  196166. {
  196167. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  196168. /* write compressed chunk */
  196169. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  196170. info_ptr->text[i].text, 0,
  196171. info_ptr->text[i].compression);
  196172. #else
  196173. png_warning(png_ptr, "Unable to write compressed text");
  196174. #endif
  196175. /* Mark this chunk as written */
  196176. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  196177. }
  196178. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  196179. {
  196180. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  196181. /* write uncompressed chunk */
  196182. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  196183. info_ptr->text[i].text, 0);
  196184. #else
  196185. png_warning(png_ptr, "Unable to write uncompressed text");
  196186. #endif
  196187. /* Mark this chunk as written */
  196188. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  196189. }
  196190. }
  196191. #endif
  196192. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  196193. if (info_ptr->unknown_chunks_num)
  196194. {
  196195. png_unknown_chunk *up;
  196196. png_debug(5, "writing extra chunks\n");
  196197. for (up = info_ptr->unknown_chunks;
  196198. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  196199. up++)
  196200. {
  196201. int keep=png_handle_as_unknown(png_ptr, up->name);
  196202. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  196203. up->location && (up->location & PNG_AFTER_IDAT) &&
  196204. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  196205. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  196206. {
  196207. png_write_chunk(png_ptr, up->name, up->data, up->size);
  196208. }
  196209. }
  196210. }
  196211. #endif
  196212. }
  196213. png_ptr->mode |= PNG_AFTER_IDAT;
  196214. /* write end of PNG file */
  196215. png_write_IEND(png_ptr);
  196216. }
  196217. #if defined(PNG_WRITE_tIME_SUPPORTED)
  196218. #if !defined(_WIN32_WCE)
  196219. /* "time.h" functions are not supported on WindowsCE */
  196220. void PNGAPI
  196221. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  196222. {
  196223. png_debug(1, "in png_convert_from_struct_tm\n");
  196224. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  196225. ptime->month = (png_byte)(ttime->tm_mon + 1);
  196226. ptime->day = (png_byte)ttime->tm_mday;
  196227. ptime->hour = (png_byte)ttime->tm_hour;
  196228. ptime->minute = (png_byte)ttime->tm_min;
  196229. ptime->second = (png_byte)ttime->tm_sec;
  196230. }
  196231. void PNGAPI
  196232. png_convert_from_time_t(png_timep ptime, time_t ttime)
  196233. {
  196234. struct tm *tbuf;
  196235. png_debug(1, "in png_convert_from_time_t\n");
  196236. tbuf = gmtime(&ttime);
  196237. png_convert_from_struct_tm(ptime, tbuf);
  196238. }
  196239. #endif
  196240. #endif
  196241. /* Initialize png_ptr structure, and allocate any memory needed */
  196242. png_structp PNGAPI
  196243. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  196244. png_error_ptr error_fn, png_error_ptr warn_fn)
  196245. {
  196246. #ifdef PNG_USER_MEM_SUPPORTED
  196247. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  196248. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  196249. }
  196250. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  196251. png_structp PNGAPI
  196252. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  196253. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  196254. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  196255. {
  196256. #endif /* PNG_USER_MEM_SUPPORTED */
  196257. png_structp png_ptr;
  196258. #ifdef PNG_SETJMP_SUPPORTED
  196259. #ifdef USE_FAR_KEYWORD
  196260. jmp_buf jmpbuf;
  196261. #endif
  196262. #endif
  196263. int i;
  196264. png_debug(1, "in png_create_write_struct\n");
  196265. #ifdef PNG_USER_MEM_SUPPORTED
  196266. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  196267. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  196268. #else
  196269. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  196270. #endif /* PNG_USER_MEM_SUPPORTED */
  196271. if (png_ptr == NULL)
  196272. return (NULL);
  196273. /* added at libpng-1.2.6 */
  196274. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  196275. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  196276. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  196277. #endif
  196278. #ifdef PNG_SETJMP_SUPPORTED
  196279. #ifdef USE_FAR_KEYWORD
  196280. if (setjmp(jmpbuf))
  196281. #else
  196282. if (setjmp(png_ptr->jmpbuf))
  196283. #endif
  196284. {
  196285. png_free(png_ptr, png_ptr->zbuf);
  196286. png_ptr->zbuf=NULL;
  196287. png_destroy_struct(png_ptr);
  196288. return (NULL);
  196289. }
  196290. #ifdef USE_FAR_KEYWORD
  196291. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  196292. #endif
  196293. #endif
  196294. #ifdef PNG_USER_MEM_SUPPORTED
  196295. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  196296. #endif /* PNG_USER_MEM_SUPPORTED */
  196297. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  196298. i=0;
  196299. do
  196300. {
  196301. if(user_png_ver[i] != png_libpng_ver[i])
  196302. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  196303. } while (png_libpng_ver[i++]);
  196304. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  196305. {
  196306. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  196307. * we must recompile any applications that use any older library version.
  196308. * For versions after libpng 1.0, we will be compatible, so we need
  196309. * only check the first digit.
  196310. */
  196311. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  196312. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  196313. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  196314. {
  196315. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  196316. char msg[80];
  196317. if (user_png_ver)
  196318. {
  196319. png_snprintf(msg, 80,
  196320. "Application was compiled with png.h from libpng-%.20s",
  196321. user_png_ver);
  196322. png_warning(png_ptr, msg);
  196323. }
  196324. png_snprintf(msg, 80,
  196325. "Application is running with png.c from libpng-%.20s",
  196326. png_libpng_ver);
  196327. png_warning(png_ptr, msg);
  196328. #endif
  196329. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  196330. png_ptr->flags=0;
  196331. #endif
  196332. png_error(png_ptr,
  196333. "Incompatible libpng version in application and library");
  196334. }
  196335. }
  196336. /* initialize zbuf - compression buffer */
  196337. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  196338. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  196339. (png_uint_32)png_ptr->zbuf_size);
  196340. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  196341. png_flush_ptr_NULL);
  196342. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196343. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  196344. 1, png_doublep_NULL, png_doublep_NULL);
  196345. #endif
  196346. #ifdef PNG_SETJMP_SUPPORTED
  196347. /* Applications that neglect to set up their own setjmp() and then encounter
  196348. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  196349. abort instead of returning. */
  196350. #ifdef USE_FAR_KEYWORD
  196351. if (setjmp(jmpbuf))
  196352. PNG_ABORT();
  196353. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  196354. #else
  196355. if (setjmp(png_ptr->jmpbuf))
  196356. PNG_ABORT();
  196357. #endif
  196358. #endif
  196359. return (png_ptr);
  196360. }
  196361. /* Initialize png_ptr structure, and allocate any memory needed */
  196362. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  196363. /* Deprecated. */
  196364. #undef png_write_init
  196365. void PNGAPI
  196366. png_write_init(png_structp png_ptr)
  196367. {
  196368. /* We only come here via pre-1.0.7-compiled applications */
  196369. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  196370. }
  196371. void PNGAPI
  196372. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  196373. png_size_t png_struct_size, png_size_t png_info_size)
  196374. {
  196375. /* We only come here via pre-1.0.12-compiled applications */
  196376. if(png_ptr == NULL) return;
  196377. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  196378. if(png_sizeof(png_struct) > png_struct_size ||
  196379. png_sizeof(png_info) > png_info_size)
  196380. {
  196381. char msg[80];
  196382. png_ptr->warning_fn=NULL;
  196383. if (user_png_ver)
  196384. {
  196385. png_snprintf(msg, 80,
  196386. "Application was compiled with png.h from libpng-%.20s",
  196387. user_png_ver);
  196388. png_warning(png_ptr, msg);
  196389. }
  196390. png_snprintf(msg, 80,
  196391. "Application is running with png.c from libpng-%.20s",
  196392. png_libpng_ver);
  196393. png_warning(png_ptr, msg);
  196394. }
  196395. #endif
  196396. if(png_sizeof(png_struct) > png_struct_size)
  196397. {
  196398. png_ptr->error_fn=NULL;
  196399. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  196400. png_ptr->flags=0;
  196401. #endif
  196402. png_error(png_ptr,
  196403. "The png struct allocated by the application for writing is too small.");
  196404. }
  196405. if(png_sizeof(png_info) > png_info_size)
  196406. {
  196407. png_ptr->error_fn=NULL;
  196408. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  196409. png_ptr->flags=0;
  196410. #endif
  196411. png_error(png_ptr,
  196412. "The info struct allocated by the application for writing is too small.");
  196413. }
  196414. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  196415. }
  196416. #endif /* PNG_1_0_X || PNG_1_2_X */
  196417. void PNGAPI
  196418. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  196419. png_size_t png_struct_size)
  196420. {
  196421. png_structp png_ptr=*ptr_ptr;
  196422. #ifdef PNG_SETJMP_SUPPORTED
  196423. jmp_buf tmp_jmp; /* to save current jump buffer */
  196424. #endif
  196425. int i = 0;
  196426. if (png_ptr == NULL)
  196427. return;
  196428. do
  196429. {
  196430. if (user_png_ver[i] != png_libpng_ver[i])
  196431. {
  196432. #ifdef PNG_LEGACY_SUPPORTED
  196433. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  196434. #else
  196435. png_ptr->warning_fn=NULL;
  196436. png_warning(png_ptr,
  196437. "Application uses deprecated png_write_init() and should be recompiled.");
  196438. break;
  196439. #endif
  196440. }
  196441. } while (png_libpng_ver[i++]);
  196442. png_debug(1, "in png_write_init_3\n");
  196443. #ifdef PNG_SETJMP_SUPPORTED
  196444. /* save jump buffer and error functions */
  196445. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  196446. #endif
  196447. if (png_sizeof(png_struct) > png_struct_size)
  196448. {
  196449. png_destroy_struct(png_ptr);
  196450. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  196451. *ptr_ptr = png_ptr;
  196452. }
  196453. /* reset all variables to 0 */
  196454. png_memset(png_ptr, 0, png_sizeof (png_struct));
  196455. /* added at libpng-1.2.6 */
  196456. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  196457. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  196458. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  196459. #endif
  196460. #ifdef PNG_SETJMP_SUPPORTED
  196461. /* restore jump buffer */
  196462. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  196463. #endif
  196464. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  196465. png_flush_ptr_NULL);
  196466. /* initialize zbuf - compression buffer */
  196467. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  196468. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  196469. (png_uint_32)png_ptr->zbuf_size);
  196470. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196471. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  196472. 1, png_doublep_NULL, png_doublep_NULL);
  196473. #endif
  196474. }
  196475. /* Write a few rows of image data. If the image is interlaced,
  196476. * either you will have to write the 7 sub images, or, if you
  196477. * have called png_set_interlace_handling(), you will have to
  196478. * "write" the image seven times.
  196479. */
  196480. void PNGAPI
  196481. png_write_rows(png_structp png_ptr, png_bytepp row,
  196482. png_uint_32 num_rows)
  196483. {
  196484. png_uint_32 i; /* row counter */
  196485. png_bytepp rp; /* row pointer */
  196486. png_debug(1, "in png_write_rows\n");
  196487. if (png_ptr == NULL)
  196488. return;
  196489. /* loop through the rows */
  196490. for (i = 0, rp = row; i < num_rows; i++, rp++)
  196491. {
  196492. png_write_row(png_ptr, *rp);
  196493. }
  196494. }
  196495. /* Write the image. You only need to call this function once, even
  196496. * if you are writing an interlaced image.
  196497. */
  196498. void PNGAPI
  196499. png_write_image(png_structp png_ptr, png_bytepp image)
  196500. {
  196501. png_uint_32 i; /* row index */
  196502. int pass, num_pass; /* pass variables */
  196503. png_bytepp rp; /* points to current row */
  196504. if (png_ptr == NULL)
  196505. return;
  196506. png_debug(1, "in png_write_image\n");
  196507. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  196508. /* intialize interlace handling. If image is not interlaced,
  196509. this will set pass to 1 */
  196510. num_pass = png_set_interlace_handling(png_ptr);
  196511. #else
  196512. num_pass = 1;
  196513. #endif
  196514. /* loop through passes */
  196515. for (pass = 0; pass < num_pass; pass++)
  196516. {
  196517. /* loop through image */
  196518. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  196519. {
  196520. png_write_row(png_ptr, *rp);
  196521. }
  196522. }
  196523. }
  196524. /* called by user to write a row of image data */
  196525. void PNGAPI
  196526. png_write_row(png_structp png_ptr, png_bytep row)
  196527. {
  196528. if (png_ptr == NULL)
  196529. return;
  196530. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  196531. png_ptr->row_number, png_ptr->pass);
  196532. /* initialize transformations and other stuff if first time */
  196533. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  196534. {
  196535. /* make sure we wrote the header info */
  196536. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  196537. png_error(png_ptr,
  196538. "png_write_info was never called before png_write_row.");
  196539. /* check for transforms that have been set but were defined out */
  196540. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  196541. if (png_ptr->transformations & PNG_INVERT_MONO)
  196542. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  196543. #endif
  196544. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  196545. if (png_ptr->transformations & PNG_FILLER)
  196546. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  196547. #endif
  196548. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  196549. if (png_ptr->transformations & PNG_PACKSWAP)
  196550. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  196551. #endif
  196552. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  196553. if (png_ptr->transformations & PNG_PACK)
  196554. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  196555. #endif
  196556. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  196557. if (png_ptr->transformations & PNG_SHIFT)
  196558. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  196559. #endif
  196560. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  196561. if (png_ptr->transformations & PNG_BGR)
  196562. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  196563. #endif
  196564. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  196565. if (png_ptr->transformations & PNG_SWAP_BYTES)
  196566. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  196567. #endif
  196568. png_write_start_row(png_ptr);
  196569. }
  196570. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  196571. /* if interlaced and not interested in row, return */
  196572. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  196573. {
  196574. switch (png_ptr->pass)
  196575. {
  196576. case 0:
  196577. if (png_ptr->row_number & 0x07)
  196578. {
  196579. png_write_finish_row(png_ptr);
  196580. return;
  196581. }
  196582. break;
  196583. case 1:
  196584. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  196585. {
  196586. png_write_finish_row(png_ptr);
  196587. return;
  196588. }
  196589. break;
  196590. case 2:
  196591. if ((png_ptr->row_number & 0x07) != 4)
  196592. {
  196593. png_write_finish_row(png_ptr);
  196594. return;
  196595. }
  196596. break;
  196597. case 3:
  196598. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  196599. {
  196600. png_write_finish_row(png_ptr);
  196601. return;
  196602. }
  196603. break;
  196604. case 4:
  196605. if ((png_ptr->row_number & 0x03) != 2)
  196606. {
  196607. png_write_finish_row(png_ptr);
  196608. return;
  196609. }
  196610. break;
  196611. case 5:
  196612. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  196613. {
  196614. png_write_finish_row(png_ptr);
  196615. return;
  196616. }
  196617. break;
  196618. case 6:
  196619. if (!(png_ptr->row_number & 0x01))
  196620. {
  196621. png_write_finish_row(png_ptr);
  196622. return;
  196623. }
  196624. break;
  196625. }
  196626. }
  196627. #endif
  196628. /* set up row info for transformations */
  196629. png_ptr->row_info.color_type = png_ptr->color_type;
  196630. png_ptr->row_info.width = png_ptr->usr_width;
  196631. png_ptr->row_info.channels = png_ptr->usr_channels;
  196632. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  196633. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  196634. png_ptr->row_info.channels);
  196635. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  196636. png_ptr->row_info.width);
  196637. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  196638. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  196639. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  196640. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  196641. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  196642. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  196643. /* Copy user's row into buffer, leaving room for filter byte. */
  196644. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  196645. png_ptr->row_info.rowbytes);
  196646. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  196647. /* handle interlacing */
  196648. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  196649. (png_ptr->transformations & PNG_INTERLACE))
  196650. {
  196651. png_do_write_interlace(&(png_ptr->row_info),
  196652. png_ptr->row_buf + 1, png_ptr->pass);
  196653. /* this should always get caught above, but still ... */
  196654. if (!(png_ptr->row_info.width))
  196655. {
  196656. png_write_finish_row(png_ptr);
  196657. return;
  196658. }
  196659. }
  196660. #endif
  196661. /* handle other transformations */
  196662. if (png_ptr->transformations)
  196663. png_do_write_transformations(png_ptr);
  196664. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196665. /* Write filter_method 64 (intrapixel differencing) only if
  196666. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  196667. * 2. Libpng did not write a PNG signature (this filter_method is only
  196668. * used in PNG datastreams that are embedded in MNG datastreams) and
  196669. * 3. The application called png_permit_mng_features with a mask that
  196670. * included PNG_FLAG_MNG_FILTER_64 and
  196671. * 4. The filter_method is 64 and
  196672. * 5. The color_type is RGB or RGBA
  196673. */
  196674. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  196675. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  196676. {
  196677. /* Intrapixel differencing */
  196678. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  196679. }
  196680. #endif
  196681. /* Find a filter if necessary, filter the row and write it out. */
  196682. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  196683. if (png_ptr->write_row_fn != NULL)
  196684. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  196685. }
  196686. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  196687. /* Set the automatic flush interval or 0 to turn flushing off */
  196688. void PNGAPI
  196689. png_set_flush(png_structp png_ptr, int nrows)
  196690. {
  196691. png_debug(1, "in png_set_flush\n");
  196692. if (png_ptr == NULL)
  196693. return;
  196694. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  196695. }
  196696. /* flush the current output buffers now */
  196697. void PNGAPI
  196698. png_write_flush(png_structp png_ptr)
  196699. {
  196700. int wrote_IDAT;
  196701. png_debug(1, "in png_write_flush\n");
  196702. if (png_ptr == NULL)
  196703. return;
  196704. /* We have already written out all of the data */
  196705. if (png_ptr->row_number >= png_ptr->num_rows)
  196706. return;
  196707. do
  196708. {
  196709. int ret;
  196710. /* compress the data */
  196711. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  196712. wrote_IDAT = 0;
  196713. /* check for compression errors */
  196714. if (ret != Z_OK)
  196715. {
  196716. if (png_ptr->zstream.msg != NULL)
  196717. png_error(png_ptr, png_ptr->zstream.msg);
  196718. else
  196719. png_error(png_ptr, "zlib error");
  196720. }
  196721. if (!(png_ptr->zstream.avail_out))
  196722. {
  196723. /* write the IDAT and reset the zlib output buffer */
  196724. png_write_IDAT(png_ptr, png_ptr->zbuf,
  196725. png_ptr->zbuf_size);
  196726. png_ptr->zstream.next_out = png_ptr->zbuf;
  196727. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196728. wrote_IDAT = 1;
  196729. }
  196730. } while(wrote_IDAT == 1);
  196731. /* If there is any data left to be output, write it into a new IDAT */
  196732. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  196733. {
  196734. /* write the IDAT and reset the zlib output buffer */
  196735. png_write_IDAT(png_ptr, png_ptr->zbuf,
  196736. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  196737. png_ptr->zstream.next_out = png_ptr->zbuf;
  196738. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196739. }
  196740. png_ptr->flush_rows = 0;
  196741. png_flush(png_ptr);
  196742. }
  196743. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  196744. /* free all memory used by the write */
  196745. void PNGAPI
  196746. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  196747. {
  196748. png_structp png_ptr = NULL;
  196749. png_infop info_ptr = NULL;
  196750. #ifdef PNG_USER_MEM_SUPPORTED
  196751. png_free_ptr free_fn = NULL;
  196752. png_voidp mem_ptr = NULL;
  196753. #endif
  196754. png_debug(1, "in png_destroy_write_struct\n");
  196755. if (png_ptr_ptr != NULL)
  196756. {
  196757. png_ptr = *png_ptr_ptr;
  196758. #ifdef PNG_USER_MEM_SUPPORTED
  196759. free_fn = png_ptr->free_fn;
  196760. mem_ptr = png_ptr->mem_ptr;
  196761. #endif
  196762. }
  196763. if (info_ptr_ptr != NULL)
  196764. info_ptr = *info_ptr_ptr;
  196765. if (info_ptr != NULL)
  196766. {
  196767. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  196768. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  196769. if (png_ptr->num_chunk_list)
  196770. {
  196771. png_free(png_ptr, png_ptr->chunk_list);
  196772. png_ptr->chunk_list=NULL;
  196773. png_ptr->num_chunk_list=0;
  196774. }
  196775. #endif
  196776. #ifdef PNG_USER_MEM_SUPPORTED
  196777. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  196778. (png_voidp)mem_ptr);
  196779. #else
  196780. png_destroy_struct((png_voidp)info_ptr);
  196781. #endif
  196782. *info_ptr_ptr = NULL;
  196783. }
  196784. if (png_ptr != NULL)
  196785. {
  196786. png_write_destroy(png_ptr);
  196787. #ifdef PNG_USER_MEM_SUPPORTED
  196788. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  196789. (png_voidp)mem_ptr);
  196790. #else
  196791. png_destroy_struct((png_voidp)png_ptr);
  196792. #endif
  196793. *png_ptr_ptr = NULL;
  196794. }
  196795. }
  196796. /* Free any memory used in png_ptr struct (old method) */
  196797. void /* PRIVATE */
  196798. png_write_destroy(png_structp png_ptr)
  196799. {
  196800. #ifdef PNG_SETJMP_SUPPORTED
  196801. jmp_buf tmp_jmp; /* save jump buffer */
  196802. #endif
  196803. png_error_ptr error_fn;
  196804. png_error_ptr warning_fn;
  196805. png_voidp error_ptr;
  196806. #ifdef PNG_USER_MEM_SUPPORTED
  196807. png_free_ptr free_fn;
  196808. #endif
  196809. png_debug(1, "in png_write_destroy\n");
  196810. /* free any memory zlib uses */
  196811. deflateEnd(&png_ptr->zstream);
  196812. /* free our memory. png_free checks NULL for us. */
  196813. png_free(png_ptr, png_ptr->zbuf);
  196814. png_free(png_ptr, png_ptr->row_buf);
  196815. png_free(png_ptr, png_ptr->prev_row);
  196816. png_free(png_ptr, png_ptr->sub_row);
  196817. png_free(png_ptr, png_ptr->up_row);
  196818. png_free(png_ptr, png_ptr->avg_row);
  196819. png_free(png_ptr, png_ptr->paeth_row);
  196820. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  196821. png_free(png_ptr, png_ptr->time_buffer);
  196822. #endif
  196823. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196824. png_free(png_ptr, png_ptr->prev_filters);
  196825. png_free(png_ptr, png_ptr->filter_weights);
  196826. png_free(png_ptr, png_ptr->inv_filter_weights);
  196827. png_free(png_ptr, png_ptr->filter_costs);
  196828. png_free(png_ptr, png_ptr->inv_filter_costs);
  196829. #endif
  196830. #ifdef PNG_SETJMP_SUPPORTED
  196831. /* reset structure */
  196832. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  196833. #endif
  196834. error_fn = png_ptr->error_fn;
  196835. warning_fn = png_ptr->warning_fn;
  196836. error_ptr = png_ptr->error_ptr;
  196837. #ifdef PNG_USER_MEM_SUPPORTED
  196838. free_fn = png_ptr->free_fn;
  196839. #endif
  196840. png_memset(png_ptr, 0, png_sizeof (png_struct));
  196841. png_ptr->error_fn = error_fn;
  196842. png_ptr->warning_fn = warning_fn;
  196843. png_ptr->error_ptr = error_ptr;
  196844. #ifdef PNG_USER_MEM_SUPPORTED
  196845. png_ptr->free_fn = free_fn;
  196846. #endif
  196847. #ifdef PNG_SETJMP_SUPPORTED
  196848. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  196849. #endif
  196850. }
  196851. /* Allow the application to select one or more row filters to use. */
  196852. void PNGAPI
  196853. png_set_filter(png_structp png_ptr, int method, int filters)
  196854. {
  196855. png_debug(1, "in png_set_filter\n");
  196856. if (png_ptr == NULL)
  196857. return;
  196858. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196859. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  196860. (method == PNG_INTRAPIXEL_DIFFERENCING))
  196861. method = PNG_FILTER_TYPE_BASE;
  196862. #endif
  196863. if (method == PNG_FILTER_TYPE_BASE)
  196864. {
  196865. switch (filters & (PNG_ALL_FILTERS | 0x07))
  196866. {
  196867. #ifndef PNG_NO_WRITE_FILTER
  196868. case 5:
  196869. case 6:
  196870. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  196871. #endif /* PNG_NO_WRITE_FILTER */
  196872. case PNG_FILTER_VALUE_NONE:
  196873. png_ptr->do_filter=PNG_FILTER_NONE; break;
  196874. #ifndef PNG_NO_WRITE_FILTER
  196875. case PNG_FILTER_VALUE_SUB:
  196876. png_ptr->do_filter=PNG_FILTER_SUB; break;
  196877. case PNG_FILTER_VALUE_UP:
  196878. png_ptr->do_filter=PNG_FILTER_UP; break;
  196879. case PNG_FILTER_VALUE_AVG:
  196880. png_ptr->do_filter=PNG_FILTER_AVG; break;
  196881. case PNG_FILTER_VALUE_PAETH:
  196882. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  196883. default: png_ptr->do_filter = (png_byte)filters; break;
  196884. #else
  196885. default: png_warning(png_ptr, "Unknown row filter for method 0");
  196886. #endif /* PNG_NO_WRITE_FILTER */
  196887. }
  196888. /* If we have allocated the row_buf, this means we have already started
  196889. * with the image and we should have allocated all of the filter buffers
  196890. * that have been selected. If prev_row isn't already allocated, then
  196891. * it is too late to start using the filters that need it, since we
  196892. * will be missing the data in the previous row. If an application
  196893. * wants to start and stop using particular filters during compression,
  196894. * it should start out with all of the filters, and then add and
  196895. * remove them after the start of compression.
  196896. */
  196897. if (png_ptr->row_buf != NULL)
  196898. {
  196899. #ifndef PNG_NO_WRITE_FILTER
  196900. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  196901. {
  196902. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  196903. (png_ptr->rowbytes + 1));
  196904. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  196905. }
  196906. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  196907. {
  196908. if (png_ptr->prev_row == NULL)
  196909. {
  196910. png_warning(png_ptr, "Can't add Up filter after starting");
  196911. png_ptr->do_filter &= ~PNG_FILTER_UP;
  196912. }
  196913. else
  196914. {
  196915. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  196916. (png_ptr->rowbytes + 1));
  196917. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  196918. }
  196919. }
  196920. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  196921. {
  196922. if (png_ptr->prev_row == NULL)
  196923. {
  196924. png_warning(png_ptr, "Can't add Average filter after starting");
  196925. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  196926. }
  196927. else
  196928. {
  196929. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  196930. (png_ptr->rowbytes + 1));
  196931. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  196932. }
  196933. }
  196934. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  196935. png_ptr->paeth_row == NULL)
  196936. {
  196937. if (png_ptr->prev_row == NULL)
  196938. {
  196939. png_warning(png_ptr, "Can't add Paeth filter after starting");
  196940. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  196941. }
  196942. else
  196943. {
  196944. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  196945. (png_ptr->rowbytes + 1));
  196946. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  196947. }
  196948. }
  196949. if (png_ptr->do_filter == PNG_NO_FILTERS)
  196950. #endif /* PNG_NO_WRITE_FILTER */
  196951. png_ptr->do_filter = PNG_FILTER_NONE;
  196952. }
  196953. }
  196954. else
  196955. png_error(png_ptr, "Unknown custom filter method");
  196956. }
  196957. /* This allows us to influence the way in which libpng chooses the "best"
  196958. * filter for the current scanline. While the "minimum-sum-of-absolute-
  196959. * differences metric is relatively fast and effective, there is some
  196960. * question as to whether it can be improved upon by trying to keep the
  196961. * filtered data going to zlib more consistent, hopefully resulting in
  196962. * better compression.
  196963. */
  196964. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  196965. void PNGAPI
  196966. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  196967. int num_weights, png_doublep filter_weights,
  196968. png_doublep filter_costs)
  196969. {
  196970. int i;
  196971. png_debug(1, "in png_set_filter_heuristics\n");
  196972. if (png_ptr == NULL)
  196973. return;
  196974. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  196975. {
  196976. png_warning(png_ptr, "Unknown filter heuristic method");
  196977. return;
  196978. }
  196979. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  196980. {
  196981. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  196982. }
  196983. if (num_weights < 0 || filter_weights == NULL ||
  196984. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  196985. {
  196986. num_weights = 0;
  196987. }
  196988. png_ptr->num_prev_filters = (png_byte)num_weights;
  196989. png_ptr->heuristic_method = (png_byte)heuristic_method;
  196990. if (num_weights > 0)
  196991. {
  196992. if (png_ptr->prev_filters == NULL)
  196993. {
  196994. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  196995. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  196996. /* To make sure that the weighting starts out fairly */
  196997. for (i = 0; i < num_weights; i++)
  196998. {
  196999. png_ptr->prev_filters[i] = 255;
  197000. }
  197001. }
  197002. if (png_ptr->filter_weights == NULL)
  197003. {
  197004. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  197005. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  197006. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  197007. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  197008. for (i = 0; i < num_weights; i++)
  197009. {
  197010. png_ptr->inv_filter_weights[i] =
  197011. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  197012. }
  197013. }
  197014. for (i = 0; i < num_weights; i++)
  197015. {
  197016. if (filter_weights[i] < 0.0)
  197017. {
  197018. png_ptr->inv_filter_weights[i] =
  197019. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  197020. }
  197021. else
  197022. {
  197023. png_ptr->inv_filter_weights[i] =
  197024. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  197025. png_ptr->filter_weights[i] =
  197026. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  197027. }
  197028. }
  197029. }
  197030. /* If, in the future, there are other filter methods, this would
  197031. * need to be based on png_ptr->filter.
  197032. */
  197033. if (png_ptr->filter_costs == NULL)
  197034. {
  197035. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  197036. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  197037. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  197038. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  197039. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  197040. {
  197041. png_ptr->inv_filter_costs[i] =
  197042. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  197043. }
  197044. }
  197045. /* Here is where we set the relative costs of the different filters. We
  197046. * should take the desired compression level into account when setting
  197047. * the costs, so that Paeth, for instance, has a high relative cost at low
  197048. * compression levels, while it has a lower relative cost at higher
  197049. * compression settings. The filter types are in order of increasing
  197050. * relative cost, so it would be possible to do this with an algorithm.
  197051. */
  197052. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  197053. {
  197054. if (filter_costs == NULL || filter_costs[i] < 0.0)
  197055. {
  197056. png_ptr->inv_filter_costs[i] =
  197057. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  197058. }
  197059. else if (filter_costs[i] >= 1.0)
  197060. {
  197061. png_ptr->inv_filter_costs[i] =
  197062. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  197063. png_ptr->filter_costs[i] =
  197064. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  197065. }
  197066. }
  197067. }
  197068. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  197069. void PNGAPI
  197070. png_set_compression_level(png_structp png_ptr, int level)
  197071. {
  197072. png_debug(1, "in png_set_compression_level\n");
  197073. if (png_ptr == NULL)
  197074. return;
  197075. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  197076. png_ptr->zlib_level = level;
  197077. }
  197078. void PNGAPI
  197079. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  197080. {
  197081. png_debug(1, "in png_set_compression_mem_level\n");
  197082. if (png_ptr == NULL)
  197083. return;
  197084. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  197085. png_ptr->zlib_mem_level = mem_level;
  197086. }
  197087. void PNGAPI
  197088. png_set_compression_strategy(png_structp png_ptr, int strategy)
  197089. {
  197090. png_debug(1, "in png_set_compression_strategy\n");
  197091. if (png_ptr == NULL)
  197092. return;
  197093. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  197094. png_ptr->zlib_strategy = strategy;
  197095. }
  197096. void PNGAPI
  197097. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  197098. {
  197099. if (png_ptr == NULL)
  197100. return;
  197101. if (window_bits > 15)
  197102. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  197103. else if (window_bits < 8)
  197104. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  197105. #ifndef WBITS_8_OK
  197106. /* avoid libpng bug with 256-byte windows */
  197107. if (window_bits == 8)
  197108. {
  197109. png_warning(png_ptr, "Compression window is being reset to 512");
  197110. window_bits=9;
  197111. }
  197112. #endif
  197113. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  197114. png_ptr->zlib_window_bits = window_bits;
  197115. }
  197116. void PNGAPI
  197117. png_set_compression_method(png_structp png_ptr, int method)
  197118. {
  197119. png_debug(1, "in png_set_compression_method\n");
  197120. if (png_ptr == NULL)
  197121. return;
  197122. if (method != 8)
  197123. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  197124. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  197125. png_ptr->zlib_method = method;
  197126. }
  197127. void PNGAPI
  197128. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  197129. {
  197130. if (png_ptr == NULL)
  197131. return;
  197132. png_ptr->write_row_fn = write_row_fn;
  197133. }
  197134. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  197135. void PNGAPI
  197136. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  197137. write_user_transform_fn)
  197138. {
  197139. png_debug(1, "in png_set_write_user_transform_fn\n");
  197140. if (png_ptr == NULL)
  197141. return;
  197142. png_ptr->transformations |= PNG_USER_TRANSFORM;
  197143. png_ptr->write_user_transform_fn = write_user_transform_fn;
  197144. }
  197145. #endif
  197146. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  197147. void PNGAPI
  197148. png_write_png(png_structp png_ptr, png_infop info_ptr,
  197149. int transforms, voidp params)
  197150. {
  197151. if (png_ptr == NULL || info_ptr == NULL)
  197152. return;
  197153. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  197154. /* invert the alpha channel from opacity to transparency */
  197155. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  197156. png_set_invert_alpha(png_ptr);
  197157. #endif
  197158. /* Write the file header information. */
  197159. png_write_info(png_ptr, info_ptr);
  197160. /* ------ these transformations don't touch the info structure ------- */
  197161. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  197162. /* invert monochrome pixels */
  197163. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  197164. png_set_invert_mono(png_ptr);
  197165. #endif
  197166. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  197167. /* Shift the pixels up to a legal bit depth and fill in
  197168. * as appropriate to correctly scale the image.
  197169. */
  197170. if ((transforms & PNG_TRANSFORM_SHIFT)
  197171. && (info_ptr->valid & PNG_INFO_sBIT))
  197172. png_set_shift(png_ptr, &info_ptr->sig_bit);
  197173. #endif
  197174. #if defined(PNG_WRITE_PACK_SUPPORTED)
  197175. /* pack pixels into bytes */
  197176. if (transforms & PNG_TRANSFORM_PACKING)
  197177. png_set_packing(png_ptr);
  197178. #endif
  197179. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  197180. /* swap location of alpha bytes from ARGB to RGBA */
  197181. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  197182. png_set_swap_alpha(png_ptr);
  197183. #endif
  197184. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  197185. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  197186. * RGB (4 channels -> 3 channels). The second parameter is not used.
  197187. */
  197188. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  197189. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  197190. #endif
  197191. #if defined(PNG_WRITE_BGR_SUPPORTED)
  197192. /* flip BGR pixels to RGB */
  197193. if (transforms & PNG_TRANSFORM_BGR)
  197194. png_set_bgr(png_ptr);
  197195. #endif
  197196. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  197197. /* swap bytes of 16-bit files to most significant byte first */
  197198. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  197199. png_set_swap(png_ptr);
  197200. #endif
  197201. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197202. /* swap bits of 1, 2, 4 bit packed pixel formats */
  197203. if (transforms & PNG_TRANSFORM_PACKSWAP)
  197204. png_set_packswap(png_ptr);
  197205. #endif
  197206. /* ----------------------- end of transformations ------------------- */
  197207. /* write the bits */
  197208. if (info_ptr->valid & PNG_INFO_IDAT)
  197209. png_write_image(png_ptr, info_ptr->row_pointers);
  197210. /* It is REQUIRED to call this to finish writing the rest of the file */
  197211. png_write_end(png_ptr, info_ptr);
  197212. transforms = transforms; /* quiet compiler warnings */
  197213. params = params;
  197214. }
  197215. #endif
  197216. #endif /* PNG_WRITE_SUPPORTED */
  197217. /*** End of inlined file: pngwrite.c ***/
  197218. /*** Start of inlined file: pngwtran.c ***/
  197219. /* pngwtran.c - transforms the data in a row for PNG writers
  197220. *
  197221. * Last changed in libpng 1.2.9 April 14, 2006
  197222. * For conditions of distribution and use, see copyright notice in png.h
  197223. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  197224. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197225. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197226. */
  197227. #define PNG_INTERNAL
  197228. #ifdef PNG_WRITE_SUPPORTED
  197229. /* Transform the data according to the user's wishes. The order of
  197230. * transformations is significant.
  197231. */
  197232. void /* PRIVATE */
  197233. png_do_write_transformations(png_structp png_ptr)
  197234. {
  197235. png_debug(1, "in png_do_write_transformations\n");
  197236. if (png_ptr == NULL)
  197237. return;
  197238. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  197239. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  197240. if(png_ptr->write_user_transform_fn != NULL)
  197241. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  197242. (png_ptr, /* png_ptr */
  197243. &(png_ptr->row_info), /* row_info: */
  197244. /* png_uint_32 width; width of row */
  197245. /* png_uint_32 rowbytes; number of bytes in row */
  197246. /* png_byte color_type; color type of pixels */
  197247. /* png_byte bit_depth; bit depth of samples */
  197248. /* png_byte channels; number of channels (1-4) */
  197249. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  197250. png_ptr->row_buf + 1); /* start of pixel data for row */
  197251. #endif
  197252. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  197253. if (png_ptr->transformations & PNG_FILLER)
  197254. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  197255. png_ptr->flags);
  197256. #endif
  197257. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197258. if (png_ptr->transformations & PNG_PACKSWAP)
  197259. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  197260. #endif
  197261. #if defined(PNG_WRITE_PACK_SUPPORTED)
  197262. if (png_ptr->transformations & PNG_PACK)
  197263. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  197264. (png_uint_32)png_ptr->bit_depth);
  197265. #endif
  197266. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  197267. if (png_ptr->transformations & PNG_SWAP_BYTES)
  197268. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  197269. #endif
  197270. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  197271. if (png_ptr->transformations & PNG_SHIFT)
  197272. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  197273. &(png_ptr->shift));
  197274. #endif
  197275. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  197276. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  197277. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  197278. #endif
  197279. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  197280. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  197281. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  197282. #endif
  197283. #if defined(PNG_WRITE_BGR_SUPPORTED)
  197284. if (png_ptr->transformations & PNG_BGR)
  197285. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  197286. #endif
  197287. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  197288. if (png_ptr->transformations & PNG_INVERT_MONO)
  197289. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  197290. #endif
  197291. }
  197292. #if defined(PNG_WRITE_PACK_SUPPORTED)
  197293. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  197294. * row_info bit depth should be 8 (one pixel per byte). The channels
  197295. * should be 1 (this only happens on grayscale and paletted images).
  197296. */
  197297. void /* PRIVATE */
  197298. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  197299. {
  197300. png_debug(1, "in png_do_pack\n");
  197301. if (row_info->bit_depth == 8 &&
  197302. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197303. row != NULL && row_info != NULL &&
  197304. #endif
  197305. row_info->channels == 1)
  197306. {
  197307. switch ((int)bit_depth)
  197308. {
  197309. case 1:
  197310. {
  197311. png_bytep sp, dp;
  197312. int mask, v;
  197313. png_uint_32 i;
  197314. png_uint_32 row_width = row_info->width;
  197315. sp = row;
  197316. dp = row;
  197317. mask = 0x80;
  197318. v = 0;
  197319. for (i = 0; i < row_width; i++)
  197320. {
  197321. if (*sp != 0)
  197322. v |= mask;
  197323. sp++;
  197324. if (mask > 1)
  197325. mask >>= 1;
  197326. else
  197327. {
  197328. mask = 0x80;
  197329. *dp = (png_byte)v;
  197330. dp++;
  197331. v = 0;
  197332. }
  197333. }
  197334. if (mask != 0x80)
  197335. *dp = (png_byte)v;
  197336. break;
  197337. }
  197338. case 2:
  197339. {
  197340. png_bytep sp, dp;
  197341. int shift, v;
  197342. png_uint_32 i;
  197343. png_uint_32 row_width = row_info->width;
  197344. sp = row;
  197345. dp = row;
  197346. shift = 6;
  197347. v = 0;
  197348. for (i = 0; i < row_width; i++)
  197349. {
  197350. png_byte value;
  197351. value = (png_byte)(*sp & 0x03);
  197352. v |= (value << shift);
  197353. if (shift == 0)
  197354. {
  197355. shift = 6;
  197356. *dp = (png_byte)v;
  197357. dp++;
  197358. v = 0;
  197359. }
  197360. else
  197361. shift -= 2;
  197362. sp++;
  197363. }
  197364. if (shift != 6)
  197365. *dp = (png_byte)v;
  197366. break;
  197367. }
  197368. case 4:
  197369. {
  197370. png_bytep sp, dp;
  197371. int shift, v;
  197372. png_uint_32 i;
  197373. png_uint_32 row_width = row_info->width;
  197374. sp = row;
  197375. dp = row;
  197376. shift = 4;
  197377. v = 0;
  197378. for (i = 0; i < row_width; i++)
  197379. {
  197380. png_byte value;
  197381. value = (png_byte)(*sp & 0x0f);
  197382. v |= (value << shift);
  197383. if (shift == 0)
  197384. {
  197385. shift = 4;
  197386. *dp = (png_byte)v;
  197387. dp++;
  197388. v = 0;
  197389. }
  197390. else
  197391. shift -= 4;
  197392. sp++;
  197393. }
  197394. if (shift != 4)
  197395. *dp = (png_byte)v;
  197396. break;
  197397. }
  197398. }
  197399. row_info->bit_depth = (png_byte)bit_depth;
  197400. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  197401. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  197402. row_info->width);
  197403. }
  197404. }
  197405. #endif
  197406. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  197407. /* Shift pixel values to take advantage of whole range. Pass the
  197408. * true number of bits in bit_depth. The row should be packed
  197409. * according to row_info->bit_depth. Thus, if you had a row of
  197410. * bit depth 4, but the pixels only had values from 0 to 7, you
  197411. * would pass 3 as bit_depth, and this routine would translate the
  197412. * data to 0 to 15.
  197413. */
  197414. void /* PRIVATE */
  197415. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  197416. {
  197417. png_debug(1, "in png_do_shift\n");
  197418. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197419. if (row != NULL && row_info != NULL &&
  197420. #else
  197421. if (
  197422. #endif
  197423. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  197424. {
  197425. int shift_start[4], shift_dec[4];
  197426. int channels = 0;
  197427. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  197428. {
  197429. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  197430. shift_dec[channels] = bit_depth->red;
  197431. channels++;
  197432. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  197433. shift_dec[channels] = bit_depth->green;
  197434. channels++;
  197435. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  197436. shift_dec[channels] = bit_depth->blue;
  197437. channels++;
  197438. }
  197439. else
  197440. {
  197441. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  197442. shift_dec[channels] = bit_depth->gray;
  197443. channels++;
  197444. }
  197445. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  197446. {
  197447. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  197448. shift_dec[channels] = bit_depth->alpha;
  197449. channels++;
  197450. }
  197451. /* with low row depths, could only be grayscale, so one channel */
  197452. if (row_info->bit_depth < 8)
  197453. {
  197454. png_bytep bp = row;
  197455. png_uint_32 i;
  197456. png_byte mask;
  197457. png_uint_32 row_bytes = row_info->rowbytes;
  197458. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  197459. mask = 0x55;
  197460. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  197461. mask = 0x11;
  197462. else
  197463. mask = 0xff;
  197464. for (i = 0; i < row_bytes; i++, bp++)
  197465. {
  197466. png_uint_16 v;
  197467. int j;
  197468. v = *bp;
  197469. *bp = 0;
  197470. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  197471. {
  197472. if (j > 0)
  197473. *bp |= (png_byte)((v << j) & 0xff);
  197474. else
  197475. *bp |= (png_byte)((v >> (-j)) & mask);
  197476. }
  197477. }
  197478. }
  197479. else if (row_info->bit_depth == 8)
  197480. {
  197481. png_bytep bp = row;
  197482. png_uint_32 i;
  197483. png_uint_32 istop = channels * row_info->width;
  197484. for (i = 0; i < istop; i++, bp++)
  197485. {
  197486. png_uint_16 v;
  197487. int j;
  197488. int c = (int)(i%channels);
  197489. v = *bp;
  197490. *bp = 0;
  197491. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  197492. {
  197493. if (j > 0)
  197494. *bp |= (png_byte)((v << j) & 0xff);
  197495. else
  197496. *bp |= (png_byte)((v >> (-j)) & 0xff);
  197497. }
  197498. }
  197499. }
  197500. else
  197501. {
  197502. png_bytep bp;
  197503. png_uint_32 i;
  197504. png_uint_32 istop = channels * row_info->width;
  197505. for (bp = row, i = 0; i < istop; i++)
  197506. {
  197507. int c = (int)(i%channels);
  197508. png_uint_16 value, v;
  197509. int j;
  197510. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  197511. value = 0;
  197512. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  197513. {
  197514. if (j > 0)
  197515. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  197516. else
  197517. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  197518. }
  197519. *bp++ = (png_byte)(value >> 8);
  197520. *bp++ = (png_byte)(value & 0xff);
  197521. }
  197522. }
  197523. }
  197524. }
  197525. #endif
  197526. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  197527. void /* PRIVATE */
  197528. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  197529. {
  197530. png_debug(1, "in png_do_write_swap_alpha\n");
  197531. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197532. if (row != NULL && row_info != NULL)
  197533. #endif
  197534. {
  197535. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  197536. {
  197537. /* This converts from ARGB to RGBA */
  197538. if (row_info->bit_depth == 8)
  197539. {
  197540. png_bytep sp, dp;
  197541. png_uint_32 i;
  197542. png_uint_32 row_width = row_info->width;
  197543. for (i = 0, sp = dp = row; i < row_width; i++)
  197544. {
  197545. png_byte save = *(sp++);
  197546. *(dp++) = *(sp++);
  197547. *(dp++) = *(sp++);
  197548. *(dp++) = *(sp++);
  197549. *(dp++) = save;
  197550. }
  197551. }
  197552. /* This converts from AARRGGBB to RRGGBBAA */
  197553. else
  197554. {
  197555. png_bytep sp, dp;
  197556. png_uint_32 i;
  197557. png_uint_32 row_width = row_info->width;
  197558. for (i = 0, sp = dp = row; i < row_width; i++)
  197559. {
  197560. png_byte save[2];
  197561. save[0] = *(sp++);
  197562. save[1] = *(sp++);
  197563. *(dp++) = *(sp++);
  197564. *(dp++) = *(sp++);
  197565. *(dp++) = *(sp++);
  197566. *(dp++) = *(sp++);
  197567. *(dp++) = *(sp++);
  197568. *(dp++) = *(sp++);
  197569. *(dp++) = save[0];
  197570. *(dp++) = save[1];
  197571. }
  197572. }
  197573. }
  197574. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  197575. {
  197576. /* This converts from AG to GA */
  197577. if (row_info->bit_depth == 8)
  197578. {
  197579. png_bytep sp, dp;
  197580. png_uint_32 i;
  197581. png_uint_32 row_width = row_info->width;
  197582. for (i = 0, sp = dp = row; i < row_width; i++)
  197583. {
  197584. png_byte save = *(sp++);
  197585. *(dp++) = *(sp++);
  197586. *(dp++) = save;
  197587. }
  197588. }
  197589. /* This converts from AAGG to GGAA */
  197590. else
  197591. {
  197592. png_bytep sp, dp;
  197593. png_uint_32 i;
  197594. png_uint_32 row_width = row_info->width;
  197595. for (i = 0, sp = dp = row; i < row_width; i++)
  197596. {
  197597. png_byte save[2];
  197598. save[0] = *(sp++);
  197599. save[1] = *(sp++);
  197600. *(dp++) = *(sp++);
  197601. *(dp++) = *(sp++);
  197602. *(dp++) = save[0];
  197603. *(dp++) = save[1];
  197604. }
  197605. }
  197606. }
  197607. }
  197608. }
  197609. #endif
  197610. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  197611. void /* PRIVATE */
  197612. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  197613. {
  197614. png_debug(1, "in png_do_write_invert_alpha\n");
  197615. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197616. if (row != NULL && row_info != NULL)
  197617. #endif
  197618. {
  197619. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  197620. {
  197621. /* This inverts the alpha channel in RGBA */
  197622. if (row_info->bit_depth == 8)
  197623. {
  197624. png_bytep sp, dp;
  197625. png_uint_32 i;
  197626. png_uint_32 row_width = row_info->width;
  197627. for (i = 0, sp = dp = row; i < row_width; i++)
  197628. {
  197629. /* does nothing
  197630. *(dp++) = *(sp++);
  197631. *(dp++) = *(sp++);
  197632. *(dp++) = *(sp++);
  197633. */
  197634. sp+=3; dp = sp;
  197635. *(dp++) = (png_byte)(255 - *(sp++));
  197636. }
  197637. }
  197638. /* This inverts the alpha channel in RRGGBBAA */
  197639. else
  197640. {
  197641. png_bytep sp, dp;
  197642. png_uint_32 i;
  197643. png_uint_32 row_width = row_info->width;
  197644. for (i = 0, sp = dp = row; i < row_width; i++)
  197645. {
  197646. /* does nothing
  197647. *(dp++) = *(sp++);
  197648. *(dp++) = *(sp++);
  197649. *(dp++) = *(sp++);
  197650. *(dp++) = *(sp++);
  197651. *(dp++) = *(sp++);
  197652. *(dp++) = *(sp++);
  197653. */
  197654. sp+=6; dp = sp;
  197655. *(dp++) = (png_byte)(255 - *(sp++));
  197656. *(dp++) = (png_byte)(255 - *(sp++));
  197657. }
  197658. }
  197659. }
  197660. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  197661. {
  197662. /* This inverts the alpha channel in GA */
  197663. if (row_info->bit_depth == 8)
  197664. {
  197665. png_bytep sp, dp;
  197666. png_uint_32 i;
  197667. png_uint_32 row_width = row_info->width;
  197668. for (i = 0, sp = dp = row; i < row_width; i++)
  197669. {
  197670. *(dp++) = *(sp++);
  197671. *(dp++) = (png_byte)(255 - *(sp++));
  197672. }
  197673. }
  197674. /* This inverts the alpha channel in GGAA */
  197675. else
  197676. {
  197677. png_bytep sp, dp;
  197678. png_uint_32 i;
  197679. png_uint_32 row_width = row_info->width;
  197680. for (i = 0, sp = dp = row; i < row_width; i++)
  197681. {
  197682. /* does nothing
  197683. *(dp++) = *(sp++);
  197684. *(dp++) = *(sp++);
  197685. */
  197686. sp+=2; dp = sp;
  197687. *(dp++) = (png_byte)(255 - *(sp++));
  197688. *(dp++) = (png_byte)(255 - *(sp++));
  197689. }
  197690. }
  197691. }
  197692. }
  197693. }
  197694. #endif
  197695. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197696. /* undoes intrapixel differencing */
  197697. void /* PRIVATE */
  197698. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  197699. {
  197700. png_debug(1, "in png_do_write_intrapixel\n");
  197701. if (
  197702. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197703. row != NULL && row_info != NULL &&
  197704. #endif
  197705. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  197706. {
  197707. int bytes_per_pixel;
  197708. png_uint_32 row_width = row_info->width;
  197709. if (row_info->bit_depth == 8)
  197710. {
  197711. png_bytep rp;
  197712. png_uint_32 i;
  197713. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  197714. bytes_per_pixel = 3;
  197715. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  197716. bytes_per_pixel = 4;
  197717. else
  197718. return;
  197719. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  197720. {
  197721. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  197722. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  197723. }
  197724. }
  197725. else if (row_info->bit_depth == 16)
  197726. {
  197727. png_bytep rp;
  197728. png_uint_32 i;
  197729. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  197730. bytes_per_pixel = 6;
  197731. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  197732. bytes_per_pixel = 8;
  197733. else
  197734. return;
  197735. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  197736. {
  197737. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  197738. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  197739. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  197740. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  197741. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  197742. *(rp ) = (png_byte)((red >> 8) & 0xff);
  197743. *(rp+1) = (png_byte)(red & 0xff);
  197744. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  197745. *(rp+5) = (png_byte)(blue & 0xff);
  197746. }
  197747. }
  197748. }
  197749. }
  197750. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  197751. #endif /* PNG_WRITE_SUPPORTED */
  197752. /*** End of inlined file: pngwtran.c ***/
  197753. /*** Start of inlined file: pngwutil.c ***/
  197754. /* pngwutil.c - utilities to write a PNG file
  197755. *
  197756. * Last changed in libpng 1.2.20 Septhember 3, 2007
  197757. * For conditions of distribution and use, see copyright notice in png.h
  197758. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197759. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197760. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197761. */
  197762. #define PNG_INTERNAL
  197763. #ifdef PNG_WRITE_SUPPORTED
  197764. /* Place a 32-bit number into a buffer in PNG byte order. We work
  197765. * with unsigned numbers for convenience, although one supported
  197766. * ancillary chunk uses signed (two's complement) numbers.
  197767. */
  197768. void PNGAPI
  197769. png_save_uint_32(png_bytep buf, png_uint_32 i)
  197770. {
  197771. buf[0] = (png_byte)((i >> 24) & 0xff);
  197772. buf[1] = (png_byte)((i >> 16) & 0xff);
  197773. buf[2] = (png_byte)((i >> 8) & 0xff);
  197774. buf[3] = (png_byte)(i & 0xff);
  197775. }
  197776. /* The png_save_int_32 function assumes integers are stored in two's
  197777. * complement format. If this isn't the case, then this routine needs to
  197778. * be modified to write data in two's complement format.
  197779. */
  197780. void PNGAPI
  197781. png_save_int_32(png_bytep buf, png_int_32 i)
  197782. {
  197783. buf[0] = (png_byte)((i >> 24) & 0xff);
  197784. buf[1] = (png_byte)((i >> 16) & 0xff);
  197785. buf[2] = (png_byte)((i >> 8) & 0xff);
  197786. buf[3] = (png_byte)(i & 0xff);
  197787. }
  197788. /* Place a 16-bit number into a buffer in PNG byte order.
  197789. * The parameter is declared unsigned int, not png_uint_16,
  197790. * just to avoid potential problems on pre-ANSI C compilers.
  197791. */
  197792. void PNGAPI
  197793. png_save_uint_16(png_bytep buf, unsigned int i)
  197794. {
  197795. buf[0] = (png_byte)((i >> 8) & 0xff);
  197796. buf[1] = (png_byte)(i & 0xff);
  197797. }
  197798. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  197799. * representing the chunk name. The array must be at least 4 bytes in
  197800. * length, and does not need to be null terminated. To be safe, pass the
  197801. * pre-defined chunk names here, and if you need a new one, define it
  197802. * where the others are defined. The length is the length of the data.
  197803. * All the data must be present. If that is not possible, use the
  197804. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  197805. * functions instead.
  197806. */
  197807. void PNGAPI
  197808. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  197809. png_bytep data, png_size_t length)
  197810. {
  197811. if(png_ptr == NULL) return;
  197812. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  197813. png_write_chunk_data(png_ptr, data, length);
  197814. png_write_chunk_end(png_ptr);
  197815. }
  197816. /* Write the start of a PNG chunk. The type is the chunk type.
  197817. * The total_length is the sum of the lengths of all the data you will be
  197818. * passing in png_write_chunk_data().
  197819. */
  197820. void PNGAPI
  197821. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  197822. png_uint_32 length)
  197823. {
  197824. png_byte buf[4];
  197825. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  197826. if(png_ptr == NULL) return;
  197827. /* write the length */
  197828. png_save_uint_32(buf, length);
  197829. png_write_data(png_ptr, buf, (png_size_t)4);
  197830. /* write the chunk name */
  197831. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  197832. /* reset the crc and run it over the chunk name */
  197833. png_reset_crc(png_ptr);
  197834. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  197835. }
  197836. /* Write the data of a PNG chunk started with png_write_chunk_start().
  197837. * Note that multiple calls to this function are allowed, and that the
  197838. * sum of the lengths from these calls *must* add up to the total_length
  197839. * given to png_write_chunk_start().
  197840. */
  197841. void PNGAPI
  197842. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  197843. {
  197844. /* write the data, and run the CRC over it */
  197845. if(png_ptr == NULL) return;
  197846. if (data != NULL && length > 0)
  197847. {
  197848. png_calculate_crc(png_ptr, data, length);
  197849. png_write_data(png_ptr, data, length);
  197850. }
  197851. }
  197852. /* Finish a chunk started with png_write_chunk_start(). */
  197853. void PNGAPI
  197854. png_write_chunk_end(png_structp png_ptr)
  197855. {
  197856. png_byte buf[4];
  197857. if(png_ptr == NULL) return;
  197858. /* write the crc */
  197859. png_save_uint_32(buf, png_ptr->crc);
  197860. png_write_data(png_ptr, buf, (png_size_t)4);
  197861. }
  197862. /* Simple function to write the signature. If we have already written
  197863. * the magic bytes of the signature, or more likely, the PNG stream is
  197864. * being embedded into another stream and doesn't need its own signature,
  197865. * we should call png_set_sig_bytes() to tell libpng how many of the
  197866. * bytes have already been written.
  197867. */
  197868. void /* PRIVATE */
  197869. png_write_sig(png_structp png_ptr)
  197870. {
  197871. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  197872. /* write the rest of the 8 byte signature */
  197873. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  197874. (png_size_t)8 - png_ptr->sig_bytes);
  197875. if(png_ptr->sig_bytes < 3)
  197876. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  197877. }
  197878. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  197879. /*
  197880. * This pair of functions encapsulates the operation of (a) compressing a
  197881. * text string, and (b) issuing it later as a series of chunk data writes.
  197882. * The compression_state structure is shared context for these functions
  197883. * set up by the caller in order to make the whole mess thread-safe.
  197884. */
  197885. typedef struct
  197886. {
  197887. char *input; /* the uncompressed input data */
  197888. int input_len; /* its length */
  197889. int num_output_ptr; /* number of output pointers used */
  197890. int max_output_ptr; /* size of output_ptr */
  197891. png_charpp output_ptr; /* array of pointers to output */
  197892. } compression_state;
  197893. /* compress given text into storage in the png_ptr structure */
  197894. static int /* PRIVATE */
  197895. png_text_compress(png_structp png_ptr,
  197896. png_charp text, png_size_t text_len, int compression,
  197897. compression_state *comp)
  197898. {
  197899. int ret;
  197900. comp->num_output_ptr = 0;
  197901. comp->max_output_ptr = 0;
  197902. comp->output_ptr = NULL;
  197903. comp->input = NULL;
  197904. comp->input_len = 0;
  197905. /* we may just want to pass the text right through */
  197906. if (compression == PNG_TEXT_COMPRESSION_NONE)
  197907. {
  197908. comp->input = text;
  197909. comp->input_len = text_len;
  197910. return((int)text_len);
  197911. }
  197912. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  197913. {
  197914. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  197915. char msg[50];
  197916. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  197917. png_warning(png_ptr, msg);
  197918. #else
  197919. png_warning(png_ptr, "Unknown compression type");
  197920. #endif
  197921. }
  197922. /* We can't write the chunk until we find out how much data we have,
  197923. * which means we need to run the compressor first and save the
  197924. * output. This shouldn't be a problem, as the vast majority of
  197925. * comments should be reasonable, but we will set up an array of
  197926. * malloc'd pointers to be sure.
  197927. *
  197928. * If we knew the application was well behaved, we could simplify this
  197929. * greatly by assuming we can always malloc an output buffer large
  197930. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  197931. * and malloc this directly. The only time this would be a bad idea is
  197932. * if we can't malloc more than 64K and we have 64K of random input
  197933. * data, or if the input string is incredibly large (although this
  197934. * wouldn't cause a failure, just a slowdown due to swapping).
  197935. */
  197936. /* set up the compression buffers */
  197937. png_ptr->zstream.avail_in = (uInt)text_len;
  197938. png_ptr->zstream.next_in = (Bytef *)text;
  197939. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197940. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  197941. /* this is the same compression loop as in png_write_row() */
  197942. do
  197943. {
  197944. /* compress the data */
  197945. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  197946. if (ret != Z_OK)
  197947. {
  197948. /* error */
  197949. if (png_ptr->zstream.msg != NULL)
  197950. png_error(png_ptr, png_ptr->zstream.msg);
  197951. else
  197952. png_error(png_ptr, "zlib error");
  197953. }
  197954. /* check to see if we need more room */
  197955. if (!(png_ptr->zstream.avail_out))
  197956. {
  197957. /* make sure the output array has room */
  197958. if (comp->num_output_ptr >= comp->max_output_ptr)
  197959. {
  197960. int old_max;
  197961. old_max = comp->max_output_ptr;
  197962. comp->max_output_ptr = comp->num_output_ptr + 4;
  197963. if (comp->output_ptr != NULL)
  197964. {
  197965. png_charpp old_ptr;
  197966. old_ptr = comp->output_ptr;
  197967. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  197968. (png_uint_32)(comp->max_output_ptr *
  197969. png_sizeof (png_charpp)));
  197970. png_memcpy(comp->output_ptr, old_ptr, old_max
  197971. * png_sizeof (png_charp));
  197972. png_free(png_ptr, old_ptr);
  197973. }
  197974. else
  197975. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  197976. (png_uint_32)(comp->max_output_ptr *
  197977. png_sizeof (png_charp)));
  197978. }
  197979. /* save the data */
  197980. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  197981. (png_uint_32)png_ptr->zbuf_size);
  197982. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  197983. png_ptr->zbuf_size);
  197984. comp->num_output_ptr++;
  197985. /* and reset the buffer */
  197986. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197987. png_ptr->zstream.next_out = png_ptr->zbuf;
  197988. }
  197989. /* continue until we don't have any more to compress */
  197990. } while (png_ptr->zstream.avail_in);
  197991. /* finish the compression */
  197992. do
  197993. {
  197994. /* tell zlib we are finished */
  197995. ret = deflate(&png_ptr->zstream, Z_FINISH);
  197996. if (ret == Z_OK)
  197997. {
  197998. /* check to see if we need more room */
  197999. if (!(png_ptr->zstream.avail_out))
  198000. {
  198001. /* check to make sure our output array has room */
  198002. if (comp->num_output_ptr >= comp->max_output_ptr)
  198003. {
  198004. int old_max;
  198005. old_max = comp->max_output_ptr;
  198006. comp->max_output_ptr = comp->num_output_ptr + 4;
  198007. if (comp->output_ptr != NULL)
  198008. {
  198009. png_charpp old_ptr;
  198010. old_ptr = comp->output_ptr;
  198011. /* This could be optimized to realloc() */
  198012. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  198013. (png_uint_32)(comp->max_output_ptr *
  198014. png_sizeof (png_charpp)));
  198015. png_memcpy(comp->output_ptr, old_ptr,
  198016. old_max * png_sizeof (png_charp));
  198017. png_free(png_ptr, old_ptr);
  198018. }
  198019. else
  198020. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  198021. (png_uint_32)(comp->max_output_ptr *
  198022. png_sizeof (png_charp)));
  198023. }
  198024. /* save off the data */
  198025. comp->output_ptr[comp->num_output_ptr] =
  198026. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  198027. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  198028. png_ptr->zbuf_size);
  198029. comp->num_output_ptr++;
  198030. /* and reset the buffer pointers */
  198031. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198032. png_ptr->zstream.next_out = png_ptr->zbuf;
  198033. }
  198034. }
  198035. else if (ret != Z_STREAM_END)
  198036. {
  198037. /* we got an error */
  198038. if (png_ptr->zstream.msg != NULL)
  198039. png_error(png_ptr, png_ptr->zstream.msg);
  198040. else
  198041. png_error(png_ptr, "zlib error");
  198042. }
  198043. } while (ret != Z_STREAM_END);
  198044. /* text length is number of buffers plus last buffer */
  198045. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  198046. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  198047. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  198048. return((int)text_len);
  198049. }
  198050. /* ship the compressed text out via chunk writes */
  198051. static void /* PRIVATE */
  198052. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  198053. {
  198054. int i;
  198055. /* handle the no-compression case */
  198056. if (comp->input)
  198057. {
  198058. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  198059. (png_size_t)comp->input_len);
  198060. return;
  198061. }
  198062. /* write saved output buffers, if any */
  198063. for (i = 0; i < comp->num_output_ptr; i++)
  198064. {
  198065. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  198066. png_ptr->zbuf_size);
  198067. png_free(png_ptr, comp->output_ptr[i]);
  198068. comp->output_ptr[i]=NULL;
  198069. }
  198070. if (comp->max_output_ptr != 0)
  198071. png_free(png_ptr, comp->output_ptr);
  198072. comp->output_ptr=NULL;
  198073. /* write anything left in zbuf */
  198074. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  198075. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  198076. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  198077. /* reset zlib for another zTXt/iTXt or image data */
  198078. deflateReset(&png_ptr->zstream);
  198079. png_ptr->zstream.data_type = Z_BINARY;
  198080. }
  198081. #endif
  198082. /* Write the IHDR chunk, and update the png_struct with the necessary
  198083. * information. Note that the rest of this code depends upon this
  198084. * information being correct.
  198085. */
  198086. void /* PRIVATE */
  198087. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  198088. int bit_depth, int color_type, int compression_type, int filter_type,
  198089. int interlace_type)
  198090. {
  198091. #ifdef PNG_USE_LOCAL_ARRAYS
  198092. PNG_IHDR;
  198093. #endif
  198094. png_byte buf[13]; /* buffer to store the IHDR info */
  198095. png_debug(1, "in png_write_IHDR\n");
  198096. /* Check that we have valid input data from the application info */
  198097. switch (color_type)
  198098. {
  198099. case PNG_COLOR_TYPE_GRAY:
  198100. switch (bit_depth)
  198101. {
  198102. case 1:
  198103. case 2:
  198104. case 4:
  198105. case 8:
  198106. case 16: png_ptr->channels = 1; break;
  198107. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  198108. }
  198109. break;
  198110. case PNG_COLOR_TYPE_RGB:
  198111. if (bit_depth != 8 && bit_depth != 16)
  198112. png_error(png_ptr, "Invalid bit depth for RGB image");
  198113. png_ptr->channels = 3;
  198114. break;
  198115. case PNG_COLOR_TYPE_PALETTE:
  198116. switch (bit_depth)
  198117. {
  198118. case 1:
  198119. case 2:
  198120. case 4:
  198121. case 8: png_ptr->channels = 1; break;
  198122. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  198123. }
  198124. break;
  198125. case PNG_COLOR_TYPE_GRAY_ALPHA:
  198126. if (bit_depth != 8 && bit_depth != 16)
  198127. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  198128. png_ptr->channels = 2;
  198129. break;
  198130. case PNG_COLOR_TYPE_RGB_ALPHA:
  198131. if (bit_depth != 8 && bit_depth != 16)
  198132. png_error(png_ptr, "Invalid bit depth for RGBA image");
  198133. png_ptr->channels = 4;
  198134. break;
  198135. default:
  198136. png_error(png_ptr, "Invalid image color type specified");
  198137. }
  198138. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  198139. {
  198140. png_warning(png_ptr, "Invalid compression type specified");
  198141. compression_type = PNG_COMPRESSION_TYPE_BASE;
  198142. }
  198143. /* Write filter_method 64 (intrapixel differencing) only if
  198144. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  198145. * 2. Libpng did not write a PNG signature (this filter_method is only
  198146. * used in PNG datastreams that are embedded in MNG datastreams) and
  198147. * 3. The application called png_permit_mng_features with a mask that
  198148. * included PNG_FLAG_MNG_FILTER_64 and
  198149. * 4. The filter_method is 64 and
  198150. * 5. The color_type is RGB or RGBA
  198151. */
  198152. if (
  198153. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198154. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  198155. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  198156. (color_type == PNG_COLOR_TYPE_RGB ||
  198157. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  198158. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  198159. #endif
  198160. filter_type != PNG_FILTER_TYPE_BASE)
  198161. {
  198162. png_warning(png_ptr, "Invalid filter type specified");
  198163. filter_type = PNG_FILTER_TYPE_BASE;
  198164. }
  198165. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  198166. if (interlace_type != PNG_INTERLACE_NONE &&
  198167. interlace_type != PNG_INTERLACE_ADAM7)
  198168. {
  198169. png_warning(png_ptr, "Invalid interlace type specified");
  198170. interlace_type = PNG_INTERLACE_ADAM7;
  198171. }
  198172. #else
  198173. interlace_type=PNG_INTERLACE_NONE;
  198174. #endif
  198175. /* save off the relevent information */
  198176. png_ptr->bit_depth = (png_byte)bit_depth;
  198177. png_ptr->color_type = (png_byte)color_type;
  198178. png_ptr->interlaced = (png_byte)interlace_type;
  198179. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198180. png_ptr->filter_type = (png_byte)filter_type;
  198181. #endif
  198182. png_ptr->compression_type = (png_byte)compression_type;
  198183. png_ptr->width = width;
  198184. png_ptr->height = height;
  198185. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  198186. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  198187. /* set the usr info, so any transformations can modify it */
  198188. png_ptr->usr_width = png_ptr->width;
  198189. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  198190. png_ptr->usr_channels = png_ptr->channels;
  198191. /* pack the header information into the buffer */
  198192. png_save_uint_32(buf, width);
  198193. png_save_uint_32(buf + 4, height);
  198194. buf[8] = (png_byte)bit_depth;
  198195. buf[9] = (png_byte)color_type;
  198196. buf[10] = (png_byte)compression_type;
  198197. buf[11] = (png_byte)filter_type;
  198198. buf[12] = (png_byte)interlace_type;
  198199. /* write the chunk */
  198200. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  198201. /* initialize zlib with PNG info */
  198202. png_ptr->zstream.zalloc = png_zalloc;
  198203. png_ptr->zstream.zfree = png_zfree;
  198204. png_ptr->zstream.opaque = (voidpf)png_ptr;
  198205. if (!(png_ptr->do_filter))
  198206. {
  198207. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  198208. png_ptr->bit_depth < 8)
  198209. png_ptr->do_filter = PNG_FILTER_NONE;
  198210. else
  198211. png_ptr->do_filter = PNG_ALL_FILTERS;
  198212. }
  198213. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  198214. {
  198215. if (png_ptr->do_filter != PNG_FILTER_NONE)
  198216. png_ptr->zlib_strategy = Z_FILTERED;
  198217. else
  198218. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  198219. }
  198220. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  198221. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  198222. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  198223. png_ptr->zlib_mem_level = 8;
  198224. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  198225. png_ptr->zlib_window_bits = 15;
  198226. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  198227. png_ptr->zlib_method = 8;
  198228. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  198229. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  198230. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  198231. png_error(png_ptr, "zlib failed to initialize compressor");
  198232. png_ptr->zstream.next_out = png_ptr->zbuf;
  198233. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198234. /* libpng is not interested in zstream.data_type */
  198235. /* set it to a predefined value, to avoid its evaluation inside zlib */
  198236. png_ptr->zstream.data_type = Z_BINARY;
  198237. png_ptr->mode = PNG_HAVE_IHDR;
  198238. }
  198239. /* write the palette. We are careful not to trust png_color to be in the
  198240. * correct order for PNG, so people can redefine it to any convenient
  198241. * structure.
  198242. */
  198243. void /* PRIVATE */
  198244. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  198245. {
  198246. #ifdef PNG_USE_LOCAL_ARRAYS
  198247. PNG_PLTE;
  198248. #endif
  198249. png_uint_32 i;
  198250. png_colorp pal_ptr;
  198251. png_byte buf[3];
  198252. png_debug(1, "in png_write_PLTE\n");
  198253. if ((
  198254. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198255. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  198256. #endif
  198257. num_pal == 0) || num_pal > 256)
  198258. {
  198259. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198260. {
  198261. png_error(png_ptr, "Invalid number of colors in palette");
  198262. }
  198263. else
  198264. {
  198265. png_warning(png_ptr, "Invalid number of colors in palette");
  198266. return;
  198267. }
  198268. }
  198269. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  198270. {
  198271. png_warning(png_ptr,
  198272. "Ignoring request to write a PLTE chunk in grayscale PNG");
  198273. return;
  198274. }
  198275. png_ptr->num_palette = (png_uint_16)num_pal;
  198276. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  198277. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  198278. #ifndef PNG_NO_POINTER_INDEXING
  198279. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  198280. {
  198281. buf[0] = pal_ptr->red;
  198282. buf[1] = pal_ptr->green;
  198283. buf[2] = pal_ptr->blue;
  198284. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  198285. }
  198286. #else
  198287. /* This is a little slower but some buggy compilers need to do this instead */
  198288. pal_ptr=palette;
  198289. for (i = 0; i < num_pal; i++)
  198290. {
  198291. buf[0] = pal_ptr[i].red;
  198292. buf[1] = pal_ptr[i].green;
  198293. buf[2] = pal_ptr[i].blue;
  198294. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  198295. }
  198296. #endif
  198297. png_write_chunk_end(png_ptr);
  198298. png_ptr->mode |= PNG_HAVE_PLTE;
  198299. }
  198300. /* write an IDAT chunk */
  198301. void /* PRIVATE */
  198302. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  198303. {
  198304. #ifdef PNG_USE_LOCAL_ARRAYS
  198305. PNG_IDAT;
  198306. #endif
  198307. png_debug(1, "in png_write_IDAT\n");
  198308. /* Optimize the CMF field in the zlib stream. */
  198309. /* This hack of the zlib stream is compliant to the stream specification. */
  198310. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  198311. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  198312. {
  198313. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  198314. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  198315. {
  198316. /* Avoid memory underflows and multiplication overflows. */
  198317. /* The conditions below are practically always satisfied;
  198318. however, they still must be checked. */
  198319. if (length >= 2 &&
  198320. png_ptr->height < 16384 && png_ptr->width < 16384)
  198321. {
  198322. png_uint_32 uncompressed_idat_size = png_ptr->height *
  198323. ((png_ptr->width *
  198324. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  198325. unsigned int z_cinfo = z_cmf >> 4;
  198326. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  198327. while (uncompressed_idat_size <= half_z_window_size &&
  198328. half_z_window_size >= 256)
  198329. {
  198330. z_cinfo--;
  198331. half_z_window_size >>= 1;
  198332. }
  198333. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  198334. if (data[0] != (png_byte)z_cmf)
  198335. {
  198336. data[0] = (png_byte)z_cmf;
  198337. data[1] &= 0xe0;
  198338. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  198339. }
  198340. }
  198341. }
  198342. else
  198343. png_error(png_ptr,
  198344. "Invalid zlib compression method or flags in IDAT");
  198345. }
  198346. png_write_chunk(png_ptr, png_IDAT, data, length);
  198347. png_ptr->mode |= PNG_HAVE_IDAT;
  198348. }
  198349. /* write an IEND chunk */
  198350. void /* PRIVATE */
  198351. png_write_IEND(png_structp png_ptr)
  198352. {
  198353. #ifdef PNG_USE_LOCAL_ARRAYS
  198354. PNG_IEND;
  198355. #endif
  198356. png_debug(1, "in png_write_IEND\n");
  198357. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  198358. (png_size_t)0);
  198359. png_ptr->mode |= PNG_HAVE_IEND;
  198360. }
  198361. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  198362. /* write a gAMA chunk */
  198363. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198364. void /* PRIVATE */
  198365. png_write_gAMA(png_structp png_ptr, double file_gamma)
  198366. {
  198367. #ifdef PNG_USE_LOCAL_ARRAYS
  198368. PNG_gAMA;
  198369. #endif
  198370. png_uint_32 igamma;
  198371. png_byte buf[4];
  198372. png_debug(1, "in png_write_gAMA\n");
  198373. /* file_gamma is saved in 1/100,000ths */
  198374. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  198375. png_save_uint_32(buf, igamma);
  198376. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  198377. }
  198378. #endif
  198379. #ifdef PNG_FIXED_POINT_SUPPORTED
  198380. void /* PRIVATE */
  198381. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  198382. {
  198383. #ifdef PNG_USE_LOCAL_ARRAYS
  198384. PNG_gAMA;
  198385. #endif
  198386. png_byte buf[4];
  198387. png_debug(1, "in png_write_gAMA\n");
  198388. /* file_gamma is saved in 1/100,000ths */
  198389. png_save_uint_32(buf, (png_uint_32)file_gamma);
  198390. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  198391. }
  198392. #endif
  198393. #endif
  198394. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  198395. /* write a sRGB chunk */
  198396. void /* PRIVATE */
  198397. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  198398. {
  198399. #ifdef PNG_USE_LOCAL_ARRAYS
  198400. PNG_sRGB;
  198401. #endif
  198402. png_byte buf[1];
  198403. png_debug(1, "in png_write_sRGB\n");
  198404. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  198405. png_warning(png_ptr,
  198406. "Invalid sRGB rendering intent specified");
  198407. buf[0]=(png_byte)srgb_intent;
  198408. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  198409. }
  198410. #endif
  198411. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  198412. /* write an iCCP chunk */
  198413. void /* PRIVATE */
  198414. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  198415. png_charp profile, int profile_len)
  198416. {
  198417. #ifdef PNG_USE_LOCAL_ARRAYS
  198418. PNG_iCCP;
  198419. #endif
  198420. png_size_t name_len;
  198421. png_charp new_name;
  198422. compression_state comp;
  198423. int embedded_profile_len = 0;
  198424. png_debug(1, "in png_write_iCCP\n");
  198425. comp.num_output_ptr = 0;
  198426. comp.max_output_ptr = 0;
  198427. comp.output_ptr = NULL;
  198428. comp.input = NULL;
  198429. comp.input_len = 0;
  198430. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  198431. &new_name)) == 0)
  198432. {
  198433. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  198434. return;
  198435. }
  198436. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  198437. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  198438. if (profile == NULL)
  198439. profile_len = 0;
  198440. if (profile_len > 3)
  198441. embedded_profile_len =
  198442. ((*( (png_bytep)profile ))<<24) |
  198443. ((*( (png_bytep)profile+1))<<16) |
  198444. ((*( (png_bytep)profile+2))<< 8) |
  198445. ((*( (png_bytep)profile+3)) );
  198446. if (profile_len < embedded_profile_len)
  198447. {
  198448. png_warning(png_ptr,
  198449. "Embedded profile length too large in iCCP chunk");
  198450. return;
  198451. }
  198452. if (profile_len > embedded_profile_len)
  198453. {
  198454. png_warning(png_ptr,
  198455. "Truncating profile to actual length in iCCP chunk");
  198456. profile_len = embedded_profile_len;
  198457. }
  198458. if (profile_len)
  198459. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  198460. PNG_COMPRESSION_TYPE_BASE, &comp);
  198461. /* make sure we include the NULL after the name and the compression type */
  198462. png_write_chunk_start(png_ptr, png_iCCP,
  198463. (png_uint_32)name_len+profile_len+2);
  198464. new_name[name_len+1]=0x00;
  198465. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  198466. if (profile_len)
  198467. png_write_compressed_data_out(png_ptr, &comp);
  198468. png_write_chunk_end(png_ptr);
  198469. png_free(png_ptr, new_name);
  198470. }
  198471. #endif
  198472. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  198473. /* write a sPLT chunk */
  198474. void /* PRIVATE */
  198475. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  198476. {
  198477. #ifdef PNG_USE_LOCAL_ARRAYS
  198478. PNG_sPLT;
  198479. #endif
  198480. png_size_t name_len;
  198481. png_charp new_name;
  198482. png_byte entrybuf[10];
  198483. int entry_size = (spalette->depth == 8 ? 6 : 10);
  198484. int palette_size = entry_size * spalette->nentries;
  198485. png_sPLT_entryp ep;
  198486. #ifdef PNG_NO_POINTER_INDEXING
  198487. int i;
  198488. #endif
  198489. png_debug(1, "in png_write_sPLT\n");
  198490. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  198491. spalette->name, &new_name))==0)
  198492. {
  198493. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  198494. return;
  198495. }
  198496. /* make sure we include the NULL after the name */
  198497. png_write_chunk_start(png_ptr, png_sPLT,
  198498. (png_uint_32)(name_len + 2 + palette_size));
  198499. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  198500. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  198501. /* loop through each palette entry, writing appropriately */
  198502. #ifndef PNG_NO_POINTER_INDEXING
  198503. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  198504. {
  198505. if (spalette->depth == 8)
  198506. {
  198507. entrybuf[0] = (png_byte)ep->red;
  198508. entrybuf[1] = (png_byte)ep->green;
  198509. entrybuf[2] = (png_byte)ep->blue;
  198510. entrybuf[3] = (png_byte)ep->alpha;
  198511. png_save_uint_16(entrybuf + 4, ep->frequency);
  198512. }
  198513. else
  198514. {
  198515. png_save_uint_16(entrybuf + 0, ep->red);
  198516. png_save_uint_16(entrybuf + 2, ep->green);
  198517. png_save_uint_16(entrybuf + 4, ep->blue);
  198518. png_save_uint_16(entrybuf + 6, ep->alpha);
  198519. png_save_uint_16(entrybuf + 8, ep->frequency);
  198520. }
  198521. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  198522. }
  198523. #else
  198524. ep=spalette->entries;
  198525. for (i=0; i>spalette->nentries; i++)
  198526. {
  198527. if (spalette->depth == 8)
  198528. {
  198529. entrybuf[0] = (png_byte)ep[i].red;
  198530. entrybuf[1] = (png_byte)ep[i].green;
  198531. entrybuf[2] = (png_byte)ep[i].blue;
  198532. entrybuf[3] = (png_byte)ep[i].alpha;
  198533. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  198534. }
  198535. else
  198536. {
  198537. png_save_uint_16(entrybuf + 0, ep[i].red);
  198538. png_save_uint_16(entrybuf + 2, ep[i].green);
  198539. png_save_uint_16(entrybuf + 4, ep[i].blue);
  198540. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  198541. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  198542. }
  198543. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  198544. }
  198545. #endif
  198546. png_write_chunk_end(png_ptr);
  198547. png_free(png_ptr, new_name);
  198548. }
  198549. #endif
  198550. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  198551. /* write the sBIT chunk */
  198552. void /* PRIVATE */
  198553. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  198554. {
  198555. #ifdef PNG_USE_LOCAL_ARRAYS
  198556. PNG_sBIT;
  198557. #endif
  198558. png_byte buf[4];
  198559. png_size_t size;
  198560. png_debug(1, "in png_write_sBIT\n");
  198561. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  198562. if (color_type & PNG_COLOR_MASK_COLOR)
  198563. {
  198564. png_byte maxbits;
  198565. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  198566. png_ptr->usr_bit_depth);
  198567. if (sbit->red == 0 || sbit->red > maxbits ||
  198568. sbit->green == 0 || sbit->green > maxbits ||
  198569. sbit->blue == 0 || sbit->blue > maxbits)
  198570. {
  198571. png_warning(png_ptr, "Invalid sBIT depth specified");
  198572. return;
  198573. }
  198574. buf[0] = sbit->red;
  198575. buf[1] = sbit->green;
  198576. buf[2] = sbit->blue;
  198577. size = 3;
  198578. }
  198579. else
  198580. {
  198581. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  198582. {
  198583. png_warning(png_ptr, "Invalid sBIT depth specified");
  198584. return;
  198585. }
  198586. buf[0] = sbit->gray;
  198587. size = 1;
  198588. }
  198589. if (color_type & PNG_COLOR_MASK_ALPHA)
  198590. {
  198591. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  198592. {
  198593. png_warning(png_ptr, "Invalid sBIT depth specified");
  198594. return;
  198595. }
  198596. buf[size++] = sbit->alpha;
  198597. }
  198598. png_write_chunk(png_ptr, png_sBIT, buf, size);
  198599. }
  198600. #endif
  198601. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  198602. /* write the cHRM chunk */
  198603. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198604. void /* PRIVATE */
  198605. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  198606. double red_x, double red_y, double green_x, double green_y,
  198607. double blue_x, double blue_y)
  198608. {
  198609. #ifdef PNG_USE_LOCAL_ARRAYS
  198610. PNG_cHRM;
  198611. #endif
  198612. png_byte buf[32];
  198613. png_uint_32 itemp;
  198614. png_debug(1, "in png_write_cHRM\n");
  198615. /* each value is saved in 1/100,000ths */
  198616. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  198617. white_x + white_y > 1.0)
  198618. {
  198619. png_warning(png_ptr, "Invalid cHRM white point specified");
  198620. #if !defined(PNG_NO_CONSOLE_IO)
  198621. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  198622. #endif
  198623. return;
  198624. }
  198625. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  198626. png_save_uint_32(buf, itemp);
  198627. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  198628. png_save_uint_32(buf + 4, itemp);
  198629. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  198630. {
  198631. png_warning(png_ptr, "Invalid cHRM red point specified");
  198632. return;
  198633. }
  198634. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  198635. png_save_uint_32(buf + 8, itemp);
  198636. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  198637. png_save_uint_32(buf + 12, itemp);
  198638. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  198639. {
  198640. png_warning(png_ptr, "Invalid cHRM green point specified");
  198641. return;
  198642. }
  198643. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  198644. png_save_uint_32(buf + 16, itemp);
  198645. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  198646. png_save_uint_32(buf + 20, itemp);
  198647. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  198648. {
  198649. png_warning(png_ptr, "Invalid cHRM blue point specified");
  198650. return;
  198651. }
  198652. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  198653. png_save_uint_32(buf + 24, itemp);
  198654. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  198655. png_save_uint_32(buf + 28, itemp);
  198656. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  198657. }
  198658. #endif
  198659. #ifdef PNG_FIXED_POINT_SUPPORTED
  198660. void /* PRIVATE */
  198661. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  198662. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  198663. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  198664. png_fixed_point blue_y)
  198665. {
  198666. #ifdef PNG_USE_LOCAL_ARRAYS
  198667. PNG_cHRM;
  198668. #endif
  198669. png_byte buf[32];
  198670. png_debug(1, "in png_write_cHRM\n");
  198671. /* each value is saved in 1/100,000ths */
  198672. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  198673. {
  198674. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  198675. #if !defined(PNG_NO_CONSOLE_IO)
  198676. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  198677. #endif
  198678. return;
  198679. }
  198680. png_save_uint_32(buf, (png_uint_32)white_x);
  198681. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  198682. if (red_x + red_y > 100000L)
  198683. {
  198684. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  198685. return;
  198686. }
  198687. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  198688. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  198689. if (green_x + green_y > 100000L)
  198690. {
  198691. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  198692. return;
  198693. }
  198694. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  198695. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  198696. if (blue_x + blue_y > 100000L)
  198697. {
  198698. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  198699. return;
  198700. }
  198701. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  198702. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  198703. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  198704. }
  198705. #endif
  198706. #endif
  198707. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  198708. /* write the tRNS chunk */
  198709. void /* PRIVATE */
  198710. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  198711. int num_trans, int color_type)
  198712. {
  198713. #ifdef PNG_USE_LOCAL_ARRAYS
  198714. PNG_tRNS;
  198715. #endif
  198716. png_byte buf[6];
  198717. png_debug(1, "in png_write_tRNS\n");
  198718. if (color_type == PNG_COLOR_TYPE_PALETTE)
  198719. {
  198720. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  198721. {
  198722. png_warning(png_ptr,"Invalid number of transparent colors specified");
  198723. return;
  198724. }
  198725. /* write the chunk out as it is */
  198726. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  198727. }
  198728. else if (color_type == PNG_COLOR_TYPE_GRAY)
  198729. {
  198730. /* one 16 bit value */
  198731. if(tran->gray >= (1 << png_ptr->bit_depth))
  198732. {
  198733. png_warning(png_ptr,
  198734. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  198735. return;
  198736. }
  198737. png_save_uint_16(buf, tran->gray);
  198738. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  198739. }
  198740. else if (color_type == PNG_COLOR_TYPE_RGB)
  198741. {
  198742. /* three 16 bit values */
  198743. png_save_uint_16(buf, tran->red);
  198744. png_save_uint_16(buf + 2, tran->green);
  198745. png_save_uint_16(buf + 4, tran->blue);
  198746. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  198747. {
  198748. png_warning(png_ptr,
  198749. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  198750. return;
  198751. }
  198752. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  198753. }
  198754. else
  198755. {
  198756. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  198757. }
  198758. }
  198759. #endif
  198760. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  198761. /* write the background chunk */
  198762. void /* PRIVATE */
  198763. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  198764. {
  198765. #ifdef PNG_USE_LOCAL_ARRAYS
  198766. PNG_bKGD;
  198767. #endif
  198768. png_byte buf[6];
  198769. png_debug(1, "in png_write_bKGD\n");
  198770. if (color_type == PNG_COLOR_TYPE_PALETTE)
  198771. {
  198772. if (
  198773. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198774. (png_ptr->num_palette ||
  198775. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  198776. #endif
  198777. back->index > png_ptr->num_palette)
  198778. {
  198779. png_warning(png_ptr, "Invalid background palette index");
  198780. return;
  198781. }
  198782. buf[0] = back->index;
  198783. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  198784. }
  198785. else if (color_type & PNG_COLOR_MASK_COLOR)
  198786. {
  198787. png_save_uint_16(buf, back->red);
  198788. png_save_uint_16(buf + 2, back->green);
  198789. png_save_uint_16(buf + 4, back->blue);
  198790. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  198791. {
  198792. png_warning(png_ptr,
  198793. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  198794. return;
  198795. }
  198796. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  198797. }
  198798. else
  198799. {
  198800. if(back->gray >= (1 << png_ptr->bit_depth))
  198801. {
  198802. png_warning(png_ptr,
  198803. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  198804. return;
  198805. }
  198806. png_save_uint_16(buf, back->gray);
  198807. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  198808. }
  198809. }
  198810. #endif
  198811. #if defined(PNG_WRITE_hIST_SUPPORTED)
  198812. /* write the histogram */
  198813. void /* PRIVATE */
  198814. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  198815. {
  198816. #ifdef PNG_USE_LOCAL_ARRAYS
  198817. PNG_hIST;
  198818. #endif
  198819. int i;
  198820. png_byte buf[3];
  198821. png_debug(1, "in png_write_hIST\n");
  198822. if (num_hist > (int)png_ptr->num_palette)
  198823. {
  198824. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  198825. png_ptr->num_palette);
  198826. png_warning(png_ptr, "Invalid number of histogram entries specified");
  198827. return;
  198828. }
  198829. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  198830. for (i = 0; i < num_hist; i++)
  198831. {
  198832. png_save_uint_16(buf, hist[i]);
  198833. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  198834. }
  198835. png_write_chunk_end(png_ptr);
  198836. }
  198837. #endif
  198838. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  198839. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  198840. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  198841. * and if invalid, correct the keyword rather than discarding the entire
  198842. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  198843. * length, forbids leading or trailing whitespace, multiple internal spaces,
  198844. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  198845. *
  198846. * The new_key is allocated to hold the corrected keyword and must be freed
  198847. * by the calling routine. This avoids problems with trying to write to
  198848. * static keywords without having to have duplicate copies of the strings.
  198849. */
  198850. png_size_t /* PRIVATE */
  198851. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  198852. {
  198853. png_size_t key_len;
  198854. png_charp kp, dp;
  198855. int kflag;
  198856. int kwarn=0;
  198857. png_debug(1, "in png_check_keyword\n");
  198858. *new_key = NULL;
  198859. if (key == NULL || (key_len = png_strlen(key)) == 0)
  198860. {
  198861. png_warning(png_ptr, "zero length keyword");
  198862. return ((png_size_t)0);
  198863. }
  198864. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  198865. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  198866. if (*new_key == NULL)
  198867. {
  198868. png_warning(png_ptr, "Out of memory while procesing keyword");
  198869. return ((png_size_t)0);
  198870. }
  198871. /* Replace non-printing characters with a blank and print a warning */
  198872. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  198873. {
  198874. if ((png_byte)*kp < 0x20 ||
  198875. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  198876. {
  198877. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  198878. char msg[40];
  198879. png_snprintf(msg, 40,
  198880. "invalid keyword character 0x%02X", (png_byte)*kp);
  198881. png_warning(png_ptr, msg);
  198882. #else
  198883. png_warning(png_ptr, "invalid character in keyword");
  198884. #endif
  198885. *dp = ' ';
  198886. }
  198887. else
  198888. {
  198889. *dp = *kp;
  198890. }
  198891. }
  198892. *dp = '\0';
  198893. /* Remove any trailing white space. */
  198894. kp = *new_key + key_len - 1;
  198895. if (*kp == ' ')
  198896. {
  198897. png_warning(png_ptr, "trailing spaces removed from keyword");
  198898. while (*kp == ' ')
  198899. {
  198900. *(kp--) = '\0';
  198901. key_len--;
  198902. }
  198903. }
  198904. /* Remove any leading white space. */
  198905. kp = *new_key;
  198906. if (*kp == ' ')
  198907. {
  198908. png_warning(png_ptr, "leading spaces removed from keyword");
  198909. while (*kp == ' ')
  198910. {
  198911. kp++;
  198912. key_len--;
  198913. }
  198914. }
  198915. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  198916. /* Remove multiple internal spaces. */
  198917. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  198918. {
  198919. if (*kp == ' ' && kflag == 0)
  198920. {
  198921. *(dp++) = *kp;
  198922. kflag = 1;
  198923. }
  198924. else if (*kp == ' ')
  198925. {
  198926. key_len--;
  198927. kwarn=1;
  198928. }
  198929. else
  198930. {
  198931. *(dp++) = *kp;
  198932. kflag = 0;
  198933. }
  198934. }
  198935. *dp = '\0';
  198936. if(kwarn)
  198937. png_warning(png_ptr, "extra interior spaces removed from keyword");
  198938. if (key_len == 0)
  198939. {
  198940. png_free(png_ptr, *new_key);
  198941. *new_key=NULL;
  198942. png_warning(png_ptr, "Zero length keyword");
  198943. }
  198944. if (key_len > 79)
  198945. {
  198946. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  198947. new_key[79] = '\0';
  198948. key_len = 79;
  198949. }
  198950. return (key_len);
  198951. }
  198952. #endif
  198953. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198954. /* write a tEXt chunk */
  198955. void /* PRIVATE */
  198956. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  198957. png_size_t text_len)
  198958. {
  198959. #ifdef PNG_USE_LOCAL_ARRAYS
  198960. PNG_tEXt;
  198961. #endif
  198962. png_size_t key_len;
  198963. png_charp new_key;
  198964. png_debug(1, "in png_write_tEXt\n");
  198965. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  198966. {
  198967. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  198968. return;
  198969. }
  198970. if (text == NULL || *text == '\0')
  198971. text_len = 0;
  198972. else
  198973. text_len = png_strlen(text);
  198974. /* make sure we include the 0 after the key */
  198975. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  198976. /*
  198977. * We leave it to the application to meet PNG-1.0 requirements on the
  198978. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  198979. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  198980. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  198981. */
  198982. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  198983. if (text_len)
  198984. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  198985. png_write_chunk_end(png_ptr);
  198986. png_free(png_ptr, new_key);
  198987. }
  198988. #endif
  198989. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198990. /* write a compressed text chunk */
  198991. void /* PRIVATE */
  198992. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  198993. png_size_t text_len, int compression)
  198994. {
  198995. #ifdef PNG_USE_LOCAL_ARRAYS
  198996. PNG_zTXt;
  198997. #endif
  198998. png_size_t key_len;
  198999. char buf[1];
  199000. png_charp new_key;
  199001. compression_state comp;
  199002. png_debug(1, "in png_write_zTXt\n");
  199003. comp.num_output_ptr = 0;
  199004. comp.max_output_ptr = 0;
  199005. comp.output_ptr = NULL;
  199006. comp.input = NULL;
  199007. comp.input_len = 0;
  199008. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  199009. {
  199010. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  199011. return;
  199012. }
  199013. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  199014. {
  199015. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  199016. png_free(png_ptr, new_key);
  199017. return;
  199018. }
  199019. text_len = png_strlen(text);
  199020. /* compute the compressed data; do it now for the length */
  199021. text_len = png_text_compress(png_ptr, text, text_len, compression,
  199022. &comp);
  199023. /* write start of chunk */
  199024. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  199025. (key_len+text_len+2));
  199026. /* write key */
  199027. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  199028. png_free(png_ptr, new_key);
  199029. buf[0] = (png_byte)compression;
  199030. /* write compression */
  199031. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  199032. /* write the compressed data */
  199033. png_write_compressed_data_out(png_ptr, &comp);
  199034. /* close the chunk */
  199035. png_write_chunk_end(png_ptr);
  199036. }
  199037. #endif
  199038. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  199039. /* write an iTXt chunk */
  199040. void /* PRIVATE */
  199041. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  199042. png_charp lang, png_charp lang_key, png_charp text)
  199043. {
  199044. #ifdef PNG_USE_LOCAL_ARRAYS
  199045. PNG_iTXt;
  199046. #endif
  199047. png_size_t lang_len, key_len, lang_key_len, text_len;
  199048. png_charp new_lang, new_key;
  199049. png_byte cbuf[2];
  199050. compression_state comp;
  199051. png_debug(1, "in png_write_iTXt\n");
  199052. comp.num_output_ptr = 0;
  199053. comp.max_output_ptr = 0;
  199054. comp.output_ptr = NULL;
  199055. comp.input = NULL;
  199056. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  199057. {
  199058. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  199059. return;
  199060. }
  199061. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  199062. {
  199063. png_warning(png_ptr, "Empty language field in iTXt chunk");
  199064. new_lang = NULL;
  199065. lang_len = 0;
  199066. }
  199067. if (lang_key == NULL)
  199068. lang_key_len = 0;
  199069. else
  199070. lang_key_len = png_strlen(lang_key);
  199071. if (text == NULL)
  199072. text_len = 0;
  199073. else
  199074. text_len = png_strlen(text);
  199075. /* compute the compressed data; do it now for the length */
  199076. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  199077. &comp);
  199078. /* make sure we include the compression flag, the compression byte,
  199079. * and the NULs after the key, lang, and lang_key parts */
  199080. png_write_chunk_start(png_ptr, png_iTXt,
  199081. (png_uint_32)(
  199082. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  199083. + key_len
  199084. + lang_len
  199085. + lang_key_len
  199086. + text_len));
  199087. /*
  199088. * We leave it to the application to meet PNG-1.0 requirements on the
  199089. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  199090. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  199091. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  199092. */
  199093. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  199094. /* set the compression flag */
  199095. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  199096. compression == PNG_TEXT_COMPRESSION_NONE)
  199097. cbuf[0] = 0;
  199098. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  199099. cbuf[0] = 1;
  199100. /* set the compression method */
  199101. cbuf[1] = 0;
  199102. png_write_chunk_data(png_ptr, cbuf, 2);
  199103. cbuf[0] = 0;
  199104. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  199105. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  199106. png_write_compressed_data_out(png_ptr, &comp);
  199107. png_write_chunk_end(png_ptr);
  199108. png_free(png_ptr, new_key);
  199109. if (new_lang)
  199110. png_free(png_ptr, new_lang);
  199111. }
  199112. #endif
  199113. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  199114. /* write the oFFs chunk */
  199115. void /* PRIVATE */
  199116. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  199117. int unit_type)
  199118. {
  199119. #ifdef PNG_USE_LOCAL_ARRAYS
  199120. PNG_oFFs;
  199121. #endif
  199122. png_byte buf[9];
  199123. png_debug(1, "in png_write_oFFs\n");
  199124. if (unit_type >= PNG_OFFSET_LAST)
  199125. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  199126. png_save_int_32(buf, x_offset);
  199127. png_save_int_32(buf + 4, y_offset);
  199128. buf[8] = (png_byte)unit_type;
  199129. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  199130. }
  199131. #endif
  199132. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  199133. /* write the pCAL chunk (described in the PNG extensions document) */
  199134. void /* PRIVATE */
  199135. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  199136. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  199137. {
  199138. #ifdef PNG_USE_LOCAL_ARRAYS
  199139. PNG_pCAL;
  199140. #endif
  199141. png_size_t purpose_len, units_len, total_len;
  199142. png_uint_32p params_len;
  199143. png_byte buf[10];
  199144. png_charp new_purpose;
  199145. int i;
  199146. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  199147. if (type >= PNG_EQUATION_LAST)
  199148. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  199149. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  199150. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  199151. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  199152. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  199153. total_len = purpose_len + units_len + 10;
  199154. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  199155. *png_sizeof(png_uint_32)));
  199156. /* Find the length of each parameter, making sure we don't count the
  199157. null terminator for the last parameter. */
  199158. for (i = 0; i < nparams; i++)
  199159. {
  199160. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  199161. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  199162. total_len += (png_size_t)params_len[i];
  199163. }
  199164. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  199165. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  199166. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  199167. png_save_int_32(buf, X0);
  199168. png_save_int_32(buf + 4, X1);
  199169. buf[8] = (png_byte)type;
  199170. buf[9] = (png_byte)nparams;
  199171. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  199172. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  199173. png_free(png_ptr, new_purpose);
  199174. for (i = 0; i < nparams; i++)
  199175. {
  199176. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  199177. (png_size_t)params_len[i]);
  199178. }
  199179. png_free(png_ptr, params_len);
  199180. png_write_chunk_end(png_ptr);
  199181. }
  199182. #endif
  199183. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  199184. /* write the sCAL chunk */
  199185. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  199186. void /* PRIVATE */
  199187. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  199188. {
  199189. #ifdef PNG_USE_LOCAL_ARRAYS
  199190. PNG_sCAL;
  199191. #endif
  199192. char buf[64];
  199193. png_size_t total_len;
  199194. png_debug(1, "in png_write_sCAL\n");
  199195. buf[0] = (char)unit;
  199196. #if defined(_WIN32_WCE)
  199197. /* sprintf() function is not supported on WindowsCE */
  199198. {
  199199. wchar_t wc_buf[32];
  199200. size_t wc_len;
  199201. swprintf(wc_buf, TEXT("%12.12e"), width);
  199202. wc_len = wcslen(wc_buf);
  199203. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  199204. total_len = wc_len + 2;
  199205. swprintf(wc_buf, TEXT("%12.12e"), height);
  199206. wc_len = wcslen(wc_buf);
  199207. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  199208. NULL, NULL);
  199209. total_len += wc_len;
  199210. }
  199211. #else
  199212. png_snprintf(buf + 1, 63, "%12.12e", width);
  199213. total_len = 1 + png_strlen(buf + 1) + 1;
  199214. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  199215. total_len += png_strlen(buf + total_len);
  199216. #endif
  199217. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  199218. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  199219. }
  199220. #else
  199221. #ifdef PNG_FIXED_POINT_SUPPORTED
  199222. void /* PRIVATE */
  199223. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  199224. png_charp height)
  199225. {
  199226. #ifdef PNG_USE_LOCAL_ARRAYS
  199227. PNG_sCAL;
  199228. #endif
  199229. png_byte buf[64];
  199230. png_size_t wlen, hlen, total_len;
  199231. png_debug(1, "in png_write_sCAL_s\n");
  199232. wlen = png_strlen(width);
  199233. hlen = png_strlen(height);
  199234. total_len = wlen + hlen + 2;
  199235. if (total_len > 64)
  199236. {
  199237. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  199238. return;
  199239. }
  199240. buf[0] = (png_byte)unit;
  199241. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  199242. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  199243. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  199244. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  199245. }
  199246. #endif
  199247. #endif
  199248. #endif
  199249. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  199250. /* write the pHYs chunk */
  199251. void /* PRIVATE */
  199252. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  199253. png_uint_32 y_pixels_per_unit,
  199254. int unit_type)
  199255. {
  199256. #ifdef PNG_USE_LOCAL_ARRAYS
  199257. PNG_pHYs;
  199258. #endif
  199259. png_byte buf[9];
  199260. png_debug(1, "in png_write_pHYs\n");
  199261. if (unit_type >= PNG_RESOLUTION_LAST)
  199262. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  199263. png_save_uint_32(buf, x_pixels_per_unit);
  199264. png_save_uint_32(buf + 4, y_pixels_per_unit);
  199265. buf[8] = (png_byte)unit_type;
  199266. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  199267. }
  199268. #endif
  199269. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199270. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  199271. * or png_convert_from_time_t(), or fill in the structure yourself.
  199272. */
  199273. void /* PRIVATE */
  199274. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  199275. {
  199276. #ifdef PNG_USE_LOCAL_ARRAYS
  199277. PNG_tIME;
  199278. #endif
  199279. png_byte buf[7];
  199280. png_debug(1, "in png_write_tIME\n");
  199281. if (mod_time->month > 12 || mod_time->month < 1 ||
  199282. mod_time->day > 31 || mod_time->day < 1 ||
  199283. mod_time->hour > 23 || mod_time->second > 60)
  199284. {
  199285. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  199286. return;
  199287. }
  199288. png_save_uint_16(buf, mod_time->year);
  199289. buf[2] = mod_time->month;
  199290. buf[3] = mod_time->day;
  199291. buf[4] = mod_time->hour;
  199292. buf[5] = mod_time->minute;
  199293. buf[6] = mod_time->second;
  199294. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  199295. }
  199296. #endif
  199297. /* initializes the row writing capability of libpng */
  199298. void /* PRIVATE */
  199299. png_write_start_row(png_structp png_ptr)
  199300. {
  199301. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  199302. #ifdef PNG_USE_LOCAL_ARRAYS
  199303. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  199304. /* start of interlace block */
  199305. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  199306. /* offset to next interlace block */
  199307. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  199308. /* start of interlace block in the y direction */
  199309. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  199310. /* offset to next interlace block in the y direction */
  199311. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  199312. #endif
  199313. #endif
  199314. png_size_t buf_size;
  199315. png_debug(1, "in png_write_start_row\n");
  199316. buf_size = (png_size_t)(PNG_ROWBYTES(
  199317. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  199318. /* set up row buffer */
  199319. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  199320. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  199321. #ifndef PNG_NO_WRITE_FILTERING
  199322. /* set up filtering buffer, if using this filter */
  199323. if (png_ptr->do_filter & PNG_FILTER_SUB)
  199324. {
  199325. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  199326. (png_ptr->rowbytes + 1));
  199327. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  199328. }
  199329. /* We only need to keep the previous row if we are using one of these. */
  199330. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  199331. {
  199332. /* set up previous row buffer */
  199333. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  199334. png_memset(png_ptr->prev_row, 0, buf_size);
  199335. if (png_ptr->do_filter & PNG_FILTER_UP)
  199336. {
  199337. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  199338. (png_ptr->rowbytes + 1));
  199339. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  199340. }
  199341. if (png_ptr->do_filter & PNG_FILTER_AVG)
  199342. {
  199343. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  199344. (png_ptr->rowbytes + 1));
  199345. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  199346. }
  199347. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  199348. {
  199349. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  199350. (png_ptr->rowbytes + 1));
  199351. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  199352. }
  199353. #endif /* PNG_NO_WRITE_FILTERING */
  199354. }
  199355. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  199356. /* if interlaced, we need to set up width and height of pass */
  199357. if (png_ptr->interlaced)
  199358. {
  199359. if (!(png_ptr->transformations & PNG_INTERLACE))
  199360. {
  199361. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  199362. png_pass_ystart[0]) / png_pass_yinc[0];
  199363. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  199364. png_pass_start[0]) / png_pass_inc[0];
  199365. }
  199366. else
  199367. {
  199368. png_ptr->num_rows = png_ptr->height;
  199369. png_ptr->usr_width = png_ptr->width;
  199370. }
  199371. }
  199372. else
  199373. #endif
  199374. {
  199375. png_ptr->num_rows = png_ptr->height;
  199376. png_ptr->usr_width = png_ptr->width;
  199377. }
  199378. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199379. png_ptr->zstream.next_out = png_ptr->zbuf;
  199380. }
  199381. /* Internal use only. Called when finished processing a row of data. */
  199382. void /* PRIVATE */
  199383. png_write_finish_row(png_structp png_ptr)
  199384. {
  199385. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  199386. #ifdef PNG_USE_LOCAL_ARRAYS
  199387. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  199388. /* start of interlace block */
  199389. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  199390. /* offset to next interlace block */
  199391. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  199392. /* start of interlace block in the y direction */
  199393. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  199394. /* offset to next interlace block in the y direction */
  199395. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  199396. #endif
  199397. #endif
  199398. int ret;
  199399. png_debug(1, "in png_write_finish_row\n");
  199400. /* next row */
  199401. png_ptr->row_number++;
  199402. /* see if we are done */
  199403. if (png_ptr->row_number < png_ptr->num_rows)
  199404. return;
  199405. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  199406. /* if interlaced, go to next pass */
  199407. if (png_ptr->interlaced)
  199408. {
  199409. png_ptr->row_number = 0;
  199410. if (png_ptr->transformations & PNG_INTERLACE)
  199411. {
  199412. png_ptr->pass++;
  199413. }
  199414. else
  199415. {
  199416. /* loop until we find a non-zero width or height pass */
  199417. do
  199418. {
  199419. png_ptr->pass++;
  199420. if (png_ptr->pass >= 7)
  199421. break;
  199422. png_ptr->usr_width = (png_ptr->width +
  199423. png_pass_inc[png_ptr->pass] - 1 -
  199424. png_pass_start[png_ptr->pass]) /
  199425. png_pass_inc[png_ptr->pass];
  199426. png_ptr->num_rows = (png_ptr->height +
  199427. png_pass_yinc[png_ptr->pass] - 1 -
  199428. png_pass_ystart[png_ptr->pass]) /
  199429. png_pass_yinc[png_ptr->pass];
  199430. if (png_ptr->transformations & PNG_INTERLACE)
  199431. break;
  199432. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  199433. }
  199434. /* reset the row above the image for the next pass */
  199435. if (png_ptr->pass < 7)
  199436. {
  199437. if (png_ptr->prev_row != NULL)
  199438. png_memset(png_ptr->prev_row, 0,
  199439. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  199440. png_ptr->usr_bit_depth,png_ptr->width))+1);
  199441. return;
  199442. }
  199443. }
  199444. #endif
  199445. /* if we get here, we've just written the last row, so we need
  199446. to flush the compressor */
  199447. do
  199448. {
  199449. /* tell the compressor we are done */
  199450. ret = deflate(&png_ptr->zstream, Z_FINISH);
  199451. /* check for an error */
  199452. if (ret == Z_OK)
  199453. {
  199454. /* check to see if we need more room */
  199455. if (!(png_ptr->zstream.avail_out))
  199456. {
  199457. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  199458. png_ptr->zstream.next_out = png_ptr->zbuf;
  199459. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199460. }
  199461. }
  199462. else if (ret != Z_STREAM_END)
  199463. {
  199464. if (png_ptr->zstream.msg != NULL)
  199465. png_error(png_ptr, png_ptr->zstream.msg);
  199466. else
  199467. png_error(png_ptr, "zlib error");
  199468. }
  199469. } while (ret != Z_STREAM_END);
  199470. /* write any extra space */
  199471. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  199472. {
  199473. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  199474. png_ptr->zstream.avail_out);
  199475. }
  199476. deflateReset(&png_ptr->zstream);
  199477. png_ptr->zstream.data_type = Z_BINARY;
  199478. }
  199479. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199480. /* Pick out the correct pixels for the interlace pass.
  199481. * The basic idea here is to go through the row with a source
  199482. * pointer and a destination pointer (sp and dp), and copy the
  199483. * correct pixels for the pass. As the row gets compacted,
  199484. * sp will always be >= dp, so we should never overwrite anything.
  199485. * See the default: case for the easiest code to understand.
  199486. */
  199487. void /* PRIVATE */
  199488. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  199489. {
  199490. #ifdef PNG_USE_LOCAL_ARRAYS
  199491. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  199492. /* start of interlace block */
  199493. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  199494. /* offset to next interlace block */
  199495. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  199496. #endif
  199497. png_debug(1, "in png_do_write_interlace\n");
  199498. /* we don't have to do anything on the last pass (6) */
  199499. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199500. if (row != NULL && row_info != NULL && pass < 6)
  199501. #else
  199502. if (pass < 6)
  199503. #endif
  199504. {
  199505. /* each pixel depth is handled separately */
  199506. switch (row_info->pixel_depth)
  199507. {
  199508. case 1:
  199509. {
  199510. png_bytep sp;
  199511. png_bytep dp;
  199512. int shift;
  199513. int d;
  199514. int value;
  199515. png_uint_32 i;
  199516. png_uint_32 row_width = row_info->width;
  199517. dp = row;
  199518. d = 0;
  199519. shift = 7;
  199520. for (i = png_pass_start[pass]; i < row_width;
  199521. i += png_pass_inc[pass])
  199522. {
  199523. sp = row + (png_size_t)(i >> 3);
  199524. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  199525. d |= (value << shift);
  199526. if (shift == 0)
  199527. {
  199528. shift = 7;
  199529. *dp++ = (png_byte)d;
  199530. d = 0;
  199531. }
  199532. else
  199533. shift--;
  199534. }
  199535. if (shift != 7)
  199536. *dp = (png_byte)d;
  199537. break;
  199538. }
  199539. case 2:
  199540. {
  199541. png_bytep sp;
  199542. png_bytep dp;
  199543. int shift;
  199544. int d;
  199545. int value;
  199546. png_uint_32 i;
  199547. png_uint_32 row_width = row_info->width;
  199548. dp = row;
  199549. shift = 6;
  199550. d = 0;
  199551. for (i = png_pass_start[pass]; i < row_width;
  199552. i += png_pass_inc[pass])
  199553. {
  199554. sp = row + (png_size_t)(i >> 2);
  199555. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  199556. d |= (value << shift);
  199557. if (shift == 0)
  199558. {
  199559. shift = 6;
  199560. *dp++ = (png_byte)d;
  199561. d = 0;
  199562. }
  199563. else
  199564. shift -= 2;
  199565. }
  199566. if (shift != 6)
  199567. *dp = (png_byte)d;
  199568. break;
  199569. }
  199570. case 4:
  199571. {
  199572. png_bytep sp;
  199573. png_bytep dp;
  199574. int shift;
  199575. int d;
  199576. int value;
  199577. png_uint_32 i;
  199578. png_uint_32 row_width = row_info->width;
  199579. dp = row;
  199580. shift = 4;
  199581. d = 0;
  199582. for (i = png_pass_start[pass]; i < row_width;
  199583. i += png_pass_inc[pass])
  199584. {
  199585. sp = row + (png_size_t)(i >> 1);
  199586. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  199587. d |= (value << shift);
  199588. if (shift == 0)
  199589. {
  199590. shift = 4;
  199591. *dp++ = (png_byte)d;
  199592. d = 0;
  199593. }
  199594. else
  199595. shift -= 4;
  199596. }
  199597. if (shift != 4)
  199598. *dp = (png_byte)d;
  199599. break;
  199600. }
  199601. default:
  199602. {
  199603. png_bytep sp;
  199604. png_bytep dp;
  199605. png_uint_32 i;
  199606. png_uint_32 row_width = row_info->width;
  199607. png_size_t pixel_bytes;
  199608. /* start at the beginning */
  199609. dp = row;
  199610. /* find out how many bytes each pixel takes up */
  199611. pixel_bytes = (row_info->pixel_depth >> 3);
  199612. /* loop through the row, only looking at the pixels that
  199613. matter */
  199614. for (i = png_pass_start[pass]; i < row_width;
  199615. i += png_pass_inc[pass])
  199616. {
  199617. /* find out where the original pixel is */
  199618. sp = row + (png_size_t)i * pixel_bytes;
  199619. /* move the pixel */
  199620. if (dp != sp)
  199621. png_memcpy(dp, sp, pixel_bytes);
  199622. /* next pixel */
  199623. dp += pixel_bytes;
  199624. }
  199625. break;
  199626. }
  199627. }
  199628. /* set new row width */
  199629. row_info->width = (row_info->width +
  199630. png_pass_inc[pass] - 1 -
  199631. png_pass_start[pass]) /
  199632. png_pass_inc[pass];
  199633. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  199634. row_info->width);
  199635. }
  199636. }
  199637. #endif
  199638. /* This filters the row, chooses which filter to use, if it has not already
  199639. * been specified by the application, and then writes the row out with the
  199640. * chosen filter.
  199641. */
  199642. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  199643. #define PNG_HISHIFT 10
  199644. #define PNG_LOMASK ((png_uint_32)0xffffL)
  199645. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  199646. void /* PRIVATE */
  199647. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  199648. {
  199649. png_bytep best_row;
  199650. #ifndef PNG_NO_WRITE_FILTER
  199651. png_bytep prev_row, row_buf;
  199652. png_uint_32 mins, bpp;
  199653. png_byte filter_to_do = png_ptr->do_filter;
  199654. png_uint_32 row_bytes = row_info->rowbytes;
  199655. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199656. int num_p_filters = (int)png_ptr->num_prev_filters;
  199657. #endif
  199658. png_debug(1, "in png_write_find_filter\n");
  199659. /* find out how many bytes offset each pixel is */
  199660. bpp = (row_info->pixel_depth + 7) >> 3;
  199661. prev_row = png_ptr->prev_row;
  199662. #endif
  199663. best_row = png_ptr->row_buf;
  199664. #ifndef PNG_NO_WRITE_FILTER
  199665. row_buf = best_row;
  199666. mins = PNG_MAXSUM;
  199667. /* The prediction method we use is to find which method provides the
  199668. * smallest value when summing the absolute values of the distances
  199669. * from zero, using anything >= 128 as negative numbers. This is known
  199670. * as the "minimum sum of absolute differences" heuristic. Other
  199671. * heuristics are the "weighted minimum sum of absolute differences"
  199672. * (experimental and can in theory improve compression), and the "zlib
  199673. * predictive" method (not implemented yet), which does test compressions
  199674. * of lines using different filter methods, and then chooses the
  199675. * (series of) filter(s) that give minimum compressed data size (VERY
  199676. * computationally expensive).
  199677. *
  199678. * GRR 980525: consider also
  199679. * (1) minimum sum of absolute differences from running average (i.e.,
  199680. * keep running sum of non-absolute differences & count of bytes)
  199681. * [track dispersion, too? restart average if dispersion too large?]
  199682. * (1b) minimum sum of absolute differences from sliding average, probably
  199683. * with window size <= deflate window (usually 32K)
  199684. * (2) minimum sum of squared differences from zero or running average
  199685. * (i.e., ~ root-mean-square approach)
  199686. */
  199687. /* We don't need to test the 'no filter' case if this is the only filter
  199688. * that has been chosen, as it doesn't actually do anything to the data.
  199689. */
  199690. if ((filter_to_do & PNG_FILTER_NONE) &&
  199691. filter_to_do != PNG_FILTER_NONE)
  199692. {
  199693. png_bytep rp;
  199694. png_uint_32 sum = 0;
  199695. png_uint_32 i;
  199696. int v;
  199697. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  199698. {
  199699. v = *rp;
  199700. sum += (v < 128) ? v : 256 - v;
  199701. }
  199702. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199703. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199704. {
  199705. png_uint_32 sumhi, sumlo;
  199706. int j;
  199707. sumlo = sum & PNG_LOMASK;
  199708. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  199709. /* Reduce the sum if we match any of the previous rows */
  199710. for (j = 0; j < num_p_filters; j++)
  199711. {
  199712. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  199713. {
  199714. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  199715. PNG_WEIGHT_SHIFT;
  199716. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  199717. PNG_WEIGHT_SHIFT;
  199718. }
  199719. }
  199720. /* Factor in the cost of this filter (this is here for completeness,
  199721. * but it makes no sense to have a "cost" for the NONE filter, as
  199722. * it has the minimum possible computational cost - none).
  199723. */
  199724. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  199725. PNG_COST_SHIFT;
  199726. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  199727. PNG_COST_SHIFT;
  199728. if (sumhi > PNG_HIMASK)
  199729. sum = PNG_MAXSUM;
  199730. else
  199731. sum = (sumhi << PNG_HISHIFT) + sumlo;
  199732. }
  199733. #endif
  199734. mins = sum;
  199735. }
  199736. /* sub filter */
  199737. if (filter_to_do == PNG_FILTER_SUB)
  199738. /* it's the only filter so no testing is needed */
  199739. {
  199740. png_bytep rp, lp, dp;
  199741. png_uint_32 i;
  199742. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  199743. i++, rp++, dp++)
  199744. {
  199745. *dp = *rp;
  199746. }
  199747. for (lp = row_buf + 1; i < row_bytes;
  199748. i++, rp++, lp++, dp++)
  199749. {
  199750. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  199751. }
  199752. best_row = png_ptr->sub_row;
  199753. }
  199754. else if (filter_to_do & PNG_FILTER_SUB)
  199755. {
  199756. png_bytep rp, dp, lp;
  199757. png_uint_32 sum = 0, lmins = mins;
  199758. png_uint_32 i;
  199759. int v;
  199760. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199761. /* We temporarily increase the "minimum sum" by the factor we
  199762. * would reduce the sum of this filter, so that we can do the
  199763. * early exit comparison without scaling the sum each time.
  199764. */
  199765. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199766. {
  199767. int j;
  199768. png_uint_32 lmhi, lmlo;
  199769. lmlo = lmins & PNG_LOMASK;
  199770. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  199771. for (j = 0; j < num_p_filters; j++)
  199772. {
  199773. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  199774. {
  199775. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  199776. PNG_WEIGHT_SHIFT;
  199777. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  199778. PNG_WEIGHT_SHIFT;
  199779. }
  199780. }
  199781. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  199782. PNG_COST_SHIFT;
  199783. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  199784. PNG_COST_SHIFT;
  199785. if (lmhi > PNG_HIMASK)
  199786. lmins = PNG_MAXSUM;
  199787. else
  199788. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  199789. }
  199790. #endif
  199791. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  199792. i++, rp++, dp++)
  199793. {
  199794. v = *dp = *rp;
  199795. sum += (v < 128) ? v : 256 - v;
  199796. }
  199797. for (lp = row_buf + 1; i < row_bytes;
  199798. i++, rp++, lp++, dp++)
  199799. {
  199800. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  199801. sum += (v < 128) ? v : 256 - v;
  199802. if (sum > lmins) /* We are already worse, don't continue. */
  199803. break;
  199804. }
  199805. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199806. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199807. {
  199808. int j;
  199809. png_uint_32 sumhi, sumlo;
  199810. sumlo = sum & PNG_LOMASK;
  199811. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  199812. for (j = 0; j < num_p_filters; j++)
  199813. {
  199814. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  199815. {
  199816. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  199817. PNG_WEIGHT_SHIFT;
  199818. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  199819. PNG_WEIGHT_SHIFT;
  199820. }
  199821. }
  199822. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  199823. PNG_COST_SHIFT;
  199824. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  199825. PNG_COST_SHIFT;
  199826. if (sumhi > PNG_HIMASK)
  199827. sum = PNG_MAXSUM;
  199828. else
  199829. sum = (sumhi << PNG_HISHIFT) + sumlo;
  199830. }
  199831. #endif
  199832. if (sum < mins)
  199833. {
  199834. mins = sum;
  199835. best_row = png_ptr->sub_row;
  199836. }
  199837. }
  199838. /* up filter */
  199839. if (filter_to_do == PNG_FILTER_UP)
  199840. {
  199841. png_bytep rp, dp, pp;
  199842. png_uint_32 i;
  199843. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  199844. pp = prev_row + 1; i < row_bytes;
  199845. i++, rp++, pp++, dp++)
  199846. {
  199847. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  199848. }
  199849. best_row = png_ptr->up_row;
  199850. }
  199851. else if (filter_to_do & PNG_FILTER_UP)
  199852. {
  199853. png_bytep rp, dp, pp;
  199854. png_uint_32 sum = 0, lmins = mins;
  199855. png_uint_32 i;
  199856. int v;
  199857. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199858. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199859. {
  199860. int j;
  199861. png_uint_32 lmhi, lmlo;
  199862. lmlo = lmins & PNG_LOMASK;
  199863. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  199864. for (j = 0; j < num_p_filters; j++)
  199865. {
  199866. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  199867. {
  199868. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  199869. PNG_WEIGHT_SHIFT;
  199870. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  199871. PNG_WEIGHT_SHIFT;
  199872. }
  199873. }
  199874. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  199875. PNG_COST_SHIFT;
  199876. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  199877. PNG_COST_SHIFT;
  199878. if (lmhi > PNG_HIMASK)
  199879. lmins = PNG_MAXSUM;
  199880. else
  199881. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  199882. }
  199883. #endif
  199884. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  199885. pp = prev_row + 1; i < row_bytes; i++)
  199886. {
  199887. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  199888. sum += (v < 128) ? v : 256 - v;
  199889. if (sum > lmins) /* We are already worse, don't continue. */
  199890. break;
  199891. }
  199892. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199893. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199894. {
  199895. int j;
  199896. png_uint_32 sumhi, sumlo;
  199897. sumlo = sum & PNG_LOMASK;
  199898. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  199899. for (j = 0; j < num_p_filters; j++)
  199900. {
  199901. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  199902. {
  199903. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  199904. PNG_WEIGHT_SHIFT;
  199905. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  199906. PNG_WEIGHT_SHIFT;
  199907. }
  199908. }
  199909. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  199910. PNG_COST_SHIFT;
  199911. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  199912. PNG_COST_SHIFT;
  199913. if (sumhi > PNG_HIMASK)
  199914. sum = PNG_MAXSUM;
  199915. else
  199916. sum = (sumhi << PNG_HISHIFT) + sumlo;
  199917. }
  199918. #endif
  199919. if (sum < mins)
  199920. {
  199921. mins = sum;
  199922. best_row = png_ptr->up_row;
  199923. }
  199924. }
  199925. /* avg filter */
  199926. if (filter_to_do == PNG_FILTER_AVG)
  199927. {
  199928. png_bytep rp, dp, pp, lp;
  199929. png_uint_32 i;
  199930. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  199931. pp = prev_row + 1; i < bpp; i++)
  199932. {
  199933. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  199934. }
  199935. for (lp = row_buf + 1; i < row_bytes; i++)
  199936. {
  199937. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  199938. & 0xff);
  199939. }
  199940. best_row = png_ptr->avg_row;
  199941. }
  199942. else if (filter_to_do & PNG_FILTER_AVG)
  199943. {
  199944. png_bytep rp, dp, pp, lp;
  199945. png_uint_32 sum = 0, lmins = mins;
  199946. png_uint_32 i;
  199947. int v;
  199948. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199949. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199950. {
  199951. int j;
  199952. png_uint_32 lmhi, lmlo;
  199953. lmlo = lmins & PNG_LOMASK;
  199954. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  199955. for (j = 0; j < num_p_filters; j++)
  199956. {
  199957. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  199958. {
  199959. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  199960. PNG_WEIGHT_SHIFT;
  199961. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  199962. PNG_WEIGHT_SHIFT;
  199963. }
  199964. }
  199965. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  199966. PNG_COST_SHIFT;
  199967. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  199968. PNG_COST_SHIFT;
  199969. if (lmhi > PNG_HIMASK)
  199970. lmins = PNG_MAXSUM;
  199971. else
  199972. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  199973. }
  199974. #endif
  199975. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  199976. pp = prev_row + 1; i < bpp; i++)
  199977. {
  199978. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  199979. sum += (v < 128) ? v : 256 - v;
  199980. }
  199981. for (lp = row_buf + 1; i < row_bytes; i++)
  199982. {
  199983. v = *dp++ =
  199984. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  199985. sum += (v < 128) ? v : 256 - v;
  199986. if (sum > lmins) /* We are already worse, don't continue. */
  199987. break;
  199988. }
  199989. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199990. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199991. {
  199992. int j;
  199993. png_uint_32 sumhi, sumlo;
  199994. sumlo = sum & PNG_LOMASK;
  199995. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  199996. for (j = 0; j < num_p_filters; j++)
  199997. {
  199998. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  199999. {
  200000. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  200001. PNG_WEIGHT_SHIFT;
  200002. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  200003. PNG_WEIGHT_SHIFT;
  200004. }
  200005. }
  200006. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  200007. PNG_COST_SHIFT;
  200008. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  200009. PNG_COST_SHIFT;
  200010. if (sumhi > PNG_HIMASK)
  200011. sum = PNG_MAXSUM;
  200012. else
  200013. sum = (sumhi << PNG_HISHIFT) + sumlo;
  200014. }
  200015. #endif
  200016. if (sum < mins)
  200017. {
  200018. mins = sum;
  200019. best_row = png_ptr->avg_row;
  200020. }
  200021. }
  200022. /* Paeth filter */
  200023. if (filter_to_do == PNG_FILTER_PAETH)
  200024. {
  200025. png_bytep rp, dp, pp, cp, lp;
  200026. png_uint_32 i;
  200027. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  200028. pp = prev_row + 1; i < bpp; i++)
  200029. {
  200030. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  200031. }
  200032. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  200033. {
  200034. int a, b, c, pa, pb, pc, p;
  200035. b = *pp++;
  200036. c = *cp++;
  200037. a = *lp++;
  200038. p = b - c;
  200039. pc = a - c;
  200040. #ifdef PNG_USE_ABS
  200041. pa = abs(p);
  200042. pb = abs(pc);
  200043. pc = abs(p + pc);
  200044. #else
  200045. pa = p < 0 ? -p : p;
  200046. pb = pc < 0 ? -pc : pc;
  200047. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  200048. #endif
  200049. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  200050. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  200051. }
  200052. best_row = png_ptr->paeth_row;
  200053. }
  200054. else if (filter_to_do & PNG_FILTER_PAETH)
  200055. {
  200056. png_bytep rp, dp, pp, cp, lp;
  200057. png_uint_32 sum = 0, lmins = mins;
  200058. png_uint_32 i;
  200059. int v;
  200060. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  200061. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  200062. {
  200063. int j;
  200064. png_uint_32 lmhi, lmlo;
  200065. lmlo = lmins & PNG_LOMASK;
  200066. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  200067. for (j = 0; j < num_p_filters; j++)
  200068. {
  200069. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  200070. {
  200071. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  200072. PNG_WEIGHT_SHIFT;
  200073. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  200074. PNG_WEIGHT_SHIFT;
  200075. }
  200076. }
  200077. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  200078. PNG_COST_SHIFT;
  200079. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  200080. PNG_COST_SHIFT;
  200081. if (lmhi > PNG_HIMASK)
  200082. lmins = PNG_MAXSUM;
  200083. else
  200084. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  200085. }
  200086. #endif
  200087. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  200088. pp = prev_row + 1; i < bpp; i++)
  200089. {
  200090. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  200091. sum += (v < 128) ? v : 256 - v;
  200092. }
  200093. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  200094. {
  200095. int a, b, c, pa, pb, pc, p;
  200096. b = *pp++;
  200097. c = *cp++;
  200098. a = *lp++;
  200099. #ifndef PNG_SLOW_PAETH
  200100. p = b - c;
  200101. pc = a - c;
  200102. #ifdef PNG_USE_ABS
  200103. pa = abs(p);
  200104. pb = abs(pc);
  200105. pc = abs(p + pc);
  200106. #else
  200107. pa = p < 0 ? -p : p;
  200108. pb = pc < 0 ? -pc : pc;
  200109. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  200110. #endif
  200111. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  200112. #else /* PNG_SLOW_PAETH */
  200113. p = a + b - c;
  200114. pa = abs(p - a);
  200115. pb = abs(p - b);
  200116. pc = abs(p - c);
  200117. if (pa <= pb && pa <= pc)
  200118. p = a;
  200119. else if (pb <= pc)
  200120. p = b;
  200121. else
  200122. p = c;
  200123. #endif /* PNG_SLOW_PAETH */
  200124. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  200125. sum += (v < 128) ? v : 256 - v;
  200126. if (sum > lmins) /* We are already worse, don't continue. */
  200127. break;
  200128. }
  200129. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  200130. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  200131. {
  200132. int j;
  200133. png_uint_32 sumhi, sumlo;
  200134. sumlo = sum & PNG_LOMASK;
  200135. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  200136. for (j = 0; j < num_p_filters; j++)
  200137. {
  200138. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  200139. {
  200140. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  200141. PNG_WEIGHT_SHIFT;
  200142. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  200143. PNG_WEIGHT_SHIFT;
  200144. }
  200145. }
  200146. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  200147. PNG_COST_SHIFT;
  200148. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  200149. PNG_COST_SHIFT;
  200150. if (sumhi > PNG_HIMASK)
  200151. sum = PNG_MAXSUM;
  200152. else
  200153. sum = (sumhi << PNG_HISHIFT) + sumlo;
  200154. }
  200155. #endif
  200156. if (sum < mins)
  200157. {
  200158. best_row = png_ptr->paeth_row;
  200159. }
  200160. }
  200161. #endif /* PNG_NO_WRITE_FILTER */
  200162. /* Do the actual writing of the filtered row data from the chosen filter. */
  200163. png_write_filtered_row(png_ptr, best_row);
  200164. #ifndef PNG_NO_WRITE_FILTER
  200165. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  200166. /* Save the type of filter we picked this time for future calculations */
  200167. if (png_ptr->num_prev_filters > 0)
  200168. {
  200169. int j;
  200170. for (j = 1; j < num_p_filters; j++)
  200171. {
  200172. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  200173. }
  200174. png_ptr->prev_filters[j] = best_row[0];
  200175. }
  200176. #endif
  200177. #endif /* PNG_NO_WRITE_FILTER */
  200178. }
  200179. /* Do the actual writing of a previously filtered row. */
  200180. void /* PRIVATE */
  200181. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  200182. {
  200183. png_debug(1, "in png_write_filtered_row\n");
  200184. png_debug1(2, "filter = %d\n", filtered_row[0]);
  200185. /* set up the zlib input buffer */
  200186. png_ptr->zstream.next_in = filtered_row;
  200187. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  200188. /* repeat until we have compressed all the data */
  200189. do
  200190. {
  200191. int ret; /* return of zlib */
  200192. /* compress the data */
  200193. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  200194. /* check for compression errors */
  200195. if (ret != Z_OK)
  200196. {
  200197. if (png_ptr->zstream.msg != NULL)
  200198. png_error(png_ptr, png_ptr->zstream.msg);
  200199. else
  200200. png_error(png_ptr, "zlib error");
  200201. }
  200202. /* see if it is time to write another IDAT */
  200203. if (!(png_ptr->zstream.avail_out))
  200204. {
  200205. /* write the IDAT and reset the zlib output buffer */
  200206. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  200207. png_ptr->zstream.next_out = png_ptr->zbuf;
  200208. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200209. }
  200210. /* repeat until all data has been compressed */
  200211. } while (png_ptr->zstream.avail_in);
  200212. /* swap the current and previous rows */
  200213. if (png_ptr->prev_row != NULL)
  200214. {
  200215. png_bytep tptr;
  200216. tptr = png_ptr->prev_row;
  200217. png_ptr->prev_row = png_ptr->row_buf;
  200218. png_ptr->row_buf = tptr;
  200219. }
  200220. /* finish row - updates counters and flushes zlib if last row */
  200221. png_write_finish_row(png_ptr);
  200222. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  200223. png_ptr->flush_rows++;
  200224. if (png_ptr->flush_dist > 0 &&
  200225. png_ptr->flush_rows >= png_ptr->flush_dist)
  200226. {
  200227. png_write_flush(png_ptr);
  200228. }
  200229. #endif
  200230. }
  200231. #endif /* PNG_WRITE_SUPPORTED */
  200232. /*** End of inlined file: pngwutil.c ***/
  200233. }
  200234. #else
  200235. extern "C"
  200236. {
  200237. #include <png.h>
  200238. #include <pngconf.h>
  200239. }
  200240. #endif
  200241. }
  200242. #undef max
  200243. #undef min
  200244. #if JUCE_MSVC
  200245. #pragma warning (pop)
  200246. #endif
  200247. BEGIN_JUCE_NAMESPACE
  200248. using ::calloc;
  200249. using ::malloc;
  200250. using ::free;
  200251. namespace PNGHelpers
  200252. {
  200253. using namespace pnglibNamespace;
  200254. static void readCallback (png_structp png, png_bytep data, png_size_t length)
  200255. {
  200256. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  200257. }
  200258. static void writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  200259. {
  200260. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  200261. }
  200262. struct PNGErrorStruct {};
  200263. static void errorCallback (png_structp, png_const_charp)
  200264. {
  200265. throw PNGErrorStruct();
  200266. }
  200267. }
  200268. PNGImageFormat::PNGImageFormat() {}
  200269. PNGImageFormat::~PNGImageFormat() {}
  200270. const String PNGImageFormat::getFormatName()
  200271. {
  200272. return "PNG";
  200273. }
  200274. bool PNGImageFormat::canUnderstand (InputStream& in)
  200275. {
  200276. const int bytesNeeded = 4;
  200277. char header [bytesNeeded];
  200278. return in.read (header, bytesNeeded) == bytesNeeded
  200279. && header[1] == 'P'
  200280. && header[2] == 'N'
  200281. && header[3] == 'G';
  200282. }
  200283. Image* PNGImageFormat::decodeImage (InputStream& in)
  200284. {
  200285. using namespace pnglibNamespace;
  200286. Image* image = 0;
  200287. png_structp pngReadStruct;
  200288. png_infop pngInfoStruct;
  200289. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  200290. if (pngReadStruct != 0)
  200291. {
  200292. pngInfoStruct = png_create_info_struct (pngReadStruct);
  200293. if (pngInfoStruct == 0)
  200294. {
  200295. png_destroy_read_struct (&pngReadStruct, 0, 0);
  200296. return 0;
  200297. }
  200298. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  200299. // read the header..
  200300. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  200301. png_uint_32 width, height;
  200302. int bitDepth, colorType, interlaceType;
  200303. png_read_info (pngReadStruct, pngInfoStruct);
  200304. png_get_IHDR (pngReadStruct, pngInfoStruct,
  200305. &width, &height,
  200306. &bitDepth, &colorType,
  200307. &interlaceType, 0, 0);
  200308. if (bitDepth == 16)
  200309. png_set_strip_16 (pngReadStruct);
  200310. if (colorType == PNG_COLOR_TYPE_PALETTE)
  200311. png_set_expand (pngReadStruct);
  200312. if (bitDepth < 8)
  200313. png_set_expand (pngReadStruct);
  200314. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  200315. png_set_expand (pngReadStruct);
  200316. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  200317. png_set_gray_to_rgb (pngReadStruct);
  200318. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  200319. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  200320. || pngInfoStruct->num_trans > 0;
  200321. // Load the image into a temp buffer in the pnglib format..
  200322. HeapBlock <uint8> tempBuffer (height * (width << 2));
  200323. {
  200324. HeapBlock <png_bytep> rows (height);
  200325. for (int y = (int) height; --y >= 0;)
  200326. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  200327. png_read_image (pngReadStruct, rows);
  200328. png_read_end (pngReadStruct, pngInfoStruct);
  200329. }
  200330. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  200331. // now convert the data to a juce image format..
  200332. image = Image::createNativeImage (hasAlphaChan ? Image::ARGB : Image::RGB,
  200333. (int) width, (int) height, hasAlphaChan);
  200334. hasAlphaChan = image->hasAlphaChannel(); // (the native image creator may not give back what we expect)
  200335. const Image::BitmapData destData (*image, 0, 0, (int) width, (int) height, true);
  200336. uint8* srcRow = tempBuffer;
  200337. uint8* destRow = destData.data;
  200338. for (int y = 0; y < (int) height; ++y)
  200339. {
  200340. const uint8* src = srcRow;
  200341. srcRow += (width << 2);
  200342. uint8* dest = destRow;
  200343. destRow += destData.lineStride;
  200344. if (hasAlphaChan)
  200345. {
  200346. for (int i = (int) width; --i >= 0;)
  200347. {
  200348. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  200349. ((PixelARGB*) dest)->premultiply();
  200350. dest += destData.pixelStride;
  200351. src += 4;
  200352. }
  200353. }
  200354. else
  200355. {
  200356. for (int i = (int) width; --i >= 0;)
  200357. {
  200358. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  200359. dest += destData.pixelStride;
  200360. src += 4;
  200361. }
  200362. }
  200363. }
  200364. }
  200365. return image;
  200366. }
  200367. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  200368. {
  200369. using namespace pnglibNamespace;
  200370. const int width = image.getWidth();
  200371. const int height = image.getHeight();
  200372. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  200373. if (pngWriteStruct == 0)
  200374. return false;
  200375. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  200376. if (pngInfoStruct == 0)
  200377. {
  200378. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  200379. return false;
  200380. }
  200381. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  200382. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  200383. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  200384. : PNG_COLOR_TYPE_RGB,
  200385. PNG_INTERLACE_NONE,
  200386. PNG_COMPRESSION_TYPE_BASE,
  200387. PNG_FILTER_TYPE_BASE);
  200388. HeapBlock <uint8> rowData (width * 4);
  200389. png_color_8 sig_bit;
  200390. sig_bit.red = 8;
  200391. sig_bit.green = 8;
  200392. sig_bit.blue = 8;
  200393. sig_bit.alpha = 8;
  200394. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  200395. png_write_info (pngWriteStruct, pngInfoStruct);
  200396. png_set_shift (pngWriteStruct, &sig_bit);
  200397. png_set_packing (pngWriteStruct);
  200398. const Image::BitmapData srcData (image, 0, 0, width, height);
  200399. for (int y = 0; y < height; ++y)
  200400. {
  200401. uint8* dst = rowData;
  200402. const uint8* src = srcData.getLinePointer (y);
  200403. if (image.hasAlphaChannel())
  200404. {
  200405. for (int i = width; --i >= 0;)
  200406. {
  200407. PixelARGB p (*(const PixelARGB*) src);
  200408. p.unpremultiply();
  200409. *dst++ = p.getRed();
  200410. *dst++ = p.getGreen();
  200411. *dst++ = p.getBlue();
  200412. *dst++ = p.getAlpha();
  200413. src += srcData.pixelStride;
  200414. }
  200415. }
  200416. else
  200417. {
  200418. for (int i = width; --i >= 0;)
  200419. {
  200420. *dst++ = ((const PixelRGB*) src)->getRed();
  200421. *dst++ = ((const PixelRGB*) src)->getGreen();
  200422. *dst++ = ((const PixelRGB*) src)->getBlue();
  200423. src += srcData.pixelStride;
  200424. }
  200425. }
  200426. png_write_rows (pngWriteStruct, &rowData, 1);
  200427. }
  200428. png_write_end (pngWriteStruct, pngInfoStruct);
  200429. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  200430. out.flush();
  200431. return true;
  200432. }
  200433. END_JUCE_NAMESPACE
  200434. /*** End of inlined file: juce_PNGLoader.cpp ***/
  200435. #endif
  200436. //==============================================================================
  200437. #if JUCE_BUILD_NATIVE
  200438. #if JUCE_WINDOWS
  200439. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  200440. /*
  200441. This file wraps together all the win32-specific code, so that
  200442. we can include all the native headers just once, and compile all our
  200443. platform-specific stuff in one big lump, keeping it out of the way of
  200444. the rest of the codebase.
  200445. */
  200446. #if JUCE_WINDOWS
  200447. BEGIN_JUCE_NAMESPACE
  200448. #define JUCE_INCLUDED_FILE 1
  200449. // Now include the actual code files..
  200450. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  200451. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  200452. // compiled on its own).
  200453. #if JUCE_INCLUDED_FILE
  200454. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  200455. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  200456. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  200457. #ifndef DOXYGEN
  200458. // use with DynamicLibraryLoader to simplify importing functions
  200459. //
  200460. // functionName: function to import
  200461. // localFunctionName: name you want to use to actually call it (must be different)
  200462. // returnType: the return type
  200463. // object: the DynamicLibraryLoader to use
  200464. // params: list of params (bracketed)
  200465. //
  200466. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  200467. typedef returnType (WINAPI *type##localFunctionName) params; \
  200468. type##localFunctionName localFunctionName \
  200469. = (type##localFunctionName)object.findProcAddress (#functionName);
  200470. // loads and unloads a DLL automatically
  200471. class JUCE_API DynamicLibraryLoader
  200472. {
  200473. public:
  200474. DynamicLibraryLoader (const String& name);
  200475. ~DynamicLibraryLoader();
  200476. void* findProcAddress (const String& functionName);
  200477. private:
  200478. void* libHandle;
  200479. };
  200480. #endif
  200481. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  200482. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  200483. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  200484. {
  200485. libHandle = LoadLibrary (name);
  200486. }
  200487. DynamicLibraryLoader::~DynamicLibraryLoader()
  200488. {
  200489. FreeLibrary ((HMODULE) libHandle);
  200490. }
  200491. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  200492. {
  200493. return GetProcAddress ((HMODULE) libHandle, functionName.toCString());
  200494. }
  200495. #endif
  200496. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  200497. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  200498. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  200499. // compiled on its own).
  200500. #if JUCE_INCLUDED_FILE
  200501. extern void juce_initialiseThreadEvents();
  200502. void Logger::outputDebugString (const String& text)
  200503. {
  200504. OutputDebugString (text + "\n");
  200505. }
  200506. static int64 hiResTicksPerSecond;
  200507. static double hiResTicksScaleFactor;
  200508. #if JUCE_USE_INTRINSICS
  200509. // CPU info functions using intrinsics...
  200510. #pragma intrinsic (__cpuid)
  200511. #pragma intrinsic (__rdtsc)
  200512. const String SystemStats::getCpuVendor()
  200513. {
  200514. int info [4];
  200515. __cpuid (info, 0);
  200516. char v [12];
  200517. memcpy (v, info + 1, 4);
  200518. memcpy (v + 4, info + 3, 4);
  200519. memcpy (v + 8, info + 2, 4);
  200520. return String (v, 12);
  200521. }
  200522. #else
  200523. // CPU info functions using old fashioned inline asm...
  200524. static void juce_getCpuVendor (char* const v)
  200525. {
  200526. int vendor[4];
  200527. zeromem (vendor, 16);
  200528. #ifdef JUCE_64BIT
  200529. #else
  200530. #ifndef __MINGW32__
  200531. __try
  200532. #endif
  200533. {
  200534. #if JUCE_GCC
  200535. unsigned int dummy = 0;
  200536. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  200537. #else
  200538. __asm
  200539. {
  200540. mov eax, 0
  200541. cpuid
  200542. mov [vendor], ebx
  200543. mov [vendor + 4], edx
  200544. mov [vendor + 8], ecx
  200545. }
  200546. #endif
  200547. }
  200548. #ifndef __MINGW32__
  200549. __except (EXCEPTION_EXECUTE_HANDLER)
  200550. {
  200551. *v = 0;
  200552. }
  200553. #endif
  200554. #endif
  200555. memcpy (v, vendor, 16);
  200556. }
  200557. const String SystemStats::getCpuVendor()
  200558. {
  200559. char v [16];
  200560. juce_getCpuVendor (v);
  200561. return String (v, 16);
  200562. }
  200563. #endif
  200564. struct CPUFlags
  200565. {
  200566. bool hasMMX : 1;
  200567. bool hasSSE : 1;
  200568. bool hasSSE2 : 1;
  200569. bool has3DNow : 1;
  200570. };
  200571. static CPUFlags cpuFlags;
  200572. bool SystemStats::hasMMX()
  200573. {
  200574. return cpuFlags.hasMMX;
  200575. }
  200576. bool SystemStats::hasSSE()
  200577. {
  200578. return cpuFlags.hasSSE;
  200579. }
  200580. bool SystemStats::hasSSE2()
  200581. {
  200582. return cpuFlags.hasSSE2;
  200583. }
  200584. bool SystemStats::has3DNow()
  200585. {
  200586. return cpuFlags.has3DNow;
  200587. }
  200588. void SystemStats::initialiseStats()
  200589. {
  200590. juce_initialiseThreadEvents();
  200591. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  200592. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  200593. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  200594. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  200595. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  200596. #else
  200597. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  200598. #endif
  200599. LARGE_INTEGER f;
  200600. QueryPerformanceFrequency (&f);
  200601. hiResTicksPerSecond = f.QuadPart;
  200602. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  200603. String s (SystemStats::getJUCEVersion());
  200604. #if JUCE_DEBUG
  200605. const MMRESULT res = timeBeginPeriod (1);
  200606. jassert (res == TIMERR_NOERROR);
  200607. #else
  200608. timeBeginPeriod (1);
  200609. #endif
  200610. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  200611. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  200612. #endif
  200613. }
  200614. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  200615. {
  200616. OSVERSIONINFO info;
  200617. info.dwOSVersionInfoSize = sizeof (info);
  200618. GetVersionEx (&info);
  200619. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  200620. {
  200621. switch (info.dwMajorVersion)
  200622. {
  200623. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  200624. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  200625. default: jassertfalse; break; // !! not a supported OS!
  200626. }
  200627. }
  200628. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  200629. {
  200630. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  200631. return Win98;
  200632. }
  200633. return UnknownOS;
  200634. }
  200635. const String SystemStats::getOperatingSystemName()
  200636. {
  200637. const char* name = "Unknown OS";
  200638. switch (getOperatingSystemType())
  200639. {
  200640. case Windows7: name = "Windows 7"; break;
  200641. case WinVista: name = "Windows Vista"; break;
  200642. case WinXP: name = "Windows XP"; break;
  200643. case Win2000: name = "Windows 2000"; break;
  200644. case Win98: name = "Windows 98"; break;
  200645. default: jassertfalse; break; // !! new type of OS?
  200646. }
  200647. return name;
  200648. }
  200649. bool SystemStats::isOperatingSystem64Bit()
  200650. {
  200651. #ifdef _WIN64
  200652. return true;
  200653. #else
  200654. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  200655. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  200656. BOOL isWow64 = FALSE;
  200657. return (fnIsWow64Process != 0)
  200658. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  200659. && (isWow64 != FALSE);
  200660. #endif
  200661. }
  200662. int SystemStats::getMemorySizeInMegabytes()
  200663. {
  200664. MEMORYSTATUSEX mem;
  200665. mem.dwLength = sizeof (mem);
  200666. GlobalMemoryStatusEx (&mem);
  200667. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  200668. }
  200669. int SystemStats::getNumCpus()
  200670. {
  200671. SYSTEM_INFO systemInfo;
  200672. GetSystemInfo (&systemInfo);
  200673. return systemInfo.dwNumberOfProcessors;
  200674. }
  200675. uint32 juce_millisecondsSinceStartup() throw()
  200676. {
  200677. return (uint32) GetTickCount();
  200678. }
  200679. int64 Time::getHighResolutionTicks() throw()
  200680. {
  200681. LARGE_INTEGER ticks;
  200682. QueryPerformanceCounter (&ticks);
  200683. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  200684. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  200685. // fix for a very obscure PCI hardware bug that can make the counter
  200686. // sometimes jump forwards by a few seconds..
  200687. static int64 hiResTicksOffset = 0;
  200688. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  200689. if (offsetDrift > (hiResTicksPerSecond >> 1))
  200690. hiResTicksOffset = newOffset;
  200691. return ticks.QuadPart + hiResTicksOffset;
  200692. }
  200693. double Time::getMillisecondCounterHiRes() throw()
  200694. {
  200695. return getHighResolutionTicks() * hiResTicksScaleFactor;
  200696. }
  200697. int64 Time::getHighResolutionTicksPerSecond() throw()
  200698. {
  200699. return hiResTicksPerSecond;
  200700. }
  200701. static int64 juce_getClockCycleCounter() throw()
  200702. {
  200703. #if JUCE_USE_INTRINSICS
  200704. // MS intrinsics version...
  200705. return __rdtsc();
  200706. #elif JUCE_GCC
  200707. // GNU inline asm version...
  200708. unsigned int hi = 0, lo = 0;
  200709. __asm__ __volatile__ (
  200710. "xor %%eax, %%eax \n\
  200711. xor %%edx, %%edx \n\
  200712. rdtsc \n\
  200713. movl %%eax, %[lo] \n\
  200714. movl %%edx, %[hi]"
  200715. :
  200716. : [hi] "m" (hi),
  200717. [lo] "m" (lo)
  200718. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  200719. return (int64) ((((uint64) hi) << 32) | lo);
  200720. #else
  200721. // MSVC inline asm version...
  200722. unsigned int hi = 0, lo = 0;
  200723. __asm
  200724. {
  200725. xor eax, eax
  200726. xor edx, edx
  200727. rdtsc
  200728. mov lo, eax
  200729. mov hi, edx
  200730. }
  200731. return (int64) ((((uint64) hi) << 32) | lo);
  200732. #endif
  200733. }
  200734. int SystemStats::getCpuSpeedInMegaherz()
  200735. {
  200736. const int64 cycles = juce_getClockCycleCounter();
  200737. const uint32 millis = Time::getMillisecondCounter();
  200738. int lastResult = 0;
  200739. for (;;)
  200740. {
  200741. int n = 1000000;
  200742. while (--n > 0) {}
  200743. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  200744. const int64 cyclesNow = juce_getClockCycleCounter();
  200745. if (millisElapsed > 80)
  200746. {
  200747. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  200748. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  200749. return newResult;
  200750. lastResult = newResult;
  200751. }
  200752. }
  200753. }
  200754. bool Time::setSystemTimeToThisTime() const
  200755. {
  200756. SYSTEMTIME st;
  200757. st.wDayOfWeek = 0;
  200758. st.wYear = (WORD) getYear();
  200759. st.wMonth = (WORD) (getMonth() + 1);
  200760. st.wDay = (WORD) getDayOfMonth();
  200761. st.wHour = (WORD) getHours();
  200762. st.wMinute = (WORD) getMinutes();
  200763. st.wSecond = (WORD) getSeconds();
  200764. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  200765. // do this twice because of daylight saving conversion problems - the
  200766. // first one sets it up, the second one kicks it in.
  200767. return SetLocalTime (&st) != 0
  200768. && SetLocalTime (&st) != 0;
  200769. }
  200770. int SystemStats::getPageSize()
  200771. {
  200772. SYSTEM_INFO systemInfo;
  200773. GetSystemInfo (&systemInfo);
  200774. return systemInfo.dwPageSize;
  200775. }
  200776. const String SystemStats::getLogonName()
  200777. {
  200778. TCHAR text [256];
  200779. DWORD len = numElementsInArray (text) - 2;
  200780. zerostruct (text);
  200781. GetUserName (text, &len);
  200782. return String (text, len);
  200783. }
  200784. const String SystemStats::getFullUserName()
  200785. {
  200786. return getLogonName();
  200787. }
  200788. #endif
  200789. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  200790. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  200791. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  200792. // compiled on its own).
  200793. #if JUCE_INCLUDED_FILE
  200794. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  200795. extern HWND juce_messageWindowHandle;
  200796. #endif
  200797. #if ! JUCE_USE_INTRINSICS
  200798. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  200799. // older ones we have to actually call the ops as win32 functions..
  200800. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  200801. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  200802. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  200803. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  200804. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  200805. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  200806. {
  200807. jassertfalse; // This operation isn't available in old MS compiler versions!
  200808. __int64 oldValue = *value;
  200809. if (oldValue == valueToCompare)
  200810. *value = newValue;
  200811. return oldValue;
  200812. }
  200813. #endif
  200814. CriticalSection::CriticalSection() throw()
  200815. {
  200816. // (just to check the MS haven't changed this structure and broken things...)
  200817. #if _MSC_VER >= 1400
  200818. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  200819. #else
  200820. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  200821. #endif
  200822. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  200823. }
  200824. CriticalSection::~CriticalSection() throw()
  200825. {
  200826. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  200827. }
  200828. void CriticalSection::enter() const throw()
  200829. {
  200830. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  200831. }
  200832. bool CriticalSection::tryEnter() const throw()
  200833. {
  200834. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  200835. }
  200836. void CriticalSection::exit() const throw()
  200837. {
  200838. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  200839. }
  200840. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  200841. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  200842. {
  200843. }
  200844. WaitableEvent::~WaitableEvent() throw()
  200845. {
  200846. CloseHandle (internal);
  200847. }
  200848. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  200849. {
  200850. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  200851. }
  200852. void WaitableEvent::signal() const throw()
  200853. {
  200854. SetEvent (internal);
  200855. }
  200856. void WaitableEvent::reset() const throw()
  200857. {
  200858. ResetEvent (internal);
  200859. }
  200860. void JUCE_API juce_threadEntryPoint (void*);
  200861. static unsigned int __stdcall threadEntryProc (void* userData)
  200862. {
  200863. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  200864. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  200865. GetCurrentThreadId(), TRUE);
  200866. #endif
  200867. juce_threadEntryPoint (userData);
  200868. _endthreadex (0);
  200869. return 0;
  200870. }
  200871. void juce_CloseThreadHandle (void* handle)
  200872. {
  200873. CloseHandle ((HANDLE) handle);
  200874. }
  200875. void* juce_createThread (void* userData)
  200876. {
  200877. unsigned int threadId;
  200878. return (void*) _beginthreadex (0, 0, &threadEntryProc, userData, 0, &threadId);
  200879. }
  200880. void juce_killThread (void* handle)
  200881. {
  200882. if (handle != 0)
  200883. {
  200884. #if JUCE_DEBUG
  200885. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  200886. #endif
  200887. TerminateThread (handle, 0);
  200888. }
  200889. }
  200890. void juce_setCurrentThreadName (const String& name)
  200891. {
  200892. #if JUCE_DEBUG && JUCE_MSVC
  200893. struct
  200894. {
  200895. DWORD dwType;
  200896. LPCSTR szName;
  200897. DWORD dwThreadID;
  200898. DWORD dwFlags;
  200899. } info;
  200900. info.dwType = 0x1000;
  200901. info.szName = name.toCString();
  200902. info.dwThreadID = GetCurrentThreadId();
  200903. info.dwFlags = 0;
  200904. __try
  200905. {
  200906. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  200907. }
  200908. __except (EXCEPTION_CONTINUE_EXECUTION)
  200909. {}
  200910. #else
  200911. (void) name;
  200912. #endif
  200913. }
  200914. Thread::ThreadID Thread::getCurrentThreadId()
  200915. {
  200916. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  200917. }
  200918. // priority 1 to 10 where 5=normal, 1=low
  200919. bool juce_setThreadPriority (void* threadHandle, int priority)
  200920. {
  200921. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  200922. if (priority < 1)
  200923. pri = THREAD_PRIORITY_IDLE;
  200924. else if (priority < 2)
  200925. pri = THREAD_PRIORITY_LOWEST;
  200926. else if (priority < 5)
  200927. pri = THREAD_PRIORITY_BELOW_NORMAL;
  200928. else if (priority < 7)
  200929. pri = THREAD_PRIORITY_NORMAL;
  200930. else if (priority < 9)
  200931. pri = THREAD_PRIORITY_ABOVE_NORMAL;
  200932. else if (priority < 10)
  200933. pri = THREAD_PRIORITY_HIGHEST;
  200934. if (threadHandle == 0)
  200935. threadHandle = GetCurrentThread();
  200936. return SetThreadPriority (threadHandle, pri) != FALSE;
  200937. }
  200938. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  200939. {
  200940. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  200941. }
  200942. static HANDLE sleepEvent = 0;
  200943. void juce_initialiseThreadEvents()
  200944. {
  200945. if (sleepEvent == 0)
  200946. #if JUCE_DEBUG
  200947. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  200948. #else
  200949. sleepEvent = CreateEvent (0, 0, 0, 0);
  200950. #endif
  200951. }
  200952. void Thread::yield()
  200953. {
  200954. Sleep (0);
  200955. }
  200956. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  200957. {
  200958. if (millisecs >= 10)
  200959. {
  200960. Sleep (millisecs);
  200961. }
  200962. else
  200963. {
  200964. jassert (sleepEvent != 0);
  200965. // unlike Sleep() this is guaranteed to return to the current thread after
  200966. // the time expires, so we'll use this for short waits, which are more likely
  200967. // to need to be accurate
  200968. WaitForSingleObject (sleepEvent, millisecs);
  200969. }
  200970. }
  200971. static int lastProcessPriority = -1;
  200972. // called by WindowDriver because Windows does wierd things to process priority
  200973. // when you swap apps, and this forces an update when the app is brought to the front.
  200974. void juce_repeatLastProcessPriority()
  200975. {
  200976. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  200977. {
  200978. DWORD p;
  200979. switch (lastProcessPriority)
  200980. {
  200981. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  200982. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  200983. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  200984. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  200985. default: jassertfalse; return; // bad priority value
  200986. }
  200987. SetPriorityClass (GetCurrentProcess(), p);
  200988. }
  200989. }
  200990. void Process::setPriority (ProcessPriority prior)
  200991. {
  200992. if (lastProcessPriority != (int) prior)
  200993. {
  200994. lastProcessPriority = (int) prior;
  200995. juce_repeatLastProcessPriority();
  200996. }
  200997. }
  200998. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  200999. {
  201000. return IsDebuggerPresent() != FALSE;
  201001. }
  201002. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  201003. {
  201004. return juce_isRunningUnderDebugger();
  201005. }
  201006. void Process::raisePrivilege()
  201007. {
  201008. jassertfalse // xxx not implemented
  201009. }
  201010. void Process::lowerPrivilege()
  201011. {
  201012. jassertfalse // xxx not implemented
  201013. }
  201014. void Process::terminate()
  201015. {
  201016. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  201017. _CrtDumpMemoryLeaks();
  201018. #endif
  201019. // bullet in the head in case there's a problem shutting down..
  201020. ExitProcess (0);
  201021. }
  201022. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  201023. {
  201024. void* result = 0;
  201025. JUCE_TRY
  201026. {
  201027. result = LoadLibrary (name);
  201028. }
  201029. JUCE_CATCH_ALL
  201030. return result;
  201031. }
  201032. void PlatformUtilities::freeDynamicLibrary (void* h)
  201033. {
  201034. JUCE_TRY
  201035. {
  201036. if (h != 0)
  201037. FreeLibrary ((HMODULE) h);
  201038. }
  201039. JUCE_CATCH_ALL
  201040. }
  201041. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  201042. {
  201043. return (h != 0) ? GetProcAddress ((HMODULE) h, name.toCString()) : 0;
  201044. }
  201045. class InterProcessLock::Pimpl
  201046. {
  201047. public:
  201048. Pimpl (const String& name, const int timeOutMillisecs)
  201049. : handle (0), refCount (1)
  201050. {
  201051. handle = CreateMutex (0, TRUE, "Global\\" + name.replaceCharacter ('\\','/'));
  201052. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  201053. {
  201054. if (timeOutMillisecs == 0)
  201055. {
  201056. close();
  201057. return;
  201058. }
  201059. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  201060. {
  201061. case WAIT_OBJECT_0:
  201062. case WAIT_ABANDONED:
  201063. break;
  201064. case WAIT_TIMEOUT:
  201065. default:
  201066. close();
  201067. break;
  201068. }
  201069. }
  201070. }
  201071. ~Pimpl()
  201072. {
  201073. close();
  201074. }
  201075. void close()
  201076. {
  201077. if (handle != 0)
  201078. {
  201079. ReleaseMutex (handle);
  201080. CloseHandle (handle);
  201081. handle = 0;
  201082. }
  201083. }
  201084. HANDLE handle;
  201085. int refCount;
  201086. };
  201087. InterProcessLock::InterProcessLock (const String& name_)
  201088. : name (name_)
  201089. {
  201090. }
  201091. InterProcessLock::~InterProcessLock()
  201092. {
  201093. }
  201094. bool InterProcessLock::enter (const int timeOutMillisecs)
  201095. {
  201096. const ScopedLock sl (lock);
  201097. if (pimpl == 0)
  201098. {
  201099. pimpl = new Pimpl (name, timeOutMillisecs);
  201100. if (pimpl->handle == 0)
  201101. pimpl = 0;
  201102. }
  201103. else
  201104. {
  201105. pimpl->refCount++;
  201106. }
  201107. return pimpl != 0;
  201108. }
  201109. void InterProcessLock::exit()
  201110. {
  201111. const ScopedLock sl (lock);
  201112. // Trying to release the lock too many times!
  201113. jassert (pimpl != 0);
  201114. if (pimpl != 0 && --(pimpl->refCount) == 0)
  201115. pimpl = 0;
  201116. }
  201117. #endif
  201118. /*** End of inlined file: juce_win32_Threads.cpp ***/
  201119. /*** Start of inlined file: juce_win32_Files.cpp ***/
  201120. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  201121. // compiled on its own).
  201122. #if JUCE_INCLUDED_FILE
  201123. #ifndef CSIDL_MYMUSIC
  201124. #define CSIDL_MYMUSIC 0x000d
  201125. #endif
  201126. #ifndef CSIDL_MYVIDEO
  201127. #define CSIDL_MYVIDEO 0x000e
  201128. #endif
  201129. #ifndef INVALID_FILE_ATTRIBUTES
  201130. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  201131. #endif
  201132. const juce_wchar File::separator = '\\';
  201133. const String File::separatorString ("\\");
  201134. bool File::exists() const
  201135. {
  201136. return fullPath.isNotEmpty()
  201137. && GetFileAttributes (fullPath) != INVALID_FILE_ATTRIBUTES;
  201138. }
  201139. bool File::existsAsFile() const
  201140. {
  201141. return fullPath.isNotEmpty()
  201142. && (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  201143. }
  201144. bool File::isDirectory() const
  201145. {
  201146. const DWORD attr = GetFileAttributes (fullPath);
  201147. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  201148. }
  201149. bool File::hasWriteAccess() const
  201150. {
  201151. if (exists())
  201152. return (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_READONLY) == 0;
  201153. // on windows, it seems that even read-only directories can still be written into,
  201154. // so checking the parent directory's permissions would return the wrong result..
  201155. return true;
  201156. }
  201157. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  201158. {
  201159. DWORD attr = GetFileAttributes (fullPath);
  201160. if (attr == INVALID_FILE_ATTRIBUTES)
  201161. return false;
  201162. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  201163. return true;
  201164. if (shouldBeReadOnly)
  201165. attr |= FILE_ATTRIBUTE_READONLY;
  201166. else
  201167. attr &= ~FILE_ATTRIBUTE_READONLY;
  201168. return SetFileAttributes (fullPath, attr) != FALSE;
  201169. }
  201170. bool File::isHidden() const
  201171. {
  201172. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  201173. }
  201174. bool File::deleteFile() const
  201175. {
  201176. if (! exists())
  201177. return true;
  201178. else if (isDirectory())
  201179. return RemoveDirectory (fullPath) != 0;
  201180. else
  201181. return DeleteFile (fullPath) != 0;
  201182. }
  201183. bool File::moveToTrash() const
  201184. {
  201185. if (! exists())
  201186. return true;
  201187. SHFILEOPSTRUCT fos;
  201188. zerostruct (fos);
  201189. // The string we pass in must be double null terminated..
  201190. String doubleNullTermPath (getFullPathName() + " ");
  201191. TCHAR* const p = const_cast <TCHAR*> (static_cast <const TCHAR*> (doubleNullTermPath));
  201192. p [getFullPathName().length()] = 0;
  201193. fos.wFunc = FO_DELETE;
  201194. fos.pFrom = p;
  201195. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  201196. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  201197. return SHFileOperation (&fos) == 0;
  201198. }
  201199. bool File::copyInternal (const File& dest) const
  201200. {
  201201. return CopyFile (fullPath, dest.getFullPathName(), false) != 0;
  201202. }
  201203. bool File::moveInternal (const File& dest) const
  201204. {
  201205. return MoveFile (fullPath, dest.getFullPathName()) != 0;
  201206. }
  201207. void File::createDirectoryInternal (const String& fileName) const
  201208. {
  201209. CreateDirectory (fileName, 0);
  201210. }
  201211. // return 0 if not possible
  201212. void* juce_fileOpen (const File& file, bool forWriting)
  201213. {
  201214. HANDLE h;
  201215. if (forWriting)
  201216. {
  201217. h = CreateFile (file.getFullPathName(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  201218. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  201219. if (h != INVALID_HANDLE_VALUE)
  201220. SetFilePointer (h, 0, 0, FILE_END);
  201221. else
  201222. h = 0;
  201223. }
  201224. else
  201225. {
  201226. h = CreateFile (file.getFullPathName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  201227. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  201228. if (h == INVALID_HANDLE_VALUE)
  201229. h = 0;
  201230. }
  201231. return h;
  201232. }
  201233. void juce_fileClose (void* handle)
  201234. {
  201235. CloseHandle (handle);
  201236. }
  201237. int juce_fileRead (void* handle, void* buffer, int size)
  201238. {
  201239. DWORD num = 0;
  201240. ReadFile ((HANDLE) handle, buffer, size, &num, 0);
  201241. return (int) num;
  201242. }
  201243. int juce_fileWrite (void* handle, const void* buffer, int size)
  201244. {
  201245. DWORD num;
  201246. WriteFile ((HANDLE) handle, buffer, size, &num, 0);
  201247. return (int) num;
  201248. }
  201249. int64 juce_fileSetPosition (void* handle, int64 pos)
  201250. {
  201251. LARGE_INTEGER li;
  201252. li.QuadPart = pos;
  201253. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  201254. return li.QuadPart;
  201255. }
  201256. int64 FileOutputStream::getPositionInternal() const
  201257. {
  201258. if (fileHandle == 0)
  201259. return -1;
  201260. LARGE_INTEGER li;
  201261. li.QuadPart = 0;
  201262. li.LowPart = SetFilePointer ((HANDLE) fileHandle, 0, &li.HighPart, FILE_CURRENT); // (returns -1 if it fails)
  201263. return jmax ((int64) 0, li.QuadPart);
  201264. }
  201265. void FileOutputStream::flushInternal()
  201266. {
  201267. if (fileHandle != 0)
  201268. FlushFileBuffers ((HANDLE) fileHandle);
  201269. }
  201270. int64 File::getSize() const
  201271. {
  201272. WIN32_FILE_ATTRIBUTE_DATA attributes;
  201273. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  201274. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  201275. return 0;
  201276. }
  201277. static int64 fileTimeToTime (const FILETIME* const ft)
  201278. {
  201279. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  201280. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  201281. }
  201282. static void timeToFileTime (const int64 time, FILETIME* const ft)
  201283. {
  201284. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  201285. }
  201286. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  201287. {
  201288. WIN32_FILE_ATTRIBUTE_DATA attributes;
  201289. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  201290. {
  201291. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  201292. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  201293. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  201294. }
  201295. else
  201296. {
  201297. creationTime = accessTime = modificationTime = 0;
  201298. }
  201299. }
  201300. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  201301. {
  201302. void* const h = juce_fileOpen (fullPath, true);
  201303. bool ok = false;
  201304. if (h != 0)
  201305. {
  201306. FILETIME m, a, c;
  201307. timeToFileTime (modificationTime, &m);
  201308. timeToFileTime (accessTime, &a);
  201309. timeToFileTime (creationTime, &c);
  201310. ok = SetFileTime ((HANDLE) h,
  201311. creationTime > 0 ? &c : 0,
  201312. accessTime > 0 ? &a : 0,
  201313. modificationTime > 0 ? &m : 0) != 0;
  201314. juce_fileClose (h);
  201315. }
  201316. return ok;
  201317. }
  201318. void File::findFileSystemRoots (Array<File>& destArray)
  201319. {
  201320. TCHAR buffer [2048];
  201321. buffer[0] = 0;
  201322. buffer[1] = 0;
  201323. GetLogicalDriveStrings (2048, buffer);
  201324. const TCHAR* n = buffer;
  201325. StringArray roots;
  201326. while (*n != 0)
  201327. {
  201328. roots.add (String (n));
  201329. while (*n++ != 0)
  201330. {}
  201331. }
  201332. roots.sort (true);
  201333. for (int i = 0; i < roots.size(); ++i)
  201334. destArray.add (roots [i]);
  201335. }
  201336. static const String getDriveFromPath (const String& path)
  201337. {
  201338. if (path.isNotEmpty() && path[1] == ':')
  201339. return path.substring (0, 2) + '\\';
  201340. return path;
  201341. }
  201342. const String File::getVolumeLabel() const
  201343. {
  201344. TCHAR dest[64];
  201345. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  201346. numElementsInArray (dest), 0, 0, 0, 0, 0))
  201347. dest[0] = 0;
  201348. return dest;
  201349. }
  201350. int File::getVolumeSerialNumber() const
  201351. {
  201352. TCHAR dest[64];
  201353. DWORD serialNum;
  201354. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  201355. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  201356. return 0;
  201357. return (int) serialNum;
  201358. }
  201359. static int64 getDiskSpaceInfo (const String& path, const bool total)
  201360. {
  201361. ULARGE_INTEGER spc, tot, totFree;
  201362. if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree))
  201363. return total ? (int64) tot.QuadPart
  201364. : (int64) spc.QuadPart;
  201365. return 0;
  201366. }
  201367. int64 File::getBytesFreeOnVolume() const
  201368. {
  201369. return getDiskSpaceInfo (getFullPathName(), false);
  201370. }
  201371. int64 File::getVolumeTotalSize() const
  201372. {
  201373. return getDiskSpaceInfo (getFullPathName(), true);
  201374. }
  201375. static unsigned int getWindowsDriveType (const String& path)
  201376. {
  201377. return GetDriveType (getDriveFromPath (path));
  201378. }
  201379. bool File::isOnCDRomDrive() const
  201380. {
  201381. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  201382. }
  201383. bool File::isOnHardDisk() const
  201384. {
  201385. if (fullPath.isEmpty())
  201386. return false;
  201387. const unsigned int n = getWindowsDriveType (getFullPathName());
  201388. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  201389. return n != DRIVE_REMOVABLE;
  201390. else
  201391. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  201392. }
  201393. bool File::isOnRemovableDrive() const
  201394. {
  201395. if (fullPath.isEmpty())
  201396. return false;
  201397. const unsigned int n = getWindowsDriveType (getFullPathName());
  201398. return n == DRIVE_CDROM
  201399. || n == DRIVE_REMOTE
  201400. || n == DRIVE_REMOVABLE
  201401. || n == DRIVE_RAMDISK;
  201402. }
  201403. static const File juce_getSpecialFolderPath (int type)
  201404. {
  201405. WCHAR path [MAX_PATH + 256];
  201406. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  201407. return File (String (path));
  201408. return File::nonexistent;
  201409. }
  201410. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  201411. {
  201412. int csidlType = 0;
  201413. switch (type)
  201414. {
  201415. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  201416. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  201417. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  201418. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  201419. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  201420. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  201421. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  201422. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  201423. case tempDirectory:
  201424. {
  201425. WCHAR dest [2048];
  201426. dest[0] = 0;
  201427. GetTempPath (numElementsInArray (dest), dest);
  201428. return File (String (dest));
  201429. }
  201430. case invokedExecutableFile:
  201431. case currentExecutableFile:
  201432. case currentApplicationFile:
  201433. {
  201434. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  201435. WCHAR dest [MAX_PATH + 256];
  201436. dest[0] = 0;
  201437. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  201438. return File (String (dest));
  201439. }
  201440. break;
  201441. default:
  201442. jassertfalse // unknown type?
  201443. return File::nonexistent;
  201444. }
  201445. return juce_getSpecialFolderPath (csidlType);
  201446. }
  201447. const File File::getCurrentWorkingDirectory()
  201448. {
  201449. WCHAR dest [MAX_PATH + 256];
  201450. dest[0] = 0;
  201451. GetCurrentDirectory (numElementsInArray (dest), dest);
  201452. return File (String (dest));
  201453. }
  201454. bool File::setAsCurrentWorkingDirectory() const
  201455. {
  201456. return SetCurrentDirectory (getFullPathName()) != FALSE;
  201457. }
  201458. const String File::getVersion() const
  201459. {
  201460. String result;
  201461. DWORD handle = 0;
  201462. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  201463. HeapBlock<char> buffer;
  201464. buffer.calloc (bufferSize);
  201465. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  201466. {
  201467. VS_FIXEDFILEINFO* vffi;
  201468. UINT len = 0;
  201469. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  201470. {
  201471. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  201472. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  201473. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  201474. << (int) LOWORD (vffi->dwFileVersionLS);
  201475. }
  201476. }
  201477. return result;
  201478. }
  201479. const File File::getLinkedTarget() const
  201480. {
  201481. File result (*this);
  201482. String p (getFullPathName());
  201483. if (! exists())
  201484. p += ".lnk";
  201485. else if (getFileExtension() != ".lnk")
  201486. return result;
  201487. ComSmartPtr <IShellLink> shellLink;
  201488. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  201489. {
  201490. ComSmartPtr <IPersistFile> persistFile;
  201491. if (SUCCEEDED (shellLink->QueryInterface (IID_IPersistFile, (LPVOID*) &persistFile)))
  201492. {
  201493. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  201494. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  201495. {
  201496. WIN32_FIND_DATA winFindData;
  201497. WCHAR resolvedPath [MAX_PATH];
  201498. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  201499. result = File (resolvedPath);
  201500. }
  201501. }
  201502. }
  201503. return result;
  201504. }
  201505. class DirectoryIterator::NativeIterator::Pimpl
  201506. {
  201507. public:
  201508. Pimpl (const File& directory, const String& wildCard)
  201509. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  201510. handle (INVALID_HANDLE_VALUE)
  201511. {
  201512. }
  201513. ~Pimpl()
  201514. {
  201515. if (handle != INVALID_HANDLE_VALUE)
  201516. FindClose (handle);
  201517. }
  201518. bool next (String& filenameFound,
  201519. bool* const isDir, bool* const isHidden, int64* const fileSize,
  201520. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  201521. {
  201522. WIN32_FIND_DATA findData;
  201523. if (handle == INVALID_HANDLE_VALUE)
  201524. {
  201525. handle = FindFirstFile (directoryWithWildCard, &findData);
  201526. if (handle == INVALID_HANDLE_VALUE)
  201527. return false;
  201528. }
  201529. else
  201530. {
  201531. if (FindNextFile (handle, &findData) == 0)
  201532. return false;
  201533. }
  201534. filenameFound = findData.cFileName;
  201535. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  201536. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  201537. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  201538. if (modTime != 0) *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  201539. if (creationTime != 0) *creationTime = fileTimeToTime (&findData.ftCreationTime);
  201540. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  201541. return true;
  201542. }
  201543. juce_UseDebuggingNewOperator
  201544. private:
  201545. const String directoryWithWildCard;
  201546. HANDLE handle;
  201547. Pimpl (const Pimpl&);
  201548. Pimpl& operator= (const Pimpl&);
  201549. };
  201550. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  201551. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  201552. {
  201553. }
  201554. DirectoryIterator::NativeIterator::~NativeIterator()
  201555. {
  201556. }
  201557. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  201558. bool* const isDir, bool* const isHidden, int64* const fileSize,
  201559. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  201560. {
  201561. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  201562. }
  201563. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  201564. {
  201565. HINSTANCE hInstance = 0;
  201566. JUCE_TRY
  201567. {
  201568. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  201569. }
  201570. JUCE_CATCH_ALL
  201571. return hInstance > (HINSTANCE) 32;
  201572. }
  201573. void File::revealToUser() const
  201574. {
  201575. if (isDirectory())
  201576. startAsProcess();
  201577. else if (getParentDirectory().exists())
  201578. getParentDirectory().startAsProcess();
  201579. }
  201580. class NamedPipeInternal
  201581. {
  201582. public:
  201583. NamedPipeInternal (const String& file, const bool isPipe_)
  201584. : pipeH (0),
  201585. cancelEvent (0),
  201586. connected (false),
  201587. isPipe (isPipe_)
  201588. {
  201589. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  201590. pipeH = isPipe ? CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  201591. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  201592. : CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0,
  201593. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  201594. }
  201595. ~NamedPipeInternal()
  201596. {
  201597. disconnectPipe();
  201598. if (pipeH != 0)
  201599. CloseHandle (pipeH);
  201600. CloseHandle (cancelEvent);
  201601. }
  201602. bool connect (const int timeOutMs)
  201603. {
  201604. if (! isPipe)
  201605. return true;
  201606. if (! connected)
  201607. {
  201608. OVERLAPPED over;
  201609. zerostruct (over);
  201610. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  201611. if (ConnectNamedPipe (pipeH, &over))
  201612. {
  201613. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  201614. }
  201615. else
  201616. {
  201617. const int err = GetLastError();
  201618. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  201619. {
  201620. HANDLE handles[] = { over.hEvent, cancelEvent };
  201621. if (WaitForMultipleObjects (2, handles, FALSE,
  201622. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  201623. connected = true;
  201624. }
  201625. else if (err == ERROR_PIPE_CONNECTED)
  201626. {
  201627. connected = true;
  201628. }
  201629. }
  201630. CloseHandle (over.hEvent);
  201631. }
  201632. return connected;
  201633. }
  201634. void disconnectPipe()
  201635. {
  201636. if (connected)
  201637. {
  201638. DisconnectNamedPipe (pipeH);
  201639. connected = false;
  201640. }
  201641. }
  201642. HANDLE pipeH;
  201643. HANDLE cancelEvent;
  201644. bool connected, isPipe;
  201645. };
  201646. void NamedPipe::close()
  201647. {
  201648. cancelPendingReads();
  201649. const ScopedLock sl (lock);
  201650. delete static_cast<NamedPipeInternal*> (internal);
  201651. internal = 0;
  201652. }
  201653. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  201654. {
  201655. close();
  201656. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  201657. if (intern->pipeH != INVALID_HANDLE_VALUE)
  201658. {
  201659. internal = intern.release();
  201660. return true;
  201661. }
  201662. return false;
  201663. }
  201664. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  201665. {
  201666. const ScopedLock sl (lock);
  201667. int bytesRead = -1;
  201668. bool waitAgain = true;
  201669. while (waitAgain && internal != 0)
  201670. {
  201671. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  201672. waitAgain = false;
  201673. if (! intern->connect (timeOutMilliseconds))
  201674. break;
  201675. if (maxBytesToRead <= 0)
  201676. return 0;
  201677. OVERLAPPED over;
  201678. zerostruct (over);
  201679. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  201680. unsigned long numRead;
  201681. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  201682. {
  201683. bytesRead = (int) numRead;
  201684. }
  201685. else if (GetLastError() == ERROR_IO_PENDING)
  201686. {
  201687. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  201688. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  201689. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  201690. : INFINITE);
  201691. if (waitResult != WAIT_OBJECT_0)
  201692. {
  201693. // if the operation timed out, let's cancel it...
  201694. CancelIo (intern->pipeH);
  201695. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  201696. }
  201697. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  201698. {
  201699. bytesRead = (int) numRead;
  201700. }
  201701. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  201702. {
  201703. intern->disconnectPipe();
  201704. waitAgain = true;
  201705. }
  201706. }
  201707. else
  201708. {
  201709. waitAgain = internal != 0;
  201710. Sleep (5);
  201711. }
  201712. CloseHandle (over.hEvent);
  201713. }
  201714. return bytesRead;
  201715. }
  201716. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  201717. {
  201718. int bytesWritten = -1;
  201719. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  201720. if (intern != 0 && intern->connect (timeOutMilliseconds))
  201721. {
  201722. if (numBytesToWrite <= 0)
  201723. return 0;
  201724. OVERLAPPED over;
  201725. zerostruct (over);
  201726. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  201727. unsigned long numWritten;
  201728. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  201729. {
  201730. bytesWritten = (int) numWritten;
  201731. }
  201732. else if (GetLastError() == ERROR_IO_PENDING)
  201733. {
  201734. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  201735. DWORD waitResult;
  201736. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  201737. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  201738. : INFINITE);
  201739. if (waitResult != WAIT_OBJECT_0)
  201740. {
  201741. CancelIo (intern->pipeH);
  201742. WaitForSingleObject (over.hEvent, INFINITE);
  201743. }
  201744. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  201745. {
  201746. bytesWritten = (int) numWritten;
  201747. }
  201748. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  201749. {
  201750. intern->disconnectPipe();
  201751. }
  201752. }
  201753. CloseHandle (over.hEvent);
  201754. }
  201755. return bytesWritten;
  201756. }
  201757. void NamedPipe::cancelPendingReads()
  201758. {
  201759. if (internal != 0)
  201760. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  201761. }
  201762. #endif
  201763. /*** End of inlined file: juce_win32_Files.cpp ***/
  201764. /*** Start of inlined file: juce_win32_Network.cpp ***/
  201765. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  201766. // compiled on its own).
  201767. #if JUCE_INCLUDED_FILE
  201768. #ifndef INTERNET_FLAG_NEED_FILE
  201769. #define INTERNET_FLAG_NEED_FILE 0x00000010
  201770. #endif
  201771. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  201772. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  201773. #endif
  201774. struct ConnectionAndRequestStruct
  201775. {
  201776. HINTERNET connection, request;
  201777. };
  201778. static HINTERNET sessionHandle = 0;
  201779. #ifndef WORKAROUND_TIMEOUT_BUG
  201780. //#define WORKAROUND_TIMEOUT_BUG 1
  201781. #endif
  201782. #if WORKAROUND_TIMEOUT_BUG
  201783. // Required because of a Microsoft bug in setting a timeout
  201784. class InternetConnectThread : public Thread
  201785. {
  201786. public:
  201787. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET& connection_, const bool isFtp_)
  201788. : Thread ("Internet"), uc (uc_), connection (connection_), isFtp (isFtp_)
  201789. {
  201790. startThread();
  201791. }
  201792. ~InternetConnectThread()
  201793. {
  201794. stopThread (60000);
  201795. }
  201796. void run()
  201797. {
  201798. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  201799. uc.nPort, _T(""), _T(""),
  201800. isFtp ? INTERNET_SERVICE_FTP
  201801. : INTERNET_SERVICE_HTTP,
  201802. 0, 0);
  201803. notify();
  201804. }
  201805. juce_UseDebuggingNewOperator
  201806. private:
  201807. URL_COMPONENTS& uc;
  201808. HINTERNET& connection;
  201809. const bool isFtp;
  201810. InternetConnectThread (const InternetConnectThread&);
  201811. InternetConnectThread& operator= (const InternetConnectThread&);
  201812. };
  201813. #endif
  201814. void* juce_openInternetFile (const String& url,
  201815. const String& headers,
  201816. const MemoryBlock& postData,
  201817. const bool isPost,
  201818. URL::OpenStreamProgressCallback* callback,
  201819. void* callbackContext,
  201820. int timeOutMs)
  201821. {
  201822. if (sessionHandle == 0)
  201823. sessionHandle = InternetOpen (_T("juce"),
  201824. INTERNET_OPEN_TYPE_PRECONFIG,
  201825. 0, 0, 0);
  201826. if (sessionHandle != 0)
  201827. {
  201828. // break up the url..
  201829. TCHAR file[1024], server[1024];
  201830. URL_COMPONENTS uc;
  201831. zerostruct (uc);
  201832. uc.dwStructSize = sizeof (uc);
  201833. uc.dwUrlPathLength = sizeof (file);
  201834. uc.dwHostNameLength = sizeof (server);
  201835. uc.lpszUrlPath = file;
  201836. uc.lpszHostName = server;
  201837. if (InternetCrackUrl (url, 0, 0, &uc))
  201838. {
  201839. int disable = 1;
  201840. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  201841. if (timeOutMs == 0)
  201842. timeOutMs = 30000;
  201843. else if (timeOutMs < 0)
  201844. timeOutMs = -1;
  201845. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  201846. const bool isFtp = url.startsWithIgnoreCase ("ftp:");
  201847. #if WORKAROUND_TIMEOUT_BUG
  201848. HINTERNET connection = 0;
  201849. {
  201850. InternetConnectThread connectThread (uc, connection, isFtp);
  201851. connectThread.wait (timeOutMs);
  201852. if (connection == 0)
  201853. {
  201854. InternetCloseHandle (sessionHandle);
  201855. sessionHandle = 0;
  201856. }
  201857. }
  201858. #else
  201859. HINTERNET connection = InternetConnect (sessionHandle,
  201860. uc.lpszHostName,
  201861. uc.nPort,
  201862. _T(""), _T(""),
  201863. isFtp ? INTERNET_SERVICE_FTP
  201864. : INTERNET_SERVICE_HTTP,
  201865. 0, 0);
  201866. #endif
  201867. if (connection != 0)
  201868. {
  201869. if (isFtp)
  201870. {
  201871. HINTERNET request = FtpOpenFile (connection,
  201872. uc.lpszUrlPath,
  201873. GENERIC_READ,
  201874. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  201875. 0);
  201876. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  201877. result->connection = connection;
  201878. result->request = request;
  201879. return result;
  201880. }
  201881. else
  201882. {
  201883. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  201884. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE;
  201885. if (url.startsWithIgnoreCase ("https:"))
  201886. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  201887. // IE7 seems to automatically work out when it's https)
  201888. HINTERNET request = HttpOpenRequest (connection,
  201889. isPost ? _T("POST")
  201890. : _T("GET"),
  201891. uc.lpszUrlPath,
  201892. 0, 0, mimeTypes, flags, 0);
  201893. if (request != 0)
  201894. {
  201895. INTERNET_BUFFERS buffers;
  201896. zerostruct (buffers);
  201897. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  201898. buffers.lpcszHeader = (LPCTSTR) headers;
  201899. buffers.dwHeadersLength = headers.length();
  201900. buffers.dwBufferTotal = (DWORD) postData.getSize();
  201901. ConnectionAndRequestStruct* result = 0;
  201902. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  201903. {
  201904. int bytesSent = 0;
  201905. for (;;)
  201906. {
  201907. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  201908. DWORD bytesDone = 0;
  201909. if (bytesToDo > 0
  201910. && ! InternetWriteFile (request,
  201911. static_cast <const char*> (postData.getData()) + bytesSent,
  201912. bytesToDo, &bytesDone))
  201913. {
  201914. break;
  201915. }
  201916. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  201917. {
  201918. result = new ConnectionAndRequestStruct();
  201919. result->connection = connection;
  201920. result->request = request;
  201921. HttpEndRequest (request, 0, 0, 0);
  201922. return result;
  201923. }
  201924. bytesSent += bytesDone;
  201925. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  201926. break;
  201927. }
  201928. }
  201929. InternetCloseHandle (request);
  201930. }
  201931. InternetCloseHandle (connection);
  201932. }
  201933. }
  201934. }
  201935. }
  201936. return 0;
  201937. }
  201938. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  201939. {
  201940. DWORD bytesRead = 0;
  201941. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  201942. if (crs != 0)
  201943. InternetReadFile (crs->request,
  201944. buffer, bytesToRead,
  201945. &bytesRead);
  201946. return bytesRead;
  201947. }
  201948. int juce_seekInInternetFile (void* handle, int newPosition)
  201949. {
  201950. if (handle != 0)
  201951. {
  201952. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  201953. return InternetSetFilePointer (crs->request, newPosition, 0, FILE_BEGIN, 0);
  201954. }
  201955. return -1;
  201956. }
  201957. int64 juce_getInternetFileContentLength (void* handle)
  201958. {
  201959. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  201960. if (crs != 0)
  201961. {
  201962. DWORD index = 0, result = 0, size = sizeof (result);
  201963. if (HttpQueryInfo (crs->request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER,
  201964. &result, &size, &index))
  201965. {
  201966. return (int64) result;
  201967. }
  201968. }
  201969. return -1;
  201970. }
  201971. void juce_closeInternetFile (void* handle)
  201972. {
  201973. if (handle != 0)
  201974. {
  201975. ScopedPointer <ConnectionAndRequestStruct> crs (static_cast <ConnectionAndRequestStruct*> (handle));
  201976. InternetCloseHandle (crs->request);
  201977. InternetCloseHandle (crs->connection);
  201978. }
  201979. }
  201980. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  201981. {
  201982. int numFound = 0;
  201983. DynamicLibraryLoader dll ("iphlpapi.dll");
  201984. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  201985. if (getAdaptersInfo != 0)
  201986. {
  201987. ULONG len = sizeof (IP_ADAPTER_INFO);
  201988. MemoryBlock mb;
  201989. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  201990. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  201991. {
  201992. mb.setSize (len);
  201993. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  201994. }
  201995. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  201996. {
  201997. PIP_ADAPTER_INFO adapter = adapterInfo;
  201998. while (adapter != 0)
  201999. {
  202000. int64 mac = 0;
  202001. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  202002. mac = (mac << 8) | adapter->Address[i];
  202003. if (littleEndian)
  202004. mac = (int64) ByteOrder::swap ((uint64) mac);
  202005. if (numFound < maxNum && mac != 0)
  202006. addresses [numFound++] = mac;
  202007. adapter = adapter->Next;
  202008. }
  202009. }
  202010. }
  202011. return numFound;
  202012. }
  202013. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  202014. {
  202015. int numFound = 0;
  202016. DynamicLibraryLoader dll ("netapi32.dll");
  202017. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  202018. if (NetbiosCall != 0)
  202019. {
  202020. NCB ncb;
  202021. zerostruct (ncb);
  202022. struct ASTAT
  202023. {
  202024. ADAPTER_STATUS adapt;
  202025. NAME_BUFFER NameBuff [30];
  202026. };
  202027. ASTAT astat;
  202028. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  202029. LANA_ENUM enums;
  202030. zerostruct (enums);
  202031. ncb.ncb_command = NCBENUM;
  202032. ncb.ncb_buffer = (unsigned char*) &enums;
  202033. ncb.ncb_length = sizeof (LANA_ENUM);
  202034. NetbiosCall (&ncb);
  202035. for (int i = 0; i < enums.length; ++i)
  202036. {
  202037. zerostruct (ncb);
  202038. ncb.ncb_command = NCBRESET;
  202039. ncb.ncb_lana_num = enums.lana[i];
  202040. if (NetbiosCall (&ncb) == 0)
  202041. {
  202042. zerostruct (ncb);
  202043. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  202044. ncb.ncb_command = NCBASTAT;
  202045. ncb.ncb_lana_num = enums.lana[i];
  202046. ncb.ncb_buffer = (unsigned char*) &astat;
  202047. ncb.ncb_length = sizeof (ASTAT);
  202048. if (NetbiosCall (&ncb) == 0)
  202049. {
  202050. if (astat.adapt.adapter_type == 0xfe)
  202051. {
  202052. uint64 mac = 0;
  202053. for (int i = 6; --i >= 0;)
  202054. mac = (mac << 8) | astat.adapt.adapter_address [littleEndian ? i : (5 - i)];
  202055. if (numFound < maxNum && mac != 0)
  202056. addresses [numFound++] = mac;
  202057. }
  202058. }
  202059. }
  202060. }
  202061. }
  202062. return numFound;
  202063. }
  202064. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  202065. {
  202066. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  202067. if (numFound == 0)
  202068. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  202069. return numFound;
  202070. }
  202071. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  202072. const String& emailSubject,
  202073. const String& bodyText,
  202074. const StringArray& filesToAttach)
  202075. {
  202076. HMODULE h = LoadLibraryA ("MAPI32.dll");
  202077. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  202078. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  202079. bool ok = false;
  202080. if (mapiSendMail != 0)
  202081. {
  202082. MapiMessage message;
  202083. zerostruct (message);
  202084. message.lpszSubject = (LPSTR) emailSubject.toCString();
  202085. message.lpszNoteText = (LPSTR) bodyText.toCString();
  202086. MapiRecipDesc recip;
  202087. zerostruct (recip);
  202088. recip.ulRecipClass = MAPI_TO;
  202089. String targetEmailAddress_ (targetEmailAddress);
  202090. if (targetEmailAddress_.isEmpty())
  202091. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  202092. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  202093. message.nRecipCount = 1;
  202094. message.lpRecips = &recip;
  202095. HeapBlock <MapiFileDesc> files;
  202096. files.calloc (filesToAttach.size());
  202097. message.nFileCount = filesToAttach.size();
  202098. message.lpFiles = files;
  202099. for (int i = 0; i < filesToAttach.size(); ++i)
  202100. {
  202101. files[i].nPosition = (ULONG) -1;
  202102. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  202103. }
  202104. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  202105. }
  202106. FreeLibrary (h);
  202107. return ok;
  202108. }
  202109. #endif
  202110. /*** End of inlined file: juce_win32_Network.cpp ***/
  202111. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  202112. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  202113. // compiled on its own).
  202114. #if JUCE_INCLUDED_FILE
  202115. static HKEY findKeyForPath (String name,
  202116. const bool createForWriting,
  202117. String& valueName)
  202118. {
  202119. HKEY rootKey = 0;
  202120. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  202121. rootKey = HKEY_CURRENT_USER;
  202122. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  202123. rootKey = HKEY_LOCAL_MACHINE;
  202124. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  202125. rootKey = HKEY_CLASSES_ROOT;
  202126. if (rootKey != 0)
  202127. {
  202128. name = name.substring (name.indexOfChar ('\\') + 1);
  202129. const int lastSlash = name.lastIndexOfChar ('\\');
  202130. valueName = name.substring (lastSlash + 1);
  202131. name = name.substring (0, lastSlash);
  202132. HKEY key;
  202133. DWORD result;
  202134. if (createForWriting)
  202135. {
  202136. if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE,
  202137. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  202138. return key;
  202139. }
  202140. else
  202141. {
  202142. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  202143. return key;
  202144. }
  202145. }
  202146. return 0;
  202147. }
  202148. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  202149. const String& defaultValue)
  202150. {
  202151. String valueName, result (defaultValue);
  202152. HKEY k = findKeyForPath (regValuePath, false, valueName);
  202153. if (k != 0)
  202154. {
  202155. WCHAR buffer [2048];
  202156. unsigned long bufferSize = sizeof (buffer);
  202157. DWORD type = REG_SZ;
  202158. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  202159. {
  202160. if (type == REG_SZ)
  202161. result = buffer;
  202162. else if (type == REG_DWORD)
  202163. result = String ((int) *(DWORD*) buffer);
  202164. }
  202165. RegCloseKey (k);
  202166. }
  202167. return result;
  202168. }
  202169. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  202170. const String& value)
  202171. {
  202172. String valueName;
  202173. HKEY k = findKeyForPath (regValuePath, true, valueName);
  202174. if (k != 0)
  202175. {
  202176. RegSetValueEx (k, valueName, 0, REG_SZ,
  202177. (const BYTE*) (const WCHAR*) value,
  202178. sizeof (WCHAR) * (value.length() + 1));
  202179. RegCloseKey (k);
  202180. }
  202181. }
  202182. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  202183. {
  202184. bool exists = false;
  202185. String valueName;
  202186. HKEY k = findKeyForPath (regValuePath, false, valueName);
  202187. if (k != 0)
  202188. {
  202189. unsigned char buffer [2048];
  202190. unsigned long bufferSize = sizeof (buffer);
  202191. DWORD type = 0;
  202192. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  202193. exists = true;
  202194. RegCloseKey (k);
  202195. }
  202196. return exists;
  202197. }
  202198. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  202199. {
  202200. String valueName;
  202201. HKEY k = findKeyForPath (regValuePath, true, valueName);
  202202. if (k != 0)
  202203. {
  202204. RegDeleteValue (k, valueName);
  202205. RegCloseKey (k);
  202206. }
  202207. }
  202208. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  202209. {
  202210. String valueName;
  202211. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  202212. if (k != 0)
  202213. {
  202214. RegDeleteKey (k, valueName);
  202215. RegCloseKey (k);
  202216. }
  202217. }
  202218. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  202219. const String& symbolicDescription,
  202220. const String& fullDescription,
  202221. const File& targetExecutable,
  202222. int iconResourceNumber)
  202223. {
  202224. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  202225. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  202226. if (iconResourceNumber != 0)
  202227. setRegistryValue (key + "\\DefaultIcon\\",
  202228. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  202229. setRegistryValue (key + "\\", fullDescription);
  202230. setRegistryValue (key + "\\shell\\open\\command\\",
  202231. targetExecutable.getFullPathName() + " %1");
  202232. }
  202233. bool juce_IsRunningInWine()
  202234. {
  202235. HKEY key;
  202236. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  202237. {
  202238. RegCloseKey (key);
  202239. return true;
  202240. }
  202241. return false;
  202242. }
  202243. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams() throw()
  202244. {
  202245. String s (::GetCommandLineW());
  202246. StringArray tokens;
  202247. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  202248. return tokens.joinIntoString (" ", 1);
  202249. }
  202250. static void* currentModuleHandle = 0;
  202251. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  202252. {
  202253. if (currentModuleHandle == 0)
  202254. currentModuleHandle = GetModuleHandle (0);
  202255. return currentModuleHandle;
  202256. }
  202257. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  202258. {
  202259. currentModuleHandle = newHandle;
  202260. }
  202261. void PlatformUtilities::fpuReset()
  202262. {
  202263. #if JUCE_MSVC
  202264. _clearfp();
  202265. #endif
  202266. }
  202267. void PlatformUtilities::beep()
  202268. {
  202269. MessageBeep (MB_OK);
  202270. }
  202271. #endif
  202272. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  202273. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  202274. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  202275. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  202276. // compiled on its own).
  202277. #if JUCE_INCLUDED_FILE
  202278. static const unsigned int specialId = WM_APP + 0x4400;
  202279. static const unsigned int broadcastId = WM_APP + 0x4403;
  202280. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  202281. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  202282. HWND juce_messageWindowHandle = 0;
  202283. extern long improbableWindowNumber; // defined in windowing.cpp
  202284. #ifndef WM_APPCOMMAND
  202285. #define WM_APPCOMMAND 0x0319
  202286. #endif
  202287. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  202288. const UINT message,
  202289. const WPARAM wParam,
  202290. const LPARAM lParam) throw()
  202291. {
  202292. JUCE_TRY
  202293. {
  202294. if (h == juce_messageWindowHandle)
  202295. {
  202296. if (message == specialCallbackId)
  202297. {
  202298. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  202299. return (LRESULT) (*func) ((void*) lParam);
  202300. }
  202301. else if (message == specialId)
  202302. {
  202303. // these are trapped early in the dispatch call, but must also be checked
  202304. // here in case there are windows modal dialog boxes doing their own
  202305. // dispatch loop and not calling our version
  202306. MessageManager::getInstance()->deliverMessage ((void*) lParam);
  202307. return 0;
  202308. }
  202309. else if (message == broadcastId)
  202310. {
  202311. const ScopedPointer <String> messageString ((String*) lParam);
  202312. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  202313. return 0;
  202314. }
  202315. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  202316. {
  202317. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  202318. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  202319. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  202320. return 0;
  202321. }
  202322. }
  202323. }
  202324. JUCE_CATCH_EXCEPTION
  202325. return DefWindowProc (h, message, wParam, lParam);
  202326. }
  202327. static bool isEventBlockedByModalComps (MSG& m)
  202328. {
  202329. if (Component::getNumCurrentlyModalComponents() == 0
  202330. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  202331. return false;
  202332. switch (m.message)
  202333. {
  202334. case WM_MOUSEMOVE:
  202335. case WM_NCMOUSEMOVE:
  202336. case 0x020A: /* WM_MOUSEWHEEL */
  202337. case 0x020E: /* WM_MOUSEHWHEEL */
  202338. case WM_KEYUP:
  202339. case WM_SYSKEYUP:
  202340. case WM_CHAR:
  202341. case WM_APPCOMMAND:
  202342. case WM_LBUTTONUP:
  202343. case WM_MBUTTONUP:
  202344. case WM_RBUTTONUP:
  202345. case WM_MOUSEACTIVATE:
  202346. case WM_NCMOUSEHOVER:
  202347. case WM_MOUSEHOVER:
  202348. return true;
  202349. case WM_NCLBUTTONDOWN:
  202350. case WM_NCLBUTTONDBLCLK:
  202351. case WM_NCRBUTTONDOWN:
  202352. case WM_NCRBUTTONDBLCLK:
  202353. case WM_NCMBUTTONDOWN:
  202354. case WM_NCMBUTTONDBLCLK:
  202355. case WM_LBUTTONDOWN:
  202356. case WM_LBUTTONDBLCLK:
  202357. case WM_MBUTTONDOWN:
  202358. case WM_MBUTTONDBLCLK:
  202359. case WM_RBUTTONDOWN:
  202360. case WM_RBUTTONDBLCLK:
  202361. case WM_KEYDOWN:
  202362. case WM_SYSKEYDOWN:
  202363. {
  202364. Component* const modal = Component::getCurrentlyModalComponent (0);
  202365. if (modal != 0)
  202366. modal->inputAttemptWhenModal();
  202367. return true;
  202368. }
  202369. default:
  202370. break;
  202371. }
  202372. return false;
  202373. }
  202374. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  202375. {
  202376. MSG m;
  202377. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  202378. return false;
  202379. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  202380. {
  202381. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  202382. {
  202383. MessageManager::getInstance()->deliverMessage ((void*) m.lParam);
  202384. }
  202385. else if (m.message == WM_QUIT)
  202386. {
  202387. if (JUCEApplication::getInstance())
  202388. JUCEApplication::getInstance()->systemRequestedQuit();
  202389. }
  202390. else if (! isEventBlockedByModalComps (m))
  202391. {
  202392. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  202393. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  202394. {
  202395. // if it's someone else's window being clicked on, and the focus is
  202396. // currently on a juce window, pass the kb focus over..
  202397. HWND currentFocus = GetFocus();
  202398. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  202399. SetFocus (m.hwnd);
  202400. }
  202401. TranslateMessage (&m);
  202402. DispatchMessage (&m);
  202403. }
  202404. }
  202405. return true;
  202406. }
  202407. bool juce_postMessageToSystemQueue (void* message)
  202408. {
  202409. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  202410. }
  202411. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  202412. void* userData)
  202413. {
  202414. if (MessageManager::getInstance()->isThisTheMessageThread())
  202415. {
  202416. return (*callback) (userData);
  202417. }
  202418. else
  202419. {
  202420. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  202421. // deadlock because the message manager is blocked from running, and can't
  202422. // call your function..
  202423. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  202424. return (void*) SendMessage (juce_messageWindowHandle,
  202425. specialCallbackId,
  202426. (WPARAM) callback,
  202427. (LPARAM) userData);
  202428. }
  202429. }
  202430. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  202431. {
  202432. if (hwnd != juce_messageWindowHandle)
  202433. reinterpret_cast <VoidArray*> (lParam)->add ((void*) hwnd);
  202434. return TRUE;
  202435. }
  202436. void MessageManager::broadcastMessage (const String& value) throw()
  202437. {
  202438. VoidArray windows;
  202439. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  202440. const String localCopy (value);
  202441. COPYDATASTRUCT data;
  202442. data.dwData = broadcastId;
  202443. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  202444. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  202445. for (int i = windows.size(); --i >= 0;)
  202446. {
  202447. HWND hwnd = (HWND) windows.getUnchecked(i);
  202448. TCHAR windowName [64]; // no need to read longer strings than this
  202449. GetWindowText (hwnd, windowName, 64);
  202450. windowName [63] = 0;
  202451. if (String (windowName) == messageWindowName)
  202452. {
  202453. DWORD_PTR result;
  202454. SendMessageTimeout (hwnd, WM_COPYDATA,
  202455. (WPARAM) juce_messageWindowHandle,
  202456. (LPARAM) &data,
  202457. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  202458. 8000,
  202459. &result);
  202460. }
  202461. }
  202462. }
  202463. static const String getMessageWindowClassName()
  202464. {
  202465. // this name has to be different for each app/dll instance because otherwise
  202466. // poor old Win32 can get a bit confused (even despite it not being a process-global
  202467. // window class).
  202468. static int number = 0;
  202469. if (number == 0)
  202470. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  202471. return "JUCEcs_" + String (number);
  202472. }
  202473. void MessageManager::doPlatformSpecificInitialisation()
  202474. {
  202475. OleInitialize (0);
  202476. const String className (getMessageWindowClassName());
  202477. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  202478. WNDCLASSEX wc;
  202479. zerostruct (wc);
  202480. wc.cbSize = sizeof (wc);
  202481. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  202482. wc.cbWndExtra = 4;
  202483. wc.hInstance = hmod;
  202484. wc.lpszClassName = className;
  202485. RegisterClassEx (&wc);
  202486. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  202487. messageWindowName,
  202488. 0, 0, 0, 0, 0, 0, 0,
  202489. hmod, 0);
  202490. }
  202491. void MessageManager::doPlatformSpecificShutdown()
  202492. {
  202493. DestroyWindow (juce_messageWindowHandle);
  202494. UnregisterClass (getMessageWindowClassName(), 0);
  202495. OleUninitialize();
  202496. }
  202497. #endif
  202498. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  202499. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  202500. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  202501. // compiled on its own).
  202502. #if JUCE_INCLUDED_FILE
  202503. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  202504. // these are in the windows SDK, but need to be repeated here for GCC..
  202505. #ifndef GET_APPCOMMAND_LPARAM
  202506. #define FAPPCOMMAND_MASK 0xF000
  202507. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  202508. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  202509. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  202510. #define APPCOMMAND_MEDIA_STOP 13
  202511. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  202512. #define WM_APPCOMMAND 0x0319
  202513. #endif
  202514. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  202515. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  202516. extern bool juce_IsRunningInWine();
  202517. #ifndef ULW_ALPHA
  202518. #define ULW_ALPHA 0x00000002
  202519. #endif
  202520. #ifndef AC_SRC_ALPHA
  202521. #define AC_SRC_ALPHA 0x01
  202522. #endif
  202523. static HPALETTE palette = 0;
  202524. static bool createPaletteIfNeeded = true;
  202525. static bool shouldDeactivateTitleBar = true;
  202526. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw();
  202527. #define WM_TRAYNOTIFY WM_USER + 100
  202528. using ::abs;
  202529. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  202530. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  202531. bool Desktop::canUseSemiTransparentWindows() throw()
  202532. {
  202533. if (updateLayeredWindow == 0)
  202534. {
  202535. if (! juce_IsRunningInWine())
  202536. {
  202537. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  202538. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  202539. }
  202540. }
  202541. return updateLayeredWindow != 0;
  202542. }
  202543. const int extendedKeyModifier = 0x10000;
  202544. const int KeyPress::spaceKey = VK_SPACE;
  202545. const int KeyPress::returnKey = VK_RETURN;
  202546. const int KeyPress::escapeKey = VK_ESCAPE;
  202547. const int KeyPress::backspaceKey = VK_BACK;
  202548. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  202549. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  202550. const int KeyPress::tabKey = VK_TAB;
  202551. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  202552. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  202553. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  202554. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  202555. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  202556. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  202557. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  202558. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  202559. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  202560. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  202561. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  202562. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  202563. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  202564. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  202565. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  202566. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  202567. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  202568. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  202569. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  202570. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  202571. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  202572. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  202573. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  202574. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  202575. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  202576. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  202577. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  202578. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  202579. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  202580. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  202581. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  202582. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  202583. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  202584. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  202585. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  202586. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  202587. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  202588. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  202589. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  202590. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  202591. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  202592. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  202593. const int KeyPress::playKey = 0x30000;
  202594. const int KeyPress::stopKey = 0x30001;
  202595. const int KeyPress::fastForwardKey = 0x30002;
  202596. const int KeyPress::rewindKey = 0x30003;
  202597. class WindowsBitmapImage : public Image
  202598. {
  202599. public:
  202600. HBITMAP hBitmap;
  202601. BITMAPV4HEADER bitmapInfo;
  202602. HDC hdc;
  202603. unsigned char* bitmapData;
  202604. WindowsBitmapImage (const PixelFormat format_,
  202605. const int w, const int h, const bool clearImage)
  202606. : Image (format_, w, h)
  202607. {
  202608. jassert (format_ == RGB || format_ == ARGB);
  202609. pixelStride = (format_ == RGB) ? 3 : 4;
  202610. zerostruct (bitmapInfo);
  202611. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  202612. bitmapInfo.bV4Width = w;
  202613. bitmapInfo.bV4Height = h;
  202614. bitmapInfo.bV4Planes = 1;
  202615. bitmapInfo.bV4CSType = 1;
  202616. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  202617. if (format_ == ARGB)
  202618. {
  202619. bitmapInfo.bV4AlphaMask = 0xff000000;
  202620. bitmapInfo.bV4RedMask = 0xff0000;
  202621. bitmapInfo.bV4GreenMask = 0xff00;
  202622. bitmapInfo.bV4BlueMask = 0xff;
  202623. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  202624. }
  202625. else
  202626. {
  202627. bitmapInfo.bV4V4Compression = BI_RGB;
  202628. }
  202629. lineStride = -((w * pixelStride + 3) & ~3);
  202630. HDC dc = GetDC (0);
  202631. hdc = CreateCompatibleDC (dc);
  202632. ReleaseDC (0, dc);
  202633. SetMapMode (hdc, MM_TEXT);
  202634. hBitmap = CreateDIBSection (hdc,
  202635. (BITMAPINFO*) &(bitmapInfo),
  202636. DIB_RGB_COLORS,
  202637. (void**) &bitmapData,
  202638. 0, 0);
  202639. SelectObject (hdc, hBitmap);
  202640. if (format_ == ARGB && clearImage)
  202641. zeromem (bitmapData, abs (h * lineStride));
  202642. imageData = bitmapData - (lineStride * (h - 1));
  202643. }
  202644. ~WindowsBitmapImage()
  202645. {
  202646. DeleteDC (hdc);
  202647. DeleteObject (hBitmap);
  202648. }
  202649. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  202650. const int x, const int y,
  202651. const RectangleList& maskedRegion) throw()
  202652. {
  202653. static HDRAWDIB hdd = 0;
  202654. static bool needToCreateDrawDib = true;
  202655. if (needToCreateDrawDib)
  202656. {
  202657. needToCreateDrawDib = false;
  202658. HDC dc = GetDC (0);
  202659. const int n = GetDeviceCaps (dc, BITSPIXEL);
  202660. ReleaseDC (0, dc);
  202661. // only open if we're not palettised
  202662. if (n > 8)
  202663. hdd = DrawDibOpen();
  202664. }
  202665. if (createPaletteIfNeeded)
  202666. {
  202667. HDC dc = GetDC (0);
  202668. const int n = GetDeviceCaps (dc, BITSPIXEL);
  202669. ReleaseDC (0, dc);
  202670. if (n <= 8)
  202671. palette = CreateHalftonePalette (dc);
  202672. createPaletteIfNeeded = false;
  202673. }
  202674. if (palette != 0)
  202675. {
  202676. SelectPalette (dc, palette, FALSE);
  202677. RealizePalette (dc);
  202678. SetStretchBltMode (dc, HALFTONE);
  202679. }
  202680. SetMapMode (dc, MM_TEXT);
  202681. if (transparent)
  202682. {
  202683. POINT p, pos;
  202684. SIZE size;
  202685. RECT windowBounds;
  202686. GetWindowRect (hwnd, &windowBounds);
  202687. p.x = -x;
  202688. p.y = -y;
  202689. pos.x = windowBounds.left;
  202690. pos.y = windowBounds.top;
  202691. size.cx = windowBounds.right - windowBounds.left;
  202692. size.cy = windowBounds.bottom - windowBounds.top;
  202693. BLENDFUNCTION bf;
  202694. bf.AlphaFormat = AC_SRC_ALPHA;
  202695. bf.BlendFlags = 0;
  202696. bf.BlendOp = AC_SRC_OVER;
  202697. bf.SourceConstantAlpha = 0xff;
  202698. if (! maskedRegion.isEmpty())
  202699. {
  202700. for (RectangleList::Iterator i (maskedRegion); i.next();)
  202701. {
  202702. const Rectangle<int>& r = *i.getRectangle();
  202703. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  202704. }
  202705. }
  202706. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  202707. }
  202708. else
  202709. {
  202710. int savedDC = 0;
  202711. if (! maskedRegion.isEmpty())
  202712. {
  202713. savedDC = SaveDC (dc);
  202714. for (RectangleList::Iterator i (maskedRegion); i.next();)
  202715. {
  202716. const Rectangle<int>& r = *i.getRectangle();
  202717. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  202718. }
  202719. }
  202720. const int w = getWidth();
  202721. const int h = getHeight();
  202722. if (hdd == 0)
  202723. {
  202724. StretchDIBits (dc,
  202725. x, y, w, h,
  202726. 0, 0, w, h,
  202727. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  202728. DIB_RGB_COLORS, SRCCOPY);
  202729. }
  202730. else
  202731. {
  202732. DrawDibDraw (hdd, dc, x, y, -1, -1,
  202733. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  202734. 0, 0, w, h, 0);
  202735. }
  202736. if (! maskedRegion.isEmpty())
  202737. RestoreDC (dc, savedDC);
  202738. }
  202739. }
  202740. juce_UseDebuggingNewOperator
  202741. private:
  202742. WindowsBitmapImage (const WindowsBitmapImage&);
  202743. WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  202744. };
  202745. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  202746. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  202747. {
  202748. SHORT k = (SHORT) keyCode;
  202749. if ((keyCode & extendedKeyModifier) == 0
  202750. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  202751. k += (SHORT) 'A' - (SHORT) 'a';
  202752. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  202753. (SHORT) '+', VK_OEM_PLUS,
  202754. (SHORT) '-', VK_OEM_MINUS,
  202755. (SHORT) '.', VK_OEM_PERIOD,
  202756. (SHORT) ';', VK_OEM_1,
  202757. (SHORT) ':', VK_OEM_1,
  202758. (SHORT) '/', VK_OEM_2,
  202759. (SHORT) '?', VK_OEM_2,
  202760. (SHORT) '[', VK_OEM_4,
  202761. (SHORT) ']', VK_OEM_6 };
  202762. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  202763. if (k == translatedValues [i])
  202764. k = translatedValues [i + 1];
  202765. return (GetKeyState (k) & 0x8000) != 0;
  202766. }
  202767. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  202768. {
  202769. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  202770. return callback (userData);
  202771. else
  202772. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  202773. }
  202774. class Win32ComponentPeer : public ComponentPeer
  202775. {
  202776. public:
  202777. Win32ComponentPeer (Component* const component,
  202778. const int windowStyleFlags)
  202779. : ComponentPeer (component, windowStyleFlags),
  202780. dontRepaint (false),
  202781. fullScreen (false),
  202782. isDragging (false),
  202783. isMouseOver (false),
  202784. hasCreatedCaret (false),
  202785. currentWindowIcon (0),
  202786. taskBarIcon (0),
  202787. dropTarget (0)
  202788. {
  202789. callFunctionIfNotLocked (&createWindowCallback, this);
  202790. setTitle (component->getName());
  202791. if ((windowStyleFlags & windowHasDropShadow) != 0
  202792. && Desktop::canUseSemiTransparentWindows())
  202793. {
  202794. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  202795. if (shadower != 0)
  202796. shadower->setOwner (component);
  202797. }
  202798. else
  202799. {
  202800. shadower = 0;
  202801. }
  202802. }
  202803. ~Win32ComponentPeer()
  202804. {
  202805. setTaskBarIcon (0);
  202806. deleteAndZero (shadower);
  202807. // do this before the next bit to avoid messages arriving for this window
  202808. // before it's destroyed
  202809. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  202810. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  202811. if (currentWindowIcon != 0)
  202812. DestroyIcon (currentWindowIcon);
  202813. if (dropTarget != 0)
  202814. {
  202815. dropTarget->Release();
  202816. dropTarget = 0;
  202817. }
  202818. }
  202819. void* getNativeHandle() const
  202820. {
  202821. return hwnd;
  202822. }
  202823. void setVisible (bool shouldBeVisible)
  202824. {
  202825. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  202826. if (shouldBeVisible)
  202827. InvalidateRect (hwnd, 0, 0);
  202828. else
  202829. lastPaintTime = 0;
  202830. }
  202831. void setTitle (const String& title)
  202832. {
  202833. SetWindowText (hwnd, title);
  202834. }
  202835. void setPosition (int x, int y)
  202836. {
  202837. offsetWithinParent (x, y);
  202838. SetWindowPos (hwnd, 0,
  202839. x - windowBorder.getLeft(),
  202840. y - windowBorder.getTop(),
  202841. 0, 0,
  202842. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  202843. }
  202844. void repaintNowIfTransparent()
  202845. {
  202846. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  202847. handlePaintMessage();
  202848. }
  202849. void updateBorderSize()
  202850. {
  202851. WINDOWINFO info;
  202852. info.cbSize = sizeof (info);
  202853. if (GetWindowInfo (hwnd, &info))
  202854. {
  202855. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  202856. info.rcClient.left - info.rcWindow.left,
  202857. info.rcWindow.bottom - info.rcClient.bottom,
  202858. info.rcWindow.right - info.rcClient.right);
  202859. }
  202860. }
  202861. void setSize (int w, int h)
  202862. {
  202863. SetWindowPos (hwnd, 0, 0, 0,
  202864. w + windowBorder.getLeftAndRight(),
  202865. h + windowBorder.getTopAndBottom(),
  202866. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  202867. updateBorderSize();
  202868. repaintNowIfTransparent();
  202869. }
  202870. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  202871. {
  202872. fullScreen = isNowFullScreen;
  202873. offsetWithinParent (x, y);
  202874. SetWindowPos (hwnd, 0,
  202875. x - windowBorder.getLeft(),
  202876. y - windowBorder.getTop(),
  202877. w + windowBorder.getLeftAndRight(),
  202878. h + windowBorder.getTopAndBottom(),
  202879. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  202880. updateBorderSize();
  202881. repaintNowIfTransparent();
  202882. }
  202883. const Rectangle<int> getBounds() const
  202884. {
  202885. RECT r;
  202886. GetWindowRect (hwnd, &r);
  202887. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  202888. HWND parentH = GetParent (hwnd);
  202889. if (parentH != 0)
  202890. {
  202891. GetWindowRect (parentH, &r);
  202892. bounds.translate (-r.left, -r.top);
  202893. }
  202894. return windowBorder.subtractedFrom (bounds);
  202895. }
  202896. const Point<int> getScreenPosition() const
  202897. {
  202898. RECT r;
  202899. GetWindowRect (hwnd, &r);
  202900. return Point<int> (r.left + windowBorder.getLeft(),
  202901. r.top + windowBorder.getTop());
  202902. }
  202903. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  202904. {
  202905. return relativePosition + getScreenPosition();
  202906. }
  202907. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  202908. {
  202909. return screenPosition - getScreenPosition();
  202910. }
  202911. void setMinimised (bool shouldBeMinimised)
  202912. {
  202913. if (shouldBeMinimised != isMinimised())
  202914. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  202915. }
  202916. bool isMinimised() const
  202917. {
  202918. WINDOWPLACEMENT wp;
  202919. wp.length = sizeof (WINDOWPLACEMENT);
  202920. GetWindowPlacement (hwnd, &wp);
  202921. return wp.showCmd == SW_SHOWMINIMIZED;
  202922. }
  202923. void setFullScreen (bool shouldBeFullScreen)
  202924. {
  202925. setMinimised (false);
  202926. if (fullScreen != shouldBeFullScreen)
  202927. {
  202928. fullScreen = shouldBeFullScreen;
  202929. const Component::SafePointer<Component> deletionChecker (component);
  202930. if (! fullScreen)
  202931. {
  202932. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  202933. if (hasTitleBar())
  202934. ShowWindow (hwnd, SW_SHOWNORMAL);
  202935. if (! boundsCopy.isEmpty())
  202936. {
  202937. setBounds (boundsCopy.getX(),
  202938. boundsCopy.getY(),
  202939. boundsCopy.getWidth(),
  202940. boundsCopy.getHeight(),
  202941. false);
  202942. }
  202943. }
  202944. else
  202945. {
  202946. if (hasTitleBar())
  202947. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  202948. else
  202949. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  202950. }
  202951. if (deletionChecker != 0)
  202952. handleMovedOrResized();
  202953. }
  202954. }
  202955. bool isFullScreen() const
  202956. {
  202957. if (! hasTitleBar())
  202958. return fullScreen;
  202959. WINDOWPLACEMENT wp;
  202960. wp.length = sizeof (wp);
  202961. GetWindowPlacement (hwnd, &wp);
  202962. return wp.showCmd == SW_SHOWMAXIMIZED;
  202963. }
  202964. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  202965. {
  202966. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  202967. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  202968. return false;
  202969. RECT r;
  202970. GetWindowRect (hwnd, &r);
  202971. POINT p;
  202972. p.x = position.getX() + r.left + windowBorder.getLeft();
  202973. p.y = position.getY() + r.top + windowBorder.getTop();
  202974. HWND w = WindowFromPoint (p);
  202975. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  202976. }
  202977. const BorderSize getFrameSize() const
  202978. {
  202979. return windowBorder;
  202980. }
  202981. bool setAlwaysOnTop (bool alwaysOnTop)
  202982. {
  202983. const bool oldDeactivate = shouldDeactivateTitleBar;
  202984. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  202985. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  202986. 0, 0, 0, 0,
  202987. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  202988. shouldDeactivateTitleBar = oldDeactivate;
  202989. if (shadower != 0)
  202990. shadower->componentBroughtToFront (*component);
  202991. return true;
  202992. }
  202993. void toFront (bool makeActive)
  202994. {
  202995. setMinimised (false);
  202996. const bool oldDeactivate = shouldDeactivateTitleBar;
  202997. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  202998. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  202999. shouldDeactivateTitleBar = oldDeactivate;
  203000. if (! makeActive)
  203001. {
  203002. // in this case a broughttofront call won't have occured, so do it now..
  203003. handleBroughtToFront();
  203004. }
  203005. }
  203006. void toBehind (ComponentPeer* other)
  203007. {
  203008. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  203009. jassert (otherPeer != 0); // wrong type of window?
  203010. if (otherPeer != 0)
  203011. {
  203012. setMinimised (false);
  203013. // must be careful not to try to put a topmost window behind a normal one, or win32
  203014. // promotes the normal one to be topmost!
  203015. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  203016. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  203017. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  203018. else if (otherPeer->getComponent()->isAlwaysOnTop())
  203019. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  203020. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  203021. }
  203022. }
  203023. bool isFocused() const
  203024. {
  203025. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  203026. }
  203027. void grabFocus()
  203028. {
  203029. const bool oldDeactivate = shouldDeactivateTitleBar;
  203030. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  203031. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  203032. shouldDeactivateTitleBar = oldDeactivate;
  203033. }
  203034. void textInputRequired (const Point<int>&)
  203035. {
  203036. if (! hasCreatedCaret)
  203037. {
  203038. hasCreatedCaret = true;
  203039. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  203040. }
  203041. ShowCaret (hwnd);
  203042. SetCaretPos (0, 0);
  203043. }
  203044. void repaint (int x, int y, int w, int h)
  203045. {
  203046. const RECT r = { x, y, x + w, y + h };
  203047. InvalidateRect (hwnd, &r, FALSE);
  203048. }
  203049. void performAnyPendingRepaintsNow()
  203050. {
  203051. MSG m;
  203052. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  203053. DispatchMessage (&m);
  203054. }
  203055. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  203056. {
  203057. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  203058. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  203059. return 0;
  203060. }
  203061. void setTaskBarIcon (const Image* const image)
  203062. {
  203063. if (image != 0)
  203064. {
  203065. HICON hicon = createHICONFromImage (*image, TRUE, 0, 0);
  203066. if (taskBarIcon == 0)
  203067. {
  203068. taskBarIcon = new NOTIFYICONDATA();
  203069. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  203070. taskBarIcon->hWnd = (HWND) hwnd;
  203071. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  203072. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  203073. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  203074. taskBarIcon->hIcon = hicon;
  203075. taskBarIcon->szTip[0] = 0;
  203076. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  203077. }
  203078. else
  203079. {
  203080. HICON oldIcon = taskBarIcon->hIcon;
  203081. taskBarIcon->hIcon = hicon;
  203082. taskBarIcon->uFlags = NIF_ICON;
  203083. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  203084. DestroyIcon (oldIcon);
  203085. }
  203086. DestroyIcon (hicon);
  203087. }
  203088. else if (taskBarIcon != 0)
  203089. {
  203090. taskBarIcon->uFlags = 0;
  203091. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  203092. DestroyIcon (taskBarIcon->hIcon);
  203093. deleteAndZero (taskBarIcon);
  203094. }
  203095. }
  203096. void setTaskBarIconToolTip (const String& toolTip) const
  203097. {
  203098. if (taskBarIcon != 0)
  203099. {
  203100. taskBarIcon->uFlags = NIF_TIP;
  203101. toolTip.copyToUnicode (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  203102. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  203103. }
  203104. }
  203105. bool isInside (HWND h) const
  203106. {
  203107. return GetAncestor (hwnd, GA_ROOT) == h;
  203108. }
  203109. static void updateKeyModifiers() throw()
  203110. {
  203111. int keyMods = 0;
  203112. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  203113. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  203114. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  203115. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  203116. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  203117. }
  203118. static void updateModifiersFromWParam (const WPARAM wParam)
  203119. {
  203120. int mouseMods = 0;
  203121. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  203122. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  203123. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  203124. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  203125. updateKeyModifiers();
  203126. }
  203127. static int64 getMouseEventTime()
  203128. {
  203129. static int64 eventTimeOffset = 0;
  203130. static DWORD lastMessageTime = 0;
  203131. const DWORD thisMessageTime = GetMessageTime();
  203132. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  203133. {
  203134. lastMessageTime = thisMessageTime;
  203135. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  203136. }
  203137. return eventTimeOffset + thisMessageTime;
  203138. }
  203139. juce_UseDebuggingNewOperator
  203140. bool dontRepaint;
  203141. static ModifierKeys currentModifiers;
  203142. static ModifierKeys modifiersAtLastCallback;
  203143. private:
  203144. HWND hwnd;
  203145. DropShadower* shadower;
  203146. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  203147. BorderSize windowBorder;
  203148. HICON currentWindowIcon;
  203149. NOTIFYICONDATA* taskBarIcon;
  203150. IDropTarget* dropTarget;
  203151. class TemporaryImage : public Timer
  203152. {
  203153. public:
  203154. TemporaryImage() {}
  203155. ~TemporaryImage() {}
  203156. WindowsBitmapImage* getImage (const bool transparent, const int w, const int h) throw()
  203157. {
  203158. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  203159. if (image == 0 || image->getWidth() < w || image->getHeight() < h || image->getFormat() != format)
  203160. image = new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false);
  203161. startTimer (3000);
  203162. return image;
  203163. }
  203164. void timerCallback()
  203165. {
  203166. stopTimer();
  203167. image = 0;
  203168. }
  203169. private:
  203170. ScopedPointer <WindowsBitmapImage> image;
  203171. TemporaryImage (const TemporaryImage&);
  203172. TemporaryImage& operator= (const TemporaryImage&);
  203173. };
  203174. TemporaryImage offscreenImageGenerator;
  203175. class WindowClassHolder : public DeletedAtShutdown
  203176. {
  203177. public:
  203178. WindowClassHolder()
  203179. : windowClassName ("JUCE_")
  203180. {
  203181. // this name has to be different for each app/dll instance because otherwise
  203182. // poor old Win32 can get a bit confused (even despite it not being a process-global
  203183. // window class).
  203184. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  203185. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  203186. TCHAR moduleFile [1024];
  203187. moduleFile[0] = 0;
  203188. GetModuleFileName (moduleHandle, moduleFile, 1024);
  203189. WORD iconNum = 0;
  203190. WNDCLASSEX wcex;
  203191. wcex.cbSize = sizeof (wcex);
  203192. wcex.style = CS_OWNDC;
  203193. wcex.lpfnWndProc = (WNDPROC) windowProc;
  203194. wcex.lpszClassName = windowClassName;
  203195. wcex.cbClsExtra = 0;
  203196. wcex.cbWndExtra = 32;
  203197. wcex.hInstance = moduleHandle;
  203198. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  203199. iconNum = 1;
  203200. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  203201. wcex.hCursor = 0;
  203202. wcex.hbrBackground = 0;
  203203. wcex.lpszMenuName = 0;
  203204. RegisterClassEx (&wcex);
  203205. }
  203206. ~WindowClassHolder()
  203207. {
  203208. if (ComponentPeer::getNumPeers() == 0)
  203209. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  203210. clearSingletonInstance();
  203211. }
  203212. String windowClassName;
  203213. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  203214. };
  203215. static void* createWindowCallback (void* userData)
  203216. {
  203217. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  203218. return 0;
  203219. }
  203220. void createWindow()
  203221. {
  203222. DWORD exstyle = WS_EX_ACCEPTFILES;
  203223. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  203224. if (hasTitleBar())
  203225. {
  203226. type |= WS_OVERLAPPED;
  203227. if ((styleFlags & windowHasCloseButton) != 0)
  203228. {
  203229. type |= WS_SYSMENU;
  203230. }
  203231. else
  203232. {
  203233. // annoyingly, windows won't let you have a min/max button without a close button
  203234. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  203235. }
  203236. if ((styleFlags & windowIsResizable) != 0)
  203237. type |= WS_THICKFRAME;
  203238. }
  203239. else
  203240. {
  203241. type |= WS_POPUP | WS_SYSMENU;
  203242. }
  203243. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  203244. exstyle |= WS_EX_TOOLWINDOW;
  203245. else
  203246. exstyle |= WS_EX_APPWINDOW;
  203247. if ((styleFlags & windowHasMinimiseButton) != 0)
  203248. type |= WS_MINIMIZEBOX;
  203249. if ((styleFlags & windowHasMaximiseButton) != 0)
  203250. type |= WS_MAXIMIZEBOX;
  203251. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  203252. exstyle |= WS_EX_TRANSPARENT;
  203253. if ((styleFlags & windowIsSemiTransparent) != 0
  203254. && Desktop::canUseSemiTransparentWindows())
  203255. exstyle |= WS_EX_LAYERED;
  203256. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0, 0, 0, 0, 0);
  203257. if (hwnd != 0)
  203258. {
  203259. SetWindowLongPtr (hwnd, 0, 0);
  203260. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  203261. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  203262. if (dropTarget == 0)
  203263. dropTarget = new JuceDropTarget (this);
  203264. RegisterDragDrop (hwnd, dropTarget);
  203265. updateBorderSize();
  203266. // Calling this function here is (for some reason) necessary to make Windows
  203267. // correctly enable the menu items that we specify in the wm_initmenu message.
  203268. GetSystemMenu (hwnd, false);
  203269. }
  203270. else
  203271. {
  203272. jassertfalse
  203273. }
  203274. }
  203275. static void* destroyWindowCallback (void* handle)
  203276. {
  203277. RevokeDragDrop ((HWND) handle);
  203278. DestroyWindow ((HWND) handle);
  203279. return 0;
  203280. }
  203281. static void* toFrontCallback1 (void* h)
  203282. {
  203283. SetForegroundWindow ((HWND) h);
  203284. return 0;
  203285. }
  203286. static void* toFrontCallback2 (void* h)
  203287. {
  203288. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  203289. return 0;
  203290. }
  203291. static void* setFocusCallback (void* h)
  203292. {
  203293. SetFocus ((HWND) h);
  203294. return 0;
  203295. }
  203296. static void* getFocusCallback (void*)
  203297. {
  203298. return GetFocus();
  203299. }
  203300. void offsetWithinParent (int& x, int& y) const
  203301. {
  203302. if (isTransparent())
  203303. {
  203304. HWND parentHwnd = GetParent (hwnd);
  203305. if (parentHwnd != 0)
  203306. {
  203307. RECT parentRect;
  203308. GetWindowRect (parentHwnd, &parentRect);
  203309. x += parentRect.left;
  203310. y += parentRect.top;
  203311. }
  203312. }
  203313. }
  203314. bool isTransparent() const
  203315. {
  203316. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  203317. }
  203318. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  203319. void setIcon (const Image& newIcon)
  203320. {
  203321. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  203322. if (hicon != 0)
  203323. {
  203324. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  203325. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  203326. if (currentWindowIcon != 0)
  203327. DestroyIcon (currentWindowIcon);
  203328. currentWindowIcon = hicon;
  203329. }
  203330. }
  203331. void handlePaintMessage()
  203332. {
  203333. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  203334. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  203335. PAINTSTRUCT paintStruct;
  203336. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  203337. // message and become re-entrant, but that's OK
  203338. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  203339. // corrupt the image it's using to paint into, so do a check here.
  203340. static bool reentrant = false;
  203341. if (reentrant)
  203342. {
  203343. DeleteObject (rgn);
  203344. EndPaint (hwnd, &paintStruct);
  203345. return;
  203346. }
  203347. reentrant = true;
  203348. // this is the rectangle to update..
  203349. int x = paintStruct.rcPaint.left;
  203350. int y = paintStruct.rcPaint.top;
  203351. int w = paintStruct.rcPaint.right - x;
  203352. int h = paintStruct.rcPaint.bottom - y;
  203353. const bool transparent = isTransparent();
  203354. if (transparent)
  203355. {
  203356. // it's not possible to have a transparent window with a title bar at the moment!
  203357. jassert (! hasTitleBar());
  203358. RECT r;
  203359. GetWindowRect (hwnd, &r);
  203360. x = y = 0;
  203361. w = r.right - r.left;
  203362. h = r.bottom - r.top;
  203363. }
  203364. if (w > 0 && h > 0)
  203365. {
  203366. clearMaskedRegion();
  203367. WindowsBitmapImage* const offscreenImage = offscreenImageGenerator.getImage (transparent, w, h);
  203368. RectangleList contextClip;
  203369. const Rectangle<int> clipBounds (0, 0, w, h);
  203370. bool needToPaintAll = true;
  203371. if (regionType == COMPLEXREGION && ! transparent)
  203372. {
  203373. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  203374. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  203375. DeleteObject (clipRgn);
  203376. char rgnData [8192];
  203377. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  203378. if (res > 0 && res <= sizeof (rgnData))
  203379. {
  203380. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  203381. if (hdr->iType == RDH_RECTANGLES
  203382. && hdr->rcBound.right - hdr->rcBound.left >= w
  203383. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  203384. {
  203385. needToPaintAll = false;
  203386. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  203387. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  203388. while (--num >= 0)
  203389. {
  203390. if (rects->right <= x + w && rects->bottom <= y + h)
  203391. {
  203392. // (need to move this one pixel to the left because of a win32 bug)
  203393. const int cx = jmax (x, (int) rects->left - 1);
  203394. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  203395. .getIntersection (clipBounds));
  203396. }
  203397. else
  203398. {
  203399. needToPaintAll = true;
  203400. break;
  203401. }
  203402. ++rects;
  203403. }
  203404. }
  203405. }
  203406. }
  203407. if (needToPaintAll)
  203408. {
  203409. contextClip.clear();
  203410. contextClip.addWithoutMerging (Rectangle<int> (0, 0, w, h));
  203411. }
  203412. if (transparent)
  203413. {
  203414. RectangleList::Iterator i (contextClip);
  203415. while (i.next())
  203416. offscreenImage->clear (*i.getRectangle());
  203417. }
  203418. // if the component's not opaque, this won't draw properly unless the platform can support this
  203419. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  203420. updateCurrentModifiers();
  203421. LowLevelGraphicsSoftwareRenderer context (*offscreenImage, -x, -y, contextClip);
  203422. handlePaint (context);
  203423. if (! dontRepaint)
  203424. offscreenImage->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  203425. }
  203426. DeleteObject (rgn);
  203427. EndPaint (hwnd, &paintStruct);
  203428. reentrant = false;
  203429. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  203430. _fpreset(); // because some graphics cards can unmask FP exceptions
  203431. #endif
  203432. lastPaintTime = Time::getMillisecondCounter();
  203433. }
  203434. void doMouseEvent (const Point<int>& position)
  203435. {
  203436. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  203437. }
  203438. void doMouseMove (const Point<int>& position)
  203439. {
  203440. if (! isMouseOver)
  203441. {
  203442. isMouseOver = true;
  203443. updateKeyModifiers();
  203444. TRACKMOUSEEVENT tme;
  203445. tme.cbSize = sizeof (tme);
  203446. tme.dwFlags = TME_LEAVE;
  203447. tme.hwndTrack = hwnd;
  203448. tme.dwHoverTime = 0;
  203449. if (! TrackMouseEvent (&tme))
  203450. jassertfalse;
  203451. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  203452. }
  203453. else if (! isDragging)
  203454. {
  203455. if (! contains (position, false))
  203456. return;
  203457. }
  203458. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  203459. static uint32 lastMouseTime = 0;
  203460. const uint32 now = Time::getMillisecondCounter();
  203461. const int maxMouseMovesPerSecond = 60;
  203462. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  203463. {
  203464. lastMouseTime = now;
  203465. doMouseEvent (position);
  203466. }
  203467. }
  203468. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  203469. {
  203470. if (GetCapture() != hwnd)
  203471. SetCapture (hwnd);
  203472. doMouseMove (position);
  203473. updateModifiersFromWParam (wParam);
  203474. isDragging = true;
  203475. doMouseEvent (position);
  203476. }
  203477. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  203478. {
  203479. updateModifiersFromWParam (wParam);
  203480. isDragging = false;
  203481. // release the mouse capture if the user has released all buttons
  203482. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  203483. ReleaseCapture();
  203484. doMouseEvent (position);
  203485. }
  203486. void doCaptureChanged()
  203487. {
  203488. if (isDragging)
  203489. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  203490. }
  203491. void doMouseExit()
  203492. {
  203493. isMouseOver = false;
  203494. doMouseEvent (getCurrentMousePos());
  203495. }
  203496. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  203497. {
  203498. updateKeyModifiers();
  203499. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  203500. handleMouseWheel (0, position, getMouseEventTime(),
  203501. isVertical ? 0.0f : amount,
  203502. isVertical ? amount : 0.0f);
  203503. }
  203504. void sendModifierKeyChangeIfNeeded()
  203505. {
  203506. if (modifiersAtLastCallback != currentModifiers)
  203507. {
  203508. modifiersAtLastCallback = currentModifiers;
  203509. handleModifierKeysChange();
  203510. }
  203511. }
  203512. bool doKeyUp (const WPARAM key)
  203513. {
  203514. updateKeyModifiers();
  203515. switch (key)
  203516. {
  203517. case VK_SHIFT:
  203518. case VK_CONTROL:
  203519. case VK_MENU:
  203520. case VK_CAPITAL:
  203521. case VK_LWIN:
  203522. case VK_RWIN:
  203523. case VK_APPS:
  203524. case VK_NUMLOCK:
  203525. case VK_SCROLL:
  203526. case VK_LSHIFT:
  203527. case VK_RSHIFT:
  203528. case VK_LCONTROL:
  203529. case VK_LMENU:
  203530. case VK_RCONTROL:
  203531. case VK_RMENU:
  203532. sendModifierKeyChangeIfNeeded();
  203533. }
  203534. return handleKeyUpOrDown (false)
  203535. || Component::getCurrentlyModalComponent() != 0;
  203536. }
  203537. bool doKeyDown (const WPARAM key)
  203538. {
  203539. updateKeyModifiers();
  203540. bool used = false;
  203541. switch (key)
  203542. {
  203543. case VK_SHIFT:
  203544. case VK_LSHIFT:
  203545. case VK_RSHIFT:
  203546. case VK_CONTROL:
  203547. case VK_LCONTROL:
  203548. case VK_RCONTROL:
  203549. case VK_MENU:
  203550. case VK_LMENU:
  203551. case VK_RMENU:
  203552. case VK_LWIN:
  203553. case VK_RWIN:
  203554. case VK_CAPITAL:
  203555. case VK_NUMLOCK:
  203556. case VK_SCROLL:
  203557. case VK_APPS:
  203558. sendModifierKeyChangeIfNeeded();
  203559. break;
  203560. case VK_LEFT:
  203561. case VK_RIGHT:
  203562. case VK_UP:
  203563. case VK_DOWN:
  203564. case VK_PRIOR:
  203565. case VK_NEXT:
  203566. case VK_HOME:
  203567. case VK_END:
  203568. case VK_DELETE:
  203569. case VK_INSERT:
  203570. case VK_F1:
  203571. case VK_F2:
  203572. case VK_F3:
  203573. case VK_F4:
  203574. case VK_F5:
  203575. case VK_F6:
  203576. case VK_F7:
  203577. case VK_F8:
  203578. case VK_F9:
  203579. case VK_F10:
  203580. case VK_F11:
  203581. case VK_F12:
  203582. case VK_F13:
  203583. case VK_F14:
  203584. case VK_F15:
  203585. case VK_F16:
  203586. used = handleKeyUpOrDown (true);
  203587. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  203588. break;
  203589. case VK_ADD:
  203590. case VK_SUBTRACT:
  203591. case VK_MULTIPLY:
  203592. case VK_DIVIDE:
  203593. case VK_SEPARATOR:
  203594. case VK_DECIMAL:
  203595. used = handleKeyUpOrDown (true);
  203596. break;
  203597. default:
  203598. used = handleKeyUpOrDown (true);
  203599. {
  203600. MSG msg;
  203601. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  203602. {
  203603. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  203604. // manually generate the key-press event that matches this key-down.
  203605. const UINT keyChar = MapVirtualKey (key, 2);
  203606. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  203607. }
  203608. }
  203609. break;
  203610. }
  203611. if (Component::getCurrentlyModalComponent() != 0)
  203612. used = true;
  203613. return used;
  203614. }
  203615. bool doKeyChar (int key, const LPARAM flags)
  203616. {
  203617. updateKeyModifiers();
  203618. juce_wchar textChar = (juce_wchar) key;
  203619. const int virtualScanCode = (flags >> 16) & 0xff;
  203620. if (key >= '0' && key <= '9')
  203621. {
  203622. switch (virtualScanCode) // check for a numeric keypad scan-code
  203623. {
  203624. case 0x52:
  203625. case 0x4f:
  203626. case 0x50:
  203627. case 0x51:
  203628. case 0x4b:
  203629. case 0x4c:
  203630. case 0x4d:
  203631. case 0x47:
  203632. case 0x48:
  203633. case 0x49:
  203634. key = (key - '0') + KeyPress::numberPad0;
  203635. break;
  203636. default:
  203637. break;
  203638. }
  203639. }
  203640. else
  203641. {
  203642. // convert the scan code to an unmodified character code..
  203643. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  203644. UINT keyChar = MapVirtualKey (virtualKey, 2);
  203645. keyChar = LOWORD (keyChar);
  203646. if (keyChar != 0)
  203647. key = (int) keyChar;
  203648. // avoid sending junk text characters for some control-key combinations
  203649. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  203650. textChar = 0;
  203651. }
  203652. return handleKeyPress (key, textChar);
  203653. }
  203654. bool doAppCommand (const LPARAM lParam)
  203655. {
  203656. int key = 0;
  203657. switch (GET_APPCOMMAND_LPARAM (lParam))
  203658. {
  203659. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  203660. key = KeyPress::playKey;
  203661. break;
  203662. case APPCOMMAND_MEDIA_STOP:
  203663. key = KeyPress::stopKey;
  203664. break;
  203665. case APPCOMMAND_MEDIA_NEXTTRACK:
  203666. key = KeyPress::fastForwardKey;
  203667. break;
  203668. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  203669. key = KeyPress::rewindKey;
  203670. break;
  203671. }
  203672. if (key != 0)
  203673. {
  203674. updateKeyModifiers();
  203675. if (hwnd == GetActiveWindow())
  203676. {
  203677. handleKeyPress (key, 0);
  203678. return true;
  203679. }
  203680. }
  203681. return false;
  203682. }
  203683. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  203684. {
  203685. public:
  203686. JuceDropTarget (Win32ComponentPeer* const owner_)
  203687. : owner (owner_)
  203688. {
  203689. }
  203690. ~JuceDropTarget() {}
  203691. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  203692. {
  203693. updateFileList (pDataObject);
  203694. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  203695. *pdwEffect = DROPEFFECT_COPY;
  203696. return S_OK;
  203697. }
  203698. HRESULT __stdcall DragLeave()
  203699. {
  203700. owner->handleFileDragExit (files);
  203701. return S_OK;
  203702. }
  203703. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  203704. {
  203705. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  203706. *pdwEffect = DROPEFFECT_COPY;
  203707. return S_OK;
  203708. }
  203709. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  203710. {
  203711. updateFileList (pDataObject);
  203712. owner->handleFileDragDrop (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  203713. *pdwEffect = DROPEFFECT_COPY;
  203714. return S_OK;
  203715. }
  203716. private:
  203717. Win32ComponentPeer* const owner;
  203718. StringArray files;
  203719. void updateFileList (IDataObject* const pDataObject)
  203720. {
  203721. files.clear();
  203722. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  203723. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  203724. if (pDataObject->GetData (&format, &medium) == S_OK)
  203725. {
  203726. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  203727. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  203728. unsigned int i = 0;
  203729. if (pDropFiles->fWide)
  203730. {
  203731. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  203732. for (;;)
  203733. {
  203734. unsigned int len = 0;
  203735. while (i + len < totalLen && fname [i + len] != 0)
  203736. ++len;
  203737. if (len == 0)
  203738. break;
  203739. files.add (String (fname + i, len));
  203740. i += len + 1;
  203741. }
  203742. }
  203743. else
  203744. {
  203745. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  203746. for (;;)
  203747. {
  203748. unsigned int len = 0;
  203749. while (i + len < totalLen && fname [i + len] != 0)
  203750. ++len;
  203751. if (len == 0)
  203752. break;
  203753. files.add (String (fname + i, len));
  203754. i += len + 1;
  203755. }
  203756. }
  203757. GlobalUnlock (medium.hGlobal);
  203758. }
  203759. }
  203760. JuceDropTarget (const JuceDropTarget&);
  203761. JuceDropTarget& operator= (const JuceDropTarget&);
  203762. };
  203763. void doSettingChange()
  203764. {
  203765. Desktop::getInstance().refreshMonitorSizes();
  203766. if (fullScreen && ! isMinimised())
  203767. {
  203768. const Rectangle<int> r (component->getParentMonitorArea());
  203769. SetWindowPos (hwnd, 0,
  203770. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  203771. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  203772. }
  203773. }
  203774. public:
  203775. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  203776. {
  203777. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  203778. if (peer != 0)
  203779. return peer->peerWindowProc (h, message, wParam, lParam);
  203780. return DefWindowProcW (h, message, wParam, lParam);
  203781. }
  203782. private:
  203783. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  203784. {
  203785. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  203786. }
  203787. const Point<int> getCurrentMousePos() throw()
  203788. {
  203789. RECT wr;
  203790. GetWindowRect (hwnd, &wr);
  203791. const DWORD mp = GetMessagePos();
  203792. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  203793. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  203794. }
  203795. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  203796. {
  203797. if (isValidPeer (this))
  203798. {
  203799. switch (message)
  203800. {
  203801. case WM_NCHITTEST:
  203802. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  203803. return HTTRANSPARENT;
  203804. if (hasTitleBar())
  203805. break;
  203806. return HTCLIENT;
  203807. case WM_PAINT:
  203808. handlePaintMessage();
  203809. return 0;
  203810. case WM_NCPAINT:
  203811. if (wParam != 1)
  203812. handlePaintMessage();
  203813. if (hasTitleBar())
  203814. break;
  203815. return 0;
  203816. case WM_ERASEBKGND:
  203817. case WM_NCCALCSIZE:
  203818. if (hasTitleBar())
  203819. break;
  203820. return 1;
  203821. case WM_MOUSEMOVE:
  203822. doMouseMove (getPointFromLParam (lParam));
  203823. return 0;
  203824. case WM_MOUSELEAVE:
  203825. doMouseExit();
  203826. return 0;
  203827. case WM_LBUTTONDOWN:
  203828. case WM_MBUTTONDOWN:
  203829. case WM_RBUTTONDOWN:
  203830. doMouseDown (getPointFromLParam (lParam), wParam);
  203831. return 0;
  203832. case WM_LBUTTONUP:
  203833. case WM_MBUTTONUP:
  203834. case WM_RBUTTONUP:
  203835. doMouseUp (getPointFromLParam (lParam), wParam);
  203836. return 0;
  203837. case WM_CAPTURECHANGED:
  203838. doCaptureChanged();
  203839. return 0;
  203840. case WM_NCMOUSEMOVE:
  203841. if (hasTitleBar())
  203842. break;
  203843. return 0;
  203844. case 0x020A: /* WM_MOUSEWHEEL */
  203845. doMouseWheel (getCurrentMousePos(), wParam, true);
  203846. return 0;
  203847. case 0x020E: /* WM_MOUSEHWHEEL */
  203848. doMouseWheel (getCurrentMousePos(), wParam, false);
  203849. return 0;
  203850. case WM_WINDOWPOSCHANGING:
  203851. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  203852. {
  203853. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  203854. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  203855. {
  203856. if (constrainer != 0)
  203857. {
  203858. const Rectangle<int> current (component->getX() - windowBorder.getLeft(),
  203859. component->getY() - windowBorder.getTop(),
  203860. component->getWidth() + windowBorder.getLeftAndRight(),
  203861. component->getHeight() + windowBorder.getTopAndBottom());
  203862. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  203863. constrainer->checkBounds (pos, current,
  203864. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  203865. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  203866. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  203867. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  203868. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  203869. wp->x = pos.getX();
  203870. wp->y = pos.getY();
  203871. wp->cx = pos.getWidth();
  203872. wp->cy = pos.getHeight();
  203873. }
  203874. }
  203875. }
  203876. return 0;
  203877. case WM_WINDOWPOSCHANGED:
  203878. handleMovedOrResized();
  203879. if (dontRepaint)
  203880. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  203881. return 0;
  203882. case WM_KEYDOWN:
  203883. case WM_SYSKEYDOWN:
  203884. if (doKeyDown (wParam))
  203885. return 0;
  203886. break;
  203887. case WM_KEYUP:
  203888. case WM_SYSKEYUP:
  203889. if (doKeyUp (wParam))
  203890. return 0;
  203891. break;
  203892. case WM_CHAR:
  203893. if (doKeyChar ((int) wParam, lParam))
  203894. return 0;
  203895. break;
  203896. case WM_APPCOMMAND:
  203897. if (doAppCommand (lParam))
  203898. return TRUE;
  203899. break;
  203900. case WM_SETFOCUS:
  203901. updateKeyModifiers();
  203902. handleFocusGain();
  203903. break;
  203904. case WM_KILLFOCUS:
  203905. if (hasCreatedCaret)
  203906. {
  203907. hasCreatedCaret = false;
  203908. DestroyCaret();
  203909. }
  203910. handleFocusLoss();
  203911. break;
  203912. case WM_ACTIVATEAPP:
  203913. // Windows does weird things to process priority when you swap apps,
  203914. // so this forces an update when the app is brought to the front
  203915. if (wParam != FALSE)
  203916. juce_repeatLastProcessPriority();
  203917. else
  203918. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  203919. juce_CheckCurrentlyFocusedTopLevelWindow();
  203920. modifiersAtLastCallback = -1;
  203921. return 0;
  203922. case WM_ACTIVATE:
  203923. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  203924. {
  203925. modifiersAtLastCallback = -1;
  203926. updateKeyModifiers();
  203927. if (isMinimised())
  203928. {
  203929. component->repaint();
  203930. handleMovedOrResized();
  203931. if (! ComponentPeer::isValidPeer (this))
  203932. return 0;
  203933. }
  203934. if (LOWORD (wParam) == WA_CLICKACTIVE
  203935. && component->isCurrentlyBlockedByAnotherModalComponent())
  203936. {
  203937. const Point<int> mousePos (component->getMouseXYRelative());
  203938. Component* const underMouse = component->getComponentAt (mousePos.getX(), mousePos.getY());
  203939. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  203940. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  203941. return 0;
  203942. }
  203943. handleBroughtToFront();
  203944. if (component->isCurrentlyBlockedByAnotherModalComponent())
  203945. Component::getCurrentlyModalComponent()->toFront (true);
  203946. return 0;
  203947. }
  203948. break;
  203949. case WM_NCACTIVATE:
  203950. // while a temporary window is being shown, prevent Windows from deactivating the
  203951. // title bars of our main windows.
  203952. if (wParam == 0 && ! shouldDeactivateTitleBar)
  203953. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  203954. break;
  203955. case WM_MOUSEACTIVATE:
  203956. if (! component->getMouseClickGrabsKeyboardFocus())
  203957. return MA_NOACTIVATE;
  203958. break;
  203959. case WM_SHOWWINDOW:
  203960. if (wParam != 0)
  203961. handleBroughtToFront();
  203962. break;
  203963. case WM_CLOSE:
  203964. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  203965. handleUserClosingWindow();
  203966. return 0;
  203967. case WM_QUERYENDSESSION:
  203968. if (JUCEApplication::getInstance() != 0)
  203969. {
  203970. JUCEApplication::getInstance()->systemRequestedQuit();
  203971. return MessageManager::getInstance()->hasStopMessageBeenSent();
  203972. }
  203973. return TRUE;
  203974. case WM_TRAYNOTIFY:
  203975. if (component->isCurrentlyBlockedByAnotherModalComponent())
  203976. {
  203977. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  203978. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  203979. {
  203980. Component* const current = Component::getCurrentlyModalComponent();
  203981. if (current != 0)
  203982. current->inputAttemptWhenModal();
  203983. }
  203984. }
  203985. else
  203986. {
  203987. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  203988. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  203989. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  203990. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  203991. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  203992. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  203993. eventMods = eventMods.withoutMouseButtons();
  203994. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  203995. Point<int>(), eventMods, component, getMouseEventTime(),
  203996. Point<int>(), getMouseEventTime(), 1, false);
  203997. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  203998. {
  203999. SetFocus (hwnd);
  204000. SetForegroundWindow (hwnd);
  204001. component->mouseDown (e);
  204002. }
  204003. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  204004. {
  204005. component->mouseUp (e);
  204006. }
  204007. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  204008. {
  204009. component->mouseDoubleClick (e);
  204010. }
  204011. else if (lParam == WM_MOUSEMOVE)
  204012. {
  204013. component->mouseMove (e);
  204014. }
  204015. }
  204016. break;
  204017. case WM_SYNCPAINT:
  204018. return 0;
  204019. case WM_PALETTECHANGED:
  204020. InvalidateRect (h, 0, 0);
  204021. break;
  204022. case WM_DISPLAYCHANGE:
  204023. InvalidateRect (h, 0, 0);
  204024. createPaletteIfNeeded = true;
  204025. // intentional fall-through...
  204026. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  204027. doSettingChange();
  204028. break;
  204029. case WM_INITMENU:
  204030. if (! hasTitleBar())
  204031. {
  204032. if (isFullScreen())
  204033. {
  204034. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  204035. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  204036. }
  204037. else if (! isMinimised())
  204038. {
  204039. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  204040. }
  204041. }
  204042. break;
  204043. case WM_SYSCOMMAND:
  204044. switch (wParam & 0xfff0)
  204045. {
  204046. case SC_CLOSE:
  204047. if (sendInputAttemptWhenModalMessage())
  204048. return 0;
  204049. if (hasTitleBar())
  204050. {
  204051. PostMessage (h, WM_CLOSE, 0, 0);
  204052. return 0;
  204053. }
  204054. break;
  204055. case SC_KEYMENU:
  204056. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  204057. // obscure situations that can arise if a modal loop is started from an alt-key
  204058. // keypress).
  204059. if (hasTitleBar() && h == GetCapture())
  204060. ReleaseCapture();
  204061. break;
  204062. case SC_MAXIMIZE:
  204063. if (sendInputAttemptWhenModalMessage())
  204064. return 0;
  204065. setFullScreen (true);
  204066. return 0;
  204067. case SC_MINIMIZE:
  204068. if (sendInputAttemptWhenModalMessage())
  204069. return 0;
  204070. if (! hasTitleBar())
  204071. {
  204072. setMinimised (true);
  204073. return 0;
  204074. }
  204075. break;
  204076. case SC_RESTORE:
  204077. if (sendInputAttemptWhenModalMessage())
  204078. return 0;
  204079. if (hasTitleBar())
  204080. {
  204081. if (isFullScreen())
  204082. {
  204083. setFullScreen (false);
  204084. return 0;
  204085. }
  204086. }
  204087. else
  204088. {
  204089. if (isMinimised())
  204090. setMinimised (false);
  204091. else if (isFullScreen())
  204092. setFullScreen (false);
  204093. return 0;
  204094. }
  204095. break;
  204096. }
  204097. break;
  204098. case WM_NCLBUTTONDOWN:
  204099. case WM_NCRBUTTONDOWN:
  204100. case WM_NCMBUTTONDOWN:
  204101. sendInputAttemptWhenModalMessage();
  204102. break;
  204103. //case WM_IME_STARTCOMPOSITION;
  204104. // return 0;
  204105. case WM_GETDLGCODE:
  204106. return DLGC_WANTALLKEYS;
  204107. default:
  204108. break;
  204109. }
  204110. }
  204111. return DefWindowProcW (h, message, wParam, lParam);
  204112. }
  204113. bool sendInputAttemptWhenModalMessage()
  204114. {
  204115. if (component->isCurrentlyBlockedByAnotherModalComponent())
  204116. {
  204117. Component* const current = Component::getCurrentlyModalComponent();
  204118. if (current != 0)
  204119. current->inputAttemptWhenModal();
  204120. return true;
  204121. }
  204122. return false;
  204123. }
  204124. Win32ComponentPeer (const Win32ComponentPeer&);
  204125. Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  204126. };
  204127. ModifierKeys Win32ComponentPeer::currentModifiers;
  204128. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  204129. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  204130. {
  204131. return new Win32ComponentPeer (this, styleFlags);
  204132. }
  204133. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  204134. void ModifierKeys::updateCurrentModifiers() throw()
  204135. {
  204136. currentModifiers = Win32ComponentPeer::currentModifiers;
  204137. }
  204138. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  204139. {
  204140. Win32ComponentPeer::updateKeyModifiers();
  204141. int keyMods = 0;
  204142. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::leftButtonModifier;
  204143. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::rightButtonModifier;
  204144. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::middleButtonModifier;
  204145. Win32ComponentPeer::currentModifiers
  204146. = Win32ComponentPeer::currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  204147. return Win32ComponentPeer::currentModifiers;
  204148. }
  204149. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  204150. {
  204151. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  204152. if (wp != 0)
  204153. wp->setTaskBarIcon (&newImage);
  204154. }
  204155. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  204156. {
  204157. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  204158. if (wp != 0)
  204159. wp->setTaskBarIconToolTip (tooltip);
  204160. }
  204161. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  204162. {
  204163. DWORD val = GetWindowLong (h, styleType);
  204164. if (bitIsSet)
  204165. val |= feature;
  204166. else
  204167. val &= ~feature;
  204168. SetWindowLongPtr (h, styleType, val);
  204169. SetWindowPos (h, 0, 0, 0, 0, 0,
  204170. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  204171. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  204172. }
  204173. bool Process::isForegroundProcess()
  204174. {
  204175. HWND fg = GetForegroundWindow();
  204176. if (fg == 0)
  204177. return true;
  204178. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  204179. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  204180. // have to see if any of our windows are children of the foreground window
  204181. fg = GetAncestor (fg, GA_ROOT);
  204182. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  204183. {
  204184. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  204185. if (wp != 0 && wp->isInside (fg))
  204186. return true;
  204187. }
  204188. return false;
  204189. }
  204190. bool AlertWindow::showNativeDialogBox (const String& title,
  204191. const String& bodyText,
  204192. bool isOkCancel)
  204193. {
  204194. return MessageBox (0, bodyText, title,
  204195. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  204196. : MB_OK)) == IDOK;
  204197. }
  204198. void Desktop::createMouseInputSources()
  204199. {
  204200. mouseSources.add (new MouseInputSource (0, true));
  204201. }
  204202. const Point<int> Desktop::getMousePosition()
  204203. {
  204204. POINT mousePos;
  204205. GetCursorPos (&mousePos);
  204206. return Point<int> (mousePos.x, mousePos.y);
  204207. }
  204208. void Desktop::setMousePosition (const Point<int>& newPosition)
  204209. {
  204210. SetCursorPos (newPosition.getX(), newPosition.getY());
  204211. }
  204212. Image* Image::createNativeImage (const PixelFormat format, const int imageWidth, const int imageHeight, const bool clearImage)
  204213. {
  204214. return new Image (format, imageWidth, imageHeight, clearImage);
  204215. }
  204216. class ScreenSaverDefeater : public Timer,
  204217. public DeletedAtShutdown
  204218. {
  204219. public:
  204220. ScreenSaverDefeater() throw()
  204221. {
  204222. startTimer (10000);
  204223. timerCallback();
  204224. }
  204225. ~ScreenSaverDefeater() {}
  204226. void timerCallback()
  204227. {
  204228. if (Process::isForegroundProcess())
  204229. {
  204230. // simulate a shift key getting pressed..
  204231. INPUT input[2];
  204232. input[0].type = INPUT_KEYBOARD;
  204233. input[0].ki.wVk = VK_SHIFT;
  204234. input[0].ki.dwFlags = 0;
  204235. input[0].ki.dwExtraInfo = 0;
  204236. input[1].type = INPUT_KEYBOARD;
  204237. input[1].ki.wVk = VK_SHIFT;
  204238. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  204239. input[1].ki.dwExtraInfo = 0;
  204240. SendInput (2, input, sizeof (INPUT));
  204241. }
  204242. }
  204243. };
  204244. static ScreenSaverDefeater* screenSaverDefeater = 0;
  204245. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  204246. {
  204247. if (isEnabled)
  204248. {
  204249. deleteAndZero (screenSaverDefeater);
  204250. }
  204251. else if (screenSaverDefeater == 0)
  204252. {
  204253. screenSaverDefeater = new ScreenSaverDefeater();
  204254. }
  204255. }
  204256. bool Desktop::isScreenSaverEnabled() throw()
  204257. {
  204258. return screenSaverDefeater == 0;
  204259. }
  204260. /* (The code below is the "correct" way to disable the screen saver, but it
  204261. completely fails on winXP when the saver is password-protected...)
  204262. static bool juce_screenSaverEnabled = true;
  204263. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  204264. {
  204265. juce_screenSaverEnabled = isEnabled;
  204266. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  204267. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  204268. }
  204269. bool Desktop::isScreenSaverEnabled() throw()
  204270. {
  204271. return juce_screenSaverEnabled;
  204272. }
  204273. */
  204274. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  204275. {
  204276. if (enableOrDisable)
  204277. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  204278. }
  204279. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  204280. {
  204281. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  204282. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  204283. return TRUE;
  204284. }
  204285. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  204286. {
  204287. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  204288. // make sure the first in the list is the main monitor
  204289. for (int i = 1; i < monitorCoords.size(); ++i)
  204290. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  204291. monitorCoords.swap (i, 0);
  204292. if (monitorCoords.size() == 0)
  204293. {
  204294. RECT r;
  204295. GetWindowRect (GetDesktopWindow(), &r);
  204296. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  204297. }
  204298. if (clipToWorkArea)
  204299. {
  204300. // clip the main monitor to the active non-taskbar area
  204301. RECT r;
  204302. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  204303. Rectangle<int>& screen = monitorCoords.getReference (0);
  204304. screen.setPosition (jmax (screen.getX(), (int) r.left),
  204305. jmax (screen.getY(), (int) r.top));
  204306. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  204307. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  204308. }
  204309. }
  204310. static Image* createImageFromHBITMAP (HBITMAP bitmap) throw()
  204311. {
  204312. Image* im = 0;
  204313. if (bitmap != 0)
  204314. {
  204315. BITMAP bm;
  204316. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  204317. && bm.bmWidth > 0 && bm.bmHeight > 0)
  204318. {
  204319. HDC tempDC = GetDC (0);
  204320. HDC dc = CreateCompatibleDC (tempDC);
  204321. ReleaseDC (0, tempDC);
  204322. SelectObject (dc, bitmap);
  204323. im = new Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  204324. for (int y = bm.bmHeight; --y >= 0;)
  204325. {
  204326. for (int x = bm.bmWidth; --x >= 0;)
  204327. {
  204328. COLORREF col = GetPixel (dc, x, y);
  204329. im->setPixelAt (x, y, Colour ((uint8) GetRValue (col),
  204330. (uint8) GetGValue (col),
  204331. (uint8) GetBValue (col)));
  204332. }
  204333. }
  204334. DeleteDC (dc);
  204335. }
  204336. }
  204337. return im;
  204338. }
  204339. static Image* createImageFromHICON (HICON icon) throw()
  204340. {
  204341. ICONINFO info;
  204342. if (GetIconInfo (icon, &info))
  204343. {
  204344. ScopedPointer<Image> mask (createImageFromHBITMAP (info.hbmMask));
  204345. if (mask == 0)
  204346. return 0;
  204347. ScopedPointer<Image> image (createImageFromHBITMAP (info.hbmColor));
  204348. if (image == 0)
  204349. return mask.release();
  204350. for (int y = image->getHeight(); --y >= 0;)
  204351. {
  204352. for (int x = image->getWidth(); --x >= 0;)
  204353. {
  204354. const float brightness = mask->getPixelAt (x, y).getBrightness();
  204355. if (brightness > 0.0f)
  204356. image->multiplyAlphaAt (x, y, 1.0f - brightness);
  204357. }
  204358. }
  204359. return image.release();
  204360. }
  204361. return 0;
  204362. }
  204363. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw()
  204364. {
  204365. WindowsBitmapImage bitmap (Image::ARGB, image.getWidth(), image.getHeight(), true);
  204366. {
  204367. Graphics g (bitmap);
  204368. g.drawImageAt (&image, 0, 0);
  204369. }
  204370. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  204371. ICONINFO info;
  204372. info.fIcon = isIcon;
  204373. info.xHotspot = hotspotX;
  204374. info.yHotspot = hotspotY;
  204375. info.hbmMask = mask;
  204376. info.hbmColor = bitmap.hBitmap;
  204377. HICON hi = CreateIconIndirect (&info);
  204378. DeleteObject (mask);
  204379. return hi;
  204380. }
  204381. Image* juce_createIconForFile (const File& file)
  204382. {
  204383. Image* image = 0;
  204384. WCHAR filename [1024];
  204385. file.getFullPathName().copyToUnicode (filename, 1023);
  204386. WORD iconNum = 0;
  204387. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  204388. filename, &iconNum);
  204389. if (icon != 0)
  204390. {
  204391. image = createImageFromHICON (icon);
  204392. DestroyIcon (icon);
  204393. }
  204394. return image;
  204395. }
  204396. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  204397. {
  204398. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  204399. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  204400. const Image* im = &image;
  204401. ScopedPointer<Image> newIm;
  204402. if (image.getWidth() > maxW || image.getHeight() > maxH)
  204403. {
  204404. im = newIm = image.createCopy (maxW, maxH);
  204405. hotspotX = (hotspotX * maxW) / image.getWidth();
  204406. hotspotY = (hotspotY * maxH) / image.getHeight();
  204407. }
  204408. return createHICONFromImage (*im, FALSE, hotspotX, hotspotY);
  204409. }
  204410. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  204411. {
  204412. if (cursorHandle != 0 && ! isStandard)
  204413. DestroyCursor ((HCURSOR) cursorHandle);
  204414. }
  204415. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  204416. {
  204417. LPCTSTR cursorName = IDC_ARROW;
  204418. switch (type)
  204419. {
  204420. case NormalCursor: break;
  204421. case NoCursor: return 0;
  204422. case WaitCursor: cursorName = IDC_WAIT; break;
  204423. case IBeamCursor: cursorName = IDC_IBEAM; break;
  204424. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  204425. case CrosshairCursor: cursorName = IDC_CROSS; break;
  204426. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  204427. case LeftRightResizeCursor:
  204428. case LeftEdgeResizeCursor:
  204429. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  204430. case UpDownResizeCursor:
  204431. case TopEdgeResizeCursor:
  204432. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  204433. case TopLeftCornerResizeCursor:
  204434. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  204435. case TopRightCornerResizeCursor:
  204436. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  204437. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  204438. case DraggingHandCursor:
  204439. {
  204440. static void* dragHandCursor = 0;
  204441. if (dragHandCursor == 0)
  204442. {
  204443. static const unsigned char dragHandData[] =
  204444. { 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,
  204445. 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,
  204446. 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 };
  204447. const ScopedPointer <Image> image (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)));
  204448. dragHandCursor = createMouseCursorFromImage (*image, 8, 7);
  204449. }
  204450. return dragHandCursor;
  204451. }
  204452. default:
  204453. jassertfalse; break;
  204454. }
  204455. HCURSOR cursorH = LoadCursor (0, cursorName);
  204456. if (cursorH == 0)
  204457. cursorH = LoadCursor (0, IDC_ARROW);
  204458. return cursorH;
  204459. }
  204460. void MouseCursor::showInWindow (ComponentPeer*) const
  204461. {
  204462. SetCursor ((HCURSOR) getHandle());
  204463. }
  204464. void MouseCursor::showInAllWindows() const
  204465. {
  204466. showInWindow (0);
  204467. }
  204468. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  204469. {
  204470. public:
  204471. JuceDropSource() {}
  204472. ~JuceDropSource() {}
  204473. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  204474. {
  204475. if (escapePressed)
  204476. return DRAGDROP_S_CANCEL;
  204477. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  204478. return DRAGDROP_S_DROP;
  204479. return S_OK;
  204480. }
  204481. HRESULT __stdcall GiveFeedback (DWORD)
  204482. {
  204483. return DRAGDROP_S_USEDEFAULTCURSORS;
  204484. }
  204485. };
  204486. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  204487. {
  204488. public:
  204489. JuceEnumFormatEtc (const FORMATETC* const format_)
  204490. : format (format_),
  204491. index (0)
  204492. {
  204493. }
  204494. ~JuceEnumFormatEtc() {}
  204495. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  204496. {
  204497. if (result == 0)
  204498. return E_POINTER;
  204499. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  204500. newOne->index = index;
  204501. *result = newOne;
  204502. return S_OK;
  204503. }
  204504. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  204505. {
  204506. if (pceltFetched != 0)
  204507. *pceltFetched = 0;
  204508. else if (celt != 1)
  204509. return S_FALSE;
  204510. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  204511. {
  204512. copyFormatEtc (lpFormatEtc [0], *format);
  204513. ++index;
  204514. if (pceltFetched != 0)
  204515. *pceltFetched = 1;
  204516. return S_OK;
  204517. }
  204518. return S_FALSE;
  204519. }
  204520. HRESULT __stdcall Skip (ULONG celt)
  204521. {
  204522. if (index + (int) celt >= 1)
  204523. return S_FALSE;
  204524. index += celt;
  204525. return S_OK;
  204526. }
  204527. HRESULT __stdcall Reset()
  204528. {
  204529. index = 0;
  204530. return S_OK;
  204531. }
  204532. private:
  204533. const FORMATETC* const format;
  204534. int index;
  204535. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  204536. {
  204537. dest = source;
  204538. if (source.ptd != 0)
  204539. {
  204540. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  204541. *(dest.ptd) = *(source.ptd);
  204542. }
  204543. }
  204544. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  204545. JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  204546. };
  204547. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  204548. {
  204549. JuceDropSource* const dropSource;
  204550. const FORMATETC* const format;
  204551. const STGMEDIUM* const medium;
  204552. JuceDataObject (const JuceDataObject&);
  204553. JuceDataObject& operator= (const JuceDataObject&);
  204554. public:
  204555. JuceDataObject (JuceDropSource* const dropSource_,
  204556. const FORMATETC* const format_,
  204557. const STGMEDIUM* const medium_)
  204558. : dropSource (dropSource_),
  204559. format (format_),
  204560. medium (medium_)
  204561. {
  204562. }
  204563. virtual ~JuceDataObject()
  204564. {
  204565. jassert (refCount == 0);
  204566. }
  204567. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  204568. {
  204569. if ((pFormatEtc->tymed & format->tymed) != 0
  204570. && pFormatEtc->cfFormat == format->cfFormat
  204571. && pFormatEtc->dwAspect == format->dwAspect)
  204572. {
  204573. pMedium->tymed = format->tymed;
  204574. pMedium->pUnkForRelease = 0;
  204575. if (format->tymed == TYMED_HGLOBAL)
  204576. {
  204577. const SIZE_T len = GlobalSize (medium->hGlobal);
  204578. void* const src = GlobalLock (medium->hGlobal);
  204579. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  204580. memcpy (dst, src, len);
  204581. GlobalUnlock (medium->hGlobal);
  204582. pMedium->hGlobal = dst;
  204583. return S_OK;
  204584. }
  204585. }
  204586. return DV_E_FORMATETC;
  204587. }
  204588. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  204589. {
  204590. if (f == 0)
  204591. return E_INVALIDARG;
  204592. if (f->tymed == format->tymed
  204593. && f->cfFormat == format->cfFormat
  204594. && f->dwAspect == format->dwAspect)
  204595. return S_OK;
  204596. return DV_E_FORMATETC;
  204597. }
  204598. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  204599. {
  204600. pFormatEtcOut->ptd = 0;
  204601. return E_NOTIMPL;
  204602. }
  204603. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  204604. {
  204605. if (result == 0)
  204606. return E_POINTER;
  204607. if (direction == DATADIR_GET)
  204608. {
  204609. *result = new JuceEnumFormatEtc (format);
  204610. return S_OK;
  204611. }
  204612. *result = 0;
  204613. return E_NOTIMPL;
  204614. }
  204615. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  204616. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  204617. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  204618. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  204619. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  204620. };
  204621. static HDROP createHDrop (const StringArray& fileNames) throw()
  204622. {
  204623. int totalChars = 0;
  204624. for (int i = fileNames.size(); --i >= 0;)
  204625. totalChars += fileNames[i].length() + 1;
  204626. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  204627. sizeof (DROPFILES)
  204628. + sizeof (WCHAR) * (totalChars + 2));
  204629. if (hDrop != 0)
  204630. {
  204631. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  204632. pDropFiles->pFiles = sizeof (DROPFILES);
  204633. pDropFiles->fWide = true;
  204634. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  204635. for (int i = 0; i < fileNames.size(); ++i)
  204636. {
  204637. fileNames[i].copyToUnicode (fname, 2048);
  204638. fname += fileNames[i].length() + 1;
  204639. }
  204640. *fname = 0;
  204641. GlobalUnlock (hDrop);
  204642. }
  204643. return hDrop;
  204644. }
  204645. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo) throw()
  204646. {
  204647. JuceDropSource* const source = new JuceDropSource();
  204648. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  204649. DWORD effect;
  204650. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  204651. data->Release();
  204652. source->Release();
  204653. return res == DRAGDROP_S_DROP;
  204654. }
  204655. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  204656. {
  204657. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  204658. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  204659. medium.hGlobal = createHDrop (files);
  204660. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  204661. : DROPEFFECT_COPY);
  204662. }
  204663. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  204664. {
  204665. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  204666. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  204667. const int numChars = text.length();
  204668. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  204669. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  204670. text.copyToUnicode (data, numChars + 1);
  204671. format.cfFormat = CF_UNICODETEXT;
  204672. GlobalUnlock (medium.hGlobal);
  204673. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  204674. }
  204675. #endif
  204676. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  204677. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  204678. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204679. // compiled on its own).
  204680. #if JUCE_INCLUDED_FILE
  204681. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  204682. NEWTEXTMETRICEXW*,
  204683. int type,
  204684. LPARAM lParam)
  204685. {
  204686. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  204687. {
  204688. const String fontName (lpelfe->elfLogFont.lfFaceName);
  204689. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  204690. }
  204691. return 1;
  204692. }
  204693. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  204694. NEWTEXTMETRICEXW*,
  204695. int type,
  204696. LPARAM lParam)
  204697. {
  204698. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  204699. {
  204700. LOGFONTW lf;
  204701. zerostruct (lf);
  204702. lf.lfWeight = FW_DONTCARE;
  204703. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  204704. lf.lfQuality = DEFAULT_QUALITY;
  204705. lf.lfCharSet = DEFAULT_CHARSET;
  204706. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  204707. lf.lfPitchAndFamily = FF_DONTCARE;
  204708. const String fontName (lpelfe->elfLogFont.lfFaceName);
  204709. fontName.copyToUnicode (lf.lfFaceName, LF_FACESIZE - 1);
  204710. HDC dc = CreateCompatibleDC (0);
  204711. EnumFontFamiliesEx (dc, &lf,
  204712. (FONTENUMPROCW) &wfontEnum2,
  204713. lParam, 0);
  204714. DeleteDC (dc);
  204715. }
  204716. return 1;
  204717. }
  204718. const StringArray Font::findAllTypefaceNames()
  204719. {
  204720. StringArray results;
  204721. HDC dc = CreateCompatibleDC (0);
  204722. {
  204723. LOGFONTW lf;
  204724. zerostruct (lf);
  204725. lf.lfWeight = FW_DONTCARE;
  204726. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  204727. lf.lfQuality = DEFAULT_QUALITY;
  204728. lf.lfCharSet = DEFAULT_CHARSET;
  204729. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  204730. lf.lfPitchAndFamily = FF_DONTCARE;
  204731. lf.lfFaceName[0] = 0;
  204732. EnumFontFamiliesEx (dc, &lf,
  204733. (FONTENUMPROCW) &wfontEnum1,
  204734. (LPARAM) &results, 0);
  204735. }
  204736. DeleteDC (dc);
  204737. results.sort (true);
  204738. return results;
  204739. }
  204740. extern bool juce_IsRunningInWine();
  204741. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  204742. {
  204743. if (juce_IsRunningInWine())
  204744. {
  204745. // If we're running in Wine, then use fonts that might be available on Linux..
  204746. defaultSans = "Bitstream Vera Sans";
  204747. defaultSerif = "Bitstream Vera Serif";
  204748. defaultFixed = "Bitstream Vera Sans Mono";
  204749. }
  204750. else
  204751. {
  204752. defaultSans = "Verdana";
  204753. defaultSerif = "Times";
  204754. defaultFixed = "Lucida Console";
  204755. }
  204756. }
  204757. class FontDCHolder : private DeletedAtShutdown
  204758. {
  204759. public:
  204760. FontDCHolder()
  204761. : dc (0), numKPs (0), size (0),
  204762. bold (false), italic (false)
  204763. {
  204764. }
  204765. ~FontDCHolder()
  204766. {
  204767. if (dc != 0)
  204768. {
  204769. DeleteDC (dc);
  204770. DeleteObject (fontH);
  204771. }
  204772. clearSingletonInstance();
  204773. }
  204774. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  204775. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  204776. {
  204777. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  204778. {
  204779. fontName = fontName_;
  204780. bold = bold_;
  204781. italic = italic_;
  204782. size = size_;
  204783. if (dc != 0)
  204784. {
  204785. DeleteDC (dc);
  204786. DeleteObject (fontH);
  204787. kps.free();
  204788. }
  204789. fontH = 0;
  204790. dc = CreateCompatibleDC (0);
  204791. SetMapperFlags (dc, 0);
  204792. SetMapMode (dc, MM_TEXT);
  204793. LOGFONTW lfw;
  204794. zerostruct (lfw);
  204795. lfw.lfCharSet = DEFAULT_CHARSET;
  204796. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  204797. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  204798. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  204799. lfw.lfQuality = PROOF_QUALITY;
  204800. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  204801. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  204802. fontName.copyToUnicode (lfw.lfFaceName, LF_FACESIZE - 1);
  204803. lfw.lfHeight = size > 0 ? size : -256;
  204804. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  204805. if (standardSizedFont != 0)
  204806. {
  204807. if (SelectObject (dc, standardSizedFont) != 0)
  204808. {
  204809. fontH = standardSizedFont;
  204810. if (size == 0)
  204811. {
  204812. OUTLINETEXTMETRIC otm;
  204813. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  204814. {
  204815. lfw.lfHeight = -(int) otm.otmEMSquare;
  204816. fontH = CreateFontIndirect (&lfw);
  204817. SelectObject (dc, fontH);
  204818. DeleteObject (standardSizedFont);
  204819. }
  204820. }
  204821. }
  204822. else
  204823. {
  204824. jassertfalse
  204825. }
  204826. }
  204827. else
  204828. {
  204829. jassertfalse
  204830. }
  204831. }
  204832. return dc;
  204833. }
  204834. KERNINGPAIR* getKerningPairs (int& numKPs_)
  204835. {
  204836. if (kps == 0)
  204837. {
  204838. numKPs = GetKerningPairs (dc, 0, 0);
  204839. kps.calloc (numKPs);
  204840. GetKerningPairs (dc, numKPs, kps);
  204841. }
  204842. numKPs_ = numKPs;
  204843. return kps;
  204844. }
  204845. private:
  204846. HFONT fontH;
  204847. HDC dc;
  204848. String fontName;
  204849. HeapBlock <KERNINGPAIR> kps;
  204850. int numKPs, size;
  204851. bool bold, italic;
  204852. FontDCHolder (const FontDCHolder&);
  204853. FontDCHolder& operator= (const FontDCHolder&);
  204854. };
  204855. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  204856. class WindowsTypeface : public CustomTypeface
  204857. {
  204858. public:
  204859. WindowsTypeface (const Font& font)
  204860. {
  204861. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  204862. font.isBold(), font.isItalic(), 0);
  204863. TEXTMETRIC tm;
  204864. tm.tmAscent = tm.tmHeight = 1;
  204865. tm.tmDefaultChar = 0;
  204866. GetTextMetrics (dc, &tm);
  204867. setCharacteristics (font.getTypefaceName(),
  204868. tm.tmAscent / (float) tm.tmHeight,
  204869. font.isBold(), font.isItalic(),
  204870. tm.tmDefaultChar);
  204871. }
  204872. bool loadGlyphIfPossible (juce_wchar character)
  204873. {
  204874. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  204875. GLYPHMETRICS gm;
  204876. {
  204877. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  204878. WORD index = 0;
  204879. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  204880. && index == 0xffff)
  204881. {
  204882. return false;
  204883. }
  204884. }
  204885. Path glyphPath;
  204886. TEXTMETRIC tm;
  204887. if (! GetTextMetrics (dc, &tm))
  204888. {
  204889. addGlyph (character, glyphPath, 0);
  204890. return true;
  204891. }
  204892. const float height = (float) tm.tmHeight;
  204893. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  204894. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  204895. &gm, 0, 0, &identityMatrix);
  204896. if (bufSize > 0)
  204897. {
  204898. HeapBlock<char> data (bufSize);
  204899. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  204900. bufSize, data, &identityMatrix);
  204901. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  204902. const float scaleX = 1.0f / height;
  204903. const float scaleY = -1.0f / height;
  204904. while ((char*) pheader < data + bufSize)
  204905. {
  204906. float x = scaleX * pheader->pfxStart.x.value;
  204907. float y = scaleY * pheader->pfxStart.y.value;
  204908. glyphPath.startNewSubPath (x, y);
  204909. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  204910. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  204911. while ((const char*) curve < curveEnd)
  204912. {
  204913. if (curve->wType == TT_PRIM_LINE)
  204914. {
  204915. for (int i = 0; i < curve->cpfx; ++i)
  204916. {
  204917. x = scaleX * curve->apfx[i].x.value;
  204918. y = scaleY * curve->apfx[i].y.value;
  204919. glyphPath.lineTo (x, y);
  204920. }
  204921. }
  204922. else if (curve->wType == TT_PRIM_QSPLINE)
  204923. {
  204924. for (int i = 0; i < curve->cpfx - 1; ++i)
  204925. {
  204926. const float x2 = scaleX * curve->apfx[i].x.value;
  204927. const float y2 = scaleY * curve->apfx[i].y.value;
  204928. float x3, y3;
  204929. if (i < curve->cpfx - 2)
  204930. {
  204931. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  204932. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  204933. }
  204934. else
  204935. {
  204936. x3 = scaleX * curve->apfx[i + 1].x.value;
  204937. y3 = scaleY * curve->apfx[i + 1].y.value;
  204938. }
  204939. glyphPath.quadraticTo (x2, y2, x3, y3);
  204940. x = x3;
  204941. y = y3;
  204942. }
  204943. }
  204944. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  204945. }
  204946. pheader = (const TTPOLYGONHEADER*) curve;
  204947. glyphPath.closeSubPath();
  204948. }
  204949. }
  204950. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  204951. int numKPs;
  204952. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  204953. for (int i = 0; i < numKPs; ++i)
  204954. {
  204955. if (kps[i].wFirst == character)
  204956. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  204957. kps[i].iKernAmount / height);
  204958. }
  204959. return true;
  204960. }
  204961. };
  204962. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  204963. {
  204964. return new WindowsTypeface (font);
  204965. }
  204966. #endif
  204967. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  204968. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  204969. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204970. // compiled on its own).
  204971. #if JUCE_INCLUDED_FILE
  204972. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw();
  204973. namespace FileChooserHelpers
  204974. {
  204975. static const void* defaultDirPath = 0;
  204976. static String returnedString; // need this to get non-existent pathnames from the directory chooser
  204977. static Component* currentExtraFileWin = 0;
  204978. static bool areThereAnyAlwaysOnTopWindows()
  204979. {
  204980. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  204981. {
  204982. Component* c = Desktop::getInstance().getComponent (i);
  204983. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  204984. return true;
  204985. }
  204986. return false;
  204987. }
  204988. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM /*lpData*/)
  204989. {
  204990. if (msg == BFFM_INITIALIZED)
  204991. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) defaultDirPath);
  204992. else if (msg == BFFM_VALIDATEFAILEDW)
  204993. returnedString = (LPCWSTR) lParam;
  204994. else if (msg == BFFM_VALIDATEFAILEDA)
  204995. returnedString = (const char*) lParam;
  204996. return 0;
  204997. }
  204998. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  204999. {
  205000. if (currentExtraFileWin != 0)
  205001. {
  205002. if (uiMsg == WM_INITDIALOG)
  205003. {
  205004. HWND dialogH = GetParent (hdlg);
  205005. jassert (dialogH != 0);
  205006. if (dialogH == 0)
  205007. dialogH = hdlg;
  205008. RECT r, cr;
  205009. GetWindowRect (dialogH, &r);
  205010. GetClientRect (dialogH, &cr);
  205011. SetWindowPos (dialogH, 0,
  205012. r.left, r.top,
  205013. currentExtraFileWin->getWidth() + jmax (150, (int) (r.right - r.left)),
  205014. jmax (150, (int) (r.bottom - r.top)),
  205015. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  205016. currentExtraFileWin->setBounds (cr.right, cr.top, currentExtraFileWin->getWidth(), cr.bottom - cr.top);
  205017. currentExtraFileWin->getChildComponent(0)->setBounds (0, 0, currentExtraFileWin->getWidth(), currentExtraFileWin->getHeight());
  205018. SetParent ((HWND) currentExtraFileWin->getWindowHandle(), (HWND) dialogH);
  205019. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_CHILD, (dialogH != 0));
  205020. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_POPUP, (dialogH == 0));
  205021. }
  205022. else if (uiMsg == WM_NOTIFY)
  205023. {
  205024. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  205025. if (ofn->hdr.code == CDN_SELCHANGE)
  205026. {
  205027. FilePreviewComponent* comp = (FilePreviewComponent*) currentExtraFileWin->getChildComponent(0);
  205028. if (comp != 0)
  205029. {
  205030. TCHAR path [MAX_PATH * 2];
  205031. path[0] = 0;
  205032. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  205033. const String fn ((const WCHAR*) path);
  205034. comp->selectedFileChanged (File (fn));
  205035. }
  205036. }
  205037. }
  205038. }
  205039. return 0;
  205040. }
  205041. class FPComponentHolder : public Component
  205042. {
  205043. public:
  205044. FPComponentHolder()
  205045. {
  205046. setVisible (true);
  205047. setOpaque (true);
  205048. }
  205049. ~FPComponentHolder()
  205050. {
  205051. }
  205052. void paint (Graphics& g)
  205053. {
  205054. g.fillAll (Colours::lightgrey);
  205055. }
  205056. private:
  205057. FPComponentHolder (const FPComponentHolder&);
  205058. FPComponentHolder& operator= (const FPComponentHolder&);
  205059. };
  205060. }
  205061. void FileChooser::showPlatformDialog (Array<File>& results,
  205062. const String& title,
  205063. const File& currentFileOrDirectory,
  205064. const String& filter,
  205065. bool selectsDirectory,
  205066. bool /*selectsFiles*/,
  205067. bool isSaveDialogue,
  205068. bool warnAboutOverwritingExistingFiles,
  205069. bool selectMultipleFiles,
  205070. FilePreviewComponent* extraInfoComponent)
  205071. {
  205072. using namespace FileChooserHelpers;
  205073. const int numCharsAvailable = 32768;
  205074. MemoryBlock filenameSpace ((numCharsAvailable + 1) * sizeof (WCHAR), true);
  205075. WCHAR* const fname = (WCHAR*) filenameSpace.getData();
  205076. int fnameIdx = 0;
  205077. JUCE_TRY
  205078. {
  205079. // use a modal window as the parent for this dialog box
  205080. // to block input from other app windows
  205081. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  205082. Component w (String::empty);
  205083. w.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  205084. mainMon.getY() + mainMon.getHeight() / 4,
  205085. 0, 0);
  205086. w.setOpaque (true);
  205087. w.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  205088. w.addToDesktop (0);
  205089. if (extraInfoComponent == 0)
  205090. w.enterModalState();
  205091. String initialDir;
  205092. if (currentFileOrDirectory.isDirectory())
  205093. {
  205094. initialDir = currentFileOrDirectory.getFullPathName();
  205095. }
  205096. else
  205097. {
  205098. currentFileOrDirectory.getFileName().copyToUnicode (fname, numCharsAvailable);
  205099. initialDir = currentFileOrDirectory.getParentDirectory().getFullPathName();
  205100. }
  205101. if (currentExtraFileWin->isValidComponent())
  205102. {
  205103. jassertfalse
  205104. return;
  205105. }
  205106. if (selectsDirectory)
  205107. {
  205108. LPITEMIDLIST list = 0;
  205109. filenameSpace.fillWith (0);
  205110. {
  205111. BROWSEINFO bi;
  205112. zerostruct (bi);
  205113. bi.hwndOwner = (HWND) w.getWindowHandle();
  205114. bi.pszDisplayName = fname;
  205115. bi.lpszTitle = title;
  205116. bi.lpfn = browseCallbackProc;
  205117. #ifdef BIF_USENEWUI
  205118. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  205119. #else
  205120. bi.ulFlags = 0x50;
  205121. #endif
  205122. defaultDirPath = (const WCHAR*) initialDir;
  205123. list = SHBrowseForFolder (&bi);
  205124. if (! SHGetPathFromIDListW (list, fname))
  205125. {
  205126. fname[0] = 0;
  205127. returnedString = String::empty;
  205128. }
  205129. }
  205130. LPMALLOC al;
  205131. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  205132. al->Free (list);
  205133. defaultDirPath = 0;
  205134. if (returnedString.isNotEmpty())
  205135. {
  205136. const String stringFName (fname);
  205137. results.add (File (stringFName).getSiblingFile (returnedString));
  205138. returnedString = String::empty;
  205139. return;
  205140. }
  205141. }
  205142. else
  205143. {
  205144. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  205145. if (warnAboutOverwritingExistingFiles)
  205146. flags |= OFN_OVERWRITEPROMPT;
  205147. if (selectMultipleFiles)
  205148. flags |= OFN_ALLOWMULTISELECT;
  205149. if (extraInfoComponent != 0)
  205150. {
  205151. flags |= OFN_ENABLEHOOK;
  205152. currentExtraFileWin = new FPComponentHolder();
  205153. currentExtraFileWin->addAndMakeVisible (extraInfoComponent);
  205154. currentExtraFileWin->setSize (jlimit (20, 800, extraInfoComponent->getWidth()),
  205155. extraInfoComponent->getHeight());
  205156. currentExtraFileWin->addToDesktop (0);
  205157. currentExtraFileWin->enterModalState();
  205158. }
  205159. {
  205160. WCHAR filters [1024];
  205161. zeromem (filters, sizeof (filters));
  205162. filter.copyToUnicode (filters, 1024);
  205163. filter.copyToUnicode (filters + filter.length() + 1,
  205164. 1022 - filter.length());
  205165. OPENFILENAMEW of;
  205166. zerostruct (of);
  205167. #ifdef OPENFILENAME_SIZE_VERSION_400W
  205168. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  205169. #else
  205170. of.lStructSize = sizeof (of);
  205171. #endif
  205172. of.hwndOwner = (HWND) w.getWindowHandle();
  205173. of.lpstrFilter = filters;
  205174. of.nFilterIndex = 1;
  205175. of.lpstrFile = fname;
  205176. of.nMaxFile = numCharsAvailable;
  205177. of.lpstrInitialDir = initialDir;
  205178. of.lpstrTitle = title;
  205179. of.Flags = flags;
  205180. if (extraInfoComponent != 0)
  205181. of.lpfnHook = &openCallback;
  205182. if (isSaveDialogue)
  205183. {
  205184. if (! GetSaveFileName (&of))
  205185. fname[0] = 0;
  205186. else
  205187. fnameIdx = of.nFileOffset;
  205188. }
  205189. else
  205190. {
  205191. if (! GetOpenFileName (&of))
  205192. fname[0] = 0;
  205193. else
  205194. fnameIdx = of.nFileOffset;
  205195. }
  205196. }
  205197. }
  205198. }
  205199. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  205200. catch (...)
  205201. {
  205202. fname[0] = 0;
  205203. }
  205204. #endif
  205205. deleteAndZero (currentExtraFileWin);
  205206. const WCHAR* const files = fname;
  205207. if (selectMultipleFiles && fnameIdx > 0 && files [fnameIdx - 1] == 0)
  205208. {
  205209. const WCHAR* filename = files + fnameIdx;
  205210. while (*filename != 0)
  205211. {
  205212. const String filepath (String (files) + "\\" + String (filename));
  205213. results.add (File (filepath));
  205214. filename += CharacterFunctions::length (filename) + 1;
  205215. }
  205216. }
  205217. else if (files[0] != 0)
  205218. {
  205219. results.add (File (files));
  205220. }
  205221. }
  205222. #endif
  205223. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  205224. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  205225. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205226. // compiled on its own).
  205227. #if JUCE_INCLUDED_FILE
  205228. void SystemClipboard::copyTextToClipboard (const String& text)
  205229. {
  205230. if (OpenClipboard (0) != 0)
  205231. {
  205232. if (EmptyClipboard() != 0)
  205233. {
  205234. const int len = text.length();
  205235. if (len > 0)
  205236. {
  205237. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  205238. (len + 1) * sizeof (wchar_t));
  205239. if (bufH != 0)
  205240. {
  205241. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  205242. text.copyToUnicode (data, len);
  205243. GlobalUnlock (bufH);
  205244. SetClipboardData (CF_UNICODETEXT, bufH);
  205245. }
  205246. }
  205247. }
  205248. CloseClipboard();
  205249. }
  205250. }
  205251. const String SystemClipboard::getTextFromClipboard()
  205252. {
  205253. String result;
  205254. if (OpenClipboard (0) != 0)
  205255. {
  205256. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  205257. if (bufH != 0)
  205258. {
  205259. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  205260. if (data != 0)
  205261. {
  205262. result = String (data, (int) (GlobalSize (bufH) / sizeof (wchar_t)));
  205263. GlobalUnlock (bufH);
  205264. }
  205265. }
  205266. CloseClipboard();
  205267. }
  205268. return result;
  205269. }
  205270. #endif
  205271. /*** End of inlined file: juce_win32_Misc.cpp ***/
  205272. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  205273. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205274. // compiled on its own).
  205275. #if JUCE_INCLUDED_FILE
  205276. namespace ActiveXHelpers
  205277. {
  205278. class JuceIStorage : public ComBaseClassHelper <IStorage>
  205279. {
  205280. public:
  205281. JuceIStorage() {}
  205282. ~JuceIStorage() {}
  205283. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  205284. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  205285. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  205286. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  205287. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  205288. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  205289. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  205290. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  205291. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  205292. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  205293. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  205294. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  205295. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  205296. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  205297. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  205298. juce_UseDebuggingNewOperator
  205299. };
  205300. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  205301. {
  205302. HWND window;
  205303. public:
  205304. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  205305. ~JuceOleInPlaceFrame() {}
  205306. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  205307. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  205308. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  205309. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  205310. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  205311. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  205312. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  205313. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  205314. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  205315. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  205316. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  205317. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  205318. juce_UseDebuggingNewOperator
  205319. };
  205320. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  205321. {
  205322. HWND window;
  205323. JuceOleInPlaceFrame* frame;
  205324. public:
  205325. JuceIOleInPlaceSite (HWND window_)
  205326. : window (window_),
  205327. frame (new JuceOleInPlaceFrame (window))
  205328. {}
  205329. ~JuceIOleInPlaceSite()
  205330. {
  205331. frame->Release();
  205332. }
  205333. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  205334. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  205335. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  205336. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  205337. HRESULT __stdcall OnUIActivate() { return S_OK; }
  205338. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  205339. {
  205340. *lplpFrame = frame;
  205341. *lplpDoc = 0;
  205342. lpFrameInfo->fMDIApp = FALSE;
  205343. lpFrameInfo->hwndFrame = window;
  205344. lpFrameInfo->haccel = 0;
  205345. lpFrameInfo->cAccelEntries = 0;
  205346. return S_OK;
  205347. }
  205348. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  205349. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  205350. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  205351. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  205352. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  205353. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  205354. juce_UseDebuggingNewOperator
  205355. };
  205356. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  205357. {
  205358. JuceIOleInPlaceSite* inplaceSite;
  205359. public:
  205360. JuceIOleClientSite (HWND window)
  205361. : inplaceSite (new JuceIOleInPlaceSite (window))
  205362. {}
  205363. ~JuceIOleClientSite()
  205364. {
  205365. inplaceSite->Release();
  205366. }
  205367. HRESULT __stdcall QueryInterface (REFIID type, void __RPC_FAR* __RPC_FAR* result)
  205368. {
  205369. if (type == IID_IOleInPlaceSite)
  205370. {
  205371. inplaceSite->AddRef();
  205372. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  205373. return S_OK;
  205374. }
  205375. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  205376. }
  205377. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  205378. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  205379. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  205380. HRESULT __stdcall ShowObject() { return S_OK; }
  205381. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  205382. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  205383. juce_UseDebuggingNewOperator
  205384. };
  205385. static VoidArray activeXComps;
  205386. static HWND getHWND (const ActiveXControlComponent* const component)
  205387. {
  205388. HWND hwnd = 0;
  205389. const IID iid = IID_IOleWindow;
  205390. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  205391. if (window != 0)
  205392. {
  205393. window->GetWindow (&hwnd);
  205394. window->Release();
  205395. }
  205396. return hwnd;
  205397. }
  205398. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  205399. {
  205400. RECT activeXRect, peerRect;
  205401. GetWindowRect (hwnd, &activeXRect);
  205402. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  205403. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  205404. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  205405. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  205406. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  205407. switch (message)
  205408. {
  205409. case WM_MOUSEMOVE:
  205410. case WM_LBUTTONDOWN:
  205411. case WM_MBUTTONDOWN:
  205412. case WM_RBUTTONDOWN:
  205413. case WM_LBUTTONUP:
  205414. case WM_MBUTTONUP:
  205415. case WM_RBUTTONUP:
  205416. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  205417. break;
  205418. default:
  205419. break;
  205420. }
  205421. }
  205422. }
  205423. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  205424. {
  205425. ActiveXControlComponent* const owner;
  205426. bool wasShowing;
  205427. public:
  205428. HWND controlHWND;
  205429. IStorage* storage;
  205430. IOleClientSite* clientSite;
  205431. IOleObject* control;
  205432. Pimpl (HWND hwnd, ActiveXControlComponent* const owner_)
  205433. : ComponentMovementWatcher (owner_),
  205434. owner (owner_),
  205435. wasShowing (owner_ != 0 && owner_->isShowing()),
  205436. controlHWND (0),
  205437. storage (new ActiveXHelpers::JuceIStorage()),
  205438. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  205439. control (0)
  205440. {
  205441. }
  205442. ~Pimpl()
  205443. {
  205444. if (control != 0)
  205445. {
  205446. control->Close (OLECLOSE_NOSAVE);
  205447. control->Release();
  205448. }
  205449. clientSite->Release();
  205450. storage->Release();
  205451. }
  205452. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  205453. {
  205454. Component* const topComp = owner->getTopLevelComponent();
  205455. if (topComp->getPeer() != 0)
  205456. {
  205457. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  205458. owner->setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner->getWidth(), owner->getHeight()));
  205459. }
  205460. }
  205461. void componentPeerChanged()
  205462. {
  205463. const bool isShowingNow = owner->isShowing();
  205464. if (wasShowing != isShowingNow)
  205465. {
  205466. wasShowing = isShowingNow;
  205467. owner->setControlVisible (isShowingNow);
  205468. }
  205469. componentMovedOrResized (true, true);
  205470. }
  205471. void componentVisibilityChanged (Component&)
  205472. {
  205473. componentPeerChanged();
  205474. }
  205475. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  205476. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  205477. {
  205478. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  205479. {
  205480. const ActiveXControlComponent* const ax
  205481. = static_cast <const ActiveXControlComponent*> (ActiveXHelpers::activeXComps.getUnchecked(i));
  205482. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  205483. {
  205484. switch (message)
  205485. {
  205486. case WM_MOUSEMOVE:
  205487. case WM_LBUTTONDOWN:
  205488. case WM_MBUTTONDOWN:
  205489. case WM_RBUTTONDOWN:
  205490. case WM_LBUTTONUP:
  205491. case WM_MBUTTONUP:
  205492. case WM_RBUTTONUP:
  205493. case WM_LBUTTONDBLCLK:
  205494. case WM_MBUTTONDBLCLK:
  205495. case WM_RBUTTONDBLCLK:
  205496. if (ax->isShowing())
  205497. {
  205498. ComponentPeer* const peer = ax->getPeer();
  205499. if (peer != 0)
  205500. {
  205501. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  205502. if (! ax->areMouseEventsAllowed())
  205503. return 0;
  205504. }
  205505. }
  205506. break;
  205507. default:
  205508. break;
  205509. }
  205510. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  205511. }
  205512. }
  205513. return DefWindowProc (hwnd, message, wParam, lParam);
  205514. }
  205515. };
  205516. ActiveXControlComponent::ActiveXControlComponent()
  205517. : originalWndProc (0),
  205518. mouseEventsAllowed (true)
  205519. {
  205520. ActiveXHelpers::activeXComps.add (this);
  205521. }
  205522. ActiveXControlComponent::~ActiveXControlComponent()
  205523. {
  205524. deleteControl();
  205525. ActiveXHelpers::activeXComps.removeValue (this);
  205526. }
  205527. void ActiveXControlComponent::paint (Graphics& g)
  205528. {
  205529. if (control == 0)
  205530. g.fillAll (Colours::lightgrey);
  205531. }
  205532. bool ActiveXControlComponent::createControl (const void* controlIID)
  205533. {
  205534. deleteControl();
  205535. ComponentPeer* const peer = getPeer();
  205536. // the component must have already been added to a real window when you call this!
  205537. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  205538. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  205539. {
  205540. const Point<int> pos (relativePositionToOtherComponent (getTopLevelComponent(), Point<int>()));
  205541. HWND hwnd = (HWND) peer->getNativeHandle();
  205542. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, this));
  205543. HRESULT hr;
  205544. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  205545. newControl->clientSite, newControl->storage,
  205546. (void**) &(newControl->control))) == S_OK)
  205547. {
  205548. newControl->control->SetHostNames (L"Juce", 0);
  205549. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  205550. {
  205551. RECT rect;
  205552. rect.left = pos.getX();
  205553. rect.top = pos.getY();
  205554. rect.right = pos.getX() + getWidth();
  205555. rect.bottom = pos.getY() + getHeight();
  205556. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  205557. {
  205558. control = newControl;
  205559. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  205560. control->controlHWND = ActiveXHelpers::getHWND (this);
  205561. if (control->controlHWND != 0)
  205562. {
  205563. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  205564. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  205565. }
  205566. return true;
  205567. }
  205568. }
  205569. }
  205570. }
  205571. return false;
  205572. }
  205573. void ActiveXControlComponent::deleteControl()
  205574. {
  205575. control = 0;
  205576. originalWndProc = 0;
  205577. }
  205578. void* ActiveXControlComponent::queryInterface (const void* iid) const
  205579. {
  205580. void* result = 0;
  205581. if (control != 0 && control->control != 0
  205582. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  205583. return result;
  205584. return 0;
  205585. }
  205586. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  205587. {
  205588. if (control->controlHWND != 0)
  205589. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  205590. }
  205591. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  205592. {
  205593. if (control->controlHWND != 0)
  205594. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  205595. }
  205596. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  205597. {
  205598. mouseEventsAllowed = eventsCanReachControl;
  205599. }
  205600. #endif
  205601. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  205602. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  205603. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205604. // compiled on its own).
  205605. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  205606. using namespace QTOLibrary;
  205607. using namespace QTOControlLib;
  205608. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  205609. static bool isQTAvailable = false;
  205610. class QuickTimeMovieComponent::Pimpl
  205611. {
  205612. public:
  205613. Pimpl() : dataHandle (0)
  205614. {
  205615. }
  205616. ~Pimpl()
  205617. {
  205618. clearHandle();
  205619. }
  205620. void clearHandle()
  205621. {
  205622. if (dataHandle != 0)
  205623. {
  205624. DisposeHandle (dataHandle);
  205625. dataHandle = 0;
  205626. }
  205627. }
  205628. IQTControlPtr qtControl;
  205629. IQTMoviePtr qtMovie;
  205630. Handle dataHandle;
  205631. };
  205632. QuickTimeMovieComponent::QuickTimeMovieComponent()
  205633. : movieLoaded (false),
  205634. controllerVisible (true)
  205635. {
  205636. pimpl = new Pimpl();
  205637. setMouseEventsAllowed (false);
  205638. }
  205639. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  205640. {
  205641. closeMovie();
  205642. pimpl->qtControl = 0;
  205643. deleteControl();
  205644. pimpl = 0;
  205645. }
  205646. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  205647. {
  205648. if (! isQTAvailable)
  205649. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  205650. return isQTAvailable;
  205651. }
  205652. void QuickTimeMovieComponent::createControlIfNeeded()
  205653. {
  205654. if (isShowing() && ! isControlCreated())
  205655. {
  205656. const IID qtIID = __uuidof (QTControl);
  205657. if (createControl (&qtIID))
  205658. {
  205659. const IID qtInterfaceIID = __uuidof (IQTControl);
  205660. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  205661. if (pimpl->qtControl != 0)
  205662. {
  205663. pimpl->qtControl->Release(); // it has one ref too many at this point
  205664. pimpl->qtControl->QuickTimeInitialize();
  205665. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  205666. if (movieFile != File::nonexistent)
  205667. loadMovie (movieFile, controllerVisible);
  205668. }
  205669. }
  205670. }
  205671. }
  205672. bool QuickTimeMovieComponent::isControlCreated() const
  205673. {
  205674. return isControlOpen();
  205675. }
  205676. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  205677. const bool isControllerVisible)
  205678. {
  205679. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  205680. movieFile = File::nonexistent;
  205681. movieLoaded = false;
  205682. pimpl->qtMovie = 0;
  205683. controllerVisible = isControllerVisible;
  205684. createControlIfNeeded();
  205685. if (isControlCreated())
  205686. {
  205687. if (pimpl->qtControl != 0)
  205688. {
  205689. pimpl->qtControl->Put_MovieHandle (0);
  205690. pimpl->clearHandle();
  205691. Movie movie;
  205692. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  205693. {
  205694. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  205695. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  205696. if (pimpl->qtMovie != 0)
  205697. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  205698. : qtMovieControllerTypeNone);
  205699. }
  205700. if (movie == 0)
  205701. pimpl->clearHandle();
  205702. }
  205703. movieLoaded = (pimpl->qtMovie != 0);
  205704. }
  205705. else
  205706. {
  205707. // You're trying to open a movie when the control hasn't yet been created, probably because
  205708. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  205709. jassertfalse
  205710. }
  205711. return movieLoaded;
  205712. }
  205713. void QuickTimeMovieComponent::closeMovie()
  205714. {
  205715. stop();
  205716. movieFile = File::nonexistent;
  205717. movieLoaded = false;
  205718. pimpl->qtMovie = 0;
  205719. if (pimpl->qtControl != 0)
  205720. pimpl->qtControl->Put_MovieHandle (0);
  205721. pimpl->clearHandle();
  205722. }
  205723. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  205724. {
  205725. return movieFile;
  205726. }
  205727. bool QuickTimeMovieComponent::isMovieOpen() const
  205728. {
  205729. return movieLoaded;
  205730. }
  205731. double QuickTimeMovieComponent::getMovieDuration() const
  205732. {
  205733. if (pimpl->qtMovie != 0)
  205734. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  205735. return 0.0;
  205736. }
  205737. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  205738. {
  205739. if (pimpl->qtMovie != 0)
  205740. {
  205741. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  205742. width = r.right - r.left;
  205743. height = r.bottom - r.top;
  205744. }
  205745. else
  205746. {
  205747. width = height = 0;
  205748. }
  205749. }
  205750. void QuickTimeMovieComponent::play()
  205751. {
  205752. if (pimpl->qtMovie != 0)
  205753. pimpl->qtMovie->Play();
  205754. }
  205755. void QuickTimeMovieComponent::stop()
  205756. {
  205757. if (pimpl->qtMovie != 0)
  205758. pimpl->qtMovie->Stop();
  205759. }
  205760. bool QuickTimeMovieComponent::isPlaying() const
  205761. {
  205762. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  205763. }
  205764. void QuickTimeMovieComponent::setPosition (const double seconds)
  205765. {
  205766. if (pimpl->qtMovie != 0)
  205767. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  205768. }
  205769. double QuickTimeMovieComponent::getPosition() const
  205770. {
  205771. if (pimpl->qtMovie != 0)
  205772. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  205773. return 0.0;
  205774. }
  205775. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  205776. {
  205777. if (pimpl->qtMovie != 0)
  205778. pimpl->qtMovie->PutRate (newSpeed);
  205779. }
  205780. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  205781. {
  205782. if (pimpl->qtMovie != 0)
  205783. {
  205784. pimpl->qtMovie->PutAudioVolume (newVolume);
  205785. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  205786. }
  205787. }
  205788. float QuickTimeMovieComponent::getMovieVolume() const
  205789. {
  205790. if (pimpl->qtMovie != 0)
  205791. return pimpl->qtMovie->GetAudioVolume();
  205792. return 0.0f;
  205793. }
  205794. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  205795. {
  205796. if (pimpl->qtMovie != 0)
  205797. pimpl->qtMovie->PutLoop (shouldLoop);
  205798. }
  205799. bool QuickTimeMovieComponent::isLooping() const
  205800. {
  205801. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  205802. }
  205803. bool QuickTimeMovieComponent::isControllerVisible() const
  205804. {
  205805. return controllerVisible;
  205806. }
  205807. void QuickTimeMovieComponent::parentHierarchyChanged()
  205808. {
  205809. createControlIfNeeded();
  205810. QTCompBaseClass::parentHierarchyChanged();
  205811. }
  205812. void QuickTimeMovieComponent::visibilityChanged()
  205813. {
  205814. createControlIfNeeded();
  205815. QTCompBaseClass::visibilityChanged();
  205816. }
  205817. void QuickTimeMovieComponent::paint (Graphics& g)
  205818. {
  205819. if (! isControlCreated())
  205820. g.fillAll (Colours::black);
  205821. }
  205822. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  205823. {
  205824. Handle dataRef = 0;
  205825. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  205826. if (err == noErr)
  205827. {
  205828. Str255 suffix;
  205829. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  205830. StringPtr name = suffix;
  205831. err = PtrAndHand (name, dataRef, name[0] + 1);
  205832. if (err == noErr)
  205833. {
  205834. long atoms[3];
  205835. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  205836. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  205837. atoms[2] = EndianU32_NtoB (MovieFileType);
  205838. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  205839. if (err == noErr)
  205840. return dataRef;
  205841. }
  205842. DisposeHandle (dataRef);
  205843. }
  205844. return 0;
  205845. }
  205846. static CFStringRef juceStringToCFString (const String& s)
  205847. {
  205848. const int len = s.length();
  205849. const juce_wchar* const t = s;
  205850. HeapBlock <UniChar> temp (len + 2);
  205851. for (int i = 0; i <= len; ++i)
  205852. temp[i] = t[i];
  205853. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  205854. }
  205855. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  205856. {
  205857. Boolean trueBool = true;
  205858. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  205859. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  205860. props[prop].propValueSize = sizeof (trueBool);
  205861. props[prop].propValueAddress = &trueBool;
  205862. ++prop;
  205863. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  205864. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  205865. props[prop].propValueSize = sizeof (trueBool);
  205866. props[prop].propValueAddress = &trueBool;
  205867. ++prop;
  205868. Boolean isActive = true;
  205869. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  205870. props[prop].propID = kQTNewMoviePropertyID_Active;
  205871. props[prop].propValueSize = sizeof (isActive);
  205872. props[prop].propValueAddress = &isActive;
  205873. ++prop;
  205874. MacSetPort (0);
  205875. jassert (prop <= 5);
  205876. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  205877. return err == noErr;
  205878. }
  205879. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  205880. {
  205881. if (input == 0)
  205882. return false;
  205883. dataHandle = 0;
  205884. bool ok = false;
  205885. QTNewMoviePropertyElement props[5];
  205886. zeromem (props, sizeof (props));
  205887. int prop = 0;
  205888. DataReferenceRecord dr;
  205889. props[prop].propClass = kQTPropertyClass_DataLocation;
  205890. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  205891. props[prop].propValueSize = sizeof (dr);
  205892. props[prop].propValueAddress = &dr;
  205893. ++prop;
  205894. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  205895. if (fin != 0)
  205896. {
  205897. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  205898. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  205899. &dr.dataRef, &dr.dataRefType);
  205900. ok = openMovie (props, prop, movie);
  205901. DisposeHandle (dr.dataRef);
  205902. CFRelease (filePath);
  205903. }
  205904. else
  205905. {
  205906. // sanity-check because this currently needs to load the whole stream into memory..
  205907. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  205908. dataHandle = NewHandle ((Size) input->getTotalLength());
  205909. HLock (dataHandle);
  205910. // read the entire stream into memory - this is a pain, but can't get it to work
  205911. // properly using a custom callback to supply the data.
  205912. input->read (*dataHandle, (int) input->getTotalLength());
  205913. HUnlock (dataHandle);
  205914. // different types to get QT to try. (We should really be a bit smarter here by
  205915. // working out in advance which one the stream contains, rather than just trying
  205916. // each one)
  205917. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  205918. "\04.avi", "\04.m4a" };
  205919. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  205920. {
  205921. /* // this fails for some bizarre reason - it can be bodged to work with
  205922. // movies, but can't seem to do it for other file types..
  205923. QTNewMovieUserProcRecord procInfo;
  205924. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  205925. procInfo.getMovieUserProcRefcon = this;
  205926. procInfo.defaultDataRef.dataRef = dataRef;
  205927. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  205928. props[prop].propClass = kQTPropertyClass_DataLocation;
  205929. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  205930. props[prop].propValueSize = sizeof (procInfo);
  205931. props[prop].propValueAddress = (void*) &procInfo;
  205932. ++prop; */
  205933. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  205934. dr.dataRefType = HandleDataHandlerSubType;
  205935. ok = openMovie (props, prop, movie);
  205936. DisposeHandle (dr.dataRef);
  205937. }
  205938. }
  205939. return ok;
  205940. }
  205941. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  205942. const bool isControllerVisible)
  205943. {
  205944. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  205945. movieFile = movieFile_;
  205946. return ok;
  205947. }
  205948. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  205949. const bool isControllerVisible)
  205950. {
  205951. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  205952. }
  205953. void QuickTimeMovieComponent::goToStart()
  205954. {
  205955. setPosition (0.0);
  205956. }
  205957. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  205958. const RectanglePlacement& placement)
  205959. {
  205960. int normalWidth, normalHeight;
  205961. getMovieNormalSize (normalWidth, normalHeight);
  205962. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  205963. {
  205964. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  205965. placement.applyTo (x, y, w, h,
  205966. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  205967. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  205968. if (w > 0 && h > 0)
  205969. {
  205970. setBounds (roundToInt (x), roundToInt (y),
  205971. roundToInt (w), roundToInt (h));
  205972. }
  205973. }
  205974. else
  205975. {
  205976. setBounds (spaceToFitWithin);
  205977. }
  205978. }
  205979. #endif
  205980. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  205981. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  205982. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205983. // compiled on its own).
  205984. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  205985. class WebBrowserComponentInternal : public ActiveXControlComponent
  205986. {
  205987. public:
  205988. WebBrowserComponentInternal()
  205989. : browser (0),
  205990. connectionPoint (0),
  205991. adviseCookie (0)
  205992. {
  205993. }
  205994. ~WebBrowserComponentInternal()
  205995. {
  205996. if (connectionPoint != 0)
  205997. connectionPoint->Unadvise (adviseCookie);
  205998. if (browser != 0)
  205999. browser->Release();
  206000. }
  206001. void createBrowser()
  206002. {
  206003. createControl (&CLSID_WebBrowser);
  206004. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  206005. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  206006. if (connectionPointContainer != 0)
  206007. {
  206008. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  206009. &connectionPoint);
  206010. if (connectionPoint != 0)
  206011. {
  206012. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  206013. jassert (owner != 0);
  206014. EventHandler* handler = new EventHandler (owner);
  206015. connectionPoint->Advise (handler, &adviseCookie);
  206016. handler->Release();
  206017. }
  206018. }
  206019. }
  206020. void goToURL (const String& url,
  206021. const StringArray* headers,
  206022. const MemoryBlock* postData)
  206023. {
  206024. if (browser != 0)
  206025. {
  206026. LPSAFEARRAY sa = 0;
  206027. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  206028. VariantInit (&flags);
  206029. VariantInit (&frame);
  206030. VariantInit (&postDataVar);
  206031. VariantInit (&headersVar);
  206032. if (headers != 0)
  206033. {
  206034. V_VT (&headersVar) = VT_BSTR;
  206035. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n"));
  206036. }
  206037. if (postData != 0 && postData->getSize() > 0)
  206038. {
  206039. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  206040. if (sa != 0)
  206041. {
  206042. void* data = 0;
  206043. SafeArrayAccessData (sa, &data);
  206044. jassert (data != 0);
  206045. if (data != 0)
  206046. {
  206047. postData->copyTo (data, 0, postData->getSize());
  206048. SafeArrayUnaccessData (sa);
  206049. VARIANT postDataVar2;
  206050. VariantInit (&postDataVar2);
  206051. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  206052. V_ARRAY (&postDataVar2) = sa;
  206053. postDataVar = postDataVar2;
  206054. }
  206055. }
  206056. }
  206057. browser->Navigate ((BSTR) (const OLECHAR*) url,
  206058. &flags, &frame,
  206059. &postDataVar, &headersVar);
  206060. if (sa != 0)
  206061. SafeArrayDestroy (sa);
  206062. VariantClear (&flags);
  206063. VariantClear (&frame);
  206064. VariantClear (&postDataVar);
  206065. VariantClear (&headersVar);
  206066. }
  206067. }
  206068. IWebBrowser2* browser;
  206069. juce_UseDebuggingNewOperator
  206070. private:
  206071. IConnectionPoint* connectionPoint;
  206072. DWORD adviseCookie;
  206073. class EventHandler : public ComBaseClassHelper <IDispatch>,
  206074. public ComponentMovementWatcher
  206075. {
  206076. public:
  206077. EventHandler (WebBrowserComponent* owner_)
  206078. : ComponentMovementWatcher (owner_),
  206079. owner (owner_)
  206080. {
  206081. }
  206082. ~EventHandler()
  206083. {
  206084. }
  206085. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  206086. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  206087. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  206088. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  206089. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  206090. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  206091. UINT __RPC_FAR* /*puArgErr*/)
  206092. {
  206093. switch (dispIdMember)
  206094. {
  206095. case DISPID_BEFORENAVIGATE2:
  206096. {
  206097. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  206098. String url;
  206099. if ((vurl->vt & VT_BYREF) != 0)
  206100. url = *vurl->pbstrVal;
  206101. else
  206102. url = vurl->bstrVal;
  206103. *pDispParams->rgvarg->pboolVal
  206104. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  206105. : VARIANT_TRUE;
  206106. return S_OK;
  206107. }
  206108. default:
  206109. break;
  206110. }
  206111. return E_NOTIMPL;
  206112. }
  206113. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) {}
  206114. void componentPeerChanged() {}
  206115. void componentVisibilityChanged (Component&)
  206116. {
  206117. owner->visibilityChanged();
  206118. }
  206119. juce_UseDebuggingNewOperator
  206120. private:
  206121. WebBrowserComponent* const owner;
  206122. EventHandler (const EventHandler&);
  206123. EventHandler& operator= (const EventHandler&);
  206124. };
  206125. };
  206126. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  206127. : browser (0),
  206128. blankPageShown (false),
  206129. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  206130. {
  206131. setOpaque (true);
  206132. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  206133. }
  206134. WebBrowserComponent::~WebBrowserComponent()
  206135. {
  206136. delete browser;
  206137. }
  206138. void WebBrowserComponent::goToURL (const String& url,
  206139. const StringArray* headers,
  206140. const MemoryBlock* postData)
  206141. {
  206142. lastURL = url;
  206143. lastHeaders.clear();
  206144. if (headers != 0)
  206145. lastHeaders = *headers;
  206146. lastPostData.setSize (0);
  206147. if (postData != 0)
  206148. lastPostData = *postData;
  206149. blankPageShown = false;
  206150. browser->goToURL (url, headers, postData);
  206151. }
  206152. void WebBrowserComponent::stop()
  206153. {
  206154. if (browser->browser != 0)
  206155. browser->browser->Stop();
  206156. }
  206157. void WebBrowserComponent::goBack()
  206158. {
  206159. lastURL = String::empty;
  206160. blankPageShown = false;
  206161. if (browser->browser != 0)
  206162. browser->browser->GoBack();
  206163. }
  206164. void WebBrowserComponent::goForward()
  206165. {
  206166. lastURL = String::empty;
  206167. if (browser->browser != 0)
  206168. browser->browser->GoForward();
  206169. }
  206170. void WebBrowserComponent::refresh()
  206171. {
  206172. if (browser->browser != 0)
  206173. browser->browser->Refresh();
  206174. }
  206175. void WebBrowserComponent::paint (Graphics& g)
  206176. {
  206177. if (browser->browser == 0)
  206178. g.fillAll (Colours::white);
  206179. }
  206180. void WebBrowserComponent::checkWindowAssociation()
  206181. {
  206182. if (isShowing())
  206183. {
  206184. if (browser->browser == 0 && getPeer() != 0)
  206185. {
  206186. browser->createBrowser();
  206187. reloadLastURL();
  206188. }
  206189. else
  206190. {
  206191. if (blankPageShown)
  206192. goBack();
  206193. }
  206194. }
  206195. else
  206196. {
  206197. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  206198. {
  206199. // when the component becomes invisible, some stuff like flash
  206200. // carries on playing audio, so we need to force it onto a blank
  206201. // page to avoid this..
  206202. blankPageShown = true;
  206203. browser->goToURL ("about:blank", 0, 0);
  206204. }
  206205. }
  206206. }
  206207. void WebBrowserComponent::reloadLastURL()
  206208. {
  206209. if (lastURL.isNotEmpty())
  206210. {
  206211. goToURL (lastURL, &lastHeaders, &lastPostData);
  206212. lastURL = String::empty;
  206213. }
  206214. }
  206215. void WebBrowserComponent::parentHierarchyChanged()
  206216. {
  206217. checkWindowAssociation();
  206218. }
  206219. void WebBrowserComponent::resized()
  206220. {
  206221. browser->setSize (getWidth(), getHeight());
  206222. }
  206223. void WebBrowserComponent::visibilityChanged()
  206224. {
  206225. checkWindowAssociation();
  206226. }
  206227. bool WebBrowserComponent::pageAboutToLoad (const String&)
  206228. {
  206229. return true;
  206230. }
  206231. #endif
  206232. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  206233. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  206234. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206235. // compiled on its own).
  206236. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  206237. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  206238. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  206239. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  206240. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  206241. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  206242. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  206243. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  206244. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  206245. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  206246. #define WGL_ACCELERATION_ARB 0x2003
  206247. #define WGL_SWAP_METHOD_ARB 0x2007
  206248. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  206249. #define WGL_PIXEL_TYPE_ARB 0x2013
  206250. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  206251. #define WGL_COLOR_BITS_ARB 0x2014
  206252. #define WGL_RED_BITS_ARB 0x2015
  206253. #define WGL_GREEN_BITS_ARB 0x2017
  206254. #define WGL_BLUE_BITS_ARB 0x2019
  206255. #define WGL_ALPHA_BITS_ARB 0x201B
  206256. #define WGL_DEPTH_BITS_ARB 0x2022
  206257. #define WGL_STENCIL_BITS_ARB 0x2023
  206258. #define WGL_FULL_ACCELERATION_ARB 0x2027
  206259. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  206260. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  206261. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  206262. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  206263. #define WGL_STEREO_ARB 0x2012
  206264. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  206265. #define WGL_SAMPLES_ARB 0x2042
  206266. #define WGL_TYPE_RGBA_ARB 0x202B
  206267. static void getWglExtensions (HDC dc, StringArray& result) throw()
  206268. {
  206269. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  206270. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  206271. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  206272. else
  206273. jassertfalse // If this fails, it may be because you didn't activate the openGL context
  206274. }
  206275. class WindowedGLContext : public OpenGLContext
  206276. {
  206277. public:
  206278. WindowedGLContext (Component* const component_,
  206279. HGLRC contextToShareWith,
  206280. const OpenGLPixelFormat& pixelFormat)
  206281. : renderContext (0),
  206282. nativeWindow (0),
  206283. dc (0),
  206284. component (component_)
  206285. {
  206286. jassert (component != 0);
  206287. createNativeWindow();
  206288. // Use a default pixel format that should be supported everywhere
  206289. PIXELFORMATDESCRIPTOR pfd;
  206290. zerostruct (pfd);
  206291. pfd.nSize = sizeof (pfd);
  206292. pfd.nVersion = 1;
  206293. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  206294. pfd.iPixelType = PFD_TYPE_RGBA;
  206295. pfd.cColorBits = 24;
  206296. pfd.cDepthBits = 16;
  206297. const int format = ChoosePixelFormat (dc, &pfd);
  206298. if (format != 0)
  206299. SetPixelFormat (dc, format, &pfd);
  206300. renderContext = wglCreateContext (dc);
  206301. makeActive();
  206302. setPixelFormat (pixelFormat);
  206303. if (contextToShareWith != 0 && renderContext != 0)
  206304. wglShareLists (contextToShareWith, renderContext);
  206305. }
  206306. ~WindowedGLContext()
  206307. {
  206308. makeInactive();
  206309. wglDeleteContext (renderContext);
  206310. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  206311. delete nativeWindow;
  206312. }
  206313. bool makeActive() const throw()
  206314. {
  206315. jassert (renderContext != 0);
  206316. return wglMakeCurrent (dc, renderContext) != 0;
  206317. }
  206318. bool makeInactive() const throw()
  206319. {
  206320. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  206321. }
  206322. bool isActive() const throw()
  206323. {
  206324. return wglGetCurrentContext() == renderContext;
  206325. }
  206326. const OpenGLPixelFormat getPixelFormat() const
  206327. {
  206328. OpenGLPixelFormat pf;
  206329. makeActive();
  206330. StringArray availableExtensions;
  206331. getWglExtensions (dc, availableExtensions);
  206332. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  206333. return pf;
  206334. }
  206335. void* getRawContext() const throw()
  206336. {
  206337. return renderContext;
  206338. }
  206339. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  206340. {
  206341. makeActive();
  206342. PIXELFORMATDESCRIPTOR pfd;
  206343. zerostruct (pfd);
  206344. pfd.nSize = sizeof (pfd);
  206345. pfd.nVersion = 1;
  206346. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  206347. pfd.iPixelType = PFD_TYPE_RGBA;
  206348. pfd.iLayerType = PFD_MAIN_PLANE;
  206349. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  206350. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  206351. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  206352. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  206353. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  206354. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  206355. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  206356. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  206357. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  206358. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  206359. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  206360. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  206361. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  206362. int format = 0;
  206363. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  206364. StringArray availableExtensions;
  206365. getWglExtensions (dc, availableExtensions);
  206366. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  206367. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  206368. {
  206369. int attributes[64];
  206370. int n = 0;
  206371. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  206372. attributes[n++] = GL_TRUE;
  206373. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  206374. attributes[n++] = GL_TRUE;
  206375. attributes[n++] = WGL_ACCELERATION_ARB;
  206376. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  206377. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  206378. attributes[n++] = GL_TRUE;
  206379. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  206380. attributes[n++] = WGL_TYPE_RGBA_ARB;
  206381. attributes[n++] = WGL_COLOR_BITS_ARB;
  206382. attributes[n++] = pfd.cColorBits;
  206383. attributes[n++] = WGL_RED_BITS_ARB;
  206384. attributes[n++] = pixelFormat.redBits;
  206385. attributes[n++] = WGL_GREEN_BITS_ARB;
  206386. attributes[n++] = pixelFormat.greenBits;
  206387. attributes[n++] = WGL_BLUE_BITS_ARB;
  206388. attributes[n++] = pixelFormat.blueBits;
  206389. attributes[n++] = WGL_ALPHA_BITS_ARB;
  206390. attributes[n++] = pixelFormat.alphaBits;
  206391. attributes[n++] = WGL_DEPTH_BITS_ARB;
  206392. attributes[n++] = pixelFormat.depthBufferBits;
  206393. if (pixelFormat.stencilBufferBits > 0)
  206394. {
  206395. attributes[n++] = WGL_STENCIL_BITS_ARB;
  206396. attributes[n++] = pixelFormat.stencilBufferBits;
  206397. }
  206398. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  206399. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  206400. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  206401. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  206402. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  206403. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  206404. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  206405. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  206406. if (availableExtensions.contains ("WGL_ARB_multisample")
  206407. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  206408. {
  206409. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  206410. attributes[n++] = 1;
  206411. attributes[n++] = WGL_SAMPLES_ARB;
  206412. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  206413. }
  206414. attributes[n++] = 0;
  206415. UINT formatsCount;
  206416. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  206417. (void) ok;
  206418. jassert (ok);
  206419. }
  206420. else
  206421. {
  206422. format = ChoosePixelFormat (dc, &pfd);
  206423. }
  206424. if (format != 0)
  206425. {
  206426. makeInactive();
  206427. // win32 can't change the pixel format of a window, so need to delete the
  206428. // old one and create a new one..
  206429. jassert (nativeWindow != 0);
  206430. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  206431. delete nativeWindow;
  206432. createNativeWindow();
  206433. if (SetPixelFormat (dc, format, &pfd))
  206434. {
  206435. wglDeleteContext (renderContext);
  206436. renderContext = wglCreateContext (dc);
  206437. jassert (renderContext != 0);
  206438. return renderContext != 0;
  206439. }
  206440. }
  206441. return false;
  206442. }
  206443. void updateWindowPosition (int x, int y, int w, int h, int)
  206444. {
  206445. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  206446. x, y, w, h,
  206447. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206448. }
  206449. void repaint()
  206450. {
  206451. const Rectangle<int> bounds (nativeWindow->getBounds());
  206452. nativeWindow->repaint (0, 0, bounds.getWidth(), bounds.getHeight());
  206453. }
  206454. void swapBuffers()
  206455. {
  206456. SwapBuffers (dc);
  206457. }
  206458. bool setSwapInterval (int numFramesPerSwap)
  206459. {
  206460. makeActive();
  206461. StringArray availableExtensions;
  206462. getWglExtensions (dc, availableExtensions);
  206463. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  206464. return availableExtensions.contains ("WGL_EXT_swap_control")
  206465. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  206466. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  206467. }
  206468. int getSwapInterval() const
  206469. {
  206470. makeActive();
  206471. StringArray availableExtensions;
  206472. getWglExtensions (dc, availableExtensions);
  206473. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  206474. if (availableExtensions.contains ("WGL_EXT_swap_control")
  206475. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  206476. return wglGetSwapIntervalEXT();
  206477. return 0;
  206478. }
  206479. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  206480. {
  206481. jassert (isActive());
  206482. StringArray availableExtensions;
  206483. getWglExtensions (dc, availableExtensions);
  206484. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  206485. int numTypes = 0;
  206486. if (availableExtensions.contains("WGL_ARB_pixel_format")
  206487. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  206488. {
  206489. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  206490. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  206491. jassertfalse
  206492. }
  206493. else
  206494. {
  206495. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  206496. }
  206497. OpenGLPixelFormat pf;
  206498. for (int i = 0; i < numTypes; ++i)
  206499. {
  206500. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  206501. {
  206502. bool alreadyListed = false;
  206503. for (int j = results.size(); --j >= 0;)
  206504. if (pf == *results.getUnchecked(j))
  206505. alreadyListed = true;
  206506. if (! alreadyListed)
  206507. results.add (new OpenGLPixelFormat (pf));
  206508. }
  206509. }
  206510. }
  206511. void* getNativeWindowHandle() const
  206512. {
  206513. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  206514. }
  206515. juce_UseDebuggingNewOperator
  206516. HGLRC renderContext;
  206517. private:
  206518. Win32ComponentPeer* nativeWindow;
  206519. Component* const component;
  206520. HDC dc;
  206521. void createNativeWindow()
  206522. {
  206523. nativeWindow = new Win32ComponentPeer (component, 0);
  206524. nativeWindow->dontRepaint = true;
  206525. nativeWindow->setVisible (true);
  206526. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  206527. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  206528. if (peer != 0)
  206529. {
  206530. SetParent (hwnd, (HWND) peer->getNativeHandle());
  206531. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  206532. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  206533. }
  206534. dc = GetDC (hwnd);
  206535. }
  206536. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  206537. OpenGLPixelFormat& result,
  206538. const StringArray& availableExtensions) const throw()
  206539. {
  206540. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  206541. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  206542. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  206543. {
  206544. int attributes[32];
  206545. int numAttributes = 0;
  206546. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  206547. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  206548. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  206549. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  206550. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  206551. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  206552. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  206553. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  206554. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  206555. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  206556. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  206557. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  206558. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  206559. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  206560. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  206561. if (availableExtensions.contains ("WGL_ARB_multisample"))
  206562. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  206563. int values[32];
  206564. zeromem (values, sizeof (values));
  206565. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  206566. {
  206567. int n = 0;
  206568. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  206569. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  206570. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  206571. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  206572. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  206573. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  206574. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  206575. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  206576. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  206577. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  206578. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  206579. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  206580. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  206581. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  206582. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  206583. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  206584. return isValidFormat;
  206585. }
  206586. else
  206587. {
  206588. jassertfalse
  206589. }
  206590. }
  206591. else
  206592. {
  206593. PIXELFORMATDESCRIPTOR pfd;
  206594. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  206595. {
  206596. result.redBits = pfd.cRedBits;
  206597. result.greenBits = pfd.cGreenBits;
  206598. result.blueBits = pfd.cBlueBits;
  206599. result.alphaBits = pfd.cAlphaBits;
  206600. result.depthBufferBits = pfd.cDepthBits;
  206601. result.stencilBufferBits = pfd.cStencilBits;
  206602. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  206603. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  206604. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  206605. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  206606. result.fullSceneAntiAliasingNumSamples = 0;
  206607. return true;
  206608. }
  206609. else
  206610. {
  206611. jassertfalse
  206612. }
  206613. }
  206614. return false;
  206615. }
  206616. WindowedGLContext (const WindowedGLContext&);
  206617. WindowedGLContext& operator= (const WindowedGLContext&);
  206618. };
  206619. OpenGLContext* OpenGLComponent::createContext()
  206620. {
  206621. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  206622. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  206623. preferredPixelFormat));
  206624. return (c->renderContext != 0) ? c.release() : 0;
  206625. }
  206626. void* OpenGLComponent::getNativeWindowHandle() const
  206627. {
  206628. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  206629. }
  206630. void juce_glViewport (const int w, const int h)
  206631. {
  206632. glViewport (0, 0, w, h);
  206633. }
  206634. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  206635. OwnedArray <OpenGLPixelFormat>& results)
  206636. {
  206637. Component tempComp;
  206638. {
  206639. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  206640. wc.makeActive();
  206641. wc.findAlternativeOpenGLPixelFormats (results);
  206642. }
  206643. }
  206644. #endif
  206645. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  206646. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  206647. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206648. // compiled on its own).
  206649. #if JUCE_INCLUDED_FILE
  206650. #if JUCE_USE_CDREADER
  206651. namespace CDReaderHelpers
  206652. {
  206653. //***************************************************************************
  206654. // %%% TARGET STATUS VALUES %%%
  206655. //***************************************************************************
  206656. #define STATUS_GOOD 0x00 // Status Good
  206657. #define STATUS_CHKCOND 0x02 // Check Condition
  206658. #define STATUS_CONDMET 0x04 // Condition Met
  206659. #define STATUS_BUSY 0x08 // Busy
  206660. #define STATUS_INTERM 0x10 // Intermediate
  206661. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  206662. #define STATUS_RESCONF 0x18 // Reservation conflict
  206663. #define STATUS_COMTERM 0x22 // Command Terminated
  206664. #define STATUS_QFULL 0x28 // Queue full
  206665. //***************************************************************************
  206666. // %%% SCSI MISCELLANEOUS EQUATES %%%
  206667. //***************************************************************************
  206668. #define MAXLUN 7 // Maximum Logical Unit Id
  206669. #define MAXTARG 7 // Maximum Target Id
  206670. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  206671. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  206672. //***************************************************************************
  206673. // %%% Commands for all Device Types %%%
  206674. //***************************************************************************
  206675. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  206676. #define SCSI_COMPARE 0x39 // Compare (O)
  206677. #define SCSI_COPY 0x18 // Copy (O)
  206678. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  206679. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  206680. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  206681. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  206682. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  206683. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  206684. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  206685. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  206686. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  206687. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  206688. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  206689. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  206690. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  206691. //***************************************************************************
  206692. // %%% Commands Unique to Direct Access Devices %%%
  206693. //***************************************************************************
  206694. #define SCSI_COMPARE 0x39 // Compare (O)
  206695. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  206696. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  206697. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  206698. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  206699. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  206700. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  206701. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  206702. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  206703. #define SCSI_READ_LONG 0x3E // Read Long (O)
  206704. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  206705. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  206706. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  206707. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  206708. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  206709. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  206710. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  206711. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  206712. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  206713. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  206714. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  206715. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  206716. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  206717. #define SCSI_VERIFY 0x2F // Verify (O)
  206718. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  206719. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  206720. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  206721. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  206722. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  206723. //***************************************************************************
  206724. // %%% Commands Unique to Sequential Access Devices %%%
  206725. //***************************************************************************
  206726. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  206727. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  206728. #define SCSI_LOCATE 0x2B // Locate (O)
  206729. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  206730. #define SCSI_READ_POS 0x34 // Read Position (O)
  206731. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  206732. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  206733. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  206734. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  206735. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  206736. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  206737. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  206738. //***************************************************************************
  206739. // %%% Commands Unique to Printer Devices %%%
  206740. //***************************************************************************
  206741. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  206742. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  206743. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  206744. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  206745. //***************************************************************************
  206746. // %%% Commands Unique to Processor Devices %%%
  206747. //***************************************************************************
  206748. #define SCSI_RECEIVE 0x08 // Receive (O)
  206749. #define SCSI_SEND 0x0A // Send (O)
  206750. //***************************************************************************
  206751. // %%% Commands Unique to Write-Once Devices %%%
  206752. //***************************************************************************
  206753. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  206754. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  206755. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  206756. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  206757. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  206758. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  206759. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  206760. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  206761. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  206762. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  206763. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  206764. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  206765. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  206766. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  206767. //***************************************************************************
  206768. // %%% Commands Unique to CD-ROM Devices %%%
  206769. //***************************************************************************
  206770. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  206771. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  206772. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  206773. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  206774. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  206775. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  206776. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  206777. #define SCSI_READHEADER 0x44 // Read Header (O)
  206778. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  206779. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  206780. //***************************************************************************
  206781. // %%% Commands Unique to Scanner Devices %%%
  206782. //***************************************************************************
  206783. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  206784. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  206785. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  206786. #define SCSI_SCAN 0x1B // Scan (O)
  206787. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  206788. //***************************************************************************
  206789. // %%% Commands Unique to Optical Memory Devices %%%
  206790. //***************************************************************************
  206791. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  206792. //***************************************************************************
  206793. // %%% Commands Unique to Medium Changer Devices %%%
  206794. //***************************************************************************
  206795. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  206796. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  206797. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  206798. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  206799. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  206800. //***************************************************************************
  206801. // %%% Commands Unique to Communication Devices %%%
  206802. //***************************************************************************
  206803. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  206804. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  206805. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  206806. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  206807. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  206808. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  206809. //***************************************************************************
  206810. // %%% Request Sense Data Format %%%
  206811. //***************************************************************************
  206812. typedef struct {
  206813. BYTE ErrorCode; // Error Code (70H or 71H)
  206814. BYTE SegmentNum; // Number of current segment descriptor
  206815. BYTE SenseKey; // Sense Key(See bit definitions too)
  206816. BYTE InfoByte0; // Information MSB
  206817. BYTE InfoByte1; // Information MID
  206818. BYTE InfoByte2; // Information MID
  206819. BYTE InfoByte3; // Information LSB
  206820. BYTE AddSenLen; // Additional Sense Length
  206821. BYTE ComSpecInf0; // Command Specific Information MSB
  206822. BYTE ComSpecInf1; // Command Specific Information MID
  206823. BYTE ComSpecInf2; // Command Specific Information MID
  206824. BYTE ComSpecInf3; // Command Specific Information LSB
  206825. BYTE AddSenseCode; // Additional Sense Code
  206826. BYTE AddSenQual; // Additional Sense Code Qualifier
  206827. BYTE FieldRepUCode; // Field Replaceable Unit Code
  206828. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  206829. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  206830. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  206831. BYTE AddSenseBytes; // Additional Sense Bytes
  206832. } SENSE_DATA_FMT;
  206833. //***************************************************************************
  206834. // %%% REQUEST SENSE ERROR CODE %%%
  206835. //***************************************************************************
  206836. #define SERROR_CURRENT 0x70 // Current Errors
  206837. #define SERROR_DEFERED 0x71 // Deferred Errors
  206838. //***************************************************************************
  206839. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  206840. //***************************************************************************
  206841. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  206842. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  206843. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  206844. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  206845. //***************************************************************************
  206846. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  206847. //***************************************************************************
  206848. #define KEY_NOSENSE 0x00 // No Sense
  206849. #define KEY_RECERROR 0x01 // Recovered Error
  206850. #define KEY_NOTREADY 0x02 // Not Ready
  206851. #define KEY_MEDIUMERR 0x03 // Medium Error
  206852. #define KEY_HARDERROR 0x04 // Hardware Error
  206853. #define KEY_ILLGLREQ 0x05 // Illegal Request
  206854. #define KEY_UNITATT 0x06 // Unit Attention
  206855. #define KEY_DATAPROT 0x07 // Data Protect
  206856. #define KEY_BLANKCHK 0x08 // Blank Check
  206857. #define KEY_VENDSPEC 0x09 // Vendor Specific
  206858. #define KEY_COPYABORT 0x0A // Copy Abort
  206859. #define KEY_EQUAL 0x0C // Equal (Search)
  206860. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  206861. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  206862. #define KEY_RESERVED 0x0F // Reserved
  206863. //***************************************************************************
  206864. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  206865. //***************************************************************************
  206866. #define DTYPE_DASD 0x00 // Disk Device
  206867. #define DTYPE_SEQD 0x01 // Tape Device
  206868. #define DTYPE_PRNT 0x02 // Printer
  206869. #define DTYPE_PROC 0x03 // Processor
  206870. #define DTYPE_WORM 0x04 // Write-once read-multiple
  206871. #define DTYPE_CROM 0x05 // CD-ROM device
  206872. #define DTYPE_SCAN 0x06 // Scanner device
  206873. #define DTYPE_OPTI 0x07 // Optical memory device
  206874. #define DTYPE_JUKE 0x08 // Medium Changer device
  206875. #define DTYPE_COMM 0x09 // Communications device
  206876. #define DTYPE_RESL 0x0A // Reserved (low)
  206877. #define DTYPE_RESH 0x1E // Reserved (high)
  206878. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  206879. //***************************************************************************
  206880. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  206881. //***************************************************************************
  206882. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  206883. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  206884. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  206885. #define ANSI_RESLO 0x3 // Reserved (low)
  206886. #define ANSI_RESHI 0x7 // Reserved (high)
  206887. typedef struct
  206888. {
  206889. USHORT Length;
  206890. UCHAR ScsiStatus;
  206891. UCHAR PathId;
  206892. UCHAR TargetId;
  206893. UCHAR Lun;
  206894. UCHAR CdbLength;
  206895. UCHAR SenseInfoLength;
  206896. UCHAR DataIn;
  206897. ULONG DataTransferLength;
  206898. ULONG TimeOutValue;
  206899. ULONG DataBufferOffset;
  206900. ULONG SenseInfoOffset;
  206901. UCHAR Cdb[16];
  206902. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  206903. typedef struct
  206904. {
  206905. USHORT Length;
  206906. UCHAR ScsiStatus;
  206907. UCHAR PathId;
  206908. UCHAR TargetId;
  206909. UCHAR Lun;
  206910. UCHAR CdbLength;
  206911. UCHAR SenseInfoLength;
  206912. UCHAR DataIn;
  206913. ULONG DataTransferLength;
  206914. ULONG TimeOutValue;
  206915. PVOID DataBuffer;
  206916. ULONG SenseInfoOffset;
  206917. UCHAR Cdb[16];
  206918. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  206919. typedef struct
  206920. {
  206921. SCSI_PASS_THROUGH_DIRECT spt;
  206922. ULONG Filler;
  206923. UCHAR ucSenseBuf[32];
  206924. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  206925. typedef struct
  206926. {
  206927. ULONG Length;
  206928. UCHAR PortNumber;
  206929. UCHAR PathId;
  206930. UCHAR TargetId;
  206931. UCHAR Lun;
  206932. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  206933. #define METHOD_BUFFERED 0
  206934. #define METHOD_IN_DIRECT 1
  206935. #define METHOD_OUT_DIRECT 2
  206936. #define METHOD_NEITHER 3
  206937. #define FILE_ANY_ACCESS 0
  206938. #ifndef FILE_READ_ACCESS
  206939. #define FILE_READ_ACCESS (0x0001)
  206940. #endif
  206941. #ifndef FILE_WRITE_ACCESS
  206942. #define FILE_WRITE_ACCESS (0x0002)
  206943. #endif
  206944. #define IOCTL_SCSI_BASE 0x00000004
  206945. #define SCSI_IOCTL_DATA_OUT 0
  206946. #define SCSI_IOCTL_DATA_IN 1
  206947. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  206948. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  206949. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  206950. )
  206951. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  206952. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  206953. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  206954. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  206955. #define SENSE_LEN 14
  206956. #define SRB_DIR_SCSI 0x00
  206957. #define SRB_POSTING 0x01
  206958. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  206959. #define SRB_DIR_IN 0x08
  206960. #define SRB_DIR_OUT 0x10
  206961. #define SRB_EVENT_NOTIFY 0x40
  206962. #define RESIDUAL_COUNT_SUPPORTED 0x02
  206963. #define MAX_SRB_TIMEOUT 1080001u
  206964. #define DEFAULT_SRB_TIMEOUT 1080001u
  206965. #define SC_HA_INQUIRY 0x00
  206966. #define SC_GET_DEV_TYPE 0x01
  206967. #define SC_EXEC_SCSI_CMD 0x02
  206968. #define SC_ABORT_SRB 0x03
  206969. #define SC_RESET_DEV 0x04
  206970. #define SC_SET_HA_PARMS 0x05
  206971. #define SC_GET_DISK_INFO 0x06
  206972. #define SC_RESCAN_SCSI_BUS 0x07
  206973. #define SC_GETSET_TIMEOUTS 0x08
  206974. #define SS_PENDING 0x00
  206975. #define SS_COMP 0x01
  206976. #define SS_ABORTED 0x02
  206977. #define SS_ABORT_FAIL 0x03
  206978. #define SS_ERR 0x04
  206979. #define SS_INVALID_CMD 0x80
  206980. #define SS_INVALID_HA 0x81
  206981. #define SS_NO_DEVICE 0x82
  206982. #define SS_INVALID_SRB 0xE0
  206983. #define SS_OLD_MANAGER 0xE1
  206984. #define SS_BUFFER_ALIGN 0xE1
  206985. #define SS_ILLEGAL_MODE 0xE2
  206986. #define SS_NO_ASPI 0xE3
  206987. #define SS_FAILED_INIT 0xE4
  206988. #define SS_ASPI_IS_BUSY 0xE5
  206989. #define SS_BUFFER_TO_BIG 0xE6
  206990. #define SS_BUFFER_TOO_BIG 0xE6
  206991. #define SS_MISMATCHED_COMPONENTS 0xE7
  206992. #define SS_NO_ADAPTERS 0xE8
  206993. #define SS_INSUFFICIENT_RESOURCES 0xE9
  206994. #define SS_ASPI_IS_SHUTDOWN 0xEA
  206995. #define SS_BAD_INSTALL 0xEB
  206996. #define HASTAT_OK 0x00
  206997. #define HASTAT_SEL_TO 0x11
  206998. #define HASTAT_DO_DU 0x12
  206999. #define HASTAT_BUS_FREE 0x13
  207000. #define HASTAT_PHASE_ERR 0x14
  207001. #define HASTAT_TIMEOUT 0x09
  207002. #define HASTAT_COMMAND_TIMEOUT 0x0B
  207003. #define HASTAT_MESSAGE_REJECT 0x0D
  207004. #define HASTAT_BUS_RESET 0x0E
  207005. #define HASTAT_PARITY_ERROR 0x0F
  207006. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  207007. #define PACKED
  207008. #pragma pack(1)
  207009. typedef struct
  207010. {
  207011. BYTE SRB_Cmd;
  207012. BYTE SRB_Status;
  207013. BYTE SRB_HaID;
  207014. BYTE SRB_Flags;
  207015. DWORD SRB_Hdr_Rsvd;
  207016. BYTE HA_Count;
  207017. BYTE HA_SCSI_ID;
  207018. BYTE HA_ManagerId[16];
  207019. BYTE HA_Identifier[16];
  207020. BYTE HA_Unique[16];
  207021. WORD HA_Rsvd1;
  207022. BYTE pad[20];
  207023. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  207024. typedef struct
  207025. {
  207026. BYTE SRB_Cmd;
  207027. BYTE SRB_Status;
  207028. BYTE SRB_HaID;
  207029. BYTE SRB_Flags;
  207030. DWORD SRB_Hdr_Rsvd;
  207031. BYTE SRB_Target;
  207032. BYTE SRB_Lun;
  207033. BYTE SRB_DeviceType;
  207034. BYTE SRB_Rsvd1;
  207035. BYTE pad[68];
  207036. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  207037. typedef struct
  207038. {
  207039. BYTE SRB_Cmd;
  207040. BYTE SRB_Status;
  207041. BYTE SRB_HaID;
  207042. BYTE SRB_Flags;
  207043. DWORD SRB_Hdr_Rsvd;
  207044. BYTE SRB_Target;
  207045. BYTE SRB_Lun;
  207046. WORD SRB_Rsvd1;
  207047. DWORD SRB_BufLen;
  207048. BYTE FAR *SRB_BufPointer;
  207049. BYTE SRB_SenseLen;
  207050. BYTE SRB_CDBLen;
  207051. BYTE SRB_HaStat;
  207052. BYTE SRB_TargStat;
  207053. VOID FAR *SRB_PostProc;
  207054. BYTE SRB_Rsvd2[20];
  207055. BYTE CDBByte[16];
  207056. BYTE SenseArea[SENSE_LEN+2];
  207057. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  207058. typedef struct
  207059. {
  207060. BYTE SRB_Cmd;
  207061. BYTE SRB_Status;
  207062. BYTE SRB_HaId;
  207063. BYTE SRB_Flags;
  207064. DWORD SRB_Hdr_Rsvd;
  207065. } PACKED SRB, *PSRB, FAR *LPSRB;
  207066. #pragma pack()
  207067. struct CDDeviceInfo
  207068. {
  207069. char vendor[9];
  207070. char productId[17];
  207071. char rev[5];
  207072. char vendorSpec[21];
  207073. BYTE ha;
  207074. BYTE tgt;
  207075. BYTE lun;
  207076. char scsiDriveLetter; // will be 0 if not using scsi
  207077. };
  207078. class CDReadBuffer
  207079. {
  207080. public:
  207081. int startFrame;
  207082. int numFrames;
  207083. int dataStartOffset;
  207084. int dataLength;
  207085. int bufferSize;
  207086. HeapBlock<BYTE> buffer;
  207087. int index;
  207088. bool wantsIndex;
  207089. CDReadBuffer (const int numberOfFrames)
  207090. : startFrame (0),
  207091. numFrames (0),
  207092. dataStartOffset (0),
  207093. dataLength (0),
  207094. bufferSize (2352 * numberOfFrames),
  207095. buffer (bufferSize),
  207096. index (0),
  207097. wantsIndex (false)
  207098. {
  207099. }
  207100. bool isZero() const throw()
  207101. {
  207102. BYTE* p = buffer + dataStartOffset;
  207103. for (int i = dataLength; --i >= 0;)
  207104. if (*p++ != 0)
  207105. return false;
  207106. return true;
  207107. }
  207108. };
  207109. class CDDeviceHandle;
  207110. class CDController
  207111. {
  207112. public:
  207113. CDController();
  207114. virtual ~CDController();
  207115. virtual bool read (CDReadBuffer* t) = 0;
  207116. virtual void shutDown();
  207117. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  207118. int getLastIndex();
  207119. public:
  207120. bool initialised;
  207121. CDDeviceHandle* deviceInfo;
  207122. int framesToCheck, framesOverlap;
  207123. void prepare (SRB_ExecSCSICmd& s);
  207124. void perform (SRB_ExecSCSICmd& s);
  207125. void setPaused (bool paused);
  207126. };
  207127. #pragma pack(1)
  207128. struct TOCTRACK
  207129. {
  207130. BYTE rsvd;
  207131. BYTE ADR;
  207132. BYTE trackNumber;
  207133. BYTE rsvd2;
  207134. BYTE addr[4];
  207135. };
  207136. struct TOC
  207137. {
  207138. WORD tocLen;
  207139. BYTE firstTrack;
  207140. BYTE lastTrack;
  207141. TOCTRACK tracks[100];
  207142. };
  207143. #pragma pack()
  207144. enum
  207145. {
  207146. READTYPE_ANY = 0,
  207147. READTYPE_ATAPI1 = 1,
  207148. READTYPE_ATAPI2 = 2,
  207149. READTYPE_READ6 = 3,
  207150. READTYPE_READ10 = 4,
  207151. READTYPE_READ_D8 = 5,
  207152. READTYPE_READ_D4 = 6,
  207153. READTYPE_READ_D4_1 = 7,
  207154. READTYPE_READ10_2 = 8
  207155. };
  207156. class CDDeviceHandle
  207157. {
  207158. public:
  207159. CDDeviceHandle (const CDDeviceInfo* const device)
  207160. : scsiHandle (0),
  207161. readType (READTYPE_ANY),
  207162. controller (0)
  207163. {
  207164. memcpy (&info, device, sizeof (info));
  207165. }
  207166. ~CDDeviceHandle()
  207167. {
  207168. if (controller != 0)
  207169. {
  207170. controller->shutDown();
  207171. controller = 0;
  207172. }
  207173. if (scsiHandle != 0)
  207174. CloseHandle (scsiHandle);
  207175. }
  207176. bool readTOC (TOC* lpToc, bool useMSF);
  207177. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  207178. void openDrawer (bool shouldBeOpen);
  207179. CDDeviceInfo info;
  207180. HANDLE scsiHandle;
  207181. BYTE readType;
  207182. private:
  207183. ScopedPointer<CDController> controller;
  207184. bool testController (const int readType,
  207185. CDController* const newController,
  207186. CDReadBuffer* const bufferToUse);
  207187. };
  207188. DWORD (*fGetASPI32SupportInfo)(void);
  207189. DWORD (*fSendASPI32Command)(LPSRB);
  207190. static HINSTANCE winAspiLib = 0;
  207191. static bool usingScsi = false;
  207192. static bool initialised = false;
  207193. static bool InitialiseCDRipper()
  207194. {
  207195. if (! initialised)
  207196. {
  207197. initialised = true;
  207198. OSVERSIONINFO info;
  207199. info.dwOSVersionInfoSize = sizeof (info);
  207200. GetVersionEx (&info);
  207201. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  207202. if (! usingScsi)
  207203. {
  207204. fGetASPI32SupportInfo = 0;
  207205. fSendASPI32Command = 0;
  207206. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  207207. if (winAspiLib != 0)
  207208. {
  207209. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  207210. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  207211. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  207212. return false;
  207213. }
  207214. else
  207215. {
  207216. usingScsi = true;
  207217. }
  207218. }
  207219. }
  207220. return true;
  207221. }
  207222. static void DeinitialiseCDRipper()
  207223. {
  207224. if (winAspiLib != 0)
  207225. {
  207226. fGetASPI32SupportInfo = 0;
  207227. fSendASPI32Command = 0;
  207228. FreeLibrary (winAspiLib);
  207229. winAspiLib = 0;
  207230. }
  207231. initialised = false;
  207232. }
  207233. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  207234. {
  207235. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  207236. OSVERSIONINFO info;
  207237. info.dwOSVersionInfoSize = sizeof (info);
  207238. GetVersionEx (&info);
  207239. DWORD flags = GENERIC_READ;
  207240. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  207241. flags = GENERIC_READ | GENERIC_WRITE;
  207242. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  207243. if (h == INVALID_HANDLE_VALUE)
  207244. {
  207245. flags ^= GENERIC_WRITE;
  207246. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  207247. }
  207248. return h;
  207249. }
  207250. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  207251. const char driveLetter,
  207252. HANDLE& deviceHandle,
  207253. const bool retryOnFailure = true)
  207254. {
  207255. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  207256. zerostruct (s);
  207257. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  207258. s.spt.CdbLength = srb->SRB_CDBLen;
  207259. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  207260. ? SCSI_IOCTL_DATA_IN
  207261. : ((srb->SRB_Flags & SRB_DIR_OUT)
  207262. ? SCSI_IOCTL_DATA_OUT
  207263. : SCSI_IOCTL_DATA_UNSPECIFIED));
  207264. s.spt.DataTransferLength = srb->SRB_BufLen;
  207265. s.spt.TimeOutValue = 5;
  207266. s.spt.DataBuffer = srb->SRB_BufPointer;
  207267. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  207268. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  207269. srb->SRB_Status = SS_ERR;
  207270. srb->SRB_TargStat = 0x0004;
  207271. DWORD bytesReturned = 0;
  207272. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  207273. &s, sizeof (s),
  207274. &s, sizeof (s),
  207275. &bytesReturned, 0) != 0)
  207276. {
  207277. srb->SRB_Status = SS_COMP;
  207278. }
  207279. else if (retryOnFailure)
  207280. {
  207281. const DWORD error = GetLastError();
  207282. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  207283. {
  207284. if (error != ERROR_INVALID_HANDLE)
  207285. CloseHandle (deviceHandle);
  207286. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  207287. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  207288. }
  207289. }
  207290. return srb->SRB_Status;
  207291. }
  207292. // Controller types..
  207293. class ControllerType1 : public CDController
  207294. {
  207295. public:
  207296. ControllerType1() {}
  207297. ~ControllerType1() {}
  207298. bool read (CDReadBuffer* rb)
  207299. {
  207300. if (rb->numFrames * 2352 > rb->bufferSize)
  207301. return false;
  207302. SRB_ExecSCSICmd s;
  207303. prepare (s);
  207304. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  207305. s.SRB_BufLen = rb->bufferSize;
  207306. s.SRB_BufPointer = rb->buffer;
  207307. s.SRB_CDBLen = 12;
  207308. s.CDBByte[0] = 0xBE;
  207309. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  207310. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  207311. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  207312. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  207313. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  207314. perform (s);
  207315. if (s.SRB_Status != SS_COMP)
  207316. return false;
  207317. rb->dataLength = rb->numFrames * 2352;
  207318. rb->dataStartOffset = 0;
  207319. return true;
  207320. }
  207321. };
  207322. class ControllerType2 : public CDController
  207323. {
  207324. public:
  207325. ControllerType2() {}
  207326. ~ControllerType2() {}
  207327. void shutDown()
  207328. {
  207329. if (initialised)
  207330. {
  207331. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  207332. SRB_ExecSCSICmd s;
  207333. prepare (s);
  207334. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  207335. s.SRB_BufLen = 0x0C;
  207336. s.SRB_BufPointer = bufPointer;
  207337. s.SRB_CDBLen = 6;
  207338. s.CDBByte[0] = 0x15;
  207339. s.CDBByte[4] = 0x0C;
  207340. perform (s);
  207341. }
  207342. }
  207343. bool init()
  207344. {
  207345. SRB_ExecSCSICmd s;
  207346. s.SRB_Status = SS_ERR;
  207347. if (deviceInfo->readType == READTYPE_READ10_2)
  207348. {
  207349. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  207350. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  207351. for (int i = 0; i < 2; ++i)
  207352. {
  207353. prepare (s);
  207354. s.SRB_Flags = SRB_EVENT_NOTIFY;
  207355. s.SRB_BufLen = 0x14;
  207356. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  207357. s.SRB_CDBLen = 6;
  207358. s.CDBByte[0] = 0x15;
  207359. s.CDBByte[1] = 0x10;
  207360. s.CDBByte[4] = 0x14;
  207361. perform (s);
  207362. if (s.SRB_Status != SS_COMP)
  207363. return false;
  207364. }
  207365. }
  207366. else
  207367. {
  207368. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  207369. prepare (s);
  207370. s.SRB_Flags = SRB_EVENT_NOTIFY;
  207371. s.SRB_BufLen = 0x0C;
  207372. s.SRB_BufPointer = bufPointer;
  207373. s.SRB_CDBLen = 6;
  207374. s.CDBByte[0] = 0x15;
  207375. s.CDBByte[4] = 0x0C;
  207376. perform (s);
  207377. }
  207378. return s.SRB_Status == SS_COMP;
  207379. }
  207380. bool read (CDReadBuffer* rb)
  207381. {
  207382. if (rb->numFrames * 2352 > rb->bufferSize)
  207383. return false;
  207384. if (!initialised)
  207385. {
  207386. initialised = init();
  207387. if (!initialised)
  207388. return false;
  207389. }
  207390. SRB_ExecSCSICmd s;
  207391. prepare (s);
  207392. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  207393. s.SRB_BufLen = rb->bufferSize;
  207394. s.SRB_BufPointer = rb->buffer;
  207395. s.SRB_CDBLen = 10;
  207396. s.CDBByte[0] = 0x28;
  207397. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  207398. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  207399. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  207400. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  207401. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  207402. perform (s);
  207403. if (s.SRB_Status != SS_COMP)
  207404. return false;
  207405. rb->dataLength = rb->numFrames * 2352;
  207406. rb->dataStartOffset = 0;
  207407. return true;
  207408. }
  207409. };
  207410. class ControllerType3 : public CDController
  207411. {
  207412. public:
  207413. ControllerType3() {}
  207414. ~ControllerType3() {}
  207415. bool read (CDReadBuffer* rb)
  207416. {
  207417. if (rb->numFrames * 2352 > rb->bufferSize)
  207418. return false;
  207419. if (!initialised)
  207420. {
  207421. setPaused (false);
  207422. initialised = true;
  207423. }
  207424. SRB_ExecSCSICmd s;
  207425. prepare (s);
  207426. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  207427. s.SRB_BufLen = rb->numFrames * 2352;
  207428. s.SRB_BufPointer = rb->buffer;
  207429. s.SRB_CDBLen = 12;
  207430. s.CDBByte[0] = 0xD8;
  207431. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  207432. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  207433. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  207434. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  207435. perform (s);
  207436. if (s.SRB_Status != SS_COMP)
  207437. return false;
  207438. rb->dataLength = rb->numFrames * 2352;
  207439. rb->dataStartOffset = 0;
  207440. return true;
  207441. }
  207442. };
  207443. class ControllerType4 : public CDController
  207444. {
  207445. public:
  207446. ControllerType4() {}
  207447. ~ControllerType4() {}
  207448. bool selectD4Mode()
  207449. {
  207450. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  207451. SRB_ExecSCSICmd s;
  207452. prepare (s);
  207453. s.SRB_Flags = SRB_EVENT_NOTIFY;
  207454. s.SRB_CDBLen = 6;
  207455. s.SRB_BufLen = 12;
  207456. s.SRB_BufPointer = bufPointer;
  207457. s.CDBByte[0] = 0x15;
  207458. s.CDBByte[1] = 0x10;
  207459. s.CDBByte[4] = 0x08;
  207460. perform (s);
  207461. return s.SRB_Status == SS_COMP;
  207462. }
  207463. bool read (CDReadBuffer* rb)
  207464. {
  207465. if (rb->numFrames * 2352 > rb->bufferSize)
  207466. return false;
  207467. if (!initialised)
  207468. {
  207469. setPaused (true);
  207470. if (deviceInfo->readType == READTYPE_READ_D4_1)
  207471. selectD4Mode();
  207472. initialised = true;
  207473. }
  207474. SRB_ExecSCSICmd s;
  207475. prepare (s);
  207476. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  207477. s.SRB_BufLen = rb->bufferSize;
  207478. s.SRB_BufPointer = rb->buffer;
  207479. s.SRB_CDBLen = 10;
  207480. s.CDBByte[0] = 0xD4;
  207481. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  207482. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  207483. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  207484. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  207485. perform (s);
  207486. if (s.SRB_Status != SS_COMP)
  207487. return false;
  207488. rb->dataLength = rb->numFrames * 2352;
  207489. rb->dataStartOffset = 0;
  207490. return true;
  207491. }
  207492. };
  207493. CDController::CDController() : initialised (false)
  207494. {
  207495. }
  207496. CDController::~CDController()
  207497. {
  207498. }
  207499. void CDController::prepare (SRB_ExecSCSICmd& s)
  207500. {
  207501. zerostruct (s);
  207502. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  207503. s.SRB_HaID = deviceInfo->info.ha;
  207504. s.SRB_Target = deviceInfo->info.tgt;
  207505. s.SRB_Lun = deviceInfo->info.lun;
  207506. s.SRB_SenseLen = SENSE_LEN;
  207507. }
  207508. void CDController::perform (SRB_ExecSCSICmd& s)
  207509. {
  207510. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  207511. s.SRB_PostProc = event;
  207512. ResetEvent (event);
  207513. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  207514. deviceInfo->info.scsiDriveLetter,
  207515. deviceInfo->scsiHandle)
  207516. : fSendASPI32Command ((LPSRB)&s);
  207517. if (status == SS_PENDING)
  207518. WaitForSingleObject (event, 4000);
  207519. CloseHandle (event);
  207520. }
  207521. void CDController::setPaused (bool paused)
  207522. {
  207523. SRB_ExecSCSICmd s;
  207524. prepare (s);
  207525. s.SRB_Flags = SRB_EVENT_NOTIFY;
  207526. s.SRB_CDBLen = 10;
  207527. s.CDBByte[0] = 0x4B;
  207528. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  207529. perform (s);
  207530. }
  207531. void CDController::shutDown()
  207532. {
  207533. }
  207534. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  207535. {
  207536. if (overlapBuffer != 0)
  207537. {
  207538. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  207539. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  207540. if (doJitter
  207541. && overlapBuffer->startFrame > 0
  207542. && overlapBuffer->numFrames > 0
  207543. && overlapBuffer->dataLength > 0)
  207544. {
  207545. const int numFrames = rb->numFrames;
  207546. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  207547. {
  207548. rb->startFrame -= framesOverlap;
  207549. if (framesToCheck < framesOverlap
  207550. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  207551. rb->numFrames += framesOverlap;
  207552. }
  207553. else
  207554. {
  207555. overlapBuffer->dataLength = 0;
  207556. overlapBuffer->startFrame = 0;
  207557. overlapBuffer->numFrames = 0;
  207558. }
  207559. }
  207560. if (! read (rb))
  207561. return false;
  207562. if (doJitter)
  207563. {
  207564. const int checkLen = framesToCheck * 2352;
  207565. const int maxToCheck = rb->dataLength - checkLen;
  207566. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  207567. return true;
  207568. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  207569. bool found = false;
  207570. for (int i = 0; i < maxToCheck; ++i)
  207571. {
  207572. if (memcmp (p, rb->buffer + i, checkLen) == 0)
  207573. {
  207574. i += checkLen;
  207575. rb->dataStartOffset = i;
  207576. rb->dataLength -= i;
  207577. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  207578. found = true;
  207579. break;
  207580. }
  207581. }
  207582. rb->numFrames = rb->dataLength / 2352;
  207583. rb->dataLength = 2352 * rb->numFrames;
  207584. if (!found)
  207585. return false;
  207586. }
  207587. if (canDoJitter)
  207588. {
  207589. memcpy (overlapBuffer->buffer,
  207590. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  207591. 2352 * framesToCheck);
  207592. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  207593. overlapBuffer->numFrames = framesToCheck;
  207594. overlapBuffer->dataLength = 2352 * framesToCheck;
  207595. overlapBuffer->dataStartOffset = 0;
  207596. }
  207597. else
  207598. {
  207599. overlapBuffer->startFrame = 0;
  207600. overlapBuffer->numFrames = 0;
  207601. overlapBuffer->dataLength = 0;
  207602. }
  207603. return true;
  207604. }
  207605. else
  207606. {
  207607. return read (rb);
  207608. }
  207609. }
  207610. int CDController::getLastIndex()
  207611. {
  207612. char qdata[100];
  207613. SRB_ExecSCSICmd s;
  207614. prepare (s);
  207615. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  207616. s.SRB_BufLen = sizeof (qdata);
  207617. s.SRB_BufPointer = (BYTE*)qdata;
  207618. s.SRB_CDBLen = 12;
  207619. s.CDBByte[0] = 0x42;
  207620. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  207621. s.CDBByte[2] = 64;
  207622. s.CDBByte[3] = 1; // get current position
  207623. s.CDBByte[7] = 0;
  207624. s.CDBByte[8] = (BYTE)sizeof (qdata);
  207625. perform (s);
  207626. if (s.SRB_Status == SS_COMP)
  207627. return qdata[7];
  207628. return 0;
  207629. }
  207630. bool CDDeviceHandle::readTOC (TOC* lpToc, bool useMSF)
  207631. {
  207632. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  207633. SRB_ExecSCSICmd s;
  207634. zerostruct (s);
  207635. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  207636. s.SRB_HaID = info.ha;
  207637. s.SRB_Target = info.tgt;
  207638. s.SRB_Lun = info.lun;
  207639. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  207640. s.SRB_BufLen = 0x324;
  207641. s.SRB_BufPointer = (BYTE*)lpToc;
  207642. s.SRB_SenseLen = 0x0E;
  207643. s.SRB_CDBLen = 0x0A;
  207644. s.SRB_PostProc = event;
  207645. s.CDBByte[0] = 0x43;
  207646. s.CDBByte[1] = (BYTE)(useMSF ? 0x02 : 0x00);
  207647. s.CDBByte[7] = 0x03;
  207648. s.CDBByte[8] = 0x24;
  207649. ResetEvent (event);
  207650. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  207651. : fSendASPI32Command ((LPSRB)&s);
  207652. if (status == SS_PENDING)
  207653. WaitForSingleObject (event, 4000);
  207654. CloseHandle (event);
  207655. return (s.SRB_Status == SS_COMP);
  207656. }
  207657. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  207658. CDReadBuffer* const overlapBuffer)
  207659. {
  207660. if (controller == 0)
  207661. {
  207662. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  207663. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  207664. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  207665. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  207666. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  207667. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  207668. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  207669. }
  207670. buffer->index = 0;
  207671. if ((controller != 0)
  207672. && controller->readAudio (buffer, overlapBuffer))
  207673. {
  207674. if (buffer->wantsIndex)
  207675. buffer->index = controller->getLastIndex();
  207676. return true;
  207677. }
  207678. return false;
  207679. }
  207680. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  207681. {
  207682. if (shouldBeOpen)
  207683. {
  207684. if (controller != 0)
  207685. {
  207686. controller->shutDown();
  207687. controller = 0;
  207688. }
  207689. if (scsiHandle != 0)
  207690. {
  207691. CloseHandle (scsiHandle);
  207692. scsiHandle = 0;
  207693. }
  207694. }
  207695. SRB_ExecSCSICmd s;
  207696. zerostruct (s);
  207697. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  207698. s.SRB_HaID = info.ha;
  207699. s.SRB_Target = info.tgt;
  207700. s.SRB_Lun = info.lun;
  207701. s.SRB_SenseLen = SENSE_LEN;
  207702. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  207703. s.SRB_BufLen = 0;
  207704. s.SRB_BufPointer = 0;
  207705. s.SRB_CDBLen = 12;
  207706. s.CDBByte[0] = 0x1b;
  207707. s.CDBByte[1] = (BYTE)(info.lun << 5);
  207708. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  207709. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  207710. s.SRB_PostProc = event;
  207711. ResetEvent (event);
  207712. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  207713. : fSendASPI32Command ((LPSRB)&s);
  207714. if (status == SS_PENDING)
  207715. WaitForSingleObject (event, 4000);
  207716. CloseHandle (event);
  207717. }
  207718. bool CDDeviceHandle::testController (const int type,
  207719. CDController* const newController,
  207720. CDReadBuffer* const rb)
  207721. {
  207722. controller = newController;
  207723. readType = (BYTE)type;
  207724. controller->deviceInfo = this;
  207725. controller->framesToCheck = 1;
  207726. controller->framesOverlap = 3;
  207727. bool passed = false;
  207728. memset (rb->buffer, 0xcd, rb->bufferSize);
  207729. if (controller->read (rb))
  207730. {
  207731. passed = true;
  207732. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  207733. int wrong = 0;
  207734. for (int i = rb->dataLength / 4; --i >= 0;)
  207735. {
  207736. if (*p++ == (int) 0xcdcdcdcd)
  207737. {
  207738. if (++wrong == 4)
  207739. {
  207740. passed = false;
  207741. break;
  207742. }
  207743. }
  207744. else
  207745. {
  207746. wrong = 0;
  207747. }
  207748. }
  207749. }
  207750. if (! passed)
  207751. {
  207752. controller->shutDown();
  207753. controller = 0;
  207754. }
  207755. return passed;
  207756. }
  207757. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  207758. {
  207759. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  207760. const int bufSize = 128;
  207761. BYTE buffer[bufSize];
  207762. zeromem (buffer, bufSize);
  207763. SRB_ExecSCSICmd s;
  207764. zerostruct (s);
  207765. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  207766. s.SRB_HaID = ha;
  207767. s.SRB_Target = tgt;
  207768. s.SRB_Lun = lun;
  207769. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  207770. s.SRB_BufLen = bufSize;
  207771. s.SRB_BufPointer = buffer;
  207772. s.SRB_SenseLen = SENSE_LEN;
  207773. s.SRB_CDBLen = 6;
  207774. s.SRB_PostProc = event;
  207775. s.CDBByte[0] = SCSI_INQUIRY;
  207776. s.CDBByte[4] = 100;
  207777. ResetEvent (event);
  207778. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  207779. WaitForSingleObject (event, 4000);
  207780. CloseHandle (event);
  207781. if (s.SRB_Status == SS_COMP)
  207782. {
  207783. memcpy (dev->vendor, &buffer[8], 8);
  207784. memcpy (dev->productId, &buffer[16], 16);
  207785. memcpy (dev->rev, &buffer[32], 4);
  207786. memcpy (dev->vendorSpec, &buffer[36], 20);
  207787. }
  207788. }
  207789. static int FindCDDevices (CDDeviceInfo* const list,
  207790. int maxItems)
  207791. {
  207792. int count = 0;
  207793. if (usingScsi)
  207794. {
  207795. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  207796. {
  207797. TCHAR drivePath[8];
  207798. drivePath[0] = driveLetter;
  207799. drivePath[1] = ':';
  207800. drivePath[2] = '\\';
  207801. drivePath[3] = 0;
  207802. if (GetDriveType (drivePath) == DRIVE_CDROM)
  207803. {
  207804. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  207805. if (h != INVALID_HANDLE_VALUE)
  207806. {
  207807. BYTE buffer[100], passThroughStruct[1024];
  207808. zeromem (buffer, sizeof (buffer));
  207809. zeromem (passThroughStruct, sizeof (passThroughStruct));
  207810. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  207811. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  207812. p->spt.CdbLength = 6;
  207813. p->spt.SenseInfoLength = 24;
  207814. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  207815. p->spt.DataTransferLength = 100;
  207816. p->spt.TimeOutValue = 2;
  207817. p->spt.DataBuffer = buffer;
  207818. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  207819. p->spt.Cdb[0] = 0x12;
  207820. p->spt.Cdb[4] = 100;
  207821. DWORD bytesReturned = 0;
  207822. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  207823. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  207824. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  207825. &bytesReturned, 0) != 0)
  207826. {
  207827. zeromem (&list[count], sizeof (CDDeviceInfo));
  207828. list[count].scsiDriveLetter = driveLetter;
  207829. memcpy (list[count].vendor, &buffer[8], 8);
  207830. memcpy (list[count].productId, &buffer[16], 16);
  207831. memcpy (list[count].rev, &buffer[32], 4);
  207832. memcpy (list[count].vendorSpec, &buffer[36], 20);
  207833. zeromem (passThroughStruct, sizeof (passThroughStruct));
  207834. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  207835. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  207836. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  207837. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  207838. &bytesReturned, 0) != 0)
  207839. {
  207840. list[count].ha = scsiAddr->PortNumber;
  207841. list[count].tgt = scsiAddr->TargetId;
  207842. list[count].lun = scsiAddr->Lun;
  207843. ++count;
  207844. }
  207845. }
  207846. CloseHandle (h);
  207847. }
  207848. }
  207849. }
  207850. }
  207851. else
  207852. {
  207853. const DWORD d = fGetASPI32SupportInfo();
  207854. BYTE status = HIBYTE (LOWORD (d));
  207855. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  207856. return 0;
  207857. const int numAdapters = LOBYTE (LOWORD (d));
  207858. for (BYTE ha = 0; ha < numAdapters; ++ha)
  207859. {
  207860. SRB_HAInquiry s;
  207861. zerostruct (s);
  207862. s.SRB_Cmd = SC_HA_INQUIRY;
  207863. s.SRB_HaID = ha;
  207864. fSendASPI32Command ((LPSRB)&s);
  207865. if (s.SRB_Status == SS_COMP)
  207866. {
  207867. maxItems = (int)s.HA_Unique[3];
  207868. if (maxItems == 0)
  207869. maxItems = 8;
  207870. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  207871. {
  207872. for (BYTE lun = 0; lun < 8; ++lun)
  207873. {
  207874. SRB_GDEVBlock sb;
  207875. zerostruct (sb);
  207876. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  207877. sb.SRB_HaID = ha;
  207878. sb.SRB_Target = tgt;
  207879. sb.SRB_Lun = lun;
  207880. fSendASPI32Command ((LPSRB) &sb);
  207881. if (sb.SRB_Status == SS_COMP
  207882. && sb.SRB_DeviceType == DTYPE_CROM)
  207883. {
  207884. zeromem (&list[count], sizeof (CDDeviceInfo));
  207885. list[count].ha = ha;
  207886. list[count].tgt = tgt;
  207887. list[count].lun = lun;
  207888. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  207889. ++count;
  207890. }
  207891. }
  207892. }
  207893. }
  207894. }
  207895. }
  207896. return count;
  207897. }
  207898. static int ripperUsers = 0;
  207899. static bool initialisedOk = false;
  207900. class DeinitialiseTimer : private Timer,
  207901. private DeletedAtShutdown
  207902. {
  207903. DeinitialiseTimer (const DeinitialiseTimer&);
  207904. DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  207905. public:
  207906. DeinitialiseTimer()
  207907. {
  207908. startTimer (4000);
  207909. }
  207910. ~DeinitialiseTimer()
  207911. {
  207912. if (--ripperUsers == 0)
  207913. DeinitialiseCDRipper();
  207914. }
  207915. void timerCallback()
  207916. {
  207917. delete this;
  207918. }
  207919. juce_UseDebuggingNewOperator
  207920. };
  207921. static void incUserCount()
  207922. {
  207923. if (ripperUsers++ == 0)
  207924. initialisedOk = InitialiseCDRipper();
  207925. }
  207926. static void decUserCount()
  207927. {
  207928. new DeinitialiseTimer();
  207929. }
  207930. struct CDDeviceWrapper
  207931. {
  207932. ScopedPointer<CDDeviceHandle> cdH;
  207933. ScopedPointer<CDReadBuffer> overlapBuffer;
  207934. bool jitter;
  207935. };
  207936. static int getAddressOf (const TOCTRACK* const t)
  207937. {
  207938. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  207939. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  207940. }
  207941. static int getMSFAddressOf (const TOCTRACK* const t)
  207942. {
  207943. return 60 * t->addr[1] + t->addr[2];
  207944. }
  207945. static const int samplesPerFrame = 44100 / 75;
  207946. static const int bytesPerFrame = samplesPerFrame * 4;
  207947. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  207948. {
  207949. SRB_GDEVBlock s;
  207950. zerostruct (s);
  207951. s.SRB_Cmd = SC_GET_DEV_TYPE;
  207952. s.SRB_HaID = device->ha;
  207953. s.SRB_Target = device->tgt;
  207954. s.SRB_Lun = device->lun;
  207955. if (usingScsi)
  207956. {
  207957. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  207958. if (h != INVALID_HANDLE_VALUE)
  207959. {
  207960. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  207961. cdh->scsiHandle = h;
  207962. return cdh;
  207963. }
  207964. }
  207965. else
  207966. {
  207967. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  207968. && s.SRB_DeviceType == DTYPE_CROM)
  207969. {
  207970. return new CDDeviceHandle (device);
  207971. }
  207972. }
  207973. return 0;
  207974. }
  207975. }
  207976. const StringArray AudioCDReader::getAvailableCDNames()
  207977. {
  207978. using namespace CDReaderHelpers;
  207979. StringArray results;
  207980. incUserCount();
  207981. if (initialisedOk)
  207982. {
  207983. CDDeviceInfo list[8];
  207984. const int num = FindCDDevices (list, 8);
  207985. decUserCount();
  207986. for (int i = 0; i < num; ++i)
  207987. {
  207988. String s;
  207989. if (list[i].scsiDriveLetter > 0)
  207990. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  207991. s << String (list[i].vendor).trim()
  207992. << ' ' << String (list[i].productId).trim()
  207993. << ' ' << String (list[i].rev).trim();
  207994. results.add (s);
  207995. }
  207996. }
  207997. return results;
  207998. }
  207999. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  208000. {
  208001. using namespace CDReaderHelpers;
  208002. incUserCount();
  208003. if (initialisedOk)
  208004. {
  208005. CDDeviceInfo list[8];
  208006. const int num = FindCDDevices (list, 8);
  208007. if (((unsigned int) deviceIndex) < (unsigned int) num)
  208008. {
  208009. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  208010. if (handle != 0)
  208011. {
  208012. CDDeviceWrapper* const d = new CDDeviceWrapper();
  208013. d->cdH = handle;
  208014. d->overlapBuffer = new CDReadBuffer(3);
  208015. return new AudioCDReader (d);
  208016. }
  208017. }
  208018. }
  208019. decUserCount();
  208020. return 0;
  208021. }
  208022. AudioCDReader::AudioCDReader (void* handle_)
  208023. : AudioFormatReader (0, "CD Audio"),
  208024. handle (handle_),
  208025. indexingEnabled (false),
  208026. lastIndex (0),
  208027. firstFrameInBuffer (0),
  208028. samplesInBuffer (0)
  208029. {
  208030. using namespace CDReaderHelpers;
  208031. jassert (handle_ != 0);
  208032. refreshTrackLengths();
  208033. sampleRate = 44100.0;
  208034. bitsPerSample = 16;
  208035. lengthInSamples = getPositionOfTrackStart (numTracks);
  208036. numChannels = 2;
  208037. usesFloatingPointData = false;
  208038. buffer.setSize (4 * bytesPerFrame, true);
  208039. }
  208040. AudioCDReader::~AudioCDReader()
  208041. {
  208042. using namespace CDReaderHelpers;
  208043. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  208044. delete device;
  208045. decUserCount();
  208046. }
  208047. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  208048. int64 startSampleInFile, int numSamples)
  208049. {
  208050. using namespace CDReaderHelpers;
  208051. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  208052. bool ok = true;
  208053. while (numSamples > 0)
  208054. {
  208055. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  208056. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  208057. if (startSampleInFile >= bufferStartSample
  208058. && startSampleInFile < bufferEndSample)
  208059. {
  208060. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  208061. int* const l = destSamples[0] + startOffsetInDestBuffer;
  208062. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  208063. const short* src = (const short*) buffer.getData();
  208064. src += 2 * (startSampleInFile - bufferStartSample);
  208065. for (int i = 0; i < toDo; ++i)
  208066. {
  208067. l[i] = src [i << 1] << 16;
  208068. if (r != 0)
  208069. r[i] = src [(i << 1) + 1] << 16;
  208070. }
  208071. startOffsetInDestBuffer += toDo;
  208072. startSampleInFile += toDo;
  208073. numSamples -= toDo;
  208074. }
  208075. else
  208076. {
  208077. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  208078. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  208079. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  208080. {
  208081. device->overlapBuffer->dataLength = 0;
  208082. device->overlapBuffer->startFrame = 0;
  208083. device->overlapBuffer->numFrames = 0;
  208084. device->jitter = false;
  208085. }
  208086. firstFrameInBuffer = frameNeeded;
  208087. lastIndex = 0;
  208088. CDReadBuffer readBuffer (framesInBuffer + 4);
  208089. readBuffer.wantsIndex = indexingEnabled;
  208090. int i;
  208091. for (i = 5; --i >= 0;)
  208092. {
  208093. readBuffer.startFrame = frameNeeded;
  208094. readBuffer.numFrames = framesInBuffer;
  208095. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  208096. break;
  208097. else
  208098. device->overlapBuffer->dataLength = 0;
  208099. }
  208100. if (i >= 0)
  208101. {
  208102. memcpy ((char*) buffer.getData(),
  208103. readBuffer.buffer + readBuffer.dataStartOffset,
  208104. readBuffer.dataLength);
  208105. samplesInBuffer = readBuffer.dataLength >> 2;
  208106. lastIndex = readBuffer.index;
  208107. }
  208108. else
  208109. {
  208110. int* l = destSamples[0] + startOffsetInDestBuffer;
  208111. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  208112. while (--numSamples >= 0)
  208113. {
  208114. *l++ = 0;
  208115. if (r != 0)
  208116. *r++ = 0;
  208117. }
  208118. // sometimes the read fails for just the very last couple of blocks, so
  208119. // we'll ignore and errors in the last half-second of the disk..
  208120. ok = startSampleInFile > (trackStarts [numTracks] - 20000);
  208121. break;
  208122. }
  208123. }
  208124. }
  208125. return ok;
  208126. }
  208127. bool AudioCDReader::isCDStillPresent() const
  208128. {
  208129. using namespace CDReaderHelpers;
  208130. TOC toc;
  208131. zerostruct (toc);
  208132. return ((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, false);
  208133. }
  208134. int AudioCDReader::getNumTracks() const
  208135. {
  208136. return numTracks;
  208137. }
  208138. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  208139. {
  208140. using namespace CDReaderHelpers;
  208141. return (trackNum >= 0 && trackNum <= numTracks) ? trackStarts [trackNum] * samplesPerFrame
  208142. : 0;
  208143. }
  208144. void AudioCDReader::refreshTrackLengths()
  208145. {
  208146. using namespace CDReaderHelpers;
  208147. zeromem (trackStarts, sizeof (trackStarts));
  208148. zeromem (audioTracks, sizeof (audioTracks));
  208149. TOC toc;
  208150. zerostruct (toc);
  208151. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false))
  208152. {
  208153. numTracks = 1 + toc.lastTrack - toc.firstTrack;
  208154. for (int i = 0; i <= numTracks; ++i)
  208155. {
  208156. trackStarts[i] = getAddressOf (&toc.tracks[i]);
  208157. audioTracks[i] = ((toc.tracks[i].ADR & 4) == 0);
  208158. }
  208159. }
  208160. else
  208161. {
  208162. numTracks = 0;
  208163. }
  208164. }
  208165. bool AudioCDReader::isTrackAudio (int trackNum) const
  208166. {
  208167. return (trackNum >= 0 && trackNum <= numTracks) ? audioTracks [trackNum]
  208168. : false;
  208169. }
  208170. void AudioCDReader::enableIndexScanning (bool b)
  208171. {
  208172. indexingEnabled = b;
  208173. }
  208174. int AudioCDReader::getLastIndex() const
  208175. {
  208176. return lastIndex;
  208177. }
  208178. const int framesPerIndexRead = 4;
  208179. int AudioCDReader::getIndexAt (int samplePos)
  208180. {
  208181. using namespace CDReaderHelpers;
  208182. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  208183. const int frameNeeded = samplePos / samplesPerFrame;
  208184. device->overlapBuffer->dataLength = 0;
  208185. device->overlapBuffer->startFrame = 0;
  208186. device->overlapBuffer->numFrames = 0;
  208187. device->jitter = false;
  208188. firstFrameInBuffer = 0;
  208189. lastIndex = 0;
  208190. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  208191. readBuffer.wantsIndex = true;
  208192. int i;
  208193. for (i = 5; --i >= 0;)
  208194. {
  208195. readBuffer.startFrame = frameNeeded;
  208196. readBuffer.numFrames = framesPerIndexRead;
  208197. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  208198. break;
  208199. }
  208200. if (i >= 0)
  208201. return readBuffer.index;
  208202. return -1;
  208203. }
  208204. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  208205. {
  208206. using namespace CDReaderHelpers;
  208207. Array <int> indexes;
  208208. const int trackStart = getPositionOfTrackStart (trackNumber);
  208209. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  208210. bool needToScan = true;
  208211. if (trackEnd - trackStart > 20 * 44100)
  208212. {
  208213. // check the end of the track for indexes before scanning the whole thing
  208214. needToScan = false;
  208215. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  208216. bool seenAnIndex = false;
  208217. while (pos <= trackEnd - samplesPerFrame)
  208218. {
  208219. const int index = getIndexAt (pos);
  208220. if (index == 0)
  208221. {
  208222. // lead-out, so skip back a bit if we've not found any indexes yet..
  208223. if (seenAnIndex)
  208224. break;
  208225. pos -= 44100 * 5;
  208226. if (pos < trackStart)
  208227. break;
  208228. }
  208229. else
  208230. {
  208231. if (index > 0)
  208232. seenAnIndex = true;
  208233. if (index > 1)
  208234. {
  208235. needToScan = true;
  208236. break;
  208237. }
  208238. pos += samplesPerFrame * framesPerIndexRead;
  208239. }
  208240. }
  208241. }
  208242. if (needToScan)
  208243. {
  208244. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  208245. int pos = trackStart;
  208246. int last = -1;
  208247. while (pos < trackEnd - samplesPerFrame * 10)
  208248. {
  208249. const int frameNeeded = pos / samplesPerFrame;
  208250. device->overlapBuffer->dataLength = 0;
  208251. device->overlapBuffer->startFrame = 0;
  208252. device->overlapBuffer->numFrames = 0;
  208253. device->jitter = false;
  208254. firstFrameInBuffer = 0;
  208255. CDReadBuffer readBuffer (4);
  208256. readBuffer.wantsIndex = true;
  208257. int i;
  208258. for (i = 5; --i >= 0;)
  208259. {
  208260. readBuffer.startFrame = frameNeeded;
  208261. readBuffer.numFrames = framesPerIndexRead;
  208262. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  208263. break;
  208264. }
  208265. if (i < 0)
  208266. break;
  208267. if (readBuffer.index > last && readBuffer.index > 1)
  208268. {
  208269. last = readBuffer.index;
  208270. indexes.add (pos);
  208271. }
  208272. pos += samplesPerFrame * framesPerIndexRead;
  208273. }
  208274. indexes.removeValue (trackStart);
  208275. }
  208276. return indexes;
  208277. }
  208278. int AudioCDReader::getCDDBId()
  208279. {
  208280. using namespace CDReaderHelpers;
  208281. refreshTrackLengths();
  208282. if (numTracks > 0)
  208283. {
  208284. TOC toc;
  208285. zerostruct (toc);
  208286. if (((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, true))
  208287. {
  208288. int n = 0;
  208289. for (int i = numTracks; --i >= 0;)
  208290. {
  208291. int j = getMSFAddressOf (&toc.tracks[i]);
  208292. while (j > 0)
  208293. {
  208294. n += (j % 10);
  208295. j /= 10;
  208296. }
  208297. }
  208298. if (n != 0)
  208299. {
  208300. const int t = getMSFAddressOf (&toc.tracks[numTracks])
  208301. - getMSFAddressOf (&toc.tracks[0]);
  208302. return ((n % 0xff) << 24) | (t << 8) | numTracks;
  208303. }
  208304. }
  208305. }
  208306. return 0;
  208307. }
  208308. void AudioCDReader::ejectDisk()
  208309. {
  208310. using namespace CDReaderHelpers;
  208311. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  208312. }
  208313. #endif
  208314. #if JUCE_USE_CDBURNER
  208315. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  208316. {
  208317. CoInitialize (0);
  208318. IDiscMaster* dm;
  208319. IDiscRecorder* result = 0;
  208320. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  208321. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  208322. IID_IDiscMaster,
  208323. (void**) &dm)))
  208324. {
  208325. if (SUCCEEDED (dm->Open()))
  208326. {
  208327. IEnumDiscRecorders* drEnum = 0;
  208328. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  208329. {
  208330. IDiscRecorder* dr = 0;
  208331. DWORD dummy;
  208332. int index = 0;
  208333. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  208334. {
  208335. if (indexToOpen == index)
  208336. {
  208337. result = dr;
  208338. break;
  208339. }
  208340. else if (list != 0)
  208341. {
  208342. BSTR path;
  208343. if (SUCCEEDED (dr->GetPath (&path)))
  208344. list->add ((const WCHAR*) path);
  208345. }
  208346. ++index;
  208347. dr->Release();
  208348. }
  208349. drEnum->Release();
  208350. }
  208351. if (master == 0)
  208352. dm->Close();
  208353. }
  208354. if (master != 0)
  208355. *master = dm;
  208356. else
  208357. dm->Release();
  208358. }
  208359. return result;
  208360. }
  208361. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  208362. public Timer
  208363. {
  208364. public:
  208365. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  208366. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  208367. listener (0), progress (0), shouldCancel (false)
  208368. {
  208369. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  208370. jassert (SUCCEEDED (hr));
  208371. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  208372. //jassert (SUCCEEDED (hr));
  208373. lastState = getDiskState();
  208374. startTimer (2000);
  208375. }
  208376. ~Pimpl() {}
  208377. void releaseObjects()
  208378. {
  208379. discRecorder->Close();
  208380. if (redbook != 0)
  208381. redbook->Release();
  208382. discRecorder->Release();
  208383. discMaster->Release();
  208384. Release();
  208385. }
  208386. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  208387. {
  208388. if (listener != 0 && ! shouldCancel)
  208389. shouldCancel = listener->audioCDBurnProgress (progress);
  208390. *pbCancel = shouldCancel;
  208391. return S_OK;
  208392. }
  208393. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  208394. {
  208395. progress = nCompleted / (float) nTotal;
  208396. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  208397. return E_NOTIMPL;
  208398. }
  208399. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  208400. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  208401. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  208402. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  208403. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  208404. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  208405. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  208406. class ScopedDiscOpener
  208407. {
  208408. public:
  208409. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  208410. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  208411. private:
  208412. Pimpl& pimpl;
  208413. ScopedDiscOpener (const ScopedDiscOpener&);
  208414. ScopedDiscOpener& operator= (const ScopedDiscOpener&);
  208415. };
  208416. DiskState getDiskState()
  208417. {
  208418. const ScopedDiscOpener opener (*this);
  208419. long type, flags;
  208420. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  208421. if (FAILED (hr))
  208422. return unknown;
  208423. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  208424. return writableDiskPresent;
  208425. if (type == 0)
  208426. return noDisc;
  208427. else
  208428. return readOnlyDiskPresent;
  208429. }
  208430. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  208431. {
  208432. ComSmartPtr<IPropertyStorage> prop;
  208433. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  208434. return defaultReturn;
  208435. PROPSPEC iPropSpec;
  208436. iPropSpec.ulKind = PRSPEC_LPWSTR;
  208437. iPropSpec.lpwstr = name;
  208438. PROPVARIANT iPropVariant;
  208439. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  208440. ? defaultReturn : (int) iPropVariant.lVal;
  208441. }
  208442. bool setIntProperty (const LPOLESTR name, const int value) const
  208443. {
  208444. ComSmartPtr<IPropertyStorage> prop;
  208445. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  208446. return false;
  208447. PROPSPEC iPropSpec;
  208448. iPropSpec.ulKind = PRSPEC_LPWSTR;
  208449. iPropSpec.lpwstr = name;
  208450. PROPVARIANT iPropVariant;
  208451. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  208452. return false;
  208453. iPropVariant.lVal = (long) value;
  208454. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  208455. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  208456. }
  208457. void timerCallback()
  208458. {
  208459. const DiskState state = getDiskState();
  208460. if (state != lastState)
  208461. {
  208462. lastState = state;
  208463. owner.sendChangeMessage (&owner);
  208464. }
  208465. }
  208466. AudioCDBurner& owner;
  208467. DiskState lastState;
  208468. IDiscMaster* discMaster;
  208469. IDiscRecorder* discRecorder;
  208470. IRedbookDiscMaster* redbook;
  208471. AudioCDBurner::BurnProgressListener* listener;
  208472. float progress;
  208473. bool shouldCancel;
  208474. };
  208475. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  208476. {
  208477. IDiscMaster* discMaster = 0;
  208478. IDiscRecorder* discRecorder = enumCDBurners (0, deviceIndex, &discMaster);
  208479. if (discRecorder != 0)
  208480. pimpl = new Pimpl (*this, discMaster, discRecorder);
  208481. }
  208482. AudioCDBurner::~AudioCDBurner()
  208483. {
  208484. if (pimpl != 0)
  208485. pimpl.release()->releaseObjects();
  208486. }
  208487. const StringArray AudioCDBurner::findAvailableDevices()
  208488. {
  208489. StringArray devs;
  208490. enumCDBurners (&devs, -1, 0);
  208491. return devs;
  208492. }
  208493. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  208494. {
  208495. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  208496. if (b->pimpl == 0)
  208497. b = 0;
  208498. return b.release();
  208499. }
  208500. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  208501. {
  208502. return pimpl->getDiskState();
  208503. }
  208504. bool AudioCDBurner::isDiskPresent() const
  208505. {
  208506. return getDiskState() == writableDiskPresent;
  208507. }
  208508. bool AudioCDBurner::openTray()
  208509. {
  208510. const Pimpl::ScopedDiscOpener opener (*pimpl);
  208511. return SUCCEEDED (pimpl->discRecorder->Eject());
  208512. }
  208513. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  208514. {
  208515. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  208516. DiskState oldState = getDiskState();
  208517. DiskState newState = oldState;
  208518. while (newState == oldState && Time::currentTimeMillis() < timeout)
  208519. {
  208520. newState = getDiskState();
  208521. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  208522. }
  208523. return newState;
  208524. }
  208525. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  208526. {
  208527. Array<int> results;
  208528. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  208529. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  208530. for (int i = 0; i < numElementsInArray (speeds); ++i)
  208531. if (speeds[i] <= maxSpeed)
  208532. results.add (speeds[i]);
  208533. results.addIfNotAlreadyThere (maxSpeed);
  208534. return results;
  208535. }
  208536. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  208537. {
  208538. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  208539. return false;
  208540. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  208541. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  208542. }
  208543. int AudioCDBurner::getNumAvailableAudioBlocks() const
  208544. {
  208545. long blocksFree = 0;
  208546. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  208547. return blocksFree;
  208548. }
  208549. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  208550. bool performFakeBurnForTesting, int writeSpeed)
  208551. {
  208552. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  208553. pimpl->listener = listener;
  208554. pimpl->progress = 0;
  208555. pimpl->shouldCancel = false;
  208556. UINT_PTR cookie;
  208557. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  208558. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  208559. ejectDiscAfterwards);
  208560. String error;
  208561. if (hr != S_OK)
  208562. {
  208563. const char* e = "Couldn't open or write to the CD device";
  208564. if (hr == IMAPI_E_USERABORT)
  208565. e = "User cancelled the write operation";
  208566. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  208567. e = "No Disk present";
  208568. error = e;
  208569. }
  208570. pimpl->discMaster->ProgressUnadvise (cookie);
  208571. pimpl->listener = 0;
  208572. return error;
  208573. }
  208574. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  208575. {
  208576. if (audioSource == 0)
  208577. return false;
  208578. ScopedPointer<AudioSource> source (audioSource);
  208579. long bytesPerBlock;
  208580. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  208581. const int samplesPerBlock = bytesPerBlock / 4;
  208582. bool ok = true;
  208583. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  208584. HeapBlock <byte> buffer (bytesPerBlock);
  208585. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  208586. int samplesDone = 0;
  208587. source->prepareToPlay (samplesPerBlock, 44100.0);
  208588. while (ok)
  208589. {
  208590. {
  208591. AudioSourceChannelInfo info;
  208592. info.buffer = &sourceBuffer;
  208593. info.numSamples = samplesPerBlock;
  208594. info.startSample = 0;
  208595. sourceBuffer.clear();
  208596. source->getNextAudioBlock (info);
  208597. }
  208598. zeromem (buffer, bytesPerBlock);
  208599. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (0, 0),
  208600. buffer, samplesPerBlock, 4);
  208601. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (1, 0),
  208602. buffer + 2, samplesPerBlock, 4);
  208603. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  208604. if (FAILED (hr))
  208605. ok = false;
  208606. samplesDone += samplesPerBlock;
  208607. if (samplesDone >= numSamples)
  208608. break;
  208609. }
  208610. hr = pimpl->redbook->CloseAudioTrack();
  208611. return ok && hr == S_OK;
  208612. }
  208613. #endif
  208614. #endif
  208615. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  208616. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  208617. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208618. // compiled on its own).
  208619. #if JUCE_INCLUDED_FILE
  208620. using ::free;
  208621. namespace MidiConstants
  208622. {
  208623. static const int midiBufferSize = 1024 * 10;
  208624. static const int numInHeaders = 32;
  208625. static const int inBufferSize = 256;
  208626. }
  208627. class MidiInThread : public Thread
  208628. {
  208629. public:
  208630. MidiInThread (MidiInput* const input_,
  208631. MidiInputCallback* const callback_)
  208632. : Thread ("Juce Midi"),
  208633. hIn (0),
  208634. input (input_),
  208635. callback (callback_),
  208636. isStarted (false),
  208637. startTime (0),
  208638. pendingLength(0)
  208639. {
  208640. for (int i = MidiConstants::numInHeaders; --i >= 0;)
  208641. {
  208642. zeromem (&hdr[i], sizeof (MIDIHDR));
  208643. hdr[i].lpData = inData[i];
  208644. hdr[i].dwBufferLength = MidiConstants::inBufferSize;
  208645. }
  208646. };
  208647. ~MidiInThread()
  208648. {
  208649. stop();
  208650. if (hIn != 0)
  208651. {
  208652. int count = 5;
  208653. while (--count >= 0)
  208654. {
  208655. if (midiInClose (hIn) == MMSYSERR_NOERROR)
  208656. break;
  208657. Sleep (20);
  208658. }
  208659. }
  208660. }
  208661. void handle (const uint32 message, const uint32 timeStamp)
  208662. {
  208663. const int byte = message & 0xff;
  208664. if (byte < 0x80)
  208665. return;
  208666. const int numBytes = MidiMessage::getMessageLengthFromFirstByte ((uint8) byte);
  208667. const double time = timeStampToTime (timeStamp);
  208668. {
  208669. const ScopedLock sl (lock);
  208670. if (pendingLength < MidiConstants::midiBufferSize - 12)
  208671. {
  208672. char* const p = pending + pendingLength;
  208673. *(double*) p = time;
  208674. *(uint32*) (p + 8) = numBytes;
  208675. *(uint32*) (p + 12) = message;
  208676. pendingLength += 12 + numBytes;
  208677. }
  208678. else
  208679. {
  208680. jassertfalse // midi buffer overflow! You might need to increase the size..
  208681. }
  208682. }
  208683. notify();
  208684. }
  208685. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  208686. {
  208687. const int num = hdr->dwBytesRecorded;
  208688. if (num > 0)
  208689. {
  208690. const double time = timeStampToTime (timeStamp);
  208691. {
  208692. const ScopedLock sl (lock);
  208693. if (pendingLength < MidiConstants::midiBufferSize - (8 + num))
  208694. {
  208695. char* const p = pending + pendingLength;
  208696. *(double*) p = time;
  208697. *(uint32*) (p + 8) = num;
  208698. memcpy (p + 12, hdr->lpData, num);
  208699. pendingLength += 12 + num;
  208700. }
  208701. else
  208702. {
  208703. jassertfalse // midi buffer overflow! You might need to increase the size..
  208704. }
  208705. }
  208706. notify();
  208707. }
  208708. }
  208709. void writeBlock (const int i)
  208710. {
  208711. hdr[i].dwBytesRecorded = 0;
  208712. MMRESULT res = midiInPrepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  208713. jassert (res == MMSYSERR_NOERROR);
  208714. res = midiInAddBuffer (hIn, &hdr[i], sizeof (MIDIHDR));
  208715. jassert (res == MMSYSERR_NOERROR);
  208716. }
  208717. void run()
  208718. {
  208719. MemoryBlock pendingCopy (64);
  208720. while (! threadShouldExit())
  208721. {
  208722. for (int i = 0; i < MidiConstants::numInHeaders; ++i)
  208723. {
  208724. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  208725. {
  208726. MMRESULT res = midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  208727. (void) res;
  208728. jassert (res == MMSYSERR_NOERROR);
  208729. writeBlock (i);
  208730. }
  208731. }
  208732. int len;
  208733. {
  208734. const ScopedLock sl (lock);
  208735. len = pendingLength;
  208736. if (len > 0)
  208737. {
  208738. pendingCopy.ensureSize (len);
  208739. pendingCopy.copyFrom (pending, 0, len);
  208740. pendingLength = 0;
  208741. }
  208742. }
  208743. //xxx needs to figure out if blocks are broken up or not
  208744. if (len == 0)
  208745. {
  208746. wait (500);
  208747. }
  208748. else
  208749. {
  208750. const char* p = (const char*) pendingCopy.getData();
  208751. while (len > 0)
  208752. {
  208753. const double time = *(const double*) p;
  208754. const int messageLen = *(const int*) (p + 8);
  208755. const MidiMessage message ((const uint8*) (p + 12), messageLen, time);
  208756. callback->handleIncomingMidiMessage (input, message);
  208757. p += 12 + messageLen;
  208758. len -= 12 + messageLen;
  208759. }
  208760. }
  208761. }
  208762. }
  208763. void start()
  208764. {
  208765. jassert (hIn != 0);
  208766. if (hIn != 0 && ! isStarted)
  208767. {
  208768. stop();
  208769. activeMidiThreads.addIfNotAlreadyThere (this);
  208770. int i;
  208771. for (i = 0; i < MidiConstants::numInHeaders; ++i)
  208772. writeBlock (i);
  208773. startTime = Time::getMillisecondCounter();
  208774. MMRESULT res = midiInStart (hIn);
  208775. jassert (res == MMSYSERR_NOERROR);
  208776. if (res == MMSYSERR_NOERROR)
  208777. {
  208778. isStarted = true;
  208779. pendingLength = 0;
  208780. startThread (6);
  208781. }
  208782. }
  208783. }
  208784. void stop()
  208785. {
  208786. if (isStarted)
  208787. {
  208788. stopThread (5000);
  208789. midiInReset (hIn);
  208790. midiInStop (hIn);
  208791. activeMidiThreads.removeValue (this);
  208792. { const ScopedLock sl (lock); }
  208793. for (int i = MidiConstants::numInHeaders; --i >= 0;)
  208794. {
  208795. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  208796. {
  208797. int c = 10;
  208798. while (--c >= 0 && midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR)) == MIDIERR_STILLPLAYING)
  208799. Sleep (20);
  208800. jassert (c >= 0);
  208801. }
  208802. }
  208803. isStarted = false;
  208804. pendingLength = 0;
  208805. }
  208806. }
  208807. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  208808. {
  208809. MidiInThread* const thread = reinterpret_cast <MidiInThread*> (dwInstance);
  208810. if (thread != 0 && activeMidiThreads.contains (thread))
  208811. {
  208812. if (uMsg == MIM_DATA)
  208813. thread->handle ((uint32) midiMessage, (uint32) timeStamp);
  208814. else if (uMsg == MIM_LONGDATA)
  208815. thread->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  208816. }
  208817. }
  208818. juce_UseDebuggingNewOperator
  208819. HMIDIIN hIn;
  208820. private:
  208821. static Array <void*, CriticalSection> activeMidiThreads;
  208822. MidiInput* input;
  208823. MidiInputCallback* callback;
  208824. bool isStarted;
  208825. uint32 startTime;
  208826. CriticalSection lock;
  208827. MIDIHDR hdr [MidiConstants::numInHeaders];
  208828. char inData [MidiConstants::numInHeaders] [MidiConstants::inBufferSize];
  208829. int pendingLength;
  208830. char pending [MidiConstants::midiBufferSize];
  208831. double timeStampToTime (uint32 timeStamp)
  208832. {
  208833. timeStamp += startTime;
  208834. const uint32 now = Time::getMillisecondCounter();
  208835. if (timeStamp > now)
  208836. {
  208837. if (timeStamp > now + 2)
  208838. --startTime;
  208839. timeStamp = now;
  208840. }
  208841. return 0.001 * timeStamp;
  208842. }
  208843. MidiInThread (const MidiInThread&);
  208844. MidiInThread& operator= (const MidiInThread&);
  208845. };
  208846. Array <void*, CriticalSection> MidiInThread::activeMidiThreads;
  208847. const StringArray MidiInput::getDevices()
  208848. {
  208849. StringArray s;
  208850. const int num = midiInGetNumDevs();
  208851. for (int i = 0; i < num; ++i)
  208852. {
  208853. MIDIINCAPS mc;
  208854. zerostruct (mc);
  208855. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  208856. s.add (String (mc.szPname, sizeof (mc.szPname)));
  208857. }
  208858. return s;
  208859. }
  208860. int MidiInput::getDefaultDeviceIndex()
  208861. {
  208862. return 0;
  208863. }
  208864. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  208865. {
  208866. if (callback == 0)
  208867. return 0;
  208868. UINT deviceId = MIDI_MAPPER;
  208869. int n = 0;
  208870. String name;
  208871. const int num = midiInGetNumDevs();
  208872. for (int i = 0; i < num; ++i)
  208873. {
  208874. MIDIINCAPS mc;
  208875. zerostruct (mc);
  208876. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  208877. {
  208878. if (index == n)
  208879. {
  208880. deviceId = i;
  208881. name = String (mc.szPname, sizeof (mc.szPname));
  208882. break;
  208883. }
  208884. ++n;
  208885. }
  208886. }
  208887. ScopedPointer <MidiInput> in (new MidiInput (name));
  208888. ScopedPointer <MidiInThread> thread (new MidiInThread (in, callback));
  208889. HMIDIIN h;
  208890. HRESULT err = midiInOpen (&h, deviceId,
  208891. (DWORD_PTR) &MidiInThread::midiInCallback,
  208892. (DWORD_PTR) (MidiInThread*) thread,
  208893. CALLBACK_FUNCTION);
  208894. if (err == MMSYSERR_NOERROR)
  208895. {
  208896. thread->hIn = h;
  208897. in->internal = thread.release();
  208898. return in.release();
  208899. }
  208900. return 0;
  208901. }
  208902. MidiInput::MidiInput (const String& name_)
  208903. : name (name_),
  208904. internal (0)
  208905. {
  208906. }
  208907. MidiInput::~MidiInput()
  208908. {
  208909. delete static_cast <MidiInThread*> (internal);
  208910. }
  208911. void MidiInput::start()
  208912. {
  208913. static_cast <MidiInThread*> (internal)->start();
  208914. }
  208915. void MidiInput::stop()
  208916. {
  208917. static_cast <MidiInThread*> (internal)->stop();
  208918. }
  208919. struct MidiOutHandle
  208920. {
  208921. int refCount;
  208922. UINT deviceId;
  208923. HMIDIOUT handle;
  208924. static Array<MidiOutHandle*> activeHandles;
  208925. juce_UseDebuggingNewOperator
  208926. };
  208927. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  208928. const StringArray MidiOutput::getDevices()
  208929. {
  208930. StringArray s;
  208931. const int num = midiOutGetNumDevs();
  208932. for (int i = 0; i < num; ++i)
  208933. {
  208934. MIDIOUTCAPS mc;
  208935. zerostruct (mc);
  208936. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  208937. s.add (String (mc.szPname, sizeof (mc.szPname)));
  208938. }
  208939. return s;
  208940. }
  208941. int MidiOutput::getDefaultDeviceIndex()
  208942. {
  208943. const int num = midiOutGetNumDevs();
  208944. int n = 0;
  208945. for (int i = 0; i < num; ++i)
  208946. {
  208947. MIDIOUTCAPS mc;
  208948. zerostruct (mc);
  208949. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  208950. {
  208951. if ((mc.wTechnology & MOD_MAPPER) != 0)
  208952. return n;
  208953. ++n;
  208954. }
  208955. }
  208956. return 0;
  208957. }
  208958. MidiOutput* MidiOutput::openDevice (int index)
  208959. {
  208960. UINT deviceId = MIDI_MAPPER;
  208961. const int num = midiOutGetNumDevs();
  208962. int i, n = 0;
  208963. for (i = 0; i < num; ++i)
  208964. {
  208965. MIDIOUTCAPS mc;
  208966. zerostruct (mc);
  208967. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  208968. {
  208969. // use the microsoft sw synth as a default - best not to allow deviceId
  208970. // to be MIDI_MAPPER, or else device sharing breaks
  208971. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  208972. deviceId = i;
  208973. if (index == n)
  208974. {
  208975. deviceId = i;
  208976. break;
  208977. }
  208978. ++n;
  208979. }
  208980. }
  208981. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  208982. {
  208983. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  208984. if (han != 0 && han->deviceId == deviceId)
  208985. {
  208986. han->refCount++;
  208987. MidiOutput* const out = new MidiOutput();
  208988. out->internal = han;
  208989. return out;
  208990. }
  208991. }
  208992. for (i = 4; --i >= 0;)
  208993. {
  208994. HMIDIOUT h = 0;
  208995. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  208996. if (res == MMSYSERR_NOERROR)
  208997. {
  208998. MidiOutHandle* const han = new MidiOutHandle();
  208999. han->deviceId = deviceId;
  209000. han->refCount = 1;
  209001. han->handle = h;
  209002. MidiOutHandle::activeHandles.add (han);
  209003. MidiOutput* const out = new MidiOutput();
  209004. out->internal = han;
  209005. return out;
  209006. }
  209007. else if (res == MMSYSERR_ALLOCATED)
  209008. {
  209009. Sleep (100);
  209010. }
  209011. else
  209012. {
  209013. break;
  209014. }
  209015. }
  209016. return 0;
  209017. }
  209018. MidiOutput::~MidiOutput()
  209019. {
  209020. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  209021. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  209022. {
  209023. midiOutClose (h->handle);
  209024. MidiOutHandle::activeHandles.removeValue (h);
  209025. delete h;
  209026. }
  209027. }
  209028. void MidiOutput::reset()
  209029. {
  209030. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  209031. midiOutReset (h->handle);
  209032. }
  209033. bool MidiOutput::getVolume (float& leftVol,
  209034. float& rightVol)
  209035. {
  209036. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  209037. DWORD n;
  209038. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  209039. {
  209040. const unsigned short* const nn = (const unsigned short*) &n;
  209041. rightVol = nn[0] / (float) 0xffff;
  209042. leftVol = nn[1] / (float) 0xffff;
  209043. return true;
  209044. }
  209045. else
  209046. {
  209047. rightVol = leftVol = 1.0f;
  209048. return false;
  209049. }
  209050. }
  209051. void MidiOutput::setVolume (float leftVol,
  209052. float rightVol)
  209053. {
  209054. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  209055. DWORD n;
  209056. unsigned short* const nn = (unsigned short*) &n;
  209057. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  209058. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  209059. midiOutSetVolume (handle->handle, n);
  209060. }
  209061. void MidiOutput::sendMessageNow (const MidiMessage& message)
  209062. {
  209063. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  209064. if (message.getRawDataSize() > 3
  209065. || message.isSysEx())
  209066. {
  209067. MIDIHDR h;
  209068. zerostruct (h);
  209069. h.lpData = (char*) message.getRawData();
  209070. h.dwBufferLength = message.getRawDataSize();
  209071. h.dwBytesRecorded = message.getRawDataSize();
  209072. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  209073. {
  209074. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  209075. if (res == MMSYSERR_NOERROR)
  209076. {
  209077. while ((h.dwFlags & MHDR_DONE) == 0)
  209078. Sleep (1);
  209079. int count = 500; // 1 sec timeout
  209080. while (--count >= 0)
  209081. {
  209082. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  209083. if (res == MIDIERR_STILLPLAYING)
  209084. Sleep (2);
  209085. else
  209086. break;
  209087. }
  209088. }
  209089. }
  209090. }
  209091. else
  209092. {
  209093. midiOutShortMsg (handle->handle,
  209094. *(unsigned int*) message.getRawData());
  209095. }
  209096. }
  209097. #endif
  209098. /*** End of inlined file: juce_win32_Midi.cpp ***/
  209099. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  209100. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209101. // compiled on its own).
  209102. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  209103. #undef WINDOWS
  209104. // #define ASIO_DEBUGGING
  209105. #ifdef ASIO_DEBUGGING
  209106. #define log(a) { Logger::writeToLog (a); DBG (a) }
  209107. #else
  209108. #define log(a) {}
  209109. #endif
  209110. #ifdef ASIO_DEBUGGING
  209111. static void logError (const String& context, long error)
  209112. {
  209113. String err ("unknown error");
  209114. if (error == ASE_NotPresent)
  209115. err = "Not Present";
  209116. else if (error == ASE_HWMalfunction)
  209117. err = "Hardware Malfunction";
  209118. else if (error == ASE_InvalidParameter)
  209119. err = "Invalid Parameter";
  209120. else if (error == ASE_InvalidMode)
  209121. err = "Invalid Mode";
  209122. else if (error == ASE_SPNotAdvancing)
  209123. err = "Sample position not advancing";
  209124. else if (error == ASE_NoClock)
  209125. err = "No Clock";
  209126. else if (error == ASE_NoMemory)
  209127. err = "Out of memory";
  209128. log ("!!error: " + context + " - " + err);
  209129. }
  209130. #else
  209131. #define logError(a, b) {}
  209132. #endif
  209133. class ASIOAudioIODevice;
  209134. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  209135. static const int maxASIOChannels = 160;
  209136. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  209137. private Timer
  209138. {
  209139. public:
  209140. Component ourWindow;
  209141. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  209142. const String& optionalDllForDirectLoading_)
  209143. : AudioIODevice (name_, "ASIO"),
  209144. asioObject (0),
  209145. classId (classId_),
  209146. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  209147. currentBitDepth (16),
  209148. currentSampleRate (0),
  209149. isOpen_ (false),
  209150. isStarted (false),
  209151. postOutput (true),
  209152. insideControlPanelModalLoop (false),
  209153. shouldUsePreferredSize (false)
  209154. {
  209155. name = name_;
  209156. ourWindow.addToDesktop (0);
  209157. windowHandle = ourWindow.getWindowHandle();
  209158. jassert (currentASIODev [slotNumber] == 0);
  209159. currentASIODev [slotNumber] = this;
  209160. openDevice();
  209161. }
  209162. ~ASIOAudioIODevice()
  209163. {
  209164. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  209165. if (currentASIODev[i] == this)
  209166. currentASIODev[i] = 0;
  209167. close();
  209168. log ("ASIO - exiting");
  209169. removeCurrentDriver();
  209170. }
  209171. void updateSampleRates()
  209172. {
  209173. // find a list of sample rates..
  209174. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  209175. sampleRates.clear();
  209176. if (asioObject != 0)
  209177. {
  209178. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  209179. {
  209180. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  209181. if (err == 0)
  209182. {
  209183. sampleRates.add ((int) possibleSampleRates[index]);
  209184. log ("rate: " + String ((int) possibleSampleRates[index]));
  209185. }
  209186. else if (err != ASE_NoClock)
  209187. {
  209188. logError ("CanSampleRate", err);
  209189. }
  209190. }
  209191. if (sampleRates.size() == 0)
  209192. {
  209193. double cr = 0;
  209194. const long err = asioObject->getSampleRate (&cr);
  209195. log ("No sample rates supported - current rate: " + String ((int) cr));
  209196. if (err == 0)
  209197. sampleRates.add ((int) cr);
  209198. }
  209199. }
  209200. }
  209201. const StringArray getOutputChannelNames()
  209202. {
  209203. return outputChannelNames;
  209204. }
  209205. const StringArray getInputChannelNames()
  209206. {
  209207. return inputChannelNames;
  209208. }
  209209. int getNumSampleRates()
  209210. {
  209211. return sampleRates.size();
  209212. }
  209213. double getSampleRate (int index)
  209214. {
  209215. return sampleRates [index];
  209216. }
  209217. int getNumBufferSizesAvailable()
  209218. {
  209219. return bufferSizes.size();
  209220. }
  209221. int getBufferSizeSamples (int index)
  209222. {
  209223. return bufferSizes [index];
  209224. }
  209225. int getDefaultBufferSize()
  209226. {
  209227. return preferredSize;
  209228. }
  209229. const String open (const BigInteger& inputChannels,
  209230. const BigInteger& outputChannels,
  209231. double sr,
  209232. int bufferSizeSamples)
  209233. {
  209234. close();
  209235. currentCallback = 0;
  209236. if (bufferSizeSamples <= 0)
  209237. shouldUsePreferredSize = true;
  209238. if (asioObject == 0 || ! isASIOOpen)
  209239. {
  209240. log ("Warning: device not open");
  209241. const String err (openDevice());
  209242. if (asioObject == 0 || ! isASIOOpen)
  209243. return err;
  209244. }
  209245. isStarted = false;
  209246. bufferIndex = -1;
  209247. long err = 0;
  209248. long newPreferredSize = 0;
  209249. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  209250. minSize = 0;
  209251. maxSize = 0;
  209252. newPreferredSize = 0;
  209253. granularity = 0;
  209254. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  209255. {
  209256. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  209257. shouldUsePreferredSize = true;
  209258. preferredSize = newPreferredSize;
  209259. }
  209260. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  209261. // dynamic changes to the buffer size...
  209262. shouldUsePreferredSize = shouldUsePreferredSize
  209263. || getName().containsIgnoreCase ("Digidesign");
  209264. if (shouldUsePreferredSize)
  209265. {
  209266. log ("Using preferred size for buffer..");
  209267. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  209268. {
  209269. bufferSizeSamples = preferredSize;
  209270. }
  209271. else
  209272. {
  209273. bufferSizeSamples = 1024;
  209274. logError ("GetBufferSize1", err);
  209275. }
  209276. shouldUsePreferredSize = false;
  209277. }
  209278. int sampleRate = roundDoubleToInt (sr);
  209279. currentSampleRate = sampleRate;
  209280. currentBlockSizeSamples = bufferSizeSamples;
  209281. currentChansOut.clear();
  209282. currentChansIn.clear();
  209283. zeromem (inBuffers, sizeof (inBuffers));
  209284. zeromem (outBuffers, sizeof (outBuffers));
  209285. updateSampleRates();
  209286. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  209287. sampleRate = sampleRates[0];
  209288. jassert (sampleRate != 0);
  209289. if (sampleRate == 0)
  209290. sampleRate = 44100;
  209291. long numSources = 32;
  209292. ASIOClockSource clocks[32];
  209293. zeromem (clocks, sizeof (clocks));
  209294. asioObject->getClockSources (clocks, &numSources);
  209295. bool isSourceSet = false;
  209296. // careful not to remove this loop because it does more than just logging!
  209297. int i;
  209298. for (i = 0; i < numSources; ++i)
  209299. {
  209300. String s ("clock: ");
  209301. s += clocks[i].name;
  209302. if (clocks[i].isCurrentSource)
  209303. {
  209304. isSourceSet = true;
  209305. s << " (cur)";
  209306. }
  209307. log (s);
  209308. }
  209309. if (numSources > 1 && ! isSourceSet)
  209310. {
  209311. log ("setting clock source");
  209312. asioObject->setClockSource (clocks[0].index);
  209313. Thread::sleep (20);
  209314. }
  209315. else
  209316. {
  209317. if (numSources == 0)
  209318. {
  209319. log ("ASIO - no clock sources!");
  209320. }
  209321. }
  209322. double cr = 0;
  209323. err = asioObject->getSampleRate (&cr);
  209324. if (err == 0)
  209325. {
  209326. currentSampleRate = cr;
  209327. }
  209328. else
  209329. {
  209330. logError ("GetSampleRate", err);
  209331. currentSampleRate = 0;
  209332. }
  209333. error = String::empty;
  209334. needToReset = false;
  209335. isReSync = false;
  209336. err = 0;
  209337. bool buffersCreated = false;
  209338. if (currentSampleRate != sampleRate)
  209339. {
  209340. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  209341. err = asioObject->setSampleRate (sampleRate);
  209342. if (err == ASE_NoClock && numSources > 0)
  209343. {
  209344. log ("trying to set a clock source..");
  209345. Thread::sleep (10);
  209346. err = asioObject->setClockSource (clocks[0].index);
  209347. if (err != 0)
  209348. {
  209349. logError ("SetClock", err);
  209350. }
  209351. Thread::sleep (10);
  209352. err = asioObject->setSampleRate (sampleRate);
  209353. }
  209354. }
  209355. if (err == 0)
  209356. {
  209357. currentSampleRate = sampleRate;
  209358. if (needToReset)
  209359. {
  209360. if (isReSync)
  209361. {
  209362. log ("Resync request");
  209363. }
  209364. log ("! Resetting ASIO after sample rate change");
  209365. removeCurrentDriver();
  209366. loadDriver();
  209367. const String error (initDriver());
  209368. if (error.isNotEmpty())
  209369. {
  209370. log ("ASIOInit: " + error);
  209371. }
  209372. needToReset = false;
  209373. isReSync = false;
  209374. }
  209375. numActiveInputChans = 0;
  209376. numActiveOutputChans = 0;
  209377. ASIOBufferInfo* info = bufferInfos;
  209378. int i;
  209379. for (i = 0; i < totalNumInputChans; ++i)
  209380. {
  209381. if (inputChannels[i])
  209382. {
  209383. currentChansIn.setBit (i);
  209384. info->isInput = 1;
  209385. info->channelNum = i;
  209386. info->buffers[0] = info->buffers[1] = 0;
  209387. ++info;
  209388. ++numActiveInputChans;
  209389. }
  209390. }
  209391. for (i = 0; i < totalNumOutputChans; ++i)
  209392. {
  209393. if (outputChannels[i])
  209394. {
  209395. currentChansOut.setBit (i);
  209396. info->isInput = 0;
  209397. info->channelNum = i;
  209398. info->buffers[0] = info->buffers[1] = 0;
  209399. ++info;
  209400. ++numActiveOutputChans;
  209401. }
  209402. }
  209403. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  209404. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  209405. if (currentASIODev[0] == this)
  209406. {
  209407. callbacks.bufferSwitch = &bufferSwitchCallback0;
  209408. callbacks.asioMessage = &asioMessagesCallback0;
  209409. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  209410. }
  209411. else if (currentASIODev[1] == this)
  209412. {
  209413. callbacks.bufferSwitch = &bufferSwitchCallback1;
  209414. callbacks.asioMessage = &asioMessagesCallback1;
  209415. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  209416. }
  209417. else if (currentASIODev[2] == this)
  209418. {
  209419. callbacks.bufferSwitch = &bufferSwitchCallback2;
  209420. callbacks.asioMessage = &asioMessagesCallback2;
  209421. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  209422. }
  209423. else
  209424. {
  209425. jassertfalse
  209426. }
  209427. log ("disposing buffers");
  209428. err = asioObject->disposeBuffers();
  209429. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  209430. err = asioObject->createBuffers (bufferInfos,
  209431. totalBuffers,
  209432. currentBlockSizeSamples,
  209433. &callbacks);
  209434. if (err != 0)
  209435. {
  209436. currentBlockSizeSamples = preferredSize;
  209437. logError ("create buffers 2", err);
  209438. asioObject->disposeBuffers();
  209439. err = asioObject->createBuffers (bufferInfos,
  209440. totalBuffers,
  209441. currentBlockSizeSamples,
  209442. &callbacks);
  209443. }
  209444. if (err == 0)
  209445. {
  209446. buffersCreated = true;
  209447. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  209448. int n = 0;
  209449. Array <int> types;
  209450. currentBitDepth = 16;
  209451. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  209452. {
  209453. if (inputChannels[i])
  209454. {
  209455. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  209456. ASIOChannelInfo channelInfo;
  209457. zerostruct (channelInfo);
  209458. channelInfo.channel = i;
  209459. channelInfo.isInput = 1;
  209460. asioObject->getChannelInfo (&channelInfo);
  209461. types.addIfNotAlreadyThere (channelInfo.type);
  209462. typeToFormatParameters (channelInfo.type,
  209463. inputChannelBitDepths[n],
  209464. inputChannelBytesPerSample[n],
  209465. inputChannelIsFloat[n],
  209466. inputChannelLittleEndian[n]);
  209467. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  209468. ++n;
  209469. }
  209470. }
  209471. jassert (numActiveInputChans == n);
  209472. n = 0;
  209473. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  209474. {
  209475. if (outputChannels[i])
  209476. {
  209477. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  209478. ASIOChannelInfo channelInfo;
  209479. zerostruct (channelInfo);
  209480. channelInfo.channel = i;
  209481. channelInfo.isInput = 0;
  209482. asioObject->getChannelInfo (&channelInfo);
  209483. types.addIfNotAlreadyThere (channelInfo.type);
  209484. typeToFormatParameters (channelInfo.type,
  209485. outputChannelBitDepths[n],
  209486. outputChannelBytesPerSample[n],
  209487. outputChannelIsFloat[n],
  209488. outputChannelLittleEndian[n]);
  209489. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  209490. ++n;
  209491. }
  209492. }
  209493. jassert (numActiveOutputChans == n);
  209494. for (i = types.size(); --i >= 0;)
  209495. {
  209496. log ("channel format: " + String (types[i]));
  209497. }
  209498. jassert (n <= totalBuffers);
  209499. for (i = 0; i < numActiveOutputChans; ++i)
  209500. {
  209501. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  209502. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  209503. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  209504. {
  209505. log ("!! Null buffers");
  209506. }
  209507. else
  209508. {
  209509. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  209510. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  209511. }
  209512. }
  209513. inputLatency = outputLatency = 0;
  209514. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  209515. {
  209516. log ("ASIO - no latencies");
  209517. }
  209518. else
  209519. {
  209520. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  209521. }
  209522. isOpen_ = true;
  209523. log ("starting ASIO");
  209524. calledback = false;
  209525. err = asioObject->start();
  209526. if (err != 0)
  209527. {
  209528. isOpen_ = false;
  209529. log ("ASIO - stop on failure");
  209530. Thread::sleep (10);
  209531. asioObject->stop();
  209532. error = "Can't start device";
  209533. Thread::sleep (10);
  209534. }
  209535. else
  209536. {
  209537. int count = 300;
  209538. while (--count > 0 && ! calledback)
  209539. Thread::sleep (10);
  209540. isStarted = true;
  209541. if (! calledback)
  209542. {
  209543. error = "Device didn't start correctly";
  209544. log ("ASIO didn't callback - stopping..");
  209545. asioObject->stop();
  209546. }
  209547. }
  209548. }
  209549. else
  209550. {
  209551. error = "Can't create i/o buffers";
  209552. }
  209553. }
  209554. else
  209555. {
  209556. error = "Can't set sample rate: ";
  209557. error << sampleRate;
  209558. }
  209559. if (error.isNotEmpty())
  209560. {
  209561. logError (error, err);
  209562. if (asioObject != 0 && buffersCreated)
  209563. asioObject->disposeBuffers();
  209564. Thread::sleep (20);
  209565. isStarted = false;
  209566. isOpen_ = false;
  209567. close();
  209568. }
  209569. needToReset = false;
  209570. isReSync = false;
  209571. return error;
  209572. }
  209573. void close()
  209574. {
  209575. error = String::empty;
  209576. stopTimer();
  209577. stop();
  209578. if (isASIOOpen && isOpen_)
  209579. {
  209580. const ScopedLock sl (callbackLock);
  209581. isOpen_ = false;
  209582. isStarted = false;
  209583. needToReset = false;
  209584. isReSync = false;
  209585. log ("ASIO - stopping");
  209586. if (asioObject != 0)
  209587. {
  209588. Thread::sleep (20);
  209589. asioObject->stop();
  209590. Thread::sleep (10);
  209591. asioObject->disposeBuffers();
  209592. }
  209593. Thread::sleep (10);
  209594. }
  209595. }
  209596. bool isOpen()
  209597. {
  209598. return isOpen_ || insideControlPanelModalLoop;
  209599. }
  209600. int getCurrentBufferSizeSamples()
  209601. {
  209602. return currentBlockSizeSamples;
  209603. }
  209604. double getCurrentSampleRate()
  209605. {
  209606. return currentSampleRate;
  209607. }
  209608. const BigInteger getActiveOutputChannels() const
  209609. {
  209610. return currentChansOut;
  209611. }
  209612. const BigInteger getActiveInputChannels() const
  209613. {
  209614. return currentChansIn;
  209615. }
  209616. int getCurrentBitDepth()
  209617. {
  209618. return currentBitDepth;
  209619. }
  209620. int getOutputLatencyInSamples()
  209621. {
  209622. return outputLatency + currentBlockSizeSamples / 4;
  209623. }
  209624. int getInputLatencyInSamples()
  209625. {
  209626. return inputLatency + currentBlockSizeSamples / 4;
  209627. }
  209628. void start (AudioIODeviceCallback* callback)
  209629. {
  209630. if (callback != 0)
  209631. {
  209632. callback->audioDeviceAboutToStart (this);
  209633. const ScopedLock sl (callbackLock);
  209634. currentCallback = callback;
  209635. }
  209636. }
  209637. void stop()
  209638. {
  209639. AudioIODeviceCallback* const lastCallback = currentCallback;
  209640. {
  209641. const ScopedLock sl (callbackLock);
  209642. currentCallback = 0;
  209643. }
  209644. if (lastCallback != 0)
  209645. lastCallback->audioDeviceStopped();
  209646. }
  209647. bool isPlaying()
  209648. {
  209649. return isASIOOpen && (currentCallback != 0);
  209650. }
  209651. const String getLastError()
  209652. {
  209653. return error;
  209654. }
  209655. bool hasControlPanel() const
  209656. {
  209657. return true;
  209658. }
  209659. bool showControlPanel()
  209660. {
  209661. log ("ASIO - showing control panel");
  209662. Component modalWindow (String::empty);
  209663. modalWindow.setOpaque (true);
  209664. modalWindow.addToDesktop (0);
  209665. modalWindow.enterModalState();
  209666. bool done = false;
  209667. JUCE_TRY
  209668. {
  209669. // are there are devices that need to be closed before showing their control panel?
  209670. // close();
  209671. insideControlPanelModalLoop = true;
  209672. const uint32 started = Time::getMillisecondCounter();
  209673. if (asioObject != 0)
  209674. {
  209675. asioObject->controlPanel();
  209676. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  209677. log ("spent: " + String (spent));
  209678. if (spent > 300)
  209679. {
  209680. shouldUsePreferredSize = true;
  209681. done = true;
  209682. }
  209683. }
  209684. }
  209685. JUCE_CATCH_ALL
  209686. insideControlPanelModalLoop = false;
  209687. return done;
  209688. }
  209689. void resetRequest() throw()
  209690. {
  209691. needToReset = true;
  209692. }
  209693. void resyncRequest() throw()
  209694. {
  209695. needToReset = true;
  209696. isReSync = true;
  209697. }
  209698. void timerCallback()
  209699. {
  209700. if (! insideControlPanelModalLoop)
  209701. {
  209702. stopTimer();
  209703. // used to cause a reset
  209704. log ("! ASIO restart request!");
  209705. if (isOpen_)
  209706. {
  209707. AudioIODeviceCallback* const oldCallback = currentCallback;
  209708. close();
  209709. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  209710. currentSampleRate, currentBlockSizeSamples);
  209711. if (oldCallback != 0)
  209712. start (oldCallback);
  209713. }
  209714. }
  209715. else
  209716. {
  209717. startTimer (100);
  209718. }
  209719. }
  209720. juce_UseDebuggingNewOperator
  209721. private:
  209722. IASIO* volatile asioObject;
  209723. ASIOCallbacks callbacks;
  209724. void* windowHandle;
  209725. CLSID classId;
  209726. const String optionalDllForDirectLoading;
  209727. String error;
  209728. long totalNumInputChans, totalNumOutputChans;
  209729. StringArray inputChannelNames, outputChannelNames;
  209730. Array<int> sampleRates, bufferSizes;
  209731. long inputLatency, outputLatency;
  209732. long minSize, maxSize, preferredSize, granularity;
  209733. int volatile currentBlockSizeSamples;
  209734. int volatile currentBitDepth;
  209735. double volatile currentSampleRate;
  209736. BigInteger currentChansOut, currentChansIn;
  209737. AudioIODeviceCallback* volatile currentCallback;
  209738. CriticalSection callbackLock;
  209739. ASIOBufferInfo bufferInfos [maxASIOChannels];
  209740. float* inBuffers [maxASIOChannels];
  209741. float* outBuffers [maxASIOChannels];
  209742. int inputChannelBitDepths [maxASIOChannels];
  209743. int outputChannelBitDepths [maxASIOChannels];
  209744. int inputChannelBytesPerSample [maxASIOChannels];
  209745. int outputChannelBytesPerSample [maxASIOChannels];
  209746. bool inputChannelIsFloat [maxASIOChannels];
  209747. bool outputChannelIsFloat [maxASIOChannels];
  209748. bool inputChannelLittleEndian [maxASIOChannels];
  209749. bool outputChannelLittleEndian [maxASIOChannels];
  209750. WaitableEvent event1;
  209751. HeapBlock <float> tempBuffer;
  209752. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  209753. bool isOpen_, isStarted;
  209754. bool volatile isASIOOpen;
  209755. bool volatile calledback;
  209756. bool volatile littleEndian, postOutput, needToReset, isReSync;
  209757. bool volatile insideControlPanelModalLoop;
  209758. bool volatile shouldUsePreferredSize;
  209759. void removeCurrentDriver()
  209760. {
  209761. if (asioObject != 0)
  209762. {
  209763. asioObject->Release();
  209764. asioObject = 0;
  209765. }
  209766. }
  209767. bool loadDriver()
  209768. {
  209769. removeCurrentDriver();
  209770. JUCE_TRY
  209771. {
  209772. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  209773. classId, (void**) &asioObject) == S_OK)
  209774. {
  209775. return true;
  209776. }
  209777. // If a class isn't registered but we have a path for it, we can fallback to
  209778. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  209779. if (optionalDllForDirectLoading.isNotEmpty())
  209780. {
  209781. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  209782. if (h != 0)
  209783. {
  209784. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  209785. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  209786. if (dllGetClassObject != 0)
  209787. {
  209788. IClassFactory* classFactory = 0;
  209789. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  209790. if (classFactory != 0)
  209791. {
  209792. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  209793. classFactory->Release();
  209794. }
  209795. return asioObject != 0;
  209796. }
  209797. }
  209798. }
  209799. }
  209800. JUCE_CATCH_ALL
  209801. asioObject = 0;
  209802. return false;
  209803. }
  209804. const String initDriver()
  209805. {
  209806. if (asioObject != 0)
  209807. {
  209808. char buffer [256];
  209809. zeromem (buffer, sizeof (buffer));
  209810. if (! asioObject->init (windowHandle))
  209811. {
  209812. asioObject->getErrorMessage (buffer);
  209813. return String (buffer, sizeof (buffer) - 1);
  209814. }
  209815. // just in case any daft drivers expect this to be called..
  209816. asioObject->getDriverName (buffer);
  209817. return String::empty;
  209818. }
  209819. return "No Driver";
  209820. }
  209821. const String openDevice()
  209822. {
  209823. // use this in case the driver starts opening dialog boxes..
  209824. Component modalWindow (String::empty);
  209825. modalWindow.setOpaque (true);
  209826. modalWindow.addToDesktop (0);
  209827. modalWindow.enterModalState();
  209828. // open the device and get its info..
  209829. log ("opening ASIO device: " + getName());
  209830. needToReset = false;
  209831. isReSync = false;
  209832. outputChannelNames.clear();
  209833. inputChannelNames.clear();
  209834. bufferSizes.clear();
  209835. sampleRates.clear();
  209836. isASIOOpen = false;
  209837. isOpen_ = false;
  209838. totalNumInputChans = 0;
  209839. totalNumOutputChans = 0;
  209840. numActiveInputChans = 0;
  209841. numActiveOutputChans = 0;
  209842. currentCallback = 0;
  209843. error = String::empty;
  209844. if (getName().isEmpty())
  209845. return error;
  209846. long err = 0;
  209847. if (loadDriver())
  209848. {
  209849. if ((error = initDriver()).isEmpty())
  209850. {
  209851. numActiveInputChans = 0;
  209852. numActiveOutputChans = 0;
  209853. totalNumInputChans = 0;
  209854. totalNumOutputChans = 0;
  209855. if (asioObject != 0
  209856. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  209857. {
  209858. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  209859. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  209860. {
  209861. // find a list of buffer sizes..
  209862. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  209863. if (granularity >= 0)
  209864. {
  209865. granularity = jmax (1, (int) granularity);
  209866. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  209867. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  209868. }
  209869. else if (granularity < 0)
  209870. {
  209871. for (int i = 0; i < 18; ++i)
  209872. {
  209873. const int s = (1 << i);
  209874. if (s >= minSize && s <= maxSize)
  209875. bufferSizes.add (s);
  209876. }
  209877. }
  209878. if (! bufferSizes.contains (preferredSize))
  209879. bufferSizes.insert (0, preferredSize);
  209880. double currentRate = 0;
  209881. asioObject->getSampleRate (&currentRate);
  209882. if (currentRate <= 0.0 || currentRate > 192001.0)
  209883. {
  209884. log ("setting sample rate");
  209885. err = asioObject->setSampleRate (44100.0);
  209886. if (err != 0)
  209887. {
  209888. logError ("setting sample rate", err);
  209889. }
  209890. asioObject->getSampleRate (&currentRate);
  209891. }
  209892. currentSampleRate = currentRate;
  209893. postOutput = (asioObject->outputReady() == 0);
  209894. if (postOutput)
  209895. {
  209896. log ("ASIO outputReady = ok");
  209897. }
  209898. updateSampleRates();
  209899. // ..because cubase does it at this point
  209900. inputLatency = outputLatency = 0;
  209901. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  209902. {
  209903. log ("ASIO - no latencies");
  209904. }
  209905. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  209906. // create some dummy buffers now.. because cubase does..
  209907. numActiveInputChans = 0;
  209908. numActiveOutputChans = 0;
  209909. ASIOBufferInfo* info = bufferInfos;
  209910. int i, numChans = 0;
  209911. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  209912. {
  209913. info->isInput = 1;
  209914. info->channelNum = i;
  209915. info->buffers[0] = info->buffers[1] = 0;
  209916. ++info;
  209917. ++numChans;
  209918. }
  209919. const int outputBufferIndex = numChans;
  209920. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  209921. {
  209922. info->isInput = 0;
  209923. info->channelNum = i;
  209924. info->buffers[0] = info->buffers[1] = 0;
  209925. ++info;
  209926. ++numChans;
  209927. }
  209928. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  209929. if (currentASIODev[0] == this)
  209930. {
  209931. callbacks.bufferSwitch = &bufferSwitchCallback0;
  209932. callbacks.asioMessage = &asioMessagesCallback0;
  209933. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  209934. }
  209935. else if (currentASIODev[1] == this)
  209936. {
  209937. callbacks.bufferSwitch = &bufferSwitchCallback1;
  209938. callbacks.asioMessage = &asioMessagesCallback1;
  209939. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  209940. }
  209941. else if (currentASIODev[2] == this)
  209942. {
  209943. callbacks.bufferSwitch = &bufferSwitchCallback2;
  209944. callbacks.asioMessage = &asioMessagesCallback2;
  209945. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  209946. }
  209947. else
  209948. {
  209949. jassertfalse
  209950. }
  209951. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  209952. if (preferredSize > 0)
  209953. {
  209954. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  209955. if (err != 0)
  209956. {
  209957. logError ("dummy buffers", err);
  209958. }
  209959. }
  209960. long newInps = 0, newOuts = 0;
  209961. asioObject->getChannels (&newInps, &newOuts);
  209962. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  209963. {
  209964. totalNumInputChans = newInps;
  209965. totalNumOutputChans = newOuts;
  209966. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  209967. }
  209968. updateSampleRates();
  209969. ASIOChannelInfo channelInfo;
  209970. channelInfo.type = 0;
  209971. for (i = 0; i < totalNumInputChans; ++i)
  209972. {
  209973. zerostruct (channelInfo);
  209974. channelInfo.channel = i;
  209975. channelInfo.isInput = 1;
  209976. asioObject->getChannelInfo (&channelInfo);
  209977. inputChannelNames.add (String (channelInfo.name));
  209978. }
  209979. for (i = 0; i < totalNumOutputChans; ++i)
  209980. {
  209981. zerostruct (channelInfo);
  209982. channelInfo.channel = i;
  209983. channelInfo.isInput = 0;
  209984. asioObject->getChannelInfo (&channelInfo);
  209985. outputChannelNames.add (String (channelInfo.name));
  209986. typeToFormatParameters (channelInfo.type,
  209987. outputChannelBitDepths[i],
  209988. outputChannelBytesPerSample[i],
  209989. outputChannelIsFloat[i],
  209990. outputChannelLittleEndian[i]);
  209991. if (i < 2)
  209992. {
  209993. // clear the channels that are used with the dummy stuff
  209994. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  209995. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  209996. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  209997. }
  209998. }
  209999. outputChannelNames.trim();
  210000. inputChannelNames.trim();
  210001. outputChannelNames.appendNumbersToDuplicates (false, true);
  210002. inputChannelNames.appendNumbersToDuplicates (false, true);
  210003. // start and stop because cubase does it..
  210004. asioObject->getLatencies (&inputLatency, &outputLatency);
  210005. if ((err = asioObject->start()) != 0)
  210006. {
  210007. // ignore an error here, as it might start later after setting other stuff up
  210008. logError ("ASIO start", err);
  210009. }
  210010. Thread::sleep (100);
  210011. asioObject->stop();
  210012. }
  210013. else
  210014. {
  210015. error = "Can't detect buffer sizes";
  210016. }
  210017. }
  210018. else
  210019. {
  210020. error = "Can't detect asio channels";
  210021. }
  210022. }
  210023. }
  210024. else
  210025. {
  210026. error = "No such device";
  210027. }
  210028. if (error.isNotEmpty())
  210029. {
  210030. logError (error, err);
  210031. if (asioObject != 0)
  210032. asioObject->disposeBuffers();
  210033. removeCurrentDriver();
  210034. isASIOOpen = false;
  210035. }
  210036. else
  210037. {
  210038. isASIOOpen = true;
  210039. log ("ASIO device open");
  210040. }
  210041. isOpen_ = false;
  210042. needToReset = false;
  210043. isReSync = false;
  210044. return error;
  210045. }
  210046. void callback (const long index)
  210047. {
  210048. if (isStarted)
  210049. {
  210050. bufferIndex = index;
  210051. processBuffer();
  210052. }
  210053. else
  210054. {
  210055. if (postOutput && (asioObject != 0))
  210056. asioObject->outputReady();
  210057. }
  210058. calledback = true;
  210059. }
  210060. void processBuffer()
  210061. {
  210062. const ASIOBufferInfo* const infos = bufferInfos;
  210063. const int bi = bufferIndex;
  210064. const ScopedLock sl (callbackLock);
  210065. if (needToReset)
  210066. {
  210067. needToReset = false;
  210068. if (isReSync)
  210069. {
  210070. log ("! ASIO resync");
  210071. isReSync = false;
  210072. }
  210073. else
  210074. {
  210075. startTimer (20);
  210076. }
  210077. }
  210078. if (bi >= 0)
  210079. {
  210080. const int samps = currentBlockSizeSamples;
  210081. if (currentCallback != 0)
  210082. {
  210083. int i;
  210084. for (i = 0; i < numActiveInputChans; ++i)
  210085. {
  210086. float* const dst = inBuffers[i];
  210087. jassert (dst != 0);
  210088. const char* const src = (const char*) (infos[i].buffers[bi]);
  210089. if (inputChannelIsFloat[i])
  210090. {
  210091. memcpy (dst, src, samps * sizeof (float));
  210092. }
  210093. else
  210094. {
  210095. jassert (dst == tempBuffer + (samps * i));
  210096. switch (inputChannelBitDepths[i])
  210097. {
  210098. case 16:
  210099. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  210100. samps, inputChannelLittleEndian[i]);
  210101. break;
  210102. case 24:
  210103. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  210104. samps, inputChannelLittleEndian[i]);
  210105. break;
  210106. case 32:
  210107. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  210108. samps, inputChannelLittleEndian[i]);
  210109. break;
  210110. case 64:
  210111. jassertfalse
  210112. break;
  210113. }
  210114. }
  210115. }
  210116. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  210117. numActiveInputChans,
  210118. outBuffers,
  210119. numActiveOutputChans,
  210120. samps);
  210121. for (i = 0; i < numActiveOutputChans; ++i)
  210122. {
  210123. float* const src = outBuffers[i];
  210124. jassert (src != 0);
  210125. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  210126. if (outputChannelIsFloat[i])
  210127. {
  210128. memcpy (dst, src, samps * sizeof (float));
  210129. }
  210130. else
  210131. {
  210132. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  210133. switch (outputChannelBitDepths[i])
  210134. {
  210135. case 16:
  210136. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  210137. samps, outputChannelLittleEndian[i]);
  210138. break;
  210139. case 24:
  210140. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  210141. samps, outputChannelLittleEndian[i]);
  210142. break;
  210143. case 32:
  210144. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  210145. samps, outputChannelLittleEndian[i]);
  210146. break;
  210147. case 64:
  210148. jassertfalse
  210149. break;
  210150. }
  210151. }
  210152. }
  210153. }
  210154. else
  210155. {
  210156. for (int i = 0; i < numActiveOutputChans; ++i)
  210157. {
  210158. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  210159. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  210160. }
  210161. }
  210162. }
  210163. if (postOutput)
  210164. asioObject->outputReady();
  210165. }
  210166. static ASIOTime* bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  210167. {
  210168. if (currentASIODev[0] != 0)
  210169. currentASIODev[0]->callback (index);
  210170. return 0;
  210171. }
  210172. static ASIOTime* bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  210173. {
  210174. if (currentASIODev[1] != 0)
  210175. currentASIODev[1]->callback (index);
  210176. return 0;
  210177. }
  210178. static ASIOTime* bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  210179. {
  210180. if (currentASIODev[2] != 0)
  210181. currentASIODev[2]->callback (index);
  210182. return 0;
  210183. }
  210184. static void bufferSwitchCallback0 (long index, long)
  210185. {
  210186. if (currentASIODev[0] != 0)
  210187. currentASIODev[0]->callback (index);
  210188. }
  210189. static void bufferSwitchCallback1 (long index, long)
  210190. {
  210191. if (currentASIODev[1] != 0)
  210192. currentASIODev[1]->callback (index);
  210193. }
  210194. static void bufferSwitchCallback2 (long index, long)
  210195. {
  210196. if (currentASIODev[2] != 0)
  210197. currentASIODev[2]->callback (index);
  210198. }
  210199. static long asioMessagesCallback0 (long selector, long value, void*, double*)
  210200. {
  210201. return asioMessagesCallback (selector, value, 0);
  210202. }
  210203. static long asioMessagesCallback1 (long selector, long value, void*, double*)
  210204. {
  210205. return asioMessagesCallback (selector, value, 1);
  210206. }
  210207. static long asioMessagesCallback2 (long selector, long value, void*, double*)
  210208. {
  210209. return asioMessagesCallback (selector, value, 2);
  210210. }
  210211. static long asioMessagesCallback (long selector, long value, const int deviceIndex)
  210212. {
  210213. switch (selector)
  210214. {
  210215. case kAsioSelectorSupported:
  210216. if (value == kAsioResetRequest
  210217. || value == kAsioEngineVersion
  210218. || value == kAsioResyncRequest
  210219. || value == kAsioLatenciesChanged
  210220. || value == kAsioSupportsInputMonitor)
  210221. return 1;
  210222. break;
  210223. case kAsioBufferSizeChange:
  210224. break;
  210225. case kAsioResetRequest:
  210226. if (currentASIODev[deviceIndex] != 0)
  210227. currentASIODev[deviceIndex]->resetRequest();
  210228. return 1;
  210229. case kAsioResyncRequest:
  210230. if (currentASIODev[deviceIndex] != 0)
  210231. currentASIODev[deviceIndex]->resyncRequest();
  210232. return 1;
  210233. case kAsioLatenciesChanged:
  210234. return 1;
  210235. case kAsioEngineVersion:
  210236. return 2;
  210237. case kAsioSupportsTimeInfo:
  210238. case kAsioSupportsTimeCode:
  210239. return 0;
  210240. }
  210241. return 0;
  210242. }
  210243. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  210244. {
  210245. }
  210246. static void convertInt16ToFloat (const char* src,
  210247. float* dest,
  210248. const int srcStrideBytes,
  210249. int numSamples,
  210250. const bool littleEndian) throw()
  210251. {
  210252. const double g = 1.0 / 32768.0;
  210253. if (littleEndian)
  210254. {
  210255. while (--numSamples >= 0)
  210256. {
  210257. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  210258. src += srcStrideBytes;
  210259. }
  210260. }
  210261. else
  210262. {
  210263. while (--numSamples >= 0)
  210264. {
  210265. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  210266. src += srcStrideBytes;
  210267. }
  210268. }
  210269. }
  210270. static void convertFloatToInt16 (const float* src,
  210271. char* dest,
  210272. const int dstStrideBytes,
  210273. int numSamples,
  210274. const bool littleEndian) throw()
  210275. {
  210276. const double maxVal = (double) 0x7fff;
  210277. if (littleEndian)
  210278. {
  210279. while (--numSamples >= 0)
  210280. {
  210281. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  210282. dest += dstStrideBytes;
  210283. }
  210284. }
  210285. else
  210286. {
  210287. while (--numSamples >= 0)
  210288. {
  210289. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  210290. dest += dstStrideBytes;
  210291. }
  210292. }
  210293. }
  210294. static void convertInt24ToFloat (const char* src,
  210295. float* dest,
  210296. const int srcStrideBytes,
  210297. int numSamples,
  210298. const bool littleEndian) throw()
  210299. {
  210300. const double g = 1.0 / 0x7fffff;
  210301. if (littleEndian)
  210302. {
  210303. while (--numSamples >= 0)
  210304. {
  210305. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  210306. src += srcStrideBytes;
  210307. }
  210308. }
  210309. else
  210310. {
  210311. while (--numSamples >= 0)
  210312. {
  210313. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  210314. src += srcStrideBytes;
  210315. }
  210316. }
  210317. }
  210318. static void convertFloatToInt24 (const float* src,
  210319. char* dest,
  210320. const int dstStrideBytes,
  210321. int numSamples,
  210322. const bool littleEndian) throw()
  210323. {
  210324. const double maxVal = (double) 0x7fffff;
  210325. if (littleEndian)
  210326. {
  210327. while (--numSamples >= 0)
  210328. {
  210329. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  210330. dest += dstStrideBytes;
  210331. }
  210332. }
  210333. else
  210334. {
  210335. while (--numSamples >= 0)
  210336. {
  210337. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  210338. dest += dstStrideBytes;
  210339. }
  210340. }
  210341. }
  210342. static void convertInt32ToFloat (const char* src,
  210343. float* dest,
  210344. const int srcStrideBytes,
  210345. int numSamples,
  210346. const bool littleEndian) throw()
  210347. {
  210348. const double g = 1.0 / 0x7fffffff;
  210349. if (littleEndian)
  210350. {
  210351. while (--numSamples >= 0)
  210352. {
  210353. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  210354. src += srcStrideBytes;
  210355. }
  210356. }
  210357. else
  210358. {
  210359. while (--numSamples >= 0)
  210360. {
  210361. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  210362. src += srcStrideBytes;
  210363. }
  210364. }
  210365. }
  210366. static void convertFloatToInt32 (const float* src,
  210367. char* dest,
  210368. const int dstStrideBytes,
  210369. int numSamples,
  210370. const bool littleEndian) throw()
  210371. {
  210372. const double maxVal = (double) 0x7fffffff;
  210373. if (littleEndian)
  210374. {
  210375. while (--numSamples >= 0)
  210376. {
  210377. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  210378. dest += dstStrideBytes;
  210379. }
  210380. }
  210381. else
  210382. {
  210383. while (--numSamples >= 0)
  210384. {
  210385. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  210386. dest += dstStrideBytes;
  210387. }
  210388. }
  210389. }
  210390. static void typeToFormatParameters (const long type,
  210391. int& bitDepth,
  210392. int& byteStride,
  210393. bool& formatIsFloat,
  210394. bool& littleEndian) throw()
  210395. {
  210396. bitDepth = 0;
  210397. littleEndian = false;
  210398. formatIsFloat = false;
  210399. switch (type)
  210400. {
  210401. case ASIOSTInt16MSB:
  210402. case ASIOSTInt16LSB:
  210403. case ASIOSTInt32MSB16:
  210404. case ASIOSTInt32LSB16:
  210405. bitDepth = 16; break;
  210406. case ASIOSTFloat32MSB:
  210407. case ASIOSTFloat32LSB:
  210408. formatIsFloat = true;
  210409. bitDepth = 32; break;
  210410. case ASIOSTInt32MSB:
  210411. case ASIOSTInt32LSB:
  210412. bitDepth = 32; break;
  210413. case ASIOSTInt24MSB:
  210414. case ASIOSTInt24LSB:
  210415. case ASIOSTInt32MSB24:
  210416. case ASIOSTInt32LSB24:
  210417. case ASIOSTInt32MSB18:
  210418. case ASIOSTInt32MSB20:
  210419. case ASIOSTInt32LSB18:
  210420. case ASIOSTInt32LSB20:
  210421. bitDepth = 24; break;
  210422. case ASIOSTFloat64MSB:
  210423. case ASIOSTFloat64LSB:
  210424. default:
  210425. bitDepth = 64;
  210426. break;
  210427. }
  210428. switch (type)
  210429. {
  210430. case ASIOSTInt16MSB:
  210431. case ASIOSTInt32MSB16:
  210432. case ASIOSTFloat32MSB:
  210433. case ASIOSTFloat64MSB:
  210434. case ASIOSTInt32MSB:
  210435. case ASIOSTInt32MSB18:
  210436. case ASIOSTInt32MSB20:
  210437. case ASIOSTInt32MSB24:
  210438. case ASIOSTInt24MSB:
  210439. littleEndian = false; break;
  210440. case ASIOSTInt16LSB:
  210441. case ASIOSTInt32LSB16:
  210442. case ASIOSTFloat32LSB:
  210443. case ASIOSTFloat64LSB:
  210444. case ASIOSTInt32LSB:
  210445. case ASIOSTInt32LSB18:
  210446. case ASIOSTInt32LSB20:
  210447. case ASIOSTInt32LSB24:
  210448. case ASIOSTInt24LSB:
  210449. littleEndian = true; break;
  210450. default:
  210451. break;
  210452. }
  210453. switch (type)
  210454. {
  210455. case ASIOSTInt16LSB:
  210456. case ASIOSTInt16MSB:
  210457. byteStride = 2; break;
  210458. case ASIOSTInt24LSB:
  210459. case ASIOSTInt24MSB:
  210460. byteStride = 3; break;
  210461. case ASIOSTInt32MSB16:
  210462. case ASIOSTInt32LSB16:
  210463. case ASIOSTInt32MSB:
  210464. case ASIOSTInt32MSB18:
  210465. case ASIOSTInt32MSB20:
  210466. case ASIOSTInt32MSB24:
  210467. case ASIOSTInt32LSB:
  210468. case ASIOSTInt32LSB18:
  210469. case ASIOSTInt32LSB20:
  210470. case ASIOSTInt32LSB24:
  210471. case ASIOSTFloat32LSB:
  210472. case ASIOSTFloat32MSB:
  210473. byteStride = 4; break;
  210474. case ASIOSTFloat64MSB:
  210475. case ASIOSTFloat64LSB:
  210476. byteStride = 8; break;
  210477. default:
  210478. break;
  210479. }
  210480. }
  210481. };
  210482. class ASIOAudioIODeviceType : public AudioIODeviceType
  210483. {
  210484. public:
  210485. ASIOAudioIODeviceType()
  210486. : AudioIODeviceType ("ASIO"),
  210487. hasScanned (false)
  210488. {
  210489. CoInitialize (0);
  210490. }
  210491. ~ASIOAudioIODeviceType()
  210492. {
  210493. }
  210494. void scanForDevices()
  210495. {
  210496. hasScanned = true;
  210497. deviceNames.clear();
  210498. classIds.clear();
  210499. HKEY hk = 0;
  210500. int index = 0;
  210501. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  210502. {
  210503. for (;;)
  210504. {
  210505. char name [256];
  210506. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  210507. {
  210508. addDriverInfo (name, hk);
  210509. }
  210510. else
  210511. {
  210512. break;
  210513. }
  210514. }
  210515. RegCloseKey (hk);
  210516. }
  210517. }
  210518. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  210519. {
  210520. jassert (hasScanned); // need to call scanForDevices() before doing this
  210521. return deviceNames;
  210522. }
  210523. int getDefaultDeviceIndex (bool) const
  210524. {
  210525. jassert (hasScanned); // need to call scanForDevices() before doing this
  210526. for (int i = deviceNames.size(); --i >= 0;)
  210527. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  210528. return i; // asio4all is a safe choice for a default..
  210529. #if JUCE_DEBUG
  210530. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  210531. return 1; // (the digi m-box driver crashes the app when you run
  210532. // it in the debugger, which can be a bit annoying)
  210533. #endif
  210534. return 0;
  210535. }
  210536. static int findFreeSlot()
  210537. {
  210538. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  210539. if (currentASIODev[i] == 0)
  210540. return i;
  210541. jassertfalse; // unfortunately you can only have a finite number
  210542. // of ASIO devices open at the same time..
  210543. return -1;
  210544. }
  210545. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  210546. {
  210547. jassert (hasScanned); // need to call scanForDevices() before doing this
  210548. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  210549. }
  210550. bool hasSeparateInputsAndOutputs() const { return false; }
  210551. AudioIODevice* createDevice (const String& outputDeviceName,
  210552. const String& inputDeviceName)
  210553. {
  210554. // ASIO can't open two different devices for input and output - they must be the same one.
  210555. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  210556. jassert (hasScanned); // need to call scanForDevices() before doing this
  210557. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  210558. : inputDeviceName);
  210559. if (index >= 0)
  210560. {
  210561. const int freeSlot = findFreeSlot();
  210562. if (freeSlot >= 0)
  210563. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  210564. }
  210565. return 0;
  210566. }
  210567. juce_UseDebuggingNewOperator
  210568. private:
  210569. StringArray deviceNames;
  210570. OwnedArray <CLSID> classIds;
  210571. bool hasScanned;
  210572. static bool checkClassIsOk (const String& classId)
  210573. {
  210574. HKEY hk = 0;
  210575. bool ok = false;
  210576. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  210577. {
  210578. int index = 0;
  210579. for (;;)
  210580. {
  210581. WCHAR buf [512];
  210582. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  210583. {
  210584. if (classId.equalsIgnoreCase (buf))
  210585. {
  210586. HKEY subKey, pathKey;
  210587. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  210588. {
  210589. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  210590. {
  210591. WCHAR pathName [1024];
  210592. DWORD dtype = REG_SZ;
  210593. DWORD dsize = sizeof (pathName);
  210594. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  210595. ok = File (pathName).exists();
  210596. RegCloseKey (pathKey);
  210597. }
  210598. RegCloseKey (subKey);
  210599. }
  210600. break;
  210601. }
  210602. }
  210603. else
  210604. {
  210605. break;
  210606. }
  210607. }
  210608. RegCloseKey (hk);
  210609. }
  210610. return ok;
  210611. }
  210612. void addDriverInfo (const String& keyName, HKEY hk)
  210613. {
  210614. HKEY subKey;
  210615. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  210616. {
  210617. WCHAR buf [256];
  210618. zerostruct (buf);
  210619. DWORD dtype = REG_SZ;
  210620. DWORD dsize = sizeof (buf);
  210621. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  210622. {
  210623. if (dsize > 0 && checkClassIsOk (buf))
  210624. {
  210625. CLSID classId;
  210626. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  210627. {
  210628. dtype = REG_SZ;
  210629. dsize = sizeof (buf);
  210630. String deviceName;
  210631. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  210632. deviceName = buf;
  210633. else
  210634. deviceName = keyName;
  210635. log ("found " + deviceName);
  210636. deviceNames.add (deviceName);
  210637. classIds.add (new CLSID (classId));
  210638. }
  210639. }
  210640. RegCloseKey (subKey);
  210641. }
  210642. }
  210643. }
  210644. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  210645. ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  210646. };
  210647. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  210648. {
  210649. return new ASIOAudioIODeviceType();
  210650. }
  210651. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  210652. void* guid,
  210653. const String& optionalDllForDirectLoading)
  210654. {
  210655. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  210656. if (freeSlot < 0)
  210657. return 0;
  210658. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  210659. }
  210660. #undef log
  210661. #endif
  210662. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  210663. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  210664. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210665. // compiled on its own).
  210666. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  210667. END_JUCE_NAMESPACE
  210668. extern "C"
  210669. {
  210670. // Declare just the minimum number of interfaces for the DSound objects that we need..
  210671. typedef struct typeDSBUFFERDESC
  210672. {
  210673. DWORD dwSize;
  210674. DWORD dwFlags;
  210675. DWORD dwBufferBytes;
  210676. DWORD dwReserved;
  210677. LPWAVEFORMATEX lpwfxFormat;
  210678. GUID guid3DAlgorithm;
  210679. } DSBUFFERDESC;
  210680. struct IDirectSoundBuffer;
  210681. #undef INTERFACE
  210682. #define INTERFACE IDirectSound
  210683. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  210684. {
  210685. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  210686. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  210687. STDMETHOD_(ULONG,Release) (THIS) PURE;
  210688. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  210689. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  210690. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  210691. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  210692. STDMETHOD(Compact) (THIS) PURE;
  210693. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  210694. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  210695. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  210696. };
  210697. #undef INTERFACE
  210698. #define INTERFACE IDirectSoundBuffer
  210699. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  210700. {
  210701. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  210702. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  210703. STDMETHOD_(ULONG,Release) (THIS) PURE;
  210704. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  210705. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  210706. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  210707. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  210708. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  210709. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  210710. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  210711. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  210712. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  210713. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  210714. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  210715. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  210716. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  210717. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  210718. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  210719. STDMETHOD(Stop) (THIS) PURE;
  210720. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  210721. STDMETHOD(Restore) (THIS) PURE;
  210722. };
  210723. typedef struct typeDSCBUFFERDESC
  210724. {
  210725. DWORD dwSize;
  210726. DWORD dwFlags;
  210727. DWORD dwBufferBytes;
  210728. DWORD dwReserved;
  210729. LPWAVEFORMATEX lpwfxFormat;
  210730. } DSCBUFFERDESC;
  210731. struct IDirectSoundCaptureBuffer;
  210732. #undef INTERFACE
  210733. #define INTERFACE IDirectSoundCapture
  210734. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  210735. {
  210736. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  210737. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  210738. STDMETHOD_(ULONG,Release) (THIS) PURE;
  210739. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  210740. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  210741. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  210742. };
  210743. #undef INTERFACE
  210744. #define INTERFACE IDirectSoundCaptureBuffer
  210745. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  210746. {
  210747. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  210748. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  210749. STDMETHOD_(ULONG,Release) (THIS) PURE;
  210750. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  210751. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  210752. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  210753. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  210754. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  210755. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  210756. STDMETHOD(Start) (THIS_ DWORD) PURE;
  210757. STDMETHOD(Stop) (THIS) PURE;
  210758. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  210759. };
  210760. };
  210761. BEGIN_JUCE_NAMESPACE
  210762. static const String getDSErrorMessage (HRESULT hr)
  210763. {
  210764. const char* result = 0;
  210765. switch (hr)
  210766. {
  210767. case MAKE_HRESULT(1, 0x878, 10):
  210768. result = "Device already allocated";
  210769. break;
  210770. case MAKE_HRESULT(1, 0x878, 30):
  210771. result = "Control unavailable";
  210772. break;
  210773. case E_INVALIDARG:
  210774. result = "Invalid parameter";
  210775. break;
  210776. case MAKE_HRESULT(1, 0x878, 50):
  210777. result = "Invalid call";
  210778. break;
  210779. case E_FAIL:
  210780. result = "Generic error";
  210781. break;
  210782. case MAKE_HRESULT(1, 0x878, 70):
  210783. result = "Priority level error";
  210784. break;
  210785. case E_OUTOFMEMORY:
  210786. result = "Out of memory";
  210787. break;
  210788. case MAKE_HRESULT(1, 0x878, 100):
  210789. result = "Bad format";
  210790. break;
  210791. case E_NOTIMPL:
  210792. result = "Unsupported function";
  210793. break;
  210794. case MAKE_HRESULT(1, 0x878, 120):
  210795. result = "No driver";
  210796. break;
  210797. case MAKE_HRESULT(1, 0x878, 130):
  210798. result = "Already initialised";
  210799. break;
  210800. case CLASS_E_NOAGGREGATION:
  210801. result = "No aggregation";
  210802. break;
  210803. case MAKE_HRESULT(1, 0x878, 150):
  210804. result = "Buffer lost";
  210805. break;
  210806. case MAKE_HRESULT(1, 0x878, 160):
  210807. result = "Another app has priority";
  210808. break;
  210809. case MAKE_HRESULT(1, 0x878, 170):
  210810. result = "Uninitialised";
  210811. break;
  210812. case E_NOINTERFACE:
  210813. result = "No interface";
  210814. break;
  210815. case S_OK:
  210816. result = "No error";
  210817. break;
  210818. default:
  210819. return "Unknown error: " + String ((int) hr);
  210820. }
  210821. return result;
  210822. }
  210823. #define DS_DEBUGGING 1
  210824. #ifdef DS_DEBUGGING
  210825. #define CATCH JUCE_CATCH_EXCEPTION
  210826. #undef log
  210827. #define log(a) Logger::writeToLog(a);
  210828. #undef logError
  210829. #define logError(a) logDSError(a, __LINE__);
  210830. static void logDSError (HRESULT hr, int lineNum)
  210831. {
  210832. if (hr != S_OK)
  210833. {
  210834. String error ("DS error at line ");
  210835. error << lineNum << " - " << getDSErrorMessage (hr);
  210836. log (error);
  210837. }
  210838. }
  210839. #else
  210840. #define CATCH JUCE_CATCH_ALL
  210841. #define log(a)
  210842. #define logError(a)
  210843. #endif
  210844. #define DSOUND_FUNCTION(functionName, params) \
  210845. typedef HRESULT (WINAPI *type##functionName) params; \
  210846. static type##functionName ds##functionName = 0;
  210847. #define DSOUND_FUNCTION_LOAD(functionName) \
  210848. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  210849. jassert (ds##functionName != 0);
  210850. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  210851. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  210852. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  210853. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  210854. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  210855. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  210856. static void initialiseDSoundFunctions()
  210857. {
  210858. if (dsDirectSoundCreate == 0)
  210859. {
  210860. HMODULE h = LoadLibraryA ("dsound.dll");
  210861. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  210862. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  210863. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  210864. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  210865. }
  210866. }
  210867. class DSoundInternalOutChannel
  210868. {
  210869. String name;
  210870. LPGUID guid;
  210871. int sampleRate, bufferSizeSamples;
  210872. float* leftBuffer;
  210873. float* rightBuffer;
  210874. IDirectSound* pDirectSound;
  210875. IDirectSoundBuffer* pOutputBuffer;
  210876. DWORD writeOffset;
  210877. int totalBytesPerBuffer;
  210878. int bytesPerBuffer;
  210879. unsigned int lastPlayCursor;
  210880. public:
  210881. int bitDepth;
  210882. bool doneFlag;
  210883. DSoundInternalOutChannel (const String& name_,
  210884. LPGUID guid_,
  210885. int rate,
  210886. int bufferSize,
  210887. float* left,
  210888. float* right)
  210889. : name (name_),
  210890. guid (guid_),
  210891. sampleRate (rate),
  210892. bufferSizeSamples (bufferSize),
  210893. leftBuffer (left),
  210894. rightBuffer (right),
  210895. pDirectSound (0),
  210896. pOutputBuffer (0),
  210897. bitDepth (16)
  210898. {
  210899. }
  210900. ~DSoundInternalOutChannel()
  210901. {
  210902. close();
  210903. }
  210904. void close()
  210905. {
  210906. HRESULT hr;
  210907. if (pOutputBuffer != 0)
  210908. {
  210909. JUCE_TRY
  210910. {
  210911. log ("closing dsound out: " + name);
  210912. hr = pOutputBuffer->Stop();
  210913. logError (hr);
  210914. }
  210915. CATCH
  210916. JUCE_TRY
  210917. {
  210918. hr = pOutputBuffer->Release();
  210919. logError (hr);
  210920. }
  210921. CATCH
  210922. pOutputBuffer = 0;
  210923. }
  210924. if (pDirectSound != 0)
  210925. {
  210926. JUCE_TRY
  210927. {
  210928. hr = pDirectSound->Release();
  210929. logError (hr);
  210930. }
  210931. CATCH
  210932. pDirectSound = 0;
  210933. }
  210934. }
  210935. const String open()
  210936. {
  210937. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  210938. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  210939. pDirectSound = 0;
  210940. pOutputBuffer = 0;
  210941. writeOffset = 0;
  210942. String error;
  210943. HRESULT hr = E_NOINTERFACE;
  210944. if (dsDirectSoundCreate != 0)
  210945. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  210946. if (hr == S_OK)
  210947. {
  210948. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  210949. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  210950. const int numChannels = 2;
  210951. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  210952. logError (hr);
  210953. if (hr == S_OK)
  210954. {
  210955. IDirectSoundBuffer* pPrimaryBuffer;
  210956. DSBUFFERDESC primaryDesc;
  210957. zerostruct (primaryDesc);
  210958. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  210959. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  210960. primaryDesc.dwBufferBytes = 0;
  210961. primaryDesc.lpwfxFormat = 0;
  210962. log ("opening dsound out step 2");
  210963. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  210964. logError (hr);
  210965. if (hr == S_OK)
  210966. {
  210967. WAVEFORMATEX wfFormat;
  210968. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  210969. wfFormat.nChannels = (unsigned short) numChannels;
  210970. wfFormat.nSamplesPerSec = sampleRate;
  210971. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  210972. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  210973. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  210974. wfFormat.cbSize = 0;
  210975. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  210976. logError (hr);
  210977. if (hr == S_OK)
  210978. {
  210979. DSBUFFERDESC secondaryDesc;
  210980. zerostruct (secondaryDesc);
  210981. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  210982. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  210983. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  210984. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  210985. secondaryDesc.lpwfxFormat = &wfFormat;
  210986. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  210987. logError (hr);
  210988. if (hr == S_OK)
  210989. {
  210990. log ("opening dsound out step 3");
  210991. DWORD dwDataLen;
  210992. unsigned char* pDSBuffData;
  210993. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  210994. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  210995. logError (hr);
  210996. if (hr == S_OK)
  210997. {
  210998. zeromem (pDSBuffData, dwDataLen);
  210999. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  211000. if (hr == S_OK)
  211001. {
  211002. hr = pOutputBuffer->SetCurrentPosition (0);
  211003. if (hr == S_OK)
  211004. {
  211005. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  211006. if (hr == S_OK)
  211007. return String::empty;
  211008. }
  211009. }
  211010. }
  211011. }
  211012. }
  211013. }
  211014. }
  211015. }
  211016. error = getDSErrorMessage (hr);
  211017. close();
  211018. return error;
  211019. }
  211020. void synchronisePosition()
  211021. {
  211022. if (pOutputBuffer != 0)
  211023. {
  211024. DWORD playCursor;
  211025. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  211026. }
  211027. }
  211028. bool service()
  211029. {
  211030. if (pOutputBuffer == 0)
  211031. return true;
  211032. DWORD playCursor, writeCursor;
  211033. for (;;)
  211034. {
  211035. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  211036. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  211037. {
  211038. pOutputBuffer->Restore();
  211039. continue;
  211040. }
  211041. if (hr == S_OK)
  211042. break;
  211043. logError (hr);
  211044. jassertfalse
  211045. return true;
  211046. }
  211047. int playWriteGap = writeCursor - playCursor;
  211048. if (playWriteGap < 0)
  211049. playWriteGap += totalBytesPerBuffer;
  211050. int bytesEmpty = playCursor - writeOffset;
  211051. if (bytesEmpty < 0)
  211052. bytesEmpty += totalBytesPerBuffer;
  211053. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  211054. {
  211055. writeOffset = writeCursor;
  211056. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  211057. }
  211058. if (bytesEmpty >= bytesPerBuffer)
  211059. {
  211060. LPBYTE lpbuf1 = 0;
  211061. LPBYTE lpbuf2 = 0;
  211062. DWORD dwSize1 = 0;
  211063. DWORD dwSize2 = 0;
  211064. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  211065. bytesPerBuffer,
  211066. (void**) &lpbuf1, &dwSize1,
  211067. (void**) &lpbuf2, &dwSize2, 0);
  211068. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  211069. {
  211070. pOutputBuffer->Restore();
  211071. hr = pOutputBuffer->Lock (writeOffset,
  211072. bytesPerBuffer,
  211073. (void**) &lpbuf1, &dwSize1,
  211074. (void**) &lpbuf2, &dwSize2, 0);
  211075. }
  211076. if (hr == S_OK)
  211077. {
  211078. if (bitDepth == 16)
  211079. {
  211080. const float gainL = 32767.0f;
  211081. const float gainR = 32767.0f;
  211082. int* dest = (int*)lpbuf1;
  211083. const float* left = leftBuffer;
  211084. const float* right = rightBuffer;
  211085. int samples1 = dwSize1 >> 2;
  211086. int samples2 = dwSize2 >> 2;
  211087. if (left == 0)
  211088. {
  211089. while (--samples1 >= 0)
  211090. {
  211091. int r = roundToInt (gainR * *right++);
  211092. if (r < -32768)
  211093. r = -32768;
  211094. else if (r > 32767)
  211095. r = 32767;
  211096. *dest++ = (r << 16);
  211097. }
  211098. dest = (int*)lpbuf2;
  211099. while (--samples2 >= 0)
  211100. {
  211101. int r = roundToInt (gainR * *right++);
  211102. if (r < -32768)
  211103. r = -32768;
  211104. else if (r > 32767)
  211105. r = 32767;
  211106. *dest++ = (r << 16);
  211107. }
  211108. }
  211109. else if (right == 0)
  211110. {
  211111. while (--samples1 >= 0)
  211112. {
  211113. int l = roundToInt (gainL * *left++);
  211114. if (l < -32768)
  211115. l = -32768;
  211116. else if (l > 32767)
  211117. l = 32767;
  211118. l &= 0xffff;
  211119. *dest++ = l;
  211120. }
  211121. dest = (int*)lpbuf2;
  211122. while (--samples2 >= 0)
  211123. {
  211124. int l = roundToInt (gainL * *left++);
  211125. if (l < -32768)
  211126. l = -32768;
  211127. else if (l > 32767)
  211128. l = 32767;
  211129. l &= 0xffff;
  211130. *dest++ = l;
  211131. }
  211132. }
  211133. else
  211134. {
  211135. while (--samples1 >= 0)
  211136. {
  211137. int l = roundToInt (gainL * *left++);
  211138. if (l < -32768)
  211139. l = -32768;
  211140. else if (l > 32767)
  211141. l = 32767;
  211142. l &= 0xffff;
  211143. int r = roundToInt (gainR * *right++);
  211144. if (r < -32768)
  211145. r = -32768;
  211146. else if (r > 32767)
  211147. r = 32767;
  211148. *dest++ = (r << 16) | l;
  211149. }
  211150. dest = (int*)lpbuf2;
  211151. while (--samples2 >= 0)
  211152. {
  211153. int l = roundToInt (gainL * *left++);
  211154. if (l < -32768)
  211155. l = -32768;
  211156. else if (l > 32767)
  211157. l = 32767;
  211158. l &= 0xffff;
  211159. int r = roundToInt (gainR * *right++);
  211160. if (r < -32768)
  211161. r = -32768;
  211162. else if (r > 32767)
  211163. r = 32767;
  211164. *dest++ = (r << 16) | l;
  211165. }
  211166. }
  211167. }
  211168. else
  211169. {
  211170. jassertfalse
  211171. }
  211172. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  211173. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  211174. }
  211175. else
  211176. {
  211177. jassertfalse
  211178. logError (hr);
  211179. }
  211180. bytesEmpty -= bytesPerBuffer;
  211181. return true;
  211182. }
  211183. else
  211184. {
  211185. return false;
  211186. }
  211187. }
  211188. };
  211189. struct DSoundInternalInChannel
  211190. {
  211191. String name;
  211192. LPGUID guid;
  211193. int sampleRate, bufferSizeSamples;
  211194. float* leftBuffer;
  211195. float* rightBuffer;
  211196. IDirectSound* pDirectSound;
  211197. IDirectSoundCapture* pDirectSoundCapture;
  211198. IDirectSoundCaptureBuffer* pInputBuffer;
  211199. public:
  211200. unsigned int readOffset;
  211201. int bytesPerBuffer, totalBytesPerBuffer;
  211202. int bitDepth;
  211203. bool doneFlag;
  211204. DSoundInternalInChannel (const String& name_,
  211205. LPGUID guid_,
  211206. int rate,
  211207. int bufferSize,
  211208. float* left,
  211209. float* right)
  211210. : name (name_),
  211211. guid (guid_),
  211212. sampleRate (rate),
  211213. bufferSizeSamples (bufferSize),
  211214. leftBuffer (left),
  211215. rightBuffer (right),
  211216. pDirectSound (0),
  211217. pDirectSoundCapture (0),
  211218. pInputBuffer (0),
  211219. bitDepth (16)
  211220. {
  211221. }
  211222. ~DSoundInternalInChannel()
  211223. {
  211224. close();
  211225. }
  211226. void close()
  211227. {
  211228. HRESULT hr;
  211229. if (pInputBuffer != 0)
  211230. {
  211231. JUCE_TRY
  211232. {
  211233. log ("closing dsound in: " + name);
  211234. hr = pInputBuffer->Stop();
  211235. logError (hr);
  211236. }
  211237. CATCH
  211238. JUCE_TRY
  211239. {
  211240. hr = pInputBuffer->Release();
  211241. logError (hr);
  211242. }
  211243. CATCH
  211244. pInputBuffer = 0;
  211245. }
  211246. if (pDirectSoundCapture != 0)
  211247. {
  211248. JUCE_TRY
  211249. {
  211250. hr = pDirectSoundCapture->Release();
  211251. logError (hr);
  211252. }
  211253. CATCH
  211254. pDirectSoundCapture = 0;
  211255. }
  211256. if (pDirectSound != 0)
  211257. {
  211258. JUCE_TRY
  211259. {
  211260. hr = pDirectSound->Release();
  211261. logError (hr);
  211262. }
  211263. CATCH
  211264. pDirectSound = 0;
  211265. }
  211266. }
  211267. const String open()
  211268. {
  211269. log ("opening dsound in device: " + name
  211270. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  211271. pDirectSound = 0;
  211272. pDirectSoundCapture = 0;
  211273. pInputBuffer = 0;
  211274. readOffset = 0;
  211275. totalBytesPerBuffer = 0;
  211276. String error;
  211277. HRESULT hr = E_NOINTERFACE;
  211278. if (dsDirectSoundCaptureCreate != 0)
  211279. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  211280. logError (hr);
  211281. if (hr == S_OK)
  211282. {
  211283. const int numChannels = 2;
  211284. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  211285. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  211286. WAVEFORMATEX wfFormat;
  211287. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  211288. wfFormat.nChannels = (unsigned short)numChannels;
  211289. wfFormat.nSamplesPerSec = sampleRate;
  211290. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  211291. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  211292. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  211293. wfFormat.cbSize = 0;
  211294. DSCBUFFERDESC captureDesc;
  211295. zerostruct (captureDesc);
  211296. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  211297. captureDesc.dwFlags = 0;
  211298. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  211299. captureDesc.lpwfxFormat = &wfFormat;
  211300. log ("opening dsound in step 2");
  211301. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  211302. logError (hr);
  211303. if (hr == S_OK)
  211304. {
  211305. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  211306. logError (hr);
  211307. if (hr == S_OK)
  211308. return String::empty;
  211309. }
  211310. }
  211311. error = getDSErrorMessage (hr);
  211312. close();
  211313. return error;
  211314. }
  211315. void synchronisePosition()
  211316. {
  211317. if (pInputBuffer != 0)
  211318. {
  211319. DWORD capturePos;
  211320. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  211321. }
  211322. }
  211323. bool service()
  211324. {
  211325. if (pInputBuffer == 0)
  211326. return true;
  211327. DWORD capturePos, readPos;
  211328. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  211329. logError (hr);
  211330. if (hr != S_OK)
  211331. return true;
  211332. int bytesFilled = readPos - readOffset;
  211333. if (bytesFilled < 0)
  211334. bytesFilled += totalBytesPerBuffer;
  211335. if (bytesFilled >= bytesPerBuffer)
  211336. {
  211337. LPBYTE lpbuf1 = 0;
  211338. LPBYTE lpbuf2 = 0;
  211339. DWORD dwsize1 = 0;
  211340. DWORD dwsize2 = 0;
  211341. HRESULT hr = pInputBuffer->Lock (readOffset,
  211342. bytesPerBuffer,
  211343. (void**) &lpbuf1, &dwsize1,
  211344. (void**) &lpbuf2, &dwsize2, 0);
  211345. if (hr == S_OK)
  211346. {
  211347. if (bitDepth == 16)
  211348. {
  211349. const float g = 1.0f / 32768.0f;
  211350. float* destL = leftBuffer;
  211351. float* destR = rightBuffer;
  211352. int samples1 = dwsize1 >> 2;
  211353. int samples2 = dwsize2 >> 2;
  211354. const short* src = (const short*)lpbuf1;
  211355. if (destL == 0)
  211356. {
  211357. while (--samples1 >= 0)
  211358. {
  211359. ++src;
  211360. *destR++ = *src++ * g;
  211361. }
  211362. src = (const short*)lpbuf2;
  211363. while (--samples2 >= 0)
  211364. {
  211365. ++src;
  211366. *destR++ = *src++ * g;
  211367. }
  211368. }
  211369. else if (destR == 0)
  211370. {
  211371. while (--samples1 >= 0)
  211372. {
  211373. *destL++ = *src++ * g;
  211374. ++src;
  211375. }
  211376. src = (const short*)lpbuf2;
  211377. while (--samples2 >= 0)
  211378. {
  211379. *destL++ = *src++ * g;
  211380. ++src;
  211381. }
  211382. }
  211383. else
  211384. {
  211385. while (--samples1 >= 0)
  211386. {
  211387. *destL++ = *src++ * g;
  211388. *destR++ = *src++ * g;
  211389. }
  211390. src = (const short*)lpbuf2;
  211391. while (--samples2 >= 0)
  211392. {
  211393. *destL++ = *src++ * g;
  211394. *destR++ = *src++ * g;
  211395. }
  211396. }
  211397. }
  211398. else
  211399. {
  211400. jassertfalse
  211401. }
  211402. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  211403. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  211404. }
  211405. else
  211406. {
  211407. logError (hr);
  211408. jassertfalse
  211409. }
  211410. bytesFilled -= bytesPerBuffer;
  211411. return true;
  211412. }
  211413. else
  211414. {
  211415. return false;
  211416. }
  211417. }
  211418. };
  211419. class DSoundAudioIODevice : public AudioIODevice,
  211420. public Thread
  211421. {
  211422. public:
  211423. DSoundAudioIODevice (const String& deviceName,
  211424. const int outputDeviceIndex_,
  211425. const int inputDeviceIndex_)
  211426. : AudioIODevice (deviceName, "DirectSound"),
  211427. Thread ("Juce DSound"),
  211428. isOpen_ (false),
  211429. isStarted (false),
  211430. outputDeviceIndex (outputDeviceIndex_),
  211431. inputDeviceIndex (inputDeviceIndex_),
  211432. totalSamplesOut (0),
  211433. sampleRate (0.0),
  211434. inputBuffers (1, 1),
  211435. outputBuffers (1, 1),
  211436. callback (0),
  211437. bufferSizeSamples (0)
  211438. {
  211439. if (outputDeviceIndex_ >= 0)
  211440. {
  211441. outChannels.add (TRANS("Left"));
  211442. outChannels.add (TRANS("Right"));
  211443. }
  211444. if (inputDeviceIndex_ >= 0)
  211445. {
  211446. inChannels.add (TRANS("Left"));
  211447. inChannels.add (TRANS("Right"));
  211448. }
  211449. }
  211450. ~DSoundAudioIODevice()
  211451. {
  211452. close();
  211453. }
  211454. const StringArray getOutputChannelNames()
  211455. {
  211456. return outChannels;
  211457. }
  211458. const StringArray getInputChannelNames()
  211459. {
  211460. return inChannels;
  211461. }
  211462. int getNumSampleRates()
  211463. {
  211464. return 4;
  211465. }
  211466. double getSampleRate (int index)
  211467. {
  211468. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  211469. return samps [jlimit (0, 3, index)];
  211470. }
  211471. int getNumBufferSizesAvailable()
  211472. {
  211473. return 50;
  211474. }
  211475. int getBufferSizeSamples (int index)
  211476. {
  211477. int n = 64;
  211478. for (int i = 0; i < index; ++i)
  211479. n += (n < 512) ? 32
  211480. : ((n < 1024) ? 64
  211481. : ((n < 2048) ? 128 : 256));
  211482. return n;
  211483. }
  211484. int getDefaultBufferSize()
  211485. {
  211486. return 2560;
  211487. }
  211488. const String open (const BigInteger& inputChannels,
  211489. const BigInteger& outputChannels,
  211490. double sampleRate,
  211491. int bufferSizeSamples)
  211492. {
  211493. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  211494. isOpen_ = lastError.isEmpty();
  211495. return lastError;
  211496. }
  211497. void close()
  211498. {
  211499. stop();
  211500. if (isOpen_)
  211501. {
  211502. closeDevice();
  211503. isOpen_ = false;
  211504. }
  211505. }
  211506. bool isOpen()
  211507. {
  211508. return isOpen_ && isThreadRunning();
  211509. }
  211510. int getCurrentBufferSizeSamples()
  211511. {
  211512. return bufferSizeSamples;
  211513. }
  211514. double getCurrentSampleRate()
  211515. {
  211516. return sampleRate;
  211517. }
  211518. int getCurrentBitDepth()
  211519. {
  211520. int i, bits = 256;
  211521. for (i = inChans.size(); --i >= 0;)
  211522. bits = jmin (bits, inChans[i]->bitDepth);
  211523. for (i = outChans.size(); --i >= 0;)
  211524. bits = jmin (bits, outChans[i]->bitDepth);
  211525. if (bits > 32)
  211526. bits = 16;
  211527. return bits;
  211528. }
  211529. const BigInteger getActiveOutputChannels() const
  211530. {
  211531. return enabledOutputs;
  211532. }
  211533. const BigInteger getActiveInputChannels() const
  211534. {
  211535. return enabledInputs;
  211536. }
  211537. int getOutputLatencyInSamples()
  211538. {
  211539. return (int) (getCurrentBufferSizeSamples() * 1.5);
  211540. }
  211541. int getInputLatencyInSamples()
  211542. {
  211543. return getOutputLatencyInSamples();
  211544. }
  211545. void start (AudioIODeviceCallback* call)
  211546. {
  211547. if (isOpen_ && call != 0 && ! isStarted)
  211548. {
  211549. if (! isThreadRunning())
  211550. {
  211551. // something gone wrong and the thread's stopped..
  211552. isOpen_ = false;
  211553. return;
  211554. }
  211555. call->audioDeviceAboutToStart (this);
  211556. const ScopedLock sl (startStopLock);
  211557. callback = call;
  211558. isStarted = true;
  211559. }
  211560. }
  211561. void stop()
  211562. {
  211563. if (isStarted)
  211564. {
  211565. AudioIODeviceCallback* const callbackLocal = callback;
  211566. {
  211567. const ScopedLock sl (startStopLock);
  211568. isStarted = false;
  211569. }
  211570. if (callbackLocal != 0)
  211571. callbackLocal->audioDeviceStopped();
  211572. }
  211573. }
  211574. bool isPlaying()
  211575. {
  211576. return isStarted && isOpen_ && isThreadRunning();
  211577. }
  211578. const String getLastError()
  211579. {
  211580. return lastError;
  211581. }
  211582. juce_UseDebuggingNewOperator
  211583. StringArray inChannels, outChannels;
  211584. int outputDeviceIndex, inputDeviceIndex;
  211585. private:
  211586. bool isOpen_;
  211587. bool isStarted;
  211588. String lastError;
  211589. OwnedArray <DSoundInternalInChannel> inChans;
  211590. OwnedArray <DSoundInternalOutChannel> outChans;
  211591. WaitableEvent startEvent;
  211592. int bufferSizeSamples;
  211593. int volatile totalSamplesOut;
  211594. int64 volatile lastBlockTime;
  211595. double sampleRate;
  211596. BigInteger enabledInputs, enabledOutputs;
  211597. AudioSampleBuffer inputBuffers, outputBuffers;
  211598. AudioIODeviceCallback* callback;
  211599. CriticalSection startStopLock;
  211600. DSoundAudioIODevice (const DSoundAudioIODevice&);
  211601. DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  211602. const String openDevice (const BigInteger& inputChannels,
  211603. const BigInteger& outputChannels,
  211604. double sampleRate_,
  211605. int bufferSizeSamples_);
  211606. void closeDevice()
  211607. {
  211608. isStarted = false;
  211609. stopThread (5000);
  211610. inChans.clear();
  211611. outChans.clear();
  211612. inputBuffers.setSize (1, 1);
  211613. outputBuffers.setSize (1, 1);
  211614. }
  211615. void resync()
  211616. {
  211617. if (! threadShouldExit())
  211618. {
  211619. sleep (5);
  211620. int i;
  211621. for (i = 0; i < outChans.size(); ++i)
  211622. outChans.getUnchecked(i)->synchronisePosition();
  211623. for (i = 0; i < inChans.size(); ++i)
  211624. inChans.getUnchecked(i)->synchronisePosition();
  211625. }
  211626. }
  211627. public:
  211628. void run()
  211629. {
  211630. while (! threadShouldExit())
  211631. {
  211632. if (wait (100))
  211633. break;
  211634. }
  211635. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  211636. const int maxTimeMS = jmax (5, 3 * latencyMs);
  211637. while (! threadShouldExit())
  211638. {
  211639. int numToDo = 0;
  211640. uint32 startTime = Time::getMillisecondCounter();
  211641. int i;
  211642. for (i = inChans.size(); --i >= 0;)
  211643. {
  211644. inChans.getUnchecked(i)->doneFlag = false;
  211645. ++numToDo;
  211646. }
  211647. for (i = outChans.size(); --i >= 0;)
  211648. {
  211649. outChans.getUnchecked(i)->doneFlag = false;
  211650. ++numToDo;
  211651. }
  211652. if (numToDo > 0)
  211653. {
  211654. const int maxCount = 3;
  211655. int count = maxCount;
  211656. for (;;)
  211657. {
  211658. for (i = inChans.size(); --i >= 0;)
  211659. {
  211660. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  211661. if ((! in->doneFlag) && in->service())
  211662. {
  211663. in->doneFlag = true;
  211664. --numToDo;
  211665. }
  211666. }
  211667. for (i = outChans.size(); --i >= 0;)
  211668. {
  211669. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  211670. if ((! out->doneFlag) && out->service())
  211671. {
  211672. out->doneFlag = true;
  211673. --numToDo;
  211674. }
  211675. }
  211676. if (numToDo <= 0)
  211677. break;
  211678. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  211679. {
  211680. resync();
  211681. break;
  211682. }
  211683. if (--count <= 0)
  211684. {
  211685. Sleep (1);
  211686. count = maxCount;
  211687. }
  211688. if (threadShouldExit())
  211689. return;
  211690. }
  211691. }
  211692. else
  211693. {
  211694. sleep (1);
  211695. }
  211696. const ScopedLock sl (startStopLock);
  211697. if (isStarted)
  211698. {
  211699. JUCE_TRY
  211700. {
  211701. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  211702. inputBuffers.getNumChannels(),
  211703. outputBuffers.getArrayOfChannels(),
  211704. outputBuffers.getNumChannels(),
  211705. bufferSizeSamples);
  211706. }
  211707. JUCE_CATCH_EXCEPTION
  211708. totalSamplesOut += bufferSizeSamples;
  211709. }
  211710. else
  211711. {
  211712. outputBuffers.clear();
  211713. totalSamplesOut = 0;
  211714. sleep (1);
  211715. }
  211716. }
  211717. }
  211718. };
  211719. class DSoundAudioIODeviceType : public AudioIODeviceType
  211720. {
  211721. public:
  211722. DSoundAudioIODeviceType()
  211723. : AudioIODeviceType ("DirectSound"),
  211724. hasScanned (false)
  211725. {
  211726. initialiseDSoundFunctions();
  211727. }
  211728. ~DSoundAudioIODeviceType()
  211729. {
  211730. }
  211731. void scanForDevices()
  211732. {
  211733. hasScanned = true;
  211734. outputDeviceNames.clear();
  211735. outputGuids.clear();
  211736. inputDeviceNames.clear();
  211737. inputGuids.clear();
  211738. if (dsDirectSoundEnumerateW != 0)
  211739. {
  211740. dsDirectSoundEnumerateW (outputEnumProcW, this);
  211741. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  211742. }
  211743. }
  211744. const StringArray getDeviceNames (bool wantInputNames) const
  211745. {
  211746. jassert (hasScanned); // need to call scanForDevices() before doing this
  211747. return wantInputNames ? inputDeviceNames
  211748. : outputDeviceNames;
  211749. }
  211750. int getDefaultDeviceIndex (bool /*forInput*/) const
  211751. {
  211752. jassert (hasScanned); // need to call scanForDevices() before doing this
  211753. return 0;
  211754. }
  211755. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  211756. {
  211757. jassert (hasScanned); // need to call scanForDevices() before doing this
  211758. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  211759. if (d == 0)
  211760. return -1;
  211761. return asInput ? d->inputDeviceIndex
  211762. : d->outputDeviceIndex;
  211763. }
  211764. bool hasSeparateInputsAndOutputs() const { return true; }
  211765. AudioIODevice* createDevice (const String& outputDeviceName,
  211766. const String& inputDeviceName)
  211767. {
  211768. jassert (hasScanned); // need to call scanForDevices() before doing this
  211769. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  211770. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  211771. if (outputIndex >= 0 || inputIndex >= 0)
  211772. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  211773. : inputDeviceName,
  211774. outputIndex, inputIndex);
  211775. return 0;
  211776. }
  211777. juce_UseDebuggingNewOperator
  211778. StringArray outputDeviceNames;
  211779. OwnedArray <GUID> outputGuids;
  211780. StringArray inputDeviceNames;
  211781. OwnedArray <GUID> inputGuids;
  211782. private:
  211783. bool hasScanned;
  211784. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  211785. {
  211786. desc = desc.trim();
  211787. if (desc.isNotEmpty())
  211788. {
  211789. const String origDesc (desc);
  211790. int n = 2;
  211791. while (outputDeviceNames.contains (desc))
  211792. desc = origDesc + " (" + String (n++) + ")";
  211793. outputDeviceNames.add (desc);
  211794. if (lpGUID != 0)
  211795. outputGuids.add (new GUID (*lpGUID));
  211796. else
  211797. outputGuids.add (0);
  211798. }
  211799. return TRUE;
  211800. }
  211801. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  211802. {
  211803. return ((DSoundAudioIODeviceType*) object)
  211804. ->outputEnumProc (lpGUID, String (description));
  211805. }
  211806. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  211807. {
  211808. return ((DSoundAudioIODeviceType*) object)
  211809. ->outputEnumProc (lpGUID, String (description));
  211810. }
  211811. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  211812. {
  211813. desc = desc.trim();
  211814. if (desc.isNotEmpty())
  211815. {
  211816. const String origDesc (desc);
  211817. int n = 2;
  211818. while (inputDeviceNames.contains (desc))
  211819. desc = origDesc + " (" + String (n++) + ")";
  211820. inputDeviceNames.add (desc);
  211821. if (lpGUID != 0)
  211822. inputGuids.add (new GUID (*lpGUID));
  211823. else
  211824. inputGuids.add (0);
  211825. }
  211826. return TRUE;
  211827. }
  211828. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  211829. {
  211830. return ((DSoundAudioIODeviceType*) object)
  211831. ->inputEnumProc (lpGUID, String (description));
  211832. }
  211833. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  211834. {
  211835. return ((DSoundAudioIODeviceType*) object)
  211836. ->inputEnumProc (lpGUID, String (description));
  211837. }
  211838. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  211839. DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  211840. };
  211841. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  211842. const BigInteger& outputChannels,
  211843. double sampleRate_,
  211844. int bufferSizeSamples_)
  211845. {
  211846. closeDevice();
  211847. totalSamplesOut = 0;
  211848. sampleRate = sampleRate_;
  211849. if (bufferSizeSamples_ <= 0)
  211850. bufferSizeSamples_ = 960; // use as a default size if none is set.
  211851. bufferSizeSamples = bufferSizeSamples_ & ~7;
  211852. DSoundAudioIODeviceType dlh;
  211853. dlh.scanForDevices();
  211854. enabledInputs = inputChannels;
  211855. enabledInputs.setRange (inChannels.size(),
  211856. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  211857. false);
  211858. inputBuffers.setSize (enabledInputs.countNumberOfSetBits(), bufferSizeSamples);
  211859. int i, numIns = 0;
  211860. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  211861. {
  211862. float* left = 0;
  211863. if (enabledInputs[i])
  211864. left = inputBuffers.getSampleData (numIns++);
  211865. float* right = 0;
  211866. if (enabledInputs[i + 1])
  211867. right = inputBuffers.getSampleData (numIns++);
  211868. if (left != 0 || right != 0)
  211869. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  211870. dlh.inputGuids [inputDeviceIndex],
  211871. (int) sampleRate, bufferSizeSamples,
  211872. left, right));
  211873. }
  211874. enabledOutputs = outputChannels;
  211875. enabledOutputs.setRange (outChannels.size(),
  211876. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  211877. false);
  211878. outputBuffers.setSize (enabledOutputs.countNumberOfSetBits(), bufferSizeSamples);
  211879. int numOuts = 0;
  211880. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  211881. {
  211882. float* left = 0;
  211883. if (enabledOutputs[i])
  211884. left = outputBuffers.getSampleData (numOuts++);
  211885. float* right = 0;
  211886. if (enabledOutputs[i + 1])
  211887. right = outputBuffers.getSampleData (numOuts++);
  211888. if (left != 0 || right != 0)
  211889. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  211890. dlh.outputGuids [outputDeviceIndex],
  211891. (int) sampleRate, bufferSizeSamples,
  211892. left, right));
  211893. }
  211894. String error;
  211895. // boost our priority while opening the devices to try to get better sync between them
  211896. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  211897. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  211898. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  211899. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  211900. for (i = 0; i < outChans.size(); ++i)
  211901. {
  211902. error = outChans[i]->open();
  211903. if (error.isNotEmpty())
  211904. {
  211905. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  211906. break;
  211907. }
  211908. }
  211909. if (error.isEmpty())
  211910. {
  211911. for (i = 0; i < inChans.size(); ++i)
  211912. {
  211913. error = inChans[i]->open();
  211914. if (error.isNotEmpty())
  211915. {
  211916. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  211917. break;
  211918. }
  211919. }
  211920. }
  211921. if (error.isEmpty())
  211922. {
  211923. totalSamplesOut = 0;
  211924. for (i = 0; i < outChans.size(); ++i)
  211925. outChans.getUnchecked(i)->synchronisePosition();
  211926. for (i = 0; i < inChans.size(); ++i)
  211927. inChans.getUnchecked(i)->synchronisePosition();
  211928. startThread (9);
  211929. sleep (10);
  211930. notify();
  211931. }
  211932. else
  211933. {
  211934. log (error);
  211935. }
  211936. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  211937. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  211938. return error;
  211939. }
  211940. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  211941. {
  211942. return new DSoundAudioIODeviceType();
  211943. }
  211944. #undef log
  211945. #endif
  211946. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  211947. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  211948. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  211949. // compiled on its own).
  211950. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  211951. #if 1
  211952. const String getAudioErrorDesc (HRESULT hr)
  211953. {
  211954. const char* e = 0;
  211955. switch (hr)
  211956. {
  211957. case E_POINTER: e = "E_POINTER"; break;
  211958. case E_INVALIDARG: e = "E_INVALIDARG"; break;
  211959. case AUDCLNT_E_NOT_INITIALIZED: e = "AUDCLNT_E_NOT_INITIALIZED"; break;
  211960. case AUDCLNT_E_ALREADY_INITIALIZED: e = "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  211961. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e = "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  211962. case AUDCLNT_E_DEVICE_INVALIDATED: e = "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  211963. case AUDCLNT_E_NOT_STOPPED: e = "AUDCLNT_E_NOT_STOPPED"; break;
  211964. case AUDCLNT_E_BUFFER_TOO_LARGE: e = "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  211965. case AUDCLNT_E_OUT_OF_ORDER: e = "AUDCLNT_E_OUT_OF_ORDER"; break;
  211966. case AUDCLNT_E_UNSUPPORTED_FORMAT: e = "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  211967. case AUDCLNT_E_INVALID_SIZE: e = "AUDCLNT_E_INVALID_SIZE"; break;
  211968. case AUDCLNT_E_DEVICE_IN_USE: e = "AUDCLNT_E_DEVICE_IN_USE"; break;
  211969. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e = "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  211970. case AUDCLNT_E_THREAD_NOT_REGISTERED: e = "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  211971. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e = "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  211972. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e = "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  211973. case AUDCLNT_E_SERVICE_NOT_RUNNING: e = "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  211974. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e = "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  211975. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e = "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  211976. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e = "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  211977. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e = "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  211978. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e = "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  211979. case AUDCLNT_E_BUFFER_SIZE_ERROR: e = "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  211980. case AUDCLNT_S_BUFFER_EMPTY: e = "AUDCLNT_S_BUFFER_EMPTY"; break;
  211981. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e = "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  211982. default: return String::toHexString ((int) hr);
  211983. }
  211984. return e;
  211985. }
  211986. #define logFailure(hr) { if (FAILED (hr)) { DBG ("WASAPI FAIL! " + getAudioErrorDesc (hr)); jassertfalse } }
  211987. #define OK(a) wasapi_checkResult(a)
  211988. static bool wasapi_checkResult (HRESULT hr)
  211989. {
  211990. logFailure (hr);
  211991. return SUCCEEDED (hr);
  211992. }
  211993. #else
  211994. #define logFailure(hr) {}
  211995. #define OK(a) SUCCEEDED(a)
  211996. #endif
  211997. static const String wasapi_getDeviceID (IMMDevice* const device)
  211998. {
  211999. String s;
  212000. WCHAR* deviceId = 0;
  212001. if (OK (device->GetId (&deviceId)))
  212002. {
  212003. s = String (deviceId);
  212004. CoTaskMemFree (deviceId);
  212005. }
  212006. return s;
  212007. }
  212008. static EDataFlow wasapi_getDataFlow (IMMDevice* const device)
  212009. {
  212010. EDataFlow flow = eRender;
  212011. ComSmartPtr <IMMEndpoint> endPoint;
  212012. if (OK (device->QueryInterface (__uuidof (IMMEndpoint), (void**) &endPoint)))
  212013. (void) OK (endPoint->GetDataFlow (&flow));
  212014. return flow;
  212015. }
  212016. static int wasapi_refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  212017. {
  212018. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  212019. }
  212020. static void wasapi_copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  212021. {
  212022. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  212023. : sizeof (WAVEFORMATEX));
  212024. }
  212025. class WASAPIDeviceBase
  212026. {
  212027. public:
  212028. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  212029. : device (device_),
  212030. sampleRate (0),
  212031. numChannels (0),
  212032. actualNumChannels (0),
  212033. defaultSampleRate (0),
  212034. minBufferSize (0),
  212035. defaultBufferSize (0),
  212036. latencySamples (0),
  212037. useExclusiveMode (useExclusiveMode_)
  212038. {
  212039. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  212040. ComSmartPtr <IAudioClient> tempClient (createClient());
  212041. if (tempClient == 0)
  212042. return;
  212043. REFERENCE_TIME defaultPeriod, minPeriod;
  212044. if (! OK (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  212045. return;
  212046. WAVEFORMATEX* mixFormat = 0;
  212047. if (! OK (tempClient->GetMixFormat (&mixFormat)))
  212048. return;
  212049. WAVEFORMATEXTENSIBLE format;
  212050. wasapi_copyWavFormat (format, mixFormat);
  212051. CoTaskMemFree (mixFormat);
  212052. actualNumChannels = numChannels = format.Format.nChannels;
  212053. defaultSampleRate = format.Format.nSamplesPerSec;
  212054. minBufferSize = wasapi_refTimeToSamples (minPeriod, defaultSampleRate);
  212055. defaultBufferSize = wasapi_refTimeToSamples (defaultPeriod, defaultSampleRate);
  212056. rates.addUsingDefaultSort (defaultSampleRate);
  212057. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  212058. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  212059. {
  212060. if (ratesToTest[i] == defaultSampleRate)
  212061. continue;
  212062. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  212063. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  212064. (WAVEFORMATEX*) &format, 0)))
  212065. if (! rates.contains (ratesToTest[i]))
  212066. rates.addUsingDefaultSort (ratesToTest[i]);
  212067. }
  212068. }
  212069. ~WASAPIDeviceBase()
  212070. {
  212071. device = 0;
  212072. CloseHandle (clientEvent);
  212073. }
  212074. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  212075. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  212076. {
  212077. sampleRate = newSampleRate;
  212078. channels = newChannels;
  212079. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  212080. numChannels = channels.getHighestBit() + 1;
  212081. if (numChannels == 0)
  212082. return true;
  212083. client = createClient();
  212084. if (client != 0
  212085. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  212086. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  212087. {
  212088. channelMaps.clear();
  212089. for (int i = 0; i <= channels.getHighestBit(); ++i)
  212090. if (channels[i])
  212091. channelMaps.add (i);
  212092. REFERENCE_TIME latency;
  212093. if (OK (client->GetStreamLatency (&latency)))
  212094. latencySamples = wasapi_refTimeToSamples (latency, sampleRate);
  212095. (void) OK (client->GetBufferSize (&actualBufferSize));
  212096. return OK (client->SetEventHandle (clientEvent));
  212097. }
  212098. return false;
  212099. }
  212100. void closeClient()
  212101. {
  212102. if (client != 0)
  212103. client->Stop();
  212104. client = 0;
  212105. ResetEvent (clientEvent);
  212106. }
  212107. ComSmartPtr <IMMDevice> device;
  212108. ComSmartPtr <IAudioClient> client;
  212109. double sampleRate, defaultSampleRate;
  212110. int numChannels, actualNumChannels;
  212111. int minBufferSize, defaultBufferSize, latencySamples;
  212112. const bool useExclusiveMode;
  212113. Array <double> rates;
  212114. HANDLE clientEvent;
  212115. BigInteger channels;
  212116. AudioDataConverters::DataFormat dataFormat;
  212117. Array <int> channelMaps;
  212118. UINT32 actualBufferSize;
  212119. int bytesPerSample;
  212120. private:
  212121. const ComSmartPtr <IAudioClient> createClient()
  212122. {
  212123. ComSmartPtr <IAudioClient> client;
  212124. if (device != 0)
  212125. {
  212126. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) &client);
  212127. logFailure (hr);
  212128. }
  212129. return client;
  212130. }
  212131. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  212132. {
  212133. WAVEFORMATEXTENSIBLE format;
  212134. zerostruct (format);
  212135. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  212136. {
  212137. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  212138. }
  212139. else
  212140. {
  212141. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  212142. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  212143. }
  212144. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  212145. format.Format.nChannels = (WORD) numChannels;
  212146. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  212147. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  212148. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  212149. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  212150. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  212151. switch (numChannels)
  212152. {
  212153. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  212154. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  212155. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  212156. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  212157. 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;
  212158. default: break;
  212159. }
  212160. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  212161. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  212162. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  212163. logFailure (hr);
  212164. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  212165. {
  212166. wasapi_copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  212167. hr = S_OK;
  212168. }
  212169. CoTaskMemFree (nearestFormat);
  212170. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  212171. if (useExclusiveMode)
  212172. OK (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  212173. GUID session;
  212174. if (hr == S_OK
  212175. && OK (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  212176. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  212177. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  212178. {
  212179. actualNumChannels = format.Format.nChannels;
  212180. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  212181. bytesPerSample = format.Format.wBitsPerSample / 8;
  212182. dataFormat = isFloat ? AudioDataConverters::float32LE
  212183. : (bytesPerSample == 4 ? AudioDataConverters::int32LE
  212184. : ((bytesPerSample == 3 ? AudioDataConverters::int24LE
  212185. : AudioDataConverters::int16LE)));
  212186. return true;
  212187. }
  212188. return false;
  212189. }
  212190. WASAPIDeviceBase (const WASAPIDeviceBase&);
  212191. WASAPIDeviceBase& operator= (const WASAPIDeviceBase&);
  212192. };
  212193. class WASAPIInputDevice : public WASAPIDeviceBase
  212194. {
  212195. public:
  212196. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  212197. : WASAPIDeviceBase (device_, useExclusiveMode_),
  212198. reservoir (1, 1)
  212199. {
  212200. }
  212201. ~WASAPIInputDevice()
  212202. {
  212203. close();
  212204. }
  212205. bool open (const double newSampleRate, const BigInteger& newChannels)
  212206. {
  212207. reservoirSize = 0;
  212208. reservoirCapacity = 16384;
  212209. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  212210. return openClient (newSampleRate, newChannels)
  212211. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioCaptureClient), (void**) &captureClient)));
  212212. }
  212213. void close()
  212214. {
  212215. closeClient();
  212216. captureClient = 0;
  212217. reservoir.setSize (0);
  212218. }
  212219. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  212220. {
  212221. if (numChannels <= 0)
  212222. return;
  212223. int offset = 0;
  212224. while (bufferSize > 0)
  212225. {
  212226. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  212227. {
  212228. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  212229. for (int i = 0; i < numDestBuffers; ++i)
  212230. {
  212231. float* const dest = destBuffers[i] + offset;
  212232. const int srcChan = channelMaps.getUnchecked(i);
  212233. switch (dataFormat)
  212234. {
  212235. case AudioDataConverters::float32LE:
  212236. AudioDataConverters::convertFloat32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  212237. break;
  212238. case AudioDataConverters::int32LE:
  212239. AudioDataConverters::convertInt32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  212240. break;
  212241. case AudioDataConverters::int24LE:
  212242. AudioDataConverters::convertInt24LEToFloat (((uint8*) reservoir.getData()) + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  212243. break;
  212244. case AudioDataConverters::int16LE:
  212245. AudioDataConverters::convertInt16LEToFloat (((uint8*) reservoir.getData()) + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  212246. break;
  212247. default: jassertfalse; break;
  212248. }
  212249. }
  212250. bufferSize -= samplesToDo;
  212251. offset += samplesToDo;
  212252. reservoirSize -= samplesToDo;
  212253. }
  212254. else
  212255. {
  212256. UINT32 packetLength = 0;
  212257. if (! OK (captureClient->GetNextPacketSize (&packetLength)))
  212258. break;
  212259. if (packetLength == 0)
  212260. {
  212261. if (thread.threadShouldExit())
  212262. break;
  212263. Thread::sleep (1);
  212264. continue;
  212265. }
  212266. uint8* inputData = 0;
  212267. UINT32 numSamplesAvailable;
  212268. DWORD flags;
  212269. if (OK (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  212270. {
  212271. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  212272. for (int i = 0; i < numDestBuffers; ++i)
  212273. {
  212274. float* const dest = destBuffers[i] + offset;
  212275. const int srcChan = channelMaps.getUnchecked(i);
  212276. switch (dataFormat)
  212277. {
  212278. case AudioDataConverters::float32LE:
  212279. AudioDataConverters::convertFloat32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  212280. break;
  212281. case AudioDataConverters::int32LE:
  212282. AudioDataConverters::convertInt32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  212283. break;
  212284. case AudioDataConverters::int24LE:
  212285. AudioDataConverters::convertInt24LEToFloat (inputData + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  212286. break;
  212287. case AudioDataConverters::int16LE:
  212288. AudioDataConverters::convertInt16LEToFloat (inputData + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  212289. break;
  212290. default: jassertfalse; break;
  212291. }
  212292. }
  212293. bufferSize -= samplesToDo;
  212294. offset += samplesToDo;
  212295. if (samplesToDo < (int) numSamplesAvailable)
  212296. {
  212297. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  212298. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  212299. bytesPerSample * actualNumChannels * reservoirSize);
  212300. }
  212301. captureClient->ReleaseBuffer (numSamplesAvailable);
  212302. }
  212303. }
  212304. }
  212305. }
  212306. ComSmartPtr <IAudioCaptureClient> captureClient;
  212307. MemoryBlock reservoir;
  212308. int reservoirSize, reservoirCapacity;
  212309. private:
  212310. WASAPIInputDevice (const WASAPIInputDevice&);
  212311. WASAPIInputDevice& operator= (const WASAPIInputDevice&);
  212312. };
  212313. class WASAPIOutputDevice : public WASAPIDeviceBase
  212314. {
  212315. public:
  212316. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  212317. : WASAPIDeviceBase (device_, useExclusiveMode_)
  212318. {
  212319. }
  212320. ~WASAPIOutputDevice()
  212321. {
  212322. close();
  212323. }
  212324. bool open (const double newSampleRate, const BigInteger& newChannels)
  212325. {
  212326. return openClient (newSampleRate, newChannels)
  212327. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioRenderClient), (void**) &renderClient)));
  212328. }
  212329. void close()
  212330. {
  212331. closeClient();
  212332. renderClient = 0;
  212333. }
  212334. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  212335. {
  212336. if (numChannels <= 0)
  212337. return;
  212338. int offset = 0;
  212339. while (bufferSize > 0)
  212340. {
  212341. UINT32 padding = 0;
  212342. if (! OK (client->GetCurrentPadding (&padding)))
  212343. return;
  212344. int samplesToDo = useExclusiveMode ? bufferSize
  212345. : jmin ((int) (actualBufferSize - padding), bufferSize);
  212346. if (samplesToDo <= 0)
  212347. {
  212348. if (thread.threadShouldExit())
  212349. break;
  212350. Thread::sleep (0);
  212351. continue;
  212352. }
  212353. uint8* outputData = 0;
  212354. if (OK (renderClient->GetBuffer (samplesToDo, &outputData)))
  212355. {
  212356. for (int i = 0; i < numSrcBuffers; ++i)
  212357. {
  212358. const float* const source = srcBuffers[i] + offset;
  212359. const int destChan = channelMaps.getUnchecked(i);
  212360. switch (dataFormat)
  212361. {
  212362. case AudioDataConverters::float32LE:
  212363. AudioDataConverters::convertFloatToFloat32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  212364. break;
  212365. case AudioDataConverters::int32LE:
  212366. AudioDataConverters::convertFloatToInt32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  212367. break;
  212368. case AudioDataConverters::int24LE:
  212369. AudioDataConverters::convertFloatToInt24LE (source, outputData + 3 * destChan, samplesToDo, 3 * actualNumChannels);
  212370. break;
  212371. case AudioDataConverters::int16LE:
  212372. AudioDataConverters::convertFloatToInt16LE (source, outputData + 2 * destChan, samplesToDo, 2 * actualNumChannels);
  212373. break;
  212374. default: jassertfalse; break;
  212375. }
  212376. }
  212377. renderClient->ReleaseBuffer (samplesToDo, 0);
  212378. offset += samplesToDo;
  212379. bufferSize -= samplesToDo;
  212380. }
  212381. }
  212382. }
  212383. ComSmartPtr <IAudioRenderClient> renderClient;
  212384. private:
  212385. WASAPIOutputDevice (const WASAPIOutputDevice&);
  212386. WASAPIOutputDevice& operator= (const WASAPIOutputDevice&);
  212387. };
  212388. class WASAPIAudioIODevice : public AudioIODevice,
  212389. public Thread
  212390. {
  212391. public:
  212392. WASAPIAudioIODevice (const String& deviceName,
  212393. const String& outputDeviceId_,
  212394. const String& inputDeviceId_,
  212395. const bool useExclusiveMode_)
  212396. : AudioIODevice (deviceName, "Windows Audio"),
  212397. Thread ("Juce WASAPI"),
  212398. isOpen_ (false),
  212399. isStarted (false),
  212400. outputDevice (0),
  212401. outputDeviceId (outputDeviceId_),
  212402. inputDevice (0),
  212403. inputDeviceId (inputDeviceId_),
  212404. useExclusiveMode (useExclusiveMode_),
  212405. currentBufferSizeSamples (0),
  212406. currentSampleRate (0),
  212407. callback (0)
  212408. {
  212409. }
  212410. ~WASAPIAudioIODevice()
  212411. {
  212412. close();
  212413. deleteAndZero (inputDevice);
  212414. deleteAndZero (outputDevice);
  212415. }
  212416. bool initialise()
  212417. {
  212418. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  212419. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  212420. latencyIn = latencyOut = 0;
  212421. Array <double> ratesIn, ratesOut;
  212422. if (createDevices())
  212423. {
  212424. jassert (inputDevice != 0 || outputDevice != 0);
  212425. if (inputDevice != 0 && outputDevice != 0)
  212426. {
  212427. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  212428. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  212429. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  212430. sampleRates = inputDevice->rates;
  212431. sampleRates.removeValuesNotIn (outputDevice->rates);
  212432. }
  212433. else
  212434. {
  212435. WASAPIDeviceBase* const d = inputDevice != 0 ? (WASAPIDeviceBase*) inputDevice : (WASAPIDeviceBase*) outputDevice;
  212436. defaultSampleRate = d->defaultSampleRate;
  212437. minBufferSize = d->minBufferSize;
  212438. defaultBufferSize = d->defaultBufferSize;
  212439. sampleRates = d->rates;
  212440. }
  212441. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  212442. if (minBufferSize != defaultBufferSize)
  212443. bufferSizes.addUsingDefaultSort (minBufferSize);
  212444. int n = 64;
  212445. for (int i = 0; i < 40; ++i)
  212446. {
  212447. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  212448. bufferSizes.addUsingDefaultSort (n);
  212449. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  212450. }
  212451. return true;
  212452. }
  212453. return false;
  212454. }
  212455. const StringArray getOutputChannelNames()
  212456. {
  212457. StringArray outChannels;
  212458. if (outputDevice != 0)
  212459. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  212460. outChannels.add ("Output channel " + String (i));
  212461. return outChannels;
  212462. }
  212463. const StringArray getInputChannelNames()
  212464. {
  212465. StringArray inChannels;
  212466. if (inputDevice != 0)
  212467. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  212468. inChannels.add ("Input channel " + String (i));
  212469. return inChannels;
  212470. }
  212471. int getNumSampleRates() { return sampleRates.size(); }
  212472. double getSampleRate (int index) { return sampleRates [index]; }
  212473. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  212474. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  212475. int getDefaultBufferSize() { return defaultBufferSize; }
  212476. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  212477. double getCurrentSampleRate() { return currentSampleRate; }
  212478. int getCurrentBitDepth() { return 32; }
  212479. int getOutputLatencyInSamples() { return latencyOut; }
  212480. int getInputLatencyInSamples() { return latencyIn; }
  212481. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  212482. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  212483. const String getLastError() { return lastError; }
  212484. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  212485. double sampleRate, int bufferSizeSamples)
  212486. {
  212487. close();
  212488. lastError = String::empty;
  212489. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  212490. {
  212491. lastError = "The input and output devices don't share a common sample rate!";
  212492. return lastError;
  212493. }
  212494. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  212495. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  212496. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  212497. {
  212498. lastError = "Couldn't open the input device!";
  212499. return lastError;
  212500. }
  212501. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  212502. {
  212503. close();
  212504. lastError = "Couldn't open the output device!";
  212505. return lastError;
  212506. }
  212507. if (inputDevice != 0)
  212508. ResetEvent (inputDevice->clientEvent);
  212509. if (outputDevice != 0)
  212510. ResetEvent (outputDevice->clientEvent);
  212511. startThread (8);
  212512. Thread::sleep (5);
  212513. if (inputDevice != 0 && inputDevice->client != 0)
  212514. {
  212515. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  212516. HRESULT hr = inputDevice->client->Start();
  212517. logFailure (hr); //xxx handle this
  212518. }
  212519. if (outputDevice != 0 && outputDevice->client != 0)
  212520. {
  212521. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  212522. HRESULT hr = outputDevice->client->Start();
  212523. logFailure (hr); //xxx handle this
  212524. }
  212525. isOpen_ = true;
  212526. return lastError;
  212527. }
  212528. void close()
  212529. {
  212530. stop();
  212531. if (inputDevice != 0)
  212532. SetEvent (inputDevice->clientEvent);
  212533. if (outputDevice != 0)
  212534. SetEvent (outputDevice->clientEvent);
  212535. stopThread (5000);
  212536. if (inputDevice != 0)
  212537. inputDevice->close();
  212538. if (outputDevice != 0)
  212539. outputDevice->close();
  212540. isOpen_ = false;
  212541. }
  212542. bool isOpen() { return isOpen_ && isThreadRunning(); }
  212543. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  212544. void start (AudioIODeviceCallback* call)
  212545. {
  212546. if (isOpen_ && call != 0 && ! isStarted)
  212547. {
  212548. if (! isThreadRunning())
  212549. {
  212550. // something's gone wrong and the thread's stopped..
  212551. isOpen_ = false;
  212552. return;
  212553. }
  212554. call->audioDeviceAboutToStart (this);
  212555. const ScopedLock sl (startStopLock);
  212556. callback = call;
  212557. isStarted = true;
  212558. }
  212559. }
  212560. void stop()
  212561. {
  212562. if (isStarted)
  212563. {
  212564. AudioIODeviceCallback* const callbackLocal = callback;
  212565. {
  212566. const ScopedLock sl (startStopLock);
  212567. isStarted = false;
  212568. }
  212569. if (callbackLocal != 0)
  212570. callbackLocal->audioDeviceStopped();
  212571. }
  212572. }
  212573. void setMMThreadPriority()
  212574. {
  212575. DynamicLibraryLoader dll ("avrt.dll");
  212576. DynamicLibraryImport (AvSetMmThreadCharacteristics, avSetMmThreadCharacteristics, HANDLE, dll, (LPCTSTR, LPDWORD))
  212577. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  212578. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  212579. {
  212580. DWORD dummy = 0;
  212581. HANDLE h = avSetMmThreadCharacteristics (_T("Pro Audio"), &dummy);
  212582. if (h != 0)
  212583. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  212584. }
  212585. }
  212586. void run()
  212587. {
  212588. setMMThreadPriority();
  212589. const int bufferSize = currentBufferSizeSamples;
  212590. HANDLE events[2];
  212591. int numEvents = 0;
  212592. if (inputDevice != 0)
  212593. events [numEvents++] = inputDevice->clientEvent;
  212594. if (outputDevice != 0)
  212595. events [numEvents++] = outputDevice->clientEvent;
  212596. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  212597. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  212598. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  212599. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  212600. float** const inputBuffers = ins.getArrayOfChannels();
  212601. float** const outputBuffers = outs.getArrayOfChannels();
  212602. ins.clear();
  212603. while (! threadShouldExit())
  212604. {
  212605. const DWORD result = useExclusiveMode ? WaitForSingleObject (inputDevice->clientEvent, 1000)
  212606. : WaitForMultipleObjects (numEvents, events, true, 1000);
  212607. if (result == WAIT_TIMEOUT)
  212608. continue;
  212609. if (threadShouldExit())
  212610. break;
  212611. if (inputDevice != 0)
  212612. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  212613. // Make the callback..
  212614. {
  212615. const ScopedLock sl (startStopLock);
  212616. if (isStarted)
  212617. {
  212618. JUCE_TRY
  212619. {
  212620. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  212621. numInputBuffers,
  212622. outputBuffers,
  212623. numOutputBuffers,
  212624. bufferSize);
  212625. }
  212626. JUCE_CATCH_EXCEPTION
  212627. }
  212628. else
  212629. {
  212630. outs.clear();
  212631. }
  212632. }
  212633. if (useExclusiveMode && WaitForSingleObject (outputDevice->clientEvent, 1000) == WAIT_TIMEOUT)
  212634. continue;
  212635. if (outputDevice != 0)
  212636. outputDevice->copyBuffers ((const float**) outputBuffers, numOutputBuffers, bufferSize, *this);
  212637. }
  212638. }
  212639. juce_UseDebuggingNewOperator
  212640. String outputDeviceId, inputDeviceId;
  212641. String lastError;
  212642. private:
  212643. // Device stats...
  212644. WASAPIInputDevice* inputDevice;
  212645. WASAPIOutputDevice* outputDevice;
  212646. const bool useExclusiveMode;
  212647. double defaultSampleRate;
  212648. int minBufferSize, defaultBufferSize;
  212649. int latencyIn, latencyOut;
  212650. Array <double> sampleRates;
  212651. Array <int> bufferSizes;
  212652. // Active state...
  212653. bool isOpen_, isStarted;
  212654. int currentBufferSizeSamples;
  212655. double currentSampleRate;
  212656. AudioIODeviceCallback* callback;
  212657. CriticalSection startStopLock;
  212658. bool createDevices()
  212659. {
  212660. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  212661. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  212662. return false;
  212663. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  212664. if (! OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection)))
  212665. return false;
  212666. UINT32 numDevices = 0;
  212667. if (! OK (deviceCollection->GetCount (&numDevices)))
  212668. return false;
  212669. for (UINT32 i = 0; i < numDevices; ++i)
  212670. {
  212671. ComSmartPtr <IMMDevice> device;
  212672. if (! OK (deviceCollection->Item (i, &device)))
  212673. continue;
  212674. const String deviceId (wasapi_getDeviceID (device));
  212675. if (deviceId.isEmpty())
  212676. continue;
  212677. const EDataFlow flow = wasapi_getDataFlow (device);
  212678. if (deviceId == inputDeviceId && flow == eCapture)
  212679. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  212680. else if (deviceId == outputDeviceId && flow == eRender)
  212681. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  212682. }
  212683. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  212684. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  212685. }
  212686. WASAPIAudioIODevice (const WASAPIAudioIODevice&);
  212687. WASAPIAudioIODevice& operator= (const WASAPIAudioIODevice&);
  212688. };
  212689. class WASAPIAudioIODeviceType : public AudioIODeviceType
  212690. {
  212691. public:
  212692. WASAPIAudioIODeviceType()
  212693. : AudioIODeviceType ("Windows Audio"),
  212694. hasScanned (false)
  212695. {
  212696. }
  212697. ~WASAPIAudioIODeviceType()
  212698. {
  212699. }
  212700. void scanForDevices()
  212701. {
  212702. hasScanned = true;
  212703. outputDeviceNames.clear();
  212704. inputDeviceNames.clear();
  212705. outputDeviceIds.clear();
  212706. inputDeviceIds.clear();
  212707. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  212708. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  212709. return;
  212710. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  212711. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  212712. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  212713. UINT32 numDevices = 0;
  212714. if (! (OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection))
  212715. && OK (deviceCollection->GetCount (&numDevices))))
  212716. return;
  212717. for (UINT32 i = 0; i < numDevices; ++i)
  212718. {
  212719. ComSmartPtr <IMMDevice> device;
  212720. if (! OK (deviceCollection->Item (i, &device)))
  212721. continue;
  212722. const String deviceId (wasapi_getDeviceID (device));
  212723. DWORD state = 0;
  212724. if (! OK (device->GetState (&state)))
  212725. continue;
  212726. if (state != DEVICE_STATE_ACTIVE)
  212727. continue;
  212728. String name;
  212729. {
  212730. ComSmartPtr <IPropertyStore> properties;
  212731. if (! OK (device->OpenPropertyStore (STGM_READ, &properties)))
  212732. continue;
  212733. PROPVARIANT value;
  212734. PropVariantInit (&value);
  212735. if (OK (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  212736. name = value.pwszVal;
  212737. PropVariantClear (&value);
  212738. }
  212739. const EDataFlow flow = wasapi_getDataFlow (device);
  212740. if (flow == eRender)
  212741. {
  212742. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  212743. outputDeviceIds.insert (index, deviceId);
  212744. outputDeviceNames.insert (index, name);
  212745. }
  212746. else if (flow == eCapture)
  212747. {
  212748. const int index = (deviceId == defaultCapture) ? 0 : -1;
  212749. inputDeviceIds.insert (index, deviceId);
  212750. inputDeviceNames.insert (index, name);
  212751. }
  212752. }
  212753. inputDeviceNames.appendNumbersToDuplicates (false, false);
  212754. outputDeviceNames.appendNumbersToDuplicates (false, false);
  212755. }
  212756. const StringArray getDeviceNames (bool wantInputNames) const
  212757. {
  212758. jassert (hasScanned); // need to call scanForDevices() before doing this
  212759. return wantInputNames ? inputDeviceNames
  212760. : outputDeviceNames;
  212761. }
  212762. int getDefaultDeviceIndex (bool /*forInput*/) const
  212763. {
  212764. jassert (hasScanned); // need to call scanForDevices() before doing this
  212765. return 0;
  212766. }
  212767. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  212768. {
  212769. jassert (hasScanned); // need to call scanForDevices() before doing this
  212770. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  212771. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  212772. : outputDeviceIds.indexOf (d->outputDeviceId));
  212773. }
  212774. bool hasSeparateInputsAndOutputs() const { return true; }
  212775. AudioIODevice* createDevice (const String& outputDeviceName,
  212776. const String& inputDeviceName)
  212777. {
  212778. jassert (hasScanned); // need to call scanForDevices() before doing this
  212779. const bool useExclusiveMode = false;
  212780. ScopedPointer<WASAPIAudioIODevice> device;
  212781. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  212782. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  212783. if (outputIndex >= 0 || inputIndex >= 0)
  212784. {
  212785. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  212786. : inputDeviceName,
  212787. outputDeviceIds [outputIndex],
  212788. inputDeviceIds [inputIndex],
  212789. useExclusiveMode);
  212790. if (! device->initialise())
  212791. device = 0;
  212792. }
  212793. return device.release();
  212794. }
  212795. juce_UseDebuggingNewOperator
  212796. StringArray outputDeviceNames, outputDeviceIds;
  212797. StringArray inputDeviceNames, inputDeviceIds;
  212798. private:
  212799. bool hasScanned;
  212800. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  212801. {
  212802. String s;
  212803. IMMDevice* dev = 0;
  212804. if (OK (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  212805. eMultimedia, &dev)))
  212806. {
  212807. WCHAR* deviceId = 0;
  212808. if (OK (dev->GetId (&deviceId)))
  212809. {
  212810. s = String (deviceId);
  212811. CoTaskMemFree (deviceId);
  212812. }
  212813. dev->Release();
  212814. }
  212815. return s;
  212816. }
  212817. WASAPIAudioIODeviceType (const WASAPIAudioIODeviceType&);
  212818. WASAPIAudioIODeviceType& operator= (const WASAPIAudioIODeviceType&);
  212819. };
  212820. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  212821. {
  212822. return new WASAPIAudioIODeviceType();
  212823. }
  212824. #undef logFailure
  212825. #undef OK
  212826. #endif
  212827. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  212828. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  212829. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212830. // compiled on its own).
  212831. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  212832. class DShowCameraDeviceInteral : public ChangeBroadcaster
  212833. {
  212834. public:
  212835. DShowCameraDeviceInteral (CameraDevice* const owner_,
  212836. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  212837. const ComSmartPtr <IBaseFilter>& filter_,
  212838. int minWidth, int minHeight,
  212839. int maxWidth, int maxHeight)
  212840. : owner (owner_),
  212841. captureGraphBuilder (captureGraphBuilder_),
  212842. filter (filter_),
  212843. ok (false),
  212844. imageNeedsFlipping (false),
  212845. width (0),
  212846. height (0),
  212847. activeUsers (0),
  212848. recordNextFrameTime (false),
  212849. activeImage (0),
  212850. loadingImage (0)
  212851. {
  212852. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  212853. if (FAILED (hr))
  212854. return;
  212855. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  212856. if (FAILED (hr))
  212857. return;
  212858. hr = graphBuilder->QueryInterface (IID_IMediaControl, (void**) &mediaControl);
  212859. if (FAILED (hr))
  212860. return;
  212861. {
  212862. ComSmartPtr <IAMStreamConfig> streamConfig;
  212863. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  212864. IID_IAMStreamConfig, (void**) &streamConfig);
  212865. if (streamConfig != 0)
  212866. {
  212867. getVideoSizes (streamConfig);
  212868. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  212869. return;
  212870. }
  212871. }
  212872. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  212873. if (FAILED (hr))
  212874. return;
  212875. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  212876. if (FAILED (hr))
  212877. return;
  212878. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  212879. if (FAILED (hr))
  212880. return;
  212881. if (! connectFilters (filter, smartTee))
  212882. return;
  212883. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  212884. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  212885. if (FAILED (hr))
  212886. return;
  212887. hr = sampleGrabberBase->QueryInterface (IID_ISampleGrabber, (void**) &sampleGrabber);
  212888. if (FAILED (hr))
  212889. return;
  212890. AM_MEDIA_TYPE mt;
  212891. zerostruct (mt);
  212892. mt.majortype = MEDIATYPE_Video;
  212893. mt.subtype = MEDIASUBTYPE_RGB24;
  212894. mt.formattype = FORMAT_VideoInfo;
  212895. sampleGrabber->SetMediaType (&mt);
  212896. callback = new GrabberCallback (*this);
  212897. sampleGrabber->SetCallback (callback, 1);
  212898. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  212899. if (FAILED (hr))
  212900. return;
  212901. ComSmartPtr <IPin> grabberInputPin;
  212902. if (! (getPin (smartTee, PINDIR_OUTPUT, &smartTeeCaptureOutputPin, "capture")
  212903. && getPin (smartTee, PINDIR_OUTPUT, &smartTeePreviewOutputPin, "preview")
  212904. && getPin (sampleGrabberBase, PINDIR_INPUT, &grabberInputPin)))
  212905. return;
  212906. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  212907. if (FAILED (hr))
  212908. return;
  212909. zerostruct (mt);
  212910. hr = sampleGrabber->GetConnectedMediaType (&mt);
  212911. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  212912. width = pVih->bmiHeader.biWidth;
  212913. height = pVih->bmiHeader.biHeight;
  212914. ComSmartPtr <IBaseFilter> nullFilter;
  212915. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  212916. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  212917. if (connectFilters (sampleGrabberBase, nullFilter)
  212918. && addGraphToRot())
  212919. {
  212920. activeImage = new Image (Image::RGB, width, height, true);
  212921. loadingImage = new Image (Image::RGB, width, height, true);
  212922. ok = true;
  212923. }
  212924. }
  212925. ~DShowCameraDeviceInteral()
  212926. {
  212927. if (mediaControl != 0)
  212928. mediaControl->Stop();
  212929. removeGraphFromRot();
  212930. for (int i = viewerComps.size(); --i >= 0;)
  212931. ((DShowCaptureViewerComp*) viewerComps.getUnchecked(i))->ownerDeleted();
  212932. callback = 0;
  212933. graphBuilder = 0;
  212934. sampleGrabber = 0;
  212935. mediaControl = 0;
  212936. filter = 0;
  212937. captureGraphBuilder = 0;
  212938. smartTee = 0;
  212939. smartTeePreviewOutputPin = 0;
  212940. smartTeeCaptureOutputPin = 0;
  212941. asfWriter = 0;
  212942. delete activeImage;
  212943. delete loadingImage;
  212944. }
  212945. void addUser()
  212946. {
  212947. if (ok && activeUsers++ == 0)
  212948. mediaControl->Run();
  212949. }
  212950. void removeUser()
  212951. {
  212952. if (ok && --activeUsers == 0)
  212953. mediaControl->Stop();
  212954. }
  212955. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  212956. {
  212957. if (recordNextFrameTime)
  212958. {
  212959. const double defaultCameraLatency = 0.1;
  212960. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  212961. recordNextFrameTime = false;
  212962. ComSmartPtr <IPin> pin;
  212963. if (getPin (filter, PINDIR_OUTPUT, &pin))
  212964. {
  212965. ComSmartPtr <IAMPushSource> pushSource;
  212966. HRESULT hr = pin->QueryInterface (IID_IAMPushSource, (void**) &pushSource);
  212967. if (pushSource != 0)
  212968. {
  212969. REFERENCE_TIME latency = 0;
  212970. hr = pushSource->GetLatency (&latency);
  212971. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  212972. }
  212973. }
  212974. }
  212975. {
  212976. const int lineStride = width * 3;
  212977. const ScopedLock sl (imageSwapLock);
  212978. {
  212979. const Image::BitmapData destData (*loadingImage, 0, 0, width, height, true);
  212980. for (int i = 0; i < height; ++i)
  212981. memcpy (destData.getLinePointer ((height - 1) - i),
  212982. buffer + lineStride * i,
  212983. lineStride);
  212984. }
  212985. imageNeedsFlipping = true;
  212986. }
  212987. if (listeners.size() > 0)
  212988. callListeners (*loadingImage);
  212989. sendChangeMessage (this);
  212990. }
  212991. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  212992. {
  212993. if (imageNeedsFlipping)
  212994. {
  212995. const ScopedLock sl (imageSwapLock);
  212996. swapVariables (loadingImage, activeImage);
  212997. imageNeedsFlipping = false;
  212998. }
  212999. RectanglePlacement rp (RectanglePlacement::centred);
  213000. double dx = 0, dy = 0, dw = width, dh = height;
  213001. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  213002. const int rx = roundToInt (dx), ry = roundToInt (dy);
  213003. const int rw = roundToInt (dw), rh = roundToInt (dh);
  213004. g.saveState();
  213005. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  213006. g.fillAll (Colours::black);
  213007. g.restoreState();
  213008. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  213009. }
  213010. bool createFileCaptureFilter (const File& file)
  213011. {
  213012. removeFileCaptureFilter();
  213013. file.deleteFile();
  213014. mediaControl->Stop();
  213015. firstRecordedTime = Time();
  213016. recordNextFrameTime = true;
  213017. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  213018. if (SUCCEEDED (hr))
  213019. {
  213020. ComSmartPtr <IFileSinkFilter> fileSink;
  213021. hr = asfWriter->QueryInterface (IID_IFileSinkFilter, (void**) &fileSink);
  213022. if (SUCCEEDED (hr))
  213023. {
  213024. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  213025. if (SUCCEEDED (hr))
  213026. {
  213027. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  213028. if (SUCCEEDED (hr))
  213029. {
  213030. ComSmartPtr <IConfigAsfWriter> asfConfig;
  213031. hr = asfWriter->QueryInterface (IID_IConfigAsfWriter, (void**) &asfConfig);
  213032. asfConfig->SetIndexMode (true);
  213033. ComSmartPtr <IWMProfileManager> profileManager;
  213034. hr = WMCreateProfileManager (&profileManager);
  213035. // This gibberish is the DirectShow profile for a video-only wmv file.
  213036. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\"><streamconfig "
  213037. "majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  213038. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\"><videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  213039. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" btemporalcompression=\"1\" lsamplesize=\"0\"> <videoinfoheader "
  213040. "dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"100000\"><rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <rctarget "
  213041. "left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  213042. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" biclrused=\"0\" biclrimportant=\"0\"/> "
  213043. "</videoinfoheader></wmmediatype></streamconfig></profile>");
  213044. prof = prof.replace ("$WIDTH", String (width))
  213045. .replace ("$HEIGHT", String (height));
  213046. ComSmartPtr <IWMProfile> currentProfile;
  213047. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, &currentProfile);
  213048. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  213049. if (SUCCEEDED (hr))
  213050. {
  213051. ComSmartPtr <IPin> asfWriterInputPin;
  213052. if (getPin (asfWriter, PINDIR_INPUT, &asfWriterInputPin, "Video Input 01"))
  213053. {
  213054. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  213055. if (SUCCEEDED (hr)
  213056. && ok && activeUsers > 0
  213057. && SUCCEEDED (mediaControl->Run()))
  213058. {
  213059. return true;
  213060. }
  213061. }
  213062. }
  213063. }
  213064. }
  213065. }
  213066. }
  213067. removeFileCaptureFilter();
  213068. if (ok && activeUsers > 0)
  213069. mediaControl->Run();
  213070. return false;
  213071. }
  213072. void removeFileCaptureFilter()
  213073. {
  213074. mediaControl->Stop();
  213075. if (asfWriter != 0)
  213076. {
  213077. graphBuilder->RemoveFilter (asfWriter);
  213078. asfWriter = 0;
  213079. }
  213080. if (ok && activeUsers > 0)
  213081. mediaControl->Run();
  213082. }
  213083. void addListener (CameraImageListener* listenerToAdd)
  213084. {
  213085. const ScopedLock sl (listenerLock);
  213086. if (listeners.size() == 0)
  213087. addUser();
  213088. listeners.addIfNotAlreadyThere (listenerToAdd);
  213089. }
  213090. void removeListener (CameraImageListener* listenerToRemove)
  213091. {
  213092. const ScopedLock sl (listenerLock);
  213093. listeners.removeValue (listenerToRemove);
  213094. if (listeners.size() == 0)
  213095. removeUser();
  213096. }
  213097. void callListeners (Image& image)
  213098. {
  213099. const ScopedLock sl (listenerLock);
  213100. for (int i = listeners.size(); --i >= 0;)
  213101. {
  213102. CameraImageListener* l = (CameraImageListener*) listeners[i];
  213103. if (l != 0)
  213104. l->imageReceived (image);
  213105. }
  213106. }
  213107. class DShowCaptureViewerComp : public Component,
  213108. public ChangeListener
  213109. {
  213110. public:
  213111. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  213112. : owner (owner_)
  213113. {
  213114. setOpaque (true);
  213115. owner->addChangeListener (this);
  213116. owner->addUser();
  213117. owner->viewerComps.add (this);
  213118. setSize (owner_->width, owner_->height);
  213119. }
  213120. ~DShowCaptureViewerComp()
  213121. {
  213122. if (owner != 0)
  213123. {
  213124. owner->viewerComps.removeValue (this);
  213125. owner->removeUser();
  213126. owner->removeChangeListener (this);
  213127. }
  213128. }
  213129. void ownerDeleted()
  213130. {
  213131. owner = 0;
  213132. }
  213133. void paint (Graphics& g)
  213134. {
  213135. g.setColour (Colours::black);
  213136. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  213137. if (owner != 0)
  213138. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  213139. else
  213140. g.fillAll (Colours::black);
  213141. }
  213142. void changeListenerCallback (void*)
  213143. {
  213144. repaint();
  213145. }
  213146. private:
  213147. DShowCameraDeviceInteral* owner;
  213148. };
  213149. bool ok;
  213150. int width, height;
  213151. Time firstRecordedTime;
  213152. VoidArray viewerComps;
  213153. private:
  213154. CameraDevice* const owner;
  213155. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  213156. ComSmartPtr <IBaseFilter> filter;
  213157. ComSmartPtr <IBaseFilter> smartTee;
  213158. ComSmartPtr <IGraphBuilder> graphBuilder;
  213159. ComSmartPtr <ISampleGrabber> sampleGrabber;
  213160. ComSmartPtr <IMediaControl> mediaControl;
  213161. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  213162. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  213163. ComSmartPtr <IBaseFilter> asfWriter;
  213164. int activeUsers;
  213165. Array <int> widths, heights;
  213166. DWORD graphRegistrationID;
  213167. CriticalSection imageSwapLock;
  213168. bool imageNeedsFlipping;
  213169. Image* loadingImage;
  213170. Image* activeImage;
  213171. bool recordNextFrameTime;
  213172. void getVideoSizes (IAMStreamConfig* const streamConfig)
  213173. {
  213174. widths.clear();
  213175. heights.clear();
  213176. int count = 0, size = 0;
  213177. streamConfig->GetNumberOfCapabilities (&count, &size);
  213178. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  213179. {
  213180. for (int i = 0; i < count; ++i)
  213181. {
  213182. VIDEO_STREAM_CONFIG_CAPS scc;
  213183. AM_MEDIA_TYPE* config;
  213184. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  213185. if (SUCCEEDED (hr))
  213186. {
  213187. const int w = scc.InputSize.cx;
  213188. const int h = scc.InputSize.cy;
  213189. bool duplicate = false;
  213190. for (int j = widths.size(); --j >= 0;)
  213191. {
  213192. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  213193. {
  213194. duplicate = true;
  213195. break;
  213196. }
  213197. }
  213198. if (! duplicate)
  213199. {
  213200. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  213201. widths.add (w);
  213202. heights.add (h);
  213203. }
  213204. deleteMediaType (config);
  213205. }
  213206. }
  213207. }
  213208. }
  213209. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  213210. const int minWidth, const int minHeight,
  213211. const int maxWidth, const int maxHeight)
  213212. {
  213213. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  213214. streamConfig->GetNumberOfCapabilities (&count, &size);
  213215. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  213216. {
  213217. AM_MEDIA_TYPE* config;
  213218. VIDEO_STREAM_CONFIG_CAPS scc;
  213219. for (int i = 0; i < count; ++i)
  213220. {
  213221. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  213222. if (SUCCEEDED (hr))
  213223. {
  213224. if (scc.InputSize.cx >= minWidth
  213225. && scc.InputSize.cy >= minHeight
  213226. && scc.InputSize.cx <= maxWidth
  213227. && scc.InputSize.cy <= maxHeight)
  213228. {
  213229. int area = scc.InputSize.cx * scc.InputSize.cy;
  213230. if (area > bestArea)
  213231. {
  213232. bestIndex = i;
  213233. bestArea = area;
  213234. }
  213235. }
  213236. deleteMediaType (config);
  213237. }
  213238. }
  213239. if (bestIndex >= 0)
  213240. {
  213241. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  213242. hr = streamConfig->SetFormat (config);
  213243. deleteMediaType (config);
  213244. return SUCCEEDED (hr);
  213245. }
  213246. }
  213247. return false;
  213248. }
  213249. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, IPin** result, const char* pinName = 0)
  213250. {
  213251. ComSmartPtr <IEnumPins> enumerator;
  213252. ComSmartPtr <IPin> pin;
  213253. filter->EnumPins (&enumerator);
  213254. while (enumerator->Next (1, &pin, 0) == S_OK)
  213255. {
  213256. PIN_DIRECTION dir;
  213257. pin->QueryDirection (&dir);
  213258. if (wantedDirection == dir)
  213259. {
  213260. PIN_INFO info;
  213261. zerostruct (info);
  213262. pin->QueryPinInfo (&info);
  213263. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  213264. {
  213265. pin->AddRef();
  213266. *result = pin;
  213267. return true;
  213268. }
  213269. }
  213270. }
  213271. return false;
  213272. }
  213273. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  213274. {
  213275. ComSmartPtr <IPin> in, out;
  213276. return getPin (first, PINDIR_OUTPUT, &out)
  213277. && getPin (second, PINDIR_INPUT, &in)
  213278. && SUCCEEDED (graphBuilder->Connect (out, in));
  213279. }
  213280. bool addGraphToRot()
  213281. {
  213282. ComSmartPtr <IRunningObjectTable> rot;
  213283. if (FAILED (GetRunningObjectTable (0, &rot)))
  213284. return false;
  213285. ComSmartPtr <IMoniker> moniker;
  213286. WCHAR buffer[128];
  213287. HRESULT hr = CreateItemMoniker (_T("!"), buffer, &moniker);
  213288. if (FAILED (hr))
  213289. return false;
  213290. graphRegistrationID = 0;
  213291. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  213292. }
  213293. void removeGraphFromRot()
  213294. {
  213295. ComSmartPtr <IRunningObjectTable> rot;
  213296. if (SUCCEEDED (GetRunningObjectTable (0, &rot)))
  213297. rot->Revoke (graphRegistrationID);
  213298. }
  213299. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  213300. {
  213301. if (pmt->cbFormat != 0)
  213302. CoTaskMemFree ((PVOID) pmt->pbFormat);
  213303. if (pmt->pUnk != 0)
  213304. pmt->pUnk->Release();
  213305. CoTaskMemFree (pmt);
  213306. }
  213307. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  213308. {
  213309. public:
  213310. GrabberCallback (DShowCameraDeviceInteral& owner_)
  213311. : owner (owner_)
  213312. {
  213313. }
  213314. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  213315. {
  213316. return E_FAIL;
  213317. }
  213318. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  213319. {
  213320. owner.handleFrame (time, buffer, bufferSize);
  213321. return S_OK;
  213322. }
  213323. private:
  213324. DShowCameraDeviceInteral& owner;
  213325. GrabberCallback (const GrabberCallback&);
  213326. GrabberCallback& operator= (const GrabberCallback&);
  213327. };
  213328. ComSmartPtr <GrabberCallback> callback;
  213329. VoidArray listeners;
  213330. CriticalSection listenerLock;
  213331. DShowCameraDeviceInteral (const DShowCameraDeviceInteral&);
  213332. DShowCameraDeviceInteral& operator= (const DShowCameraDeviceInteral&);
  213333. };
  213334. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  213335. : name (name_)
  213336. {
  213337. isRecording = false;
  213338. }
  213339. CameraDevice::~CameraDevice()
  213340. {
  213341. stopRecording();
  213342. delete static_cast <DShowCameraDeviceInteral*> (internal);
  213343. internal = 0;
  213344. }
  213345. Component* CameraDevice::createViewerComponent()
  213346. {
  213347. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  213348. }
  213349. const String CameraDevice::getFileExtension()
  213350. {
  213351. return ".wmv";
  213352. }
  213353. void CameraDevice::startRecordingToFile (const File& file, int quality)
  213354. {
  213355. stopRecording();
  213356. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  213357. d->addUser();
  213358. isRecording = d->createFileCaptureFilter (file);
  213359. }
  213360. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  213361. {
  213362. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  213363. return d->firstRecordedTime;
  213364. }
  213365. void CameraDevice::stopRecording()
  213366. {
  213367. if (isRecording)
  213368. {
  213369. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  213370. d->removeFileCaptureFilter();
  213371. d->removeUser();
  213372. isRecording = false;
  213373. }
  213374. }
  213375. void CameraDevice::addListener (CameraImageListener* listenerToAdd)
  213376. {
  213377. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  213378. if (listenerToAdd != 0)
  213379. d->addListener (listenerToAdd);
  213380. }
  213381. void CameraDevice::removeListener (CameraImageListener* listenerToRemove)
  213382. {
  213383. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  213384. if (listenerToRemove != 0)
  213385. d->removeListener (listenerToRemove);
  213386. }
  213387. static ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  213388. const int deviceIndexToOpen,
  213389. String& name)
  213390. {
  213391. int index = 0;
  213392. ComSmartPtr <IBaseFilter> result;
  213393. ComSmartPtr <ICreateDevEnum> pDevEnum;
  213394. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  213395. if (SUCCEEDED (hr))
  213396. {
  213397. ComSmartPtr <IEnumMoniker> enumerator;
  213398. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, &enumerator, 0);
  213399. if (SUCCEEDED (hr) && enumerator != 0)
  213400. {
  213401. ComSmartPtr <IBaseFilter> captureFilter;
  213402. ComSmartPtr <IMoniker> moniker;
  213403. ULONG fetched;
  213404. while (enumerator->Next (1, &moniker, &fetched) == S_OK)
  213405. {
  213406. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) &captureFilter);
  213407. if (SUCCEEDED (hr))
  213408. {
  213409. ComSmartPtr <IPropertyBag> propertyBag;
  213410. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) &propertyBag);
  213411. if (SUCCEEDED (hr))
  213412. {
  213413. VARIANT var;
  213414. var.vt = VT_BSTR;
  213415. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  213416. propertyBag = 0;
  213417. if (SUCCEEDED (hr))
  213418. {
  213419. if (names != 0)
  213420. names->add (var.bstrVal);
  213421. if (index == deviceIndexToOpen)
  213422. {
  213423. name = var.bstrVal;
  213424. result = captureFilter;
  213425. captureFilter = 0;
  213426. break;
  213427. }
  213428. ++index;
  213429. }
  213430. moniker = 0;
  213431. }
  213432. captureFilter = 0;
  213433. }
  213434. }
  213435. }
  213436. }
  213437. return result;
  213438. }
  213439. const StringArray CameraDevice::getAvailableDevices()
  213440. {
  213441. StringArray devs;
  213442. String dummy;
  213443. enumerateCameras (&devs, -1, dummy);
  213444. return devs;
  213445. }
  213446. CameraDevice* CameraDevice::openDevice (int index,
  213447. int minWidth, int minHeight,
  213448. int maxWidth, int maxHeight)
  213449. {
  213450. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  213451. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  213452. if (SUCCEEDED (hr))
  213453. {
  213454. String name;
  213455. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  213456. if (filter != 0)
  213457. {
  213458. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  213459. DShowCameraDeviceInteral* const intern
  213460. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  213461. minWidth, minHeight, maxWidth, maxHeight);
  213462. cam->internal = intern;
  213463. if (intern->ok)
  213464. return cam.release();
  213465. }
  213466. }
  213467. return 0;
  213468. }
  213469. #endif
  213470. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  213471. #endif
  213472. // Auto-link the other win32 libs that are needed by library calls..
  213473. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  213474. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  213475. // Auto-links to various win32 libs that are needed by library calls..
  213476. #pragma comment(lib, "kernel32.lib")
  213477. #pragma comment(lib, "user32.lib")
  213478. #pragma comment(lib, "shell32.lib")
  213479. #pragma comment(lib, "gdi32.lib")
  213480. #pragma comment(lib, "vfw32.lib")
  213481. #pragma comment(lib, "comdlg32.lib")
  213482. #pragma comment(lib, "winmm.lib")
  213483. #pragma comment(lib, "wininet.lib")
  213484. #pragma comment(lib, "ole32.lib")
  213485. #pragma comment(lib, "oleaut32.lib")
  213486. #pragma comment(lib, "advapi32.lib")
  213487. #pragma comment(lib, "ws2_32.lib")
  213488. #pragma comment(lib, "comsupp.lib")
  213489. #pragma comment(lib, "version.lib")
  213490. #if JUCE_OPENGL
  213491. #pragma comment(lib, "OpenGL32.Lib")
  213492. #pragma comment(lib, "GlU32.Lib")
  213493. #endif
  213494. #if JUCE_QUICKTIME
  213495. #pragma comment (lib, "QTMLClient.lib")
  213496. #endif
  213497. #if JUCE_USE_CAMERA
  213498. #pragma comment (lib, "Strmiids.lib")
  213499. #pragma comment (lib, "wmvcore.lib")
  213500. #endif
  213501. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  213502. #endif
  213503. END_JUCE_NAMESPACE
  213504. #endif
  213505. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  213506. #endif
  213507. #if JUCE_LINUX
  213508. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  213509. /*
  213510. This file wraps together all the mac-specific code, so that
  213511. we can include all the native headers just once, and compile all our
  213512. platform-specific stuff in one big lump, keeping it out of the way of
  213513. the rest of the codebase.
  213514. */
  213515. #if JUCE_LINUX
  213516. BEGIN_JUCE_NAMESPACE
  213517. #define JUCE_INCLUDED_FILE 1
  213518. // Now include the actual code files..
  213519. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  213520. /*
  213521. This file contains posix routines that are common to both the Linux and Mac builds.
  213522. It gets included directly in the cpp files for these platforms.
  213523. */
  213524. CriticalSection::CriticalSection() throw()
  213525. {
  213526. pthread_mutexattr_t atts;
  213527. pthread_mutexattr_init (&atts);
  213528. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  213529. pthread_mutex_init (&internal, &atts);
  213530. }
  213531. CriticalSection::~CriticalSection() throw()
  213532. {
  213533. pthread_mutex_destroy (&internal);
  213534. }
  213535. void CriticalSection::enter() const throw()
  213536. {
  213537. pthread_mutex_lock (&internal);
  213538. }
  213539. bool CriticalSection::tryEnter() const throw()
  213540. {
  213541. return pthread_mutex_trylock (&internal) == 0;
  213542. }
  213543. void CriticalSection::exit() const throw()
  213544. {
  213545. pthread_mutex_unlock (&internal);
  213546. }
  213547. class WaitableEventImpl
  213548. {
  213549. public:
  213550. WaitableEventImpl (const bool manualReset_)
  213551. : triggered (false),
  213552. manualReset (manualReset_)
  213553. {
  213554. pthread_cond_init (&condition, 0);
  213555. pthread_mutex_init (&mutex, 0);
  213556. }
  213557. ~WaitableEventImpl()
  213558. {
  213559. pthread_cond_destroy (&condition);
  213560. pthread_mutex_destroy (&mutex);
  213561. }
  213562. bool wait (const int timeOutMillisecs) throw()
  213563. {
  213564. pthread_mutex_lock (&mutex);
  213565. if (! triggered)
  213566. {
  213567. if (timeOutMillisecs < 0)
  213568. {
  213569. do
  213570. {
  213571. pthread_cond_wait (&condition, &mutex);
  213572. }
  213573. while (! triggered);
  213574. }
  213575. else
  213576. {
  213577. struct timeval now;
  213578. gettimeofday (&now, 0);
  213579. struct timespec time;
  213580. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  213581. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  213582. if (time.tv_nsec >= 1000000000)
  213583. {
  213584. time.tv_nsec -= 1000000000;
  213585. time.tv_sec++;
  213586. }
  213587. do
  213588. {
  213589. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  213590. {
  213591. pthread_mutex_unlock (&mutex);
  213592. return false;
  213593. }
  213594. }
  213595. while (! triggered);
  213596. }
  213597. }
  213598. if (! manualReset)
  213599. triggered = false;
  213600. pthread_mutex_unlock (&mutex);
  213601. return true;
  213602. }
  213603. void signal() throw()
  213604. {
  213605. pthread_mutex_lock (&mutex);
  213606. triggered = true;
  213607. pthread_cond_broadcast (&condition);
  213608. pthread_mutex_unlock (&mutex);
  213609. }
  213610. void reset() throw()
  213611. {
  213612. pthread_mutex_lock (&mutex);
  213613. triggered = false;
  213614. pthread_mutex_unlock (&mutex);
  213615. }
  213616. private:
  213617. pthread_cond_t condition;
  213618. pthread_mutex_t mutex;
  213619. bool triggered;
  213620. const bool manualReset;
  213621. WaitableEventImpl (const WaitableEventImpl&);
  213622. WaitableEventImpl& operator= (const WaitableEventImpl&);
  213623. };
  213624. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  213625. : internal (new WaitableEventImpl (manualReset))
  213626. {
  213627. }
  213628. WaitableEvent::~WaitableEvent() throw()
  213629. {
  213630. delete static_cast <WaitableEventImpl*> (internal);
  213631. }
  213632. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  213633. {
  213634. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  213635. }
  213636. void WaitableEvent::signal() const throw()
  213637. {
  213638. static_cast <WaitableEventImpl*> (internal)->signal();
  213639. }
  213640. void WaitableEvent::reset() const throw()
  213641. {
  213642. static_cast <WaitableEventImpl*> (internal)->reset();
  213643. }
  213644. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  213645. {
  213646. struct timespec time;
  213647. time.tv_sec = millisecs / 1000;
  213648. time.tv_nsec = (millisecs % 1000) * 1000000;
  213649. nanosleep (&time, 0);
  213650. }
  213651. const juce_wchar File::separator = '/';
  213652. const String File::separatorString ("/");
  213653. const File File::getCurrentWorkingDirectory()
  213654. {
  213655. HeapBlock<char> heapBuffer;
  213656. char localBuffer [1024];
  213657. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  213658. int bufferSize = 4096;
  213659. while (cwd == 0 && errno == ERANGE)
  213660. {
  213661. heapBuffer.malloc (bufferSize);
  213662. cwd = getcwd (heapBuffer, bufferSize - 1);
  213663. bufferSize += 1024;
  213664. }
  213665. return File (String::fromUTF8 (cwd));
  213666. }
  213667. bool File::setAsCurrentWorkingDirectory() const
  213668. {
  213669. return chdir (getFullPathName().toUTF8()) == 0;
  213670. }
  213671. static bool juce_stat (const String& fileName, struct stat& info)
  213672. {
  213673. return fileName.isNotEmpty()
  213674. && (stat (fileName.toUTF8(), &info) == 0);
  213675. }
  213676. bool File::isDirectory() const
  213677. {
  213678. struct stat info;
  213679. return fullPath.isEmpty()
  213680. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  213681. }
  213682. bool File::exists() const
  213683. {
  213684. return fullPath.isNotEmpty()
  213685. && access (fullPath.toUTF8(), F_OK) == 0;
  213686. }
  213687. bool File::existsAsFile() const
  213688. {
  213689. return exists() && ! isDirectory();
  213690. }
  213691. int64 File::getSize() const
  213692. {
  213693. struct stat info;
  213694. return juce_stat (fullPath, info) ? info.st_size : 0;
  213695. }
  213696. bool File::hasWriteAccess() const
  213697. {
  213698. if (exists())
  213699. return access (fullPath.toUTF8(), W_OK) == 0;
  213700. if ((! isDirectory()) && fullPath.containsChar (separator))
  213701. return getParentDirectory().hasWriteAccess();
  213702. return false;
  213703. }
  213704. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  213705. {
  213706. struct stat info;
  213707. const int res = stat (fullPath.toUTF8(), &info);
  213708. if (res != 0)
  213709. return false;
  213710. info.st_mode &= 0777; // Just permissions
  213711. if (shouldBeReadOnly)
  213712. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  213713. else
  213714. // Give everybody write permission?
  213715. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  213716. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  213717. }
  213718. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  213719. {
  213720. modificationTime = 0;
  213721. accessTime = 0;
  213722. creationTime = 0;
  213723. struct stat info;
  213724. const int res = stat (fullPath.toUTF8(), &info);
  213725. if (res == 0)
  213726. {
  213727. modificationTime = (int64) info.st_mtime * 1000;
  213728. accessTime = (int64) info.st_atime * 1000;
  213729. creationTime = (int64) info.st_ctime * 1000;
  213730. }
  213731. }
  213732. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  213733. {
  213734. struct utimbuf times;
  213735. times.actime = (time_t) (accessTime / 1000);
  213736. times.modtime = (time_t) (modificationTime / 1000);
  213737. return utime (fullPath.toUTF8(), &times) == 0;
  213738. }
  213739. bool File::deleteFile() const
  213740. {
  213741. if (! exists())
  213742. return true;
  213743. else if (isDirectory())
  213744. return rmdir (fullPath.toUTF8()) == 0;
  213745. else
  213746. return remove (fullPath.toUTF8()) == 0;
  213747. }
  213748. bool File::moveInternal (const File& dest) const
  213749. {
  213750. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  213751. return true;
  213752. if (hasWriteAccess() && copyInternal (dest))
  213753. {
  213754. if (deleteFile())
  213755. return true;
  213756. dest.deleteFile();
  213757. }
  213758. return false;
  213759. }
  213760. void File::createDirectoryInternal (const String& fileName) const
  213761. {
  213762. mkdir (fileName.toUTF8(), 0777);
  213763. }
  213764. void* juce_fileOpen (const File& file, bool forWriting)
  213765. {
  213766. int flags = O_RDONLY;
  213767. if (forWriting)
  213768. {
  213769. if (file.exists())
  213770. {
  213771. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  213772. if (f != -1)
  213773. lseek (f, 0, SEEK_END);
  213774. return (void*) f;
  213775. }
  213776. else
  213777. {
  213778. flags = O_RDWR + O_CREAT;
  213779. }
  213780. }
  213781. return (void*) open (file.getFullPathName().toUTF8(), flags, 00644);
  213782. }
  213783. void juce_fileClose (void* handle)
  213784. {
  213785. if (handle != 0)
  213786. close ((int) (pointer_sized_int) handle);
  213787. }
  213788. int juce_fileRead (void* handle, void* buffer, int size)
  213789. {
  213790. if (handle != 0)
  213791. return jmax (0, (int) read ((int) (pointer_sized_int) handle, buffer, size));
  213792. return 0;
  213793. }
  213794. int juce_fileWrite (void* handle, const void* buffer, int size)
  213795. {
  213796. if (handle != 0)
  213797. return (int) write ((int) (pointer_sized_int) handle, buffer, size);
  213798. return 0;
  213799. }
  213800. int64 juce_fileSetPosition (void* handle, int64 pos)
  213801. {
  213802. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  213803. return pos;
  213804. return -1;
  213805. }
  213806. int64 FileOutputStream::getPositionInternal() const
  213807. {
  213808. if (fileHandle != 0)
  213809. return lseek ((int) (pointer_sized_int) fileHandle, 0, SEEK_CUR);
  213810. return -1;
  213811. }
  213812. void FileOutputStream::flushInternal()
  213813. {
  213814. if (fileHandle != 0)
  213815. fsync ((int) (pointer_sized_int) fileHandle);
  213816. }
  213817. const File juce_getExecutableFile()
  213818. {
  213819. Dl_info exeInfo;
  213820. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  213821. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  213822. }
  213823. // if this file doesn't exist, find a parent of it that does..
  213824. static bool juce_doStatFS (File f, struct statfs& result)
  213825. {
  213826. for (int i = 5; --i >= 0;)
  213827. {
  213828. if (f.exists())
  213829. break;
  213830. f = f.getParentDirectory();
  213831. }
  213832. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  213833. }
  213834. int64 File::getBytesFreeOnVolume() const
  213835. {
  213836. struct statfs buf;
  213837. if (juce_doStatFS (*this, buf))
  213838. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  213839. return 0;
  213840. }
  213841. int64 File::getVolumeTotalSize() const
  213842. {
  213843. struct statfs buf;
  213844. if (juce_doStatFS (*this, buf))
  213845. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  213846. return 0;
  213847. }
  213848. const String File::getVolumeLabel() const
  213849. {
  213850. #if JUCE_MAC
  213851. struct VolAttrBuf
  213852. {
  213853. u_int32_t length;
  213854. attrreference_t mountPointRef;
  213855. char mountPointSpace [MAXPATHLEN];
  213856. } attrBuf;
  213857. struct attrlist attrList;
  213858. zerostruct (attrList);
  213859. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  213860. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  213861. File f (*this);
  213862. for (;;)
  213863. {
  213864. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  213865. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  213866. (int) attrBuf.mountPointRef.attr_length);
  213867. const File parent (f.getParentDirectory());
  213868. if (f == parent)
  213869. break;
  213870. f = parent;
  213871. }
  213872. #endif
  213873. return String::empty;
  213874. }
  213875. int File::getVolumeSerialNumber() const
  213876. {
  213877. return 0; // xxx
  213878. }
  213879. void juce_runSystemCommand (const String& command)
  213880. {
  213881. int result = system (command.toUTF8());
  213882. (void) result;
  213883. }
  213884. const String juce_getOutputFromCommand (const String& command)
  213885. {
  213886. // slight bodge here, as we just pipe the output into a temp file and read it...
  213887. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  213888. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  213889. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  213890. String result (tempFile.loadFileAsString());
  213891. tempFile.deleteFile();
  213892. return result;
  213893. }
  213894. class InterProcessLock::Pimpl
  213895. {
  213896. public:
  213897. Pimpl (const String& name, const int timeOutMillisecs)
  213898. : handle (0), refCount (1)
  213899. {
  213900. #if JUCE_MAC
  213901. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  213902. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  213903. #else
  213904. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  213905. #endif
  213906. temp.create();
  213907. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  213908. if (handle != 0)
  213909. {
  213910. struct flock fl;
  213911. zerostruct (fl);
  213912. fl.l_whence = SEEK_SET;
  213913. fl.l_type = F_WRLCK;
  213914. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  213915. for (;;)
  213916. {
  213917. const int result = fcntl (handle, F_SETLK, &fl);
  213918. if (result >= 0)
  213919. return;
  213920. if (errno != EINTR)
  213921. {
  213922. if (timeOutMillisecs == 0
  213923. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  213924. break;
  213925. Thread::sleep (10);
  213926. }
  213927. }
  213928. }
  213929. closeFile();
  213930. }
  213931. ~Pimpl()
  213932. {
  213933. closeFile();
  213934. }
  213935. void closeFile()
  213936. {
  213937. if (handle != 0)
  213938. {
  213939. struct flock fl;
  213940. zerostruct (fl);
  213941. fl.l_whence = SEEK_SET;
  213942. fl.l_type = F_UNLCK;
  213943. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  213944. {}
  213945. close (handle);
  213946. handle = 0;
  213947. }
  213948. }
  213949. int handle, refCount;
  213950. };
  213951. InterProcessLock::InterProcessLock (const String& name_)
  213952. : name (name_)
  213953. {
  213954. }
  213955. InterProcessLock::~InterProcessLock()
  213956. {
  213957. }
  213958. bool InterProcessLock::enter (const int timeOutMillisecs)
  213959. {
  213960. const ScopedLock sl (lock);
  213961. if (pimpl == 0)
  213962. {
  213963. pimpl = new Pimpl (name, timeOutMillisecs);
  213964. if (pimpl->handle == 0)
  213965. pimpl = 0;
  213966. }
  213967. else
  213968. {
  213969. pimpl->refCount++;
  213970. }
  213971. return pimpl != 0;
  213972. }
  213973. void InterProcessLock::exit()
  213974. {
  213975. const ScopedLock sl (lock);
  213976. // Trying to release the lock too many times!
  213977. jassert (pimpl != 0);
  213978. if (pimpl != 0 && --(pimpl->refCount) == 0)
  213979. pimpl = 0;
  213980. }
  213981. /*** End of inlined file: juce_posix_SharedCode.h ***/
  213982. /*** Start of inlined file: juce_linux_Files.cpp ***/
  213983. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  213984. // compiled on its own).
  213985. #if JUCE_INCLUDED_FILE
  213986. static const short U_ISOFS_SUPER_MAGIC = 0x9660; // linux/iso_fs.h
  213987. static const short U_MSDOS_SUPER_MAGIC = 0x4d44; // linux/msdos_fs.h
  213988. static const short U_NFS_SUPER_MAGIC = 0x6969; // linux/nfs_fs.h
  213989. static const short U_SMB_SUPER_MAGIC = 0x517B; // linux/smb_fs.h
  213990. bool File::copyInternal (const File& dest) const
  213991. {
  213992. FileInputStream in (*this);
  213993. if (dest.deleteFile())
  213994. {
  213995. {
  213996. FileOutputStream out (dest);
  213997. if (out.failedToOpen())
  213998. return false;
  213999. if (out.writeFromInputStream (in, -1) == getSize())
  214000. return true;
  214001. }
  214002. dest.deleteFile();
  214003. }
  214004. return false;
  214005. }
  214006. void File::findFileSystemRoots (Array<File>& destArray)
  214007. {
  214008. destArray.add (File ("/"));
  214009. }
  214010. bool File::isOnCDRomDrive() const
  214011. {
  214012. struct statfs buf;
  214013. return statfs (getFullPathName().toUTF8(), &buf) == 0
  214014. && buf.f_type == U_ISOFS_SUPER_MAGIC;
  214015. }
  214016. bool File::isOnHardDisk() const
  214017. {
  214018. struct statfs buf;
  214019. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  214020. {
  214021. switch (buf.f_type)
  214022. {
  214023. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  214024. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  214025. case U_NFS_SUPER_MAGIC: // Network NFS
  214026. case U_SMB_SUPER_MAGIC: // Network Samba
  214027. return false;
  214028. default:
  214029. // Assume anything else is a hard-disk (but note it could
  214030. // be a RAM disk. There isn't a good way of determining
  214031. // this for sure)
  214032. return true;
  214033. }
  214034. }
  214035. // Assume so if this fails for some reason
  214036. return true;
  214037. }
  214038. bool File::isOnRemovableDrive() const
  214039. {
  214040. jassertfalse // xxx not implemented for linux!
  214041. return false;
  214042. }
  214043. bool File::isHidden() const
  214044. {
  214045. return getFileName().startsWithChar ('.');
  214046. }
  214047. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  214048. const File File::getSpecialLocation (const SpecialLocationType type)
  214049. {
  214050. switch (type)
  214051. {
  214052. case userHomeDirectory:
  214053. {
  214054. const char* homeDir = getenv ("HOME");
  214055. if (homeDir == 0)
  214056. {
  214057. struct passwd* const pw = getpwuid (getuid());
  214058. if (pw != 0)
  214059. homeDir = pw->pw_dir;
  214060. }
  214061. return File (String::fromUTF8 (homeDir));
  214062. }
  214063. case userDocumentsDirectory:
  214064. case userMusicDirectory:
  214065. case userMoviesDirectory:
  214066. case userApplicationDataDirectory:
  214067. return File ("~");
  214068. case userDesktopDirectory:
  214069. return File ("~/Desktop");
  214070. case commonApplicationDataDirectory:
  214071. return File ("/var");
  214072. case globalApplicationsDirectory:
  214073. return File ("/usr");
  214074. case tempDirectory:
  214075. {
  214076. File tmp ("/var/tmp");
  214077. if (! tmp.isDirectory())
  214078. {
  214079. tmp = "/tmp";
  214080. if (! tmp.isDirectory())
  214081. tmp = File::getCurrentWorkingDirectory();
  214082. }
  214083. return tmp;
  214084. }
  214085. case invokedExecutableFile:
  214086. if (juce_Argv0 != 0)
  214087. return File (String::fromUTF8 (juce_Argv0));
  214088. // deliberate fall-through...
  214089. case currentExecutableFile:
  214090. case currentApplicationFile:
  214091. return juce_getExecutableFile();
  214092. default:
  214093. jassertfalse // unknown type?
  214094. break;
  214095. }
  214096. return File::nonexistent;
  214097. }
  214098. const String File::getVersion() const
  214099. {
  214100. return String::empty; // xxx not yet implemented
  214101. }
  214102. const File File::getLinkedTarget() const
  214103. {
  214104. char buffer [4096];
  214105. size_t numChars = readlink (getFullPathName().toUTF8(),
  214106. buffer, sizeof (buffer));
  214107. if (numChars > 0 && numChars <= sizeof (buffer))
  214108. return File (String::fromUTF8 (buffer, (int) numChars));
  214109. return *this;
  214110. }
  214111. bool File::moveToTrash() const
  214112. {
  214113. if (! exists())
  214114. return true;
  214115. File trashCan ("~/.Trash");
  214116. if (! trashCan.isDirectory())
  214117. trashCan = "~/.local/share/Trash/files";
  214118. if (! trashCan.isDirectory())
  214119. return false;
  214120. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  214121. getFileExtension()));
  214122. }
  214123. class DirectoryIterator::NativeIterator::Pimpl
  214124. {
  214125. public:
  214126. Pimpl (const File& directory, const String& wildCard_)
  214127. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  214128. wildCard (wildCard_),
  214129. dir (opendir (directory.getFullPathName().toUTF8()))
  214130. {
  214131. if (wildCard == "*.*")
  214132. wildCard = "*";
  214133. wildcardUTF8 = wildCard.toUTF8();
  214134. }
  214135. ~Pimpl()
  214136. {
  214137. if (dir != 0)
  214138. closedir (dir);
  214139. }
  214140. bool next (String& filenameFound,
  214141. bool* const isDir, bool* const isHidden, int64* const fileSize,
  214142. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  214143. {
  214144. if (dir == 0)
  214145. return false;
  214146. for (;;)
  214147. {
  214148. struct dirent* const de = readdir (dir);
  214149. if (de == 0)
  214150. return false;
  214151. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  214152. {
  214153. filenameFound = String::fromUTF8 (de->d_name);
  214154. const String path (parentDir + filenameFound);
  214155. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  214156. {
  214157. struct stat info;
  214158. const bool statOk = juce_stat (path, info);
  214159. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  214160. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  214161. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  214162. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  214163. }
  214164. if (isHidden != 0)
  214165. *isHidden = filenameFound.startsWithChar ('.');
  214166. if (isReadOnly != 0)
  214167. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  214168. return true;
  214169. }
  214170. }
  214171. }
  214172. private:
  214173. String parentDir, wildCard;
  214174. const char* wildcardUTF8;
  214175. DIR* dir;
  214176. Pimpl (const Pimpl&);
  214177. Pimpl& operator= (const Pimpl&);
  214178. };
  214179. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  214180. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  214181. {
  214182. }
  214183. DirectoryIterator::NativeIterator::~NativeIterator()
  214184. {
  214185. }
  214186. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  214187. bool* const isDir, bool* const isHidden, int64* const fileSize,
  214188. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  214189. {
  214190. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  214191. }
  214192. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  214193. {
  214194. String cmdString (fileName.replace (" ", "\\ ",false));
  214195. cmdString << " " << parameters;
  214196. if (URL::isProbablyAWebsiteURL (fileName)
  214197. || cmdString.startsWithIgnoreCase ("file:")
  214198. || URL::isProbablyAnEmailAddress (fileName))
  214199. {
  214200. // create a command that tries to launch a bunch of likely browsers
  214201. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  214202. StringArray cmdLines;
  214203. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  214204. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  214205. cmdString = cmdLines.joinIntoString (" || ");
  214206. }
  214207. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  214208. const int cpid = fork();
  214209. if (cpid == 0)
  214210. {
  214211. setsid();
  214212. // Child process
  214213. execve (argv[0], (char**) argv, environ);
  214214. exit (0);
  214215. }
  214216. return cpid >= 0;
  214217. }
  214218. void File::revealToUser() const
  214219. {
  214220. if (isDirectory())
  214221. startAsProcess();
  214222. else if (getParentDirectory().exists())
  214223. getParentDirectory().startAsProcess();
  214224. }
  214225. #endif
  214226. /*** End of inlined file: juce_linux_Files.cpp ***/
  214227. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  214228. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  214229. // compiled on its own).
  214230. #if JUCE_INCLUDED_FILE
  214231. struct NamedPipeInternal
  214232. {
  214233. String pipeInName, pipeOutName;
  214234. int pipeIn, pipeOut;
  214235. bool volatile createdPipe, blocked, stopReadOperation;
  214236. static void signalHandler (int) {}
  214237. };
  214238. void NamedPipe::cancelPendingReads()
  214239. {
  214240. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  214241. {
  214242. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  214243. intern->stopReadOperation = true;
  214244. char buffer [1] = { 0 };
  214245. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  214246. (void) bytesWritten;
  214247. int timeout = 2000;
  214248. while (intern->blocked && --timeout >= 0)
  214249. Thread::sleep (2);
  214250. intern->stopReadOperation = false;
  214251. }
  214252. }
  214253. void NamedPipe::close()
  214254. {
  214255. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  214256. if (intern != 0)
  214257. {
  214258. internal = 0;
  214259. if (intern->pipeIn != -1)
  214260. ::close (intern->pipeIn);
  214261. if (intern->pipeOut != -1)
  214262. ::close (intern->pipeOut);
  214263. if (intern->createdPipe)
  214264. {
  214265. unlink (intern->pipeInName.toUTF8());
  214266. unlink (intern->pipeOutName.toUTF8());
  214267. }
  214268. delete intern;
  214269. }
  214270. }
  214271. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  214272. {
  214273. close();
  214274. NamedPipeInternal* const intern = new NamedPipeInternal();
  214275. internal = intern;
  214276. intern->createdPipe = createPipe;
  214277. intern->blocked = false;
  214278. intern->stopReadOperation = false;
  214279. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  214280. siginterrupt (SIGPIPE, 1);
  214281. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  214282. intern->pipeInName = pipePath + "_in";
  214283. intern->pipeOutName = pipePath + "_out";
  214284. intern->pipeIn = -1;
  214285. intern->pipeOut = -1;
  214286. if (createPipe)
  214287. {
  214288. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  214289. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  214290. {
  214291. delete intern;
  214292. internal = 0;
  214293. return false;
  214294. }
  214295. }
  214296. return true;
  214297. }
  214298. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  214299. {
  214300. int bytesRead = -1;
  214301. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  214302. if (intern != 0)
  214303. {
  214304. intern->blocked = true;
  214305. if (intern->pipeIn == -1)
  214306. {
  214307. if (intern->createdPipe)
  214308. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  214309. else
  214310. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  214311. if (intern->pipeIn == -1)
  214312. {
  214313. intern->blocked = false;
  214314. return -1;
  214315. }
  214316. }
  214317. bytesRead = 0;
  214318. char* p = (char*) destBuffer;
  214319. while (bytesRead < maxBytesToRead)
  214320. {
  214321. const int bytesThisTime = maxBytesToRead - bytesRead;
  214322. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  214323. if (numRead <= 0 || intern->stopReadOperation)
  214324. {
  214325. bytesRead = -1;
  214326. break;
  214327. }
  214328. bytesRead += numRead;
  214329. p += bytesRead;
  214330. }
  214331. intern->blocked = false;
  214332. }
  214333. return bytesRead;
  214334. }
  214335. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  214336. {
  214337. int bytesWritten = -1;
  214338. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  214339. if (intern != 0)
  214340. {
  214341. if (intern->pipeOut == -1)
  214342. {
  214343. if (intern->createdPipe)
  214344. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  214345. else
  214346. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  214347. if (intern->pipeOut == -1)
  214348. {
  214349. return -1;
  214350. }
  214351. }
  214352. const char* p = (const char*) sourceBuffer;
  214353. bytesWritten = 0;
  214354. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  214355. while (bytesWritten < numBytesToWrite
  214356. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  214357. {
  214358. const int bytesThisTime = numBytesToWrite - bytesWritten;
  214359. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  214360. if (numWritten <= 0)
  214361. {
  214362. bytesWritten = -1;
  214363. break;
  214364. }
  214365. bytesWritten += numWritten;
  214366. p += bytesWritten;
  214367. }
  214368. }
  214369. return bytesWritten;
  214370. }
  214371. #endif
  214372. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  214373. /*** Start of inlined file: juce_linux_Network.cpp ***/
  214374. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  214375. // compiled on its own).
  214376. #if JUCE_INCLUDED_FILE
  214377. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  214378. {
  214379. int numResults = 0;
  214380. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  214381. if (s != -1)
  214382. {
  214383. char buf [1024];
  214384. struct ifconf ifc;
  214385. ifc.ifc_len = sizeof (buf);
  214386. ifc.ifc_buf = buf;
  214387. ioctl (s, SIOCGIFCONF, &ifc);
  214388. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  214389. {
  214390. struct ifreq ifr;
  214391. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  214392. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  214393. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  214394. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  214395. && numResults < maxNum)
  214396. {
  214397. int64 a = 0;
  214398. for (int j = 6; --j >= 0;)
  214399. a = (a << 8) | (uint8) ifr.ifr_hwaddr.sa_data [littleEndian ? j : (5 - j)];
  214400. *addresses++ = a;
  214401. ++numResults;
  214402. }
  214403. }
  214404. close (s);
  214405. }
  214406. return numResults;
  214407. }
  214408. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  214409. const String& emailSubject,
  214410. const String& bodyText,
  214411. const StringArray& filesToAttach)
  214412. {
  214413. jassertfalse // xxx todo
  214414. return false;
  214415. }
  214416. /** A HTTP input stream that uses sockets.
  214417. */
  214418. class JUCE_HTTPSocketStream
  214419. {
  214420. public:
  214421. JUCE_HTTPSocketStream()
  214422. : readPosition (0),
  214423. socketHandle (-1),
  214424. levelsOfRedirection (0),
  214425. timeoutSeconds (15)
  214426. {
  214427. }
  214428. ~JUCE_HTTPSocketStream()
  214429. {
  214430. closeSocket();
  214431. }
  214432. bool open (const String& url,
  214433. const String& headers,
  214434. const MemoryBlock& postData,
  214435. const bool isPost,
  214436. URL::OpenStreamProgressCallback* callback,
  214437. void* callbackContext,
  214438. int timeOutMs)
  214439. {
  214440. closeSocket();
  214441. uint32 timeOutTime = Time::getMillisecondCounter();
  214442. if (timeOutMs == 0)
  214443. timeOutTime += 60000;
  214444. else if (timeOutMs < 0)
  214445. timeOutTime = 0xffffffff;
  214446. else
  214447. timeOutTime += timeOutMs;
  214448. String hostName, hostPath;
  214449. int hostPort;
  214450. if (! decomposeURL (url, hostName, hostPath, hostPort))
  214451. return false;
  214452. const struct hostent* host = 0;
  214453. int port = 0;
  214454. String proxyName, proxyPath;
  214455. int proxyPort = 0;
  214456. String proxyURL (getenv ("http_proxy"));
  214457. if (proxyURL.startsWithIgnoreCase ("http://"))
  214458. {
  214459. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  214460. return false;
  214461. host = gethostbyname (proxyName.toUTF8());
  214462. port = proxyPort;
  214463. }
  214464. else
  214465. {
  214466. host = gethostbyname (hostName.toUTF8());
  214467. port = hostPort;
  214468. }
  214469. if (host == 0)
  214470. return false;
  214471. struct sockaddr_in address;
  214472. zerostruct (address);
  214473. memcpy (&address.sin_addr, host->h_addr, host->h_length);
  214474. address.sin_family = host->h_addrtype;
  214475. address.sin_port = htons (port);
  214476. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  214477. if (socketHandle == -1)
  214478. return false;
  214479. int receiveBufferSize = 16384;
  214480. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  214481. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  214482. #if JUCE_MAC
  214483. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  214484. #endif
  214485. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  214486. {
  214487. closeSocket();
  214488. return false;
  214489. }
  214490. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  214491. proxyName, proxyPort,
  214492. hostPath, url,
  214493. headers, postData,
  214494. isPost));
  214495. size_t totalHeaderSent = 0;
  214496. while (totalHeaderSent < requestHeader.getSize())
  214497. {
  214498. if (Time::getMillisecondCounter() > timeOutTime)
  214499. {
  214500. closeSocket();
  214501. return false;
  214502. }
  214503. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  214504. if (send (socketHandle,
  214505. ((const char*) requestHeader.getData()) + totalHeaderSent,
  214506. numToSend, 0)
  214507. != numToSend)
  214508. {
  214509. closeSocket();
  214510. return false;
  214511. }
  214512. totalHeaderSent += numToSend;
  214513. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  214514. {
  214515. closeSocket();
  214516. return false;
  214517. }
  214518. }
  214519. const String responseHeader (readResponse (timeOutTime));
  214520. if (responseHeader.isNotEmpty())
  214521. {
  214522. //DBG (responseHeader);
  214523. StringArray lines;
  214524. lines.addLines (responseHeader);
  214525. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  214526. .substring (0, 3).getIntValue();
  214527. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  214528. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  214529. String location (findHeaderItem (lines, "Location:"));
  214530. if (statusCode >= 300 && statusCode < 400
  214531. && location.isNotEmpty())
  214532. {
  214533. if (! location.startsWithIgnoreCase ("http://"))
  214534. location = "http://" + location;
  214535. if (levelsOfRedirection++ < 3)
  214536. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  214537. }
  214538. else
  214539. {
  214540. levelsOfRedirection = 0;
  214541. return true;
  214542. }
  214543. }
  214544. closeSocket();
  214545. return false;
  214546. }
  214547. int read (void* buffer, int bytesToRead)
  214548. {
  214549. fd_set readbits;
  214550. FD_ZERO (&readbits);
  214551. FD_SET (socketHandle, &readbits);
  214552. struct timeval tv;
  214553. tv.tv_sec = timeoutSeconds;
  214554. tv.tv_usec = 0;
  214555. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  214556. return 0; // (timeout)
  214557. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  214558. readPosition += bytesRead;
  214559. return bytesRead;
  214560. }
  214561. int readPosition;
  214562. juce_UseDebuggingNewOperator
  214563. private:
  214564. int socketHandle, levelsOfRedirection;
  214565. const int timeoutSeconds;
  214566. void closeSocket()
  214567. {
  214568. if (socketHandle >= 0)
  214569. close (socketHandle);
  214570. socketHandle = -1;
  214571. }
  214572. const MemoryBlock createRequestHeader (const String& hostName,
  214573. const int hostPort,
  214574. const String& proxyName,
  214575. const int proxyPort,
  214576. const String& hostPath,
  214577. const String& originalURL,
  214578. const String& headers,
  214579. const MemoryBlock& postData,
  214580. const bool isPost)
  214581. {
  214582. String header (isPost ? "POST " : "GET ");
  214583. if (proxyName.isEmpty())
  214584. {
  214585. header << hostPath << " HTTP/1.0\r\nHost: "
  214586. << hostName << ':' << hostPort;
  214587. }
  214588. else
  214589. {
  214590. header << originalURL << " HTTP/1.0\r\nHost: "
  214591. << proxyName << ':' << proxyPort;
  214592. }
  214593. header << "\r\nUser-Agent: JUCE/"
  214594. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  214595. << "\r\nConnection: Close\r\nContent-Length: "
  214596. << postData.getSize() << "\r\n"
  214597. << headers << "\r\n";
  214598. MemoryBlock mb;
  214599. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  214600. mb.append (postData.getData(), postData.getSize());
  214601. return mb;
  214602. }
  214603. const String readResponse (const uint32 timeOutTime)
  214604. {
  214605. int bytesRead = 0, numConsecutiveLFs = 0;
  214606. MemoryBlock buffer (1024, true);
  214607. while (numConsecutiveLFs < 2 && bytesRead < 32768
  214608. && Time::getMillisecondCounter() <= timeOutTime)
  214609. {
  214610. fd_set readbits;
  214611. FD_ZERO (&readbits);
  214612. FD_SET (socketHandle, &readbits);
  214613. struct timeval tv;
  214614. tv.tv_sec = timeoutSeconds;
  214615. tv.tv_usec = 0;
  214616. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  214617. return String::empty; // (timeout)
  214618. buffer.ensureSize (bytesRead + 8, true);
  214619. char* const dest = (char*) buffer.getData() + bytesRead;
  214620. if (recv (socketHandle, dest, 1, 0) == -1)
  214621. return String::empty;
  214622. const char lastByte = *dest;
  214623. ++bytesRead;
  214624. if (lastByte == '\n')
  214625. ++numConsecutiveLFs;
  214626. else if (lastByte != '\r')
  214627. numConsecutiveLFs = 0;
  214628. }
  214629. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  214630. if (header.startsWithIgnoreCase ("HTTP/"))
  214631. return header.trimEnd();
  214632. return String::empty;
  214633. }
  214634. static bool decomposeURL (const String& url,
  214635. String& host, String& path, int& port)
  214636. {
  214637. if (! url.startsWithIgnoreCase ("http://"))
  214638. return false;
  214639. const int nextSlash = url.indexOfChar (7, '/');
  214640. int nextColon = url.indexOfChar (7, ':');
  214641. if (nextColon > nextSlash && nextSlash > 0)
  214642. nextColon = -1;
  214643. if (nextColon >= 0)
  214644. {
  214645. host = url.substring (7, nextColon);
  214646. if (nextSlash >= 0)
  214647. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  214648. else
  214649. port = url.substring (nextColon + 1).getIntValue();
  214650. }
  214651. else
  214652. {
  214653. port = 80;
  214654. if (nextSlash >= 0)
  214655. host = url.substring (7, nextSlash);
  214656. else
  214657. host = url.substring (7);
  214658. }
  214659. if (nextSlash >= 0)
  214660. path = url.substring (nextSlash);
  214661. else
  214662. path = "/";
  214663. return true;
  214664. }
  214665. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  214666. {
  214667. for (int i = 0; i < lines.size(); ++i)
  214668. if (lines[i].startsWithIgnoreCase (itemName))
  214669. return lines[i].substring (itemName.length()).trim();
  214670. return String::empty;
  214671. }
  214672. };
  214673. void* juce_openInternetFile (const String& url,
  214674. const String& headers,
  214675. const MemoryBlock& postData,
  214676. const bool isPost,
  214677. URL::OpenStreamProgressCallback* callback,
  214678. void* callbackContext,
  214679. int timeOutMs)
  214680. {
  214681. JUCE_HTTPSocketStream* const s = new JUCE_HTTPSocketStream();
  214682. if (s->open (url, headers, postData, isPost,
  214683. callback, callbackContext, timeOutMs))
  214684. return s;
  214685. delete s;
  214686. return 0;
  214687. }
  214688. void juce_closeInternetFile (void* handle)
  214689. {
  214690. delete static_cast <JUCE_HTTPSocketStream*> (handle);
  214691. }
  214692. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  214693. {
  214694. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  214695. if (s != 0)
  214696. return s->read (buffer, bytesToRead);
  214697. return 0;
  214698. }
  214699. int64 juce_getInternetFileContentLength (void* handle)
  214700. {
  214701. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  214702. if (s != 0)
  214703. {
  214704. //xxx todo
  214705. jassertfalse
  214706. }
  214707. return -1;
  214708. }
  214709. int juce_seekInInternetFile (void* handle, int newPosition)
  214710. {
  214711. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  214712. if (s != 0)
  214713. return s->readPosition;
  214714. return 0;
  214715. }
  214716. #endif
  214717. /*** End of inlined file: juce_linux_Network.cpp ***/
  214718. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  214719. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  214720. // compiled on its own).
  214721. #if JUCE_INCLUDED_FILE
  214722. void Logger::outputDebugString (const String& text)
  214723. {
  214724. std::cerr << text << std::endl;
  214725. }
  214726. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  214727. {
  214728. return Linux;
  214729. }
  214730. const String SystemStats::getOperatingSystemName()
  214731. {
  214732. return "Linux";
  214733. }
  214734. bool SystemStats::isOperatingSystem64Bit()
  214735. {
  214736. #if JUCE_64BIT
  214737. return true;
  214738. #else
  214739. //xxx not sure how to find this out?..
  214740. return false;
  214741. #endif
  214742. }
  214743. static const String juce_getCpuInfo (const char* const key)
  214744. {
  214745. StringArray lines;
  214746. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  214747. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  214748. if (lines[i].startsWithIgnoreCase (key))
  214749. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  214750. return String::empty;
  214751. }
  214752. bool SystemStats::hasMMX() { return juce_getCpuInfo ("flags").contains ("mmx"); }
  214753. bool SystemStats::hasSSE() { return juce_getCpuInfo ("flags").contains ("sse"); }
  214754. bool SystemStats::hasSSE2() { return juce_getCpuInfo ("flags").contains ("sse2"); }
  214755. bool SystemStats::has3DNow() { return juce_getCpuInfo ("flags").contains ("3dnow"); }
  214756. const String SystemStats::getCpuVendor()
  214757. {
  214758. return juce_getCpuInfo ("vendor_id");
  214759. }
  214760. int SystemStats::getCpuSpeedInMegaherz()
  214761. {
  214762. return roundToInt (juce_getCpuInfo ("cpu MHz").getFloatValue());
  214763. }
  214764. int SystemStats::getMemorySizeInMegabytes()
  214765. {
  214766. struct sysinfo sysi;
  214767. if (sysinfo (&sysi) == 0)
  214768. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  214769. return 0;
  214770. }
  214771. int SystemStats::getPageSize()
  214772. {
  214773. return sysconf (_SC_PAGESIZE);
  214774. }
  214775. int SystemStats::getNumCpus()
  214776. {
  214777. return juce_getCpuInfo ("processor").getIntValue() + 1;
  214778. }
  214779. const String SystemStats::getLogonName()
  214780. {
  214781. const char* user = getenv ("USER");
  214782. if (user == 0)
  214783. {
  214784. struct passwd* const pw = getpwuid (getuid());
  214785. if (pw != 0)
  214786. user = pw->pw_name;
  214787. }
  214788. return String::fromUTF8 (user);
  214789. }
  214790. const String SystemStats::getFullUserName()
  214791. {
  214792. return getLogonName();
  214793. }
  214794. void SystemStats::initialiseStats()
  214795. {
  214796. }
  214797. void PlatformUtilities::fpuReset()
  214798. {
  214799. }
  214800. uint32 juce_millisecondsSinceStartup() throw()
  214801. {
  214802. static unsigned int calibrate = 0;
  214803. static bool calibrated = false;
  214804. timeval t;
  214805. unsigned int ret = 0;
  214806. if (! gettimeofday (&t, 0))
  214807. {
  214808. if (! calibrated)
  214809. {
  214810. struct sysinfo sysi;
  214811. if (sysinfo (&sysi) == 0)
  214812. // Safe to assume system was not brought up earlier than 1970!
  214813. calibrate = t.tv_sec - sysi.uptime;
  214814. calibrated = true;
  214815. }
  214816. ret = 1000 * (t.tv_sec - calibrate) + (t.tv_usec / 1000);
  214817. }
  214818. return ret;
  214819. }
  214820. double Time::getMillisecondCounterHiRes() throw()
  214821. {
  214822. return getHighResolutionTicks() * 0.001;
  214823. }
  214824. int64 Time::getHighResolutionTicks() throw()
  214825. {
  214826. timeval t;
  214827. if (gettimeofday (&t, 0))
  214828. return 0;
  214829. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  214830. }
  214831. int64 Time::getHighResolutionTicksPerSecond() throw()
  214832. {
  214833. return 1000000; // (microseconds)
  214834. }
  214835. bool Time::setSystemTimeToThisTime() const
  214836. {
  214837. timeval t;
  214838. t.tv_sec = millisSinceEpoch % 1000000;
  214839. t.tv_usec = millisSinceEpoch - t.tv_sec;
  214840. return settimeofday (&t, 0) ? false : true;
  214841. }
  214842. #endif
  214843. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  214844. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  214845. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  214846. // compiled on its own).
  214847. #if JUCE_INCLUDED_FILE
  214848. /*
  214849. Note that a lot of methods that you'd expect to find in this file actually
  214850. live in juce_posix_SharedCode.h!
  214851. */
  214852. void JUCE_API juce_threadEntryPoint (void*);
  214853. void* threadEntryProc (void* value)
  214854. {
  214855. juce_threadEntryPoint (value);
  214856. return 0;
  214857. }
  214858. void* juce_createThread (void* userData)
  214859. {
  214860. pthread_t handle = 0;
  214861. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  214862. {
  214863. pthread_detach (handle);
  214864. return (void*) handle;
  214865. }
  214866. return 0;
  214867. }
  214868. void juce_killThread (void* handle)
  214869. {
  214870. if (handle != 0)
  214871. pthread_cancel ((pthread_t) handle);
  214872. }
  214873. void juce_setCurrentThreadName (const String& /*name*/)
  214874. {
  214875. }
  214876. Thread::ThreadID Thread::getCurrentThreadId()
  214877. {
  214878. return (ThreadID) pthread_self();
  214879. }
  214880. /* This is all a bit non-ideal... the trouble is that on Linux you
  214881. need to call setpriority to affect the dynamic priority for
  214882. non-realtime processes, but this requires the pid, which is not
  214883. accessible from the pthread_t. We could get it by calling getpid
  214884. once each thread has started, but then we would need a list of
  214885. running threads etc etc.
  214886. Also there is no such thing as IDLE priority on Linux.
  214887. For the moment, map idle, low and normal process priorities to
  214888. SCHED_OTHER, with the thread priority ignored for these classes.
  214889. Map high priority processes to the lower half of the SCHED_RR
  214890. range, and realtime to the upper half.
  214891. priority 1 to 10 where 5=normal, 1=low. If the handle is 0, sets the
  214892. priority of the current thread
  214893. */
  214894. bool juce_setThreadPriority (void* handle, int priority)
  214895. {
  214896. struct sched_param param;
  214897. int policy;
  214898. if (handle == 0)
  214899. handle = (void*) pthread_self();
  214900. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) == 0
  214901. && policy != SCHED_OTHER)
  214902. {
  214903. int minp = sched_get_priority_min (policy);
  214904. int maxp = sched_get_priority_max (policy);
  214905. int pri = ((maxp - minp) / 2) * (priority - 1) / 9;
  214906. if (param.__sched_priority >= (minp + (maxp - minp) / 2))
  214907. param.__sched_priority = minp + ((maxp - minp) / 2) + pri; // (realtime)
  214908. else
  214909. param.__sched_priority = minp + pri; // (high)
  214910. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  214911. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  214912. }
  214913. return false;
  214914. }
  214915. /* Remove this macro if you're having problems compiling the cpu affinity
  214916. calls (the API for these has changed about quite a bit in various Linux
  214917. versions, and a lot of distros seem to ship with obsolete versions)
  214918. */
  214919. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  214920. #define SUPPORT_AFFINITIES 1
  214921. #endif
  214922. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  214923. {
  214924. #if SUPPORT_AFFINITIES
  214925. cpu_set_t affinity;
  214926. CPU_ZERO (&affinity);
  214927. for (int i = 0; i < 32; ++i)
  214928. if ((affinityMask & (1 << i)) != 0)
  214929. CPU_SET (i, &affinity);
  214930. /*
  214931. N.B. If this line causes a compile error, then you've probably not got the latest
  214932. version of glibc installed.
  214933. If you don't want to update your copy of glibc and don't care about cpu affinities,
  214934. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  214935. */
  214936. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  214937. sched_yield();
  214938. #else
  214939. /* affinities aren't supported because either the appropriate header files weren't found,
  214940. or the SUPPORT_AFFINITIES macro was turned off
  214941. */
  214942. jassertfalse
  214943. #endif
  214944. }
  214945. void Thread::yield()
  214946. {
  214947. sched_yield();
  214948. }
  214949. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  214950. void Process::setPriority (ProcessPriority prior)
  214951. {
  214952. struct sched_param param;
  214953. int policy, maxp, minp;
  214954. const int p = (int) prior;
  214955. if (p <= 1)
  214956. policy = SCHED_OTHER;
  214957. else
  214958. policy = SCHED_RR;
  214959. minp = sched_get_priority_min (policy);
  214960. maxp = sched_get_priority_max (policy);
  214961. if (p < 2)
  214962. param.__sched_priority = 0;
  214963. else if (p == 2 )
  214964. // Set to middle of lower realtime priority range
  214965. param.__sched_priority = minp + (maxp - minp) / 4;
  214966. else
  214967. // Set to middle of higher realtime priority range
  214968. param.__sched_priority = minp + (3 * (maxp - minp) / 4);
  214969. pthread_setschedparam (pthread_self(), policy, &param);
  214970. }
  214971. void Process::terminate()
  214972. {
  214973. exit (0);
  214974. }
  214975. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  214976. {
  214977. static char testResult = 0;
  214978. if (testResult == 0)
  214979. {
  214980. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  214981. if (testResult >= 0)
  214982. {
  214983. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  214984. testResult = 1;
  214985. }
  214986. }
  214987. return testResult < 0;
  214988. }
  214989. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  214990. {
  214991. return juce_isRunningUnderDebugger();
  214992. }
  214993. void Process::raisePrivilege()
  214994. {
  214995. // If running suid root, change effective user
  214996. // to root
  214997. if (geteuid() != 0 && getuid() == 0)
  214998. {
  214999. setreuid (geteuid(), getuid());
  215000. setregid (getegid(), getgid());
  215001. }
  215002. }
  215003. void Process::lowerPrivilege()
  215004. {
  215005. // If runing suid root, change effective user
  215006. // back to real user
  215007. if (geteuid() == 0 && getuid() != 0)
  215008. {
  215009. setreuid (geteuid(), getuid());
  215010. setregid (getegid(), getgid());
  215011. }
  215012. }
  215013. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  215014. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  215015. {
  215016. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  215017. }
  215018. void PlatformUtilities::freeDynamicLibrary (void* handle)
  215019. {
  215020. dlclose(handle);
  215021. }
  215022. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  215023. {
  215024. return dlsym (libraryHandle, procedureName.toCString());
  215025. }
  215026. #endif
  215027. #endif
  215028. /*** End of inlined file: juce_linux_Threads.cpp ***/
  215029. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  215030. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  215031. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  215032. // compiled on its own).
  215033. #if JUCE_INCLUDED_FILE
  215034. #if JUCE_DEBUG
  215035. #define JUCE_DEBUG_XERRORS 1
  215036. #endif
  215037. extern Display* display;
  215038. extern Window juce_messageWindowHandle;
  215039. namespace ClipboardHelpers
  215040. {
  215041. static String localClipboardContent;
  215042. static Atom atom_UTF8_STRING;
  215043. static Atom atom_CLIPBOARD;
  215044. static Atom atom_TARGETS;
  215045. static void initSelectionAtoms()
  215046. {
  215047. static bool isInitialised = false;
  215048. if (! isInitialised)
  215049. {
  215050. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  215051. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  215052. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  215053. }
  215054. }
  215055. // Read the content of a window property as either a locale-dependent string or an utf8 string
  215056. // works only for strings shorter than 1000000 bytes
  215057. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  215058. {
  215059. String returnData;
  215060. char* clipData;
  215061. Atom actualType;
  215062. int actualFormat;
  215063. unsigned long numItems, bytesLeft;
  215064. if (XGetWindowProperty (display, window, prop,
  215065. 0L /* offset */, 1000000 /* length (max) */, False,
  215066. AnyPropertyType /* format */,
  215067. &actualType, &actualFormat, &numItems, &bytesLeft,
  215068. (unsigned char**) &clipData) == Success)
  215069. {
  215070. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  215071. returnData = String::fromUTF8 (clipData, numItems);
  215072. else if (actualType == XA_STRING && actualFormat == 8)
  215073. returnData = String (clipData, numItems);
  215074. if (clipData != 0)
  215075. XFree (clipData);
  215076. jassert (bytesLeft == 0 || numItems == 1000000);
  215077. }
  215078. XDeleteProperty (display, window, prop);
  215079. return returnData;
  215080. }
  215081. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  215082. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  215083. {
  215084. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  215085. // The selection owner will be asked to set the JUCE_SEL property on the
  215086. // juce_messageWindowHandle with the selection content
  215087. XConvertSelection (display, selection, requestedFormat, property_name,
  215088. juce_messageWindowHandle, CurrentTime);
  215089. int count = 50; // will wait at most for 200 ms
  215090. while (--count >= 0)
  215091. {
  215092. XEvent event;
  215093. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  215094. {
  215095. if (event.xselection.property == property_name)
  215096. {
  215097. jassert (event.xselection.requestor == juce_messageWindowHandle);
  215098. selectionContent = readWindowProperty (event.xselection.requestor,
  215099. event.xselection.property,
  215100. requestedFormat);
  215101. return true;
  215102. }
  215103. else
  215104. {
  215105. return false; // the format we asked for was denied.. (event.xselection.property == None)
  215106. }
  215107. }
  215108. // not very elegant.. we could do a select() or something like that...
  215109. // however clipboard content requesting is inherently slow on x11, it
  215110. // often takes 50ms or more so...
  215111. Thread::sleep (4);
  215112. }
  215113. return false;
  215114. }
  215115. }
  215116. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  215117. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  215118. {
  215119. ClipboardHelpers::initSelectionAtoms();
  215120. // the selection content is sent to the target window as a window property
  215121. XSelectionEvent reply;
  215122. reply.type = SelectionNotify;
  215123. reply.display = evt.display;
  215124. reply.requestor = evt.requestor;
  215125. reply.selection = evt.selection;
  215126. reply.target = evt.target;
  215127. reply.property = None; // == "fail"
  215128. reply.time = evt.time;
  215129. HeapBlock <char> data;
  215130. int propertyFormat = 0, numDataItems = 0;
  215131. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  215132. {
  215133. if (evt.target == XA_STRING)
  215134. {
  215135. // format data according to system locale
  215136. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  215137. data.calloc (numDataItems + 1);
  215138. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  215139. propertyFormat = 8; // bits/item
  215140. }
  215141. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  215142. {
  215143. // translate to utf8
  215144. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  215145. data.calloc (numDataItems + 1);
  215146. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  215147. propertyFormat = 8; // bits/item
  215148. }
  215149. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  215150. {
  215151. // another application wants to know what we are able to send
  215152. numDataItems = 2;
  215153. propertyFormat = 32; // atoms are 32-bit
  215154. data.calloc (numDataItems * 4);
  215155. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  215156. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  215157. atoms[1] = XA_STRING;
  215158. }
  215159. }
  215160. else
  215161. {
  215162. DBG ("requested unsupported clipboard");
  215163. }
  215164. if (data != 0)
  215165. {
  215166. const int maxReasonableSelectionSize = 1000000;
  215167. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  215168. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  215169. {
  215170. XChangeProperty (evt.display, evt.requestor,
  215171. evt.property, evt.target,
  215172. propertyFormat /* 8 or 32 */, PropModeReplace,
  215173. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  215174. reply.property = evt.property; // " == success"
  215175. }
  215176. }
  215177. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  215178. }
  215179. void SystemClipboard::copyTextToClipboard (const String& clipText)
  215180. {
  215181. ClipboardHelpers::initSelectionAtoms();
  215182. ClipboardHelpers::localClipboardContent = clipText;
  215183. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  215184. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  215185. }
  215186. const String SystemClipboard::getTextFromClipboard()
  215187. {
  215188. ClipboardHelpers::initSelectionAtoms();
  215189. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  215190. level" clipboard that is supposed to be filled by ctrl-C
  215191. etc). When a clipboard manager is running, the content of this
  215192. selection is preserved even when the original selection owner
  215193. exits.
  215194. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  215195. filled by good old x11 apps such as xterm)
  215196. */
  215197. String content;
  215198. Atom selection = XA_PRIMARY;
  215199. Window selectionOwner = None;
  215200. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  215201. {
  215202. selection = ClipboardHelpers::atom_CLIPBOARD;
  215203. selectionOwner = XGetSelectionOwner (display, selection);
  215204. }
  215205. if (selectionOwner != None)
  215206. {
  215207. if (selectionOwner == juce_messageWindowHandle)
  215208. {
  215209. content = ClipboardHelpers::localClipboardContent;
  215210. }
  215211. else
  215212. {
  215213. // first try: we want an utf8 string
  215214. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  215215. if (! ok)
  215216. {
  215217. // second chance, ask for a good old locale-dependent string ..
  215218. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  215219. }
  215220. }
  215221. }
  215222. return content;
  215223. }
  215224. #endif
  215225. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  215226. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  215227. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  215228. // compiled on its own).
  215229. #if JUCE_INCLUDED_FILE
  215230. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  215231. #define JUCE_DEBUG_XERRORS 1
  215232. #endif
  215233. Display* display = 0;
  215234. Window juce_messageWindowHandle = None;
  215235. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  215236. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  215237. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  215238. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  215239. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  215240. class InternalMessageQueue
  215241. {
  215242. public:
  215243. InternalMessageQueue()
  215244. : bytesInSocket (0)
  215245. {
  215246. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  215247. (void) ret; jassert (ret == 0);
  215248. //setNonBlocking (fd[0]);
  215249. //setNonBlocking (fd[1]);
  215250. }
  215251. ~InternalMessageQueue()
  215252. {
  215253. close (fd[0]);
  215254. close (fd[1]);
  215255. }
  215256. void postMessage (Message* msg)
  215257. {
  215258. const int maxBytesInSocketQueue = 128;
  215259. ScopedLock sl (lock);
  215260. queue.add (msg);
  215261. if (bytesInSocket < maxBytesInSocketQueue)
  215262. {
  215263. ++bytesInSocket;
  215264. ScopedUnlock ul (lock);
  215265. const unsigned char x = 0xff;
  215266. size_t bytesWritten = write (fd[0], &x, 1);
  215267. (void) bytesWritten;
  215268. }
  215269. }
  215270. bool isEmpty() const
  215271. {
  215272. ScopedLock sl (lock);
  215273. return queue.size() == 0;
  215274. }
  215275. Message* popNextMessage()
  215276. {
  215277. ScopedLock sl (lock);
  215278. if (bytesInSocket > 0)
  215279. {
  215280. --bytesInSocket;
  215281. ScopedUnlock ul (lock);
  215282. unsigned char x;
  215283. size_t numBytes = read (fd[1], &x, 1);
  215284. (void) numBytes;
  215285. }
  215286. Message* m = queue[0];
  215287. queue.remove (0, false /* deleteObject */);
  215288. return m;
  215289. }
  215290. int getWaitHandle() const { return fd[1]; }
  215291. private:
  215292. CriticalSection lock;
  215293. OwnedArray <Message> queue;
  215294. int fd[2];
  215295. int bytesInSocket;
  215296. static bool setNonBlocking (int handle)
  215297. {
  215298. int socketFlags = fcntl (handle, F_GETFL, 0);
  215299. if (socketFlags == -1)
  215300. return false;
  215301. socketFlags |= O_NONBLOCK;
  215302. return fcntl (handle, F_SETFL, socketFlags) == 0;
  215303. }
  215304. };
  215305. struct MessageThreadFuncCall
  215306. {
  215307. enum { uniqueID = 0x73774623 };
  215308. MessageCallbackFunction* func;
  215309. void* parameter;
  215310. void* result;
  215311. CriticalSection lock;
  215312. WaitableEvent event;
  215313. };
  215314. static InternalMessageQueue* juce_internalMessageQueue = 0;
  215315. // error handling in X11
  215316. static bool errorOccurred = false;
  215317. static bool keyboardBreakOccurred = false;
  215318. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  215319. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  215320. // Usually happens when client-server connection is broken
  215321. static int ioErrorHandler (Display* display)
  215322. {
  215323. DBG ("ERROR: connection to X server broken.. terminating.");
  215324. errorOccurred = true;
  215325. if (JUCEApplication::getInstance() != 0)
  215326. Process::terminate();
  215327. return 0;
  215328. }
  215329. // A protocol error has occurred
  215330. static int errorHandler (Display* display, XErrorEvent* event)
  215331. {
  215332. #if JUCE_DEBUG_XERRORS
  215333. char errorStr[64] = { 0 };
  215334. char requestStr[64] = { 0 };
  215335. XGetErrorText (display, event->error_code, errorStr, 64);
  215336. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(),
  215337. "Unknown", requestStr, 64);
  215338. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  215339. #endif
  215340. return 0;
  215341. }
  215342. // Breakin from keyboard
  215343. static void signalHandler (int sig)
  215344. {
  215345. if (sig == SIGINT)
  215346. {
  215347. keyboardBreakOccurred = true;
  215348. return;
  215349. }
  215350. static bool reentrant = false;
  215351. if (! reentrant)
  215352. {
  215353. reentrant = true;
  215354. // Illegal instruction
  215355. fflush (stdout);
  215356. Logger::outputDebugString ("ERROR: Program executed illegal instruction.. terminating");
  215357. errorOccurred = true;
  215358. if (JUCEApplication::getInstance() != 0)
  215359. Process::terminate();
  215360. }
  215361. else
  215362. {
  215363. if (JUCEApplication::getInstance() != 0)
  215364. exit(0);
  215365. }
  215366. }
  215367. void MessageManager::doPlatformSpecificInitialisation()
  215368. {
  215369. // Initialise xlib for multiple thread support
  215370. static bool initThreadCalled = false;
  215371. if (! initThreadCalled)
  215372. {
  215373. if (! XInitThreads())
  215374. {
  215375. // This is fatal! Print error and closedown
  215376. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  215377. if (JUCEApplication::getInstance() != 0)
  215378. Process::terminate();
  215379. return;
  215380. }
  215381. initThreadCalled = true;
  215382. }
  215383. // This is called if the client/server connection is broken
  215384. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  215385. // This is called if a protocol error occurs
  215386. oldErrorHandler = XSetErrorHandler (errorHandler);
  215387. // Install signal handler for break-in
  215388. struct sigaction saction;
  215389. sigset_t maskSet;
  215390. sigemptyset (&maskSet);
  215391. saction.sa_handler = signalHandler;
  215392. saction.sa_mask = maskSet;
  215393. saction.sa_flags = 0;
  215394. sigaction (SIGINT, &saction, 0);
  215395. #ifndef _DEBUG
  215396. // Setup signal handlers for various fatal errors
  215397. sigaction (SIGILL, &saction, 0);
  215398. sigaction (SIGBUS, &saction, 0);
  215399. sigaction (SIGFPE, &saction, 0);
  215400. sigaction (SIGSEGV, &saction, 0);
  215401. sigaction (SIGSYS, &saction, 0);
  215402. #endif
  215403. // Create the internal message queue
  215404. juce_internalMessageQueue = new InternalMessageQueue();
  215405. // Try to connect to a display
  215406. String displayName (getenv ("DISPLAY"));
  215407. if (displayName.isEmpty())
  215408. displayName = ":0.0";
  215409. display = XOpenDisplay (displayName.toCString());
  215410. if (display == 0)
  215411. {
  215412. // This is not fatal! we can run headless.
  215413. return;
  215414. }
  215415. // Get defaults for various properties
  215416. int screen = DefaultScreen (display);
  215417. Window root = RootWindow (display, screen);
  215418. Visual* visual = DefaultVisual (display, screen);
  215419. // Create a context to store user data associated with Windows we
  215420. // create in WindowDriver
  215421. windowHandleXContext = XUniqueContext();
  215422. // We're only interested in client messages for this window
  215423. // which are always sent
  215424. XSetWindowAttributes swa;
  215425. swa.event_mask = NoEventMask;
  215426. // Create our message window (this will never be mapped)
  215427. juce_messageWindowHandle = XCreateWindow (display, root,
  215428. 0, 0, 1, 1, 0, 0, InputOnly,
  215429. visual, CWEventMask, &swa);
  215430. }
  215431. void MessageManager::doPlatformSpecificShutdown()
  215432. {
  215433. deleteAndZero (juce_internalMessageQueue);
  215434. if (display != 0 && ! errorOccurred)
  215435. {
  215436. XDestroyWindow (display, juce_messageWindowHandle);
  215437. XCloseDisplay (display);
  215438. // reset pointers
  215439. juce_messageWindowHandle = 0;
  215440. display = 0;
  215441. // Restore original error handlers
  215442. XSetIOErrorHandler (oldIOErrorHandler);
  215443. oldIOErrorHandler = 0;
  215444. XSetErrorHandler (oldErrorHandler);
  215445. oldErrorHandler = 0;
  215446. }
  215447. }
  215448. bool juce_postMessageToSystemQueue (void* message)
  215449. {
  215450. if (errorOccurred)
  215451. return false;
  215452. juce_internalMessageQueue->postMessage ((Message*) message);
  215453. return true;
  215454. }
  215455. void MessageManager::broadcastMessage (const String& value) throw()
  215456. {
  215457. /* TODO */
  215458. }
  215459. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func,
  215460. void* parameter)
  215461. {
  215462. if (errorOccurred)
  215463. return 0;
  215464. if (! isThisTheMessageThread())
  215465. {
  215466. MessageThreadFuncCall messageCallContext;
  215467. messageCallContext.func = func;
  215468. messageCallContext.parameter = parameter;
  215469. juce_internalMessageQueue->postMessage (new Message (MessageThreadFuncCall::uniqueID,
  215470. 0, 0, &messageCallContext));
  215471. // Wait for it to complete before continuing
  215472. messageCallContext.event.wait();
  215473. return messageCallContext.result;
  215474. }
  215475. else
  215476. {
  215477. // Just call the function directly
  215478. return func (parameter);
  215479. }
  215480. }
  215481. // Wait for an event (either XEvent, or an internal Message)
  215482. static bool juce_sleepUntilEvent (const int timeoutMs)
  215483. {
  215484. if (! juce_internalMessageQueue->isEmpty())
  215485. return true;
  215486. if (display != 0)
  215487. {
  215488. ScopedXLock xlock;
  215489. if (XPending (display))
  215490. return true;
  215491. }
  215492. struct timeval tv;
  215493. tv.tv_sec = 0;
  215494. tv.tv_usec = timeoutMs * 1000;
  215495. int fd0 = juce_internalMessageQueue->getWaitHandle();
  215496. int fdmax = fd0;
  215497. fd_set readset;
  215498. FD_ZERO (&readset);
  215499. FD_SET (fd0, &readset);
  215500. if (display != 0)
  215501. {
  215502. ScopedXLock xlock;
  215503. int fd1 = XConnectionNumber (display);
  215504. FD_SET (fd1, &readset);
  215505. fdmax = jmax (fd0, fd1);
  215506. }
  215507. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  215508. return (ret > 0); // ret <= 0 if error or timeout
  215509. }
  215510. // Handle next XEvent (if any)
  215511. static bool juce_dispatchNextXEvent()
  215512. {
  215513. if (display == 0)
  215514. return false;
  215515. XEvent evt;
  215516. {
  215517. ScopedXLock xlock;
  215518. if (! XPending (display))
  215519. return false;
  215520. XNextEvent (display, &evt);
  215521. }
  215522. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  215523. {
  215524. juce_handleSelectionRequest (evt.xselectionrequest);
  215525. }
  215526. else if (evt.xany.window != juce_messageWindowHandle)
  215527. {
  215528. juce_windowMessageReceive (&evt);
  215529. }
  215530. return true;
  215531. }
  215532. // Handle next internal Message (if any)
  215533. static bool juce_dispatchNextInternalMessage()
  215534. {
  215535. ScopedPointer <Message> msg (juce_internalMessageQueue->popNextMessage());
  215536. if (msg == 0)
  215537. return false;
  215538. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  215539. {
  215540. // Handle callback message
  215541. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  215542. call->result = (*(call->func)) (call->parameter);
  215543. call->event.signal();
  215544. }
  215545. else
  215546. {
  215547. // Handle "normal" messages
  215548. MessageManager::getInstance()->deliverMessage (msg.release());
  215549. }
  215550. return true;
  215551. }
  215552. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  215553. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  215554. {
  215555. for (;;)
  215556. {
  215557. if (errorOccurred)
  215558. break;
  215559. if (keyboardBreakOccurred)
  215560. {
  215561. errorOccurred = true;
  215562. if (JUCEApplication::getInstance() != 0)
  215563. Process::terminate();
  215564. break;
  215565. }
  215566. static int totalEventCount = 0;
  215567. ++totalEventCount;
  215568. // The purpose here is to give either priority to XEvents or
  215569. // to internal messages This is necessary to keep a "good"
  215570. // behaviour when the cpu is overloaded
  215571. if (totalEventCount & 1)
  215572. {
  215573. if (juce_dispatchNextXEvent() || juce_dispatchNextInternalMessage())
  215574. return true;
  215575. }
  215576. else
  215577. {
  215578. if (juce_dispatchNextInternalMessage() || juce_dispatchNextXEvent())
  215579. return true;
  215580. }
  215581. if (returnIfNoPendingMessages) // early exit
  215582. break;
  215583. // the timeout is to be on the safe side, but it does not seem to be useful
  215584. juce_sleepUntilEvent (2000);
  215585. }
  215586. return false;
  215587. }
  215588. #endif
  215589. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  215590. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  215591. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  215592. // compiled on its own).
  215593. #if JUCE_INCLUDED_FILE
  215594. class FreeTypeFontFace
  215595. {
  215596. public:
  215597. enum FontStyle
  215598. {
  215599. Plain = 0,
  215600. Bold = 1,
  215601. Italic = 2
  215602. };
  215603. struct FontNameIndex
  215604. {
  215605. String fileName;
  215606. int faceIndex;
  215607. };
  215608. FreeTypeFontFace (const String& familyName)
  215609. : hasSerif (false),
  215610. monospaced (false)
  215611. {
  215612. family = familyName;
  215613. }
  215614. void setFileName (const String& name, const int faceIndex, FontStyle style)
  215615. {
  215616. if (names [(int) style].fileName.isEmpty())
  215617. {
  215618. names [(int) style].fileName = name;
  215619. names [(int) style].faceIndex = faceIndex;
  215620. }
  215621. }
  215622. const String& getFamilyName() const throw() { return family; }
  215623. const String& getFileName (const int style, int& faceIndex) const throw()
  215624. {
  215625. faceIndex = names[style].faceIndex;
  215626. return names[style].fileName;
  215627. }
  215628. void setMonospaced (bool mono) throw() { monospaced = mono; }
  215629. bool getMonospaced() const throw() { return monospaced; }
  215630. void setSerif (const bool serif) throw() { hasSerif = serif; }
  215631. bool getSerif() const throw() { return hasSerif; }
  215632. private:
  215633. String family;
  215634. FontNameIndex names[4];
  215635. bool hasSerif, monospaced;
  215636. };
  215637. class FreeTypeInterface : public DeletedAtShutdown
  215638. {
  215639. public:
  215640. FreeTypeInterface()
  215641. : ftLib (0),
  215642. lastFace (0),
  215643. lastBold (false),
  215644. lastItalic (false)
  215645. {
  215646. if (FT_Init_FreeType (&ftLib) != 0)
  215647. {
  215648. ftLib = 0;
  215649. DBG ("Failed to initialize FreeType");
  215650. }
  215651. StringArray fontDirs;
  215652. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  215653. fontDirs.removeEmptyStrings (true);
  215654. if (fontDirs.size() == 0)
  215655. {
  215656. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  215657. const ScopedPointer<XmlElement> fontsInfo (fontsConfig.getDocumentElement());
  215658. if (fontsInfo != 0)
  215659. {
  215660. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  215661. {
  215662. fontDirs.add (e->getAllSubText().trim());
  215663. }
  215664. }
  215665. }
  215666. if (fontDirs.size() == 0)
  215667. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  215668. for (int i = 0; i < fontDirs.size(); ++i)
  215669. enumerateFaces (fontDirs[i]);
  215670. }
  215671. ~FreeTypeInterface()
  215672. {
  215673. if (lastFace != 0)
  215674. FT_Done_Face (lastFace);
  215675. if (ftLib != 0)
  215676. FT_Done_FreeType (ftLib);
  215677. clearSingletonInstance();
  215678. }
  215679. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  215680. {
  215681. for (int i = 0; i < faces.size(); i++)
  215682. if (faces[i]->getFamilyName() == familyName)
  215683. return faces[i];
  215684. if (! create)
  215685. return 0;
  215686. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  215687. faces.add (newFace);
  215688. return newFace;
  215689. }
  215690. // Enumerate all font faces available in a given directory
  215691. void enumerateFaces (const String& path)
  215692. {
  215693. File dirPath (path);
  215694. if (path.isEmpty() || ! dirPath.isDirectory())
  215695. return;
  215696. DirectoryIterator di (dirPath, true);
  215697. while (di.next())
  215698. {
  215699. File possible (di.getFile());
  215700. if (possible.hasFileExtension ("ttf")
  215701. || possible.hasFileExtension ("pfb")
  215702. || possible.hasFileExtension ("pcf"))
  215703. {
  215704. FT_Face face;
  215705. int faceIndex = 0;
  215706. int numFaces = 0;
  215707. do
  215708. {
  215709. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  215710. faceIndex, &face) == 0)
  215711. {
  215712. if (faceIndex == 0)
  215713. numFaces = face->num_faces;
  215714. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  215715. {
  215716. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  215717. int style = (int) FreeTypeFontFace::Plain;
  215718. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  215719. style |= (int) FreeTypeFontFace::Bold;
  215720. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  215721. style |= (int) FreeTypeFontFace::Italic;
  215722. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  215723. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  215724. // Surely there must be a better way to do this?
  215725. const String name (face->family_name);
  215726. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  215727. || name.containsIgnoreCase ("Verdana")
  215728. || name.containsIgnoreCase ("Arial")));
  215729. }
  215730. FT_Done_Face (face);
  215731. }
  215732. ++faceIndex;
  215733. }
  215734. while (faceIndex < numFaces);
  215735. }
  215736. }
  215737. }
  215738. // Create a FreeType face object for a given font
  215739. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  215740. {
  215741. FT_Face face = 0;
  215742. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  215743. {
  215744. face = lastFace;
  215745. }
  215746. else
  215747. {
  215748. if (lastFace != 0)
  215749. {
  215750. FT_Done_Face (lastFace);
  215751. lastFace = 0;
  215752. }
  215753. lastFontName = fontName;
  215754. lastBold = bold;
  215755. lastItalic = italic;
  215756. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  215757. if (ftFace != 0)
  215758. {
  215759. int style = (int) FreeTypeFontFace::Plain;
  215760. if (bold)
  215761. style |= (int) FreeTypeFontFace::Bold;
  215762. if (italic)
  215763. style |= (int) FreeTypeFontFace::Italic;
  215764. int faceIndex;
  215765. String fileName (ftFace->getFileName (style, faceIndex));
  215766. if (fileName.isEmpty())
  215767. {
  215768. style ^= (int) FreeTypeFontFace::Bold;
  215769. fileName = ftFace->getFileName (style, faceIndex);
  215770. if (fileName.isEmpty())
  215771. {
  215772. style ^= (int) FreeTypeFontFace::Bold;
  215773. style ^= (int) FreeTypeFontFace::Italic;
  215774. fileName = ftFace->getFileName (style, faceIndex);
  215775. if (! fileName.length())
  215776. {
  215777. style ^= (int) FreeTypeFontFace::Bold;
  215778. fileName = ftFace->getFileName (style, faceIndex);
  215779. }
  215780. }
  215781. }
  215782. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  215783. {
  215784. face = lastFace;
  215785. // If there isn't a unicode charmap then select the first one.
  215786. if (FT_Select_Charmap (face, ft_encoding_unicode))
  215787. FT_Set_Charmap (face, face->charmaps[0]);
  215788. }
  215789. }
  215790. }
  215791. return face;
  215792. }
  215793. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  215794. {
  215795. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  215796. const float height = (float) (face->ascender - face->descender);
  215797. const float scaleX = 1.0f / height;
  215798. const float scaleY = -1.0f / height;
  215799. Path destShape;
  215800. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  215801. || face->glyph->format != ft_glyph_format_outline)
  215802. {
  215803. return false;
  215804. }
  215805. const FT_Outline* const outline = &face->glyph->outline;
  215806. const short* const contours = outline->contours;
  215807. const char* const tags = outline->tags;
  215808. FT_Vector* const points = outline->points;
  215809. for (int c = 0; c < outline->n_contours; c++)
  215810. {
  215811. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  215812. const int endPoint = contours[c];
  215813. for (int p = startPoint; p <= endPoint; p++)
  215814. {
  215815. const float x = scaleX * points[p].x;
  215816. const float y = scaleY * points[p].y;
  215817. if (p == startPoint)
  215818. {
  215819. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  215820. {
  215821. float x2 = scaleX * points [endPoint].x;
  215822. float y2 = scaleY * points [endPoint].y;
  215823. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  215824. {
  215825. x2 = (x + x2) * 0.5f;
  215826. y2 = (y + y2) * 0.5f;
  215827. }
  215828. destShape.startNewSubPath (x2, y2);
  215829. }
  215830. else
  215831. {
  215832. destShape.startNewSubPath (x, y);
  215833. }
  215834. }
  215835. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  215836. {
  215837. if (p != startPoint)
  215838. destShape.lineTo (x, y);
  215839. }
  215840. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  215841. {
  215842. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  215843. float x2 = scaleX * points [nextIndex].x;
  215844. float y2 = scaleY * points [nextIndex].y;
  215845. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  215846. {
  215847. x2 = (x + x2) * 0.5f;
  215848. y2 = (y + y2) * 0.5f;
  215849. }
  215850. else
  215851. {
  215852. ++p;
  215853. }
  215854. destShape.quadraticTo (x, y, x2, y2);
  215855. }
  215856. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  215857. {
  215858. if (p >= endPoint)
  215859. return false;
  215860. const int next1 = p + 1;
  215861. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  215862. const float x2 = scaleX * points [next1].x;
  215863. const float y2 = scaleY * points [next1].y;
  215864. const float x3 = scaleX * points [next2].x;
  215865. const float y3 = scaleY * points [next2].y;
  215866. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  215867. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  215868. return false;
  215869. destShape.cubicTo (x, y, x2, y2, x3, y3);
  215870. p += 2;
  215871. }
  215872. }
  215873. destShape.closeSubPath();
  215874. }
  215875. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  215876. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  215877. addKerning (face, dest, character, glyphIndex);
  215878. return true;
  215879. }
  215880. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  215881. {
  215882. const float height = (float) (face->ascender - face->descender);
  215883. uint32 rightGlyphIndex;
  215884. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  215885. while (rightGlyphIndex != 0)
  215886. {
  215887. FT_Vector kerning;
  215888. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  215889. {
  215890. if (kerning.x != 0)
  215891. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  215892. }
  215893. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  215894. }
  215895. }
  215896. // Add a glyph to a font
  215897. bool addGlyphToFont (const uint32 character, const String& fontName,
  215898. bool bold, bool italic, CustomTypeface& dest)
  215899. {
  215900. FT_Face face = createFT_Face (fontName, bold, italic);
  215901. return face != 0 && addGlyph (face, dest, character);
  215902. }
  215903. void getFamilyNames (StringArray& familyNames) const
  215904. {
  215905. for (int i = 0; i < faces.size(); i++)
  215906. familyNames.add (faces[i]->getFamilyName());
  215907. }
  215908. void getMonospacedNames (StringArray& monoSpaced) const
  215909. {
  215910. for (int i = 0; i < faces.size(); i++)
  215911. if (faces[i]->getMonospaced())
  215912. monoSpaced.add (faces[i]->getFamilyName());
  215913. }
  215914. void getSerifNames (StringArray& serif) const
  215915. {
  215916. for (int i = 0; i < faces.size(); i++)
  215917. if (faces[i]->getSerif())
  215918. serif.add (faces[i]->getFamilyName());
  215919. }
  215920. void getSansSerifNames (StringArray& sansSerif) const
  215921. {
  215922. for (int i = 0; i < faces.size(); i++)
  215923. if (! faces[i]->getSerif())
  215924. sansSerif.add (faces[i]->getFamilyName());
  215925. }
  215926. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  215927. private:
  215928. FT_Library ftLib;
  215929. FT_Face lastFace;
  215930. String lastFontName;
  215931. bool lastBold, lastItalic;
  215932. OwnedArray<FreeTypeFontFace> faces;
  215933. };
  215934. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  215935. class FreetypeTypeface : public CustomTypeface
  215936. {
  215937. public:
  215938. FreetypeTypeface (const Font& font)
  215939. {
  215940. FT_Face face = FreeTypeInterface::getInstance()
  215941. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  215942. if (face == 0)
  215943. {
  215944. #if JUCE_DEBUG
  215945. String msg ("Failed to create typeface: ");
  215946. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  215947. DBG (msg);
  215948. #endif
  215949. }
  215950. else
  215951. {
  215952. setCharacteristics (font.getTypefaceName(),
  215953. face->ascender / (float) (face->ascender - face->descender),
  215954. font.isBold(), font.isItalic(),
  215955. L' ');
  215956. }
  215957. }
  215958. bool loadGlyphIfPossible (juce_wchar character)
  215959. {
  215960. return FreeTypeInterface::getInstance()
  215961. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  215962. }
  215963. };
  215964. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  215965. {
  215966. return new FreetypeTypeface (font);
  215967. }
  215968. const StringArray Font::findAllTypefaceNames()
  215969. {
  215970. StringArray s;
  215971. FreeTypeInterface::getInstance()->getFamilyNames (s);
  215972. s.sort (true);
  215973. return s;
  215974. }
  215975. static const String pickBestFont (const StringArray& names,
  215976. const char* const choicesString)
  215977. {
  215978. StringArray choices;
  215979. choices.addTokens (String (choicesString), ",", String::empty);
  215980. choices.trim();
  215981. choices.removeEmptyStrings();
  215982. int i, j;
  215983. for (j = 0; j < choices.size(); ++j)
  215984. if (names.contains (choices[j], true))
  215985. return choices[j];
  215986. for (j = 0; j < choices.size(); ++j)
  215987. for (i = 0; i < names.size(); i++)
  215988. if (names[i].startsWithIgnoreCase (choices[j]))
  215989. return names[i];
  215990. for (j = 0; j < choices.size(); ++j)
  215991. for (i = 0; i < names.size(); i++)
  215992. if (names[i].containsIgnoreCase (choices[j]))
  215993. return names[i];
  215994. return names[0];
  215995. }
  215996. static const String linux_getDefaultSansSerifFontName()
  215997. {
  215998. StringArray allFonts;
  215999. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  216000. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  216001. }
  216002. static const String linux_getDefaultSerifFontName()
  216003. {
  216004. StringArray allFonts;
  216005. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  216006. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  216007. }
  216008. static const String linux_getDefaultMonospacedFontName()
  216009. {
  216010. StringArray allFonts;
  216011. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  216012. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  216013. }
  216014. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  216015. {
  216016. defaultSans = linux_getDefaultSansSerifFontName();
  216017. defaultSerif = linux_getDefaultSerifFontName();
  216018. defaultFixed = linux_getDefaultMonospacedFontName();
  216019. }
  216020. #endif
  216021. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  216022. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  216023. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216024. // compiled on its own).
  216025. #if JUCE_INCLUDED_FILE
  216026. // These are defined in juce_linux_Messaging.cpp
  216027. extern Display* display;
  216028. extern XContext windowHandleXContext;
  216029. namespace Atoms
  216030. {
  216031. enum ProtocolItems
  216032. {
  216033. TAKE_FOCUS = 0,
  216034. DELETE_WINDOW = 1,
  216035. PING = 2
  216036. };
  216037. static Atom Protocols, ProtocolList[3], ChangeState, State,
  216038. ActiveWin, Pid, WindowType, WindowState,
  216039. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  216040. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  216041. XdndActionDescription, XdndActionCopy,
  216042. allowedActions[5],
  216043. allowedMimeTypes[2];
  216044. const unsigned long DndVersion = 3;
  216045. static void initialiseAtoms()
  216046. {
  216047. static bool atomsInitialised = false;
  216048. if (! atomsInitialised)
  216049. {
  216050. atomsInitialised = true;
  216051. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  216052. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  216053. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  216054. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  216055. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  216056. State = XInternAtom (display, "WM_STATE", True);
  216057. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  216058. Pid = XInternAtom (display, "_NET_WM_PID", False);
  216059. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  216060. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  216061. XdndAware = XInternAtom (display, "XdndAware", False);
  216062. XdndEnter = XInternAtom (display, "XdndEnter", False);
  216063. XdndLeave = XInternAtom (display, "XdndLeave", False);
  216064. XdndPosition = XInternAtom (display, "XdndPosition", False);
  216065. XdndStatus = XInternAtom (display, "XdndStatus", False);
  216066. XdndDrop = XInternAtom (display, "XdndDrop", False);
  216067. XdndFinished = XInternAtom (display, "XdndFinished", False);
  216068. XdndSelection = XInternAtom (display, "XdndSelection", False);
  216069. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  216070. XdndActionList = XInternAtom (display, "XdndActionList", False);
  216071. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  216072. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  216073. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  216074. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  216075. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  216076. allowedActions[1] = XdndActionCopy;
  216077. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  216078. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  216079. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  216080. }
  216081. }
  216082. }
  216083. namespace Keys
  216084. {
  216085. enum MouseButtons
  216086. {
  216087. NoButton = 0,
  216088. LeftButton = 1,
  216089. MiddleButton = 2,
  216090. RightButton = 3,
  216091. WheelUp = 4,
  216092. WheelDown = 5
  216093. };
  216094. static int AltMask = 0;
  216095. static int NumLockMask = 0;
  216096. static bool numLock = false;
  216097. static bool capsLock = false;
  216098. static char keyStates [32];
  216099. static const int extendedKeyModifier = 0x10000000;
  216100. }
  216101. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  216102. {
  216103. int keysym;
  216104. if (keyCode & Keys::extendedKeyModifier)
  216105. {
  216106. keysym = 0xff00 | (keyCode & 0xff);
  216107. }
  216108. else
  216109. {
  216110. keysym = keyCode;
  216111. if (keysym == (XK_Tab & 0xff)
  216112. || keysym == (XK_Return & 0xff)
  216113. || keysym == (XK_Escape & 0xff)
  216114. || keysym == (XK_BackSpace & 0xff))
  216115. {
  216116. keysym |= 0xff00;
  216117. }
  216118. }
  216119. ScopedXLock xlock;
  216120. const int keycode = XKeysymToKeycode (display, keysym);
  216121. const int keybyte = keycode >> 3;
  216122. const int keybit = (1 << (keycode & 7));
  216123. return (Keys::keyStates [keybyte] & keybit) != 0;
  216124. }
  216125. #if JUCE_USE_XSHM
  216126. namespace XSHMHelpers
  216127. {
  216128. static int trappedErrorCode = 0;
  216129. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  216130. {
  216131. trappedErrorCode = err->error_code;
  216132. return 0;
  216133. }
  216134. static bool isShmAvailable() throw()
  216135. {
  216136. static bool isChecked = false;
  216137. static bool isAvailable = false;
  216138. if (! isChecked)
  216139. {
  216140. isChecked = true;
  216141. int major, minor;
  216142. Bool pixmaps;
  216143. ScopedXLock xlock;
  216144. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  216145. {
  216146. trappedErrorCode = 0;
  216147. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  216148. XShmSegmentInfo segmentInfo;
  216149. zerostruct (segmentInfo);
  216150. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  216151. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  216152. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  216153. xImage->bytes_per_line * xImage->height,
  216154. IPC_CREAT | 0777)) >= 0)
  216155. {
  216156. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  216157. if (segmentInfo.shmaddr != (void*) -1)
  216158. {
  216159. segmentInfo.readOnly = False;
  216160. xImage->data = segmentInfo.shmaddr;
  216161. XSync (display, False);
  216162. if (XShmAttach (display, &segmentInfo) != 0)
  216163. {
  216164. XSync (display, False);
  216165. XShmDetach (display, &segmentInfo);
  216166. isAvailable = true;
  216167. }
  216168. }
  216169. XFlush (display);
  216170. XDestroyImage (xImage);
  216171. shmdt (segmentInfo.shmaddr);
  216172. }
  216173. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  216174. XSetErrorHandler (oldHandler);
  216175. if (trappedErrorCode != 0)
  216176. isAvailable = false;
  216177. }
  216178. }
  216179. return isAvailable;
  216180. }
  216181. }
  216182. #endif
  216183. #if JUCE_USE_XRENDER
  216184. namespace XRender
  216185. {
  216186. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  216187. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  216188. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  216189. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  216190. static tXRenderQueryVersion xRenderQueryVersion = 0;
  216191. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  216192. static tXRenderFindFormat xRenderFindFormat = 0;
  216193. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  216194. static bool isAvailable()
  216195. {
  216196. static bool hasLoaded = false;
  216197. if (! hasLoaded)
  216198. {
  216199. ScopedXLock xlock;
  216200. hasLoaded = true;
  216201. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  216202. if (h != 0)
  216203. {
  216204. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  216205. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  216206. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  216207. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  216208. }
  216209. if (xRenderQueryVersion != 0
  216210. && xRenderFindStandardFormat != 0
  216211. && xRenderFindFormat != 0
  216212. && xRenderFindVisualFormat != 0)
  216213. {
  216214. int major, minor;
  216215. if (xRenderQueryVersion (display, &major, &minor))
  216216. return true;
  216217. }
  216218. xRenderQueryVersion = 0;
  216219. }
  216220. return xRenderQueryVersion != 0;
  216221. }
  216222. static XRenderPictFormat* findPictureFormat()
  216223. {
  216224. ScopedXLock xlock;
  216225. XRenderPictFormat* pictFormat = 0;
  216226. if (isAvailable())
  216227. {
  216228. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  216229. if (pictFormat == 0)
  216230. {
  216231. XRenderPictFormat desiredFormat;
  216232. desiredFormat.type = PictTypeDirect;
  216233. desiredFormat.depth = 32;
  216234. desiredFormat.direct.alphaMask = 0xff;
  216235. desiredFormat.direct.redMask = 0xff;
  216236. desiredFormat.direct.greenMask = 0xff;
  216237. desiredFormat.direct.blueMask = 0xff;
  216238. desiredFormat.direct.alpha = 24;
  216239. desiredFormat.direct.red = 16;
  216240. desiredFormat.direct.green = 8;
  216241. desiredFormat.direct.blue = 0;
  216242. pictFormat = xRenderFindFormat (display,
  216243. PictFormatType | PictFormatDepth
  216244. | PictFormatRedMask | PictFormatRed
  216245. | PictFormatGreenMask | PictFormatGreen
  216246. | PictFormatBlueMask | PictFormatBlue
  216247. | PictFormatAlphaMask | PictFormatAlpha,
  216248. &desiredFormat,
  216249. 0);
  216250. }
  216251. }
  216252. return pictFormat;
  216253. }
  216254. }
  216255. #endif
  216256. namespace Visuals
  216257. {
  216258. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  216259. {
  216260. ScopedXLock xlock;
  216261. Visual* visual = 0;
  216262. int numVisuals = 0;
  216263. long desiredMask = VisualNoMask;
  216264. XVisualInfo desiredVisual;
  216265. desiredVisual.screen = DefaultScreen (display);
  216266. desiredVisual.depth = desiredDepth;
  216267. desiredMask = VisualScreenMask | VisualDepthMask;
  216268. if (desiredDepth == 32)
  216269. {
  216270. desiredVisual.c_class = TrueColor;
  216271. desiredVisual.red_mask = 0x00FF0000;
  216272. desiredVisual.green_mask = 0x0000FF00;
  216273. desiredVisual.blue_mask = 0x000000FF;
  216274. desiredVisual.bits_per_rgb = 8;
  216275. desiredMask |= VisualClassMask;
  216276. desiredMask |= VisualRedMaskMask;
  216277. desiredMask |= VisualGreenMaskMask;
  216278. desiredMask |= VisualBlueMaskMask;
  216279. desiredMask |= VisualBitsPerRGBMask;
  216280. }
  216281. XVisualInfo* xvinfos = XGetVisualInfo (display,
  216282. desiredMask,
  216283. &desiredVisual,
  216284. &numVisuals);
  216285. if (xvinfos != 0)
  216286. {
  216287. for (int i = 0; i < numVisuals; i++)
  216288. {
  216289. if (xvinfos[i].depth == desiredDepth)
  216290. {
  216291. visual = xvinfos[i].visual;
  216292. break;
  216293. }
  216294. }
  216295. XFree (xvinfos);
  216296. }
  216297. return visual;
  216298. }
  216299. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  216300. {
  216301. Visual* visual = 0;
  216302. if (desiredDepth == 32)
  216303. {
  216304. #if JUCE_USE_XSHM
  216305. if (XSHMHelpers::isShmAvailable())
  216306. {
  216307. #if JUCE_USE_XRENDER
  216308. if (XRender::isAvailable())
  216309. {
  216310. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  216311. if (pictFormat != 0)
  216312. {
  216313. int numVisuals = 0;
  216314. XVisualInfo desiredVisual;
  216315. desiredVisual.screen = DefaultScreen (display);
  216316. desiredVisual.depth = 32;
  216317. desiredVisual.bits_per_rgb = 8;
  216318. XVisualInfo* xvinfos = XGetVisualInfo (display,
  216319. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  216320. &desiredVisual, &numVisuals);
  216321. if (xvinfos != 0)
  216322. {
  216323. for (int i = 0; i < numVisuals; ++i)
  216324. {
  216325. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  216326. if (pictVisualFormat != 0
  216327. && pictVisualFormat->type == PictTypeDirect
  216328. && pictVisualFormat->direct.alphaMask)
  216329. {
  216330. visual = xvinfos[i].visual;
  216331. matchedDepth = 32;
  216332. break;
  216333. }
  216334. }
  216335. XFree (xvinfos);
  216336. }
  216337. }
  216338. }
  216339. #endif
  216340. if (visual == 0)
  216341. {
  216342. visual = findVisualWithDepth (32);
  216343. if (visual != 0)
  216344. matchedDepth = 32;
  216345. }
  216346. }
  216347. #endif
  216348. }
  216349. if (visual == 0 && desiredDepth >= 24)
  216350. {
  216351. visual = findVisualWithDepth (24);
  216352. if (visual != 0)
  216353. matchedDepth = 24;
  216354. }
  216355. if (visual == 0 && desiredDepth >= 16)
  216356. {
  216357. visual = findVisualWithDepth (16);
  216358. if (visual != 0)
  216359. matchedDepth = 16;
  216360. }
  216361. return visual;
  216362. }
  216363. }
  216364. class XBitmapImage : public Image
  216365. {
  216366. public:
  216367. XBitmapImage (const PixelFormat format_, const int w, const int h,
  216368. const bool clearImage, const int imageDepth_, Visual* visual)
  216369. : Image (format_, w, h),
  216370. imageDepth (imageDepth_),
  216371. gc (None)
  216372. {
  216373. jassert (format_ == RGB || format_ == ARGB);
  216374. pixelStride = (format_ == RGB) ? 3 : 4;
  216375. lineStride = ((w * pixelStride + 3) & ~3);
  216376. ScopedXLock xlock;
  216377. #if JUCE_USE_XSHM
  216378. usingXShm = false;
  216379. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  216380. {
  216381. zerostruct (segmentInfo);
  216382. segmentInfo.shmid = -1;
  216383. segmentInfo.shmaddr = (char *) -1;
  216384. segmentInfo.readOnly = False;
  216385. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  216386. if (xImage != 0)
  216387. {
  216388. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  216389. xImage->bytes_per_line * xImage->height,
  216390. IPC_CREAT | 0777)) >= 0)
  216391. {
  216392. if (segmentInfo.shmid != -1)
  216393. {
  216394. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  216395. if (segmentInfo.shmaddr != (void*) -1)
  216396. {
  216397. segmentInfo.readOnly = False;
  216398. xImage->data = segmentInfo.shmaddr;
  216399. imageData = (uint8*) segmentInfo.shmaddr;
  216400. if (XShmAttach (display, &segmentInfo) != 0)
  216401. {
  216402. usingXShm = true;
  216403. }
  216404. else
  216405. {
  216406. jassertfalse
  216407. }
  216408. }
  216409. else
  216410. {
  216411. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  216412. }
  216413. }
  216414. }
  216415. }
  216416. }
  216417. if (! usingXShm)
  216418. #endif
  216419. {
  216420. imageDataAllocated.malloc (lineStride * h);
  216421. imageData = imageDataAllocated;
  216422. if (format_ == ARGB && clearImage)
  216423. zeromem (imageData, h * lineStride);
  216424. xImage = (XImage*) juce_calloc (sizeof (XImage));
  216425. xImage->width = w;
  216426. xImage->height = h;
  216427. xImage->xoffset = 0;
  216428. xImage->format = ZPixmap;
  216429. xImage->data = (char*) imageData;
  216430. xImage->byte_order = ImageByteOrder (display);
  216431. xImage->bitmap_unit = BitmapUnit (display);
  216432. xImage->bitmap_bit_order = BitmapBitOrder (display);
  216433. xImage->bitmap_pad = 32;
  216434. xImage->depth = pixelStride * 8;
  216435. xImage->bytes_per_line = lineStride;
  216436. xImage->bits_per_pixel = pixelStride * 8;
  216437. xImage->red_mask = 0x00FF0000;
  216438. xImage->green_mask = 0x0000FF00;
  216439. xImage->blue_mask = 0x000000FF;
  216440. if (imageDepth == 16)
  216441. {
  216442. const int pixelStride = 2;
  216443. const int lineStride = ((w * pixelStride + 3) & ~3);
  216444. imageData16Bit.malloc (lineStride * h);
  216445. xImage->data = imageData16Bit;
  216446. xImage->bitmap_pad = 16;
  216447. xImage->depth = pixelStride * 8;
  216448. xImage->bytes_per_line = lineStride;
  216449. xImage->bits_per_pixel = pixelStride * 8;
  216450. xImage->red_mask = visual->red_mask;
  216451. xImage->green_mask = visual->green_mask;
  216452. xImage->blue_mask = visual->blue_mask;
  216453. }
  216454. if (! XInitImage (xImage))
  216455. {
  216456. jassertfalse
  216457. }
  216458. }
  216459. }
  216460. ~XBitmapImage()
  216461. {
  216462. ScopedXLock xlock;
  216463. if (gc != None)
  216464. XFreeGC (display, gc);
  216465. #if JUCE_USE_XSHM
  216466. if (usingXShm)
  216467. {
  216468. XShmDetach (display, &segmentInfo);
  216469. XFlush (display);
  216470. XDestroyImage (xImage);
  216471. shmdt (segmentInfo.shmaddr);
  216472. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  216473. }
  216474. else
  216475. #endif
  216476. {
  216477. xImage->data = 0;
  216478. XDestroyImage (xImage);
  216479. }
  216480. }
  216481. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  216482. {
  216483. ScopedXLock xlock;
  216484. if (gc == None)
  216485. {
  216486. XGCValues gcvalues;
  216487. gcvalues.foreground = None;
  216488. gcvalues.background = None;
  216489. gcvalues.function = GXcopy;
  216490. gcvalues.plane_mask = AllPlanes;
  216491. gcvalues.clip_mask = None;
  216492. gcvalues.graphics_exposures = False;
  216493. gc = XCreateGC (display, window,
  216494. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  216495. &gcvalues);
  216496. }
  216497. if (imageDepth == 16)
  216498. {
  216499. const uint32 rMask = xImage->red_mask;
  216500. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  216501. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  216502. const uint32 gMask = xImage->green_mask;
  216503. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  216504. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  216505. const uint32 bMask = xImage->blue_mask;
  216506. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  216507. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  216508. const Image::BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  216509. for (int y = sy; y < sy + dh; ++y)
  216510. {
  216511. const uint8* p = srcData.getPixelPointer (sx, y);
  216512. for (int x = sx; x < sx + dw; ++x)
  216513. {
  216514. const PixelRGB* const pixel = (const PixelRGB*) p;
  216515. p += srcData.pixelStride;
  216516. XPutPixel (xImage, x, y,
  216517. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  216518. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  216519. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  216520. }
  216521. }
  216522. }
  216523. // blit results to screen.
  216524. #if JUCE_USE_XSHM
  216525. if (usingXShm)
  216526. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  216527. else
  216528. #endif
  216529. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  216530. }
  216531. juce_UseDebuggingNewOperator
  216532. private:
  216533. XImage* xImage;
  216534. const int imageDepth;
  216535. HeapBlock <char> imageData16Bit;
  216536. GC gc;
  216537. #if JUCE_USE_XSHM
  216538. XShmSegmentInfo segmentInfo;
  216539. bool usingXShm;
  216540. #endif
  216541. static int getShiftNeeded (const uint32 mask) throw()
  216542. {
  216543. for (int i = 32; --i >= 0;)
  216544. if (((mask >> i) & 1) != 0)
  216545. return i - 7;
  216546. jassertfalse
  216547. return 0;
  216548. }
  216549. };
  216550. class LinuxComponentPeer : public ComponentPeer
  216551. {
  216552. public:
  216553. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  216554. : ComponentPeer (component, windowStyleFlags),
  216555. windowH (0),
  216556. parentWindow (0),
  216557. wx (0),
  216558. wy (0),
  216559. ww (0),
  216560. wh (0),
  216561. fullScreen (false),
  216562. mapped (false),
  216563. visual (0),
  216564. depth (0)
  216565. {
  216566. // it's dangerous to create a window on a thread other than the message thread..
  216567. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  216568. repainter = new LinuxRepaintManager (this);
  216569. createWindow();
  216570. setTitle (component->getName());
  216571. }
  216572. ~LinuxComponentPeer()
  216573. {
  216574. // it's dangerous to delete a window on a thread other than the message thread..
  216575. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  216576. deleteIconPixmaps();
  216577. destroyWindow();
  216578. windowH = 0;
  216579. }
  216580. void* getNativeHandle() const
  216581. {
  216582. return (void*) windowH;
  216583. }
  216584. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  216585. {
  216586. XPointer peer = 0;
  216587. ScopedXLock xlock;
  216588. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  216589. {
  216590. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  216591. peer = 0;
  216592. }
  216593. return (LinuxComponentPeer*) peer;
  216594. }
  216595. void setVisible (bool shouldBeVisible)
  216596. {
  216597. ScopedXLock xlock;
  216598. if (shouldBeVisible)
  216599. XMapWindow (display, windowH);
  216600. else
  216601. XUnmapWindow (display, windowH);
  216602. }
  216603. void setTitle (const String& title)
  216604. {
  216605. setWindowTitle (windowH, title);
  216606. }
  216607. void setPosition (int x, int y)
  216608. {
  216609. setBounds (x, y, ww, wh, false);
  216610. }
  216611. void setSize (int w, int h)
  216612. {
  216613. setBounds (wx, wy, w, h, false);
  216614. }
  216615. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  216616. {
  216617. fullScreen = isNowFullScreen;
  216618. if (windowH != 0)
  216619. {
  216620. Component::SafePointer<Component> deletionChecker (component);
  216621. wx = x;
  216622. wy = y;
  216623. ww = jmax (1, w);
  216624. wh = jmax (1, h);
  216625. ScopedXLock xlock;
  216626. // Make sure the Window manager does what we want
  216627. XSizeHints* hints = XAllocSizeHints();
  216628. hints->flags = USSize | USPosition;
  216629. hints->width = ww;
  216630. hints->height = wh;
  216631. hints->x = wx;
  216632. hints->y = wy;
  216633. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  216634. {
  216635. hints->min_width = hints->max_width = hints->width;
  216636. hints->min_height = hints->max_height = hints->height;
  216637. hints->flags |= PMinSize | PMaxSize;
  216638. }
  216639. XSetWMNormalHints (display, windowH, hints);
  216640. XFree (hints);
  216641. XMoveResizeWindow (display, windowH,
  216642. wx - windowBorder.getLeft(),
  216643. wy - windowBorder.getTop(), ww, wh);
  216644. if (deletionChecker != 0)
  216645. {
  216646. updateBorderSize();
  216647. handleMovedOrResized();
  216648. }
  216649. }
  216650. }
  216651. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  216652. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  216653. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  216654. {
  216655. return relativePosition + getScreenPosition();
  216656. }
  216657. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  216658. {
  216659. return screenPosition - getScreenPosition();
  216660. }
  216661. void setMinimised (bool shouldBeMinimised)
  216662. {
  216663. if (shouldBeMinimised)
  216664. {
  216665. Window root = RootWindow (display, DefaultScreen (display));
  216666. XClientMessageEvent clientMsg;
  216667. clientMsg.display = display;
  216668. clientMsg.window = windowH;
  216669. clientMsg.type = ClientMessage;
  216670. clientMsg.format = 32;
  216671. clientMsg.message_type = Atoms::ChangeState;
  216672. clientMsg.data.l[0] = IconicState;
  216673. ScopedXLock xlock;
  216674. XSendEvent (display, root, false,
  216675. SubstructureRedirectMask | SubstructureNotifyMask,
  216676. (XEvent*) &clientMsg);
  216677. }
  216678. else
  216679. {
  216680. setVisible (true);
  216681. }
  216682. }
  216683. bool isMinimised() const
  216684. {
  216685. bool minimised = false;
  216686. unsigned char* stateProp;
  216687. unsigned long nitems, bytesLeft;
  216688. Atom actualType;
  216689. int actualFormat;
  216690. ScopedXLock xlock;
  216691. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  216692. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  216693. &stateProp) == Success
  216694. && actualType == Atoms::State
  216695. && actualFormat == 32
  216696. && nitems > 0)
  216697. {
  216698. if (((unsigned long*) stateProp)[0] == IconicState)
  216699. minimised = true;
  216700. XFree (stateProp);
  216701. }
  216702. return minimised;
  216703. }
  216704. void setFullScreen (const bool shouldBeFullScreen)
  216705. {
  216706. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  216707. setMinimised (false);
  216708. if (fullScreen != shouldBeFullScreen)
  216709. {
  216710. if (shouldBeFullScreen)
  216711. r = Desktop::getInstance().getMainMonitorArea();
  216712. if (! r.isEmpty())
  216713. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  216714. getComponent()->repaint();
  216715. }
  216716. }
  216717. bool isFullScreen() const
  216718. {
  216719. return fullScreen;
  216720. }
  216721. bool isChildWindowOf (Window possibleParent) const
  216722. {
  216723. Window* windowList = 0;
  216724. uint32 windowListSize = 0;
  216725. Window parent, root;
  216726. ScopedXLock xlock;
  216727. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  216728. {
  216729. if (windowList != 0)
  216730. XFree (windowList);
  216731. return parent == possibleParent;
  216732. }
  216733. return false;
  216734. }
  216735. bool isFrontWindow() const
  216736. {
  216737. Window* windowList = 0;
  216738. uint32 windowListSize = 0;
  216739. bool result = false;
  216740. ScopedXLock xlock;
  216741. Window parent, root = RootWindow (display, DefaultScreen (display));
  216742. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  216743. {
  216744. for (int i = windowListSize; --i >= 0;)
  216745. {
  216746. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  216747. if (peer != 0)
  216748. {
  216749. result = (peer == this);
  216750. break;
  216751. }
  216752. }
  216753. }
  216754. if (windowList != 0)
  216755. XFree (windowList);
  216756. return result;
  216757. }
  216758. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  216759. {
  216760. int x = position.getX();
  216761. int y = position.getY();
  216762. if (((unsigned int) x) >= (unsigned int) ww
  216763. || ((unsigned int) y) >= (unsigned int) wh)
  216764. return false;
  216765. bool inFront = false;
  216766. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  216767. {
  216768. Component* const c = Desktop::getInstance().getComponent (i);
  216769. if (inFront)
  216770. {
  216771. if (c->contains (x + wx - c->getScreenX(),
  216772. y + wy - c->getScreenY()))
  216773. {
  216774. return false;
  216775. }
  216776. }
  216777. else if (c == getComponent())
  216778. {
  216779. inFront = true;
  216780. }
  216781. }
  216782. if (trueIfInAChildWindow)
  216783. return true;
  216784. ::Window root, child;
  216785. unsigned int bw, depth;
  216786. int wx, wy, w, h;
  216787. ScopedXLock xlock;
  216788. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  216789. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  216790. &bw, &depth))
  216791. {
  216792. return false;
  216793. }
  216794. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  216795. return false;
  216796. return child == None;
  216797. }
  216798. const BorderSize getFrameSize() const
  216799. {
  216800. return BorderSize();
  216801. }
  216802. bool setAlwaysOnTop (bool alwaysOnTop)
  216803. {
  216804. if (windowH != 0)
  216805. {
  216806. const bool wasVisible = component->isVisible();
  216807. if (wasVisible)
  216808. setVisible (false); // doesn't always seem to work if the window is visible when this is done..
  216809. {
  216810. ScopedXLock xlock;
  216811. XSetWindowAttributes swa;
  216812. swa.override_redirect = alwaysOnTop ? True : False;
  216813. XChangeWindowAttributes (display, windowH, CWOverrideRedirect, &swa);
  216814. }
  216815. if (wasVisible)
  216816. setVisible (true);
  216817. }
  216818. return true;
  216819. }
  216820. void toFront (bool makeActive)
  216821. {
  216822. if (makeActive)
  216823. {
  216824. setVisible (true);
  216825. grabFocus();
  216826. }
  216827. XEvent ev;
  216828. ev.xclient.type = ClientMessage;
  216829. ev.xclient.serial = 0;
  216830. ev.xclient.send_event = True;
  216831. ev.xclient.message_type = Atoms::ActiveWin;
  216832. ev.xclient.window = windowH;
  216833. ev.xclient.format = 32;
  216834. ev.xclient.data.l[0] = 2;
  216835. ev.xclient.data.l[1] = CurrentTime;
  216836. ev.xclient.data.l[2] = 0;
  216837. ev.xclient.data.l[3] = 0;
  216838. ev.xclient.data.l[4] = 0;
  216839. {
  216840. ScopedXLock xlock;
  216841. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  216842. False,
  216843. SubstructureRedirectMask | SubstructureNotifyMask,
  216844. &ev);
  216845. XWindowAttributes attr;
  216846. XGetWindowAttributes (display, windowH, &attr);
  216847. if (attr.override_redirect)
  216848. XRaiseWindow (display, windowH);
  216849. XSync (display, False);
  216850. }
  216851. handleBroughtToFront();
  216852. }
  216853. void toBehind (ComponentPeer* other)
  216854. {
  216855. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  216856. jassert (otherPeer != 0); // wrong type of window?
  216857. if (otherPeer != 0)
  216858. {
  216859. setMinimised (false);
  216860. Window newStack[] = { otherPeer->windowH, windowH };
  216861. ScopedXLock xlock;
  216862. XRestackWindows (display, newStack, 2);
  216863. }
  216864. }
  216865. bool isFocused() const
  216866. {
  216867. int revert;
  216868. Window focusedWindow = 0;
  216869. ScopedXLock xlock;
  216870. XGetInputFocus (display, &focusedWindow, &revert);
  216871. return focusedWindow == windowH;
  216872. }
  216873. void grabFocus()
  216874. {
  216875. XWindowAttributes atts;
  216876. ScopedXLock xlock;
  216877. if (windowH != 0
  216878. && XGetWindowAttributes (display, windowH, &atts)
  216879. && atts.map_state == IsViewable
  216880. && ! isFocused())
  216881. {
  216882. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  216883. isActiveApplication = true;
  216884. }
  216885. }
  216886. void textInputRequired (const Point<int>&)
  216887. {
  216888. }
  216889. void repaint (int x, int y, int w, int h)
  216890. {
  216891. if (Rectangle<int>::intersectRectangles (x, y, w, h,
  216892. 0, 0,
  216893. getComponent()->getWidth(),
  216894. getComponent()->getHeight()))
  216895. {
  216896. repainter->repaint (x, y, w, h);
  216897. }
  216898. }
  216899. void performAnyPendingRepaintsNow()
  216900. {
  216901. repainter->performAnyPendingRepaintsNow();
  216902. }
  216903. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  216904. {
  216905. ScopedXLock xlock;
  216906. const int width = image.getWidth();
  216907. const int height = image.getHeight();
  216908. HeapBlock <char> colour (width * height);
  216909. int index = 0;
  216910. for (int y = 0; y < height; ++y)
  216911. for (int x = 0; x < width; ++x)
  216912. colour[index++] = static_cast<char> (image.getPixelAt (x, y).getARGB());
  216913. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  216914. 0, colour.getData(),
  216915. width, height, 32, 0);
  216916. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  216917. width, height, 24);
  216918. GC gc = XCreateGC (display, pixmap, 0, 0);
  216919. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  216920. XFreeGC (display, gc);
  216921. return pixmap;
  216922. }
  216923. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  216924. {
  216925. ScopedXLock xlock;
  216926. const int width = image.getWidth();
  216927. const int height = image.getHeight();
  216928. const int stride = (width + 7) >> 3;
  216929. HeapBlock <char> mask;
  216930. mask.calloc (stride * height);
  216931. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  216932. for (int y = 0; y < height; ++y)
  216933. {
  216934. for (int x = 0; x < width; ++x)
  216935. {
  216936. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  216937. const int offset = y * stride + (x >> 3);
  216938. if (image.getPixelAt (x, y).getAlpha() >= 128)
  216939. mask[offset] |= bit;
  216940. }
  216941. }
  216942. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  216943. mask.getData(), width, height, 1, 0, 1);
  216944. }
  216945. void setIcon (const Image& newIcon)
  216946. {
  216947. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  216948. HeapBlock <unsigned long> data (dataSize);
  216949. int index = 0;
  216950. data[index++] = newIcon.getWidth();
  216951. data[index++] = newIcon.getHeight();
  216952. for (int y = 0; y < newIcon.getHeight(); ++y)
  216953. for (int x = 0; x < newIcon.getWidth(); ++x)
  216954. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  216955. ScopedXLock xlock;
  216956. XChangeProperty (display, windowH,
  216957. XInternAtom (display, "_NET_WM_ICON", False),
  216958. XA_CARDINAL, 32, PropModeReplace,
  216959. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  216960. deleteIconPixmaps();
  216961. XWMHints* wmHints = XGetWMHints (display, windowH);
  216962. if (wmHints == 0)
  216963. wmHints = XAllocWMHints();
  216964. wmHints->flags |= IconPixmapHint | IconMaskHint;
  216965. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  216966. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  216967. XSetWMHints (display, windowH, wmHints);
  216968. XFree (wmHints);
  216969. XSync (display, False);
  216970. }
  216971. void deleteIconPixmaps()
  216972. {
  216973. ScopedXLock xlock;
  216974. XWMHints* wmHints = XGetWMHints (display, windowH);
  216975. if (wmHints != 0)
  216976. {
  216977. if ((wmHints->flags & IconPixmapHint) != 0)
  216978. {
  216979. wmHints->flags &= ~IconPixmapHint;
  216980. XFreePixmap (display, wmHints->icon_pixmap);
  216981. }
  216982. if ((wmHints->flags & IconMaskHint) != 0)
  216983. {
  216984. wmHints->flags &= ~IconMaskHint;
  216985. XFreePixmap (display, wmHints->icon_mask);
  216986. }
  216987. XSetWMHints (display, windowH, wmHints);
  216988. XFree (wmHints);
  216989. }
  216990. }
  216991. void handleWindowMessage (XEvent* event)
  216992. {
  216993. switch (event->xany.type)
  216994. {
  216995. case 2: // 'KeyPress'
  216996. {
  216997. ScopedXLock xlock;
  216998. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  216999. updateKeyStates (keyEvent->keycode, true);
  217000. char utf8 [64];
  217001. zeromem (utf8, sizeof (utf8));
  217002. KeySym sym;
  217003. {
  217004. const char* oldLocale = ::setlocale (LC_ALL, 0);
  217005. ::setlocale (LC_ALL, "");
  217006. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  217007. ::setlocale (LC_ALL, oldLocale);
  217008. }
  217009. const juce_wchar unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  217010. int keyCode = (int) unicodeChar;
  217011. if (keyCode < 0x20)
  217012. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  217013. const ModifierKeys oldMods (currentModifiers);
  217014. bool keyPressed = false;
  217015. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  217016. if ((sym & 0xff00) == 0xff00)
  217017. {
  217018. // Translate keypad
  217019. if (sym == XK_KP_Divide)
  217020. keyCode = XK_slash;
  217021. else if (sym == XK_KP_Multiply)
  217022. keyCode = XK_asterisk;
  217023. else if (sym == XK_KP_Subtract)
  217024. keyCode = XK_hyphen;
  217025. else if (sym == XK_KP_Add)
  217026. keyCode = XK_plus;
  217027. else if (sym == XK_KP_Enter)
  217028. keyCode = XK_Return;
  217029. else if (sym == XK_KP_Decimal)
  217030. keyCode = Keys::numLock ? XK_period : XK_Delete;
  217031. else if (sym == XK_KP_0)
  217032. keyCode = Keys::numLock ? XK_0 : XK_Insert;
  217033. else if (sym == XK_KP_1)
  217034. keyCode = Keys::numLock ? XK_1 : XK_End;
  217035. else if (sym == XK_KP_2)
  217036. keyCode = Keys::numLock ? XK_2 : XK_Down;
  217037. else if (sym == XK_KP_3)
  217038. keyCode = Keys::numLock ? XK_3 : XK_Page_Down;
  217039. else if (sym == XK_KP_4)
  217040. keyCode = Keys::numLock ? XK_4 : XK_Left;
  217041. else if (sym == XK_KP_5)
  217042. keyCode = XK_5;
  217043. else if (sym == XK_KP_6)
  217044. keyCode = Keys::numLock ? XK_6 : XK_Right;
  217045. else if (sym == XK_KP_7)
  217046. keyCode = Keys::numLock ? XK_7 : XK_Home;
  217047. else if (sym == XK_KP_8)
  217048. keyCode = Keys::numLock ? XK_8 : XK_Up;
  217049. else if (sym == XK_KP_9)
  217050. keyCode = Keys::numLock ? XK_9 : XK_Page_Up;
  217051. switch (sym)
  217052. {
  217053. case XK_Left:
  217054. case XK_Right:
  217055. case XK_Up:
  217056. case XK_Down:
  217057. case XK_Page_Up:
  217058. case XK_Page_Down:
  217059. case XK_End:
  217060. case XK_Home:
  217061. case XK_Delete:
  217062. case XK_Insert:
  217063. keyPressed = true;
  217064. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  217065. break;
  217066. case XK_Tab:
  217067. case XK_Return:
  217068. case XK_Escape:
  217069. case XK_BackSpace:
  217070. keyPressed = true;
  217071. keyCode &= 0xff;
  217072. break;
  217073. default:
  217074. {
  217075. if (sym >= XK_F1 && sym <= XK_F16)
  217076. {
  217077. keyPressed = true;
  217078. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  217079. }
  217080. break;
  217081. }
  217082. }
  217083. }
  217084. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  217085. keyPressed = true;
  217086. if (oldMods != currentModifiers)
  217087. handleModifierKeysChange();
  217088. if (keyDownChange)
  217089. handleKeyUpOrDown (true);
  217090. if (keyPressed)
  217091. handleKeyPress (keyCode, unicodeChar);
  217092. break;
  217093. }
  217094. case KeyRelease:
  217095. {
  217096. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  217097. updateKeyStates (keyEvent->keycode, false);
  217098. ScopedXLock xlock;
  217099. KeySym sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  217100. const ModifierKeys oldMods (currentModifiers);
  217101. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  217102. if (oldMods != currentModifiers)
  217103. handleModifierKeysChange();
  217104. if (keyDownChange)
  217105. handleKeyUpOrDown (false);
  217106. break;
  217107. }
  217108. case ButtonPress:
  217109. {
  217110. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  217111. updateKeyModifiers (buttonPressEvent->state);
  217112. bool buttonMsg = false;
  217113. const int map = pointerMap [buttonPressEvent->button - Button1];
  217114. if (map == Keys::WheelUp || map == Keys::WheelDown)
  217115. {
  217116. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  217117. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  217118. }
  217119. if (map == Keys::LeftButton)
  217120. {
  217121. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  217122. buttonMsg = true;
  217123. }
  217124. else if (map == Keys::RightButton)
  217125. {
  217126. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  217127. buttonMsg = true;
  217128. }
  217129. else if (map == Keys::MiddleButton)
  217130. {
  217131. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  217132. buttonMsg = true;
  217133. }
  217134. if (buttonMsg)
  217135. {
  217136. toFront (true);
  217137. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  217138. getEventTime (buttonPressEvent->time));
  217139. }
  217140. clearLastMousePos();
  217141. break;
  217142. }
  217143. case ButtonRelease:
  217144. {
  217145. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  217146. updateKeyModifiers (buttonRelEvent->state);
  217147. const int map = pointerMap [buttonRelEvent->button - Button1];
  217148. if (map == Keys::LeftButton)
  217149. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  217150. else if (map == Keys::RightButton)
  217151. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  217152. else if (map == Keys::MiddleButton)
  217153. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  217154. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  217155. getEventTime (buttonRelEvent->time));
  217156. clearLastMousePos();
  217157. break;
  217158. }
  217159. case MotionNotify:
  217160. {
  217161. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  217162. updateKeyModifiers (movedEvent->state);
  217163. const Point<int> mousePos (Desktop::getMousePosition());
  217164. if (lastMousePos != mousePos)
  217165. {
  217166. lastMousePos = mousePos;
  217167. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  217168. {
  217169. Window wRoot = 0, wParent = 0;
  217170. {
  217171. ScopedXLock xlock;
  217172. unsigned int numChildren;
  217173. Window* wChild = 0;
  217174. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  217175. }
  217176. if (wParent != 0
  217177. && wParent != windowH
  217178. && wParent != wRoot)
  217179. {
  217180. parentWindow = wParent;
  217181. updateBounds();
  217182. }
  217183. else
  217184. {
  217185. parentWindow = 0;
  217186. }
  217187. }
  217188. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  217189. }
  217190. break;
  217191. }
  217192. case EnterNotify:
  217193. {
  217194. clearLastMousePos();
  217195. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  217196. if (! currentModifiers.isAnyMouseButtonDown())
  217197. {
  217198. updateKeyModifiers (enterEvent->state);
  217199. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  217200. }
  217201. break;
  217202. }
  217203. case LeaveNotify:
  217204. {
  217205. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  217206. // Suppress the normal leave if we've got a pointer grab, or if
  217207. // it's a bogus one caused by clicking a mouse button when running
  217208. // in a Window manager
  217209. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  217210. || leaveEvent->mode == NotifyUngrab)
  217211. {
  217212. updateKeyModifiers (leaveEvent->state);
  217213. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  217214. }
  217215. break;
  217216. }
  217217. case FocusIn:
  217218. {
  217219. isActiveApplication = true;
  217220. if (isFocused())
  217221. handleFocusGain();
  217222. break;
  217223. }
  217224. case FocusOut:
  217225. {
  217226. isActiveApplication = false;
  217227. if (! isFocused())
  217228. handleFocusLoss();
  217229. break;
  217230. }
  217231. case Expose:
  217232. {
  217233. // Batch together all pending expose events
  217234. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  217235. XEvent nextEvent;
  217236. ScopedXLock xlock;
  217237. if (exposeEvent->window != windowH)
  217238. {
  217239. Window child;
  217240. XTranslateCoordinates (display, exposeEvent->window, windowH,
  217241. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  217242. &child);
  217243. }
  217244. repaint (exposeEvent->x, exposeEvent->y,
  217245. exposeEvent->width, exposeEvent->height);
  217246. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  217247. {
  217248. XPeekEvent (display, (XEvent*) &nextEvent);
  217249. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  217250. break;
  217251. XNextEvent (display, (XEvent*) &nextEvent);
  217252. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  217253. repaint (nextExposeEvent->x, nextExposeEvent->y,
  217254. nextExposeEvent->width, nextExposeEvent->height);
  217255. }
  217256. break;
  217257. }
  217258. case CirculateNotify:
  217259. case CreateNotify:
  217260. case DestroyNotify:
  217261. // Think we can ignore these
  217262. break;
  217263. case ConfigureNotify:
  217264. {
  217265. updateBounds();
  217266. updateBorderSize();
  217267. handleMovedOrResized();
  217268. // if the native title bar is dragged, need to tell any active menus, etc.
  217269. if ((styleFlags & windowHasTitleBar) != 0
  217270. && component->isCurrentlyBlockedByAnotherModalComponent())
  217271. {
  217272. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  217273. if (currentModalComp != 0)
  217274. currentModalComp->inputAttemptWhenModal();
  217275. }
  217276. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  217277. if (confEvent->window == windowH
  217278. && confEvent->above != 0
  217279. && isFrontWindow())
  217280. {
  217281. handleBroughtToFront();
  217282. }
  217283. break;
  217284. }
  217285. case ReparentNotify:
  217286. {
  217287. parentWindow = 0;
  217288. Window wRoot = 0;
  217289. Window* wChild = 0;
  217290. unsigned int numChildren;
  217291. {
  217292. ScopedXLock xlock;
  217293. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  217294. }
  217295. if (parentWindow == windowH || parentWindow == wRoot)
  217296. parentWindow = 0;
  217297. updateBounds();
  217298. updateBorderSize();
  217299. handleMovedOrResized();
  217300. break;
  217301. }
  217302. case GravityNotify:
  217303. {
  217304. updateBounds();
  217305. updateBorderSize();
  217306. handleMovedOrResized();
  217307. break;
  217308. }
  217309. case MapNotify:
  217310. mapped = true;
  217311. handleBroughtToFront();
  217312. break;
  217313. case UnmapNotify:
  217314. mapped = false;
  217315. break;
  217316. case MappingNotify:
  217317. {
  217318. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  217319. if (mappingEvent->request != MappingPointer)
  217320. {
  217321. // Deal with modifier/keyboard mapping
  217322. ScopedXLock xlock;
  217323. XRefreshKeyboardMapping (mappingEvent);
  217324. updateModifierMappings();
  217325. }
  217326. break;
  217327. }
  217328. case ClientMessage:
  217329. {
  217330. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  217331. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  217332. {
  217333. const Atom atom = (Atom) clientMsg->data.l[0];
  217334. if (atom == Atoms::ProtocolList [Atoms::PING])
  217335. {
  217336. Window root = RootWindow (display, DefaultScreen (display));
  217337. event->xclient.window = root;
  217338. XSendEvent (display, root, False, NoEventMask, event);
  217339. XFlush (display);
  217340. }
  217341. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  217342. {
  217343. XWindowAttributes atts;
  217344. ScopedXLock xlock;
  217345. if (clientMsg->window != 0
  217346. && XGetWindowAttributes (display, clientMsg->window, &atts))
  217347. {
  217348. if (atts.map_state == IsViewable)
  217349. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  217350. }
  217351. }
  217352. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  217353. {
  217354. handleUserClosingWindow();
  217355. }
  217356. }
  217357. else if (clientMsg->message_type == Atoms::XdndEnter)
  217358. {
  217359. handleDragAndDropEnter (clientMsg);
  217360. }
  217361. else if (clientMsg->message_type == Atoms::XdndLeave)
  217362. {
  217363. resetDragAndDrop();
  217364. }
  217365. else if (clientMsg->message_type == Atoms::XdndPosition)
  217366. {
  217367. handleDragAndDropPosition (clientMsg);
  217368. }
  217369. else if (clientMsg->message_type == Atoms::XdndDrop)
  217370. {
  217371. handleDragAndDropDrop (clientMsg);
  217372. }
  217373. else if (clientMsg->message_type == Atoms::XdndStatus)
  217374. {
  217375. handleDragAndDropStatus (clientMsg);
  217376. }
  217377. else if (clientMsg->message_type == Atoms::XdndFinished)
  217378. {
  217379. resetDragAndDrop();
  217380. }
  217381. break;
  217382. }
  217383. case SelectionNotify:
  217384. handleDragAndDropSelection (event);
  217385. break;
  217386. case SelectionClear:
  217387. case SelectionRequest:
  217388. break;
  217389. default:
  217390. #if JUCE_USE_XSHM
  217391. {
  217392. ScopedXLock xlock;
  217393. if (event->xany.type == XShmGetEventBase (display))
  217394. repainter->notifyPaintCompleted();
  217395. }
  217396. #endif
  217397. break;
  217398. }
  217399. }
  217400. void showMouseCursor (Cursor cursor) throw()
  217401. {
  217402. ScopedXLock xlock;
  217403. XDefineCursor (display, windowH, cursor);
  217404. }
  217405. void setTaskBarIcon (const Image& image)
  217406. {
  217407. ScopedXLock xlock;
  217408. taskbarImage = image.createCopy();
  217409. Screen* const screen = XDefaultScreenOfDisplay (display);
  217410. const int screenNumber = XScreenNumberOfScreen (screen);
  217411. String screenAtom ("_NET_SYSTEM_TRAY_S");
  217412. screenAtom << screenNumber;
  217413. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  217414. XGrabServer (display);
  217415. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  217416. if (managerWin != None)
  217417. XSelectInput (display, managerWin, StructureNotifyMask);
  217418. XUngrabServer (display);
  217419. XFlush (display);
  217420. if (managerWin != None)
  217421. {
  217422. XEvent ev;
  217423. zerostruct (ev);
  217424. ev.xclient.type = ClientMessage;
  217425. ev.xclient.window = managerWin;
  217426. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  217427. ev.xclient.format = 32;
  217428. ev.xclient.data.l[0] = CurrentTime;
  217429. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  217430. ev.xclient.data.l[2] = windowH;
  217431. ev.xclient.data.l[3] = 0;
  217432. ev.xclient.data.l[4] = 0;
  217433. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  217434. XSync (display, False);
  217435. }
  217436. // For older KDE's ...
  217437. long atomData = 1;
  217438. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  217439. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  217440. // For more recent KDE's...
  217441. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  217442. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  217443. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  217444. XSizeHints* hints = XAllocSizeHints();
  217445. hints->flags = PMinSize;
  217446. hints->min_width = 22;
  217447. hints->min_height = 22;
  217448. XSetWMNormalHints (display, windowH, hints);
  217449. XFree (hints);
  217450. }
  217451. const Image* getTaskbarIcon() const throw() { return taskbarImage; }
  217452. juce_UseDebuggingNewOperator
  217453. bool dontRepaint;
  217454. static ModifierKeys currentModifiers;
  217455. static bool isActiveApplication;
  217456. private:
  217457. class LinuxRepaintManager : public Timer
  217458. {
  217459. public:
  217460. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  217461. : peer (peer_),
  217462. lastTimeImageUsed (0)
  217463. {
  217464. #if JUCE_USE_XSHM
  217465. shmCompletedDrawing = true;
  217466. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  217467. if (useARGBImagesForRendering)
  217468. {
  217469. ScopedXLock xlock;
  217470. XShmSegmentInfo segmentinfo;
  217471. XImage* const testImage
  217472. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  217473. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  217474. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  217475. XDestroyImage (testImage);
  217476. }
  217477. #endif
  217478. }
  217479. ~LinuxRepaintManager()
  217480. {
  217481. }
  217482. void timerCallback()
  217483. {
  217484. #if JUCE_USE_XSHM
  217485. if (! shmCompletedDrawing)
  217486. return;
  217487. #endif
  217488. if (! regionsNeedingRepaint.isEmpty())
  217489. {
  217490. stopTimer();
  217491. performAnyPendingRepaintsNow();
  217492. }
  217493. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  217494. {
  217495. stopTimer();
  217496. image = 0;
  217497. }
  217498. }
  217499. void repaint (int x, int y, int w, int h)
  217500. {
  217501. if (! isTimerRunning())
  217502. startTimer (repaintTimerPeriod);
  217503. regionsNeedingRepaint.add (x, y, w, h);
  217504. }
  217505. void performAnyPendingRepaintsNow()
  217506. {
  217507. #if JUCE_USE_XSHM
  217508. if (! shmCompletedDrawing)
  217509. {
  217510. startTimer (repaintTimerPeriod);
  217511. return;
  217512. }
  217513. #endif
  217514. peer->clearMaskedRegion();
  217515. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  217516. regionsNeedingRepaint.clear();
  217517. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  217518. if (! totalArea.isEmpty())
  217519. {
  217520. if (image == 0 || image->getWidth() < totalArea.getWidth()
  217521. || image->getHeight() < totalArea.getHeight())
  217522. {
  217523. #if JUCE_USE_XSHM
  217524. image = new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  217525. : Image::RGB,
  217526. #else
  217527. image = new XBitmapImage (Image::RGB,
  217528. #endif
  217529. (totalArea.getWidth() + 31) & ~31,
  217530. (totalArea.getHeight() + 31) & ~31,
  217531. false,
  217532. peer->depth,
  217533. peer->visual);
  217534. }
  217535. startTimer (repaintTimerPeriod);
  217536. RectangleList adjustedList (originalRepaintRegion);
  217537. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  217538. LowLevelGraphicsSoftwareRenderer context (*image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  217539. if (peer->depth == 32)
  217540. {
  217541. RectangleList::Iterator i (originalRepaintRegion);
  217542. while (i.next())
  217543. image->clear (*i.getRectangle() - totalArea.getPosition());
  217544. }
  217545. peer->handlePaint (context);
  217546. if (! peer->maskedRegion.isEmpty())
  217547. originalRepaintRegion.subtract (peer->maskedRegion);
  217548. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  217549. {
  217550. #if JUCE_USE_XSHM
  217551. shmCompletedDrawing = false;
  217552. #endif
  217553. const Rectangle<int>& r = *i.getRectangle();
  217554. image->blitToWindow (peer->windowH,
  217555. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  217556. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  217557. }
  217558. }
  217559. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  217560. startTimer (repaintTimerPeriod);
  217561. }
  217562. #if JUCE_USE_XSHM
  217563. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  217564. #endif
  217565. private:
  217566. enum { repaintTimerPeriod = 1000 / 100 };
  217567. LinuxComponentPeer* const peer;
  217568. ScopedPointer <XBitmapImage> image;
  217569. uint32 lastTimeImageUsed;
  217570. RectangleList regionsNeedingRepaint;
  217571. #if JUCE_USE_XSHM
  217572. bool useARGBImagesForRendering, shmCompletedDrawing;
  217573. #endif
  217574. LinuxRepaintManager (const LinuxRepaintManager&);
  217575. LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  217576. };
  217577. ScopedPointer <LinuxRepaintManager> repainter;
  217578. friend class LinuxRepaintManager;
  217579. Window windowH, parentWindow;
  217580. int wx, wy, ww, wh;
  217581. ScopedPointer<Image> taskbarImage;
  217582. bool fullScreen, mapped;
  217583. Visual* visual;
  217584. int depth;
  217585. BorderSize windowBorder;
  217586. struct MotifWmHints
  217587. {
  217588. unsigned long flags;
  217589. unsigned long functions;
  217590. unsigned long decorations;
  217591. long input_mode;
  217592. unsigned long status;
  217593. };
  217594. static void updateKeyStates (const int keycode, const bool press) throw()
  217595. {
  217596. const int keybyte = keycode >> 3;
  217597. const int keybit = (1 << (keycode & 7));
  217598. if (press)
  217599. Keys::keyStates [keybyte] |= keybit;
  217600. else
  217601. Keys::keyStates [keybyte] &= ~keybit;
  217602. }
  217603. static void updateKeyModifiers (const int status) throw()
  217604. {
  217605. int keyMods = 0;
  217606. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  217607. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  217608. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  217609. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  217610. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  217611. Keys::capsLock = ((status & LockMask) != 0);
  217612. }
  217613. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  217614. {
  217615. int modifier = 0;
  217616. bool isModifier = true;
  217617. switch (sym)
  217618. {
  217619. case XK_Shift_L:
  217620. case XK_Shift_R:
  217621. modifier = ModifierKeys::shiftModifier;
  217622. break;
  217623. case XK_Control_L:
  217624. case XK_Control_R:
  217625. modifier = ModifierKeys::ctrlModifier;
  217626. break;
  217627. case XK_Alt_L:
  217628. case XK_Alt_R:
  217629. modifier = ModifierKeys::altModifier;
  217630. break;
  217631. case XK_Num_Lock:
  217632. if (press)
  217633. Keys::numLock = ! Keys::numLock;
  217634. break;
  217635. case XK_Caps_Lock:
  217636. if (press)
  217637. Keys::capsLock = ! Keys::capsLock;
  217638. break;
  217639. case XK_Scroll_Lock:
  217640. break;
  217641. default:
  217642. isModifier = false;
  217643. break;
  217644. }
  217645. if (modifier != 0)
  217646. {
  217647. if (press)
  217648. currentModifiers = currentModifiers.withFlags (modifier);
  217649. else
  217650. currentModifiers = currentModifiers.withoutFlags (modifier);
  217651. }
  217652. return isModifier;
  217653. }
  217654. // Alt and Num lock are not defined by standard X
  217655. // modifier constants: check what they're mapped to
  217656. static void updateModifierMappings() throw()
  217657. {
  217658. ScopedXLock xlock;
  217659. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  217660. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  217661. Keys::AltMask = 0;
  217662. Keys::NumLockMask = 0;
  217663. XModifierKeymap* mapping = XGetModifierMapping (display);
  217664. if (mapping)
  217665. {
  217666. for (int i = 0; i < 8; i++)
  217667. {
  217668. if (mapping->modifiermap [i << 1] == altLeftCode)
  217669. Keys::AltMask = 1 << i;
  217670. else if (mapping->modifiermap [i << 1] == numLockCode)
  217671. Keys::NumLockMask = 1 << i;
  217672. }
  217673. XFreeModifiermap (mapping);
  217674. }
  217675. }
  217676. void removeWindowDecorations (Window wndH)
  217677. {
  217678. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  217679. if (hints != None)
  217680. {
  217681. MotifWmHints motifHints;
  217682. zerostruct (motifHints);
  217683. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  217684. motifHints.decorations = 0;
  217685. ScopedXLock xlock;
  217686. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  217687. (unsigned char*) &motifHints, 4);
  217688. }
  217689. hints = XInternAtom (display, "_WIN_HINTS", True);
  217690. if (hints != None)
  217691. {
  217692. long gnomeHints = 0;
  217693. ScopedXLock xlock;
  217694. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  217695. (unsigned char*) &gnomeHints, 1);
  217696. }
  217697. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  217698. if (hints != None)
  217699. {
  217700. long kwmHints = 2; /*KDE_tinyDecoration*/
  217701. ScopedXLock xlock;
  217702. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  217703. (unsigned char*) &kwmHints, 1);
  217704. }
  217705. }
  217706. void addWindowButtons (Window wndH)
  217707. {
  217708. ScopedXLock xlock;
  217709. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  217710. if (hints != None)
  217711. {
  217712. MotifWmHints motifHints;
  217713. zerostruct (motifHints);
  217714. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  217715. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  217716. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  217717. if ((styleFlags & windowHasCloseButton) != 0)
  217718. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  217719. if ((styleFlags & windowHasMinimiseButton) != 0)
  217720. {
  217721. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  217722. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  217723. }
  217724. if ((styleFlags & windowHasMaximiseButton) != 0)
  217725. {
  217726. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  217727. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  217728. }
  217729. if ((styleFlags & windowIsResizable) != 0)
  217730. {
  217731. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  217732. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  217733. }
  217734. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  217735. }
  217736. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  217737. if (hints != None)
  217738. {
  217739. int netHints [6];
  217740. int num = 0;
  217741. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", (styleFlags & windowIsResizable) ? True : False);
  217742. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", (styleFlags & windowHasMaximiseButton) ? True : False);
  217743. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", (styleFlags & windowHasMinimiseButton) ? True : False);
  217744. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", (styleFlags & windowHasCloseButton) ? True : False);
  217745. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace,
  217746. (unsigned char*) &netHints, num);
  217747. }
  217748. }
  217749. void setWindowType (Window wndH)
  217750. {
  217751. int netHints [2];
  217752. int numHints = 0;
  217753. if ((styleFlags & windowIsTemporary) != 0
  217754. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  217755. {
  217756. netHints [numHints] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  217757. }
  217758. else
  217759. {
  217760. netHints [numHints] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  217761. }
  217762. if (netHints [numHints] != 0)
  217763. ++numHints;
  217764. netHints[numHints] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  217765. if (netHints [numHints] != 0)
  217766. ++numHints;
  217767. XChangeProperty (display, wndH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  217768. (unsigned char*) &netHints, numHints);
  217769. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  217770. {
  217771. Atom skipTaskbar = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", False);
  217772. XChangeProperty (display, wndH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  217773. (unsigned char*) &skipTaskbar, 1);
  217774. }
  217775. }
  217776. void createWindow()
  217777. {
  217778. ScopedXLock xlock;
  217779. Atoms::initialiseAtoms();
  217780. resetDragAndDrop();
  217781. // Get defaults for various properties
  217782. const int screen = DefaultScreen (display);
  217783. Window root = RootWindow (display, screen);
  217784. // Try to obtain a 32-bit visual or fallback to 24 or 16
  217785. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  217786. if (visual == 0)
  217787. {
  217788. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  217789. Process::terminate();
  217790. }
  217791. // Create and install a colormap suitable fr our visual
  217792. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  217793. XInstallColormap (display, colormap);
  217794. // Set up the window attributes
  217795. XSetWindowAttributes swa;
  217796. swa.border_pixel = 0;
  217797. swa.background_pixmap = None;
  217798. swa.colormap = colormap;
  217799. swa.override_redirect = getComponent()->isAlwaysOnTop() ? True : False;
  217800. swa.event_mask = getAllEventsMask();
  217801. Window wndH = XCreateWindow (display, root,
  217802. 0, 0, 1, 1,
  217803. 0, depth, InputOutput, visual,
  217804. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask | CWOverrideRedirect,
  217805. &swa);
  217806. XGrabButton (display, AnyButton, AnyModifier, wndH, False,
  217807. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  217808. GrabModeAsync, GrabModeAsync, None, None);
  217809. // Set the window context to identify the window handle object
  217810. if (XSaveContext (display, (XID) wndH, windowHandleXContext, (XPointer) this))
  217811. {
  217812. // Failed
  217813. jassertfalse
  217814. Logger::outputDebugString ("Failed to create context information for window.\n");
  217815. XDestroyWindow (display, wndH);
  217816. wndH = 0;
  217817. }
  217818. // Set window manager hints
  217819. XWMHints* wmHints = XAllocWMHints();
  217820. wmHints->flags = InputHint | StateHint;
  217821. wmHints->input = True; // Locally active input model
  217822. wmHints->initial_state = NormalState;
  217823. XSetWMHints (display, wndH, wmHints);
  217824. XFree (wmHints);
  217825. // Set the window type
  217826. setWindowType (wndH);
  217827. // Define decoration
  217828. if ((styleFlags & windowHasTitleBar) == 0)
  217829. removeWindowDecorations (wndH);
  217830. else
  217831. addWindowButtons (wndH);
  217832. // Set window name
  217833. setWindowTitle (wndH, getComponent()->getName());
  217834. // Associate the PID, allowing to be shut down when something goes wrong
  217835. unsigned long pid = getpid();
  217836. XChangeProperty (display, wndH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  217837. (unsigned char*) &pid, 1);
  217838. // Set window manager protocols
  217839. XChangeProperty (display, wndH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  217840. (unsigned char*) Atoms::ProtocolList, 2);
  217841. // Set drag and drop flags
  217842. XChangeProperty (display, wndH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  217843. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  217844. XChangeProperty (display, wndH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  217845. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  217846. XChangeProperty (display, wndH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  217847. (const unsigned char*) "", 0);
  217848. unsigned long dndVersion = Atoms::DndVersion;
  217849. XChangeProperty (display, wndH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  217850. (const unsigned char*) &dndVersion, 1);
  217851. // Initialise the pointer and keyboard mapping
  217852. // This is not the same as the logical pointer mapping the X server uses:
  217853. // we don't mess with this.
  217854. static bool mappingInitialised = false;
  217855. if (! mappingInitialised)
  217856. {
  217857. mappingInitialised = true;
  217858. const int numButtons = XGetPointerMapping (display, 0, 0);
  217859. if (numButtons == 2)
  217860. {
  217861. pointerMap[0] = Keys::LeftButton;
  217862. pointerMap[1] = Keys::RightButton;
  217863. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  217864. }
  217865. else if (numButtons >= 3)
  217866. {
  217867. pointerMap[0] = Keys::LeftButton;
  217868. pointerMap[1] = Keys::MiddleButton;
  217869. pointerMap[2] = Keys::RightButton;
  217870. if (numButtons >= 5)
  217871. {
  217872. pointerMap[3] = Keys::WheelUp;
  217873. pointerMap[4] = Keys::WheelDown;
  217874. }
  217875. }
  217876. updateModifierMappings();
  217877. }
  217878. windowH = wndH;
  217879. }
  217880. void destroyWindow()
  217881. {
  217882. ScopedXLock xlock;
  217883. XPointer handlePointer;
  217884. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  217885. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  217886. XDestroyWindow (display, windowH);
  217887. // Wait for it to complete and then remove any events for this
  217888. // window from the event queue.
  217889. XSync (display, false);
  217890. XEvent event;
  217891. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  217892. {}
  217893. }
  217894. static int getAllEventsMask() throw()
  217895. {
  217896. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  217897. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  217898. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  217899. }
  217900. static int64 getEventTime (::Time t)
  217901. {
  217902. static int64 eventTimeOffset = 0x12345678;
  217903. const int64 thisMessageTime = t;
  217904. if (eventTimeOffset == 0x12345678)
  217905. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  217906. return eventTimeOffset + thisMessageTime;
  217907. }
  217908. static void setWindowTitle (Window xwin, const String& title)
  217909. {
  217910. XTextProperty nameProperty;
  217911. char* strings[] = { const_cast <char*> (title.toUTF8()) };
  217912. ScopedXLock xlock;
  217913. if (XStringListToTextProperty (strings, 1, &nameProperty))
  217914. {
  217915. XSetWMName (display, xwin, &nameProperty);
  217916. XSetWMIconName (display, xwin, &nameProperty);
  217917. XFree (nameProperty.value);
  217918. }
  217919. }
  217920. void updateBorderSize()
  217921. {
  217922. if ((styleFlags & windowHasTitleBar) == 0)
  217923. {
  217924. windowBorder = BorderSize (0);
  217925. }
  217926. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  217927. {
  217928. ScopedXLock xlock;
  217929. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  217930. if (hints != None)
  217931. {
  217932. unsigned char* data = 0;
  217933. unsigned long nitems, bytesLeft;
  217934. Atom actualType;
  217935. int actualFormat;
  217936. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  217937. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  217938. &data) == Success)
  217939. {
  217940. const unsigned long* const sizes = (const unsigned long*) data;
  217941. if (actualFormat == 32)
  217942. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  217943. (int) sizes[3], (int) sizes[1]);
  217944. XFree (data);
  217945. }
  217946. }
  217947. }
  217948. }
  217949. void updateBounds()
  217950. {
  217951. jassert (windowH != 0);
  217952. if (windowH != 0)
  217953. {
  217954. Window root, child;
  217955. unsigned int bw, depth;
  217956. ScopedXLock xlock;
  217957. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  217958. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  217959. &bw, &depth))
  217960. {
  217961. wx = wy = ww = wh = 0;
  217962. }
  217963. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  217964. {
  217965. wx = wy = 0;
  217966. }
  217967. }
  217968. }
  217969. void resetDragAndDrop()
  217970. {
  217971. dragAndDropFiles.clear();
  217972. lastDropPos = Point<int> (-1, -1);
  217973. dragAndDropCurrentMimeType = 0;
  217974. dragAndDropSourceWindow = 0;
  217975. srcMimeTypeAtomList.clear();
  217976. }
  217977. void sendDragAndDropMessage (XClientMessageEvent& msg)
  217978. {
  217979. msg.type = ClientMessage;
  217980. msg.display = display;
  217981. msg.window = dragAndDropSourceWindow;
  217982. msg.format = 32;
  217983. msg.data.l[0] = windowH;
  217984. ScopedXLock xlock;
  217985. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  217986. }
  217987. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  217988. {
  217989. XClientMessageEvent msg;
  217990. zerostruct (msg);
  217991. msg.message_type = Atoms::XdndStatus;
  217992. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  217993. msg.data.l[4] = dropAction;
  217994. sendDragAndDropMessage (msg);
  217995. }
  217996. void sendDragAndDropLeave()
  217997. {
  217998. XClientMessageEvent msg;
  217999. zerostruct (msg);
  218000. msg.message_type = Atoms::XdndLeave;
  218001. sendDragAndDropMessage (msg);
  218002. }
  218003. void sendDragAndDropFinish()
  218004. {
  218005. XClientMessageEvent msg;
  218006. zerostruct (msg);
  218007. msg.message_type = Atoms::XdndFinished;
  218008. sendDragAndDropMessage (msg);
  218009. }
  218010. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  218011. {
  218012. if ((clientMsg->data.l[1] & 1) == 0)
  218013. {
  218014. sendDragAndDropLeave();
  218015. if (dragAndDropFiles.size() > 0)
  218016. handleFileDragExit (dragAndDropFiles);
  218017. dragAndDropFiles.clear();
  218018. }
  218019. }
  218020. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  218021. {
  218022. if (dragAndDropSourceWindow == 0)
  218023. return;
  218024. dragAndDropSourceWindow = clientMsg->data.l[0];
  218025. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  218026. (int) clientMsg->data.l[2] & 0xffff);
  218027. dropPos -= getScreenPosition();
  218028. if (lastDropPos != dropPos)
  218029. {
  218030. lastDropPos = dropPos;
  218031. dragAndDropTimestamp = clientMsg->data.l[3];
  218032. Atom targetAction = Atoms::XdndActionCopy;
  218033. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  218034. {
  218035. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  218036. {
  218037. targetAction = Atoms::allowedActions[i];
  218038. break;
  218039. }
  218040. }
  218041. sendDragAndDropStatus (true, targetAction);
  218042. if (dragAndDropFiles.size() == 0)
  218043. updateDraggedFileList (clientMsg);
  218044. if (dragAndDropFiles.size() > 0)
  218045. handleFileDragMove (dragAndDropFiles, dropPos);
  218046. }
  218047. }
  218048. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  218049. {
  218050. if (dragAndDropFiles.size() == 0)
  218051. updateDraggedFileList (clientMsg);
  218052. const StringArray files (dragAndDropFiles);
  218053. const Point<int> lastPos (lastDropPos);
  218054. sendDragAndDropFinish();
  218055. resetDragAndDrop();
  218056. if (files.size() > 0)
  218057. handleFileDragDrop (files, lastPos);
  218058. }
  218059. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  218060. {
  218061. dragAndDropFiles.clear();
  218062. srcMimeTypeAtomList.clear();
  218063. dragAndDropCurrentMimeType = 0;
  218064. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  218065. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  218066. {
  218067. dragAndDropSourceWindow = 0;
  218068. return;
  218069. }
  218070. dragAndDropSourceWindow = clientMsg->data.l[0];
  218071. if ((clientMsg->data.l[1] & 1) != 0)
  218072. {
  218073. Atom actual;
  218074. int format;
  218075. unsigned long count = 0, remaining = 0;
  218076. unsigned char* data = 0;
  218077. ScopedXLock xlock;
  218078. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  218079. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  218080. &count, &remaining, &data);
  218081. if (data != 0)
  218082. {
  218083. if (actual == XA_ATOM && format == 32 && count != 0)
  218084. {
  218085. const unsigned long* const types = (const unsigned long*) data;
  218086. for (unsigned int i = 0; i < count; ++i)
  218087. if (types[i] != None)
  218088. srcMimeTypeAtomList.add (types[i]);
  218089. }
  218090. XFree (data);
  218091. }
  218092. }
  218093. if (srcMimeTypeAtomList.size() == 0)
  218094. {
  218095. for (int i = 2; i < 5; ++i)
  218096. if (clientMsg->data.l[i] != None)
  218097. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  218098. if (srcMimeTypeAtomList.size() == 0)
  218099. {
  218100. dragAndDropSourceWindow = 0;
  218101. return;
  218102. }
  218103. }
  218104. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  218105. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  218106. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  218107. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  218108. handleDragAndDropPosition (clientMsg);
  218109. }
  218110. void handleDragAndDropSelection (const XEvent* const evt)
  218111. {
  218112. dragAndDropFiles.clear();
  218113. if (evt->xselection.property != 0)
  218114. {
  218115. StringArray lines;
  218116. {
  218117. MemoryBlock dropData;
  218118. for (;;)
  218119. {
  218120. Atom actual;
  218121. uint8* data = 0;
  218122. unsigned long count = 0, remaining = 0;
  218123. int format = 0;
  218124. ScopedXLock xlock;
  218125. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  218126. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  218127. &format, &count, &remaining, &data) == Success)
  218128. {
  218129. dropData.append (data, count * format / 8);
  218130. XFree (data);
  218131. if (remaining == 0)
  218132. break;
  218133. }
  218134. else
  218135. {
  218136. XFree (data);
  218137. break;
  218138. }
  218139. }
  218140. lines.addLines (dropData.toString());
  218141. }
  218142. for (int i = 0; i < lines.size(); ++i)
  218143. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  218144. dragAndDropFiles.trim();
  218145. dragAndDropFiles.removeEmptyStrings();
  218146. }
  218147. }
  218148. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  218149. {
  218150. dragAndDropFiles.clear();
  218151. if (dragAndDropSourceWindow != None
  218152. && dragAndDropCurrentMimeType != 0)
  218153. {
  218154. dragAndDropTimestamp = clientMsg->data.l[2];
  218155. ScopedXLock xlock;
  218156. XConvertSelection (display,
  218157. Atoms::XdndSelection,
  218158. dragAndDropCurrentMimeType,
  218159. XInternAtom (display, "JXSelectionWindowProperty", 0),
  218160. windowH,
  218161. dragAndDropTimestamp);
  218162. }
  218163. }
  218164. StringArray dragAndDropFiles;
  218165. int dragAndDropTimestamp;
  218166. Point<int> lastDropPos;
  218167. Atom dragAndDropCurrentMimeType;
  218168. Window dragAndDropSourceWindow;
  218169. Array <Atom> srcMimeTypeAtomList;
  218170. static int pointerMap[5];
  218171. static Point<int> lastMousePos;
  218172. static void clearLastMousePos() throw()
  218173. {
  218174. lastMousePos = Point<int> (0x100000, 0x100000);
  218175. }
  218176. };
  218177. ModifierKeys LinuxComponentPeer::currentModifiers;
  218178. bool LinuxComponentPeer::isActiveApplication = false;
  218179. int LinuxComponentPeer::pointerMap[5];
  218180. Point<int> LinuxComponentPeer::lastMousePos;
  218181. bool Process::isForegroundProcess()
  218182. {
  218183. return LinuxComponentPeer::isActiveApplication;
  218184. }
  218185. void ModifierKeys::updateCurrentModifiers() throw()
  218186. {
  218187. currentModifiers = LinuxComponentPeer::currentModifiers;
  218188. }
  218189. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  218190. {
  218191. Window root, child;
  218192. int x, y, winx, winy;
  218193. unsigned int mask;
  218194. int mouseMods = 0;
  218195. ScopedXLock xlock;
  218196. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  218197. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  218198. {
  218199. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  218200. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  218201. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  218202. }
  218203. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  218204. return LinuxComponentPeer::currentModifiers;
  218205. }
  218206. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  218207. {
  218208. if (enableOrDisable)
  218209. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  218210. }
  218211. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  218212. {
  218213. return new LinuxComponentPeer (this, styleFlags);
  218214. }
  218215. // (this callback is hooked up in the messaging code)
  218216. void juce_windowMessageReceive (XEvent* event)
  218217. {
  218218. if (event->xany.window != None)
  218219. {
  218220. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  218221. if (ComponentPeer::isValidPeer (peer))
  218222. peer->handleWindowMessage (event);
  218223. }
  218224. else
  218225. {
  218226. switch (event->xany.type)
  218227. {
  218228. case KeymapNotify:
  218229. {
  218230. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  218231. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  218232. break;
  218233. }
  218234. default:
  218235. break;
  218236. }
  218237. }
  218238. }
  218239. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  218240. {
  218241. if (display == 0)
  218242. return;
  218243. #if JUCE_USE_XINERAMA
  218244. int major_opcode, first_event, first_error;
  218245. ScopedXLock xlock;
  218246. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  218247. {
  218248. typedef Bool (*tXineramaIsActive) (Display*);
  218249. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  218250. static tXineramaIsActive xXineramaIsActive = 0;
  218251. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  218252. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  218253. {
  218254. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  218255. if (h != 0)
  218256. {
  218257. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  218258. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  218259. }
  218260. }
  218261. if (xXineramaIsActive != 0
  218262. && xXineramaQueryScreens != 0
  218263. && xXineramaIsActive (display))
  218264. {
  218265. int numMonitors = 0;
  218266. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  218267. if (screens != 0)
  218268. {
  218269. for (int i = numMonitors; --i >= 0;)
  218270. {
  218271. int index = screens[i].screen_number;
  218272. if (index >= 0)
  218273. {
  218274. while (monitorCoords.size() < index)
  218275. monitorCoords.add (Rectangle<int>());
  218276. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  218277. screens[i].y_org,
  218278. screens[i].width,
  218279. screens[i].height));
  218280. }
  218281. }
  218282. XFree (screens);
  218283. }
  218284. }
  218285. }
  218286. if (monitorCoords.size() == 0)
  218287. #endif
  218288. {
  218289. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  218290. if (hints != None)
  218291. {
  218292. const int numMonitors = ScreenCount (display);
  218293. for (int i = 0; i < numMonitors; ++i)
  218294. {
  218295. Window root = RootWindow (display, i);
  218296. unsigned long nitems, bytesLeft;
  218297. Atom actualType;
  218298. int actualFormat;
  218299. unsigned char* data = 0;
  218300. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  218301. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  218302. &data) == Success)
  218303. {
  218304. const long* const position = (const long*) data;
  218305. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  218306. monitorCoords.add (Rectangle<int> (position[0], position[1],
  218307. position[2], position[3]));
  218308. XFree (data);
  218309. }
  218310. }
  218311. }
  218312. if (monitorCoords.size() == 0)
  218313. {
  218314. monitorCoords.add (Rectangle<int> (0, 0,
  218315. DisplayWidth (display, DefaultScreen (display)),
  218316. DisplayHeight (display, DefaultScreen (display))));
  218317. }
  218318. }
  218319. }
  218320. void Desktop::createMouseInputSources()
  218321. {
  218322. mouseSources.add (new MouseInputSource (0, true));
  218323. }
  218324. bool Desktop::canUseSemiTransparentWindows() throw()
  218325. {
  218326. int matchedDepth = 0;
  218327. const int desiredDepth = 32;
  218328. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  218329. && (matchedDepth == desiredDepth);
  218330. }
  218331. const Point<int> Desktop::getMousePosition()
  218332. {
  218333. Window root, child;
  218334. int x, y, winx, winy;
  218335. unsigned int mask;
  218336. ScopedXLock xlock;
  218337. if (XQueryPointer (display,
  218338. RootWindow (display, DefaultScreen (display)),
  218339. &root, &child,
  218340. &x, &y, &winx, &winy, &mask) == False)
  218341. {
  218342. // Pointer not on the default screen
  218343. x = y = -1;
  218344. }
  218345. return Point<int> (x, y);
  218346. }
  218347. void Desktop::setMousePosition (const Point<int>& newPosition)
  218348. {
  218349. ScopedXLock xlock;
  218350. Window root = RootWindow (display, DefaultScreen (display));
  218351. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  218352. }
  218353. static bool screenSaverAllowed = true;
  218354. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  218355. {
  218356. if (screenSaverAllowed != isEnabled)
  218357. {
  218358. screenSaverAllowed = isEnabled;
  218359. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  218360. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  218361. if (xScreenSaverSuspend == 0)
  218362. {
  218363. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  218364. if (h != 0)
  218365. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  218366. }
  218367. ScopedXLock xlock;
  218368. if (xScreenSaverSuspend != 0)
  218369. xScreenSaverSuspend (display, ! isEnabled);
  218370. }
  218371. }
  218372. bool Desktop::isScreenSaverEnabled() throw()
  218373. {
  218374. return screenSaverAllowed;
  218375. }
  218376. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  218377. {
  218378. ScopedXLock xlock;
  218379. const unsigned int imageW = image.getWidth();
  218380. const unsigned int imageH = image.getHeight();
  218381. #if JUCE_USE_XCURSOR
  218382. {
  218383. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  218384. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  218385. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  218386. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  218387. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  218388. static tXcursorImageCreate xXcursorImageCreate = 0;
  218389. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  218390. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  218391. static bool hasBeenLoaded = false;
  218392. if (! hasBeenLoaded)
  218393. {
  218394. hasBeenLoaded = true;
  218395. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  218396. if (h != 0)
  218397. {
  218398. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  218399. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  218400. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  218401. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  218402. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  218403. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  218404. || ! xXcursorSupportsARGB (display))
  218405. xXcursorSupportsARGB = 0;
  218406. }
  218407. }
  218408. if (xXcursorSupportsARGB != 0)
  218409. {
  218410. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  218411. if (xcImage != 0)
  218412. {
  218413. xcImage->xhot = hotspotX;
  218414. xcImage->yhot = hotspotY;
  218415. XcursorPixel* dest = xcImage->pixels;
  218416. for (int y = 0; y < (int) imageH; ++y)
  218417. for (int x = 0; x < (int) imageW; ++x)
  218418. *dest++ = image.getPixelAt (x, y).getARGB();
  218419. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  218420. xXcursorImageDestroy (xcImage);
  218421. if (result != 0)
  218422. return result;
  218423. }
  218424. }
  218425. }
  218426. #endif
  218427. Window root = RootWindow (display, DefaultScreen (display));
  218428. unsigned int cursorW, cursorH;
  218429. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  218430. return 0;
  218431. Image im (Image::ARGB, cursorW, cursorH, true);
  218432. {
  218433. Graphics g (im);
  218434. if (imageW > cursorW || imageH > cursorH)
  218435. {
  218436. hotspotX = (hotspotX * cursorW) / imageW;
  218437. hotspotY = (hotspotY * cursorH) / imageH;
  218438. g.drawImageWithin (&image, 0, 0, imageW, imageH,
  218439. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  218440. false);
  218441. }
  218442. else
  218443. {
  218444. g.drawImageAt (&image, 0, 0);
  218445. }
  218446. }
  218447. const int stride = (cursorW + 7) >> 3;
  218448. HeapBlock <char> maskPlane, sourcePlane;
  218449. maskPlane.calloc (stride * cursorH);
  218450. sourcePlane.calloc (stride * cursorH);
  218451. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  218452. for (int y = cursorH; --y >= 0;)
  218453. {
  218454. for (int x = cursorW; --x >= 0;)
  218455. {
  218456. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  218457. const int offset = y * stride + (x >> 3);
  218458. const Colour c (im.getPixelAt (x, y));
  218459. if (c.getAlpha() >= 128)
  218460. maskPlane[offset] |= mask;
  218461. if (c.getBrightness() >= 0.5f)
  218462. sourcePlane[offset] |= mask;
  218463. }
  218464. }
  218465. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  218466. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  218467. XColor white, black;
  218468. black.red = black.green = black.blue = 0;
  218469. white.red = white.green = white.blue = 0xffff;
  218470. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  218471. XFreePixmap (display, sourcePixmap);
  218472. XFreePixmap (display, maskPixmap);
  218473. return result;
  218474. }
  218475. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  218476. {
  218477. ScopedXLock xlock;
  218478. if (cursorHandle != 0)
  218479. XFreeCursor (display, (Cursor) cursorHandle);
  218480. }
  218481. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  218482. {
  218483. unsigned int shape;
  218484. switch (type)
  218485. {
  218486. case NormalCursor: return None; // Use parent cursor
  218487. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  218488. case WaitCursor: shape = XC_watch; break;
  218489. case IBeamCursor: shape = XC_xterm; break;
  218490. case PointingHandCursor: shape = XC_hand2; break;
  218491. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  218492. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  218493. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  218494. case TopEdgeResizeCursor: shape = XC_top_side; break;
  218495. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  218496. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  218497. case RightEdgeResizeCursor: shape = XC_right_side; break;
  218498. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  218499. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  218500. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  218501. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  218502. case CrosshairCursor: shape = XC_crosshair; break;
  218503. case DraggingHandCursor:
  218504. {
  218505. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  218506. 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,
  218507. 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 };
  218508. const int dragHandDataSize = 99;
  218509. const ScopedPointer <Image> im (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize));
  218510. return createMouseCursorFromImage (*im, 8, 7);
  218511. }
  218512. case CopyingCursor:
  218513. {
  218514. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  218515. 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,
  218516. 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,
  218517. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  218518. const int copyCursorSize = 119;
  218519. const ScopedPointer <Image> im (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize));
  218520. return createMouseCursorFromImage (*im, 1, 3);
  218521. }
  218522. default:
  218523. jassertfalse;
  218524. return None;
  218525. }
  218526. ScopedXLock xlock;
  218527. return (void*) XCreateFontCursor (display, shape);
  218528. }
  218529. void MouseCursor::showInWindow (ComponentPeer* peer) const
  218530. {
  218531. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  218532. if (lp != 0)
  218533. lp->showMouseCursor ((Cursor) getHandle());
  218534. }
  218535. void MouseCursor::showInAllWindows() const
  218536. {
  218537. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  218538. showInWindow (ComponentPeer::getPeer (i));
  218539. }
  218540. Image* juce_createIconForFile (const File& file)
  218541. {
  218542. return 0;
  218543. }
  218544. Image* Image::createNativeImage (const PixelFormat format, const int imageWidth, const int imageHeight, const bool clearImage)
  218545. {
  218546. return new Image (format, imageWidth, imageHeight, clearImage);
  218547. }
  218548. #if JUCE_OPENGL
  218549. class WindowedGLContext : public OpenGLContext
  218550. {
  218551. public:
  218552. WindowedGLContext (Component* const component,
  218553. const OpenGLPixelFormat& pixelFormat_,
  218554. GLXContext sharedContext)
  218555. : renderContext (0),
  218556. embeddedWindow (0),
  218557. pixelFormat (pixelFormat_)
  218558. {
  218559. jassert (component != 0);
  218560. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  218561. if (peer == 0)
  218562. return;
  218563. ScopedXLock xlock;
  218564. XSync (display, False);
  218565. GLint attribs [64];
  218566. int n = 0;
  218567. attribs[n++] = GLX_RGBA;
  218568. attribs[n++] = GLX_DOUBLEBUFFER;
  218569. attribs[n++] = GLX_RED_SIZE;
  218570. attribs[n++] = pixelFormat.redBits;
  218571. attribs[n++] = GLX_GREEN_SIZE;
  218572. attribs[n++] = pixelFormat.greenBits;
  218573. attribs[n++] = GLX_BLUE_SIZE;
  218574. attribs[n++] = pixelFormat.blueBits;
  218575. attribs[n++] = GLX_ALPHA_SIZE;
  218576. attribs[n++] = pixelFormat.alphaBits;
  218577. attribs[n++] = GLX_DEPTH_SIZE;
  218578. attribs[n++] = pixelFormat.depthBufferBits;
  218579. attribs[n++] = GLX_STENCIL_SIZE;
  218580. attribs[n++] = pixelFormat.stencilBufferBits;
  218581. attribs[n++] = GLX_ACCUM_RED_SIZE;
  218582. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  218583. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  218584. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  218585. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  218586. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  218587. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  218588. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  218589. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  218590. attribs[n++] = None;
  218591. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  218592. if (bestVisual == 0)
  218593. return;
  218594. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  218595. Window windowH = (Window) peer->getNativeHandle();
  218596. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  218597. XSetWindowAttributes swa;
  218598. swa.colormap = colourMap;
  218599. swa.border_pixel = 0;
  218600. swa.event_mask = ExposureMask | StructureNotifyMask;
  218601. embeddedWindow = XCreateWindow (display, windowH,
  218602. 0, 0, 1, 1, 0,
  218603. bestVisual->depth,
  218604. InputOutput,
  218605. bestVisual->visual,
  218606. CWBorderPixel | CWColormap | CWEventMask,
  218607. &swa);
  218608. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  218609. XMapWindow (display, embeddedWindow);
  218610. XFreeColormap (display, colourMap);
  218611. XFree (bestVisual);
  218612. XSync (display, False);
  218613. }
  218614. ~WindowedGLContext()
  218615. {
  218616. makeInactive();
  218617. ScopedXLock xlock;
  218618. glXDestroyContext (display, renderContext);
  218619. XUnmapWindow (display, embeddedWindow);
  218620. XDestroyWindow (display, embeddedWindow);
  218621. }
  218622. bool makeActive() const throw()
  218623. {
  218624. jassert (renderContext != 0);
  218625. ScopedXLock xlock;
  218626. return glXMakeCurrent (display, embeddedWindow, renderContext)
  218627. && XSync (display, False);
  218628. }
  218629. bool makeInactive() const throw()
  218630. {
  218631. ScopedXLock xlock;
  218632. return (! isActive()) || glXMakeCurrent (display, None, 0);
  218633. }
  218634. bool isActive() const throw()
  218635. {
  218636. ScopedXLock xlock;
  218637. return glXGetCurrentContext() == renderContext;
  218638. }
  218639. const OpenGLPixelFormat getPixelFormat() const
  218640. {
  218641. return pixelFormat;
  218642. }
  218643. void* getRawContext() const throw()
  218644. {
  218645. return renderContext;
  218646. }
  218647. void updateWindowPosition (int x, int y, int w, int h, int)
  218648. {
  218649. ScopedXLock xlock;
  218650. XMoveResizeWindow (display, embeddedWindow,
  218651. x, y, jmax (1, w), jmax (1, h));
  218652. }
  218653. void swapBuffers()
  218654. {
  218655. ScopedXLock xlock;
  218656. glXSwapBuffers (display, embeddedWindow);
  218657. }
  218658. bool setSwapInterval (const int numFramesPerSwap)
  218659. {
  218660. // xxx needs doing..
  218661. return false;
  218662. }
  218663. int getSwapInterval() const
  218664. {
  218665. // xxx needs doing..
  218666. return 0;
  218667. }
  218668. void repaint()
  218669. {
  218670. }
  218671. juce_UseDebuggingNewOperator
  218672. GLXContext renderContext;
  218673. private:
  218674. Window embeddedWindow;
  218675. OpenGLPixelFormat pixelFormat;
  218676. WindowedGLContext (const WindowedGLContext&);
  218677. WindowedGLContext& operator= (const WindowedGLContext&);
  218678. };
  218679. OpenGLContext* OpenGLComponent::createContext()
  218680. {
  218681. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  218682. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  218683. return (c->renderContext != 0) ? c.release() : 0;
  218684. }
  218685. void juce_glViewport (const int w, const int h)
  218686. {
  218687. glViewport (0, 0, w, h);
  218688. }
  218689. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  218690. OwnedArray <OpenGLPixelFormat>& results)
  218691. {
  218692. results.add (new OpenGLPixelFormat()); // xxx
  218693. }
  218694. #endif
  218695. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  218696. {
  218697. jassertfalse // not implemented!
  218698. return false;
  218699. }
  218700. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  218701. {
  218702. jassertfalse // not implemented!
  218703. return false;
  218704. }
  218705. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  218706. {
  218707. if (! isOnDesktop ())
  218708. addToDesktop (0);
  218709. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  218710. if (wp != 0)
  218711. {
  218712. wp->setTaskBarIcon (newImage);
  218713. setVisible (true);
  218714. toFront (false);
  218715. repaint();
  218716. }
  218717. }
  218718. void SystemTrayIconComponent::paint (Graphics& g)
  218719. {
  218720. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  218721. if (wp != 0)
  218722. {
  218723. const Image* const image = wp->getTaskbarIcon();
  218724. if (image != 0)
  218725. {
  218726. g.drawImageWithin (image, 0, 0, getWidth(), getHeight(),
  218727. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  218728. false);
  218729. }
  218730. }
  218731. }
  218732. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  218733. {
  218734. // xxx not yet implemented!
  218735. }
  218736. void PlatformUtilities::beep()
  218737. {
  218738. std::cout << "\a" << std::flush;
  218739. }
  218740. bool AlertWindow::showNativeDialogBox (const String& title,
  218741. const String& bodyText,
  218742. bool isOkCancel)
  218743. {
  218744. // use a non-native one for the time being..
  218745. if (isOkCancel)
  218746. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  218747. else
  218748. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  218749. return true;
  218750. }
  218751. const int KeyPress::spaceKey = XK_space & 0xff;
  218752. const int KeyPress::returnKey = XK_Return & 0xff;
  218753. const int KeyPress::escapeKey = XK_Escape & 0xff;
  218754. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  218755. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  218756. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  218757. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  218758. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  218759. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  218760. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  218761. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  218762. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  218763. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  218764. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  218765. const int KeyPress::tabKey = XK_Tab & 0xff;
  218766. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  218767. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  218768. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  218769. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  218770. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  218771. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  218772. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  218773. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  218774. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  218775. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  218776. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  218777. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  218778. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  218779. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  218780. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  218781. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  218782. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  218783. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  218784. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  218785. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  218786. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  218787. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  218788. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  218789. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  218790. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  218791. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  218792. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  218793. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  218794. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  218795. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  218796. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  218797. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  218798. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  218799. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  218800. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  218801. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  218802. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  218803. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  218804. #endif
  218805. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  218806. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  218807. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218808. // compiled on its own).
  218809. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  218810. static const int maxNumChans = 64;
  218811. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  218812. {
  218813. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  218814. snd_pcm_hw_params_t* hwParams;
  218815. snd_pcm_hw_params_alloca (&hwParams);
  218816. for (int i = 0; ratesToTry[i] != 0; ++i)
  218817. {
  218818. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  218819. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  218820. {
  218821. rates.addIfNotAlreadyThere (ratesToTry[i]);
  218822. }
  218823. }
  218824. }
  218825. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  218826. {
  218827. snd_pcm_hw_params_t *params;
  218828. snd_pcm_hw_params_alloca (&params);
  218829. if (snd_pcm_hw_params_any (handle, params) >= 0)
  218830. {
  218831. snd_pcm_hw_params_get_channels_min (params, minChans);
  218832. snd_pcm_hw_params_get_channels_max (params, maxChans);
  218833. }
  218834. }
  218835. static void getDeviceProperties (const String& deviceID,
  218836. unsigned int& minChansOut,
  218837. unsigned int& maxChansOut,
  218838. unsigned int& minChansIn,
  218839. unsigned int& maxChansIn,
  218840. Array <int>& rates)
  218841. {
  218842. if (deviceID.isEmpty())
  218843. return;
  218844. snd_ctl_t* handle;
  218845. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  218846. {
  218847. snd_pcm_info_t* info;
  218848. snd_pcm_info_alloca (&info);
  218849. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  218850. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  218851. snd_pcm_info_set_subdevice (info, 0);
  218852. if (snd_ctl_pcm_info (handle, info) >= 0)
  218853. {
  218854. snd_pcm_t* pcmHandle;
  218855. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  218856. {
  218857. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  218858. getDeviceSampleRates (pcmHandle, rates);
  218859. snd_pcm_close (pcmHandle);
  218860. }
  218861. }
  218862. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  218863. if (snd_ctl_pcm_info (handle, info) >= 0)
  218864. {
  218865. snd_pcm_t* pcmHandle;
  218866. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  218867. {
  218868. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  218869. if (rates.size() == 0)
  218870. getDeviceSampleRates (pcmHandle, rates);
  218871. snd_pcm_close (pcmHandle);
  218872. }
  218873. }
  218874. snd_ctl_close (handle);
  218875. }
  218876. }
  218877. class ALSADevice
  218878. {
  218879. public:
  218880. ALSADevice (const String& deviceID,
  218881. const bool forInput)
  218882. : handle (0),
  218883. bitDepth (16),
  218884. numChannelsRunning (0),
  218885. isInput (forInput),
  218886. sampleFormat (AudioDataConverters::int16LE)
  218887. {
  218888. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  218889. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  218890. SND_PCM_ASYNC));
  218891. }
  218892. ~ALSADevice()
  218893. {
  218894. if (handle != 0)
  218895. snd_pcm_close (handle);
  218896. }
  218897. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  218898. {
  218899. if (handle == 0)
  218900. return false;
  218901. snd_pcm_hw_params_t* hwParams;
  218902. snd_pcm_hw_params_alloca (&hwParams);
  218903. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  218904. return false;
  218905. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  218906. isInterleaved = false;
  218907. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  218908. isInterleaved = true;
  218909. else
  218910. {
  218911. jassertfalse
  218912. return false;
  218913. }
  218914. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32, AudioDataConverters::float32LE,
  218915. SND_PCM_FORMAT_FLOAT_BE, 32, AudioDataConverters::float32BE,
  218916. SND_PCM_FORMAT_S32_LE, 32, AudioDataConverters::int32LE,
  218917. SND_PCM_FORMAT_S32_BE, 32, AudioDataConverters::int32BE,
  218918. SND_PCM_FORMAT_S24_3LE, 24, AudioDataConverters::int24LE,
  218919. SND_PCM_FORMAT_S24_3BE, 24, AudioDataConverters::int24BE,
  218920. SND_PCM_FORMAT_S16_LE, 16, AudioDataConverters::int16LE,
  218921. SND_PCM_FORMAT_S16_BE, 16, AudioDataConverters::int16BE };
  218922. bitDepth = 0;
  218923. for (int i = 0; i < numElementsInArray (formatsToTry); i += 3)
  218924. {
  218925. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  218926. {
  218927. bitDepth = formatsToTry [i + 1];
  218928. sampleFormat = (AudioDataConverters::DataFormat) formatsToTry [i + 2];
  218929. break;
  218930. }
  218931. }
  218932. if (bitDepth == 0)
  218933. {
  218934. error = "device doesn't support a compatible PCM format";
  218935. DBG ("ALSA error: " + error + "\n");
  218936. return false;
  218937. }
  218938. int dir = 0;
  218939. unsigned int periods = 4;
  218940. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  218941. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  218942. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  218943. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  218944. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  218945. || failed (snd_pcm_hw_params (handle, hwParams)))
  218946. {
  218947. return false;
  218948. }
  218949. snd_pcm_sw_params_t* swParams;
  218950. snd_pcm_sw_params_alloca (&swParams);
  218951. snd_pcm_uframes_t boundary;
  218952. if (failed (snd_pcm_sw_params_current (handle, swParams))
  218953. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  218954. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  218955. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  218956. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  218957. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  218958. || failed (snd_pcm_sw_params (handle, swParams)))
  218959. {
  218960. return false;
  218961. }
  218962. /*
  218963. #if JUCE_DEBUG
  218964. // enable this to dump the config of the devices that get opened
  218965. snd_output_t* out;
  218966. snd_output_stdio_attach (&out, stderr, 0);
  218967. snd_pcm_hw_params_dump (hwParams, out);
  218968. snd_pcm_sw_params_dump (swParams, out);
  218969. #endif
  218970. */
  218971. numChannelsRunning = numChannels;
  218972. return true;
  218973. }
  218974. bool write (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  218975. {
  218976. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  218977. float** const data = outputChannelBuffer.getArrayOfChannels();
  218978. if (isInterleaved)
  218979. {
  218980. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  218981. float* interleaved = static_cast <float*> (scratch.getData());
  218982. AudioDataConverters::interleaveSamples ((const float**) data, interleaved, numSamples, numChannelsRunning);
  218983. AudioDataConverters::convertFloatToFormat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  218984. snd_pcm_sframes_t num = snd_pcm_writei (handle, interleaved, numSamples);
  218985. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  218986. return false;
  218987. }
  218988. else
  218989. {
  218990. for (int i = 0; i < numChannelsRunning; ++i)
  218991. if (data[i] != 0)
  218992. AudioDataConverters::convertFloatToFormat (sampleFormat, data[i], data[i], numSamples);
  218993. snd_pcm_sframes_t num = snd_pcm_writen (handle, (void**) data, numSamples);
  218994. if (failed (num))
  218995. {
  218996. if (num == -EPIPE)
  218997. {
  218998. if (failed (snd_pcm_prepare (handle)))
  218999. return false;
  219000. }
  219001. else if (num != -ESTRPIPE)
  219002. return false;
  219003. }
  219004. }
  219005. return true;
  219006. }
  219007. bool read (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  219008. {
  219009. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  219010. float** const data = inputChannelBuffer.getArrayOfChannels();
  219011. if (isInterleaved)
  219012. {
  219013. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  219014. float* interleaved = static_cast <float*> (scratch.getData());
  219015. snd_pcm_sframes_t num = snd_pcm_readi (handle, interleaved, numSamples);
  219016. if (failed (num))
  219017. {
  219018. if (num == -EPIPE)
  219019. {
  219020. if (failed (snd_pcm_prepare (handle)))
  219021. return false;
  219022. }
  219023. else if (num != -ESTRPIPE)
  219024. return false;
  219025. }
  219026. AudioDataConverters::convertFormatToFloat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  219027. AudioDataConverters::deinterleaveSamples (interleaved, data, numSamples, numChannelsRunning);
  219028. }
  219029. else
  219030. {
  219031. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  219032. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  219033. return false;
  219034. for (int i = 0; i < numChannelsRunning; ++i)
  219035. if (data[i] != 0)
  219036. AudioDataConverters::convertFormatToFloat (sampleFormat, data[i], data[i], numSamples);
  219037. }
  219038. return true;
  219039. }
  219040. juce_UseDebuggingNewOperator
  219041. snd_pcm_t* handle;
  219042. String error;
  219043. int bitDepth, numChannelsRunning;
  219044. private:
  219045. const bool isInput;
  219046. bool isInterleaved;
  219047. MemoryBlock scratch;
  219048. AudioDataConverters::DataFormat sampleFormat;
  219049. bool failed (const int errorNum)
  219050. {
  219051. if (errorNum >= 0)
  219052. return false;
  219053. error = snd_strerror (errorNum);
  219054. DBG ("ALSA error: " + error + "\n");
  219055. return true;
  219056. }
  219057. };
  219058. class ALSAThread : public Thread
  219059. {
  219060. public:
  219061. ALSAThread (const String& inputId_,
  219062. const String& outputId_)
  219063. : Thread ("Juce ALSA"),
  219064. sampleRate (0),
  219065. bufferSize (0),
  219066. callback (0),
  219067. inputId (inputId_),
  219068. outputId (outputId_),
  219069. outputDevice (0),
  219070. inputDevice (0),
  219071. numCallbacks (0),
  219072. inputChannelBuffer (1, 1),
  219073. outputChannelBuffer (1, 1)
  219074. {
  219075. initialiseRatesAndChannels();
  219076. }
  219077. ~ALSAThread()
  219078. {
  219079. close();
  219080. }
  219081. void open (BigInteger inputChannels,
  219082. BigInteger outputChannels,
  219083. const double sampleRate_,
  219084. const int bufferSize_)
  219085. {
  219086. close();
  219087. error = String::empty;
  219088. sampleRate = sampleRate_;
  219089. bufferSize = bufferSize_;
  219090. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  219091. inputChannelBuffer.clear();
  219092. inputChannelDataForCallback.clear();
  219093. currentInputChans.clear();
  219094. if (inputChannels.getHighestBit() >= 0)
  219095. {
  219096. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  219097. {
  219098. if (inputChannels[i])
  219099. {
  219100. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  219101. currentInputChans.setBit (i);
  219102. }
  219103. }
  219104. }
  219105. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  219106. outputChannelBuffer.clear();
  219107. outputChannelDataForCallback.clear();
  219108. currentOutputChans.clear();
  219109. if (outputChannels.getHighestBit() >= 0)
  219110. {
  219111. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  219112. {
  219113. if (outputChannels[i])
  219114. {
  219115. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  219116. currentOutputChans.setBit (i);
  219117. }
  219118. }
  219119. }
  219120. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  219121. {
  219122. outputDevice = new ALSADevice (outputId, false);
  219123. if (outputDevice->error.isNotEmpty())
  219124. {
  219125. error = outputDevice->error;
  219126. deleteAndZero (outputDevice);
  219127. return;
  219128. }
  219129. currentOutputChans.setRange (0, minChansOut, true);
  219130. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  219131. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  219132. bufferSize))
  219133. {
  219134. error = outputDevice->error;
  219135. deleteAndZero (outputDevice);
  219136. return;
  219137. }
  219138. }
  219139. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  219140. {
  219141. inputDevice = new ALSADevice (inputId, true);
  219142. if (inputDevice->error.isNotEmpty())
  219143. {
  219144. error = inputDevice->error;
  219145. deleteAndZero (inputDevice);
  219146. return;
  219147. }
  219148. currentInputChans.setRange (0, minChansIn, true);
  219149. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  219150. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  219151. bufferSize))
  219152. {
  219153. error = inputDevice->error;
  219154. deleteAndZero (inputDevice);
  219155. return;
  219156. }
  219157. }
  219158. if (outputDevice == 0 && inputDevice == 0)
  219159. {
  219160. error = "no channels";
  219161. return;
  219162. }
  219163. if (outputDevice != 0 && inputDevice != 0)
  219164. {
  219165. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  219166. }
  219167. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  219168. return;
  219169. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  219170. return;
  219171. startThread (9);
  219172. int count = 1000;
  219173. while (numCallbacks == 0)
  219174. {
  219175. sleep (5);
  219176. if (--count < 0 || ! isThreadRunning())
  219177. {
  219178. error = "device didn't start";
  219179. break;
  219180. }
  219181. }
  219182. }
  219183. void close()
  219184. {
  219185. stopThread (6000);
  219186. deleteAndZero (inputDevice);
  219187. deleteAndZero (outputDevice);
  219188. inputChannelBuffer.setSize (1, 1);
  219189. outputChannelBuffer.setSize (1, 1);
  219190. numCallbacks = 0;
  219191. }
  219192. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  219193. {
  219194. const ScopedLock sl (callbackLock);
  219195. callback = newCallback;
  219196. }
  219197. void run()
  219198. {
  219199. while (! threadShouldExit())
  219200. {
  219201. if (inputDevice != 0)
  219202. {
  219203. if (! inputDevice->read (inputChannelBuffer, bufferSize))
  219204. {
  219205. DBG ("ALSA: read failure");
  219206. break;
  219207. }
  219208. }
  219209. if (threadShouldExit())
  219210. break;
  219211. {
  219212. const ScopedLock sl (callbackLock);
  219213. ++numCallbacks;
  219214. if (callback != 0)
  219215. {
  219216. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  219217. inputChannelDataForCallback.size(),
  219218. outputChannelDataForCallback.getRawDataPointer(),
  219219. outputChannelDataForCallback.size(),
  219220. bufferSize);
  219221. }
  219222. else
  219223. {
  219224. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  219225. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  219226. }
  219227. }
  219228. if (outputDevice != 0)
  219229. {
  219230. failed (snd_pcm_wait (outputDevice->handle, 2000));
  219231. if (threadShouldExit())
  219232. break;
  219233. failed (snd_pcm_avail_update (outputDevice->handle));
  219234. if (! outputDevice->write (outputChannelBuffer, bufferSize))
  219235. {
  219236. DBG ("ALSA: write failure");
  219237. break;
  219238. }
  219239. }
  219240. }
  219241. }
  219242. int getBitDepth() const throw()
  219243. {
  219244. if (outputDevice != 0)
  219245. return outputDevice->bitDepth;
  219246. if (inputDevice != 0)
  219247. return inputDevice->bitDepth;
  219248. return 16;
  219249. }
  219250. juce_UseDebuggingNewOperator
  219251. String error;
  219252. double sampleRate;
  219253. int bufferSize;
  219254. BigInteger currentInputChans, currentOutputChans;
  219255. Array <int> sampleRates;
  219256. StringArray channelNamesOut, channelNamesIn;
  219257. AudioIODeviceCallback* callback;
  219258. private:
  219259. const String inputId, outputId;
  219260. ALSADevice* outputDevice;
  219261. ALSADevice* inputDevice;
  219262. int numCallbacks;
  219263. CriticalSection callbackLock;
  219264. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  219265. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  219266. unsigned int minChansOut, maxChansOut;
  219267. unsigned int minChansIn, maxChansIn;
  219268. bool failed (const int errorNum) throw()
  219269. {
  219270. if (errorNum >= 0)
  219271. return false;
  219272. error = snd_strerror (errorNum);
  219273. DBG ("ALSA error: " + error + "\n");
  219274. return true;
  219275. }
  219276. void initialiseRatesAndChannels() throw()
  219277. {
  219278. sampleRates.clear();
  219279. channelNamesOut.clear();
  219280. channelNamesIn.clear();
  219281. minChansOut = 0;
  219282. maxChansOut = 0;
  219283. minChansIn = 0;
  219284. maxChansIn = 0;
  219285. unsigned int dummy = 0;
  219286. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  219287. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  219288. unsigned int i;
  219289. for (i = 0; i < maxChansOut; ++i)
  219290. channelNamesOut.add ("channel " + String ((int) i + 1));
  219291. for (i = 0; i < maxChansIn; ++i)
  219292. channelNamesIn.add ("channel " + String ((int) i + 1));
  219293. }
  219294. };
  219295. class ALSAAudioIODevice : public AudioIODevice
  219296. {
  219297. public:
  219298. ALSAAudioIODevice (const String& deviceName,
  219299. const String& inputId_,
  219300. const String& outputId_)
  219301. : AudioIODevice (deviceName, "ALSA"),
  219302. inputId (inputId_),
  219303. outputId (outputId_),
  219304. isOpen_ (false),
  219305. isStarted (false),
  219306. internal (new ALSAThread (inputId_, outputId_))
  219307. {
  219308. }
  219309. ~ALSAAudioIODevice()
  219310. {
  219311. }
  219312. const StringArray getOutputChannelNames()
  219313. {
  219314. return internal->channelNamesOut;
  219315. }
  219316. const StringArray getInputChannelNames()
  219317. {
  219318. return internal->channelNamesIn;
  219319. }
  219320. int getNumSampleRates()
  219321. {
  219322. return internal->sampleRates.size();
  219323. }
  219324. double getSampleRate (int index)
  219325. {
  219326. return internal->sampleRates [index];
  219327. }
  219328. int getNumBufferSizesAvailable()
  219329. {
  219330. return 50;
  219331. }
  219332. int getBufferSizeSamples (int index)
  219333. {
  219334. int n = 16;
  219335. for (int i = 0; i < index; ++i)
  219336. n += n < 64 ? 16
  219337. : (n < 512 ? 32
  219338. : (n < 1024 ? 64
  219339. : (n < 2048 ? 128 : 256)));
  219340. return n;
  219341. }
  219342. int getDefaultBufferSize()
  219343. {
  219344. return 512;
  219345. }
  219346. const String open (const BigInteger& inputChannels,
  219347. const BigInteger& outputChannels,
  219348. double sampleRate,
  219349. int bufferSizeSamples)
  219350. {
  219351. close();
  219352. if (bufferSizeSamples <= 0)
  219353. bufferSizeSamples = getDefaultBufferSize();
  219354. if (sampleRate <= 0)
  219355. {
  219356. for (int i = 0; i < getNumSampleRates(); ++i)
  219357. {
  219358. if (getSampleRate (i) >= 44100)
  219359. {
  219360. sampleRate = getSampleRate (i);
  219361. break;
  219362. }
  219363. }
  219364. }
  219365. internal->open (inputChannels, outputChannels,
  219366. sampleRate, bufferSizeSamples);
  219367. isOpen_ = internal->error.isEmpty();
  219368. return internal->error;
  219369. }
  219370. void close()
  219371. {
  219372. stop();
  219373. internal->close();
  219374. isOpen_ = false;
  219375. }
  219376. bool isOpen()
  219377. {
  219378. return isOpen_;
  219379. }
  219380. int getCurrentBufferSizeSamples()
  219381. {
  219382. return internal->bufferSize;
  219383. }
  219384. double getCurrentSampleRate()
  219385. {
  219386. return internal->sampleRate;
  219387. }
  219388. int getCurrentBitDepth()
  219389. {
  219390. return internal->getBitDepth();
  219391. }
  219392. const BigInteger getActiveOutputChannels() const
  219393. {
  219394. return internal->currentOutputChans;
  219395. }
  219396. const BigInteger getActiveInputChannels() const
  219397. {
  219398. return internal->currentInputChans;
  219399. }
  219400. int getOutputLatencyInSamples()
  219401. {
  219402. return 0;
  219403. }
  219404. int getInputLatencyInSamples()
  219405. {
  219406. return 0;
  219407. }
  219408. void start (AudioIODeviceCallback* callback)
  219409. {
  219410. if (! isOpen_)
  219411. callback = 0;
  219412. internal->setCallback (callback);
  219413. if (callback != 0)
  219414. callback->audioDeviceAboutToStart (this);
  219415. isStarted = (callback != 0);
  219416. }
  219417. void stop()
  219418. {
  219419. AudioIODeviceCallback* const oldCallback = internal->callback;
  219420. start (0);
  219421. if (oldCallback != 0)
  219422. oldCallback->audioDeviceStopped();
  219423. }
  219424. bool isPlaying()
  219425. {
  219426. return isStarted && internal->error.isEmpty();
  219427. }
  219428. const String getLastError()
  219429. {
  219430. return internal->error;
  219431. }
  219432. String inputId, outputId;
  219433. private:
  219434. bool isOpen_, isStarted;
  219435. ScopedPointer<ALSAThread> internal;
  219436. };
  219437. class ALSAAudioIODeviceType : public AudioIODeviceType
  219438. {
  219439. public:
  219440. ALSAAudioIODeviceType()
  219441. : AudioIODeviceType ("ALSA"),
  219442. hasScanned (false)
  219443. {
  219444. }
  219445. ~ALSAAudioIODeviceType()
  219446. {
  219447. }
  219448. void scanForDevices()
  219449. {
  219450. if (hasScanned)
  219451. return;
  219452. hasScanned = true;
  219453. inputNames.clear();
  219454. inputIds.clear();
  219455. outputNames.clear();
  219456. outputIds.clear();
  219457. snd_ctl_t* handle;
  219458. snd_ctl_card_info_t* info;
  219459. snd_ctl_card_info_alloca (&info);
  219460. int cardNum = -1;
  219461. while (outputIds.size() + inputIds.size() <= 32)
  219462. {
  219463. snd_card_next (&cardNum);
  219464. if (cardNum < 0)
  219465. break;
  219466. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  219467. {
  219468. if (snd_ctl_card_info (handle, info) >= 0)
  219469. {
  219470. String cardId (snd_ctl_card_info_get_id (info));
  219471. if (cardId.removeCharacters ("0123456789").isEmpty())
  219472. cardId = String (cardNum);
  219473. int device = -1;
  219474. for (;;)
  219475. {
  219476. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  219477. break;
  219478. String id, name;
  219479. id << "hw:" << cardId << ',' << device;
  219480. bool isInput, isOutput;
  219481. if (testDevice (id, isInput, isOutput))
  219482. {
  219483. name << snd_ctl_card_info_get_name (info);
  219484. if (name.isEmpty())
  219485. name = id;
  219486. if (isInput)
  219487. {
  219488. inputNames.add (name);
  219489. inputIds.add (id);
  219490. }
  219491. if (isOutput)
  219492. {
  219493. outputNames.add (name);
  219494. outputIds.add (id);
  219495. }
  219496. }
  219497. }
  219498. }
  219499. snd_ctl_close (handle);
  219500. }
  219501. }
  219502. inputNames.appendNumbersToDuplicates (false, true);
  219503. outputNames.appendNumbersToDuplicates (false, true);
  219504. }
  219505. const StringArray getDeviceNames (bool wantInputNames) const
  219506. {
  219507. jassert (hasScanned); // need to call scanForDevices() before doing this
  219508. return wantInputNames ? inputNames : outputNames;
  219509. }
  219510. int getDefaultDeviceIndex (bool forInput) const
  219511. {
  219512. jassert (hasScanned); // need to call scanForDevices() before doing this
  219513. return 0;
  219514. }
  219515. bool hasSeparateInputsAndOutputs() const { return true; }
  219516. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  219517. {
  219518. jassert (hasScanned); // need to call scanForDevices() before doing this
  219519. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  219520. if (d == 0)
  219521. return -1;
  219522. return asInput ? inputIds.indexOf (d->inputId)
  219523. : outputIds.indexOf (d->outputId);
  219524. }
  219525. AudioIODevice* createDevice (const String& outputDeviceName,
  219526. const String& inputDeviceName)
  219527. {
  219528. jassert (hasScanned); // need to call scanForDevices() before doing this
  219529. const int inputIndex = inputNames.indexOf (inputDeviceName);
  219530. const int outputIndex = outputNames.indexOf (outputDeviceName);
  219531. String deviceName (outputIndex >= 0 ? outputDeviceName
  219532. : inputDeviceName);
  219533. if (inputIndex >= 0 || outputIndex >= 0)
  219534. return new ALSAAudioIODevice (deviceName,
  219535. inputIds [inputIndex],
  219536. outputIds [outputIndex]);
  219537. return 0;
  219538. }
  219539. juce_UseDebuggingNewOperator
  219540. private:
  219541. StringArray inputNames, outputNames, inputIds, outputIds;
  219542. bool hasScanned;
  219543. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  219544. {
  219545. unsigned int minChansOut = 0, maxChansOut = 0;
  219546. unsigned int minChansIn = 0, maxChansIn = 0;
  219547. Array <int> rates;
  219548. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  219549. DBG ("ALSA device: " + id
  219550. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  219551. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  219552. + " rates=" + String (rates.size()));
  219553. isInput = maxChansIn > 0;
  219554. isOutput = maxChansOut > 0;
  219555. return (isInput || isOutput) && rates.size() > 0;
  219556. }
  219557. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  219558. ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  219559. };
  219560. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  219561. {
  219562. return new ALSAAudioIODeviceType();
  219563. }
  219564. #endif
  219565. /*** End of inlined file: juce_linux_Audio.cpp ***/
  219566. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  219567. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219568. // compiled on its own).
  219569. #ifdef JUCE_INCLUDED_FILE
  219570. #if JUCE_JACK
  219571. static void* juce_libjack_handle = 0;
  219572. void* juce_load_jack_function (const char* const name)
  219573. {
  219574. if (juce_libjack_handle == 0)
  219575. return 0;
  219576. return dlsym (juce_libjack_handle, name);
  219577. }
  219578. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  219579. typedef return_type (*fn_name##_ptr_t)argument_types; \
  219580. return_type fn_name argument_types { \
  219581. static fn_name##_ptr_t fn = 0; \
  219582. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  219583. if (fn) return (*fn)arguments; \
  219584. else return 0; \
  219585. }
  219586. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  219587. typedef void (*fn_name##_ptr_t)argument_types; \
  219588. void fn_name argument_types { \
  219589. static fn_name##_ptr_t fn = 0; \
  219590. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  219591. if (fn) (*fn)arguments; \
  219592. }
  219593. 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));
  219594. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  219595. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  219596. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  219597. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  219598. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  219599. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  219600. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  219601. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  219602. 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));
  219603. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  219604. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  219605. 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));
  219606. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  219607. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  219608. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  219609. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  219610. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  219611. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  219612. #if JUCE_DEBUG
  219613. #define JACK_LOGGING_ENABLED 1
  219614. #endif
  219615. #if JACK_LOGGING_ENABLED
  219616. static void jack_Log (const String& s)
  219617. {
  219618. std::cerr << s << std::endl;
  219619. }
  219620. static void dumpJackErrorMessage (const jack_status_t status) throw()
  219621. {
  219622. if (status & JackServerFailed || status & JackServerError)
  219623. jack_Log ("Unable to connect to JACK server");
  219624. if (status & JackVersionError)
  219625. jack_Log ("Client's protocol version does not match");
  219626. if (status & JackInvalidOption)
  219627. jack_Log ("The operation contained an invalid or unsupported option");
  219628. if (status & JackNameNotUnique)
  219629. jack_Log ("The desired client name was not unique");
  219630. if (status & JackNoSuchClient)
  219631. jack_Log ("Requested client does not exist");
  219632. if (status & JackInitFailure)
  219633. jack_Log ("Unable to initialize client");
  219634. }
  219635. #else
  219636. #define dumpJackErrorMessage(a) {}
  219637. #define jack_Log(...) {}
  219638. #endif
  219639. #ifndef JUCE_JACK_CLIENT_NAME
  219640. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  219641. #endif
  219642. class JackAudioIODevice : public AudioIODevice
  219643. {
  219644. public:
  219645. JackAudioIODevice (const String& deviceName,
  219646. const String& inputId_,
  219647. const String& outputId_)
  219648. : AudioIODevice (deviceName, "JACK"),
  219649. inputId (inputId_),
  219650. outputId (outputId_),
  219651. isOpen_ (false),
  219652. callback (0),
  219653. totalNumberOfInputChannels (0),
  219654. totalNumberOfOutputChannels (0)
  219655. {
  219656. jassert (deviceName.isNotEmpty());
  219657. jack_status_t status;
  219658. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  219659. if (client == 0)
  219660. {
  219661. dumpJackErrorMessage (status);
  219662. }
  219663. else
  219664. {
  219665. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  219666. // open input ports
  219667. const StringArray inputChannels (getInputChannelNames());
  219668. for (int i = 0; i < inputChannels.size(); i++)
  219669. {
  219670. String inputName;
  219671. inputName << "in_" << ++totalNumberOfInputChannels;
  219672. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  219673. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  219674. }
  219675. // open output ports
  219676. const StringArray outputChannels (getOutputChannelNames());
  219677. for (int i = 0; i < outputChannels.size (); i++)
  219678. {
  219679. String outputName;
  219680. outputName << "out_" << ++totalNumberOfOutputChannels;
  219681. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  219682. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  219683. }
  219684. inChans.calloc (totalNumberOfInputChannels + 2);
  219685. outChans.calloc (totalNumberOfOutputChannels + 2);
  219686. }
  219687. }
  219688. ~JackAudioIODevice()
  219689. {
  219690. close();
  219691. if (client != 0)
  219692. {
  219693. JUCE_NAMESPACE::jack_client_close (client);
  219694. client = 0;
  219695. }
  219696. }
  219697. const StringArray getChannelNames (bool forInput) const
  219698. {
  219699. StringArray names;
  219700. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  219701. forInput ? JackPortIsInput : JackPortIsOutput);
  219702. if (ports != 0)
  219703. {
  219704. int j = 0;
  219705. while (ports[j] != 0)
  219706. {
  219707. const String portName (ports [j++]);
  219708. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  219709. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  219710. }
  219711. free (ports);
  219712. }
  219713. return names;
  219714. }
  219715. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  219716. const StringArray getInputChannelNames() { return getChannelNames (true); }
  219717. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  219718. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  219719. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  219720. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  219721. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  219722. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  219723. double sampleRate, int bufferSizeSamples)
  219724. {
  219725. if (client == 0)
  219726. {
  219727. lastError = "No JACK client running";
  219728. return lastError;
  219729. }
  219730. lastError = String::empty;
  219731. close();
  219732. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  219733. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  219734. JUCE_NAMESPACE::jack_activate (client);
  219735. isOpen_ = true;
  219736. if (! inputChannels.isZero())
  219737. {
  219738. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  219739. if (ports != 0)
  219740. {
  219741. const int numInputChannels = inputChannels.getHighestBit() + 1;
  219742. for (int i = 0; i < numInputChannels; ++i)
  219743. {
  219744. const String portName (ports[i]);
  219745. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  219746. {
  219747. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  219748. if (error != 0)
  219749. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  219750. }
  219751. }
  219752. free (ports);
  219753. }
  219754. }
  219755. if (! outputChannels.isZero())
  219756. {
  219757. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  219758. if (ports != 0)
  219759. {
  219760. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  219761. for (int i = 0; i < numOutputChannels; ++i)
  219762. {
  219763. const String portName (ports[i]);
  219764. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  219765. {
  219766. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  219767. if (error != 0)
  219768. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  219769. }
  219770. }
  219771. free (ports);
  219772. }
  219773. }
  219774. return lastError;
  219775. }
  219776. void close()
  219777. {
  219778. stop();
  219779. if (client != 0)
  219780. {
  219781. JUCE_NAMESPACE::jack_deactivate (client);
  219782. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  219783. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  219784. }
  219785. isOpen_ = false;
  219786. }
  219787. void start (AudioIODeviceCallback* newCallback)
  219788. {
  219789. if (isOpen_ && newCallback != callback)
  219790. {
  219791. if (newCallback != 0)
  219792. newCallback->audioDeviceAboutToStart (this);
  219793. AudioIODeviceCallback* const oldCallback = callback;
  219794. {
  219795. const ScopedLock sl (callbackLock);
  219796. callback = newCallback;
  219797. }
  219798. if (oldCallback != 0)
  219799. oldCallback->audioDeviceStopped();
  219800. }
  219801. }
  219802. void stop()
  219803. {
  219804. start (0);
  219805. }
  219806. bool isOpen() { return isOpen_; }
  219807. bool isPlaying() { return callback != 0; }
  219808. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  219809. double getCurrentSampleRate() { return getSampleRate (0); }
  219810. int getCurrentBitDepth() { return 32; }
  219811. const String getLastError() { return lastError; }
  219812. const BigInteger getActiveOutputChannels() const
  219813. {
  219814. BigInteger outputBits;
  219815. for (int i = 0; i < outputPorts.size(); i++)
  219816. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  219817. outputBits.setBit (i);
  219818. return outputBits;
  219819. }
  219820. const BigInteger getActiveInputChannels() const
  219821. {
  219822. BigInteger inputBits;
  219823. for (int i = 0; i < inputPorts.size(); i++)
  219824. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  219825. inputBits.setBit (i);
  219826. return inputBits;
  219827. }
  219828. int getOutputLatencyInSamples()
  219829. {
  219830. int latency = 0;
  219831. for (int i = 0; i < outputPorts.size(); i++)
  219832. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  219833. return latency;
  219834. }
  219835. int getInputLatencyInSamples()
  219836. {
  219837. int latency = 0;
  219838. for (int i = 0; i < inputPorts.size(); i++)
  219839. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  219840. return latency;
  219841. }
  219842. String inputId, outputId;
  219843. private:
  219844. void process (const int numSamples)
  219845. {
  219846. int i, numActiveInChans = 0, numActiveOutChans = 0;
  219847. for (i = 0; i < totalNumberOfInputChannels; ++i)
  219848. {
  219849. jack_default_audio_sample_t* in
  219850. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  219851. if (in != 0)
  219852. inChans [numActiveInChans++] = (float*) in;
  219853. }
  219854. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  219855. {
  219856. jack_default_audio_sample_t* out
  219857. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  219858. if (out != 0)
  219859. outChans [numActiveOutChans++] = (float*) out;
  219860. }
  219861. const ScopedLock sl (callbackLock);
  219862. if (callback != 0)
  219863. {
  219864. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  219865. outChans, numActiveOutChans, numSamples);
  219866. }
  219867. else
  219868. {
  219869. for (i = 0; i < numActiveOutChans; ++i)
  219870. zeromem (outChans[i], sizeof (float) * numSamples);
  219871. }
  219872. }
  219873. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  219874. {
  219875. if (callbackArgument != 0)
  219876. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  219877. return 0;
  219878. }
  219879. static void threadInitCallback (void* callbackArgument)
  219880. {
  219881. jack_Log ("JackAudioIODevice::initialise");
  219882. }
  219883. static void shutdownCallback (void* callbackArgument)
  219884. {
  219885. jack_Log ("JackAudioIODevice::shutdown");
  219886. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  219887. if (device != 0)
  219888. {
  219889. device->client = 0;
  219890. device->close();
  219891. }
  219892. }
  219893. static void errorCallback (const char* msg)
  219894. {
  219895. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  219896. }
  219897. bool isOpen_;
  219898. jack_client_t* client;
  219899. String lastError;
  219900. AudioIODeviceCallback* callback;
  219901. CriticalSection callbackLock;
  219902. HeapBlock <float*> inChans, outChans;
  219903. int totalNumberOfInputChannels;
  219904. int totalNumberOfOutputChannels;
  219905. VoidArray inputPorts, outputPorts;
  219906. };
  219907. class JackAudioIODeviceType : public AudioIODeviceType
  219908. {
  219909. public:
  219910. JackAudioIODeviceType()
  219911. : AudioIODeviceType ("JACK"),
  219912. hasScanned (false)
  219913. {
  219914. }
  219915. ~JackAudioIODeviceType()
  219916. {
  219917. }
  219918. void scanForDevices()
  219919. {
  219920. hasScanned = true;
  219921. inputNames.clear();
  219922. inputIds.clear();
  219923. outputNames.clear();
  219924. outputIds.clear();
  219925. if (juce_libjack_handle == 0)
  219926. {
  219927. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  219928. if (juce_libjack_handle == 0)
  219929. return;
  219930. }
  219931. // open a dummy client
  219932. jack_status_t status;
  219933. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  219934. if (client == 0)
  219935. {
  219936. dumpJackErrorMessage (status);
  219937. }
  219938. else
  219939. {
  219940. // scan for output devices
  219941. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  219942. if (ports != 0)
  219943. {
  219944. int j = 0;
  219945. while (ports[j] != 0)
  219946. {
  219947. String clientName (ports[j]);
  219948. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  219949. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  219950. && ! inputNames.contains (clientName))
  219951. {
  219952. inputNames.add (clientName);
  219953. inputIds.add (ports [j]);
  219954. }
  219955. ++j;
  219956. }
  219957. free (ports);
  219958. }
  219959. // scan for input devices
  219960. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  219961. if (ports != 0)
  219962. {
  219963. int j = 0;
  219964. while (ports[j] != 0)
  219965. {
  219966. String clientName (ports[j]);
  219967. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  219968. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  219969. && ! outputNames.contains (clientName))
  219970. {
  219971. outputNames.add (clientName);
  219972. outputIds.add (ports [j]);
  219973. }
  219974. ++j;
  219975. }
  219976. free (ports);
  219977. }
  219978. JUCE_NAMESPACE::jack_client_close (client);
  219979. }
  219980. }
  219981. const StringArray getDeviceNames (bool wantInputNames) const
  219982. {
  219983. jassert (hasScanned); // need to call scanForDevices() before doing this
  219984. return wantInputNames ? inputNames : outputNames;
  219985. }
  219986. int getDefaultDeviceIndex (bool forInput) const
  219987. {
  219988. jassert (hasScanned); // need to call scanForDevices() before doing this
  219989. return 0;
  219990. }
  219991. bool hasSeparateInputsAndOutputs() const { return true; }
  219992. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  219993. {
  219994. jassert (hasScanned); // need to call scanForDevices() before doing this
  219995. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  219996. if (d == 0)
  219997. return -1;
  219998. return asInput ? inputIds.indexOf (d->inputId)
  219999. : outputIds.indexOf (d->outputId);
  220000. }
  220001. AudioIODevice* createDevice (const String& outputDeviceName,
  220002. const String& inputDeviceName)
  220003. {
  220004. jassert (hasScanned); // need to call scanForDevices() before doing this
  220005. const int inputIndex = inputNames.indexOf (inputDeviceName);
  220006. const int outputIndex = outputNames.indexOf (outputDeviceName);
  220007. if (inputIndex >= 0 || outputIndex >= 0)
  220008. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  220009. : inputDeviceName,
  220010. inputIds [inputIndex],
  220011. outputIds [outputIndex]);
  220012. return 0;
  220013. }
  220014. juce_UseDebuggingNewOperator
  220015. private:
  220016. StringArray inputNames, outputNames, inputIds, outputIds;
  220017. bool hasScanned;
  220018. JackAudioIODeviceType (const JackAudioIODeviceType&);
  220019. JackAudioIODeviceType& operator= (const JackAudioIODeviceType&);
  220020. };
  220021. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  220022. {
  220023. return new JackAudioIODeviceType();
  220024. }
  220025. #else // if JACK is turned off..
  220026. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  220027. #endif
  220028. #endif
  220029. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  220030. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  220031. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  220032. // compiled on its own).
  220033. #if JUCE_INCLUDED_FILE
  220034. #if JUCE_ALSA
  220035. static snd_seq_t* iterateDevices (const bool forInput,
  220036. StringArray& deviceNamesFound,
  220037. const int deviceIndexToOpen)
  220038. {
  220039. snd_seq_t* returnedHandle = 0;
  220040. snd_seq_t* seqHandle;
  220041. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  220042. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  220043. {
  220044. snd_seq_system_info_t* systemInfo;
  220045. snd_seq_client_info_t* clientInfo;
  220046. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  220047. {
  220048. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  220049. && snd_seq_client_info_malloc (&clientInfo) == 0)
  220050. {
  220051. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  220052. while (--numClients >= 0 && returnedHandle == 0)
  220053. {
  220054. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  220055. {
  220056. snd_seq_port_info_t* portInfo;
  220057. if (snd_seq_port_info_malloc (&portInfo) == 0)
  220058. {
  220059. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  220060. const int client = snd_seq_client_info_get_client (clientInfo);
  220061. snd_seq_port_info_set_client (portInfo, client);
  220062. snd_seq_port_info_set_port (portInfo, -1);
  220063. while (--numPorts >= 0)
  220064. {
  220065. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  220066. && (snd_seq_port_info_get_capability (portInfo)
  220067. & (forInput ? SND_SEQ_PORT_CAP_READ
  220068. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  220069. {
  220070. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  220071. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  220072. {
  220073. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  220074. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  220075. if (sourcePort != -1)
  220076. {
  220077. snd_seq_set_client_name (seqHandle,
  220078. forInput ? "Juce Midi Input"
  220079. : "Juce Midi Output");
  220080. const int portId
  220081. = snd_seq_create_simple_port (seqHandle,
  220082. forInput ? "Juce Midi In Port"
  220083. : "Juce Midi Out Port",
  220084. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  220085. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  220086. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  220087. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  220088. returnedHandle = seqHandle;
  220089. }
  220090. }
  220091. }
  220092. }
  220093. snd_seq_port_info_free (portInfo);
  220094. }
  220095. }
  220096. }
  220097. snd_seq_client_info_free (clientInfo);
  220098. }
  220099. snd_seq_system_info_free (systemInfo);
  220100. }
  220101. if (returnedHandle == 0)
  220102. snd_seq_close (seqHandle);
  220103. }
  220104. deviceNamesFound.appendNumbersToDuplicates (true, true);
  220105. return returnedHandle;
  220106. }
  220107. static snd_seq_t* createDevice (const bool forInput,
  220108. const String& deviceNameToOpen)
  220109. {
  220110. snd_seq_t* seqHandle = 0;
  220111. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  220112. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  220113. {
  220114. snd_seq_set_client_name (seqHandle,
  220115. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  220116. const int portId
  220117. = snd_seq_create_simple_port (seqHandle,
  220118. forInput ? "in"
  220119. : "out",
  220120. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  220121. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  220122. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  220123. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  220124. if (portId < 0)
  220125. {
  220126. snd_seq_close (seqHandle);
  220127. seqHandle = 0;
  220128. }
  220129. }
  220130. return seqHandle;
  220131. }
  220132. class MidiOutputDevice
  220133. {
  220134. public:
  220135. MidiOutputDevice (MidiOutput* const midiOutput_,
  220136. snd_seq_t* const seqHandle_)
  220137. :
  220138. midiOutput (midiOutput_),
  220139. seqHandle (seqHandle_),
  220140. maxEventSize (16 * 1024)
  220141. {
  220142. jassert (seqHandle != 0 && midiOutput != 0);
  220143. snd_midi_event_new (maxEventSize, &midiParser);
  220144. }
  220145. ~MidiOutputDevice()
  220146. {
  220147. snd_midi_event_free (midiParser);
  220148. snd_seq_close (seqHandle);
  220149. }
  220150. void sendMessageNow (const MidiMessage& message)
  220151. {
  220152. if (message.getRawDataSize() > maxEventSize)
  220153. {
  220154. maxEventSize = message.getRawDataSize();
  220155. snd_midi_event_free (midiParser);
  220156. snd_midi_event_new (maxEventSize, &midiParser);
  220157. }
  220158. snd_seq_event_t event;
  220159. snd_seq_ev_clear (&event);
  220160. snd_midi_event_encode (midiParser,
  220161. message.getRawData(),
  220162. message.getRawDataSize(),
  220163. &event);
  220164. snd_midi_event_reset_encode (midiParser);
  220165. snd_seq_ev_set_source (&event, 0);
  220166. snd_seq_ev_set_subs (&event);
  220167. snd_seq_ev_set_direct (&event);
  220168. snd_seq_event_output (seqHandle, &event);
  220169. snd_seq_drain_output (seqHandle);
  220170. }
  220171. juce_UseDebuggingNewOperator
  220172. private:
  220173. MidiOutput* const midiOutput;
  220174. snd_seq_t* const seqHandle;
  220175. snd_midi_event_t* midiParser;
  220176. int maxEventSize;
  220177. };
  220178. const StringArray MidiOutput::getDevices()
  220179. {
  220180. StringArray devices;
  220181. iterateDevices (false, devices, -1);
  220182. return devices;
  220183. }
  220184. int MidiOutput::getDefaultDeviceIndex()
  220185. {
  220186. return 0;
  220187. }
  220188. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  220189. {
  220190. MidiOutput* newDevice = 0;
  220191. StringArray devices;
  220192. snd_seq_t* const handle = iterateDevices (false, devices, deviceIndex);
  220193. if (handle != 0)
  220194. {
  220195. newDevice = new MidiOutput();
  220196. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  220197. }
  220198. return newDevice;
  220199. }
  220200. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  220201. {
  220202. MidiOutput* newDevice = 0;
  220203. snd_seq_t* const handle = createDevice (false, deviceName);
  220204. if (handle != 0)
  220205. {
  220206. newDevice = new MidiOutput();
  220207. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  220208. }
  220209. return newDevice;
  220210. }
  220211. MidiOutput::~MidiOutput()
  220212. {
  220213. MidiOutputDevice* const device = (MidiOutputDevice*) internal;
  220214. delete device;
  220215. }
  220216. void MidiOutput::reset()
  220217. {
  220218. }
  220219. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  220220. {
  220221. return false;
  220222. }
  220223. void MidiOutput::setVolume (float leftVol, float rightVol)
  220224. {
  220225. }
  220226. void MidiOutput::sendMessageNow (const MidiMessage& message)
  220227. {
  220228. ((MidiOutputDevice*) internal)->sendMessageNow (message);
  220229. }
  220230. class MidiInputThread : public Thread
  220231. {
  220232. public:
  220233. MidiInputThread (MidiInput* const midiInput_,
  220234. snd_seq_t* const seqHandle_,
  220235. MidiInputCallback* const callback_)
  220236. : Thread ("Juce MIDI Input"),
  220237. midiInput (midiInput_),
  220238. seqHandle (seqHandle_),
  220239. callback (callback_)
  220240. {
  220241. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  220242. }
  220243. ~MidiInputThread()
  220244. {
  220245. snd_seq_close (seqHandle);
  220246. }
  220247. void run()
  220248. {
  220249. const int maxEventSize = 16 * 1024;
  220250. snd_midi_event_t* midiParser;
  220251. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  220252. {
  220253. HeapBlock <uint8> buffer (maxEventSize);
  220254. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  220255. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  220256. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  220257. while (! threadShouldExit())
  220258. {
  220259. if (poll (pfd, numPfds, 500) > 0)
  220260. {
  220261. snd_seq_event_t* inputEvent = 0;
  220262. snd_seq_nonblock (seqHandle, 1);
  220263. do
  220264. {
  220265. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  220266. {
  220267. // xxx what about SYSEXes that are too big for the buffer?
  220268. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  220269. snd_midi_event_reset_decode (midiParser);
  220270. if (numBytes > 0)
  220271. {
  220272. const MidiMessage message ((const uint8*) buffer,
  220273. numBytes,
  220274. Time::getMillisecondCounter() * 0.001);
  220275. callback->handleIncomingMidiMessage (midiInput, message);
  220276. }
  220277. snd_seq_free_event (inputEvent);
  220278. }
  220279. }
  220280. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  220281. snd_seq_free_event (inputEvent);
  220282. }
  220283. }
  220284. snd_midi_event_free (midiParser);
  220285. }
  220286. };
  220287. juce_UseDebuggingNewOperator
  220288. private:
  220289. MidiInput* const midiInput;
  220290. snd_seq_t* const seqHandle;
  220291. MidiInputCallback* const callback;
  220292. };
  220293. MidiInput::MidiInput (const String& name_)
  220294. : name (name_),
  220295. internal (0)
  220296. {
  220297. }
  220298. MidiInput::~MidiInput()
  220299. {
  220300. stop();
  220301. MidiInputThread* const thread = (MidiInputThread*) internal;
  220302. delete thread;
  220303. }
  220304. void MidiInput::start()
  220305. {
  220306. ((MidiInputThread*) internal)->startThread();
  220307. }
  220308. void MidiInput::stop()
  220309. {
  220310. ((MidiInputThread*) internal)->stopThread (3000);
  220311. }
  220312. int MidiInput::getDefaultDeviceIndex()
  220313. {
  220314. return 0;
  220315. }
  220316. const StringArray MidiInput::getDevices()
  220317. {
  220318. StringArray devices;
  220319. iterateDevices (true, devices, -1);
  220320. return devices;
  220321. }
  220322. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  220323. {
  220324. MidiInput* newDevice = 0;
  220325. StringArray devices;
  220326. snd_seq_t* const handle = iterateDevices (true, devices, deviceIndex);
  220327. if (handle != 0)
  220328. {
  220329. newDevice = new MidiInput (devices [deviceIndex]);
  220330. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  220331. }
  220332. return newDevice;
  220333. }
  220334. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  220335. {
  220336. MidiInput* newDevice = 0;
  220337. snd_seq_t* const handle = createDevice (true, deviceName);
  220338. if (handle != 0)
  220339. {
  220340. newDevice = new MidiInput (deviceName);
  220341. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  220342. }
  220343. return newDevice;
  220344. }
  220345. #else
  220346. // (These are just stub functions if ALSA is unavailable...)
  220347. const StringArray MidiOutput::getDevices() { return StringArray(); }
  220348. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  220349. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  220350. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  220351. MidiOutput::~MidiOutput() {}
  220352. void MidiOutput::reset() {}
  220353. bool MidiOutput::getVolume (float&, float&) { return false; }
  220354. void MidiOutput::setVolume (float, float) {}
  220355. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  220356. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  220357. MidiInput::~MidiInput() {}
  220358. void MidiInput::start() {}
  220359. void MidiInput::stop() {}
  220360. int MidiInput::getDefaultDeviceIndex() { return 0; }
  220361. const StringArray MidiInput::getDevices() { return StringArray(); }
  220362. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  220363. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  220364. #endif
  220365. #endif
  220366. /*** End of inlined file: juce_linux_Midi.cpp ***/
  220367. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  220368. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  220369. // compiled on its own).
  220370. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  220371. AudioCDReader::AudioCDReader()
  220372. : AudioFormatReader (0, "CD Audio")
  220373. {
  220374. }
  220375. const StringArray AudioCDReader::getAvailableCDNames()
  220376. {
  220377. StringArray names;
  220378. return names;
  220379. }
  220380. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  220381. {
  220382. return 0;
  220383. }
  220384. AudioCDReader::~AudioCDReader()
  220385. {
  220386. }
  220387. void AudioCDReader::refreshTrackLengths()
  220388. {
  220389. }
  220390. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  220391. int64 startSampleInFile, int numSamples)
  220392. {
  220393. return false;
  220394. }
  220395. bool AudioCDReader::isCDStillPresent() const
  220396. {
  220397. return false;
  220398. }
  220399. int AudioCDReader::getNumTracks() const
  220400. {
  220401. return 0;
  220402. }
  220403. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  220404. {
  220405. return 0;
  220406. }
  220407. bool AudioCDReader::isTrackAudio (int trackNum) const
  220408. {
  220409. return false;
  220410. }
  220411. void AudioCDReader::enableIndexScanning (bool b)
  220412. {
  220413. }
  220414. int AudioCDReader::getLastIndex() const
  220415. {
  220416. return 0;
  220417. }
  220418. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  220419. {
  220420. return Array<int>();
  220421. }
  220422. int AudioCDReader::getCDDBId()
  220423. {
  220424. return 0;
  220425. }
  220426. #endif
  220427. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  220428. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  220429. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  220430. // compiled on its own).
  220431. #if JUCE_INCLUDED_FILE
  220432. void FileChooser::showPlatformDialog (Array<File>& results,
  220433. const String& title,
  220434. const File& file,
  220435. const String& filters,
  220436. bool isDirectory,
  220437. bool selectsFiles,
  220438. bool isSave,
  220439. bool warnAboutOverwritingExistingFiles,
  220440. bool selectMultipleFiles,
  220441. FilePreviewComponent* previewComponent)
  220442. {
  220443. const String separator (":");
  220444. String command ("zenity --file-selection");
  220445. if (title.isNotEmpty())
  220446. command << " --title=\"" << title << "\"";
  220447. if (file != File::nonexistent)
  220448. command << " --filename=\"" << file.getFullPathName () << "\"";
  220449. if (isDirectory)
  220450. command << " --directory";
  220451. if (isSave)
  220452. command << " --save";
  220453. if (selectMultipleFiles)
  220454. command << " --multiple --separator=\"" << separator << "\"";
  220455. command << " 2>&1";
  220456. MemoryOutputStream result;
  220457. int status = -1;
  220458. FILE* stream = popen (command.toUTF8(), "r");
  220459. if (stream != 0)
  220460. {
  220461. for (;;)
  220462. {
  220463. char buffer [1024];
  220464. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  220465. if (bytesRead <= 0)
  220466. break;
  220467. result.write (buffer, bytesRead);
  220468. }
  220469. status = pclose (stream);
  220470. }
  220471. if (status == 0)
  220472. {
  220473. StringArray tokens;
  220474. if (selectMultipleFiles)
  220475. tokens.addTokens (result.toUTF8(), separator, String::empty);
  220476. else
  220477. tokens.add (result.toUTF8());
  220478. for (int i = 0; i < tokens.size(); i++)
  220479. results.add (File (tokens[i]));
  220480. return;
  220481. }
  220482. //xxx ain't got one!
  220483. jassertfalse
  220484. }
  220485. #endif
  220486. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  220487. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  220488. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  220489. // compiled on its own).
  220490. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  220491. /*
  220492. Sorry.. This class isn't implemented on Linux!
  220493. */
  220494. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  220495. : browser (0),
  220496. blankPageShown (false),
  220497. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  220498. {
  220499. setOpaque (true);
  220500. }
  220501. WebBrowserComponent::~WebBrowserComponent()
  220502. {
  220503. }
  220504. void WebBrowserComponent::goToURL (const String& url,
  220505. const StringArray* headers,
  220506. const MemoryBlock* postData)
  220507. {
  220508. lastURL = url;
  220509. lastHeaders.clear();
  220510. if (headers != 0)
  220511. lastHeaders = *headers;
  220512. lastPostData.setSize (0);
  220513. if (postData != 0)
  220514. lastPostData = *postData;
  220515. blankPageShown = false;
  220516. }
  220517. void WebBrowserComponent::stop()
  220518. {
  220519. }
  220520. void WebBrowserComponent::goBack()
  220521. {
  220522. lastURL = String::empty;
  220523. blankPageShown = false;
  220524. }
  220525. void WebBrowserComponent::goForward()
  220526. {
  220527. lastURL = String::empty;
  220528. }
  220529. void WebBrowserComponent::refresh()
  220530. {
  220531. }
  220532. void WebBrowserComponent::paint (Graphics& g)
  220533. {
  220534. g.fillAll (Colours::white);
  220535. }
  220536. void WebBrowserComponent::checkWindowAssociation()
  220537. {
  220538. }
  220539. void WebBrowserComponent::reloadLastURL()
  220540. {
  220541. if (lastURL.isNotEmpty())
  220542. {
  220543. goToURL (lastURL, &lastHeaders, &lastPostData);
  220544. lastURL = String::empty;
  220545. }
  220546. }
  220547. void WebBrowserComponent::parentHierarchyChanged()
  220548. {
  220549. checkWindowAssociation();
  220550. }
  220551. void WebBrowserComponent::resized()
  220552. {
  220553. }
  220554. void WebBrowserComponent::visibilityChanged()
  220555. {
  220556. checkWindowAssociation();
  220557. }
  220558. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  220559. {
  220560. return true;
  220561. }
  220562. #endif
  220563. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  220564. #endif
  220565. END_JUCE_NAMESPACE
  220566. #endif
  220567. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  220568. #endif
  220569. #if JUCE_MAC || JUCE_IPHONE
  220570. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  220571. /*
  220572. This file wraps together all the mac-specific code, so that
  220573. we can include all the native headers just once, and compile all our
  220574. platform-specific stuff in one big lump, keeping it out of the way of
  220575. the rest of the codebase.
  220576. */
  220577. #if JUCE_MAC || JUCE_IPHONE
  220578. BEGIN_JUCE_NAMESPACE
  220579. #undef Point
  220580. #define JUCE_INCLUDED_FILE 1
  220581. // Now include the actual code files..
  220582. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  220583. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  220584. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  220585. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  220586. cross-linked so that when you make a call to a class that you thought was private, it ends up
  220587. actually calling into a similarly named class in the other module's address space.
  220588. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  220589. have unique names, and should avoid this problem.
  220590. If you're using the amalgamated version, you can just set this macro to something unique before
  220591. you include juce_amalgamated.cpp.
  220592. */
  220593. #ifndef JUCE_ObjCExtraSuffix
  220594. #define JUCE_ObjCExtraSuffix 3
  220595. #endif
  220596. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  220597. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  220598. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  220599. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  220600. /*** Start of inlined file: juce_mac_Strings.mm ***/
  220601. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220602. // compiled on its own).
  220603. #if JUCE_INCLUDED_FILE
  220604. static const String nsStringToJuce (NSString* s)
  220605. {
  220606. return String::fromUTF8 ([s UTF8String]);
  220607. }
  220608. static NSString* juceStringToNS (const String& s)
  220609. {
  220610. return [NSString stringWithUTF8String: s.toUTF8()];
  220611. }
  220612. static const String convertUTF16ToString (const UniChar* utf16)
  220613. {
  220614. String s;
  220615. while (*utf16 != 0)
  220616. s += (juce_wchar) *utf16++;
  220617. return s;
  220618. }
  220619. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  220620. {
  220621. String result;
  220622. if (cfString != 0)
  220623. {
  220624. CFRange range = { 0, CFStringGetLength (cfString) };
  220625. HeapBlock <UniChar> u (range.length + 1);
  220626. CFStringGetCharacters (cfString, range, u);
  220627. u[range.length] = 0;
  220628. result = convertUTF16ToString (u);
  220629. }
  220630. return result;
  220631. }
  220632. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  220633. {
  220634. const int len = s.length();
  220635. HeapBlock <UniChar> temp (len + 2);
  220636. for (int i = 0; i <= len; ++i)
  220637. temp[i] = s[i];
  220638. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  220639. }
  220640. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  220641. {
  220642. #if JUCE_IPHONE
  220643. const ScopedAutoReleasePool pool;
  220644. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  220645. #else
  220646. UnicodeMapping map;
  220647. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  220648. kUnicodeNoSubset,
  220649. kTextEncodingDefaultFormat);
  220650. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  220651. kUnicodeCanonicalCompVariant,
  220652. kTextEncodingDefaultFormat);
  220653. map.mappingVersion = kUnicodeUseLatestMapping;
  220654. UnicodeToTextInfo conversionInfo = 0;
  220655. String result;
  220656. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  220657. {
  220658. const int len = s.length();
  220659. HeapBlock <UniChar> tempIn, tempOut;
  220660. tempIn.calloc (len + 2);
  220661. tempOut.calloc (len + 2);
  220662. for (int i = 0; i <= len; ++i)
  220663. tempIn[i] = s[i];
  220664. ByteCount bytesRead = 0;
  220665. ByteCount outputBufferSize = 0;
  220666. if (ConvertFromUnicodeToText (conversionInfo,
  220667. len * sizeof (UniChar), tempIn,
  220668. kUnicodeDefaultDirectionMask,
  220669. 0, 0, 0, 0,
  220670. len * sizeof (UniChar), &bytesRead,
  220671. &outputBufferSize, tempOut) == noErr)
  220672. {
  220673. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  220674. juce_wchar* t = result;
  220675. unsigned int i;
  220676. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  220677. t[i] = (juce_wchar) tempOut[i];
  220678. t[i] = 0;
  220679. }
  220680. DisposeUnicodeToTextInfo (&conversionInfo);
  220681. }
  220682. return result;
  220683. #endif
  220684. }
  220685. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  220686. void SystemClipboard::copyTextToClipboard (const String& text)
  220687. {
  220688. #if JUCE_IPHONE
  220689. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  220690. forPasteboardType: @"public.text"];
  220691. #else
  220692. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  220693. owner: nil];
  220694. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  220695. forType: NSStringPboardType];
  220696. #endif
  220697. }
  220698. const String SystemClipboard::getTextFromClipboard()
  220699. {
  220700. #if JUCE_IPHONE
  220701. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  220702. #else
  220703. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  220704. #endif
  220705. return text == 0 ? String::empty
  220706. : nsStringToJuce (text);
  220707. }
  220708. #endif
  220709. #endif
  220710. /*** End of inlined file: juce_mac_Strings.mm ***/
  220711. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  220712. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220713. // compiled on its own).
  220714. #if JUCE_INCLUDED_FILE
  220715. namespace SystemStatsHelpers
  220716. {
  220717. static int64 highResTimerFrequency = 0;
  220718. static double highResTimerToMillisecRatio = 0;
  220719. #if JUCE_INTEL
  220720. static void juce_getCpuVendor (char* const v) throw()
  220721. {
  220722. int vendor[4];
  220723. zerostruct (vendor);
  220724. int dummy = 0;
  220725. asm ("mov %%ebx, %%esi \n\t"
  220726. "cpuid \n\t"
  220727. "xchg %%esi, %%ebx"
  220728. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  220729. memcpy (v, vendor, 16);
  220730. }
  220731. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures)
  220732. {
  220733. unsigned int cpu = 0;
  220734. unsigned int ext = 0;
  220735. unsigned int family = 0;
  220736. unsigned int dummy = 0;
  220737. asm ("mov %%ebx, %%esi \n\t"
  220738. "cpuid \n\t"
  220739. "xchg %%esi, %%ebx"
  220740. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  220741. familyModel = family;
  220742. extFeatures = ext;
  220743. return cpu;
  220744. }
  220745. struct CPUFlags
  220746. {
  220747. bool hasMMX : 1;
  220748. bool hasSSE : 1;
  220749. bool hasSSE2 : 1;
  220750. bool has3DNow : 1;
  220751. };
  220752. static CPUFlags cpuFlags;
  220753. #endif
  220754. }
  220755. void SystemStats::initialiseStats()
  220756. {
  220757. using namespace SystemStatsHelpers;
  220758. static bool initialised = false;
  220759. if (! initialised)
  220760. {
  220761. initialised = true;
  220762. #if JUCE_MAC
  220763. // extremely annoying: adding this line stops the apple menu items from working. Of
  220764. // course, not adding it means that carbon windows (e.g. in plugins) won't get
  220765. // any events.
  220766. //NSApplicationLoad();
  220767. [NSApplication sharedApplication];
  220768. #endif
  220769. #if JUCE_INTEL
  220770. {
  220771. unsigned int familyModel, extFeatures;
  220772. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  220773. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  220774. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  220775. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  220776. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  220777. }
  220778. #endif
  220779. mach_timebase_info_data_t timebase;
  220780. (void) mach_timebase_info (&timebase);
  220781. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  220782. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  220783. String s (SystemStats::getJUCEVersion());
  220784. rlimit lim;
  220785. getrlimit (RLIMIT_NOFILE, &lim);
  220786. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  220787. setrlimit (RLIMIT_NOFILE, &lim);
  220788. }
  220789. }
  220790. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  220791. {
  220792. return MacOSX;
  220793. }
  220794. const String SystemStats::getOperatingSystemName()
  220795. {
  220796. return "Mac OS X";
  220797. }
  220798. bool SystemStats::isOperatingSystem64Bit()
  220799. {
  220800. #if JUCE_64BIT
  220801. return true;
  220802. #else
  220803. //xxx not sure how to find this out?..
  220804. return false;
  220805. #endif
  220806. }
  220807. int SystemStats::getMemorySizeInMegabytes()
  220808. {
  220809. uint64 mem = 0;
  220810. size_t memSize = sizeof (mem);
  220811. int mib[] = { CTL_HW, HW_MEMSIZE };
  220812. sysctl (mib, 2, &mem, &memSize, 0, 0);
  220813. return (int) (mem / (1024 * 1024));
  220814. }
  220815. bool SystemStats::hasMMX()
  220816. {
  220817. #if JUCE_INTEL
  220818. return SystemStatsHelpers::cpuFlags.hasMMX;
  220819. #else
  220820. return false;
  220821. #endif
  220822. }
  220823. bool SystemStats::hasSSE()
  220824. {
  220825. #if JUCE_INTEL
  220826. return SystemStatsHelpers::cpuFlags.hasSSE;
  220827. #else
  220828. return false;
  220829. #endif
  220830. }
  220831. bool SystemStats::hasSSE2()
  220832. {
  220833. #if JUCE_INTEL
  220834. return SystemStatsHelpers::cpuFlags.hasSSE2;
  220835. #else
  220836. return false;
  220837. #endif
  220838. }
  220839. bool SystemStats::has3DNow()
  220840. {
  220841. #if JUCE_INTEL
  220842. return SystemStatsHelpers::cpuFlags.has3DNow;
  220843. #else
  220844. return false;
  220845. #endif
  220846. }
  220847. const String SystemStats::getCpuVendor()
  220848. {
  220849. #if JUCE_INTEL
  220850. char v [16];
  220851. SystemStatsHelpers::juce_getCpuVendor (v);
  220852. return String (v, 16);
  220853. #else
  220854. return String::empty;
  220855. #endif
  220856. }
  220857. int SystemStats::getCpuSpeedInMegaherz()
  220858. {
  220859. uint64 speedHz = 0;
  220860. size_t speedSize = sizeof (speedHz);
  220861. int mib[] = { CTL_HW, HW_CPU_FREQ };
  220862. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  220863. #if JUCE_BIG_ENDIAN
  220864. if (speedSize == 4)
  220865. speedHz >>= 32;
  220866. #endif
  220867. return (int) (speedHz / 1000000);
  220868. }
  220869. int SystemStats::getNumCpus()
  220870. {
  220871. #if JUCE_IPHONE || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  220872. return (int) [[NSProcessInfo processInfo] activeProcessorCount];
  220873. #else
  220874. return MPProcessors();
  220875. #endif
  220876. }
  220877. const String SystemStats::getLogonName()
  220878. {
  220879. return nsStringToJuce (NSUserName());
  220880. }
  220881. const String SystemStats::getFullUserName()
  220882. {
  220883. return nsStringToJuce (NSFullUserName());
  220884. }
  220885. uint32 juce_millisecondsSinceStartup() throw()
  220886. {
  220887. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  220888. }
  220889. double Time::getMillisecondCounterHiRes() throw()
  220890. {
  220891. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  220892. }
  220893. int64 Time::getHighResolutionTicks() throw()
  220894. {
  220895. return (int64) mach_absolute_time();
  220896. }
  220897. int64 Time::getHighResolutionTicksPerSecond() throw()
  220898. {
  220899. return SystemStatsHelpers::highResTimerFrequency;
  220900. }
  220901. bool Time::setSystemTimeToThisTime() const
  220902. {
  220903. jassertfalse
  220904. return false;
  220905. }
  220906. int SystemStats::getPageSize()
  220907. {
  220908. return (int) NSPageSize();
  220909. }
  220910. void PlatformUtilities::fpuReset()
  220911. {
  220912. }
  220913. #endif
  220914. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  220915. /*** Start of inlined file: juce_mac_Network.mm ***/
  220916. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220917. // compiled on its own).
  220918. #if JUCE_INCLUDED_FILE
  220919. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  220920. {
  220921. #ifndef IFT_ETHER
  220922. #define IFT_ETHER 6
  220923. #endif
  220924. ifaddrs* addrs = 0;
  220925. int numResults = 0;
  220926. if (getifaddrs (&addrs) == 0)
  220927. {
  220928. const ifaddrs* cursor = addrs;
  220929. while (cursor != 0 && numResults < maxNum)
  220930. {
  220931. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  220932. if (sto->ss_family == AF_LINK)
  220933. {
  220934. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  220935. if (sadd->sdl_type == IFT_ETHER)
  220936. {
  220937. const uint8* const addr = ((const uint8*) sadd->sdl_data) + sadd->sdl_nlen;
  220938. uint64 a = 0;
  220939. for (int i = 6; --i >= 0;)
  220940. a = (a << 8) | addr [littleEndian ? i : (5 - i)];
  220941. *addresses++ = (int64) a;
  220942. ++numResults;
  220943. }
  220944. }
  220945. cursor = cursor->ifa_next;
  220946. }
  220947. freeifaddrs (addrs);
  220948. }
  220949. return numResults;
  220950. }
  220951. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  220952. const String& emailSubject,
  220953. const String& bodyText,
  220954. const StringArray& filesToAttach)
  220955. {
  220956. #if JUCE_IPHONE
  220957. //xxx probably need to use MFMailComposeViewController
  220958. jassertfalse
  220959. return false;
  220960. #else
  220961. const ScopedAutoReleasePool pool;
  220962. String script;
  220963. script << "tell application \"Mail\"\r\n"
  220964. "set newMessage to make new outgoing message with properties {subject:\""
  220965. << emailSubject.replace ("\"", "\\\"")
  220966. << "\", content:\""
  220967. << bodyText.replace ("\"", "\\\"")
  220968. << "\" & return & return}\r\n"
  220969. "tell newMessage\r\n"
  220970. "set visible to true\r\n"
  220971. "set sender to \"sdfsdfsdfewf\"\r\n"
  220972. "make new to recipient at end of to recipients with properties {address:\""
  220973. << targetEmailAddress
  220974. << "\"}\r\n";
  220975. for (int i = 0; i < filesToAttach.size(); ++i)
  220976. {
  220977. script << "tell content\r\n"
  220978. "make new attachment with properties {file name:\""
  220979. << filesToAttach[i].replace ("\"", "\\\"")
  220980. << "\"} at after the last paragraph\r\n"
  220981. "end tell\r\n";
  220982. }
  220983. script << "end tell\r\n"
  220984. "end tell\r\n";
  220985. NSAppleScript* s = [[NSAppleScript alloc]
  220986. initWithSource: juceStringToNS (script)];
  220987. NSDictionary* error = 0;
  220988. const bool ok = [s executeAndReturnError: &error] != nil;
  220989. [s release];
  220990. return ok;
  220991. #endif
  220992. }
  220993. END_JUCE_NAMESPACE
  220994. using namespace JUCE_NAMESPACE;
  220995. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  220996. @interface JuceURLConnection : NSObject
  220997. {
  220998. @public
  220999. NSURLRequest* request;
  221000. NSURLConnection* connection;
  221001. NSMutableData* data;
  221002. Thread* runLoopThread;
  221003. bool initialised, hasFailed, hasFinished;
  221004. int position;
  221005. int64 contentLength;
  221006. NSLock* dataLock;
  221007. }
  221008. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  221009. - (void) dealloc;
  221010. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  221011. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  221012. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  221013. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  221014. - (BOOL) isOpen;
  221015. - (int) read: (char*) dest numBytes: (int) num;
  221016. - (int) readPosition;
  221017. - (void) stop;
  221018. - (void) createConnection;
  221019. @end
  221020. class JuceURLConnectionMessageThread : public Thread
  221021. {
  221022. JuceURLConnection* owner;
  221023. public:
  221024. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  221025. : Thread ("http connection"),
  221026. owner (owner_)
  221027. {
  221028. }
  221029. ~JuceURLConnectionMessageThread()
  221030. {
  221031. stopThread (10000);
  221032. }
  221033. void run()
  221034. {
  221035. [owner createConnection];
  221036. while (! threadShouldExit())
  221037. {
  221038. const ScopedAutoReleasePool pool;
  221039. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  221040. }
  221041. }
  221042. };
  221043. @implementation JuceURLConnection
  221044. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  221045. withCallback: (URL::OpenStreamProgressCallback*) callback
  221046. withContext: (void*) context;
  221047. {
  221048. [super init];
  221049. request = req;
  221050. [request retain];
  221051. data = [[NSMutableData data] retain];
  221052. dataLock = [[NSLock alloc] init];
  221053. connection = 0;
  221054. initialised = false;
  221055. hasFailed = false;
  221056. hasFinished = false;
  221057. contentLength = -1;
  221058. runLoopThread = new JuceURLConnectionMessageThread (self);
  221059. runLoopThread->startThread();
  221060. while (runLoopThread->isThreadRunning() && ! initialised)
  221061. {
  221062. if (callback != 0)
  221063. callback (context, -1, (int) [[request HTTPBody] length]);
  221064. Thread::sleep (1);
  221065. }
  221066. return self;
  221067. }
  221068. - (void) dealloc
  221069. {
  221070. [self stop];
  221071. deleteAndZero (runLoopThread);
  221072. [connection release];
  221073. [data release];
  221074. [dataLock release];
  221075. [request release];
  221076. [super dealloc];
  221077. }
  221078. - (void) createConnection
  221079. {
  221080. connection = [[NSURLConnection alloc] initWithRequest: request
  221081. delegate: [self retain]];
  221082. if (connection == nil)
  221083. runLoopThread->signalThreadShouldExit();
  221084. }
  221085. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  221086. {
  221087. (void) conn;
  221088. [dataLock lock];
  221089. [data setLength: 0];
  221090. [dataLock unlock];
  221091. initialised = true;
  221092. contentLength = [response expectedContentLength];
  221093. }
  221094. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  221095. {
  221096. (void) conn;
  221097. DBG (nsStringToJuce ([error description]));
  221098. hasFailed = true;
  221099. initialised = true;
  221100. if (runLoopThread != 0)
  221101. runLoopThread->signalThreadShouldExit();
  221102. }
  221103. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  221104. {
  221105. (void) conn;
  221106. [dataLock lock];
  221107. [data appendData: newData];
  221108. [dataLock unlock];
  221109. initialised = true;
  221110. }
  221111. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  221112. {
  221113. (void) conn;
  221114. hasFinished = true;
  221115. initialised = true;
  221116. if (runLoopThread != 0)
  221117. runLoopThread->signalThreadShouldExit();
  221118. }
  221119. - (BOOL) isOpen
  221120. {
  221121. return connection != 0 && ! hasFailed;
  221122. }
  221123. - (int) readPosition
  221124. {
  221125. return position;
  221126. }
  221127. - (int) read: (char*) dest numBytes: (int) numNeeded
  221128. {
  221129. int numDone = 0;
  221130. while (numNeeded > 0)
  221131. {
  221132. int available = jmin (numNeeded, (int) [data length]);
  221133. if (available > 0)
  221134. {
  221135. [dataLock lock];
  221136. [data getBytes: dest length: available];
  221137. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  221138. [dataLock unlock];
  221139. numDone += available;
  221140. numNeeded -= available;
  221141. dest += available;
  221142. }
  221143. else
  221144. {
  221145. if (hasFailed || hasFinished)
  221146. break;
  221147. Thread::sleep (1);
  221148. }
  221149. }
  221150. position += numDone;
  221151. return numDone;
  221152. }
  221153. - (void) stop
  221154. {
  221155. [connection cancel];
  221156. if (runLoopThread != 0)
  221157. runLoopThread->stopThread (10000);
  221158. }
  221159. @end
  221160. BEGIN_JUCE_NAMESPACE
  221161. void* juce_openInternetFile (const String& url,
  221162. const String& headers,
  221163. const MemoryBlock& postData,
  221164. const bool isPost,
  221165. URL::OpenStreamProgressCallback* callback,
  221166. void* callbackContext,
  221167. int timeOutMs)
  221168. {
  221169. const ScopedAutoReleasePool pool;
  221170. NSMutableURLRequest* req = [NSMutableURLRequest
  221171. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  221172. cachePolicy: NSURLRequestUseProtocolCachePolicy
  221173. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  221174. if (req == nil)
  221175. return 0;
  221176. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  221177. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  221178. StringArray headerLines;
  221179. headerLines.addLines (headers);
  221180. headerLines.removeEmptyStrings (true);
  221181. for (int i = 0; i < headerLines.size(); ++i)
  221182. {
  221183. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  221184. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  221185. if (key.isNotEmpty() && value.isNotEmpty())
  221186. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  221187. }
  221188. if (isPost && postData.getSize() > 0)
  221189. {
  221190. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  221191. length: postData.getSize()]];
  221192. }
  221193. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  221194. withCallback: callback
  221195. withContext: callbackContext];
  221196. if ([s isOpen])
  221197. return s;
  221198. [s release];
  221199. return 0;
  221200. }
  221201. void juce_closeInternetFile (void* handle)
  221202. {
  221203. JuceURLConnection* const s = (JuceURLConnection*) handle;
  221204. if (s != 0)
  221205. {
  221206. const ScopedAutoReleasePool pool;
  221207. [s stop];
  221208. [s release];
  221209. }
  221210. }
  221211. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  221212. {
  221213. JuceURLConnection* const s = (JuceURLConnection*) handle;
  221214. if (s != 0)
  221215. {
  221216. const ScopedAutoReleasePool pool;
  221217. return [s read: (char*) buffer numBytes: bytesToRead];
  221218. }
  221219. return 0;
  221220. }
  221221. int64 juce_getInternetFileContentLength (void* handle)
  221222. {
  221223. JuceURLConnection* const s = (JuceURLConnection*) handle;
  221224. if (s != 0)
  221225. return s->contentLength;
  221226. return -1;
  221227. }
  221228. int juce_seekInInternetFile (void* handle, int /*newPosition*/)
  221229. {
  221230. JuceURLConnection* const s = (JuceURLConnection*) handle;
  221231. if (s != 0)
  221232. return [s readPosition];
  221233. return 0;
  221234. }
  221235. #endif
  221236. /*** End of inlined file: juce_mac_Network.mm ***/
  221237. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  221238. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221239. // compiled on its own).
  221240. #if JUCE_INCLUDED_FILE
  221241. struct NamedPipeInternal
  221242. {
  221243. String pipeInName, pipeOutName;
  221244. int pipeIn, pipeOut;
  221245. bool volatile createdPipe, blocked, stopReadOperation;
  221246. static void signalHandler (int) {}
  221247. };
  221248. void NamedPipe::cancelPendingReads()
  221249. {
  221250. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  221251. {
  221252. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  221253. intern->stopReadOperation = true;
  221254. char buffer [1] = { 0 };
  221255. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  221256. (void) bytesWritten;
  221257. int timeout = 2000;
  221258. while (intern->blocked && --timeout >= 0)
  221259. Thread::sleep (2);
  221260. intern->stopReadOperation = false;
  221261. }
  221262. }
  221263. void NamedPipe::close()
  221264. {
  221265. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  221266. if (intern != 0)
  221267. {
  221268. internal = 0;
  221269. if (intern->pipeIn != -1)
  221270. ::close (intern->pipeIn);
  221271. if (intern->pipeOut != -1)
  221272. ::close (intern->pipeOut);
  221273. if (intern->createdPipe)
  221274. {
  221275. unlink (intern->pipeInName.toUTF8());
  221276. unlink (intern->pipeOutName.toUTF8());
  221277. }
  221278. delete intern;
  221279. }
  221280. }
  221281. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  221282. {
  221283. close();
  221284. NamedPipeInternal* const intern = new NamedPipeInternal();
  221285. internal = intern;
  221286. intern->createdPipe = createPipe;
  221287. intern->blocked = false;
  221288. intern->stopReadOperation = false;
  221289. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  221290. siginterrupt (SIGPIPE, 1);
  221291. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  221292. intern->pipeInName = pipePath + "_in";
  221293. intern->pipeOutName = pipePath + "_out";
  221294. intern->pipeIn = -1;
  221295. intern->pipeOut = -1;
  221296. if (createPipe)
  221297. {
  221298. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  221299. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  221300. {
  221301. delete intern;
  221302. internal = 0;
  221303. return false;
  221304. }
  221305. }
  221306. return true;
  221307. }
  221308. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  221309. {
  221310. int bytesRead = -1;
  221311. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  221312. if (intern != 0)
  221313. {
  221314. intern->blocked = true;
  221315. if (intern->pipeIn == -1)
  221316. {
  221317. if (intern->createdPipe)
  221318. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  221319. else
  221320. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  221321. if (intern->pipeIn == -1)
  221322. {
  221323. intern->blocked = false;
  221324. return -1;
  221325. }
  221326. }
  221327. bytesRead = 0;
  221328. char* p = (char*) destBuffer;
  221329. while (bytesRead < maxBytesToRead)
  221330. {
  221331. const int bytesThisTime = maxBytesToRead - bytesRead;
  221332. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  221333. if (numRead <= 0 || intern->stopReadOperation)
  221334. {
  221335. bytesRead = -1;
  221336. break;
  221337. }
  221338. bytesRead += numRead;
  221339. p += bytesRead;
  221340. }
  221341. intern->blocked = false;
  221342. }
  221343. return bytesRead;
  221344. }
  221345. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  221346. {
  221347. int bytesWritten = -1;
  221348. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  221349. if (intern != 0)
  221350. {
  221351. if (intern->pipeOut == -1)
  221352. {
  221353. if (intern->createdPipe)
  221354. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  221355. else
  221356. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  221357. if (intern->pipeOut == -1)
  221358. {
  221359. return -1;
  221360. }
  221361. }
  221362. const char* p = (const char*) sourceBuffer;
  221363. bytesWritten = 0;
  221364. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  221365. while (bytesWritten < numBytesToWrite
  221366. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  221367. {
  221368. const int bytesThisTime = numBytesToWrite - bytesWritten;
  221369. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  221370. if (numWritten <= 0)
  221371. {
  221372. bytesWritten = -1;
  221373. break;
  221374. }
  221375. bytesWritten += numWritten;
  221376. p += bytesWritten;
  221377. }
  221378. }
  221379. return bytesWritten;
  221380. }
  221381. #endif
  221382. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  221383. /*** Start of inlined file: juce_mac_Threads.mm ***/
  221384. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221385. // compiled on its own).
  221386. #if JUCE_INCLUDED_FILE
  221387. /*
  221388. Note that a lot of methods that you'd expect to find in this file actually
  221389. live in juce_posix_SharedCode.h!
  221390. */
  221391. void JUCE_API juce_threadEntryPoint (void*);
  221392. void* threadEntryProc (void* userData)
  221393. {
  221394. const ScopedAutoReleasePool pool;
  221395. juce_threadEntryPoint (userData);
  221396. return 0;
  221397. }
  221398. void* juce_createThread (void* userData)
  221399. {
  221400. pthread_t handle = 0;
  221401. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  221402. {
  221403. pthread_detach (handle);
  221404. return (void*) handle;
  221405. }
  221406. return 0;
  221407. }
  221408. void juce_killThread (void* handle)
  221409. {
  221410. if (handle != 0)
  221411. pthread_cancel ((pthread_t) handle);
  221412. }
  221413. void juce_setCurrentThreadName (const String& /*name*/)
  221414. {
  221415. }
  221416. bool juce_setThreadPriority (void* handle, int priority)
  221417. {
  221418. if (handle == 0)
  221419. handle = (void*) pthread_self();
  221420. struct sched_param param;
  221421. int policy;
  221422. pthread_getschedparam ((pthread_t) handle, &policy, &param);
  221423. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  221424. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  221425. }
  221426. Thread::ThreadID Thread::getCurrentThreadId()
  221427. {
  221428. return static_cast <ThreadID> (pthread_self());
  221429. }
  221430. void Thread::yield()
  221431. {
  221432. sched_yield();
  221433. }
  221434. void Thread::setCurrentThreadAffinityMask (const uint32 /*affinityMask*/)
  221435. {
  221436. // xxx
  221437. jassertfalse
  221438. }
  221439. bool Process::isForegroundProcess()
  221440. {
  221441. #if JUCE_MAC
  221442. return [NSApp isActive];
  221443. #else
  221444. return true; // xxx change this if more than one app is ever possible on the iPhone!
  221445. #endif
  221446. }
  221447. void Process::raisePrivilege()
  221448. {
  221449. jassertfalse
  221450. }
  221451. void Process::lowerPrivilege()
  221452. {
  221453. jassertfalse
  221454. }
  221455. void Process::terminate()
  221456. {
  221457. exit (0);
  221458. }
  221459. void Process::setPriority (ProcessPriority)
  221460. {
  221461. // xxx
  221462. }
  221463. #endif
  221464. /*** End of inlined file: juce_mac_Threads.mm ***/
  221465. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  221466. /*
  221467. This file contains posix routines that are common to both the Linux and Mac builds.
  221468. It gets included directly in the cpp files for these platforms.
  221469. */
  221470. CriticalSection::CriticalSection() throw()
  221471. {
  221472. pthread_mutexattr_t atts;
  221473. pthread_mutexattr_init (&atts);
  221474. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  221475. pthread_mutex_init (&internal, &atts);
  221476. }
  221477. CriticalSection::~CriticalSection() throw()
  221478. {
  221479. pthread_mutex_destroy (&internal);
  221480. }
  221481. void CriticalSection::enter() const throw()
  221482. {
  221483. pthread_mutex_lock (&internal);
  221484. }
  221485. bool CriticalSection::tryEnter() const throw()
  221486. {
  221487. return pthread_mutex_trylock (&internal) == 0;
  221488. }
  221489. void CriticalSection::exit() const throw()
  221490. {
  221491. pthread_mutex_unlock (&internal);
  221492. }
  221493. class WaitableEventImpl
  221494. {
  221495. public:
  221496. WaitableEventImpl (const bool manualReset_)
  221497. : triggered (false),
  221498. manualReset (manualReset_)
  221499. {
  221500. pthread_cond_init (&condition, 0);
  221501. pthread_mutex_init (&mutex, 0);
  221502. }
  221503. ~WaitableEventImpl()
  221504. {
  221505. pthread_cond_destroy (&condition);
  221506. pthread_mutex_destroy (&mutex);
  221507. }
  221508. bool wait (const int timeOutMillisecs) throw()
  221509. {
  221510. pthread_mutex_lock (&mutex);
  221511. if (! triggered)
  221512. {
  221513. if (timeOutMillisecs < 0)
  221514. {
  221515. do
  221516. {
  221517. pthread_cond_wait (&condition, &mutex);
  221518. }
  221519. while (! triggered);
  221520. }
  221521. else
  221522. {
  221523. struct timeval now;
  221524. gettimeofday (&now, 0);
  221525. struct timespec time;
  221526. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  221527. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  221528. if (time.tv_nsec >= 1000000000)
  221529. {
  221530. time.tv_nsec -= 1000000000;
  221531. time.tv_sec++;
  221532. }
  221533. do
  221534. {
  221535. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  221536. {
  221537. pthread_mutex_unlock (&mutex);
  221538. return false;
  221539. }
  221540. }
  221541. while (! triggered);
  221542. }
  221543. }
  221544. if (! manualReset)
  221545. triggered = false;
  221546. pthread_mutex_unlock (&mutex);
  221547. return true;
  221548. }
  221549. void signal() throw()
  221550. {
  221551. pthread_mutex_lock (&mutex);
  221552. triggered = true;
  221553. pthread_cond_broadcast (&condition);
  221554. pthread_mutex_unlock (&mutex);
  221555. }
  221556. void reset() throw()
  221557. {
  221558. pthread_mutex_lock (&mutex);
  221559. triggered = false;
  221560. pthread_mutex_unlock (&mutex);
  221561. }
  221562. private:
  221563. pthread_cond_t condition;
  221564. pthread_mutex_t mutex;
  221565. bool triggered;
  221566. const bool manualReset;
  221567. WaitableEventImpl (const WaitableEventImpl&);
  221568. WaitableEventImpl& operator= (const WaitableEventImpl&);
  221569. };
  221570. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  221571. : internal (new WaitableEventImpl (manualReset))
  221572. {
  221573. }
  221574. WaitableEvent::~WaitableEvent() throw()
  221575. {
  221576. delete static_cast <WaitableEventImpl*> (internal);
  221577. }
  221578. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  221579. {
  221580. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  221581. }
  221582. void WaitableEvent::signal() const throw()
  221583. {
  221584. static_cast <WaitableEventImpl*> (internal)->signal();
  221585. }
  221586. void WaitableEvent::reset() const throw()
  221587. {
  221588. static_cast <WaitableEventImpl*> (internal)->reset();
  221589. }
  221590. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  221591. {
  221592. struct timespec time;
  221593. time.tv_sec = millisecs / 1000;
  221594. time.tv_nsec = (millisecs % 1000) * 1000000;
  221595. nanosleep (&time, 0);
  221596. }
  221597. const juce_wchar File::separator = '/';
  221598. const String File::separatorString ("/");
  221599. const File File::getCurrentWorkingDirectory()
  221600. {
  221601. HeapBlock<char> heapBuffer;
  221602. char localBuffer [1024];
  221603. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  221604. int bufferSize = 4096;
  221605. while (cwd == 0 && errno == ERANGE)
  221606. {
  221607. heapBuffer.malloc (bufferSize);
  221608. cwd = getcwd (heapBuffer, bufferSize - 1);
  221609. bufferSize += 1024;
  221610. }
  221611. return File (String::fromUTF8 (cwd));
  221612. }
  221613. bool File::setAsCurrentWorkingDirectory() const
  221614. {
  221615. return chdir (getFullPathName().toUTF8()) == 0;
  221616. }
  221617. static bool juce_stat (const String& fileName, struct stat& info)
  221618. {
  221619. return fileName.isNotEmpty()
  221620. && (stat (fileName.toUTF8(), &info) == 0);
  221621. }
  221622. bool File::isDirectory() const
  221623. {
  221624. struct stat info;
  221625. return fullPath.isEmpty()
  221626. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  221627. }
  221628. bool File::exists() const
  221629. {
  221630. return fullPath.isNotEmpty()
  221631. && access (fullPath.toUTF8(), F_OK) == 0;
  221632. }
  221633. bool File::existsAsFile() const
  221634. {
  221635. return exists() && ! isDirectory();
  221636. }
  221637. int64 File::getSize() const
  221638. {
  221639. struct stat info;
  221640. return juce_stat (fullPath, info) ? info.st_size : 0;
  221641. }
  221642. bool File::hasWriteAccess() const
  221643. {
  221644. if (exists())
  221645. return access (fullPath.toUTF8(), W_OK) == 0;
  221646. if ((! isDirectory()) && fullPath.containsChar (separator))
  221647. return getParentDirectory().hasWriteAccess();
  221648. return false;
  221649. }
  221650. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  221651. {
  221652. struct stat info;
  221653. const int res = stat (fullPath.toUTF8(), &info);
  221654. if (res != 0)
  221655. return false;
  221656. info.st_mode &= 0777; // Just permissions
  221657. if (shouldBeReadOnly)
  221658. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  221659. else
  221660. // Give everybody write permission?
  221661. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  221662. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  221663. }
  221664. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  221665. {
  221666. modificationTime = 0;
  221667. accessTime = 0;
  221668. creationTime = 0;
  221669. struct stat info;
  221670. const int res = stat (fullPath.toUTF8(), &info);
  221671. if (res == 0)
  221672. {
  221673. modificationTime = (int64) info.st_mtime * 1000;
  221674. accessTime = (int64) info.st_atime * 1000;
  221675. creationTime = (int64) info.st_ctime * 1000;
  221676. }
  221677. }
  221678. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  221679. {
  221680. struct utimbuf times;
  221681. times.actime = (time_t) (accessTime / 1000);
  221682. times.modtime = (time_t) (modificationTime / 1000);
  221683. return utime (fullPath.toUTF8(), &times) == 0;
  221684. }
  221685. bool File::deleteFile() const
  221686. {
  221687. if (! exists())
  221688. return true;
  221689. else if (isDirectory())
  221690. return rmdir (fullPath.toUTF8()) == 0;
  221691. else
  221692. return remove (fullPath.toUTF8()) == 0;
  221693. }
  221694. bool File::moveInternal (const File& dest) const
  221695. {
  221696. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  221697. return true;
  221698. if (hasWriteAccess() && copyInternal (dest))
  221699. {
  221700. if (deleteFile())
  221701. return true;
  221702. dest.deleteFile();
  221703. }
  221704. return false;
  221705. }
  221706. void File::createDirectoryInternal (const String& fileName) const
  221707. {
  221708. mkdir (fileName.toUTF8(), 0777);
  221709. }
  221710. void* juce_fileOpen (const File& file, bool forWriting)
  221711. {
  221712. int flags = O_RDONLY;
  221713. if (forWriting)
  221714. {
  221715. if (file.exists())
  221716. {
  221717. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  221718. if (f != -1)
  221719. lseek (f, 0, SEEK_END);
  221720. return (void*) f;
  221721. }
  221722. else
  221723. {
  221724. flags = O_RDWR + O_CREAT;
  221725. }
  221726. }
  221727. return (void*) open (file.getFullPathName().toUTF8(), flags, 00644);
  221728. }
  221729. void juce_fileClose (void* handle)
  221730. {
  221731. if (handle != 0)
  221732. close ((int) (pointer_sized_int) handle);
  221733. }
  221734. int juce_fileRead (void* handle, void* buffer, int size)
  221735. {
  221736. if (handle != 0)
  221737. return jmax (0, (int) read ((int) (pointer_sized_int) handle, buffer, size));
  221738. return 0;
  221739. }
  221740. int juce_fileWrite (void* handle, const void* buffer, int size)
  221741. {
  221742. if (handle != 0)
  221743. return (int) write ((int) (pointer_sized_int) handle, buffer, size);
  221744. return 0;
  221745. }
  221746. int64 juce_fileSetPosition (void* handle, int64 pos)
  221747. {
  221748. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  221749. return pos;
  221750. return -1;
  221751. }
  221752. int64 FileOutputStream::getPositionInternal() const
  221753. {
  221754. if (fileHandle != 0)
  221755. return lseek ((int) (pointer_sized_int) fileHandle, 0, SEEK_CUR);
  221756. return -1;
  221757. }
  221758. void FileOutputStream::flushInternal()
  221759. {
  221760. if (fileHandle != 0)
  221761. fsync ((int) (pointer_sized_int) fileHandle);
  221762. }
  221763. const File juce_getExecutableFile()
  221764. {
  221765. Dl_info exeInfo;
  221766. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  221767. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  221768. }
  221769. // if this file doesn't exist, find a parent of it that does..
  221770. static bool juce_doStatFS (File f, struct statfs& result)
  221771. {
  221772. for (int i = 5; --i >= 0;)
  221773. {
  221774. if (f.exists())
  221775. break;
  221776. f = f.getParentDirectory();
  221777. }
  221778. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  221779. }
  221780. int64 File::getBytesFreeOnVolume() const
  221781. {
  221782. struct statfs buf;
  221783. if (juce_doStatFS (*this, buf))
  221784. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  221785. return 0;
  221786. }
  221787. int64 File::getVolumeTotalSize() const
  221788. {
  221789. struct statfs buf;
  221790. if (juce_doStatFS (*this, buf))
  221791. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  221792. return 0;
  221793. }
  221794. const String File::getVolumeLabel() const
  221795. {
  221796. #if JUCE_MAC
  221797. struct VolAttrBuf
  221798. {
  221799. u_int32_t length;
  221800. attrreference_t mountPointRef;
  221801. char mountPointSpace [MAXPATHLEN];
  221802. } attrBuf;
  221803. struct attrlist attrList;
  221804. zerostruct (attrList);
  221805. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  221806. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  221807. File f (*this);
  221808. for (;;)
  221809. {
  221810. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  221811. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  221812. (int) attrBuf.mountPointRef.attr_length);
  221813. const File parent (f.getParentDirectory());
  221814. if (f == parent)
  221815. break;
  221816. f = parent;
  221817. }
  221818. #endif
  221819. return String::empty;
  221820. }
  221821. int File::getVolumeSerialNumber() const
  221822. {
  221823. return 0; // xxx
  221824. }
  221825. void juce_runSystemCommand (const String& command)
  221826. {
  221827. int result = system (command.toUTF8());
  221828. (void) result;
  221829. }
  221830. const String juce_getOutputFromCommand (const String& command)
  221831. {
  221832. // slight bodge here, as we just pipe the output into a temp file and read it...
  221833. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  221834. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  221835. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  221836. String result (tempFile.loadFileAsString());
  221837. tempFile.deleteFile();
  221838. return result;
  221839. }
  221840. class InterProcessLock::Pimpl
  221841. {
  221842. public:
  221843. Pimpl (const String& name, const int timeOutMillisecs)
  221844. : handle (0), refCount (1)
  221845. {
  221846. #if JUCE_MAC
  221847. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  221848. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  221849. #else
  221850. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  221851. #endif
  221852. temp.create();
  221853. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  221854. if (handle != 0)
  221855. {
  221856. struct flock fl;
  221857. zerostruct (fl);
  221858. fl.l_whence = SEEK_SET;
  221859. fl.l_type = F_WRLCK;
  221860. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  221861. for (;;)
  221862. {
  221863. const int result = fcntl (handle, F_SETLK, &fl);
  221864. if (result >= 0)
  221865. return;
  221866. if (errno != EINTR)
  221867. {
  221868. if (timeOutMillisecs == 0
  221869. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  221870. break;
  221871. Thread::sleep (10);
  221872. }
  221873. }
  221874. }
  221875. closeFile();
  221876. }
  221877. ~Pimpl()
  221878. {
  221879. closeFile();
  221880. }
  221881. void closeFile()
  221882. {
  221883. if (handle != 0)
  221884. {
  221885. struct flock fl;
  221886. zerostruct (fl);
  221887. fl.l_whence = SEEK_SET;
  221888. fl.l_type = F_UNLCK;
  221889. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  221890. {}
  221891. close (handle);
  221892. handle = 0;
  221893. }
  221894. }
  221895. int handle, refCount;
  221896. };
  221897. InterProcessLock::InterProcessLock (const String& name_)
  221898. : name (name_)
  221899. {
  221900. }
  221901. InterProcessLock::~InterProcessLock()
  221902. {
  221903. }
  221904. bool InterProcessLock::enter (const int timeOutMillisecs)
  221905. {
  221906. const ScopedLock sl (lock);
  221907. if (pimpl == 0)
  221908. {
  221909. pimpl = new Pimpl (name, timeOutMillisecs);
  221910. if (pimpl->handle == 0)
  221911. pimpl = 0;
  221912. }
  221913. else
  221914. {
  221915. pimpl->refCount++;
  221916. }
  221917. return pimpl != 0;
  221918. }
  221919. void InterProcessLock::exit()
  221920. {
  221921. const ScopedLock sl (lock);
  221922. // Trying to release the lock too many times!
  221923. jassert (pimpl != 0);
  221924. if (pimpl != 0 && --(pimpl->refCount) == 0)
  221925. pimpl = 0;
  221926. }
  221927. /*** End of inlined file: juce_posix_SharedCode.h ***/
  221928. /*** Start of inlined file: juce_mac_Files.mm ***/
  221929. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221930. // compiled on its own).
  221931. #if JUCE_INCLUDED_FILE
  221932. /*
  221933. Note that a lot of methods that you'd expect to find in this file actually
  221934. live in juce_posix_SharedCode.h!
  221935. */
  221936. bool File::copyInternal (const File& dest) const
  221937. {
  221938. const ScopedAutoReleasePool pool;
  221939. NSFileManager* fm = [NSFileManager defaultManager];
  221940. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  221941. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  221942. && [fm copyItemAtPath: juceStringToNS (fullPath)
  221943. toPath: juceStringToNS (dest.getFullPathName())
  221944. error: nil];
  221945. #else
  221946. && [fm copyPath: juceStringToNS (fullPath)
  221947. toPath: juceStringToNS (dest.getFullPathName())
  221948. handler: nil];
  221949. #endif
  221950. }
  221951. void File::findFileSystemRoots (Array<File>& destArray)
  221952. {
  221953. destArray.add (File ("/"));
  221954. }
  221955. static bool isFileOnDriveType (const File& f, const char* const* types)
  221956. {
  221957. struct statfs buf;
  221958. if (juce_doStatFS (f, buf))
  221959. {
  221960. const String type (buf.f_fstypename);
  221961. while (*types != 0)
  221962. if (type.equalsIgnoreCase (*types++))
  221963. return true;
  221964. }
  221965. return false;
  221966. }
  221967. bool File::isOnCDRomDrive() const
  221968. {
  221969. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  221970. return isFileOnDriveType (*this, cdTypes);
  221971. }
  221972. bool File::isOnHardDisk() const
  221973. {
  221974. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  221975. return ! (isOnCDRomDrive() || isFileOnDriveType (*this, nonHDTypes));
  221976. }
  221977. bool File::isOnRemovableDrive() const
  221978. {
  221979. #if JUCE_IPHONE
  221980. return false; // xxx is this possible?
  221981. #else
  221982. const ScopedAutoReleasePool pool;
  221983. BOOL removable = false;
  221984. [[NSWorkspace sharedWorkspace]
  221985. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  221986. isRemovable: &removable
  221987. isWritable: nil
  221988. isUnmountable: nil
  221989. description: nil
  221990. type: nil];
  221991. return removable;
  221992. #endif
  221993. }
  221994. static bool juce_isHiddenFile (const String& path)
  221995. {
  221996. #if JUCE_IPHONE
  221997. return File (path).getFileName().startsWithChar ('.');
  221998. #else
  221999. FSRef ref;
  222000. if (! PlatformUtilities::makeFSRefFromPath (&ref, path))
  222001. return false;
  222002. FSCatalogInfo info;
  222003. FSGetCatalogInfo (&ref, kFSCatInfoNodeFlags | kFSCatInfoFinderInfo, &info, 0, 0, 0);
  222004. if ((info.nodeFlags & kFSNodeIsDirectoryBit) != 0)
  222005. return (((FolderInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  222006. return (((FileInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  222007. #endif
  222008. }
  222009. bool File::isHidden() const
  222010. {
  222011. return juce_isHiddenFile (getFullPathName());
  222012. }
  222013. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  222014. const File File::getSpecialLocation (const SpecialLocationType type)
  222015. {
  222016. const ScopedAutoReleasePool pool;
  222017. String resultPath;
  222018. switch (type)
  222019. {
  222020. case userHomeDirectory:
  222021. resultPath = nsStringToJuce (NSHomeDirectory());
  222022. break;
  222023. case userDocumentsDirectory:
  222024. resultPath = "~/Documents";
  222025. break;
  222026. case userDesktopDirectory:
  222027. resultPath = "~/Desktop";
  222028. break;
  222029. case userApplicationDataDirectory:
  222030. resultPath = "~/Library";
  222031. break;
  222032. case commonApplicationDataDirectory:
  222033. resultPath = "/Library";
  222034. break;
  222035. case globalApplicationsDirectory:
  222036. resultPath = "/Applications";
  222037. break;
  222038. case userMusicDirectory:
  222039. resultPath = "~/Music";
  222040. break;
  222041. case userMoviesDirectory:
  222042. resultPath = "~/Movies";
  222043. break;
  222044. case tempDirectory:
  222045. {
  222046. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  222047. tmp.createDirectory();
  222048. return tmp.getFullPathName();
  222049. }
  222050. case invokedExecutableFile:
  222051. if (juce_Argv0 != 0)
  222052. return File (String::fromUTF8 (juce_Argv0));
  222053. // deliberate fall-through...
  222054. case currentExecutableFile:
  222055. return juce_getExecutableFile();
  222056. case currentApplicationFile:
  222057. {
  222058. const File exe (juce_getExecutableFile());
  222059. const File parent (exe.getParentDirectory());
  222060. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  222061. ? parent.getParentDirectory().getParentDirectory()
  222062. : exe;
  222063. }
  222064. default:
  222065. jassertfalse // unknown type?
  222066. break;
  222067. }
  222068. if (resultPath.isNotEmpty())
  222069. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  222070. return File::nonexistent;
  222071. }
  222072. const String File::getVersion() const
  222073. {
  222074. const ScopedAutoReleasePool pool;
  222075. String result;
  222076. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  222077. if (bundle != 0)
  222078. {
  222079. NSDictionary* info = [bundle infoDictionary];
  222080. if (info != 0)
  222081. {
  222082. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  222083. if (name != nil)
  222084. result = nsStringToJuce (name);
  222085. }
  222086. }
  222087. return result;
  222088. }
  222089. const File File::getLinkedTarget() const
  222090. {
  222091. #if JUCE_IPHONE || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  222092. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  222093. #else
  222094. NSString* dest = [[NSFileManager defaultManager] pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  222095. #endif
  222096. if (dest != nil)
  222097. return File (nsStringToJuce (dest));
  222098. return *this;
  222099. }
  222100. bool File::moveToTrash() const
  222101. {
  222102. if (! exists())
  222103. return true;
  222104. #if JUCE_IPHONE
  222105. return deleteFile(); //xxx is there a trashcan on the iPhone?
  222106. #else
  222107. const ScopedAutoReleasePool pool;
  222108. NSString* p = juceStringToNS (getFullPathName());
  222109. return [[NSWorkspace sharedWorkspace]
  222110. performFileOperation: NSWorkspaceRecycleOperation
  222111. source: [p stringByDeletingLastPathComponent]
  222112. destination: @""
  222113. files: [NSArray arrayWithObject: [p lastPathComponent]]
  222114. tag: nil ];
  222115. #endif
  222116. }
  222117. class DirectoryIterator::NativeIterator::Pimpl
  222118. {
  222119. public:
  222120. Pimpl (const File& directory, const String& wildCard_)
  222121. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  222122. wildCard (wildCard_),
  222123. enumerator (0)
  222124. {
  222125. ScopedAutoReleasePool pool;
  222126. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  222127. wildcardUTF8 = wildCard.toUTF8();
  222128. }
  222129. ~Pimpl()
  222130. {
  222131. [enumerator release];
  222132. }
  222133. bool next (String& filenameFound,
  222134. bool* const isDir, bool* const isHidden, int64* const fileSize,
  222135. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  222136. {
  222137. ScopedAutoReleasePool pool;
  222138. for (;;)
  222139. {
  222140. NSString* file;
  222141. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  222142. return false;
  222143. [enumerator skipDescendents];
  222144. filenameFound = nsStringToJuce (file);
  222145. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  222146. continue;
  222147. const String path (parentDir + filenameFound);
  222148. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  222149. {
  222150. struct stat info;
  222151. const bool statOk = juce_stat (path, info);
  222152. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  222153. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  222154. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  222155. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  222156. }
  222157. if (isHidden != 0)
  222158. *isHidden = juce_isHiddenFile (path);
  222159. if (isReadOnly != 0)
  222160. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  222161. return true;
  222162. }
  222163. }
  222164. private:
  222165. String parentDir, wildCard;
  222166. const char* wildcardUTF8;
  222167. NSDirectoryEnumerator* enumerator;
  222168. Pimpl (const Pimpl&);
  222169. Pimpl& operator= (const Pimpl&);
  222170. };
  222171. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  222172. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  222173. {
  222174. }
  222175. DirectoryIterator::NativeIterator::~NativeIterator()
  222176. {
  222177. }
  222178. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  222179. bool* const isDir, bool* const isHidden, int64* const fileSize,
  222180. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  222181. {
  222182. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  222183. }
  222184. bool juce_launchExecutable (const String& pathAndArguments)
  222185. {
  222186. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  222187. const int cpid = fork();
  222188. if (cpid == 0)
  222189. {
  222190. // Child process
  222191. if (execve (argv[0], (char**) argv, 0) < 0)
  222192. exit (0);
  222193. }
  222194. else
  222195. {
  222196. if (cpid < 0)
  222197. return false;
  222198. }
  222199. return true;
  222200. }
  222201. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  222202. {
  222203. #if JUCE_IPHONE
  222204. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  222205. #else
  222206. const ScopedAutoReleasePool pool;
  222207. if (parameters.isEmpty())
  222208. {
  222209. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  222210. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  222211. }
  222212. bool ok = false;
  222213. FSRef ref;
  222214. if (PlatformUtilities::makeFSRefFromPath (&ref, fileName))
  222215. {
  222216. if (PlatformUtilities::isBundle (fileName))
  222217. {
  222218. NSMutableArray* urls = [NSMutableArray array];
  222219. StringArray docs;
  222220. docs.addTokens (parameters, true);
  222221. for (int i = 0; i < docs.size(); ++i)
  222222. [urls addObject: juceStringToNS (docs[i])];
  222223. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  222224. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  222225. options: 0
  222226. additionalEventParamDescriptor: nil
  222227. launchIdentifiers: nil];
  222228. }
  222229. else
  222230. {
  222231. ok = juce_launchExecutable ("\"" + fileName + "\" " + parameters);
  222232. }
  222233. }
  222234. return ok;
  222235. #endif
  222236. }
  222237. void File::revealToUser() const
  222238. {
  222239. #if ! JUCE_IPHONE
  222240. if (exists())
  222241. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  222242. else if (getParentDirectory().exists())
  222243. getParentDirectory().revealToUser();
  222244. #endif
  222245. }
  222246. #if ! JUCE_IPHONE
  222247. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  222248. {
  222249. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  222250. }
  222251. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  222252. {
  222253. char path [2048];
  222254. zerostruct (path);
  222255. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  222256. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  222257. return String::empty;
  222258. }
  222259. #endif
  222260. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  222261. {
  222262. const ScopedAutoReleasePool pool;
  222263. #if JUCE_IPHONE || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  222264. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  222265. #else
  222266. NSDictionary* fileDict = [[NSFileManager defaultManager] fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  222267. #endif
  222268. //return (OSType) [fileDict objectForKey: NSFileHFSTypeCode];
  222269. return [fileDict fileHFSTypeCode];
  222270. }
  222271. bool PlatformUtilities::isBundle (const String& filename)
  222272. {
  222273. #if JUCE_IPHONE
  222274. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  222275. #else
  222276. const ScopedAutoReleasePool pool;
  222277. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  222278. #endif
  222279. }
  222280. #endif
  222281. /*** End of inlined file: juce_mac_Files.mm ***/
  222282. #if JUCE_IPHONE
  222283. /*** Start of inlined file: juce_iphone_MiscUtilities.mm ***/
  222284. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222285. // compiled on its own).
  222286. #if JUCE_INCLUDED_FILE
  222287. static JUCEApplication* juce_intialisingApp;
  222288. END_JUCE_NAMESPACE
  222289. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  222290. {
  222291. }
  222292. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  222293. - (void) applicationWillResignActive: (UIApplication*) application;
  222294. @end
  222295. @implementation JuceAppStartupDelegate
  222296. - (void) applicationDidFinishLaunching: (UIApplication*) application
  222297. {
  222298. String dummy;
  222299. if (! juce_intialisingApp->initialiseApp (dummy))
  222300. exit (0);
  222301. }
  222302. - (void) applicationWillResignActive: (UIApplication*) application
  222303. {
  222304. JUCEApplication::shutdownAppAndClearUp();
  222305. }
  222306. @end
  222307. BEGIN_JUCE_NAMESPACE
  222308. int juce_IPhoneMain (int argc, const char* argv[], JUCEApplication* app)
  222309. {
  222310. juce_intialisingApp = app;
  222311. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  222312. }
  222313. ScopedAutoReleasePool::ScopedAutoReleasePool()
  222314. {
  222315. pool = [[NSAutoreleasePool alloc] init];
  222316. }
  222317. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  222318. {
  222319. [((NSAutoreleasePool*) pool) release];
  222320. }
  222321. void PlatformUtilities::beep()
  222322. {
  222323. //xxx
  222324. //AudioServicesPlaySystemSound ();
  222325. }
  222326. void PlatformUtilities::addItemToDock (const File& file)
  222327. {
  222328. }
  222329. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  222330. END_JUCE_NAMESPACE
  222331. @interface JuceAlertBoxDelegate : NSObject
  222332. {
  222333. @public
  222334. bool clickedOk;
  222335. }
  222336. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  222337. @end
  222338. @implementation JuceAlertBoxDelegate
  222339. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  222340. {
  222341. clickedOk = (buttonIndex == 0);
  222342. alertView.hidden = true;
  222343. }
  222344. @end
  222345. BEGIN_JUCE_NAMESPACE
  222346. // (This function is used directly by other bits of code)
  222347. bool juce_iPhoneShowModalAlert (const String& title,
  222348. const String& bodyText,
  222349. NSString* okButtonText,
  222350. NSString* cancelButtonText)
  222351. {
  222352. const ScopedAutoReleasePool pool;
  222353. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  222354. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  222355. message: juceStringToNS (bodyText)
  222356. delegate: callback
  222357. cancelButtonTitle: okButtonText
  222358. otherButtonTitles: cancelButtonText, nil];
  222359. [alert retain];
  222360. [alert show];
  222361. while (! alert.hidden && alert.superview != nil)
  222362. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  222363. const bool result = callback->clickedOk;
  222364. [alert release];
  222365. [callback release];
  222366. return result;
  222367. }
  222368. bool AlertWindow::showNativeDialogBox (const String& title,
  222369. const String& bodyText,
  222370. bool isOkCancel)
  222371. {
  222372. return juce_iPhoneShowModalAlert (title, bodyText,
  222373. @"OK",
  222374. isOkCancel ? @"Cancel" : nil);
  222375. }
  222376. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  222377. {
  222378. jassertfalse // no such thing on the iphone!
  222379. return false;
  222380. }
  222381. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  222382. {
  222383. jassertfalse // no such thing on the iphone!
  222384. return false;
  222385. }
  222386. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  222387. {
  222388. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  222389. }
  222390. bool Desktop::isScreenSaverEnabled() throw()
  222391. {
  222392. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  222393. }
  222394. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  222395. {
  222396. const ScopedAutoReleasePool pool;
  222397. monitorCoords.clear();
  222398. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  222399. : [[UIScreen mainScreen] bounds];
  222400. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  222401. (int) r.origin.y,
  222402. (int) r.size.width,
  222403. (int) r.size.height));
  222404. }
  222405. #endif
  222406. #endif
  222407. /*** End of inlined file: juce_iphone_MiscUtilities.mm ***/
  222408. #else
  222409. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  222410. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222411. // compiled on its own).
  222412. #if JUCE_INCLUDED_FILE
  222413. ScopedAutoReleasePool::ScopedAutoReleasePool()
  222414. {
  222415. pool = [[NSAutoreleasePool alloc] init];
  222416. }
  222417. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  222418. {
  222419. [((NSAutoreleasePool*) pool) release];
  222420. }
  222421. void PlatformUtilities::beep()
  222422. {
  222423. NSBeep();
  222424. }
  222425. void PlatformUtilities::addItemToDock (const File& file)
  222426. {
  222427. // check that it's not already there...
  222428. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  222429. .containsIgnoreCase (file.getFullPathName()))
  222430. {
  222431. 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>"
  222432. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  222433. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  222434. }
  222435. }
  222436. int PlatformUtilities::getOSXMinorVersionNumber()
  222437. {
  222438. SInt32 versionMinor = 0;
  222439. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  222440. (void) err;
  222441. jassert (err == noErr);
  222442. return (int) versionMinor;
  222443. }
  222444. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  222445. bool AlertWindow::showNativeDialogBox (const String& title,
  222446. const String& bodyText,
  222447. bool isOkCancel)
  222448. {
  222449. const ScopedAutoReleasePool pool;
  222450. return NSRunAlertPanel (juceStringToNS (title),
  222451. juceStringToNS (bodyText),
  222452. @"Ok",
  222453. isOkCancel ? @"Cancel" : nil,
  222454. nil) == NSAlertDefaultReturn;
  222455. }
  222456. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  222457. {
  222458. if (files.size() == 0)
  222459. return false;
  222460. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  222461. if (draggingSource == 0)
  222462. {
  222463. jassertfalse // This method must be called in response to a component's mouseDown or mouseDrag event!
  222464. return false;
  222465. }
  222466. Component* sourceComp = draggingSource->getComponentUnderMouse();
  222467. if (sourceComp == 0)
  222468. {
  222469. jassertfalse // This method must be called in response to a component's mouseDown or mouseDrag event!
  222470. return false;
  222471. }
  222472. const ScopedAutoReleasePool pool;
  222473. NSView* view = (NSView*) sourceComp->getWindowHandle();
  222474. if (view == 0)
  222475. return false;
  222476. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  222477. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  222478. owner: nil];
  222479. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  222480. for (int i = 0; i < files.size(); ++i)
  222481. [filesArray addObject: juceStringToNS (files[i])];
  222482. [pboard setPropertyList: filesArray
  222483. forType: NSFilenamesPboardType];
  222484. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  222485. fromView: nil];
  222486. dragPosition.x -= 16;
  222487. dragPosition.y -= 16;
  222488. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  222489. at: dragPosition
  222490. offset: NSMakeSize (0, 0)
  222491. event: [[view window] currentEvent]
  222492. pasteboard: pboard
  222493. source: view
  222494. slideBack: YES];
  222495. return true;
  222496. }
  222497. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  222498. {
  222499. jassertfalse // not implemented!
  222500. return false;
  222501. }
  222502. bool Desktop::canUseSemiTransparentWindows() throw()
  222503. {
  222504. return true;
  222505. }
  222506. const Point<int> Desktop::getMousePosition()
  222507. {
  222508. const ScopedAutoReleasePool pool;
  222509. const NSPoint p ([NSEvent mouseLocation]);
  222510. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  222511. }
  222512. void Desktop::setMousePosition (const Point<int>& newPosition)
  222513. {
  222514. // this rubbish needs to be done around the warp call, to avoid causing a
  222515. // bizarre glitch..
  222516. CGAssociateMouseAndMouseCursorPosition (false);
  222517. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  222518. CGAssociateMouseAndMouseCursorPosition (true);
  222519. }
  222520. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  222521. class ScreenSaverDefeater : public Timer,
  222522. public DeletedAtShutdown
  222523. {
  222524. public:
  222525. ScreenSaverDefeater()
  222526. {
  222527. startTimer (10000);
  222528. timerCallback();
  222529. }
  222530. ~ScreenSaverDefeater() {}
  222531. void timerCallback()
  222532. {
  222533. if (Process::isForegroundProcess())
  222534. UpdateSystemActivity (UsrActivity);
  222535. }
  222536. };
  222537. static ScreenSaverDefeater* screenSaverDefeater = 0;
  222538. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  222539. {
  222540. if (isEnabled)
  222541. {
  222542. deleteAndZero (screenSaverDefeater);
  222543. }
  222544. else if (screenSaverDefeater == 0)
  222545. {
  222546. screenSaverDefeater = new ScreenSaverDefeater();
  222547. }
  222548. }
  222549. bool Desktop::isScreenSaverEnabled() throw()
  222550. {
  222551. return screenSaverDefeater == 0;
  222552. }
  222553. #else
  222554. static IOPMAssertionID screenSaverDisablerID = 0;
  222555. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  222556. {
  222557. if (isEnabled)
  222558. {
  222559. if (screenSaverDisablerID != 0)
  222560. {
  222561. IOPMAssertionRelease (screenSaverDisablerID);
  222562. screenSaverDisablerID = 0;
  222563. }
  222564. }
  222565. else
  222566. {
  222567. if (screenSaverDisablerID == 0)
  222568. {
  222569. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  222570. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  222571. CFSTR ("Juce"), &screenSaverDisablerID);
  222572. #else
  222573. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  222574. &screenSaverDisablerID);
  222575. #endif
  222576. }
  222577. }
  222578. }
  222579. bool Desktop::isScreenSaverEnabled() throw()
  222580. {
  222581. return screenSaverDisablerID == 0;
  222582. }
  222583. #endif
  222584. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  222585. {
  222586. const ScopedAutoReleasePool pool;
  222587. monitorCoords.clear();
  222588. NSArray* screens = [NSScreen screens];
  222589. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  222590. for (unsigned int i = 0; i < [screens count]; ++i)
  222591. {
  222592. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  222593. NSRect r = clipToWorkArea ? [s visibleFrame]
  222594. : [s frame];
  222595. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  222596. (int) (mainScreenBottom - (r.origin.y + r.size.height)),
  222597. (int) r.size.width,
  222598. (int) r.size.height));
  222599. }
  222600. jassert (monitorCoords.size() > 0);
  222601. }
  222602. #endif
  222603. #endif
  222604. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  222605. #endif
  222606. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  222607. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222608. // compiled on its own).
  222609. #if JUCE_INCLUDED_FILE
  222610. void Logger::outputDebugString (const String& text)
  222611. {
  222612. std::cerr << text << std::endl;
  222613. }
  222614. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  222615. {
  222616. static char testResult = 0;
  222617. if (testResult == 0)
  222618. {
  222619. struct kinfo_proc info;
  222620. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  222621. size_t sz = sizeof (info);
  222622. sysctl (m, 4, &info, &sz, 0, 0);
  222623. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  222624. }
  222625. return testResult > 0;
  222626. }
  222627. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  222628. {
  222629. return juce_isRunningUnderDebugger();
  222630. }
  222631. #endif
  222632. /*** End of inlined file: juce_mac_Debugging.mm ***/
  222633. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  222634. #if JUCE_IPHONE
  222635. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  222636. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222637. // compiled on its own).
  222638. #if JUCE_INCLUDED_FILE
  222639. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  222640. #define SUPPORT_10_4_FONTS 1
  222641. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  222642. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  222643. #define SUPPORT_ONLY_10_4_FONTS 1
  222644. #endif
  222645. END_JUCE_NAMESPACE
  222646. @interface NSFont (PrivateHack)
  222647. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  222648. @end
  222649. BEGIN_JUCE_NAMESPACE
  222650. #endif
  222651. class MacTypeface : public Typeface
  222652. {
  222653. public:
  222654. MacTypeface (const Font& font)
  222655. : Typeface (font.getTypefaceName())
  222656. {
  222657. const ScopedAutoReleasePool pool;
  222658. renderingTransform = CGAffineTransformIdentity;
  222659. bool needsItalicTransform = false;
  222660. #if JUCE_IPHONE
  222661. NSString* fontName = juceStringToNS (font.getTypefaceName());
  222662. if (font.isItalic() || font.isBold())
  222663. {
  222664. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  222665. for (NSString* i in familyFonts)
  222666. {
  222667. const String fn (nsStringToJuce (i));
  222668. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  222669. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  222670. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  222671. || afterDash.containsIgnoreCase ("italic")
  222672. || fn.endsWithIgnoreCase ("oblique")
  222673. || fn.endsWithIgnoreCase ("italic");
  222674. if (probablyBold == font.isBold()
  222675. && probablyItalic == font.isItalic())
  222676. {
  222677. fontName = i;
  222678. needsItalicTransform = false;
  222679. break;
  222680. }
  222681. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  222682. {
  222683. fontName = i;
  222684. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  222685. }
  222686. }
  222687. if (needsItalicTransform)
  222688. renderingTransform.c = 0.15f;
  222689. }
  222690. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  222691. const int ascender = abs (CGFontGetAscent (fontRef));
  222692. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  222693. ascent = ascender / totalHeight;
  222694. unitsToHeightScaleFactor = 1.0f / totalHeight;
  222695. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  222696. #else
  222697. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  222698. if (font.isItalic())
  222699. {
  222700. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  222701. toHaveTrait: NSItalicFontMask];
  222702. if (newFont == nsFont)
  222703. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  222704. nsFont = newFont;
  222705. }
  222706. if (font.isBold())
  222707. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  222708. [nsFont retain];
  222709. ascent = std::abs ((float) [nsFont ascender]);
  222710. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  222711. ascent /= totalSize;
  222712. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  222713. if (needsItalicTransform)
  222714. {
  222715. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  222716. renderingTransform.c = 0.15f;
  222717. }
  222718. #if SUPPORT_ONLY_10_4_FONTS
  222719. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  222720. if (atsFont == 0)
  222721. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  222722. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  222723. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  222724. unitsToHeightScaleFactor = 1.0f / totalHeight;
  222725. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  222726. #else
  222727. #if SUPPORT_10_4_FONTS
  222728. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  222729. {
  222730. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  222731. if (atsFont == 0)
  222732. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  222733. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  222734. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  222735. unitsToHeightScaleFactor = 1.0f / totalHeight;
  222736. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  222737. }
  222738. else
  222739. #endif
  222740. {
  222741. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  222742. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  222743. unitsToHeightScaleFactor = 1.0f / totalHeight;
  222744. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  222745. }
  222746. #endif
  222747. #endif
  222748. }
  222749. ~MacTypeface()
  222750. {
  222751. #if ! JUCE_IPHONE
  222752. [nsFont release];
  222753. #endif
  222754. if (fontRef != 0)
  222755. CGFontRelease (fontRef);
  222756. }
  222757. float getAscent() const
  222758. {
  222759. return ascent;
  222760. }
  222761. float getDescent() const
  222762. {
  222763. return 1.0f - ascent;
  222764. }
  222765. float getStringWidth (const String& text)
  222766. {
  222767. if (fontRef == 0 || text.isEmpty())
  222768. return 0;
  222769. const int length = text.length();
  222770. HeapBlock <CGGlyph> glyphs;
  222771. createGlyphsForString (text, length, glyphs);
  222772. float x = 0;
  222773. #if SUPPORT_ONLY_10_4_FONTS
  222774. HeapBlock <NSSize> advances (length);
  222775. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  222776. for (int i = 0; i < length; ++i)
  222777. x += advances[i].width;
  222778. #else
  222779. #if SUPPORT_10_4_FONTS
  222780. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  222781. {
  222782. HeapBlock <NSSize> advances (length);
  222783. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  222784. for (int i = 0; i < length; ++i)
  222785. x += advances[i].width;
  222786. }
  222787. else
  222788. #endif
  222789. {
  222790. HeapBlock <int> advances (length);
  222791. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  222792. for (int i = 0; i < length; ++i)
  222793. x += advances[i];
  222794. }
  222795. #endif
  222796. return x * unitsToHeightScaleFactor;
  222797. }
  222798. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  222799. {
  222800. xOffsets.add (0);
  222801. if (fontRef == 0 || text.isEmpty())
  222802. return;
  222803. const int length = text.length();
  222804. HeapBlock <CGGlyph> glyphs;
  222805. createGlyphsForString (text, length, glyphs);
  222806. #if SUPPORT_ONLY_10_4_FONTS
  222807. HeapBlock <NSSize> advances (length);
  222808. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  222809. int x = 0;
  222810. for (int i = 0; i < length; ++i)
  222811. {
  222812. x += advances[i].width;
  222813. xOffsets.add (x * unitsToHeightScaleFactor);
  222814. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  222815. }
  222816. #else
  222817. #if SUPPORT_10_4_FONTS
  222818. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  222819. {
  222820. HeapBlock <NSSize> advances (length);
  222821. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  222822. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  222823. float x = 0;
  222824. for (int i = 0; i < length; ++i)
  222825. {
  222826. x += advances[i].width;
  222827. xOffsets.add (x * unitsToHeightScaleFactor);
  222828. resultGlyphs.add (nsGlyphs[i]);
  222829. }
  222830. }
  222831. else
  222832. #endif
  222833. {
  222834. HeapBlock <int> advances (length);
  222835. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  222836. {
  222837. int x = 0;
  222838. for (int i = 0; i < length; ++i)
  222839. {
  222840. x += advances [i];
  222841. xOffsets.add (x * unitsToHeightScaleFactor);
  222842. resultGlyphs.add (glyphs[i]);
  222843. }
  222844. }
  222845. }
  222846. #endif
  222847. }
  222848. bool getOutlineForGlyph (int glyphNumber, Path& path)
  222849. {
  222850. #if JUCE_IPHONE
  222851. return false;
  222852. #else
  222853. if (nsFont == 0)
  222854. return false;
  222855. // we might need to apply a transform to the path, so it mustn't have anything else in it
  222856. jassert (path.isEmpty());
  222857. const ScopedAutoReleasePool pool;
  222858. NSBezierPath* bez = [NSBezierPath bezierPath];
  222859. [bez moveToPoint: NSMakePoint (0, 0)];
  222860. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  222861. inFont: nsFont];
  222862. for (int i = 0; i < [bez elementCount]; ++i)
  222863. {
  222864. NSPoint p[3];
  222865. switch ([bez elementAtIndex: i associatedPoints: p])
  222866. {
  222867. case NSMoveToBezierPathElement:
  222868. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  222869. break;
  222870. case NSLineToBezierPathElement:
  222871. path.lineTo ((float) p[0].x, (float) -p[0].y);
  222872. break;
  222873. case NSCurveToBezierPathElement:
  222874. 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);
  222875. break;
  222876. case NSClosePathBezierPathElement:
  222877. path.closeSubPath();
  222878. break;
  222879. default:
  222880. jassertfalse
  222881. break;
  222882. }
  222883. }
  222884. path.applyTransform (pathTransform);
  222885. return true;
  222886. #endif
  222887. }
  222888. juce_UseDebuggingNewOperator
  222889. CGFontRef fontRef;
  222890. float fontHeightToCGSizeFactor;
  222891. CGAffineTransform renderingTransform;
  222892. private:
  222893. float ascent, unitsToHeightScaleFactor;
  222894. #if JUCE_IPHONE
  222895. #else
  222896. NSFont* nsFont;
  222897. AffineTransform pathTransform;
  222898. #endif
  222899. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  222900. {
  222901. #if SUPPORT_10_4_FONTS
  222902. #if ! SUPPORT_ONLY_10_4_FONTS
  222903. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  222904. #endif
  222905. {
  222906. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  222907. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  222908. for (int i = 0; i < length; ++i)
  222909. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  222910. return;
  222911. }
  222912. #endif
  222913. #if ! SUPPORT_ONLY_10_4_FONTS
  222914. if (charToGlyphMapper == 0)
  222915. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  222916. glyphs.malloc (length);
  222917. for (int i = 0; i < length; ++i)
  222918. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  222919. #endif
  222920. }
  222921. #if ! SUPPORT_ONLY_10_4_FONTS
  222922. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  222923. class CharToGlyphMapper
  222924. {
  222925. public:
  222926. CharToGlyphMapper (CGFontRef fontRef)
  222927. : segCount (0), endCode (0), startCode (0), idDelta (0),
  222928. idRangeOffset (0), glyphIndexes (0)
  222929. {
  222930. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  222931. if (cmapTable != 0)
  222932. {
  222933. const int numSubtables = getValue16 (cmapTable, 2);
  222934. for (int i = 0; i < numSubtables; ++i)
  222935. {
  222936. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  222937. {
  222938. const int offset = getValue32 (cmapTable, i * 8 + 8);
  222939. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  222940. {
  222941. const int length = getValue16 (cmapTable, offset + 2);
  222942. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  222943. segCount = segCountX2 / 2;
  222944. const int endCodeOffset = offset + 14;
  222945. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  222946. const int idDeltaOffset = startCodeOffset + segCountX2;
  222947. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  222948. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  222949. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  222950. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  222951. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  222952. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  222953. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  222954. }
  222955. break;
  222956. }
  222957. }
  222958. CFRelease (cmapTable);
  222959. }
  222960. }
  222961. ~CharToGlyphMapper()
  222962. {
  222963. if (endCode != 0)
  222964. {
  222965. CFRelease (endCode);
  222966. CFRelease (startCode);
  222967. CFRelease (idDelta);
  222968. CFRelease (idRangeOffset);
  222969. CFRelease (glyphIndexes);
  222970. }
  222971. }
  222972. int getGlyphForCharacter (const juce_wchar c) const
  222973. {
  222974. for (int i = 0; i < segCount; ++i)
  222975. {
  222976. if (getValue16 (endCode, i * 2) >= c)
  222977. {
  222978. const int start = getValue16 (startCode, i * 2);
  222979. if (start > c)
  222980. break;
  222981. const int delta = getValue16 (idDelta, i * 2);
  222982. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  222983. if (rangeOffset == 0)
  222984. return delta + c;
  222985. else
  222986. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  222987. }
  222988. }
  222989. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  222990. return jmax (-1, c - 29);
  222991. }
  222992. private:
  222993. int segCount;
  222994. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  222995. static uint16 getValue16 (CFDataRef data, const int index)
  222996. {
  222997. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  222998. }
  222999. static uint32 getValue32 (CFDataRef data, const int index)
  223000. {
  223001. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  223002. }
  223003. };
  223004. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  223005. #endif
  223006. MacTypeface (const MacTypeface&);
  223007. MacTypeface& operator= (const MacTypeface&);
  223008. };
  223009. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  223010. {
  223011. return new MacTypeface (font);
  223012. }
  223013. const StringArray Font::findAllTypefaceNames()
  223014. {
  223015. StringArray names;
  223016. const ScopedAutoReleasePool pool;
  223017. #if JUCE_IPHONE
  223018. NSArray* fonts = [UIFont familyNames];
  223019. #else
  223020. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  223021. #endif
  223022. for (unsigned int i = 0; i < [fonts count]; ++i)
  223023. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  223024. names.sort (true);
  223025. return names;
  223026. }
  223027. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  223028. {
  223029. #if JUCE_IPHONE
  223030. defaultSans = "Helvetica";
  223031. defaultSerif = "Times New Roman";
  223032. defaultFixed = "Courier New";
  223033. #else
  223034. defaultSans = "Lucida Grande";
  223035. defaultSerif = "Times New Roman";
  223036. defaultFixed = "Monaco";
  223037. #endif
  223038. }
  223039. #endif
  223040. /*** End of inlined file: juce_mac_Fonts.mm ***/
  223041. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  223042. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223043. // compiled on its own).
  223044. #if JUCE_INCLUDED_FILE
  223045. class CoreGraphicsImage : public Image
  223046. {
  223047. public:
  223048. CoreGraphicsImage (const PixelFormat format_,
  223049. const int imageWidth_,
  223050. const int imageHeight_,
  223051. const bool clearImage)
  223052. : Image (format_, imageWidth_, imageHeight_, clearImage)
  223053. {
  223054. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  223055. : CGColorSpaceCreateDeviceRGB();
  223056. context = CGBitmapContextCreate (imageData, imageWidth, imageHeight, 8, lineStride,
  223057. colourSpace, getCGImageFlags (*this));
  223058. CGColorSpaceRelease (colourSpace);
  223059. }
  223060. ~CoreGraphicsImage()
  223061. {
  223062. CGContextRelease (context);
  223063. }
  223064. LowLevelGraphicsContext* createLowLevelContext();
  223065. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  223066. {
  223067. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (&juceImage);
  223068. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  223069. {
  223070. return CGBitmapContextCreateImage (nativeImage->context);
  223071. }
  223072. else
  223073. {
  223074. const Image::BitmapData srcData (juceImage, 0, 0, juceImage.getWidth(), juceImage.getHeight());
  223075. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  223076. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  223077. 8, srcData.pixelStride * 8, srcData.lineStride,
  223078. colourSpace, getCGImageFlags (juceImage), provider,
  223079. 0, true, kCGRenderingIntentDefault);
  223080. CGDataProviderRelease (provider);
  223081. return imageRef;
  223082. }
  223083. }
  223084. #if JUCE_MAC
  223085. static NSImage* createNSImage (const Image& image)
  223086. {
  223087. const ScopedAutoReleasePool pool;
  223088. NSImage* im = [[NSImage alloc] init];
  223089. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  223090. [im lockFocus];
  223091. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  223092. CGImageRef imageRef = createImage (image, false, colourSpace);
  223093. CGColorSpaceRelease (colourSpace);
  223094. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  223095. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  223096. CGImageRelease (imageRef);
  223097. [im unlockFocus];
  223098. return im;
  223099. }
  223100. #endif
  223101. CGContextRef context;
  223102. private:
  223103. static CGBitmapInfo getCGImageFlags (const Image& image)
  223104. {
  223105. #if JUCE_BIG_ENDIAN
  223106. return image.getFormat() == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  223107. #else
  223108. return image.getFormat() == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  223109. #endif
  223110. }
  223111. };
  223112. Image* Image::createNativeImage (const PixelFormat format, const int imageWidth, const int imageHeight, const bool clearImage)
  223113. {
  223114. #if USE_COREGRAPHICS_RENDERING
  223115. return new CoreGraphicsImage (format == RGB ? ARGB : format, imageWidth, imageHeight, clearImage);
  223116. #else
  223117. return new Image (format, imageWidth, imageHeight, clearImage);
  223118. #endif
  223119. }
  223120. class CoreGraphicsContext : public LowLevelGraphicsContext
  223121. {
  223122. public:
  223123. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  223124. : context (context_),
  223125. flipHeight (flipHeight_),
  223126. state (new SavedState()),
  223127. numGradientLookupEntries (0)
  223128. {
  223129. CGContextRetain (context);
  223130. CGContextSaveGState(context);
  223131. CGContextSetShouldSmoothFonts (context, true);
  223132. CGContextSetShouldAntialias (context, true);
  223133. CGContextSetBlendMode (context, kCGBlendModeNormal);
  223134. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  223135. greyColourSpace = CGColorSpaceCreateDeviceGray();
  223136. gradientCallbacks.version = 0;
  223137. gradientCallbacks.evaluate = gradientCallback;
  223138. gradientCallbacks.releaseInfo = 0;
  223139. setFont (Font());
  223140. }
  223141. ~CoreGraphicsContext()
  223142. {
  223143. CGContextRestoreGState (context);
  223144. CGContextRelease (context);
  223145. CGColorSpaceRelease (rgbColourSpace);
  223146. CGColorSpaceRelease (greyColourSpace);
  223147. }
  223148. bool isVectorDevice() const { return false; }
  223149. void setOrigin (int x, int y)
  223150. {
  223151. CGContextTranslateCTM (context, x, -y);
  223152. }
  223153. bool clipToRectangle (const Rectangle<int>& r)
  223154. {
  223155. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  223156. return ! isClipEmpty();
  223157. }
  223158. bool clipToRectangleList (const RectangleList& clipRegion)
  223159. {
  223160. if (clipRegion.isEmpty())
  223161. {
  223162. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  223163. return false;
  223164. }
  223165. else
  223166. {
  223167. const int numRects = clipRegion.getNumRectangles();
  223168. HeapBlock <CGRect> rects (numRects);
  223169. for (int i = 0; i < numRects; ++i)
  223170. {
  223171. const Rectangle<int>& r = clipRegion.getRectangle(i);
  223172. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  223173. }
  223174. CGContextClipToRects (context, rects, numRects);
  223175. return ! isClipEmpty();
  223176. }
  223177. }
  223178. void excludeClipRectangle (const Rectangle<int>& r)
  223179. {
  223180. RectangleList remaining (getClipBounds());
  223181. remaining.subtract (r);
  223182. clipToRectangleList (remaining);
  223183. }
  223184. void clipToPath (const Path& path, const AffineTransform& transform)
  223185. {
  223186. createPath (path, transform);
  223187. CGContextClip (context);
  223188. }
  223189. void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform)
  223190. {
  223191. if (! transform.isSingularity())
  223192. {
  223193. ScopedPointer<Image> imageToDelete;
  223194. const Image* singleChannelImage = &sourceImage;
  223195. if (sourceImage.getFormat() != Image::SingleChannel)
  223196. {
  223197. imageToDelete = sourceImage.createCopyOfAlphaChannel();
  223198. singleChannelImage = imageToDelete;
  223199. }
  223200. CGImageRef image = CoreGraphicsImage::createImage (*singleChannelImage, true, greyColourSpace);
  223201. flip();
  223202. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  223203. applyTransform (t);
  223204. CGRect r = CGRectMake (srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  223205. CGContextClipToMask (context, r, image);
  223206. applyTransform (t.inverted());
  223207. flip();
  223208. CGImageRelease (image);
  223209. }
  223210. }
  223211. bool clipRegionIntersects (const Rectangle<int>& r)
  223212. {
  223213. return getClipBounds().intersects (r);
  223214. }
  223215. const Rectangle<int> getClipBounds() const
  223216. {
  223217. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  223218. return Rectangle<int> (roundToInt (bounds.origin.x),
  223219. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  223220. roundToInt (bounds.size.width),
  223221. roundToInt (bounds.size.height));
  223222. }
  223223. bool isClipEmpty() const
  223224. {
  223225. return CGRectIsEmpty (CGContextGetClipBoundingBox (context));
  223226. }
  223227. void saveState()
  223228. {
  223229. CGContextSaveGState (context);
  223230. stateStack.add (new SavedState (*state));
  223231. }
  223232. void restoreState()
  223233. {
  223234. CGContextRestoreGState (context);
  223235. SavedState* const top = stateStack.getLast();
  223236. if (top != 0)
  223237. {
  223238. state = top;
  223239. stateStack.removeLast (1, false);
  223240. }
  223241. else
  223242. {
  223243. jassertfalse // trying to pop with an empty stack!
  223244. }
  223245. }
  223246. void setFill (const FillType& fillType)
  223247. {
  223248. state->fillType = fillType;
  223249. if (fillType.isColour())
  223250. {
  223251. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  223252. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  223253. CGContextSetAlpha (context, 1.0f);
  223254. }
  223255. }
  223256. void setOpacity (float newOpacity)
  223257. {
  223258. state->fillType.setOpacity (newOpacity);
  223259. setFill (state->fillType);
  223260. }
  223261. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  223262. {
  223263. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  223264. ? kCGInterpolationLow
  223265. : kCGInterpolationHigh);
  223266. }
  223267. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  223268. {
  223269. CGRect cgRect = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  223270. if (replaceExistingContents)
  223271. {
  223272. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  223273. CGContextClearRect (context, cgRect);
  223274. #else
  223275. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  223276. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  223277. CGContextClearRect (context, cgRect);
  223278. else
  223279. #endif
  223280. CGContextSetBlendMode (context, kCGBlendModeCopy);
  223281. #endif
  223282. fillRect (r, false);
  223283. CGContextSetBlendMode (context, kCGBlendModeNormal);
  223284. }
  223285. else
  223286. {
  223287. if (state->fillType.isColour())
  223288. {
  223289. CGContextFillRect (context, cgRect);
  223290. }
  223291. else if (state->fillType.isGradient())
  223292. {
  223293. CGContextSaveGState (context);
  223294. CGContextClipToRect (context, cgRect);
  223295. drawGradient();
  223296. CGContextRestoreGState (context);
  223297. }
  223298. else
  223299. {
  223300. CGContextSaveGState (context);
  223301. CGContextClipToRect (context, cgRect);
  223302. drawImage (*(state->fillType.image), state->fillType.image->getBounds(), state->fillType.transform, true);
  223303. CGContextRestoreGState (context);
  223304. }
  223305. }
  223306. }
  223307. void fillPath (const Path& path, const AffineTransform& transform)
  223308. {
  223309. CGContextSaveGState (context);
  223310. if (state->fillType.isColour())
  223311. {
  223312. flip();
  223313. applyTransform (transform);
  223314. createPath (path);
  223315. if (path.isUsingNonZeroWinding())
  223316. CGContextFillPath (context);
  223317. else
  223318. CGContextEOFillPath (context);
  223319. }
  223320. else
  223321. {
  223322. createPath (path, transform);
  223323. if (path.isUsingNonZeroWinding())
  223324. CGContextClip (context);
  223325. else
  223326. CGContextEOClip (context);
  223327. if (state->fillType.isGradient())
  223328. drawGradient();
  223329. else
  223330. drawImage (*(state->fillType.image), state->fillType.image->getBounds(), state->fillType.transform, true);
  223331. }
  223332. CGContextRestoreGState (context);
  223333. }
  223334. void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  223335. const AffineTransform& transform, const bool fillEntireClipAsTiles)
  223336. {
  223337. jassert (sourceImage.getBounds().contains (srcClip));
  223338. CGImageRef fullImage = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  223339. CGImageRef image = fullImage;
  223340. if (srcClip != sourceImage.getBounds())
  223341. {
  223342. image = CGImageCreateWithImageInRect (fullImage, CGRectMake (srcClip.getX(), srcClip.getY(),
  223343. srcClip.getWidth(), srcClip.getHeight()));
  223344. CGImageRelease (fullImage);
  223345. }
  223346. CGContextSaveGState (context);
  223347. CGContextSetAlpha (context, state->fillType.getOpacity());
  223348. flip();
  223349. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, srcClip.getHeight()).followedBy (transform));
  223350. CGRect imageRect = CGRectMake (0, 0, srcClip.getWidth(), srcClip.getHeight());
  223351. if (fillEntireClipAsTiles)
  223352. {
  223353. #if JUCE_IPHONE
  223354. CGContextDrawTiledImage (context, imageRect, image);
  223355. #else
  223356. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  223357. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  223358. // if it's doing a transformation - it's quicker to just draw lots of images manually
  223359. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  223360. CGContextDrawTiledImage (context, imageRect, image);
  223361. else
  223362. #endif
  223363. {
  223364. // Fallback to manually doing a tiled fill on 10.4
  223365. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  223366. const int iw = srcClip.getWidth();
  223367. const int ih = srcClip.getHeight();
  223368. int x = 0, y = 0;
  223369. while (x > clip.origin.x) x -= iw;
  223370. while (y > clip.origin.y) y -= ih;
  223371. const int right = (int) (clip.origin.x + clip.size.width);
  223372. const int bottom = (int) (clip.origin.y + clip.size.height);
  223373. while (y < bottom)
  223374. {
  223375. for (int x2 = x; x2 < right; x2 += iw)
  223376. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  223377. y += ih;
  223378. }
  223379. }
  223380. #endif
  223381. }
  223382. else
  223383. {
  223384. CGContextDrawImage (context, imageRect, image);
  223385. }
  223386. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  223387. CGContextRestoreGState (context);
  223388. }
  223389. void drawLine (const Line<float>& line)
  223390. {
  223391. CGContextSetLineCap (context, kCGLineCapSquare);
  223392. CGContextSetLineWidth (context, 1.0f);
  223393. CGContextSetRGBStrokeColor (context,
  223394. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  223395. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  223396. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  223397. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  223398. CGContextStrokeLineSegments (context, cgLine, 1);
  223399. }
  223400. void drawVerticalLine (const int x, float top, float bottom)
  223401. {
  223402. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  223403. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  223404. #else
  223405. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  223406. // the x co-ord slightly to trick it..
  223407. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  223408. #endif
  223409. }
  223410. void drawHorizontalLine (const int y, float left, float right)
  223411. {
  223412. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  223413. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  223414. #else
  223415. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  223416. // the x co-ord slightly to trick it..
  223417. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  223418. #endif
  223419. }
  223420. void setFont (const Font& newFont)
  223421. {
  223422. if (state->font != newFont)
  223423. {
  223424. state->fontRef = 0;
  223425. state->font = newFont;
  223426. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  223427. if (mf != 0)
  223428. {
  223429. state->fontRef = mf->fontRef;
  223430. CGContextSetFont (context, state->fontRef);
  223431. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  223432. state->fontTransform = mf->renderingTransform;
  223433. state->fontTransform.a *= state->font.getHorizontalScale();
  223434. CGContextSetTextMatrix (context, state->fontTransform);
  223435. }
  223436. }
  223437. }
  223438. const Font getFont()
  223439. {
  223440. return state->font;
  223441. }
  223442. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  223443. {
  223444. if (state->fontRef != 0 && state->fillType.isColour())
  223445. {
  223446. if (transform.isOnlyTranslation())
  223447. {
  223448. CGGlyph g = glyphNumber;
  223449. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  223450. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  223451. }
  223452. else
  223453. {
  223454. CGContextSaveGState (context);
  223455. flip();
  223456. applyTransform (transform);
  223457. CGAffineTransform t = state->fontTransform;
  223458. t.d = -t.d;
  223459. CGContextSetTextMatrix (context, t);
  223460. CGGlyph g = glyphNumber;
  223461. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  223462. CGContextSetTextMatrix (context, state->fontTransform);
  223463. CGContextRestoreGState (context);
  223464. }
  223465. }
  223466. else
  223467. {
  223468. Path p;
  223469. Font& f = state->font;
  223470. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  223471. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  223472. .followedBy (transform));
  223473. }
  223474. }
  223475. private:
  223476. CGContextRef context;
  223477. const CGFloat flipHeight;
  223478. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  223479. CGFunctionCallbacks gradientCallbacks;
  223480. struct SavedState
  223481. {
  223482. SavedState()
  223483. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  223484. {
  223485. }
  223486. SavedState (const SavedState& other)
  223487. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  223488. fontTransform (other.fontTransform)
  223489. {
  223490. }
  223491. ~SavedState()
  223492. {
  223493. }
  223494. FillType fillType;
  223495. Font font;
  223496. CGFontRef fontRef;
  223497. CGAffineTransform fontTransform;
  223498. };
  223499. ScopedPointer <SavedState> state;
  223500. OwnedArray <SavedState> stateStack;
  223501. HeapBlock <PixelARGB> gradientLookupTable;
  223502. int numGradientLookupEntries;
  223503. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  223504. {
  223505. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  223506. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  223507. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  223508. colour.unpremultiply();
  223509. outData[0] = colour.getRed() / 255.0f;
  223510. outData[1] = colour.getGreen() / 255.0f;
  223511. outData[2] = colour.getBlue() / 255.0f;
  223512. outData[3] = colour.getAlpha() / 255.0f;
  223513. }
  223514. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  223515. {
  223516. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  223517. --numGradientLookupEntries;
  223518. CGShadingRef result = 0;
  223519. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  223520. CGPoint p1 (CGPointMake (gradient.x1, gradient.y1));
  223521. if (gradient.isRadial)
  223522. {
  223523. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  223524. p1, hypotf (gradient.x1 - gradient.x2, gradient.y1 - gradient.y2),
  223525. function, true, true);
  223526. }
  223527. else
  223528. {
  223529. result = CGShadingCreateAxial (rgbColourSpace, p1,
  223530. CGPointMake (gradient.x2, gradient.y2),
  223531. function, true, true);
  223532. }
  223533. CGFunctionRelease (function);
  223534. return result;
  223535. }
  223536. void drawGradient()
  223537. {
  223538. flip();
  223539. applyTransform (state->fillType.transform);
  223540. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  223541. // you draw a gradient with high quality interp enabled).
  223542. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  223543. CGContextSetAlpha (context, state->fillType.getOpacity());
  223544. CGContextDrawShading (context, shading);
  223545. CGShadingRelease (shading);
  223546. }
  223547. void createPath (const Path& path) const
  223548. {
  223549. CGContextBeginPath (context);
  223550. Path::Iterator i (path);
  223551. while (i.next())
  223552. {
  223553. switch (i.elementType)
  223554. {
  223555. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  223556. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  223557. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  223558. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  223559. case Path::Iterator::closePath: CGContextClosePath (context); break;
  223560. default: jassertfalse; break;
  223561. }
  223562. }
  223563. }
  223564. void createPath (const Path& path, const AffineTransform& transform) const
  223565. {
  223566. CGContextBeginPath (context);
  223567. Path::Iterator i (path);
  223568. while (i.next())
  223569. {
  223570. switch (i.elementType)
  223571. {
  223572. case Path::Iterator::startNewSubPath:
  223573. transform.transformPoint (i.x1, i.y1);
  223574. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  223575. break;
  223576. case Path::Iterator::lineTo:
  223577. transform.transformPoint (i.x1, i.y1);
  223578. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  223579. break;
  223580. case Path::Iterator::quadraticTo:
  223581. transform.transformPoint (i.x1, i.y1);
  223582. transform.transformPoint (i.x2, i.y2);
  223583. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  223584. break;
  223585. case Path::Iterator::cubicTo:
  223586. transform.transformPoint (i.x1, i.y1);
  223587. transform.transformPoint (i.x2, i.y2);
  223588. transform.transformPoint (i.x3, i.y3);
  223589. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  223590. break;
  223591. case Path::Iterator::closePath:
  223592. CGContextClosePath (context); break;
  223593. default:
  223594. jassertfalse
  223595. break;
  223596. }
  223597. }
  223598. }
  223599. void flip() const
  223600. {
  223601. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  223602. }
  223603. void applyTransform (const AffineTransform& transform) const
  223604. {
  223605. CGAffineTransform t;
  223606. t.a = transform.mat00;
  223607. t.b = transform.mat10;
  223608. t.c = transform.mat01;
  223609. t.d = transform.mat11;
  223610. t.tx = transform.mat02;
  223611. t.ty = transform.mat12;
  223612. CGContextConcatCTM (context, t);
  223613. }
  223614. CoreGraphicsContext (const CoreGraphicsContext&);
  223615. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  223616. };
  223617. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  223618. {
  223619. return new CoreGraphicsContext (context, imageHeight);
  223620. }
  223621. #endif
  223622. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  223623. /*** Start of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  223624. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223625. // compiled on its own).
  223626. #if JUCE_INCLUDED_FILE
  223627. class UIViewComponentPeer;
  223628. END_JUCE_NAMESPACE
  223629. #define JuceUIView MakeObjCClassName(JuceUIView)
  223630. @interface JuceUIView : UIView <UITextFieldDelegate>
  223631. {
  223632. @public
  223633. UIViewComponentPeer* owner;
  223634. UITextField *hiddenTextField;
  223635. }
  223636. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  223637. - (void) dealloc;
  223638. - (void) drawRect: (CGRect) r;
  223639. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  223640. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  223641. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  223642. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  223643. - (BOOL) becomeFirstResponder;
  223644. - (BOOL) resignFirstResponder;
  223645. - (BOOL) canBecomeFirstResponder;
  223646. - (void) asyncRepaint: (id) rect;
  223647. - (BOOL) textField: (UITextField*) textField shouldChangeCharactersInRange: (NSRange) range replacementString: (NSString*) string;
  223648. - (BOOL) textFieldShouldClear: (UITextField*) textField;
  223649. - (BOOL) textFieldShouldReturn: (UITextField*) textField;
  223650. @end
  223651. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  223652. @interface JuceUIWindow : UIWindow
  223653. {
  223654. @private
  223655. UIViewComponentPeer* owner;
  223656. bool isZooming;
  223657. }
  223658. - (void) setOwner: (UIViewComponentPeer*) owner;
  223659. - (void) becomeKeyWindow;
  223660. @end
  223661. BEGIN_JUCE_NAMESPACE
  223662. class UIViewComponentPeer : public ComponentPeer,
  223663. public FocusChangeListener
  223664. {
  223665. public:
  223666. UIViewComponentPeer (Component* const component,
  223667. const int windowStyleFlags,
  223668. UIView* viewToAttachTo);
  223669. ~UIViewComponentPeer();
  223670. void* getNativeHandle() const;
  223671. void setVisible (bool shouldBeVisible);
  223672. void setTitle (const String& title);
  223673. void setPosition (int x, int y);
  223674. void setSize (int w, int h);
  223675. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  223676. const Rectangle<int> getBounds() const;
  223677. const Rectangle<int> getBounds (const bool global) const;
  223678. const Point<int> getScreenPosition() const;
  223679. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  223680. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  223681. void setMinimised (bool shouldBeMinimised);
  223682. bool isMinimised() const;
  223683. void setFullScreen (bool shouldBeFullScreen);
  223684. bool isFullScreen() const;
  223685. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  223686. const BorderSize getFrameSize() const;
  223687. bool setAlwaysOnTop (bool alwaysOnTop);
  223688. void toFront (bool makeActiveWindow);
  223689. void toBehind (ComponentPeer* other);
  223690. void setIcon (const Image& newIcon);
  223691. virtual void drawRect (CGRect r);
  223692. virtual bool canBecomeKeyWindow();
  223693. virtual bool windowShouldClose();
  223694. virtual void redirectMovedOrResized();
  223695. virtual CGRect constrainRect (CGRect r);
  223696. virtual void viewFocusGain();
  223697. virtual void viewFocusLoss();
  223698. bool isFocused() const;
  223699. void grabFocus();
  223700. void textInputRequired (const Point<int>& position);
  223701. virtual BOOL textFieldReplaceCharacters (const Range<int>& range, const String& text);
  223702. virtual BOOL textFieldShouldClear();
  223703. virtual BOOL textFieldShouldReturn();
  223704. void updateHiddenTextContent (TextInputTarget* target);
  223705. void globalFocusChanged (Component*);
  223706. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  223707. void repaint (int x, int y, int w, int h);
  223708. void performAnyPendingRepaintsNow();
  223709. juce_UseDebuggingNewOperator
  223710. UIWindow* window;
  223711. JuceUIView* view;
  223712. bool isSharedWindow, fullScreen, insideDrawRect;
  223713. static ModifierKeys currentModifiers;
  223714. static int64 getMouseTime (UIEvent* e)
  223715. {
  223716. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  223717. + (int64) ([e timestamp] * 1000.0);
  223718. }
  223719. Array <UITouch*> currentTouches;
  223720. };
  223721. END_JUCE_NAMESPACE
  223722. @implementation JuceUIView
  223723. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  223724. withFrame: (CGRect) frame
  223725. {
  223726. [super initWithFrame: frame];
  223727. owner = owner_;
  223728. hiddenTextField = [[UITextField alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  223729. [self addSubview: hiddenTextField];
  223730. hiddenTextField.delegate = self;
  223731. return self;
  223732. }
  223733. - (void) dealloc
  223734. {
  223735. [hiddenTextField removeFromSuperview];
  223736. [hiddenTextField release];
  223737. [super dealloc];
  223738. }
  223739. - (void) drawRect: (CGRect) r
  223740. {
  223741. if (owner != 0)
  223742. owner->drawRect (r);
  223743. }
  223744. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  223745. {
  223746. return false;
  223747. }
  223748. ModifierKeys UIViewComponentPeer::currentModifiers;
  223749. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  223750. {
  223751. return UIViewComponentPeer::currentModifiers;
  223752. }
  223753. void ModifierKeys::updateCurrentModifiers() throw()
  223754. {
  223755. currentModifiers = UIViewComponentPeer::currentModifiers;
  223756. }
  223757. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  223758. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  223759. {
  223760. if (owner != 0)
  223761. owner->handleTouches (event, true, false, false);
  223762. }
  223763. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  223764. {
  223765. if (owner != 0)
  223766. owner->handleTouches (event, false, false, false);
  223767. }
  223768. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  223769. {
  223770. if (owner != 0)
  223771. owner->handleTouches (event, false, true, false);
  223772. }
  223773. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  223774. {
  223775. if (owner != 0)
  223776. owner->handleTouches (event, false, true, true);
  223777. [self touchesEnded: touches withEvent: event];
  223778. }
  223779. - (BOOL) becomeFirstResponder
  223780. {
  223781. if (owner != 0)
  223782. owner->viewFocusGain();
  223783. return true;
  223784. }
  223785. - (BOOL) resignFirstResponder
  223786. {
  223787. if (owner != 0)
  223788. owner->viewFocusLoss();
  223789. return true;
  223790. }
  223791. - (BOOL) canBecomeFirstResponder
  223792. {
  223793. return owner != 0 && owner->canBecomeKeyWindow();
  223794. }
  223795. - (void) asyncRepaint: (id) rect
  223796. {
  223797. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  223798. [self setNeedsDisplayInRect: *r];
  223799. }
  223800. - (BOOL) textField: (UITextField*) textField shouldChangeCharactersInRange: (NSRange) range replacementString: (NSString*) text
  223801. {
  223802. return owner->textFieldReplaceCharacters (Range<int> (range.location, range.location + range.length),
  223803. nsStringToJuce (text));
  223804. }
  223805. - (BOOL) textFieldShouldClear: (UITextField*) textField
  223806. {
  223807. return owner->textFieldShouldClear();
  223808. }
  223809. - (BOOL) textFieldShouldReturn: (UITextField*) textField
  223810. {
  223811. return owner->textFieldShouldReturn();
  223812. }
  223813. @end
  223814. @implementation JuceUIWindow
  223815. - (void) setOwner: (UIViewComponentPeer*) owner_
  223816. {
  223817. owner = owner_;
  223818. isZooming = false;
  223819. }
  223820. - (void) becomeKeyWindow
  223821. {
  223822. [super becomeKeyWindow];
  223823. if (owner != 0)
  223824. owner->grabFocus();
  223825. }
  223826. @end
  223827. BEGIN_JUCE_NAMESPACE
  223828. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  223829. const int windowStyleFlags,
  223830. UIView* viewToAttachTo)
  223831. : ComponentPeer (component, windowStyleFlags),
  223832. window (0),
  223833. view (0),
  223834. isSharedWindow (viewToAttachTo != 0),
  223835. fullScreen (false),
  223836. insideDrawRect (false)
  223837. {
  223838. CGRect r = CGRectMake (0, 0, (float) component->getWidth(), (float) component->getHeight());
  223839. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  223840. if (isSharedWindow)
  223841. {
  223842. window = [viewToAttachTo window];
  223843. [viewToAttachTo addSubview: view];
  223844. setVisible (component->isVisible());
  223845. }
  223846. else
  223847. {
  223848. r.origin.x = (float) component->getX();
  223849. r.origin.y = (float) component->getY();
  223850. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  223851. window = [[JuceUIWindow alloc] init];
  223852. window.frame = r;
  223853. window.opaque = component->isOpaque();
  223854. view.opaque = component->isOpaque();
  223855. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  223856. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  223857. [((JuceUIWindow*) window) setOwner: this];
  223858. if (component->isAlwaysOnTop())
  223859. window.windowLevel = UIWindowLevelAlert;
  223860. [window addSubview: view];
  223861. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  223862. view.hidden = ! component->isVisible();
  223863. window.hidden = ! component->isVisible();
  223864. view.multipleTouchEnabled = YES;
  223865. }
  223866. setTitle (component->getName());
  223867. Desktop::getInstance().addFocusChangeListener (this);
  223868. }
  223869. UIViewComponentPeer::~UIViewComponentPeer()
  223870. {
  223871. Desktop::getInstance().removeFocusChangeListener (this);
  223872. view->owner = 0;
  223873. [view removeFromSuperview];
  223874. [view release];
  223875. if (! isSharedWindow)
  223876. {
  223877. [((JuceUIWindow*) window) setOwner: 0];
  223878. [window release];
  223879. }
  223880. }
  223881. void* UIViewComponentPeer::getNativeHandle() const
  223882. {
  223883. return view;
  223884. }
  223885. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  223886. {
  223887. view.hidden = ! shouldBeVisible;
  223888. if (! isSharedWindow)
  223889. window.hidden = ! shouldBeVisible;
  223890. }
  223891. void UIViewComponentPeer::setTitle (const String& title)
  223892. {
  223893. // xxx is this possible?
  223894. }
  223895. void UIViewComponentPeer::setPosition (int x, int y)
  223896. {
  223897. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  223898. }
  223899. void UIViewComponentPeer::setSize (int w, int h)
  223900. {
  223901. setBounds (component->getX(), component->getY(), w, h, false);
  223902. }
  223903. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  223904. {
  223905. fullScreen = isNowFullScreen;
  223906. w = jmax (0, w);
  223907. h = jmax (0, h);
  223908. CGRect r;
  223909. r.origin.x = (float) x;
  223910. r.origin.y = (float) y;
  223911. r.size.width = (float) w;
  223912. r.size.height = (float) h;
  223913. if (isSharedWindow)
  223914. {
  223915. //r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  223916. if ([view frame].size.width != r.size.width
  223917. || [view frame].size.height != r.size.height)
  223918. [view setNeedsDisplay];
  223919. view.frame = r;
  223920. }
  223921. else
  223922. {
  223923. window.frame = r;
  223924. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  223925. }
  223926. }
  223927. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  223928. {
  223929. CGRect r = [view frame];
  223930. if (global && [view window] != 0)
  223931. {
  223932. r = [view convertRect: r toView: nil];
  223933. CGRect wr = [[view window] frame];
  223934. r.origin.x += wr.origin.x;
  223935. r.origin.y += wr.origin.y;
  223936. }
  223937. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y,
  223938. (int) r.size.width, (int) r.size.height);
  223939. }
  223940. const Rectangle<int> UIViewComponentPeer::getBounds() const
  223941. {
  223942. return getBounds (! isSharedWindow);
  223943. }
  223944. const Point<int> UIViewComponentPeer::getScreenPosition() const
  223945. {
  223946. return getBounds (true).getPosition();
  223947. }
  223948. const Point<int> UIViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  223949. {
  223950. return relativePosition + getScreenPosition();
  223951. }
  223952. const Point<int> UIViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  223953. {
  223954. return screenPosition - getScreenPosition();
  223955. }
  223956. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  223957. {
  223958. if (constrainer != 0)
  223959. {
  223960. CGRect current = [window frame];
  223961. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  223962. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  223963. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  223964. (int) r.size.width, (int) r.size.height);
  223965. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  223966. (int) current.size.width, (int) current.size.height);
  223967. constrainer->checkBounds (pos, original,
  223968. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  223969. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  223970. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  223971. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  223972. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  223973. r.origin.x = pos.getX();
  223974. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  223975. r.size.width = pos.getWidth();
  223976. r.size.height = pos.getHeight();
  223977. }
  223978. return r;
  223979. }
  223980. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  223981. {
  223982. // xxx
  223983. }
  223984. bool UIViewComponentPeer::isMinimised() const
  223985. {
  223986. return false;
  223987. }
  223988. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  223989. {
  223990. if (! isSharedWindow)
  223991. {
  223992. Rectangle<int> r (lastNonFullscreenBounds);
  223993. setMinimised (false);
  223994. if (fullScreen != shouldBeFullScreen)
  223995. {
  223996. if (shouldBeFullScreen)
  223997. r = Desktop::getInstance().getMainMonitorArea();
  223998. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  223999. if (r != getComponent()->getBounds() && ! r.isEmpty())
  224000. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  224001. }
  224002. }
  224003. }
  224004. bool UIViewComponentPeer::isFullScreen() const
  224005. {
  224006. return fullScreen;
  224007. }
  224008. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  224009. {
  224010. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  224011. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  224012. return false;
  224013. CGPoint p;
  224014. p.x = (float) position.getX();
  224015. p.y = (float) position.getY();
  224016. UIView* v = [view hitTest: p withEvent: nil];
  224017. if (trueIfInAChildWindow)
  224018. return v != nil;
  224019. return v == view;
  224020. }
  224021. const BorderSize UIViewComponentPeer::getFrameSize() const
  224022. {
  224023. BorderSize b;
  224024. if (! isSharedWindow)
  224025. {
  224026. CGRect v = [view convertRect: [view frame] toView: nil];
  224027. CGRect w = [window frame];
  224028. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  224029. b.setBottom ((int) v.origin.y);
  224030. b.setLeft ((int) v.origin.x);
  224031. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  224032. }
  224033. return b;
  224034. }
  224035. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  224036. {
  224037. if (! isSharedWindow)
  224038. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  224039. return true;
  224040. }
  224041. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  224042. {
  224043. if (isSharedWindow)
  224044. [[view superview] bringSubviewToFront: view];
  224045. if (window != 0 && component->isVisible())
  224046. [window makeKeyAndVisible];
  224047. }
  224048. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  224049. {
  224050. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  224051. jassert (otherPeer != 0); // wrong type of window?
  224052. if (otherPeer != 0)
  224053. {
  224054. if (isSharedWindow)
  224055. {
  224056. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  224057. }
  224058. else
  224059. {
  224060. jassertfalse // don't know how to do this
  224061. }
  224062. }
  224063. }
  224064. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  224065. {
  224066. // to do..
  224067. }
  224068. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  224069. {
  224070. NSArray* touches = [[event touchesForView: view] allObjects];
  224071. for (unsigned int i = 0; i < [touches count]; ++i)
  224072. {
  224073. UITouch* touch = [touches objectAtIndex: i];
  224074. CGPoint p = [touch locationInView: view];
  224075. const Point<int> pos ((int) p.x, (int) p.y);
  224076. juce_lastMousePos = pos + getScreenPosition();
  224077. const int64 time = getMouseTime (event);
  224078. int touchIndex = currentTouches.indexOf (touch);
  224079. if (touchIndex < 0)
  224080. {
  224081. touchIndex = currentTouches.size();
  224082. currentTouches.add (touch);
  224083. }
  224084. if (isDown)
  224085. {
  224086. currentModifiers = currentModifiers.withoutMouseButtons();
  224087. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  224088. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  224089. }
  224090. else if (isUp)
  224091. {
  224092. currentModifiers = currentModifiers.withoutMouseButtons();
  224093. currentTouches.remove (touchIndex);
  224094. }
  224095. if (isCancel)
  224096. currentTouches.clear();
  224097. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  224098. }
  224099. }
  224100. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  224101. void UIViewComponentPeer::viewFocusGain()
  224102. {
  224103. if (currentlyFocusedPeer != this)
  224104. {
  224105. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  224106. currentlyFocusedPeer->handleFocusLoss();
  224107. currentlyFocusedPeer = this;
  224108. handleFocusGain();
  224109. }
  224110. }
  224111. void UIViewComponentPeer::viewFocusLoss()
  224112. {
  224113. if (currentlyFocusedPeer == this)
  224114. {
  224115. currentlyFocusedPeer = 0;
  224116. handleFocusLoss();
  224117. }
  224118. }
  224119. void juce_HandleProcessFocusChange()
  224120. {
  224121. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  224122. {
  224123. if (Process::isForegroundProcess())
  224124. {
  224125. currentlyFocusedPeer->handleFocusGain();
  224126. ComponentPeer::bringModalComponentToFront();
  224127. }
  224128. else
  224129. {
  224130. currentlyFocusedPeer->handleFocusLoss();
  224131. // turn kiosk mode off if we lose focus..
  224132. Desktop::getInstance().setKioskModeComponent (0);
  224133. }
  224134. }
  224135. }
  224136. bool UIViewComponentPeer::isFocused() const
  224137. {
  224138. return isSharedWindow ? this == currentlyFocusedPeer
  224139. : (window != 0 && [window isKeyWindow]);
  224140. }
  224141. void UIViewComponentPeer::grabFocus()
  224142. {
  224143. if (window != 0)
  224144. {
  224145. [window makeKeyWindow];
  224146. viewFocusGain();
  224147. }
  224148. }
  224149. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  224150. {
  224151. }
  224152. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  224153. {
  224154. view->hiddenTextField.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  224155. }
  224156. BOOL UIViewComponentPeer::textFieldReplaceCharacters (const Range<int>& range, const String& text)
  224157. {
  224158. TextInputTarget* const target = findCurrentTextInputTarget();
  224159. if (target != 0)
  224160. {
  224161. const Range<int> currentSelection (target->getHighlightedRegion());
  224162. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  224163. if (currentSelection.isEmpty())
  224164. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  224165. target->insertTextAtCaret (text);
  224166. updateHiddenTextContent (target);
  224167. }
  224168. return NO;
  224169. }
  224170. BOOL UIViewComponentPeer::textFieldShouldClear()
  224171. {
  224172. TextInputTarget* const target = findCurrentTextInputTarget();
  224173. if (target != 0)
  224174. {
  224175. target->setHighlightedRegion (Range<int> (0, std::numeric_limits<int>::max()));
  224176. target->insertTextAtCaret (String::empty);
  224177. updateHiddenTextContent (target);
  224178. }
  224179. return YES;
  224180. }
  224181. BOOL UIViewComponentPeer::textFieldShouldReturn()
  224182. {
  224183. TextInputTarget* const target = findCurrentTextInputTarget();
  224184. if (target != 0)
  224185. {
  224186. target->insertTextAtCaret ("\n");
  224187. updateHiddenTextContent (target);
  224188. }
  224189. return YES;
  224190. }
  224191. void UIViewComponentPeer::globalFocusChanged (Component*)
  224192. {
  224193. TextInputTarget* const target = findCurrentTextInputTarget();
  224194. if (target != 0)
  224195. {
  224196. Component* comp = dynamic_cast<Component*> (target);
  224197. Point<int> pos (comp->relativePositionToOtherComponent (component, Point<int>()));
  224198. view->hiddenTextField.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  224199. updateHiddenTextContent (target);
  224200. [view->hiddenTextField becomeFirstResponder];
  224201. }
  224202. else
  224203. {
  224204. [view->hiddenTextField resignFirstResponder];
  224205. }
  224206. }
  224207. void UIViewComponentPeer::drawRect (CGRect r)
  224208. {
  224209. if (r.size.width < 1.0f || r.size.height < 1.0f)
  224210. return;
  224211. CGContextRef cg = UIGraphicsGetCurrentContext();
  224212. if (! component->isOpaque())
  224213. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  224214. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  224215. CoreGraphicsContext g (cg, view.bounds.size.height);
  224216. insideDrawRect = true;
  224217. handlePaint (g);
  224218. insideDrawRect = false;
  224219. }
  224220. bool UIViewComponentPeer::canBecomeKeyWindow()
  224221. {
  224222. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  224223. }
  224224. bool UIViewComponentPeer::windowShouldClose()
  224225. {
  224226. if (! isValidPeer (this))
  224227. return YES;
  224228. handleUserClosingWindow();
  224229. return NO;
  224230. }
  224231. void UIViewComponentPeer::redirectMovedOrResized()
  224232. {
  224233. handleMovedOrResized();
  224234. }
  224235. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  224236. {
  224237. }
  224238. class AsyncRepaintMessage : public CallbackMessage
  224239. {
  224240. public:
  224241. UIViewComponentPeer* const peer;
  224242. const Rectangle<int> rect;
  224243. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  224244. : peer (peer_), rect (rect_)
  224245. {
  224246. }
  224247. void messageCallback()
  224248. {
  224249. if (ComponentPeer::isValidPeer (peer))
  224250. peer->repaint (rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight());
  224251. }
  224252. };
  224253. void UIViewComponentPeer::repaint (int x, int y, int w, int h)
  224254. {
  224255. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  224256. {
  224257. (new AsyncRepaintMessage (this, Rectangle<int> (x, y, w, h)))->post();
  224258. }
  224259. else
  224260. {
  224261. [view setNeedsDisplayInRect: CGRectMake ((float) x, (float) y, (float) w, (float) h)];
  224262. }
  224263. }
  224264. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  224265. {
  224266. }
  224267. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  224268. {
  224269. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  224270. }
  224271. Image* juce_createIconForFile (const File& file)
  224272. {
  224273. return 0;
  224274. }
  224275. void Desktop::createMouseInputSources()
  224276. {
  224277. for (int i = 0; i < 10; ++i)
  224278. mouseSources.add (new MouseInputSource (i, false));
  224279. }
  224280. bool Desktop::canUseSemiTransparentWindows() throw()
  224281. {
  224282. return true;
  224283. }
  224284. const Point<int> Desktop::getMousePosition()
  224285. {
  224286. return juce_lastMousePos;
  224287. }
  224288. void Desktop::setMousePosition (const Point<int>&)
  224289. {
  224290. }
  224291. const int KeyPress::spaceKey = ' ';
  224292. const int KeyPress::returnKey = 0x0d;
  224293. const int KeyPress::escapeKey = 0x1b;
  224294. const int KeyPress::backspaceKey = 0x7f;
  224295. const int KeyPress::leftKey = 0x1000;
  224296. const int KeyPress::rightKey = 0x1001;
  224297. const int KeyPress::upKey = 0x1002;
  224298. const int KeyPress::downKey = 0x1003;
  224299. const int KeyPress::pageUpKey = 0x1004;
  224300. const int KeyPress::pageDownKey = 0x1005;
  224301. const int KeyPress::endKey = 0x1006;
  224302. const int KeyPress::homeKey = 0x1007;
  224303. const int KeyPress::deleteKey = 0x1008;
  224304. const int KeyPress::insertKey = -1;
  224305. const int KeyPress::tabKey = 9;
  224306. const int KeyPress::F1Key = 0x2001;
  224307. const int KeyPress::F2Key = 0x2002;
  224308. const int KeyPress::F3Key = 0x2003;
  224309. const int KeyPress::F4Key = 0x2004;
  224310. const int KeyPress::F5Key = 0x2005;
  224311. const int KeyPress::F6Key = 0x2006;
  224312. const int KeyPress::F7Key = 0x2007;
  224313. const int KeyPress::F8Key = 0x2008;
  224314. const int KeyPress::F9Key = 0x2009;
  224315. const int KeyPress::F10Key = 0x200a;
  224316. const int KeyPress::F11Key = 0x200b;
  224317. const int KeyPress::F12Key = 0x200c;
  224318. const int KeyPress::F13Key = 0x200d;
  224319. const int KeyPress::F14Key = 0x200e;
  224320. const int KeyPress::F15Key = 0x200f;
  224321. const int KeyPress::F16Key = 0x2010;
  224322. const int KeyPress::numberPad0 = 0x30020;
  224323. const int KeyPress::numberPad1 = 0x30021;
  224324. const int KeyPress::numberPad2 = 0x30022;
  224325. const int KeyPress::numberPad3 = 0x30023;
  224326. const int KeyPress::numberPad4 = 0x30024;
  224327. const int KeyPress::numberPad5 = 0x30025;
  224328. const int KeyPress::numberPad6 = 0x30026;
  224329. const int KeyPress::numberPad7 = 0x30027;
  224330. const int KeyPress::numberPad8 = 0x30028;
  224331. const int KeyPress::numberPad9 = 0x30029;
  224332. const int KeyPress::numberPadAdd = 0x3002a;
  224333. const int KeyPress::numberPadSubtract = 0x3002b;
  224334. const int KeyPress::numberPadMultiply = 0x3002c;
  224335. const int KeyPress::numberPadDivide = 0x3002d;
  224336. const int KeyPress::numberPadSeparator = 0x3002e;
  224337. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  224338. const int KeyPress::numberPadEquals = 0x30030;
  224339. const int KeyPress::numberPadDelete = 0x30031;
  224340. const int KeyPress::playKey = 0x30000;
  224341. const int KeyPress::stopKey = 0x30001;
  224342. const int KeyPress::fastForwardKey = 0x30002;
  224343. const int KeyPress::rewindKey = 0x30003;
  224344. #endif
  224345. /*** End of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  224346. /*** Start of inlined file: juce_iphone_MessageManager.mm ***/
  224347. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224348. // compiled on its own).
  224349. #if JUCE_INCLUDED_FILE
  224350. struct CallbackMessagePayload
  224351. {
  224352. MessageCallbackFunction* function;
  224353. void* parameter;
  224354. void* volatile result;
  224355. bool volatile hasBeenExecuted;
  224356. };
  224357. END_JUCE_NAMESPACE
  224358. using namespace JUCE_NAMESPACE;
  224359. @interface JuceAppDelegate : NSObject <UIApplicationDelegate>
  224360. {
  224361. }
  224362. - (JuceAppDelegate*) init;
  224363. - (void) dealloc;
  224364. - (BOOL) application: (UIApplication*) application handleOpenURL: (NSURL*) url;
  224365. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  224366. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  224367. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  224368. - (void) customEvent: (id) data;
  224369. - (void) performCallback: (id) info;
  224370. @end
  224371. @implementation JuceAppDelegate
  224372. - (JuceAppDelegate*) init
  224373. {
  224374. [super init];
  224375. [[UIApplication sharedApplication] setDelegate: self];
  224376. return self;
  224377. }
  224378. - (void) dealloc
  224379. {
  224380. [[UIApplication sharedApplication] setDelegate: nil];
  224381. [super dealloc];
  224382. }
  224383. - (BOOL) application: (UIApplication*) application handleOpenURL: (NSURL*) url
  224384. {
  224385. if (JUCEApplication::getInstance() != 0)
  224386. {
  224387. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce ([url absoluteString]));
  224388. return YES;
  224389. }
  224390. return NO;
  224391. }
  224392. - (void) applicationDidBecomeActive: (NSNotification*) aNotification
  224393. {
  224394. juce_HandleProcessFocusChange();
  224395. }
  224396. - (void) applicationDidResignActive: (NSNotification*) aNotification
  224397. {
  224398. juce_HandleProcessFocusChange();
  224399. }
  224400. - (void) applicationWillUnhide: (NSNotification*) aNotification
  224401. {
  224402. juce_HandleProcessFocusChange();
  224403. }
  224404. - (void) customEvent: (id) n
  224405. {
  224406. NSData* data = (NSData*) n;
  224407. void* message = 0;
  224408. [data getBytes: &message length: sizeof (message)];
  224409. [data release];
  224410. if (message != 0)
  224411. MessageManager::getInstance()->deliverMessage (message);
  224412. }
  224413. - (void) performCallback: (id) info
  224414. {
  224415. if ([info isKindOfClass: [NSData class]])
  224416. {
  224417. CallbackMessagePayload* pl = (CallbackMessagePayload*) [((NSData*) info) bytes];
  224418. if (pl != 0)
  224419. {
  224420. pl->result = (*pl->function) (pl->parameter);
  224421. pl->hasBeenExecuted = true;
  224422. }
  224423. }
  224424. else
  224425. {
  224426. jassertfalse // should never get here!
  224427. }
  224428. }
  224429. @end
  224430. BEGIN_JUCE_NAMESPACE
  224431. static JuceAppDelegate* juceAppDelegate = 0;
  224432. void MessageManager::runDispatchLoop()
  224433. {
  224434. jassert (isThisTheMessageThread()); // must only be called by the message thread
  224435. runDispatchLoopUntil (-1);
  224436. }
  224437. void MessageManager::stopDispatchLoop()
  224438. {
  224439. exit (0); // iPhone apps get no mercy..
  224440. }
  224441. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  224442. {
  224443. const ScopedAutoReleasePool pool;
  224444. jassert (isThisTheMessageThread()); // must only be called by the message thread
  224445. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  224446. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  224447. while (! quitMessagePosted)
  224448. {
  224449. const ScopedAutoReleasePool pool;
  224450. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  224451. beforeDate: endDate];
  224452. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  224453. break;
  224454. }
  224455. return ! quitMessagePosted;
  224456. }
  224457. static CFRunLoopRef runLoop = 0;
  224458. static CFRunLoopSourceRef runLoopSource = 0;
  224459. static Array <void*, CriticalSection>* pendingMessages = 0;
  224460. static void runLoopSourceCallback (void*)
  224461. {
  224462. if (pendingMessages != 0)
  224463. {
  224464. int numDispatched = 0;
  224465. do
  224466. {
  224467. void* const nextMessage = pendingMessages->remove (0);
  224468. if (nextMessage == 0)
  224469. return;
  224470. const ScopedAutoReleasePool pool;
  224471. MessageManager::getInstance()->deliverMessage (nextMessage);
  224472. } while (++numDispatched <= 4);
  224473. CFRunLoopSourceSignal (runLoopSource);
  224474. CFRunLoopWakeUp (runLoop);
  224475. }
  224476. }
  224477. void MessageManager::doPlatformSpecificInitialisation()
  224478. {
  224479. pendingMessages = new Array <void*, CriticalSection>();
  224480. runLoop = CFRunLoopGetCurrent();
  224481. CFRunLoopSourceContext sourceContext;
  224482. zerostruct (sourceContext);
  224483. sourceContext.perform = runLoopSourceCallback;
  224484. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  224485. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  224486. if (juceAppDelegate == 0)
  224487. juceAppDelegate = [[JuceAppDelegate alloc] init];
  224488. }
  224489. void MessageManager::doPlatformSpecificShutdown()
  224490. {
  224491. CFRunLoopSourceInvalidate (runLoopSource);
  224492. CFRelease (runLoopSource);
  224493. runLoopSource = 0;
  224494. if (pendingMessages != 0)
  224495. {
  224496. while (pendingMessages->size() > 0)
  224497. delete ((Message*) pendingMessages->remove(0));
  224498. deleteAndZero (pendingMessages);
  224499. }
  224500. if (juceAppDelegate != 0)
  224501. {
  224502. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  224503. [juceAppDelegate release];
  224504. juceAppDelegate = 0;
  224505. }
  224506. }
  224507. bool juce_postMessageToSystemQueue (void* message)
  224508. {
  224509. if (pendingMessages != 0)
  224510. {
  224511. pendingMessages->add (message);
  224512. CFRunLoopSourceSignal (runLoopSource);
  224513. CFRunLoopWakeUp (runLoop);
  224514. }
  224515. return true;
  224516. }
  224517. void MessageManager::broadcastMessage (const String& value) throw()
  224518. {
  224519. }
  224520. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  224521. void* data)
  224522. {
  224523. if (isThisTheMessageThread())
  224524. {
  224525. return (*callback) (data);
  224526. }
  224527. else
  224528. {
  224529. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  224530. // deadlock because the message manager is blocked from running, so can never
  224531. // call your function..
  224532. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  224533. const ScopedAutoReleasePool pool;
  224534. CallbackMessagePayload cmp;
  224535. cmp.function = callback;
  224536. cmp.parameter = data;
  224537. cmp.result = 0;
  224538. cmp.hasBeenExecuted = false;
  224539. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  224540. withObject: [NSData dataWithBytesNoCopy: &cmp
  224541. length: sizeof (cmp)
  224542. freeWhenDone: NO]
  224543. waitUntilDone: YES];
  224544. return cmp.result;
  224545. }
  224546. }
  224547. #endif
  224548. /*** End of inlined file: juce_iphone_MessageManager.mm ***/
  224549. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  224550. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224551. // compiled on its own).
  224552. #if JUCE_INCLUDED_FILE
  224553. #if JUCE_MAC
  224554. END_JUCE_NAMESPACE
  224555. using namespace JUCE_NAMESPACE;
  224556. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  224557. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  224558. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  224559. #else
  224560. @interface JuceFileChooserDelegate : NSObject
  224561. #endif
  224562. {
  224563. StringArray* filters;
  224564. }
  224565. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  224566. - (void) dealloc;
  224567. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  224568. @end
  224569. @implementation JuceFileChooserDelegate
  224570. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  224571. {
  224572. [super init];
  224573. filters = filters_;
  224574. return self;
  224575. }
  224576. - (void) dealloc
  224577. {
  224578. delete filters;
  224579. [super dealloc];
  224580. }
  224581. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  224582. {
  224583. (void) sender;
  224584. const File f (nsStringToJuce (filename));
  224585. for (int i = filters->size(); --i >= 0;)
  224586. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  224587. return true;
  224588. return f.isDirectory();
  224589. }
  224590. @end
  224591. BEGIN_JUCE_NAMESPACE
  224592. void FileChooser::showPlatformDialog (Array<File>& results,
  224593. const String& title,
  224594. const File& currentFileOrDirectory,
  224595. const String& filter,
  224596. bool selectsDirectory,
  224597. bool selectsFiles,
  224598. bool isSaveDialogue,
  224599. bool warnAboutOverwritingExistingFiles,
  224600. bool selectMultipleFiles,
  224601. FilePreviewComponent* extraInfoComponent)
  224602. {
  224603. const ScopedAutoReleasePool pool;
  224604. StringArray* filters = new StringArray();
  224605. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  224606. filters->trim();
  224607. filters->removeEmptyStrings();
  224608. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  224609. [delegate autorelease];
  224610. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  224611. : [NSOpenPanel openPanel];
  224612. [panel setTitle: juceStringToNS (title)];
  224613. if (! isSaveDialogue)
  224614. {
  224615. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  224616. [openPanel setCanChooseDirectories: selectsDirectory];
  224617. [openPanel setCanChooseFiles: selectsFiles];
  224618. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  224619. }
  224620. [panel setDelegate: delegate];
  224621. if (isSaveDialogue || selectsDirectory)
  224622. [panel setCanCreateDirectories: YES];
  224623. String directory, filename;
  224624. if (currentFileOrDirectory.isDirectory())
  224625. {
  224626. directory = currentFileOrDirectory.getFullPathName();
  224627. }
  224628. else
  224629. {
  224630. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  224631. filename = currentFileOrDirectory.getFileName();
  224632. }
  224633. if ([panel runModalForDirectory: juceStringToNS (directory)
  224634. file: juceStringToNS (filename)]
  224635. == NSOKButton)
  224636. {
  224637. if (isSaveDialogue)
  224638. {
  224639. results.add (File (nsStringToJuce ([panel filename])));
  224640. }
  224641. else
  224642. {
  224643. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  224644. NSArray* urls = [openPanel filenames];
  224645. for (unsigned int i = 0; i < [urls count]; ++i)
  224646. {
  224647. NSString* f = [urls objectAtIndex: i];
  224648. results.add (File (nsStringToJuce (f)));
  224649. }
  224650. }
  224651. }
  224652. [panel setDelegate: nil];
  224653. }
  224654. #else
  224655. void FileChooser::showPlatformDialog (Array<File>& results,
  224656. const String& title,
  224657. const File& currentFileOrDirectory,
  224658. const String& filter,
  224659. bool selectsDirectory,
  224660. bool selectsFiles,
  224661. bool isSaveDialogue,
  224662. bool warnAboutOverwritingExistingFiles,
  224663. bool selectMultipleFiles,
  224664. FilePreviewComponent* extraInfoComponent)
  224665. {
  224666. const ScopedAutoReleasePool pool;
  224667. jassertfalse //xxx to do
  224668. }
  224669. #endif
  224670. #endif
  224671. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  224672. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  224673. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224674. // compiled on its own).
  224675. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  224676. #if JUCE_MAC
  224677. END_JUCE_NAMESPACE
  224678. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  224679. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  224680. {
  224681. CriticalSection* contextLock;
  224682. bool needsUpdate;
  224683. }
  224684. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  224685. - (bool) makeActive;
  224686. - (void) makeInactive;
  224687. - (void) reshape;
  224688. @end
  224689. @implementation ThreadSafeNSOpenGLView
  224690. - (id) initWithFrame: (NSRect) frameRect
  224691. pixelFormat: (NSOpenGLPixelFormat*) format
  224692. {
  224693. contextLock = new CriticalSection();
  224694. self = [super initWithFrame: frameRect pixelFormat: format];
  224695. if (self != nil)
  224696. [[NSNotificationCenter defaultCenter] addObserver: self
  224697. selector: @selector (_surfaceNeedsUpdate:)
  224698. name: NSViewGlobalFrameDidChangeNotification
  224699. object: self];
  224700. return self;
  224701. }
  224702. - (void) dealloc
  224703. {
  224704. [[NSNotificationCenter defaultCenter] removeObserver: self];
  224705. delete contextLock;
  224706. [super dealloc];
  224707. }
  224708. - (bool) makeActive
  224709. {
  224710. const ScopedLock sl (*contextLock);
  224711. if ([self openGLContext] == 0)
  224712. return false;
  224713. [[self openGLContext] makeCurrentContext];
  224714. if (needsUpdate)
  224715. {
  224716. [super update];
  224717. needsUpdate = false;
  224718. }
  224719. return true;
  224720. }
  224721. - (void) makeInactive
  224722. {
  224723. const ScopedLock sl (*contextLock);
  224724. [NSOpenGLContext clearCurrentContext];
  224725. }
  224726. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  224727. {
  224728. const ScopedLock sl (*contextLock);
  224729. needsUpdate = true;
  224730. }
  224731. - (void) update
  224732. {
  224733. const ScopedLock sl (*contextLock);
  224734. needsUpdate = true;
  224735. }
  224736. - (void) reshape
  224737. {
  224738. const ScopedLock sl (*contextLock);
  224739. needsUpdate = true;
  224740. }
  224741. @end
  224742. BEGIN_JUCE_NAMESPACE
  224743. class WindowedGLContext : public OpenGLContext
  224744. {
  224745. public:
  224746. WindowedGLContext (Component* const component,
  224747. const OpenGLPixelFormat& pixelFormat_,
  224748. NSOpenGLContext* sharedContext)
  224749. : renderContext (0),
  224750. pixelFormat (pixelFormat_)
  224751. {
  224752. jassert (component != 0);
  224753. NSOpenGLPixelFormatAttribute attribs [64];
  224754. int n = 0;
  224755. attribs[n++] = NSOpenGLPFADoubleBuffer;
  224756. attribs[n++] = NSOpenGLPFAAccelerated;
  224757. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  224758. attribs[n++] = NSOpenGLPFAColorSize;
  224759. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  224760. pixelFormat.greenBits,
  224761. pixelFormat.blueBits);
  224762. attribs[n++] = NSOpenGLPFAAlphaSize;
  224763. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  224764. attribs[n++] = NSOpenGLPFADepthSize;
  224765. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  224766. attribs[n++] = NSOpenGLPFAStencilSize;
  224767. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  224768. attribs[n++] = NSOpenGLPFAAccumSize;
  224769. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  224770. pixelFormat.accumulationBufferGreenBits,
  224771. pixelFormat.accumulationBufferBlueBits,
  224772. pixelFormat.accumulationBufferAlphaBits);
  224773. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  224774. attribs[n++] = NSOpenGLPFASampleBuffers;
  224775. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  224776. attribs[n++] = NSOpenGLPFAClosestPolicy;
  224777. attribs[n++] = NSOpenGLPFANoRecovery;
  224778. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  224779. NSOpenGLPixelFormat* format
  224780. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  224781. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  224782. pixelFormat: format];
  224783. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  224784. shareContext: sharedContext] autorelease];
  224785. const GLint swapInterval = 1;
  224786. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  224787. [view setOpenGLContext: renderContext];
  224788. [renderContext setView: view];
  224789. [format release];
  224790. viewHolder = new NSViewComponentInternal (view, component);
  224791. }
  224792. ~WindowedGLContext()
  224793. {
  224794. makeInactive();
  224795. [renderContext clearDrawable];
  224796. viewHolder = 0;
  224797. }
  224798. bool makeActive() const throw()
  224799. {
  224800. jassert (renderContext != 0);
  224801. [view makeActive];
  224802. return isActive();
  224803. }
  224804. bool makeInactive() const throw()
  224805. {
  224806. [view makeInactive];
  224807. return true;
  224808. }
  224809. bool isActive() const throw()
  224810. {
  224811. return [NSOpenGLContext currentContext] == renderContext;
  224812. }
  224813. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  224814. void* getRawContext() const throw() { return renderContext; }
  224815. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  224816. {
  224817. }
  224818. void swapBuffers()
  224819. {
  224820. [renderContext flushBuffer];
  224821. }
  224822. bool setSwapInterval (const int numFramesPerSwap)
  224823. {
  224824. [renderContext setValues: (const GLint*) &numFramesPerSwap
  224825. forParameter: NSOpenGLCPSwapInterval];
  224826. return true;
  224827. }
  224828. int getSwapInterval() const
  224829. {
  224830. GLint numFrames = 0;
  224831. [renderContext getValues: &numFrames
  224832. forParameter: NSOpenGLCPSwapInterval];
  224833. return numFrames;
  224834. }
  224835. void repaint()
  224836. {
  224837. // we need to invalidate the juce view that holds this gl view, to make it
  224838. // cause a repaint callback
  224839. NSView* v = (NSView*) viewHolder->view;
  224840. NSRect r = [v frame];
  224841. // bit of a bodge here.. if we only invalidate the area of the gl component,
  224842. // it's completely covered by the NSOpenGLView, so the OS throws away the
  224843. // repaint message, thus never causing our paint() callback, and never repainting
  224844. // the comp. So invalidating just a little bit around the edge helps..
  224845. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  224846. }
  224847. void* getNativeWindowHandle() const { return viewHolder->view; }
  224848. juce_UseDebuggingNewOperator
  224849. NSOpenGLContext* renderContext;
  224850. ThreadSafeNSOpenGLView* view;
  224851. private:
  224852. OpenGLPixelFormat pixelFormat;
  224853. ScopedPointer <NSViewComponentInternal> viewHolder;
  224854. WindowedGLContext (const WindowedGLContext&);
  224855. WindowedGLContext& operator= (const WindowedGLContext&);
  224856. };
  224857. OpenGLContext* OpenGLComponent::createContext()
  224858. {
  224859. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  224860. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  224861. return (c->renderContext != 0) ? c.release() : 0;
  224862. }
  224863. void* OpenGLComponent::getNativeWindowHandle() const
  224864. {
  224865. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  224866. : 0;
  224867. }
  224868. void juce_glViewport (const int w, const int h)
  224869. {
  224870. glViewport (0, 0, w, h);
  224871. }
  224872. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  224873. OwnedArray <OpenGLPixelFormat>& results)
  224874. {
  224875. /* GLint attribs [64];
  224876. int n = 0;
  224877. attribs[n++] = AGL_RGBA;
  224878. attribs[n++] = AGL_DOUBLEBUFFER;
  224879. attribs[n++] = AGL_ACCELERATED;
  224880. attribs[n++] = AGL_NO_RECOVERY;
  224881. attribs[n++] = AGL_NONE;
  224882. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  224883. while (p != 0)
  224884. {
  224885. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  224886. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  224887. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  224888. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  224889. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  224890. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  224891. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  224892. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  224893. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  224894. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  224895. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  224896. results.add (pf);
  224897. p = aglNextPixelFormat (p);
  224898. }*/
  224899. //jassertfalse //xxx can't see how you do this in cocoa!
  224900. }
  224901. #else
  224902. END_JUCE_NAMESPACE
  224903. @interface JuceGLView : UIView
  224904. {
  224905. }
  224906. + (Class) layerClass;
  224907. @end
  224908. @implementation JuceGLView
  224909. + (Class) layerClass
  224910. {
  224911. return [CAEAGLLayer class];
  224912. }
  224913. @end
  224914. BEGIN_JUCE_NAMESPACE
  224915. class GLESContext : public OpenGLContext
  224916. {
  224917. public:
  224918. GLESContext (UIViewComponentPeer* peer,
  224919. Component* const component_,
  224920. const OpenGLPixelFormat& pixelFormat_,
  224921. const GLESContext* const sharedContext,
  224922. NSUInteger apiType)
  224923. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  224924. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  224925. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  224926. {
  224927. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  224928. view.opaque = YES;
  224929. view.hidden = NO;
  224930. view.backgroundColor = [UIColor blackColor];
  224931. view.userInteractionEnabled = NO;
  224932. glLayer = (CAEAGLLayer*) [view layer];
  224933. [peer->view addSubview: view];
  224934. if (sharedContext != 0)
  224935. context = [[EAGLContext alloc] initWithAPI: apiType
  224936. sharegroup: [sharedContext->context sharegroup]];
  224937. else
  224938. context = [[EAGLContext alloc] initWithAPI: apiType];
  224939. createGLBuffers();
  224940. }
  224941. ~GLESContext()
  224942. {
  224943. makeInactive();
  224944. [context release];
  224945. [view removeFromSuperview];
  224946. [view release];
  224947. freeGLBuffers();
  224948. }
  224949. bool makeActive() const throw()
  224950. {
  224951. jassert (context != 0);
  224952. [EAGLContext setCurrentContext: context];
  224953. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  224954. return true;
  224955. }
  224956. void swapBuffers()
  224957. {
  224958. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  224959. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  224960. }
  224961. bool makeInactive() const throw()
  224962. {
  224963. return [EAGLContext setCurrentContext: nil];
  224964. }
  224965. bool isActive() const throw()
  224966. {
  224967. return [EAGLContext currentContext] == context;
  224968. }
  224969. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  224970. void* getRawContext() const throw() { return glLayer; }
  224971. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  224972. {
  224973. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  224974. if (lastWidth != w || lastHeight != h)
  224975. {
  224976. lastWidth = w;
  224977. lastHeight = h;
  224978. freeGLBuffers();
  224979. createGLBuffers();
  224980. }
  224981. }
  224982. bool setSwapInterval (const int numFramesPerSwap)
  224983. {
  224984. numFrames = numFramesPerSwap;
  224985. return true;
  224986. }
  224987. int getSwapInterval() const
  224988. {
  224989. return numFrames;
  224990. }
  224991. void repaint()
  224992. {
  224993. }
  224994. void createGLBuffers()
  224995. {
  224996. makeActive();
  224997. glGenFramebuffersOES (1, &frameBufferHandle);
  224998. glGenRenderbuffersOES (1, &colorBufferHandle);
  224999. glGenRenderbuffersOES (1, &depthBufferHandle);
  225000. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  225001. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  225002. GLint width, height;
  225003. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  225004. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  225005. if (useDepthBuffer)
  225006. {
  225007. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  225008. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  225009. }
  225010. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  225011. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  225012. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  225013. if (useDepthBuffer)
  225014. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  225015. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  225016. }
  225017. void freeGLBuffers()
  225018. {
  225019. if (frameBufferHandle != 0)
  225020. {
  225021. glDeleteFramebuffersOES (1, &frameBufferHandle);
  225022. frameBufferHandle = 0;
  225023. }
  225024. if (colorBufferHandle != 0)
  225025. {
  225026. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  225027. colorBufferHandle = 0;
  225028. }
  225029. if (depthBufferHandle != 0)
  225030. {
  225031. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  225032. depthBufferHandle = 0;
  225033. }
  225034. }
  225035. juce_UseDebuggingNewOperator
  225036. private:
  225037. Component::SafePointer<Component> component;
  225038. OpenGLPixelFormat pixelFormat;
  225039. JuceGLView* view;
  225040. CAEAGLLayer* glLayer;
  225041. EAGLContext* context;
  225042. bool useDepthBuffer;
  225043. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  225044. int numFrames;
  225045. int lastWidth, lastHeight;
  225046. GLESContext (const GLESContext&);
  225047. GLESContext& operator= (const GLESContext&);
  225048. };
  225049. OpenGLContext* OpenGLComponent::createContext()
  225050. {
  225051. ScopedAutoReleasePool pool;
  225052. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  225053. if (peer != 0)
  225054. return new GLESContext (peer, this, preferredPixelFormat,
  225055. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  225056. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  225057. return 0;
  225058. }
  225059. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  225060. OwnedArray <OpenGLPixelFormat>& /*results*/)
  225061. {
  225062. }
  225063. void juce_glViewport (const int w, const int h)
  225064. {
  225065. glViewport (0, 0, w, h);
  225066. }
  225067. #endif
  225068. #endif
  225069. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  225070. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  225071. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225072. // compiled on its own).
  225073. #if JUCE_INCLUDED_FILE
  225074. #if JUCE_MAC
  225075. namespace MouseCursorHelpers
  225076. {
  225077. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  225078. {
  225079. NSImage* im = CoreGraphicsImage::createNSImage (image);
  225080. NSCursor* c = [[NSCursor alloc] initWithImage: im
  225081. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  225082. [im release];
  225083. return c;
  225084. }
  225085. static void* fromWebKitFile (const char* filename, float hx, float hy)
  225086. {
  225087. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  225088. BufferedInputStream buf (&fileStream, 4096, false);
  225089. PNGImageFormat pngFormat;
  225090. const ScopedPointer <Image> im (pngFormat.decodeImage (buf));
  225091. if (im != 0)
  225092. return createFromImage (*im, hx * im->getWidth(), hy * im->getHeight());
  225093. jassertfalse;
  225094. return 0;
  225095. }
  225096. }
  225097. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  225098. {
  225099. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  225100. }
  225101. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  225102. {
  225103. const ScopedAutoReleasePool pool;
  225104. NSCursor* c = 0;
  225105. switch (type)
  225106. {
  225107. case NormalCursor: c = [NSCursor arrowCursor]; break;
  225108. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  225109. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  225110. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  225111. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  225112. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  225113. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  225114. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  225115. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  225116. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  225117. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  225118. case UpDownResizeCursor:
  225119. case TopEdgeResizeCursor:
  225120. case BottomEdgeResizeCursor:
  225121. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  225122. case TopLeftCornerResizeCursor:
  225123. case BottomRightCornerResizeCursor:
  225124. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  225125. case TopRightCornerResizeCursor:
  225126. case BottomLeftCornerResizeCursor:
  225127. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  225128. case UpDownLeftRightResizeCursor:
  225129. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  225130. default:
  225131. jassertfalse;
  225132. break;
  225133. }
  225134. [c retain];
  225135. return c;
  225136. }
  225137. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  225138. {
  225139. [((NSCursor*) cursorHandle) release];
  225140. }
  225141. void MouseCursor::showInAllWindows() const
  225142. {
  225143. showInWindow (0);
  225144. }
  225145. void MouseCursor::showInWindow (ComponentPeer*) const
  225146. {
  225147. [((NSCursor*) getHandle()) set];
  225148. }
  225149. #else
  225150. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  225151. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  225152. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  225153. void MouseCursor::showInAllWindows() const {}
  225154. void MouseCursor::showInWindow (ComponentPeer*) const {}
  225155. #endif
  225156. #endif
  225157. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  225158. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  225159. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225160. // compiled on its own).
  225161. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  225162. #if JUCE_MAC
  225163. END_JUCE_NAMESPACE
  225164. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  225165. @interface DownloadClickDetector : NSObject
  225166. {
  225167. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  225168. }
  225169. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  225170. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  225171. request: (NSURLRequest*) request
  225172. frame: (WebFrame*) frame
  225173. decisionListener: (id<WebPolicyDecisionListener>) listener;
  225174. @end
  225175. @implementation DownloadClickDetector
  225176. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  225177. {
  225178. [super init];
  225179. ownerComponent = ownerComponent_;
  225180. return self;
  225181. }
  225182. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  225183. request: (NSURLRequest*) request
  225184. frame: (WebFrame*) frame
  225185. decisionListener: (id <WebPolicyDecisionListener>) listener
  225186. {
  225187. (void) sender;
  225188. (void) request;
  225189. (void) frame;
  225190. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  225191. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  225192. [listener use];
  225193. else
  225194. [listener ignore];
  225195. }
  225196. @end
  225197. BEGIN_JUCE_NAMESPACE
  225198. class WebBrowserComponentInternal : public NSViewComponent
  225199. {
  225200. public:
  225201. WebBrowserComponentInternal (WebBrowserComponent* owner)
  225202. {
  225203. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  225204. frameName: @""
  225205. groupName: @""];
  225206. setView (webView);
  225207. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  225208. [webView setPolicyDelegate: clickListener];
  225209. }
  225210. ~WebBrowserComponentInternal()
  225211. {
  225212. [webView setPolicyDelegate: nil];
  225213. [clickListener release];
  225214. setView (0);
  225215. }
  225216. void goToURL (const String& url,
  225217. const StringArray* headers,
  225218. const MemoryBlock* postData)
  225219. {
  225220. NSMutableURLRequest* r
  225221. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  225222. cachePolicy: NSURLRequestUseProtocolCachePolicy
  225223. timeoutInterval: 30.0];
  225224. if (postData != 0 && postData->getSize() > 0)
  225225. {
  225226. [r setHTTPMethod: @"POST"];
  225227. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  225228. length: postData->getSize()]];
  225229. }
  225230. if (headers != 0)
  225231. {
  225232. for (int i = 0; i < headers->size(); ++i)
  225233. {
  225234. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  225235. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  225236. [r setValue: juceStringToNS (headerValue)
  225237. forHTTPHeaderField: juceStringToNS (headerName)];
  225238. }
  225239. }
  225240. stop();
  225241. [[webView mainFrame] loadRequest: r];
  225242. }
  225243. void goBack()
  225244. {
  225245. [webView goBack];
  225246. }
  225247. void goForward()
  225248. {
  225249. [webView goForward];
  225250. }
  225251. void stop()
  225252. {
  225253. [webView stopLoading: nil];
  225254. }
  225255. void refresh()
  225256. {
  225257. [webView reload: nil];
  225258. }
  225259. private:
  225260. WebView* webView;
  225261. DownloadClickDetector* clickListener;
  225262. };
  225263. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  225264. : browser (0),
  225265. blankPageShown (false),
  225266. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  225267. {
  225268. setOpaque (true);
  225269. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  225270. }
  225271. WebBrowserComponent::~WebBrowserComponent()
  225272. {
  225273. deleteAndZero (browser);
  225274. }
  225275. void WebBrowserComponent::goToURL (const String& url,
  225276. const StringArray* headers,
  225277. const MemoryBlock* postData)
  225278. {
  225279. lastURL = url;
  225280. lastHeaders.clear();
  225281. if (headers != 0)
  225282. lastHeaders = *headers;
  225283. lastPostData.setSize (0);
  225284. if (postData != 0)
  225285. lastPostData = *postData;
  225286. blankPageShown = false;
  225287. browser->goToURL (url, headers, postData);
  225288. }
  225289. void WebBrowserComponent::stop()
  225290. {
  225291. browser->stop();
  225292. }
  225293. void WebBrowserComponent::goBack()
  225294. {
  225295. lastURL = String::empty;
  225296. blankPageShown = false;
  225297. browser->goBack();
  225298. }
  225299. void WebBrowserComponent::goForward()
  225300. {
  225301. lastURL = String::empty;
  225302. browser->goForward();
  225303. }
  225304. void WebBrowserComponent::refresh()
  225305. {
  225306. browser->refresh();
  225307. }
  225308. void WebBrowserComponent::paint (Graphics&)
  225309. {
  225310. }
  225311. void WebBrowserComponent::checkWindowAssociation()
  225312. {
  225313. if (isShowing())
  225314. {
  225315. if (blankPageShown)
  225316. goBack();
  225317. }
  225318. else
  225319. {
  225320. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  225321. {
  225322. // when the component becomes invisible, some stuff like flash
  225323. // carries on playing audio, so we need to force it onto a blank
  225324. // page to avoid this, (and send it back when it's made visible again).
  225325. blankPageShown = true;
  225326. browser->goToURL ("about:blank", 0, 0);
  225327. }
  225328. }
  225329. }
  225330. void WebBrowserComponent::reloadLastURL()
  225331. {
  225332. if (lastURL.isNotEmpty())
  225333. {
  225334. goToURL (lastURL, &lastHeaders, &lastPostData);
  225335. lastURL = String::empty;
  225336. }
  225337. }
  225338. void WebBrowserComponent::parentHierarchyChanged()
  225339. {
  225340. checkWindowAssociation();
  225341. }
  225342. void WebBrowserComponent::resized()
  225343. {
  225344. browser->setSize (getWidth(), getHeight());
  225345. }
  225346. void WebBrowserComponent::visibilityChanged()
  225347. {
  225348. checkWindowAssociation();
  225349. }
  225350. bool WebBrowserComponent::pageAboutToLoad (const String&)
  225351. {
  225352. return true;
  225353. }
  225354. #else
  225355. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  225356. {
  225357. }
  225358. WebBrowserComponent::~WebBrowserComponent()
  225359. {
  225360. }
  225361. void WebBrowserComponent::goToURL (const String& url,
  225362. const StringArray* headers,
  225363. const MemoryBlock* postData)
  225364. {
  225365. }
  225366. void WebBrowserComponent::stop()
  225367. {
  225368. }
  225369. void WebBrowserComponent::goBack()
  225370. {
  225371. }
  225372. void WebBrowserComponent::goForward()
  225373. {
  225374. }
  225375. void WebBrowserComponent::refresh()
  225376. {
  225377. }
  225378. void WebBrowserComponent::paint (Graphics& g)
  225379. {
  225380. }
  225381. void WebBrowserComponent::checkWindowAssociation()
  225382. {
  225383. }
  225384. void WebBrowserComponent::reloadLastURL()
  225385. {
  225386. }
  225387. void WebBrowserComponent::parentHierarchyChanged()
  225388. {
  225389. }
  225390. void WebBrowserComponent::resized()
  225391. {
  225392. }
  225393. void WebBrowserComponent::visibilityChanged()
  225394. {
  225395. }
  225396. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  225397. {
  225398. return true;
  225399. }
  225400. #endif
  225401. #endif
  225402. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  225403. /*** Start of inlined file: juce_iphone_Audio.cpp ***/
  225404. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225405. // compiled on its own).
  225406. #if JUCE_INCLUDED_FILE
  225407. class IPhoneAudioIODevice : public AudioIODevice
  225408. {
  225409. public:
  225410. IPhoneAudioIODevice (const String& deviceName)
  225411. : AudioIODevice (deviceName, "Audio"),
  225412. audioUnit (0),
  225413. isRunning (false),
  225414. callback (0),
  225415. actualBufferSize (0),
  225416. floatData (1, 2)
  225417. {
  225418. numInputChannels = 2;
  225419. numOutputChannels = 2;
  225420. preferredBufferSize = 0;
  225421. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  225422. updateDeviceInfo();
  225423. }
  225424. ~IPhoneAudioIODevice()
  225425. {
  225426. close();
  225427. }
  225428. const StringArray getOutputChannelNames()
  225429. {
  225430. StringArray s;
  225431. s.add ("Left");
  225432. s.add ("Right");
  225433. return s;
  225434. }
  225435. const StringArray getInputChannelNames()
  225436. {
  225437. StringArray s;
  225438. if (audioInputIsAvailable)
  225439. {
  225440. s.add ("Left");
  225441. s.add ("Right");
  225442. }
  225443. return s;
  225444. }
  225445. int getNumSampleRates()
  225446. {
  225447. return 1;
  225448. }
  225449. double getSampleRate (int index)
  225450. {
  225451. return sampleRate;
  225452. }
  225453. int getNumBufferSizesAvailable()
  225454. {
  225455. return 1;
  225456. }
  225457. int getBufferSizeSamples (int index)
  225458. {
  225459. return getDefaultBufferSize();
  225460. }
  225461. int getDefaultBufferSize()
  225462. {
  225463. return 1024;
  225464. }
  225465. const String open (const BigInteger& inputChannels,
  225466. const BigInteger& outputChannels,
  225467. double sampleRate,
  225468. int bufferSize)
  225469. {
  225470. close();
  225471. lastError = String::empty;
  225472. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  225473. // xxx set up channel mapping
  225474. activeOutputChans = outputChannels;
  225475. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  225476. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  225477. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  225478. activeInputChans = inputChannels;
  225479. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  225480. numInputChannels = activeInputChans.countNumberOfSetBits();
  225481. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  225482. AudioSessionSetActive (true);
  225483. UInt32 audioCategory = kAudioSessionCategory_PlayAndRecord;
  225484. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  225485. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  225486. fixAudioRouteIfSetToReceiver();
  225487. updateDeviceInfo();
  225488. Float32 bufferDuration = preferredBufferSize / sampleRate;
  225489. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  225490. actualBufferSize = preferredBufferSize;
  225491. prepareFloatBuffers();
  225492. isRunning = true;
  225493. propertyChanged (0, 0, 0); // creates and starts the AU
  225494. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  225495. return lastError;
  225496. }
  225497. void close()
  225498. {
  225499. if (isRunning)
  225500. {
  225501. isRunning = false;
  225502. AudioSessionSetActive (false);
  225503. if (audioUnit != 0)
  225504. {
  225505. AudioComponentInstanceDispose (audioUnit);
  225506. audioUnit = 0;
  225507. }
  225508. }
  225509. }
  225510. bool isOpen()
  225511. {
  225512. return isRunning;
  225513. }
  225514. int getCurrentBufferSizeSamples()
  225515. {
  225516. return actualBufferSize;
  225517. }
  225518. double getCurrentSampleRate()
  225519. {
  225520. return sampleRate;
  225521. }
  225522. int getCurrentBitDepth()
  225523. {
  225524. return 16;
  225525. }
  225526. const BigInteger getActiveOutputChannels() const
  225527. {
  225528. return activeOutputChans;
  225529. }
  225530. const BigInteger getActiveInputChannels() const
  225531. {
  225532. return activeInputChans;
  225533. }
  225534. int getOutputLatencyInSamples()
  225535. {
  225536. return 0; //xxx
  225537. }
  225538. int getInputLatencyInSamples()
  225539. {
  225540. return 0; //xxx
  225541. }
  225542. void start (AudioIODeviceCallback* callback_)
  225543. {
  225544. if (isRunning && callback != callback_)
  225545. {
  225546. if (callback_ != 0)
  225547. callback_->audioDeviceAboutToStart (this);
  225548. const ScopedLock sl (callbackLock);
  225549. callback = callback_;
  225550. }
  225551. }
  225552. void stop()
  225553. {
  225554. if (isRunning)
  225555. {
  225556. AudioIODeviceCallback* lastCallback;
  225557. {
  225558. const ScopedLock sl (callbackLock);
  225559. lastCallback = callback;
  225560. callback = 0;
  225561. }
  225562. if (lastCallback != 0)
  225563. lastCallback->audioDeviceStopped();
  225564. }
  225565. }
  225566. bool isPlaying()
  225567. {
  225568. return isRunning && callback != 0;
  225569. }
  225570. const String getLastError()
  225571. {
  225572. return lastError;
  225573. }
  225574. private:
  225575. CriticalSection callbackLock;
  225576. Float64 sampleRate;
  225577. int numInputChannels, numOutputChannels;
  225578. int preferredBufferSize;
  225579. int actualBufferSize;
  225580. bool isRunning;
  225581. String lastError;
  225582. AudioStreamBasicDescription format;
  225583. AudioUnit audioUnit;
  225584. UInt32 audioInputIsAvailable;
  225585. AudioIODeviceCallback* callback;
  225586. BigInteger activeOutputChans, activeInputChans;
  225587. AudioSampleBuffer floatData;
  225588. float* inputChannels[3];
  225589. float* outputChannels[3];
  225590. bool monoInputChannelNumber, monoOutputChannelNumber;
  225591. void prepareFloatBuffers()
  225592. {
  225593. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  225594. zerostruct (inputChannels);
  225595. zerostruct (outputChannels);
  225596. for (int i = 0; i < numInputChannels; ++i)
  225597. inputChannels[i] = floatData.getSampleData (i);
  225598. for (int i = 0; i < numOutputChannels; ++i)
  225599. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  225600. }
  225601. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  225602. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  225603. {
  225604. OSStatus err = noErr;
  225605. if (audioInputIsAvailable)
  225606. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  225607. const ScopedLock sl (callbackLock);
  225608. if (callback != 0)
  225609. {
  225610. if (audioInputIsAvailable && numInputChannels > 0)
  225611. {
  225612. short* shortData = (short*) ioData->mBuffers[0].mData;
  225613. if (numInputChannels >= 2)
  225614. {
  225615. for (UInt32 i = 0; i < inNumberFrames; ++i)
  225616. {
  225617. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  225618. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  225619. }
  225620. }
  225621. else
  225622. {
  225623. if (monoInputChannelNumber > 0)
  225624. ++shortData;
  225625. for (UInt32 i = 0; i < inNumberFrames; ++i)
  225626. {
  225627. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  225628. ++shortData;
  225629. }
  225630. }
  225631. }
  225632. else
  225633. {
  225634. for (int i = numInputChannels; --i >= 0;)
  225635. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  225636. }
  225637. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  225638. outputChannels, numOutputChannels,
  225639. (int) inNumberFrames);
  225640. short* shortData = (short*) ioData->mBuffers[0].mData;
  225641. int n = 0;
  225642. if (numOutputChannels >= 2)
  225643. {
  225644. for (UInt32 i = 0; i < inNumberFrames; ++i)
  225645. {
  225646. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  225647. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  225648. }
  225649. }
  225650. else if (numOutputChannels == 1)
  225651. {
  225652. for (UInt32 i = 0; i < inNumberFrames; ++i)
  225653. {
  225654. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  225655. shortData [n++] = s;
  225656. shortData [n++] = s;
  225657. }
  225658. }
  225659. else
  225660. {
  225661. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  225662. }
  225663. }
  225664. else
  225665. {
  225666. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  225667. }
  225668. return err;
  225669. }
  225670. void updateDeviceInfo()
  225671. {
  225672. UInt32 size = sizeof (sampleRate);
  225673. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  225674. size = sizeof (audioInputIsAvailable);
  225675. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  225676. }
  225677. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  225678. {
  225679. if (! isRunning)
  225680. return;
  225681. if (inPropertyValue != 0)
  225682. {
  225683. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  225684. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  225685. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  225686. SInt32 routeChangeReason;
  225687. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  225688. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  225689. fixAudioRouteIfSetToReceiver();
  225690. }
  225691. updateDeviceInfo();
  225692. createAudioUnit();
  225693. AudioSessionSetActive (true);
  225694. if (audioUnit != 0)
  225695. {
  225696. UInt32 formatSize = sizeof (format);
  225697. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  225698. Float32 bufferDuration = preferredBufferSize / sampleRate;
  225699. UInt32 bufferDurationSize = sizeof (bufferDuration);
  225700. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  225701. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  225702. AudioOutputUnitStart (audioUnit);
  225703. }
  225704. }
  225705. void interruptionListener (UInt32 inInterruption)
  225706. {
  225707. /*if (inInterruption == kAudioSessionBeginInterruption)
  225708. {
  225709. isRunning = false;
  225710. AudioOutputUnitStop (audioUnit);
  225711. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  225712. "This could have been interrupted by another application or by unplugging a headset",
  225713. @"Resume",
  225714. @"Cancel"))
  225715. {
  225716. isRunning = true;
  225717. propertyChanged (0, 0, 0);
  225718. }
  225719. }*/
  225720. if (inInterruption == kAudioSessionEndInterruption)
  225721. {
  225722. isRunning = true;
  225723. AudioSessionSetActive (true);
  225724. AudioOutputUnitStart (audioUnit);
  225725. }
  225726. }
  225727. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  225728. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  225729. {
  225730. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  225731. }
  225732. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  225733. {
  225734. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  225735. }
  225736. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  225737. {
  225738. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  225739. }
  225740. void resetFormat (const int numChannels)
  225741. {
  225742. memset (&format, 0, sizeof (format));
  225743. format.mFormatID = kAudioFormatLinearPCM;
  225744. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  225745. format.mBitsPerChannel = 8 * sizeof (short);
  225746. format.mChannelsPerFrame = 2;
  225747. format.mFramesPerPacket = 1;
  225748. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  225749. }
  225750. bool createAudioUnit()
  225751. {
  225752. if (audioUnit != 0)
  225753. {
  225754. AudioComponentInstanceDispose (audioUnit);
  225755. audioUnit = 0;
  225756. }
  225757. resetFormat (2);
  225758. AudioComponentDescription desc;
  225759. desc.componentType = kAudioUnitType_Output;
  225760. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  225761. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  225762. desc.componentFlags = 0;
  225763. desc.componentFlagsMask = 0;
  225764. AudioComponent comp = AudioComponentFindNext (0, &desc);
  225765. AudioComponentInstanceNew (comp, &audioUnit);
  225766. if (audioUnit == 0)
  225767. return false;
  225768. const UInt32 one = 1;
  225769. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  225770. AudioChannelLayout layout;
  225771. layout.mChannelBitmap = 0;
  225772. layout.mNumberChannelDescriptions = 0;
  225773. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  225774. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  225775. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  225776. AURenderCallbackStruct inputProc;
  225777. inputProc.inputProc = processStatic;
  225778. inputProc.inputProcRefCon = this;
  225779. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  225780. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  225781. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  225782. AudioUnitInitialize (audioUnit);
  225783. return true;
  225784. }
  225785. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  225786. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  225787. static void fixAudioRouteIfSetToReceiver()
  225788. {
  225789. CFStringRef audioRoute = 0;
  225790. UInt32 propertySize = sizeof (audioRoute);
  225791. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  225792. {
  225793. NSString* route = (NSString*) audioRoute;
  225794. //DBG ("audio route: " + nsStringToJuce (route));
  225795. if ([route hasPrefix: @"Receiver"])
  225796. {
  225797. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  225798. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  225799. }
  225800. CFRelease (audioRoute);
  225801. }
  225802. }
  225803. IPhoneAudioIODevice (const IPhoneAudioIODevice&);
  225804. IPhoneAudioIODevice& operator= (const IPhoneAudioIODevice&);
  225805. };
  225806. class IPhoneAudioIODeviceType : public AudioIODeviceType
  225807. {
  225808. public:
  225809. IPhoneAudioIODeviceType()
  225810. : AudioIODeviceType ("iPhone Audio")
  225811. {
  225812. }
  225813. ~IPhoneAudioIODeviceType()
  225814. {
  225815. }
  225816. void scanForDevices()
  225817. {
  225818. }
  225819. const StringArray getDeviceNames (bool wantInputNames) const
  225820. {
  225821. StringArray s;
  225822. s.add ("iPhone Audio");
  225823. return s;
  225824. }
  225825. int getDefaultDeviceIndex (bool forInput) const
  225826. {
  225827. return 0;
  225828. }
  225829. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  225830. {
  225831. return device != 0 ? 0 : -1;
  225832. }
  225833. bool hasSeparateInputsAndOutputs() const { return false; }
  225834. AudioIODevice* createDevice (const String& outputDeviceName,
  225835. const String& inputDeviceName)
  225836. {
  225837. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  225838. {
  225839. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  225840. : inputDeviceName);
  225841. }
  225842. return 0;
  225843. }
  225844. juce_UseDebuggingNewOperator
  225845. private:
  225846. IPhoneAudioIODeviceType (const IPhoneAudioIODeviceType&);
  225847. IPhoneAudioIODeviceType& operator= (const IPhoneAudioIODeviceType&);
  225848. };
  225849. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  225850. {
  225851. return new IPhoneAudioIODeviceType();
  225852. }
  225853. #endif
  225854. /*** End of inlined file: juce_iphone_Audio.cpp ***/
  225855. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  225856. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225857. // compiled on its own).
  225858. #if JUCE_INCLUDED_FILE
  225859. #if JUCE_MAC
  225860. #undef log
  225861. #define log(a) Logger::writeToLog(a)
  225862. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  225863. {
  225864. if (err == noErr)
  225865. return true;
  225866. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  225867. jassertfalse
  225868. return false;
  225869. }
  225870. #undef OK
  225871. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  225872. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  225873. {
  225874. String result;
  225875. CFStringRef str = 0;
  225876. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  225877. if (str != 0)
  225878. {
  225879. result = PlatformUtilities::cfStringToJuceString (str);
  225880. CFRelease (str);
  225881. str = 0;
  225882. }
  225883. MIDIEntityRef entity = 0;
  225884. MIDIEndpointGetEntity (endpoint, &entity);
  225885. if (entity == 0)
  225886. return result; // probably virtual
  225887. if (result.isEmpty())
  225888. {
  225889. // endpoint name has zero length - try the entity
  225890. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  225891. if (str != 0)
  225892. {
  225893. result += PlatformUtilities::cfStringToJuceString (str);
  225894. CFRelease (str);
  225895. str = 0;
  225896. }
  225897. }
  225898. // now consider the device's name
  225899. MIDIDeviceRef device = 0;
  225900. MIDIEntityGetDevice (entity, &device);
  225901. if (device == 0)
  225902. return result;
  225903. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  225904. if (str != 0)
  225905. {
  225906. const String s (PlatformUtilities::cfStringToJuceString (str));
  225907. CFRelease (str);
  225908. // if an external device has only one entity, throw away
  225909. // the endpoint name and just use the device name
  225910. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  225911. {
  225912. result = s;
  225913. }
  225914. else if (! result.startsWithIgnoreCase (s))
  225915. {
  225916. // prepend the device name to the entity name
  225917. result = (s + " " + result).trimEnd();
  225918. }
  225919. }
  225920. return result;
  225921. }
  225922. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  225923. {
  225924. String result;
  225925. // Does the endpoint have connections?
  225926. CFDataRef connections = 0;
  225927. int numConnections = 0;
  225928. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  225929. if (connections != 0)
  225930. {
  225931. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  225932. if (numConnections > 0)
  225933. {
  225934. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  225935. for (int i = 0; i < numConnections; ++i, ++pid)
  225936. {
  225937. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  225938. MIDIObjectRef connObject;
  225939. MIDIObjectType connObjectType;
  225940. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  225941. if (err == noErr)
  225942. {
  225943. String s;
  225944. if (connObjectType == kMIDIObjectType_ExternalSource
  225945. || connObjectType == kMIDIObjectType_ExternalDestination)
  225946. {
  225947. // Connected to an external device's endpoint (10.3 and later).
  225948. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  225949. }
  225950. else
  225951. {
  225952. // Connected to an external device (10.2) (or something else, catch-all)
  225953. CFStringRef str = 0;
  225954. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  225955. if (str != 0)
  225956. {
  225957. s = PlatformUtilities::cfStringToJuceString (str);
  225958. CFRelease (str);
  225959. }
  225960. }
  225961. if (s.isNotEmpty())
  225962. {
  225963. if (result.isNotEmpty())
  225964. result += ", ";
  225965. result += s;
  225966. }
  225967. }
  225968. }
  225969. }
  225970. CFRelease (connections);
  225971. }
  225972. if (result.isNotEmpty())
  225973. return result;
  225974. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  225975. return getEndpointName (endpoint, false);
  225976. }
  225977. const StringArray MidiOutput::getDevices()
  225978. {
  225979. StringArray s;
  225980. const ItemCount num = MIDIGetNumberOfDestinations();
  225981. for (ItemCount i = 0; i < num; ++i)
  225982. {
  225983. MIDIEndpointRef dest = MIDIGetDestination (i);
  225984. if (dest != 0)
  225985. {
  225986. String name (getConnectedEndpointName (dest));
  225987. if (name.isEmpty())
  225988. name = "<error>";
  225989. s.add (name);
  225990. }
  225991. else
  225992. {
  225993. s.add ("<error>");
  225994. }
  225995. }
  225996. return s;
  225997. }
  225998. int MidiOutput::getDefaultDeviceIndex()
  225999. {
  226000. return 0;
  226001. }
  226002. static MIDIClientRef globalMidiClient;
  226003. static bool hasGlobalClientBeenCreated = false;
  226004. static bool makeSureClientExists()
  226005. {
  226006. if (! hasGlobalClientBeenCreated)
  226007. {
  226008. String name ("JUCE");
  226009. if (JUCEApplication::getInstance() != 0)
  226010. name = JUCEApplication::getInstance()->getApplicationName();
  226011. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  226012. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  226013. CFRelease (appName);
  226014. }
  226015. return hasGlobalClientBeenCreated;
  226016. }
  226017. class MidiPortAndEndpoint
  226018. {
  226019. public:
  226020. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  226021. : port (port_), endPoint (endPoint_)
  226022. {
  226023. }
  226024. ~MidiPortAndEndpoint()
  226025. {
  226026. if (port != 0)
  226027. MIDIPortDispose (port);
  226028. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  226029. MIDIEndpointDispose (endPoint);
  226030. }
  226031. MIDIPortRef port;
  226032. MIDIEndpointRef endPoint;
  226033. };
  226034. MidiOutput* MidiOutput::openDevice (int index)
  226035. {
  226036. MidiOutput* mo = 0;
  226037. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  226038. {
  226039. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  226040. CFStringRef pname;
  226041. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  226042. {
  226043. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  226044. if (makeSureClientExists())
  226045. {
  226046. MIDIPortRef port;
  226047. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  226048. {
  226049. mo = new MidiOutput();
  226050. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  226051. }
  226052. }
  226053. CFRelease (pname);
  226054. }
  226055. }
  226056. return mo;
  226057. }
  226058. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  226059. {
  226060. MidiOutput* mo = 0;
  226061. if (makeSureClientExists())
  226062. {
  226063. MIDIEndpointRef endPoint;
  226064. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  226065. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  226066. {
  226067. mo = new MidiOutput();
  226068. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  226069. }
  226070. CFRelease (name);
  226071. }
  226072. return mo;
  226073. }
  226074. MidiOutput::~MidiOutput()
  226075. {
  226076. delete (MidiPortAndEndpoint*) internal;
  226077. }
  226078. void MidiOutput::reset()
  226079. {
  226080. }
  226081. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  226082. {
  226083. return false;
  226084. }
  226085. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  226086. {
  226087. }
  226088. void MidiOutput::sendMessageNow (const MidiMessage& message)
  226089. {
  226090. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*) internal;
  226091. if (message.isSysEx())
  226092. {
  226093. const int maxPacketSize = 256;
  226094. int pos = 0, bytesLeft = message.getRawDataSize();
  226095. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  226096. HeapBlock <MIDIPacketList> packets;
  226097. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  226098. packets->numPackets = numPackets;
  226099. MIDIPacket* p = packets->packet;
  226100. for (int i = 0; i < numPackets; ++i)
  226101. {
  226102. p->timeStamp = 0;
  226103. p->length = jmin (maxPacketSize, bytesLeft);
  226104. memcpy (p->data, message.getRawData() + pos, p->length);
  226105. pos += p->length;
  226106. bytesLeft -= p->length;
  226107. p = MIDIPacketNext (p);
  226108. }
  226109. if (mpe->port != 0)
  226110. MIDISend (mpe->port, mpe->endPoint, packets);
  226111. else
  226112. MIDIReceived (mpe->endPoint, packets);
  226113. }
  226114. else
  226115. {
  226116. MIDIPacketList packets;
  226117. packets.numPackets = 1;
  226118. packets.packet[0].timeStamp = 0;
  226119. packets.packet[0].length = message.getRawDataSize();
  226120. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  226121. if (mpe->port != 0)
  226122. MIDISend (mpe->port, mpe->endPoint, &packets);
  226123. else
  226124. MIDIReceived (mpe->endPoint, &packets);
  226125. }
  226126. }
  226127. const StringArray MidiInput::getDevices()
  226128. {
  226129. StringArray s;
  226130. const ItemCount num = MIDIGetNumberOfSources();
  226131. for (ItemCount i = 0; i < num; ++i)
  226132. {
  226133. MIDIEndpointRef source = MIDIGetSource (i);
  226134. if (source != 0)
  226135. {
  226136. String name (getConnectedEndpointName (source));
  226137. if (name.isEmpty())
  226138. name = "<error>";
  226139. s.add (name);
  226140. }
  226141. else
  226142. {
  226143. s.add ("<error>");
  226144. }
  226145. }
  226146. return s;
  226147. }
  226148. int MidiInput::getDefaultDeviceIndex()
  226149. {
  226150. return 0;
  226151. }
  226152. struct MidiPortAndCallback
  226153. {
  226154. MidiInput* input;
  226155. MidiPortAndEndpoint* portAndEndpoint;
  226156. MidiInputCallback* callback;
  226157. MemoryBlock pendingData;
  226158. int pendingBytes;
  226159. double pendingDataTime;
  226160. bool active;
  226161. void processSysex (const uint8*& d, int& size, const double time)
  226162. {
  226163. if (*d == 0xf0)
  226164. {
  226165. pendingBytes = 0;
  226166. pendingDataTime = time;
  226167. }
  226168. pendingData.ensureSize (pendingBytes + size, false);
  226169. uint8* totalMessage = (uint8*) pendingData.getData();
  226170. uint8* dest = totalMessage + pendingBytes;
  226171. while (size > 0)
  226172. {
  226173. if (pendingBytes > 0 && *d >= 0x80)
  226174. {
  226175. if (*d >= 0xfa || *d == 0xf8)
  226176. {
  226177. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  226178. ++d;
  226179. --size;
  226180. }
  226181. else
  226182. {
  226183. if (*d == 0xf7)
  226184. {
  226185. *dest++ = *d++;
  226186. pendingBytes++;
  226187. --size;
  226188. }
  226189. break;
  226190. }
  226191. }
  226192. else
  226193. {
  226194. *dest++ = *d++;
  226195. pendingBytes++;
  226196. --size;
  226197. }
  226198. }
  226199. if (totalMessage [pendingBytes - 1] == 0xf7)
  226200. {
  226201. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  226202. pendingBytes = 0;
  226203. }
  226204. else
  226205. {
  226206. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  226207. }
  226208. }
  226209. };
  226210. namespace CoreMidiCallbacks
  226211. {
  226212. static CriticalSection callbackLock;
  226213. static VoidArray activeCallbacks;
  226214. }
  226215. static void midiInputProc (const MIDIPacketList* pktlist,
  226216. void* readProcRefCon,
  226217. void* /*srcConnRefCon*/)
  226218. {
  226219. double time = Time::getMillisecondCounterHiRes() * 0.001;
  226220. const double originalTime = time;
  226221. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  226222. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  226223. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  226224. {
  226225. const MIDIPacket* packet = &pktlist->packet[0];
  226226. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  226227. {
  226228. const uint8* d = (const uint8*) (packet->data);
  226229. int size = packet->length;
  226230. while (size > 0)
  226231. {
  226232. time = originalTime;
  226233. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  226234. {
  226235. mpc->processSysex (d, size, time);
  226236. }
  226237. else
  226238. {
  226239. int used = 0;
  226240. const MidiMessage m (d, size, used, 0, time);
  226241. if (used <= 0)
  226242. {
  226243. jassertfalse // malformed midi message
  226244. break;
  226245. }
  226246. else
  226247. {
  226248. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  226249. }
  226250. size -= used;
  226251. d += used;
  226252. }
  226253. }
  226254. packet = MIDIPacketNext (packet);
  226255. }
  226256. }
  226257. }
  226258. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  226259. {
  226260. MidiInput* mi = 0;
  226261. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  226262. {
  226263. MIDIEndpointRef endPoint = MIDIGetSource (index);
  226264. if (endPoint != 0)
  226265. {
  226266. CFStringRef pname;
  226267. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  226268. {
  226269. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  226270. if (makeSureClientExists())
  226271. {
  226272. MIDIPortRef port;
  226273. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  226274. mpc->active = false;
  226275. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  226276. {
  226277. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  226278. {
  226279. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  226280. mpc->callback = callback;
  226281. mpc->pendingBytes = 0;
  226282. mpc->pendingData.ensureSize (128);
  226283. mi = new MidiInput (getDevices() [index]);
  226284. mpc->input = mi;
  226285. mi->internal = mpc;
  226286. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  226287. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  226288. }
  226289. else
  226290. {
  226291. OK (MIDIPortDispose (port));
  226292. }
  226293. }
  226294. }
  226295. }
  226296. CFRelease (pname);
  226297. }
  226298. }
  226299. return mi;
  226300. }
  226301. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  226302. {
  226303. MidiInput* mi = 0;
  226304. if (makeSureClientExists())
  226305. {
  226306. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  226307. mpc->active = false;
  226308. MIDIEndpointRef endPoint;
  226309. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  226310. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  226311. {
  226312. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  226313. mpc->callback = callback;
  226314. mpc->pendingBytes = 0;
  226315. mpc->pendingData.ensureSize (128);
  226316. mi = new MidiInput (deviceName);
  226317. mpc->input = mi;
  226318. mi->internal = mpc;
  226319. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  226320. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  226321. }
  226322. CFRelease (name);
  226323. }
  226324. return mi;
  226325. }
  226326. MidiInput::MidiInput (const String& name_)
  226327. : name (name_)
  226328. {
  226329. }
  226330. MidiInput::~MidiInput()
  226331. {
  226332. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) internal;
  226333. mpc->active = false;
  226334. {
  226335. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  226336. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  226337. }
  226338. if (mpc->portAndEndpoint->port != 0)
  226339. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  226340. delete mpc->portAndEndpoint;
  226341. delete mpc;
  226342. }
  226343. void MidiInput::start()
  226344. {
  226345. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  226346. ((MidiPortAndCallback*) internal)->active = true;
  226347. }
  226348. void MidiInput::stop()
  226349. {
  226350. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  226351. ((MidiPortAndCallback*) internal)->active = false;
  226352. }
  226353. #undef log
  226354. #else
  226355. MidiOutput::~MidiOutput()
  226356. {
  226357. }
  226358. void MidiOutput::reset()
  226359. {
  226360. }
  226361. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  226362. {
  226363. return false;
  226364. }
  226365. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  226366. {
  226367. }
  226368. void MidiOutput::sendMessageNow (const MidiMessage& message)
  226369. {
  226370. }
  226371. const StringArray MidiOutput::getDevices()
  226372. {
  226373. return StringArray();
  226374. }
  226375. MidiOutput* MidiOutput::openDevice (int index)
  226376. {
  226377. return 0;
  226378. }
  226379. const StringArray MidiInput::getDevices()
  226380. {
  226381. return StringArray();
  226382. }
  226383. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  226384. {
  226385. return 0;
  226386. }
  226387. #endif
  226388. #endif
  226389. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  226390. #else
  226391. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  226392. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226393. // compiled on its own).
  226394. #if JUCE_INCLUDED_FILE
  226395. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226396. #define SUPPORT_10_4_FONTS 1
  226397. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  226398. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226399. #define SUPPORT_ONLY_10_4_FONTS 1
  226400. #endif
  226401. END_JUCE_NAMESPACE
  226402. @interface NSFont (PrivateHack)
  226403. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  226404. @end
  226405. BEGIN_JUCE_NAMESPACE
  226406. #endif
  226407. class MacTypeface : public Typeface
  226408. {
  226409. public:
  226410. MacTypeface (const Font& font)
  226411. : Typeface (font.getTypefaceName())
  226412. {
  226413. const ScopedAutoReleasePool pool;
  226414. renderingTransform = CGAffineTransformIdentity;
  226415. bool needsItalicTransform = false;
  226416. #if JUCE_IPHONE
  226417. NSString* fontName = juceStringToNS (font.getTypefaceName());
  226418. if (font.isItalic() || font.isBold())
  226419. {
  226420. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  226421. for (NSString* i in familyFonts)
  226422. {
  226423. const String fn (nsStringToJuce (i));
  226424. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  226425. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  226426. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  226427. || afterDash.containsIgnoreCase ("italic")
  226428. || fn.endsWithIgnoreCase ("oblique")
  226429. || fn.endsWithIgnoreCase ("italic");
  226430. if (probablyBold == font.isBold()
  226431. && probablyItalic == font.isItalic())
  226432. {
  226433. fontName = i;
  226434. needsItalicTransform = false;
  226435. break;
  226436. }
  226437. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  226438. {
  226439. fontName = i;
  226440. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  226441. }
  226442. }
  226443. if (needsItalicTransform)
  226444. renderingTransform.c = 0.15f;
  226445. }
  226446. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  226447. const int ascender = abs (CGFontGetAscent (fontRef));
  226448. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  226449. ascent = ascender / totalHeight;
  226450. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226451. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  226452. #else
  226453. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  226454. if (font.isItalic())
  226455. {
  226456. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  226457. toHaveTrait: NSItalicFontMask];
  226458. if (newFont == nsFont)
  226459. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  226460. nsFont = newFont;
  226461. }
  226462. if (font.isBold())
  226463. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  226464. [nsFont retain];
  226465. ascent = std::abs ((float) [nsFont ascender]);
  226466. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  226467. ascent /= totalSize;
  226468. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  226469. if (needsItalicTransform)
  226470. {
  226471. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  226472. renderingTransform.c = 0.15f;
  226473. }
  226474. #if SUPPORT_ONLY_10_4_FONTS
  226475. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226476. if (atsFont == 0)
  226477. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226478. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226479. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226480. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226481. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226482. #else
  226483. #if SUPPORT_10_4_FONTS
  226484. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226485. {
  226486. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226487. if (atsFont == 0)
  226488. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226489. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226490. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226491. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226492. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226493. }
  226494. else
  226495. #endif
  226496. {
  226497. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  226498. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  226499. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226500. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  226501. }
  226502. #endif
  226503. #endif
  226504. }
  226505. ~MacTypeface()
  226506. {
  226507. #if ! JUCE_IPHONE
  226508. [nsFont release];
  226509. #endif
  226510. if (fontRef != 0)
  226511. CGFontRelease (fontRef);
  226512. }
  226513. float getAscent() const
  226514. {
  226515. return ascent;
  226516. }
  226517. float getDescent() const
  226518. {
  226519. return 1.0f - ascent;
  226520. }
  226521. float getStringWidth (const String& text)
  226522. {
  226523. if (fontRef == 0 || text.isEmpty())
  226524. return 0;
  226525. const int length = text.length();
  226526. HeapBlock <CGGlyph> glyphs;
  226527. createGlyphsForString (text, length, glyphs);
  226528. float x = 0;
  226529. #if SUPPORT_ONLY_10_4_FONTS
  226530. HeapBlock <NSSize> advances (length);
  226531. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226532. for (int i = 0; i < length; ++i)
  226533. x += advances[i].width;
  226534. #else
  226535. #if SUPPORT_10_4_FONTS
  226536. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226537. {
  226538. HeapBlock <NSSize> advances (length);
  226539. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  226540. for (int i = 0; i < length; ++i)
  226541. x += advances[i].width;
  226542. }
  226543. else
  226544. #endif
  226545. {
  226546. HeapBlock <int> advances (length);
  226547. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226548. for (int i = 0; i < length; ++i)
  226549. x += advances[i];
  226550. }
  226551. #endif
  226552. return x * unitsToHeightScaleFactor;
  226553. }
  226554. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  226555. {
  226556. xOffsets.add (0);
  226557. if (fontRef == 0 || text.isEmpty())
  226558. return;
  226559. const int length = text.length();
  226560. HeapBlock <CGGlyph> glyphs;
  226561. createGlyphsForString (text, length, glyphs);
  226562. #if SUPPORT_ONLY_10_4_FONTS
  226563. HeapBlock <NSSize> advances (length);
  226564. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226565. int x = 0;
  226566. for (int i = 0; i < length; ++i)
  226567. {
  226568. x += advances[i].width;
  226569. xOffsets.add (x * unitsToHeightScaleFactor);
  226570. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  226571. }
  226572. #else
  226573. #if SUPPORT_10_4_FONTS
  226574. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226575. {
  226576. HeapBlock <NSSize> advances (length);
  226577. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226578. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  226579. float x = 0;
  226580. for (int i = 0; i < length; ++i)
  226581. {
  226582. x += advances[i].width;
  226583. xOffsets.add (x * unitsToHeightScaleFactor);
  226584. resultGlyphs.add (nsGlyphs[i]);
  226585. }
  226586. }
  226587. else
  226588. #endif
  226589. {
  226590. HeapBlock <int> advances (length);
  226591. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226592. {
  226593. int x = 0;
  226594. for (int i = 0; i < length; ++i)
  226595. {
  226596. x += advances [i];
  226597. xOffsets.add (x * unitsToHeightScaleFactor);
  226598. resultGlyphs.add (glyphs[i]);
  226599. }
  226600. }
  226601. }
  226602. #endif
  226603. }
  226604. bool getOutlineForGlyph (int glyphNumber, Path& path)
  226605. {
  226606. #if JUCE_IPHONE
  226607. return false;
  226608. #else
  226609. if (nsFont == 0)
  226610. return false;
  226611. // we might need to apply a transform to the path, so it mustn't have anything else in it
  226612. jassert (path.isEmpty());
  226613. const ScopedAutoReleasePool pool;
  226614. NSBezierPath* bez = [NSBezierPath bezierPath];
  226615. [bez moveToPoint: NSMakePoint (0, 0)];
  226616. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  226617. inFont: nsFont];
  226618. for (int i = 0; i < [bez elementCount]; ++i)
  226619. {
  226620. NSPoint p[3];
  226621. switch ([bez elementAtIndex: i associatedPoints: p])
  226622. {
  226623. case NSMoveToBezierPathElement:
  226624. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  226625. break;
  226626. case NSLineToBezierPathElement:
  226627. path.lineTo ((float) p[0].x, (float) -p[0].y);
  226628. break;
  226629. case NSCurveToBezierPathElement:
  226630. 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);
  226631. break;
  226632. case NSClosePathBezierPathElement:
  226633. path.closeSubPath();
  226634. break;
  226635. default:
  226636. jassertfalse
  226637. break;
  226638. }
  226639. }
  226640. path.applyTransform (pathTransform);
  226641. return true;
  226642. #endif
  226643. }
  226644. juce_UseDebuggingNewOperator
  226645. CGFontRef fontRef;
  226646. float fontHeightToCGSizeFactor;
  226647. CGAffineTransform renderingTransform;
  226648. private:
  226649. float ascent, unitsToHeightScaleFactor;
  226650. #if JUCE_IPHONE
  226651. #else
  226652. NSFont* nsFont;
  226653. AffineTransform pathTransform;
  226654. #endif
  226655. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  226656. {
  226657. #if SUPPORT_10_4_FONTS
  226658. #if ! SUPPORT_ONLY_10_4_FONTS
  226659. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226660. #endif
  226661. {
  226662. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  226663. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226664. for (int i = 0; i < length; ++i)
  226665. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  226666. return;
  226667. }
  226668. #endif
  226669. #if ! SUPPORT_ONLY_10_4_FONTS
  226670. if (charToGlyphMapper == 0)
  226671. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  226672. glyphs.malloc (length);
  226673. for (int i = 0; i < length; ++i)
  226674. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  226675. #endif
  226676. }
  226677. #if ! SUPPORT_ONLY_10_4_FONTS
  226678. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  226679. class CharToGlyphMapper
  226680. {
  226681. public:
  226682. CharToGlyphMapper (CGFontRef fontRef)
  226683. : segCount (0), endCode (0), startCode (0), idDelta (0),
  226684. idRangeOffset (0), glyphIndexes (0)
  226685. {
  226686. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  226687. if (cmapTable != 0)
  226688. {
  226689. const int numSubtables = getValue16 (cmapTable, 2);
  226690. for (int i = 0; i < numSubtables; ++i)
  226691. {
  226692. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  226693. {
  226694. const int offset = getValue32 (cmapTable, i * 8 + 8);
  226695. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  226696. {
  226697. const int length = getValue16 (cmapTable, offset + 2);
  226698. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  226699. segCount = segCountX2 / 2;
  226700. const int endCodeOffset = offset + 14;
  226701. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  226702. const int idDeltaOffset = startCodeOffset + segCountX2;
  226703. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  226704. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  226705. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  226706. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  226707. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  226708. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  226709. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  226710. }
  226711. break;
  226712. }
  226713. }
  226714. CFRelease (cmapTable);
  226715. }
  226716. }
  226717. ~CharToGlyphMapper()
  226718. {
  226719. if (endCode != 0)
  226720. {
  226721. CFRelease (endCode);
  226722. CFRelease (startCode);
  226723. CFRelease (idDelta);
  226724. CFRelease (idRangeOffset);
  226725. CFRelease (glyphIndexes);
  226726. }
  226727. }
  226728. int getGlyphForCharacter (const juce_wchar c) const
  226729. {
  226730. for (int i = 0; i < segCount; ++i)
  226731. {
  226732. if (getValue16 (endCode, i * 2) >= c)
  226733. {
  226734. const int start = getValue16 (startCode, i * 2);
  226735. if (start > c)
  226736. break;
  226737. const int delta = getValue16 (idDelta, i * 2);
  226738. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  226739. if (rangeOffset == 0)
  226740. return delta + c;
  226741. else
  226742. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  226743. }
  226744. }
  226745. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  226746. return jmax (-1, c - 29);
  226747. }
  226748. private:
  226749. int segCount;
  226750. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  226751. static uint16 getValue16 (CFDataRef data, const int index)
  226752. {
  226753. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  226754. }
  226755. static uint32 getValue32 (CFDataRef data, const int index)
  226756. {
  226757. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  226758. }
  226759. };
  226760. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  226761. #endif
  226762. MacTypeface (const MacTypeface&);
  226763. MacTypeface& operator= (const MacTypeface&);
  226764. };
  226765. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  226766. {
  226767. return new MacTypeface (font);
  226768. }
  226769. const StringArray Font::findAllTypefaceNames()
  226770. {
  226771. StringArray names;
  226772. const ScopedAutoReleasePool pool;
  226773. #if JUCE_IPHONE
  226774. NSArray* fonts = [UIFont familyNames];
  226775. #else
  226776. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  226777. #endif
  226778. for (unsigned int i = 0; i < [fonts count]; ++i)
  226779. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  226780. names.sort (true);
  226781. return names;
  226782. }
  226783. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  226784. {
  226785. #if JUCE_IPHONE
  226786. defaultSans = "Helvetica";
  226787. defaultSerif = "Times New Roman";
  226788. defaultFixed = "Courier New";
  226789. #else
  226790. defaultSans = "Lucida Grande";
  226791. defaultSerif = "Times New Roman";
  226792. defaultFixed = "Monaco";
  226793. #endif
  226794. }
  226795. #endif
  226796. /*** End of inlined file: juce_mac_Fonts.mm ***/
  226797. // (must go before juce_mac_CoreGraphicsContext.mm)
  226798. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226799. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226800. // compiled on its own).
  226801. #if JUCE_INCLUDED_FILE
  226802. class CoreGraphicsImage : public Image
  226803. {
  226804. public:
  226805. CoreGraphicsImage (const PixelFormat format_,
  226806. const int imageWidth_,
  226807. const int imageHeight_,
  226808. const bool clearImage)
  226809. : Image (format_, imageWidth_, imageHeight_, clearImage)
  226810. {
  226811. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  226812. : CGColorSpaceCreateDeviceRGB();
  226813. context = CGBitmapContextCreate (imageData, imageWidth, imageHeight, 8, lineStride,
  226814. colourSpace, getCGImageFlags (*this));
  226815. CGColorSpaceRelease (colourSpace);
  226816. }
  226817. ~CoreGraphicsImage()
  226818. {
  226819. CGContextRelease (context);
  226820. }
  226821. LowLevelGraphicsContext* createLowLevelContext();
  226822. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  226823. {
  226824. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (&juceImage);
  226825. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  226826. {
  226827. return CGBitmapContextCreateImage (nativeImage->context);
  226828. }
  226829. else
  226830. {
  226831. const Image::BitmapData srcData (juceImage, 0, 0, juceImage.getWidth(), juceImage.getHeight());
  226832. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  226833. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  226834. 8, srcData.pixelStride * 8, srcData.lineStride,
  226835. colourSpace, getCGImageFlags (juceImage), provider,
  226836. 0, true, kCGRenderingIntentDefault);
  226837. CGDataProviderRelease (provider);
  226838. return imageRef;
  226839. }
  226840. }
  226841. #if JUCE_MAC
  226842. static NSImage* createNSImage (const Image& image)
  226843. {
  226844. const ScopedAutoReleasePool pool;
  226845. NSImage* im = [[NSImage alloc] init];
  226846. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  226847. [im lockFocus];
  226848. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  226849. CGImageRef imageRef = createImage (image, false, colourSpace);
  226850. CGColorSpaceRelease (colourSpace);
  226851. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  226852. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  226853. CGImageRelease (imageRef);
  226854. [im unlockFocus];
  226855. return im;
  226856. }
  226857. #endif
  226858. CGContextRef context;
  226859. private:
  226860. static CGBitmapInfo getCGImageFlags (const Image& image)
  226861. {
  226862. #if JUCE_BIG_ENDIAN
  226863. return image.getFormat() == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  226864. #else
  226865. return image.getFormat() == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  226866. #endif
  226867. }
  226868. };
  226869. Image* Image::createNativeImage (const PixelFormat format, const int imageWidth, const int imageHeight, const bool clearImage)
  226870. {
  226871. #if USE_COREGRAPHICS_RENDERING
  226872. return new CoreGraphicsImage (format == RGB ? ARGB : format, imageWidth, imageHeight, clearImage);
  226873. #else
  226874. return new Image (format, imageWidth, imageHeight, clearImage);
  226875. #endif
  226876. }
  226877. class CoreGraphicsContext : public LowLevelGraphicsContext
  226878. {
  226879. public:
  226880. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  226881. : context (context_),
  226882. flipHeight (flipHeight_),
  226883. state (new SavedState()),
  226884. numGradientLookupEntries (0)
  226885. {
  226886. CGContextRetain (context);
  226887. CGContextSaveGState(context);
  226888. CGContextSetShouldSmoothFonts (context, true);
  226889. CGContextSetShouldAntialias (context, true);
  226890. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226891. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  226892. greyColourSpace = CGColorSpaceCreateDeviceGray();
  226893. gradientCallbacks.version = 0;
  226894. gradientCallbacks.evaluate = gradientCallback;
  226895. gradientCallbacks.releaseInfo = 0;
  226896. setFont (Font());
  226897. }
  226898. ~CoreGraphicsContext()
  226899. {
  226900. CGContextRestoreGState (context);
  226901. CGContextRelease (context);
  226902. CGColorSpaceRelease (rgbColourSpace);
  226903. CGColorSpaceRelease (greyColourSpace);
  226904. }
  226905. bool isVectorDevice() const { return false; }
  226906. void setOrigin (int x, int y)
  226907. {
  226908. CGContextTranslateCTM (context, x, -y);
  226909. }
  226910. bool clipToRectangle (const Rectangle<int>& r)
  226911. {
  226912. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  226913. return ! isClipEmpty();
  226914. }
  226915. bool clipToRectangleList (const RectangleList& clipRegion)
  226916. {
  226917. if (clipRegion.isEmpty())
  226918. {
  226919. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  226920. return false;
  226921. }
  226922. else
  226923. {
  226924. const int numRects = clipRegion.getNumRectangles();
  226925. HeapBlock <CGRect> rects (numRects);
  226926. for (int i = 0; i < numRects; ++i)
  226927. {
  226928. const Rectangle<int>& r = clipRegion.getRectangle(i);
  226929. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  226930. }
  226931. CGContextClipToRects (context, rects, numRects);
  226932. return ! isClipEmpty();
  226933. }
  226934. }
  226935. void excludeClipRectangle (const Rectangle<int>& r)
  226936. {
  226937. RectangleList remaining (getClipBounds());
  226938. remaining.subtract (r);
  226939. clipToRectangleList (remaining);
  226940. }
  226941. void clipToPath (const Path& path, const AffineTransform& transform)
  226942. {
  226943. createPath (path, transform);
  226944. CGContextClip (context);
  226945. }
  226946. void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform)
  226947. {
  226948. if (! transform.isSingularity())
  226949. {
  226950. ScopedPointer<Image> imageToDelete;
  226951. const Image* singleChannelImage = &sourceImage;
  226952. if (sourceImage.getFormat() != Image::SingleChannel)
  226953. {
  226954. imageToDelete = sourceImage.createCopyOfAlphaChannel();
  226955. singleChannelImage = imageToDelete;
  226956. }
  226957. CGImageRef image = CoreGraphicsImage::createImage (*singleChannelImage, true, greyColourSpace);
  226958. flip();
  226959. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  226960. applyTransform (t);
  226961. CGRect r = CGRectMake (srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  226962. CGContextClipToMask (context, r, image);
  226963. applyTransform (t.inverted());
  226964. flip();
  226965. CGImageRelease (image);
  226966. }
  226967. }
  226968. bool clipRegionIntersects (const Rectangle<int>& r)
  226969. {
  226970. return getClipBounds().intersects (r);
  226971. }
  226972. const Rectangle<int> getClipBounds() const
  226973. {
  226974. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226975. return Rectangle<int> (roundToInt (bounds.origin.x),
  226976. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  226977. roundToInt (bounds.size.width),
  226978. roundToInt (bounds.size.height));
  226979. }
  226980. bool isClipEmpty() const
  226981. {
  226982. return CGRectIsEmpty (CGContextGetClipBoundingBox (context));
  226983. }
  226984. void saveState()
  226985. {
  226986. CGContextSaveGState (context);
  226987. stateStack.add (new SavedState (*state));
  226988. }
  226989. void restoreState()
  226990. {
  226991. CGContextRestoreGState (context);
  226992. SavedState* const top = stateStack.getLast();
  226993. if (top != 0)
  226994. {
  226995. state = top;
  226996. stateStack.removeLast (1, false);
  226997. }
  226998. else
  226999. {
  227000. jassertfalse // trying to pop with an empty stack!
  227001. }
  227002. }
  227003. void setFill (const FillType& fillType)
  227004. {
  227005. state->fillType = fillType;
  227006. if (fillType.isColour())
  227007. {
  227008. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  227009. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  227010. CGContextSetAlpha (context, 1.0f);
  227011. }
  227012. }
  227013. void setOpacity (float newOpacity)
  227014. {
  227015. state->fillType.setOpacity (newOpacity);
  227016. setFill (state->fillType);
  227017. }
  227018. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  227019. {
  227020. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  227021. ? kCGInterpolationLow
  227022. : kCGInterpolationHigh);
  227023. }
  227024. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  227025. {
  227026. CGRect cgRect = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  227027. if (replaceExistingContents)
  227028. {
  227029. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  227030. CGContextClearRect (context, cgRect);
  227031. #else
  227032. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  227033. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  227034. CGContextClearRect (context, cgRect);
  227035. else
  227036. #endif
  227037. CGContextSetBlendMode (context, kCGBlendModeCopy);
  227038. #endif
  227039. fillRect (r, false);
  227040. CGContextSetBlendMode (context, kCGBlendModeNormal);
  227041. }
  227042. else
  227043. {
  227044. if (state->fillType.isColour())
  227045. {
  227046. CGContextFillRect (context, cgRect);
  227047. }
  227048. else if (state->fillType.isGradient())
  227049. {
  227050. CGContextSaveGState (context);
  227051. CGContextClipToRect (context, cgRect);
  227052. drawGradient();
  227053. CGContextRestoreGState (context);
  227054. }
  227055. else
  227056. {
  227057. CGContextSaveGState (context);
  227058. CGContextClipToRect (context, cgRect);
  227059. drawImage (*(state->fillType.image), state->fillType.image->getBounds(), state->fillType.transform, true);
  227060. CGContextRestoreGState (context);
  227061. }
  227062. }
  227063. }
  227064. void fillPath (const Path& path, const AffineTransform& transform)
  227065. {
  227066. CGContextSaveGState (context);
  227067. if (state->fillType.isColour())
  227068. {
  227069. flip();
  227070. applyTransform (transform);
  227071. createPath (path);
  227072. if (path.isUsingNonZeroWinding())
  227073. CGContextFillPath (context);
  227074. else
  227075. CGContextEOFillPath (context);
  227076. }
  227077. else
  227078. {
  227079. createPath (path, transform);
  227080. if (path.isUsingNonZeroWinding())
  227081. CGContextClip (context);
  227082. else
  227083. CGContextEOClip (context);
  227084. if (state->fillType.isGradient())
  227085. drawGradient();
  227086. else
  227087. drawImage (*(state->fillType.image), state->fillType.image->getBounds(), state->fillType.transform, true);
  227088. }
  227089. CGContextRestoreGState (context);
  227090. }
  227091. void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  227092. const AffineTransform& transform, const bool fillEntireClipAsTiles)
  227093. {
  227094. jassert (sourceImage.getBounds().contains (srcClip));
  227095. CGImageRef fullImage = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  227096. CGImageRef image = fullImage;
  227097. if (srcClip != sourceImage.getBounds())
  227098. {
  227099. image = CGImageCreateWithImageInRect (fullImage, CGRectMake (srcClip.getX(), srcClip.getY(),
  227100. srcClip.getWidth(), srcClip.getHeight()));
  227101. CGImageRelease (fullImage);
  227102. }
  227103. CGContextSaveGState (context);
  227104. CGContextSetAlpha (context, state->fillType.getOpacity());
  227105. flip();
  227106. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, srcClip.getHeight()).followedBy (transform));
  227107. CGRect imageRect = CGRectMake (0, 0, srcClip.getWidth(), srcClip.getHeight());
  227108. if (fillEntireClipAsTiles)
  227109. {
  227110. #if JUCE_IPHONE
  227111. CGContextDrawTiledImage (context, imageRect, image);
  227112. #else
  227113. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  227114. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  227115. // if it's doing a transformation - it's quicker to just draw lots of images manually
  227116. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  227117. CGContextDrawTiledImage (context, imageRect, image);
  227118. else
  227119. #endif
  227120. {
  227121. // Fallback to manually doing a tiled fill on 10.4
  227122. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  227123. const int iw = srcClip.getWidth();
  227124. const int ih = srcClip.getHeight();
  227125. int x = 0, y = 0;
  227126. while (x > clip.origin.x) x -= iw;
  227127. while (y > clip.origin.y) y -= ih;
  227128. const int right = (int) (clip.origin.x + clip.size.width);
  227129. const int bottom = (int) (clip.origin.y + clip.size.height);
  227130. while (y < bottom)
  227131. {
  227132. for (int x2 = x; x2 < right; x2 += iw)
  227133. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  227134. y += ih;
  227135. }
  227136. }
  227137. #endif
  227138. }
  227139. else
  227140. {
  227141. CGContextDrawImage (context, imageRect, image);
  227142. }
  227143. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  227144. CGContextRestoreGState (context);
  227145. }
  227146. void drawLine (const Line<float>& line)
  227147. {
  227148. CGContextSetLineCap (context, kCGLineCapSquare);
  227149. CGContextSetLineWidth (context, 1.0f);
  227150. CGContextSetRGBStrokeColor (context,
  227151. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  227152. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  227153. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  227154. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  227155. CGContextStrokeLineSegments (context, cgLine, 1);
  227156. }
  227157. void drawVerticalLine (const int x, float top, float bottom)
  227158. {
  227159. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  227160. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  227161. #else
  227162. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  227163. // the x co-ord slightly to trick it..
  227164. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  227165. #endif
  227166. }
  227167. void drawHorizontalLine (const int y, float left, float right)
  227168. {
  227169. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  227170. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  227171. #else
  227172. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  227173. // the x co-ord slightly to trick it..
  227174. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  227175. #endif
  227176. }
  227177. void setFont (const Font& newFont)
  227178. {
  227179. if (state->font != newFont)
  227180. {
  227181. state->fontRef = 0;
  227182. state->font = newFont;
  227183. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  227184. if (mf != 0)
  227185. {
  227186. state->fontRef = mf->fontRef;
  227187. CGContextSetFont (context, state->fontRef);
  227188. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  227189. state->fontTransform = mf->renderingTransform;
  227190. state->fontTransform.a *= state->font.getHorizontalScale();
  227191. CGContextSetTextMatrix (context, state->fontTransform);
  227192. }
  227193. }
  227194. }
  227195. const Font getFont()
  227196. {
  227197. return state->font;
  227198. }
  227199. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  227200. {
  227201. if (state->fontRef != 0 && state->fillType.isColour())
  227202. {
  227203. if (transform.isOnlyTranslation())
  227204. {
  227205. CGGlyph g = glyphNumber;
  227206. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  227207. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  227208. }
  227209. else
  227210. {
  227211. CGContextSaveGState (context);
  227212. flip();
  227213. applyTransform (transform);
  227214. CGAffineTransform t = state->fontTransform;
  227215. t.d = -t.d;
  227216. CGContextSetTextMatrix (context, t);
  227217. CGGlyph g = glyphNumber;
  227218. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  227219. CGContextSetTextMatrix (context, state->fontTransform);
  227220. CGContextRestoreGState (context);
  227221. }
  227222. }
  227223. else
  227224. {
  227225. Path p;
  227226. Font& f = state->font;
  227227. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  227228. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  227229. .followedBy (transform));
  227230. }
  227231. }
  227232. private:
  227233. CGContextRef context;
  227234. const CGFloat flipHeight;
  227235. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  227236. CGFunctionCallbacks gradientCallbacks;
  227237. struct SavedState
  227238. {
  227239. SavedState()
  227240. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  227241. {
  227242. }
  227243. SavedState (const SavedState& other)
  227244. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  227245. fontTransform (other.fontTransform)
  227246. {
  227247. }
  227248. ~SavedState()
  227249. {
  227250. }
  227251. FillType fillType;
  227252. Font font;
  227253. CGFontRef fontRef;
  227254. CGAffineTransform fontTransform;
  227255. };
  227256. ScopedPointer <SavedState> state;
  227257. OwnedArray <SavedState> stateStack;
  227258. HeapBlock <PixelARGB> gradientLookupTable;
  227259. int numGradientLookupEntries;
  227260. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  227261. {
  227262. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  227263. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  227264. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  227265. colour.unpremultiply();
  227266. outData[0] = colour.getRed() / 255.0f;
  227267. outData[1] = colour.getGreen() / 255.0f;
  227268. outData[2] = colour.getBlue() / 255.0f;
  227269. outData[3] = colour.getAlpha() / 255.0f;
  227270. }
  227271. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  227272. {
  227273. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  227274. --numGradientLookupEntries;
  227275. CGShadingRef result = 0;
  227276. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  227277. CGPoint p1 (CGPointMake (gradient.x1, gradient.y1));
  227278. if (gradient.isRadial)
  227279. {
  227280. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  227281. p1, hypotf (gradient.x1 - gradient.x2, gradient.y1 - gradient.y2),
  227282. function, true, true);
  227283. }
  227284. else
  227285. {
  227286. result = CGShadingCreateAxial (rgbColourSpace, p1,
  227287. CGPointMake (gradient.x2, gradient.y2),
  227288. function, true, true);
  227289. }
  227290. CGFunctionRelease (function);
  227291. return result;
  227292. }
  227293. void drawGradient()
  227294. {
  227295. flip();
  227296. applyTransform (state->fillType.transform);
  227297. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  227298. // you draw a gradient with high quality interp enabled).
  227299. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  227300. CGContextSetAlpha (context, state->fillType.getOpacity());
  227301. CGContextDrawShading (context, shading);
  227302. CGShadingRelease (shading);
  227303. }
  227304. void createPath (const Path& path) const
  227305. {
  227306. CGContextBeginPath (context);
  227307. Path::Iterator i (path);
  227308. while (i.next())
  227309. {
  227310. switch (i.elementType)
  227311. {
  227312. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  227313. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  227314. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  227315. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  227316. case Path::Iterator::closePath: CGContextClosePath (context); break;
  227317. default: jassertfalse; break;
  227318. }
  227319. }
  227320. }
  227321. void createPath (const Path& path, const AffineTransform& transform) const
  227322. {
  227323. CGContextBeginPath (context);
  227324. Path::Iterator i (path);
  227325. while (i.next())
  227326. {
  227327. switch (i.elementType)
  227328. {
  227329. case Path::Iterator::startNewSubPath:
  227330. transform.transformPoint (i.x1, i.y1);
  227331. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  227332. break;
  227333. case Path::Iterator::lineTo:
  227334. transform.transformPoint (i.x1, i.y1);
  227335. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  227336. break;
  227337. case Path::Iterator::quadraticTo:
  227338. transform.transformPoint (i.x1, i.y1);
  227339. transform.transformPoint (i.x2, i.y2);
  227340. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  227341. break;
  227342. case Path::Iterator::cubicTo:
  227343. transform.transformPoint (i.x1, i.y1);
  227344. transform.transformPoint (i.x2, i.y2);
  227345. transform.transformPoint (i.x3, i.y3);
  227346. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  227347. break;
  227348. case Path::Iterator::closePath:
  227349. CGContextClosePath (context); break;
  227350. default:
  227351. jassertfalse
  227352. break;
  227353. }
  227354. }
  227355. }
  227356. void flip() const
  227357. {
  227358. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  227359. }
  227360. void applyTransform (const AffineTransform& transform) const
  227361. {
  227362. CGAffineTransform t;
  227363. t.a = transform.mat00;
  227364. t.b = transform.mat10;
  227365. t.c = transform.mat01;
  227366. t.d = transform.mat11;
  227367. t.tx = transform.mat02;
  227368. t.ty = transform.mat12;
  227369. CGContextConcatCTM (context, t);
  227370. }
  227371. CoreGraphicsContext (const CoreGraphicsContext&);
  227372. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  227373. };
  227374. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  227375. {
  227376. return new CoreGraphicsContext (context, imageHeight);
  227377. }
  227378. #endif
  227379. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  227380. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  227381. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227382. // compiled on its own).
  227383. #if JUCE_INCLUDED_FILE
  227384. class NSViewComponentPeer;
  227385. END_JUCE_NAMESPACE
  227386. #define JuceNSView MakeObjCClassName(JuceNSView)
  227387. @interface JuceNSView : NSView<NSTextInput>
  227388. {
  227389. @public
  227390. NSViewComponentPeer* owner;
  227391. NSNotificationCenter* notificationCenter;
  227392. String* stringBeingComposed;
  227393. bool textWasInserted;
  227394. }
  227395. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  227396. - (void) dealloc;
  227397. - (BOOL) isOpaque;
  227398. - (void) drawRect: (NSRect) r;
  227399. - (void) mouseDown: (NSEvent*) ev;
  227400. - (void) asyncMouseDown: (NSEvent*) ev;
  227401. - (void) mouseUp: (NSEvent*) ev;
  227402. - (void) asyncMouseUp: (NSEvent*) ev;
  227403. - (void) mouseDragged: (NSEvent*) ev;
  227404. - (void) mouseMoved: (NSEvent*) ev;
  227405. - (void) mouseEntered: (NSEvent*) ev;
  227406. - (void) mouseExited: (NSEvent*) ev;
  227407. - (void) rightMouseDown: (NSEvent*) ev;
  227408. - (void) rightMouseDragged: (NSEvent*) ev;
  227409. - (void) rightMouseUp: (NSEvent*) ev;
  227410. - (void) otherMouseDown: (NSEvent*) ev;
  227411. - (void) otherMouseDragged: (NSEvent*) ev;
  227412. - (void) otherMouseUp: (NSEvent*) ev;
  227413. - (void) scrollWheel: (NSEvent*) ev;
  227414. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  227415. - (void) frameChanged: (NSNotification*) n;
  227416. - (void) viewDidMoveToWindow;
  227417. - (void) keyDown: (NSEvent*) ev;
  227418. - (void) keyUp: (NSEvent*) ev;
  227419. // NSTextInput Methods
  227420. - (void) insertText: (id) aString;
  227421. - (void) doCommandBySelector: (SEL) aSelector;
  227422. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  227423. - (void) unmarkText;
  227424. - (BOOL) hasMarkedText;
  227425. - (long) conversationIdentifier;
  227426. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  227427. - (NSRange) markedRange;
  227428. - (NSRange) selectedRange;
  227429. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  227430. - (unsigned int) characterIndexForPoint: (NSPoint) thePoint;
  227431. - (NSArray*) validAttributesForMarkedText;
  227432. - (void) flagsChanged: (NSEvent*) ev;
  227433. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  227434. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  227435. #endif
  227436. - (BOOL) becomeFirstResponder;
  227437. - (BOOL) resignFirstResponder;
  227438. - (BOOL) acceptsFirstResponder;
  227439. - (void) asyncRepaint: (id) rect;
  227440. - (NSArray*) getSupportedDragTypes;
  227441. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  227442. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  227443. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  227444. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  227445. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  227446. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  227447. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  227448. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  227449. @end
  227450. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  227451. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  227452. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  227453. #else
  227454. @interface JuceNSWindow : NSWindow
  227455. #endif
  227456. {
  227457. @private
  227458. NSViewComponentPeer* owner;
  227459. bool isZooming;
  227460. }
  227461. - (void) setOwner: (NSViewComponentPeer*) owner;
  227462. - (BOOL) canBecomeKeyWindow;
  227463. - (void) becomeKeyWindow;
  227464. - (BOOL) windowShouldClose: (id) window;
  227465. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  227466. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  227467. - (void) zoom: (id) sender;
  227468. @end
  227469. BEGIN_JUCE_NAMESPACE
  227470. class NSViewComponentPeer : public ComponentPeer
  227471. {
  227472. public:
  227473. NSViewComponentPeer (Component* const component,
  227474. const int windowStyleFlags,
  227475. NSView* viewToAttachTo);
  227476. ~NSViewComponentPeer();
  227477. void* getNativeHandle() const;
  227478. void setVisible (bool shouldBeVisible);
  227479. void setTitle (const String& title);
  227480. void setPosition (int x, int y);
  227481. void setSize (int w, int h);
  227482. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  227483. const Rectangle<int> getBounds (const bool global) const;
  227484. const Rectangle<int> getBounds() const;
  227485. const Point<int> getScreenPosition() const;
  227486. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  227487. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  227488. void setMinimised (bool shouldBeMinimised);
  227489. bool isMinimised() const;
  227490. void setFullScreen (bool shouldBeFullScreen);
  227491. bool isFullScreen() const;
  227492. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  227493. const BorderSize getFrameSize() const;
  227494. bool setAlwaysOnTop (bool alwaysOnTop);
  227495. void toFront (bool makeActiveWindow);
  227496. void toBehind (ComponentPeer* other);
  227497. void setIcon (const Image& newIcon);
  227498. const StringArray getAvailableRenderingEngines() throw();
  227499. int getCurrentRenderingEngine() throw();
  227500. void setCurrentRenderingEngine (int index) throw();
  227501. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  227502. for example having more than one juce plugin loaded into a host, then when a
  227503. method is called, the actual code that runs might actually be in a different module
  227504. than the one you expect... So any calls to library functions or statics that are
  227505. made inside obj-c methods will probably end up getting executed in a different DLL's
  227506. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  227507. To work around this insanity, I'm only allowing obj-c methods to make calls to
  227508. virtual methods of an object that's known to live inside the right module's space.
  227509. */
  227510. virtual void redirectMouseDown (NSEvent* ev);
  227511. virtual void redirectMouseUp (NSEvent* ev);
  227512. virtual void redirectMouseDrag (NSEvent* ev);
  227513. virtual void redirectMouseMove (NSEvent* ev);
  227514. virtual void redirectMouseEnter (NSEvent* ev);
  227515. virtual void redirectMouseExit (NSEvent* ev);
  227516. virtual void redirectMouseWheel (NSEvent* ev);
  227517. void sendMouseEvent (NSEvent* ev);
  227518. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  227519. virtual bool redirectKeyDown (NSEvent* ev);
  227520. virtual bool redirectKeyUp (NSEvent* ev);
  227521. virtual void redirectModKeyChange (NSEvent* ev);
  227522. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  227523. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  227524. #endif
  227525. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  227526. virtual bool isOpaque();
  227527. virtual void drawRect (NSRect r);
  227528. virtual bool canBecomeKeyWindow();
  227529. virtual bool windowShouldClose();
  227530. virtual void redirectMovedOrResized();
  227531. virtual void viewMovedToWindow();
  227532. virtual NSRect constrainRect (NSRect r);
  227533. static void showArrowCursorIfNeeded();
  227534. static void updateModifiers (NSEvent* e);
  227535. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  227536. static int getKeyCodeFromEvent (NSEvent* ev)
  227537. {
  227538. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  227539. int keyCode = unmodified[0];
  227540. if (keyCode == 0x19) // (backwards-tab)
  227541. keyCode = '\t';
  227542. else if (keyCode == 0x03) // (enter)
  227543. keyCode = '\r';
  227544. return keyCode;
  227545. }
  227546. static int64 getMouseTime (NSEvent* e)
  227547. {
  227548. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  227549. + (int64) ([e timestamp] * 1000.0);
  227550. }
  227551. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  227552. {
  227553. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  227554. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  227555. }
  227556. static int getModifierForButtonNumber (const NSInteger num)
  227557. {
  227558. return num == 0 ? ModifierKeys::leftButtonModifier
  227559. : (num == 1 ? ModifierKeys::rightButtonModifier
  227560. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  227561. }
  227562. virtual void viewFocusGain();
  227563. virtual void viewFocusLoss();
  227564. bool isFocused() const;
  227565. void grabFocus();
  227566. void textInputRequired (const Point<int>& position);
  227567. void repaint (int x, int y, int w, int h);
  227568. void performAnyPendingRepaintsNow();
  227569. juce_UseDebuggingNewOperator
  227570. NSWindow* window;
  227571. JuceNSView* view;
  227572. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  227573. static ModifierKeys currentModifiers;
  227574. static ComponentPeer* currentlyFocusedPeer;
  227575. static Array<int> keysCurrentlyDown;
  227576. };
  227577. END_JUCE_NAMESPACE
  227578. @implementation JuceNSView
  227579. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  227580. withFrame: (NSRect) frame
  227581. {
  227582. [super initWithFrame: frame];
  227583. owner = owner_;
  227584. stringBeingComposed = 0;
  227585. textWasInserted = false;
  227586. notificationCenter = [NSNotificationCenter defaultCenter];
  227587. [notificationCenter addObserver: self
  227588. selector: @selector (frameChanged:)
  227589. name: NSViewFrameDidChangeNotification
  227590. object: self];
  227591. if (! owner_->isSharedWindow)
  227592. {
  227593. [notificationCenter addObserver: self
  227594. selector: @selector (frameChanged:)
  227595. name: NSWindowDidMoveNotification
  227596. object: owner_->window];
  227597. }
  227598. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  227599. return self;
  227600. }
  227601. - (void) dealloc
  227602. {
  227603. [notificationCenter removeObserver: self];
  227604. delete stringBeingComposed;
  227605. [super dealloc];
  227606. }
  227607. - (void) drawRect: (NSRect) r
  227608. {
  227609. if (owner != 0)
  227610. owner->drawRect (r);
  227611. }
  227612. - (BOOL) isOpaque
  227613. {
  227614. return owner == 0 || owner->isOpaque();
  227615. }
  227616. - (void) mouseDown: (NSEvent*) ev
  227617. {
  227618. // In some host situations, the host will stop modal loops from working
  227619. // correctly if they're called from a mouse event, so we'll trigger
  227620. // the event asynchronously..
  227621. if (JUCEApplication::getInstance() == 0)
  227622. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  227623. withObject: ev
  227624. waitUntilDone: NO];
  227625. else
  227626. [self asyncMouseDown: ev];
  227627. }
  227628. - (void) asyncMouseDown: (NSEvent*) ev
  227629. {
  227630. if (owner != 0)
  227631. owner->redirectMouseDown (ev);
  227632. }
  227633. - (void) mouseUp: (NSEvent*) ev
  227634. {
  227635. // In some host situations, the host will stop modal loops from working
  227636. // correctly if they're called from a mouse event, so we'll trigger
  227637. // the event asynchronously..
  227638. if (JUCEApplication::getInstance() == 0)
  227639. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  227640. withObject: ev
  227641. waitUntilDone: NO];
  227642. else
  227643. [self asyncMouseUp: ev];
  227644. }
  227645. - (void) asyncMouseUp: (NSEvent*) ev
  227646. {
  227647. if (owner != 0)
  227648. owner->redirectMouseUp (ev);
  227649. }
  227650. - (void) mouseDragged: (NSEvent*) ev
  227651. {
  227652. if (owner != 0)
  227653. owner->redirectMouseDrag (ev);
  227654. }
  227655. - (void) mouseMoved: (NSEvent*) ev
  227656. {
  227657. if (owner != 0)
  227658. owner->redirectMouseMove (ev);
  227659. }
  227660. - (void) mouseEntered: (NSEvent*) ev
  227661. {
  227662. if (owner != 0)
  227663. owner->redirectMouseEnter (ev);
  227664. }
  227665. - (void) mouseExited: (NSEvent*) ev
  227666. {
  227667. if (owner != 0)
  227668. owner->redirectMouseExit (ev);
  227669. }
  227670. - (void) rightMouseDown: (NSEvent*) ev
  227671. {
  227672. [self mouseDown: ev];
  227673. }
  227674. - (void) rightMouseDragged: (NSEvent*) ev
  227675. {
  227676. [self mouseDragged: ev];
  227677. }
  227678. - (void) rightMouseUp: (NSEvent*) ev
  227679. {
  227680. [self mouseUp: ev];
  227681. }
  227682. - (void) otherMouseDown: (NSEvent*) ev
  227683. {
  227684. [self mouseDown: ev];
  227685. }
  227686. - (void) otherMouseDragged: (NSEvent*) ev
  227687. {
  227688. [self mouseDragged: ev];
  227689. }
  227690. - (void) otherMouseUp: (NSEvent*) ev
  227691. {
  227692. [self mouseUp: ev];
  227693. }
  227694. - (void) scrollWheel: (NSEvent*) ev
  227695. {
  227696. if (owner != 0)
  227697. owner->redirectMouseWheel (ev);
  227698. }
  227699. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  227700. {
  227701. (void) ev;
  227702. return YES;
  227703. }
  227704. - (void) frameChanged: (NSNotification*) n
  227705. {
  227706. (void) n;
  227707. if (owner != 0)
  227708. owner->redirectMovedOrResized();
  227709. }
  227710. - (void) viewDidMoveToWindow
  227711. {
  227712. if (owner != 0)
  227713. owner->viewMovedToWindow();
  227714. }
  227715. - (void) asyncRepaint: (id) rect
  227716. {
  227717. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  227718. [self setNeedsDisplayInRect: *r];
  227719. }
  227720. - (void) keyDown: (NSEvent*) ev
  227721. {
  227722. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  227723. textWasInserted = false;
  227724. if (target != 0)
  227725. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  227726. else
  227727. deleteAndZero (stringBeingComposed);
  227728. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  227729. [super keyDown: ev];
  227730. }
  227731. - (void) keyUp: (NSEvent*) ev
  227732. {
  227733. if (owner == 0 || ! owner->redirectKeyUp (ev))
  227734. [super keyUp: ev];
  227735. }
  227736. - (void) insertText: (id) aString
  227737. {
  227738. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  227739. if ([aString length] > 0)
  227740. {
  227741. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  227742. if (target != 0)
  227743. {
  227744. target->insertTextAtCaret (nsStringToJuce ([aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString));
  227745. textWasInserted = true;
  227746. }
  227747. }
  227748. deleteAndZero (stringBeingComposed);
  227749. }
  227750. - (void) doCommandBySelector: (SEL) aSelector
  227751. {
  227752. (void) aSelector;
  227753. }
  227754. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  227755. {
  227756. (void) selectionRange;
  227757. if (stringBeingComposed == 0)
  227758. stringBeingComposed = new String();
  227759. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  227760. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  227761. if (target != 0)
  227762. {
  227763. const Range<int> currentHighlight (target->getHighlightedRegion());
  227764. target->insertTextAtCaret (*stringBeingComposed);
  227765. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  227766. textWasInserted = true;
  227767. }
  227768. }
  227769. - (void) unmarkText
  227770. {
  227771. if (stringBeingComposed != 0)
  227772. {
  227773. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  227774. if (target != 0)
  227775. {
  227776. target->insertTextAtCaret (*stringBeingComposed);
  227777. textWasInserted = true;
  227778. }
  227779. }
  227780. deleteAndZero (stringBeingComposed);
  227781. }
  227782. - (BOOL) hasMarkedText
  227783. {
  227784. return stringBeingComposed != 0;
  227785. }
  227786. - (long) conversationIdentifier
  227787. {
  227788. return (long) (pointer_sized_int) self;
  227789. }
  227790. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  227791. {
  227792. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  227793. if (target != 0)
  227794. {
  227795. const Range<int> r ((int) theRange.location,
  227796. (int) (theRange.location + theRange.length));
  227797. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  227798. }
  227799. return nil;
  227800. }
  227801. - (NSRange) markedRange
  227802. {
  227803. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  227804. : NSMakeRange (NSNotFound, 0);
  227805. }
  227806. - (NSRange) selectedRange
  227807. {
  227808. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  227809. if (target != 0)
  227810. {
  227811. const Range<int> highlight (target->getHighlightedRegion());
  227812. if (! highlight.isEmpty())
  227813. return NSMakeRange (highlight.getStart(), highlight.getLength());
  227814. }
  227815. return NSMakeRange (NSNotFound, 0);
  227816. }
  227817. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  227818. {
  227819. (void) theRange;
  227820. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  227821. if (comp == 0)
  227822. return NSMakeRect (0, 0, 0, 0);
  227823. const Rectangle<int> bounds (comp->getScreenBounds());
  227824. return NSMakeRect (bounds.getX(),
  227825. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  227826. bounds.getWidth(),
  227827. bounds.getHeight());
  227828. }
  227829. - (unsigned int) characterIndexForPoint: (NSPoint) thePoint
  227830. {
  227831. (void) thePoint;
  227832. return NSNotFound;
  227833. }
  227834. - (NSArray*) validAttributesForMarkedText
  227835. {
  227836. return [NSArray array];
  227837. }
  227838. - (void) flagsChanged: (NSEvent*) ev
  227839. {
  227840. if (owner != 0)
  227841. owner->redirectModKeyChange (ev);
  227842. }
  227843. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  227844. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  227845. {
  227846. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  227847. return true;
  227848. return [super performKeyEquivalent: ev];
  227849. }
  227850. #endif
  227851. - (BOOL) becomeFirstResponder
  227852. {
  227853. if (owner != 0)
  227854. owner->viewFocusGain();
  227855. return true;
  227856. }
  227857. - (BOOL) resignFirstResponder
  227858. {
  227859. if (owner != 0)
  227860. owner->viewFocusLoss();
  227861. return true;
  227862. }
  227863. - (BOOL) acceptsFirstResponder
  227864. {
  227865. return owner != 0 && owner->canBecomeKeyWindow();
  227866. }
  227867. - (NSArray*) getSupportedDragTypes
  227868. {
  227869. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  227870. }
  227871. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  227872. {
  227873. return owner != 0 && owner->sendDragCallback (type, sender);
  227874. }
  227875. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  227876. {
  227877. if ([self sendDragCallback: 0 sender: sender])
  227878. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  227879. else
  227880. return NSDragOperationNone;
  227881. }
  227882. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  227883. {
  227884. if ([self sendDragCallback: 0 sender: sender])
  227885. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  227886. else
  227887. return NSDragOperationNone;
  227888. }
  227889. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  227890. {
  227891. [self sendDragCallback: 1 sender: sender];
  227892. }
  227893. - (void) draggingExited: (id <NSDraggingInfo>) sender
  227894. {
  227895. [self sendDragCallback: 1 sender: sender];
  227896. }
  227897. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  227898. {
  227899. (void) sender;
  227900. return YES;
  227901. }
  227902. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  227903. {
  227904. return [self sendDragCallback: 2 sender: sender];
  227905. }
  227906. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  227907. {
  227908. (void) sender;
  227909. }
  227910. @end
  227911. @implementation JuceNSWindow
  227912. - (void) setOwner: (NSViewComponentPeer*) owner_
  227913. {
  227914. owner = owner_;
  227915. isZooming = false;
  227916. }
  227917. - (BOOL) canBecomeKeyWindow
  227918. {
  227919. return owner != 0 && owner->canBecomeKeyWindow();
  227920. }
  227921. - (void) becomeKeyWindow
  227922. {
  227923. [super becomeKeyWindow];
  227924. if (owner != 0)
  227925. owner->grabFocus();
  227926. }
  227927. - (BOOL) windowShouldClose: (id) window
  227928. {
  227929. (void) window;
  227930. return owner == 0 || owner->windowShouldClose();
  227931. }
  227932. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  227933. {
  227934. (void) screen;
  227935. if (owner != 0)
  227936. frameRect = owner->constrainRect (frameRect);
  227937. return frameRect;
  227938. }
  227939. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  227940. {
  227941. (void) window;
  227942. if (isZooming)
  227943. return proposedFrameSize;
  227944. NSRect frameRect = [self frame];
  227945. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  227946. frameRect.size = proposedFrameSize;
  227947. if (owner != 0)
  227948. frameRect = owner->constrainRect (frameRect);
  227949. return frameRect.size;
  227950. }
  227951. - (void) zoom: (id) sender
  227952. {
  227953. isZooming = true;
  227954. [super zoom: sender];
  227955. isZooming = false;
  227956. }
  227957. - (void) windowWillMove: (NSNotification*) notification
  227958. {
  227959. (void) notification;
  227960. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  227961. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  227962. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  227963. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  227964. }
  227965. @end
  227966. BEGIN_JUCE_NAMESPACE
  227967. ModifierKeys NSViewComponentPeer::currentModifiers;
  227968. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  227969. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  227970. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  227971. {
  227972. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  227973. return true;
  227974. if (keyCode >= 'A' && keyCode <= 'Z'
  227975. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  227976. return true;
  227977. if (keyCode >= 'a' && keyCode <= 'z'
  227978. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  227979. return true;
  227980. return false;
  227981. }
  227982. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  227983. {
  227984. int m = 0;
  227985. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  227986. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  227987. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  227988. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  227989. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  227990. }
  227991. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  227992. {
  227993. updateModifiers (ev);
  227994. int keyCode = getKeyCodeFromEvent (ev);
  227995. if (keyCode != 0)
  227996. {
  227997. if (isKeyDown)
  227998. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  227999. else
  228000. keysCurrentlyDown.removeValue (keyCode);
  228001. }
  228002. }
  228003. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  228004. {
  228005. return NSViewComponentPeer::currentModifiers;
  228006. }
  228007. void ModifierKeys::updateCurrentModifiers() throw()
  228008. {
  228009. currentModifiers = NSViewComponentPeer::currentModifiers;
  228010. }
  228011. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  228012. const int windowStyleFlags,
  228013. NSView* viewToAttachTo)
  228014. : ComponentPeer (component_, windowStyleFlags),
  228015. window (0),
  228016. view (0),
  228017. isSharedWindow (viewToAttachTo != 0),
  228018. fullScreen (false),
  228019. insideDrawRect (false),
  228020. #if USE_COREGRAPHICS_RENDERING
  228021. usingCoreGraphics (true),
  228022. #else
  228023. usingCoreGraphics (false),
  228024. #endif
  228025. recursiveToFrontCall (false)
  228026. {
  228027. NSRect r;
  228028. r.origin.x = 0;
  228029. r.origin.y = 0;
  228030. r.size.width = (float) component->getWidth();
  228031. r.size.height = (float) component->getHeight();
  228032. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  228033. [view setPostsFrameChangedNotifications: YES];
  228034. if (isSharedWindow)
  228035. {
  228036. window = [viewToAttachTo window];
  228037. [viewToAttachTo addSubview: view];
  228038. setVisible (component->isVisible());
  228039. }
  228040. else
  228041. {
  228042. r.origin.x = (float) component->getX();
  228043. r.origin.y = (float) component->getY();
  228044. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  228045. unsigned int style = 0;
  228046. if ((windowStyleFlags & windowHasTitleBar) == 0)
  228047. style = NSBorderlessWindowMask;
  228048. else
  228049. style = NSTitledWindowMask;
  228050. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  228051. style |= NSMiniaturizableWindowMask;
  228052. if ((windowStyleFlags & windowHasCloseButton) != 0)
  228053. style |= NSClosableWindowMask;
  228054. if ((windowStyleFlags & windowIsResizable) != 0)
  228055. style |= NSResizableWindowMask;
  228056. window = [[JuceNSWindow alloc] initWithContentRect: r
  228057. styleMask: style
  228058. backing: NSBackingStoreBuffered
  228059. defer: YES];
  228060. [((JuceNSWindow*) window) setOwner: this];
  228061. [window orderOut: nil];
  228062. [window setDelegate: (JuceNSWindow*) window];
  228063. [window setOpaque: component->isOpaque()];
  228064. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  228065. if (component->isAlwaysOnTop())
  228066. [window setLevel: NSFloatingWindowLevel];
  228067. [window setContentView: view];
  228068. [window setAutodisplay: YES];
  228069. [window setAcceptsMouseMovedEvents: YES];
  228070. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  228071. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  228072. [window setReleasedWhenClosed: YES];
  228073. [window retain];
  228074. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  228075. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  228076. }
  228077. setTitle (component->getName());
  228078. }
  228079. NSViewComponentPeer::~NSViewComponentPeer()
  228080. {
  228081. view->owner = 0;
  228082. [view removeFromSuperview];
  228083. [view release];
  228084. if (! isSharedWindow)
  228085. {
  228086. [((JuceNSWindow*) window) setOwner: 0];
  228087. [window close];
  228088. [window release];
  228089. }
  228090. }
  228091. void* NSViewComponentPeer::getNativeHandle() const
  228092. {
  228093. return view;
  228094. }
  228095. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  228096. {
  228097. if (isSharedWindow)
  228098. {
  228099. [view setHidden: ! shouldBeVisible];
  228100. }
  228101. else
  228102. {
  228103. if (shouldBeVisible)
  228104. {
  228105. [window orderFront: nil];
  228106. handleBroughtToFront();
  228107. }
  228108. else
  228109. {
  228110. [window orderOut: nil];
  228111. }
  228112. }
  228113. }
  228114. void NSViewComponentPeer::setTitle (const String& title)
  228115. {
  228116. const ScopedAutoReleasePool pool;
  228117. if (! isSharedWindow)
  228118. [window setTitle: juceStringToNS (title)];
  228119. }
  228120. void NSViewComponentPeer::setPosition (int x, int y)
  228121. {
  228122. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  228123. }
  228124. void NSViewComponentPeer::setSize (int w, int h)
  228125. {
  228126. setBounds (component->getX(), component->getY(), w, h, false);
  228127. }
  228128. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  228129. {
  228130. fullScreen = isNowFullScreen;
  228131. w = jmax (0, w);
  228132. h = jmax (0, h);
  228133. NSRect r;
  228134. r.origin.x = (float) x;
  228135. r.origin.y = (float) y;
  228136. r.size.width = (float) w;
  228137. r.size.height = (float) h;
  228138. if (isSharedWindow)
  228139. {
  228140. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  228141. if ([view frame].size.width != r.size.width
  228142. || [view frame].size.height != r.size.height)
  228143. [view setNeedsDisplay: true];
  228144. [view setFrame: r];
  228145. }
  228146. else
  228147. {
  228148. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  228149. [window setFrame: [window frameRectForContentRect: r]
  228150. display: true];
  228151. }
  228152. }
  228153. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  228154. {
  228155. NSRect r = [view frame];
  228156. if (global && [view window] != 0)
  228157. {
  228158. r = [view convertRect: r toView: nil];
  228159. NSRect wr = [[view window] frame];
  228160. r.origin.x += wr.origin.x;
  228161. r.origin.y += wr.origin.y;
  228162. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  228163. }
  228164. else
  228165. {
  228166. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  228167. }
  228168. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  228169. }
  228170. const Rectangle<int> NSViewComponentPeer::getBounds() const
  228171. {
  228172. return getBounds (! isSharedWindow);
  228173. }
  228174. const Point<int> NSViewComponentPeer::getScreenPosition() const
  228175. {
  228176. return getBounds (true).getPosition();
  228177. }
  228178. const Point<int> NSViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  228179. {
  228180. return relativePosition + getScreenPosition();
  228181. }
  228182. const Point<int> NSViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  228183. {
  228184. return screenPosition - getScreenPosition();
  228185. }
  228186. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  228187. {
  228188. if (constrainer != 0)
  228189. {
  228190. NSRect current = [window frame];
  228191. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  228192. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  228193. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  228194. (int) r.size.width, (int) r.size.height);
  228195. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  228196. (int) current.size.width, (int) current.size.height);
  228197. constrainer->checkBounds (pos, original,
  228198. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  228199. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  228200. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  228201. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  228202. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  228203. r.origin.x = pos.getX();
  228204. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  228205. r.size.width = pos.getWidth();
  228206. r.size.height = pos.getHeight();
  228207. }
  228208. return r;
  228209. }
  228210. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  228211. {
  228212. if (! isSharedWindow)
  228213. {
  228214. if (shouldBeMinimised)
  228215. [window miniaturize: nil];
  228216. else
  228217. [window deminiaturize: nil];
  228218. }
  228219. }
  228220. bool NSViewComponentPeer::isMinimised() const
  228221. {
  228222. return window != 0 && [window isMiniaturized];
  228223. }
  228224. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  228225. {
  228226. if (! isSharedWindow)
  228227. {
  228228. Rectangle<int> r (lastNonFullscreenBounds);
  228229. setMinimised (false);
  228230. if (fullScreen != shouldBeFullScreen)
  228231. {
  228232. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  228233. {
  228234. fullScreen = true;
  228235. [window performZoom: nil];
  228236. }
  228237. else
  228238. {
  228239. if (shouldBeFullScreen)
  228240. r = Desktop::getInstance().getMainMonitorArea();
  228241. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  228242. if (r != getComponent()->getBounds() && ! r.isEmpty())
  228243. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  228244. }
  228245. }
  228246. }
  228247. }
  228248. bool NSViewComponentPeer::isFullScreen() const
  228249. {
  228250. return fullScreen;
  228251. }
  228252. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  228253. {
  228254. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  228255. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  228256. return false;
  228257. NSPoint p;
  228258. p.x = (float) position.getX();
  228259. p.y = (float) position.getY();
  228260. NSView* v = [view hitTest: p];
  228261. if (trueIfInAChildWindow)
  228262. return v != nil;
  228263. return v == view;
  228264. }
  228265. const BorderSize NSViewComponentPeer::getFrameSize() const
  228266. {
  228267. BorderSize b;
  228268. if (! isSharedWindow)
  228269. {
  228270. NSRect v = [view convertRect: [view frame] toView: nil];
  228271. NSRect w = [window frame];
  228272. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  228273. b.setBottom ((int) v.origin.y);
  228274. b.setLeft ((int) v.origin.x);
  228275. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  228276. }
  228277. return b;
  228278. }
  228279. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  228280. {
  228281. if (! isSharedWindow)
  228282. {
  228283. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  228284. : NSNormalWindowLevel];
  228285. }
  228286. return true;
  228287. }
  228288. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  228289. {
  228290. if (isSharedWindow)
  228291. {
  228292. [[view superview] addSubview: view
  228293. positioned: NSWindowAbove
  228294. relativeTo: nil];
  228295. }
  228296. if (window != 0 && component->isVisible())
  228297. {
  228298. if (makeActiveWindow)
  228299. [window makeKeyAndOrderFront: nil];
  228300. else
  228301. [window orderFront: nil];
  228302. if (! recursiveToFrontCall)
  228303. {
  228304. recursiveToFrontCall = true;
  228305. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  228306. handleBroughtToFront();
  228307. recursiveToFrontCall = false;
  228308. }
  228309. }
  228310. }
  228311. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  228312. {
  228313. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  228314. jassert (otherPeer != 0); // wrong type of window?
  228315. if (otherPeer != 0)
  228316. {
  228317. if (isSharedWindow)
  228318. {
  228319. [[view superview] addSubview: view
  228320. positioned: NSWindowBelow
  228321. relativeTo: otherPeer->view];
  228322. }
  228323. else
  228324. {
  228325. [window orderWindow: NSWindowBelow
  228326. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  228327. : nil ];
  228328. }
  228329. }
  228330. }
  228331. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  228332. {
  228333. // to do..
  228334. }
  228335. void NSViewComponentPeer::viewFocusGain()
  228336. {
  228337. if (currentlyFocusedPeer != this)
  228338. {
  228339. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  228340. currentlyFocusedPeer->handleFocusLoss();
  228341. currentlyFocusedPeer = this;
  228342. handleFocusGain();
  228343. }
  228344. }
  228345. void NSViewComponentPeer::viewFocusLoss()
  228346. {
  228347. if (currentlyFocusedPeer == this)
  228348. {
  228349. currentlyFocusedPeer = 0;
  228350. handleFocusLoss();
  228351. }
  228352. }
  228353. void juce_HandleProcessFocusChange()
  228354. {
  228355. NSViewComponentPeer::keysCurrentlyDown.clear();
  228356. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  228357. {
  228358. if (Process::isForegroundProcess())
  228359. {
  228360. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  228361. ComponentPeer::bringModalComponentToFront();
  228362. }
  228363. else
  228364. {
  228365. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  228366. // turn kiosk mode off if we lose focus..
  228367. Desktop::getInstance().setKioskModeComponent (0);
  228368. }
  228369. }
  228370. }
  228371. bool NSViewComponentPeer::isFocused() const
  228372. {
  228373. return isSharedWindow ? this == currentlyFocusedPeer
  228374. : (window != 0 && [window isKeyWindow]);
  228375. }
  228376. void NSViewComponentPeer::grabFocus()
  228377. {
  228378. if (window != 0)
  228379. {
  228380. [window makeKeyWindow];
  228381. [window makeFirstResponder: view];
  228382. viewFocusGain();
  228383. }
  228384. }
  228385. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  228386. {
  228387. }
  228388. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  228389. {
  228390. String unicode (nsStringToJuce ([ev characters]));
  228391. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  228392. int keyCode = getKeyCodeFromEvent (ev);
  228393. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  228394. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  228395. if (unicode.isNotEmpty() || keyCode != 0)
  228396. {
  228397. if (isKeyDown)
  228398. {
  228399. bool used = false;
  228400. while (unicode.length() > 0)
  228401. {
  228402. juce_wchar textCharacter = unicode[0];
  228403. unicode = unicode.substring (1);
  228404. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  228405. textCharacter = 0;
  228406. used = handleKeyUpOrDown (true) || used;
  228407. used = handleKeyPress (keyCode, textCharacter) || used;
  228408. }
  228409. return used;
  228410. }
  228411. else
  228412. {
  228413. if (handleKeyUpOrDown (false))
  228414. return true;
  228415. }
  228416. }
  228417. return false;
  228418. }
  228419. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  228420. {
  228421. updateKeysDown (ev, true);
  228422. bool used = handleKeyEvent (ev, true);
  228423. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  228424. {
  228425. // for command keys, the key-up event is thrown away, so simulate one..
  228426. updateKeysDown (ev, false);
  228427. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  228428. }
  228429. // (If we're running modally, don't allow unused keystrokes to be passed
  228430. // along to other blocked views..)
  228431. if (Component::getCurrentlyModalComponent() != 0)
  228432. used = true;
  228433. return used;
  228434. }
  228435. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  228436. {
  228437. updateKeysDown (ev, false);
  228438. return handleKeyEvent (ev, false)
  228439. || Component::getCurrentlyModalComponent() != 0;
  228440. }
  228441. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  228442. {
  228443. keysCurrentlyDown.clear();
  228444. handleKeyUpOrDown (true);
  228445. updateModifiers (ev);
  228446. handleModifierKeysChange();
  228447. }
  228448. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  228449. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  228450. {
  228451. if ([ev type] == NSKeyDown)
  228452. return redirectKeyDown (ev);
  228453. else if ([ev type] == NSKeyUp)
  228454. return redirectKeyUp (ev);
  228455. return false;
  228456. }
  228457. #endif
  228458. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  228459. {
  228460. updateModifiers (ev);
  228461. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  228462. }
  228463. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  228464. {
  228465. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  228466. sendMouseEvent (ev);
  228467. }
  228468. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  228469. {
  228470. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  228471. sendMouseEvent (ev);
  228472. showArrowCursorIfNeeded();
  228473. }
  228474. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  228475. {
  228476. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  228477. sendMouseEvent (ev);
  228478. }
  228479. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  228480. {
  228481. currentModifiers = currentModifiers.withoutMouseButtons();
  228482. sendMouseEvent (ev);
  228483. showArrowCursorIfNeeded();
  228484. }
  228485. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  228486. {
  228487. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  228488. currentModifiers = currentModifiers.withoutMouseButtons();
  228489. sendMouseEvent (ev);
  228490. }
  228491. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  228492. {
  228493. currentModifiers = currentModifiers.withoutMouseButtons();
  228494. sendMouseEvent (ev);
  228495. }
  228496. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  228497. {
  228498. updateModifiers (ev);
  228499. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev),
  228500. [ev deltaX] * 10.0f, [ev deltaY] * 10.0f);
  228501. }
  228502. void NSViewComponentPeer::showArrowCursorIfNeeded()
  228503. {
  228504. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  228505. if (mouse.getComponentUnderMouse() == 0
  228506. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  228507. {
  228508. [[NSCursor arrowCursor] set];
  228509. }
  228510. }
  228511. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  228512. {
  228513. NSString* bestType
  228514. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  228515. if (bestType == nil)
  228516. return false;
  228517. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  228518. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  228519. StringArray files;
  228520. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  228521. if (list == nil)
  228522. return false;
  228523. if ([list isKindOfClass: [NSArray class]])
  228524. {
  228525. NSArray* items = (NSArray*) list;
  228526. for (unsigned int i = 0; i < [items count]; ++i)
  228527. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  228528. }
  228529. if (files.size() == 0)
  228530. return false;
  228531. if (type == 0)
  228532. handleFileDragMove (files, pos);
  228533. else if (type == 1)
  228534. handleFileDragExit (files);
  228535. else if (type == 2)
  228536. handleFileDragDrop (files, pos);
  228537. return true;
  228538. }
  228539. bool NSViewComponentPeer::isOpaque()
  228540. {
  228541. return component == 0 || component->isOpaque();
  228542. }
  228543. void NSViewComponentPeer::drawRect (NSRect r)
  228544. {
  228545. if (r.size.width < 1.0f || r.size.height < 1.0f)
  228546. return;
  228547. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  228548. if (! component->isOpaque())
  228549. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  228550. #if USE_COREGRAPHICS_RENDERING
  228551. if (usingCoreGraphics)
  228552. {
  228553. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  228554. insideDrawRect = true;
  228555. handlePaint (context);
  228556. insideDrawRect = false;
  228557. }
  228558. else
  228559. #endif
  228560. {
  228561. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  228562. (int) (r.size.width + 0.5f),
  228563. (int) (r.size.height + 0.5f),
  228564. ! getComponent()->isOpaque());
  228565. const int xOffset = -roundToInt (r.origin.x);
  228566. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  228567. const NSRect* rects = 0;
  228568. NSInteger numRects = 0;
  228569. [view getRectsBeingDrawn: &rects count: &numRects];
  228570. const Rectangle<int> clipBounds (temp.getBounds());
  228571. RectangleList clip;
  228572. for (int i = 0; i < numRects; ++i)
  228573. {
  228574. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  228575. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  228576. roundToInt (rects[i].size.width),
  228577. roundToInt (rects[i].size.height))));
  228578. }
  228579. if (! clip.isEmpty())
  228580. {
  228581. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  228582. insideDrawRect = true;
  228583. handlePaint (context);
  228584. insideDrawRect = false;
  228585. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  228586. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace);
  228587. CGColorSpaceRelease (colourSpace);
  228588. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  228589. CGImageRelease (image);
  228590. }
  228591. }
  228592. }
  228593. const StringArray NSViewComponentPeer::getAvailableRenderingEngines() throw()
  228594. {
  228595. StringArray s;
  228596. s.add ("Software Renderer");
  228597. #if USE_COREGRAPHICS_RENDERING
  228598. s.add ("CoreGraphics Renderer");
  228599. #endif
  228600. return s;
  228601. }
  228602. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  228603. {
  228604. return usingCoreGraphics ? 1 : 0;
  228605. }
  228606. void NSViewComponentPeer::setCurrentRenderingEngine (int index) throw()
  228607. {
  228608. #if USE_COREGRAPHICS_RENDERING
  228609. if (usingCoreGraphics != (index > 0))
  228610. {
  228611. usingCoreGraphics = index > 0;
  228612. [view setNeedsDisplay: true];
  228613. }
  228614. #endif
  228615. }
  228616. bool NSViewComponentPeer::canBecomeKeyWindow()
  228617. {
  228618. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  228619. }
  228620. bool NSViewComponentPeer::windowShouldClose()
  228621. {
  228622. if (! isValidPeer (this))
  228623. return YES;
  228624. handleUserClosingWindow();
  228625. return NO;
  228626. }
  228627. void NSViewComponentPeer::redirectMovedOrResized()
  228628. {
  228629. handleMovedOrResized();
  228630. }
  228631. void NSViewComponentPeer::viewMovedToWindow()
  228632. {
  228633. if (isSharedWindow)
  228634. window = [view window];
  228635. }
  228636. void Desktop::createMouseInputSources()
  228637. {
  228638. mouseSources.add (new MouseInputSource (0, true));
  228639. }
  228640. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  228641. {
  228642. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  228643. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  228644. // is apparently still available in 64-bit apps..
  228645. if (enableOrDisable)
  228646. {
  228647. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  228648. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  228649. }
  228650. else
  228651. {
  228652. SetSystemUIMode (kUIModeNormal, 0);
  228653. }
  228654. }
  228655. class AsyncRepaintMessage : public CallbackMessage
  228656. {
  228657. public:
  228658. NSViewComponentPeer* const peer;
  228659. const Rectangle<int> rect;
  228660. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  228661. : peer (peer_), rect (rect_)
  228662. {
  228663. }
  228664. void messageCallback()
  228665. {
  228666. if (ComponentPeer::isValidPeer (peer))
  228667. peer->repaint (rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight());
  228668. }
  228669. };
  228670. void NSViewComponentPeer::repaint (int x, int y, int w, int h)
  228671. {
  228672. if (insideDrawRect)
  228673. {
  228674. (new AsyncRepaintMessage (this, Rectangle<int> (x, y, w, h)))->post();
  228675. }
  228676. else
  228677. {
  228678. [view setNeedsDisplayInRect: NSMakeRect ((float) x, (float) ([view frame].size.height - (y + h)),
  228679. (float) w, (float) h)];
  228680. }
  228681. }
  228682. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  228683. {
  228684. [view displayIfNeeded];
  228685. }
  228686. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  228687. {
  228688. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  228689. }
  228690. Image* juce_createIconForFile (const File& file)
  228691. {
  228692. const ScopedAutoReleasePool pool;
  228693. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  228694. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  228695. [NSGraphicsContext saveGraphicsState];
  228696. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  228697. [image drawAtPoint: NSMakePoint (0, 0)
  228698. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  228699. operation: NSCompositeSourceOver fraction: 1.0f];
  228700. [[NSGraphicsContext currentContext] flushGraphics];
  228701. [NSGraphicsContext restoreGraphicsState];
  228702. return result;
  228703. }
  228704. const int KeyPress::spaceKey = ' ';
  228705. const int KeyPress::returnKey = 0x0d;
  228706. const int KeyPress::escapeKey = 0x1b;
  228707. const int KeyPress::backspaceKey = 0x7f;
  228708. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  228709. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  228710. const int KeyPress::upKey = NSUpArrowFunctionKey;
  228711. const int KeyPress::downKey = NSDownArrowFunctionKey;
  228712. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  228713. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  228714. const int KeyPress::endKey = NSEndFunctionKey;
  228715. const int KeyPress::homeKey = NSHomeFunctionKey;
  228716. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  228717. const int KeyPress::insertKey = -1;
  228718. const int KeyPress::tabKey = 9;
  228719. const int KeyPress::F1Key = NSF1FunctionKey;
  228720. const int KeyPress::F2Key = NSF2FunctionKey;
  228721. const int KeyPress::F3Key = NSF3FunctionKey;
  228722. const int KeyPress::F4Key = NSF4FunctionKey;
  228723. const int KeyPress::F5Key = NSF5FunctionKey;
  228724. const int KeyPress::F6Key = NSF6FunctionKey;
  228725. const int KeyPress::F7Key = NSF7FunctionKey;
  228726. const int KeyPress::F8Key = NSF8FunctionKey;
  228727. const int KeyPress::F9Key = NSF9FunctionKey;
  228728. const int KeyPress::F10Key = NSF10FunctionKey;
  228729. const int KeyPress::F11Key = NSF1FunctionKey;
  228730. const int KeyPress::F12Key = NSF12FunctionKey;
  228731. const int KeyPress::F13Key = NSF13FunctionKey;
  228732. const int KeyPress::F14Key = NSF14FunctionKey;
  228733. const int KeyPress::F15Key = NSF15FunctionKey;
  228734. const int KeyPress::F16Key = NSF16FunctionKey;
  228735. const int KeyPress::numberPad0 = 0x30020;
  228736. const int KeyPress::numberPad1 = 0x30021;
  228737. const int KeyPress::numberPad2 = 0x30022;
  228738. const int KeyPress::numberPad3 = 0x30023;
  228739. const int KeyPress::numberPad4 = 0x30024;
  228740. const int KeyPress::numberPad5 = 0x30025;
  228741. const int KeyPress::numberPad6 = 0x30026;
  228742. const int KeyPress::numberPad7 = 0x30027;
  228743. const int KeyPress::numberPad8 = 0x30028;
  228744. const int KeyPress::numberPad9 = 0x30029;
  228745. const int KeyPress::numberPadAdd = 0x3002a;
  228746. const int KeyPress::numberPadSubtract = 0x3002b;
  228747. const int KeyPress::numberPadMultiply = 0x3002c;
  228748. const int KeyPress::numberPadDivide = 0x3002d;
  228749. const int KeyPress::numberPadSeparator = 0x3002e;
  228750. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  228751. const int KeyPress::numberPadEquals = 0x30030;
  228752. const int KeyPress::numberPadDelete = 0x30031;
  228753. const int KeyPress::playKey = 0x30000;
  228754. const int KeyPress::stopKey = 0x30001;
  228755. const int KeyPress::fastForwardKey = 0x30002;
  228756. const int KeyPress::rewindKey = 0x30003;
  228757. #endif
  228758. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  228759. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  228760. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228761. // compiled on its own).
  228762. #if JUCE_INCLUDED_FILE
  228763. #if JUCE_MAC
  228764. namespace MouseCursorHelpers
  228765. {
  228766. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  228767. {
  228768. NSImage* im = CoreGraphicsImage::createNSImage (image);
  228769. NSCursor* c = [[NSCursor alloc] initWithImage: im
  228770. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  228771. [im release];
  228772. return c;
  228773. }
  228774. static void* fromWebKitFile (const char* filename, float hx, float hy)
  228775. {
  228776. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  228777. BufferedInputStream buf (&fileStream, 4096, false);
  228778. PNGImageFormat pngFormat;
  228779. const ScopedPointer <Image> im (pngFormat.decodeImage (buf));
  228780. if (im != 0)
  228781. return createFromImage (*im, hx * im->getWidth(), hy * im->getHeight());
  228782. jassertfalse;
  228783. return 0;
  228784. }
  228785. }
  228786. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  228787. {
  228788. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  228789. }
  228790. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  228791. {
  228792. const ScopedAutoReleasePool pool;
  228793. NSCursor* c = 0;
  228794. switch (type)
  228795. {
  228796. case NormalCursor: c = [NSCursor arrowCursor]; break;
  228797. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  228798. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  228799. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  228800. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  228801. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  228802. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  228803. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  228804. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  228805. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  228806. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  228807. case UpDownResizeCursor:
  228808. case TopEdgeResizeCursor:
  228809. case BottomEdgeResizeCursor:
  228810. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  228811. case TopLeftCornerResizeCursor:
  228812. case BottomRightCornerResizeCursor:
  228813. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  228814. case TopRightCornerResizeCursor:
  228815. case BottomLeftCornerResizeCursor:
  228816. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  228817. case UpDownLeftRightResizeCursor:
  228818. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  228819. default:
  228820. jassertfalse;
  228821. break;
  228822. }
  228823. [c retain];
  228824. return c;
  228825. }
  228826. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  228827. {
  228828. [((NSCursor*) cursorHandle) release];
  228829. }
  228830. void MouseCursor::showInAllWindows() const
  228831. {
  228832. showInWindow (0);
  228833. }
  228834. void MouseCursor::showInWindow (ComponentPeer*) const
  228835. {
  228836. [((NSCursor*) getHandle()) set];
  228837. }
  228838. #else
  228839. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  228840. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  228841. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  228842. void MouseCursor::showInAllWindows() const {}
  228843. void MouseCursor::showInWindow (ComponentPeer*) const {}
  228844. #endif
  228845. #endif
  228846. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  228847. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  228848. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228849. // compiled on its own).
  228850. #if JUCE_INCLUDED_FILE
  228851. class NSViewComponentInternal : public ComponentMovementWatcher
  228852. {
  228853. Component* const owner;
  228854. NSViewComponentPeer* currentPeer;
  228855. bool wasShowing;
  228856. public:
  228857. NSView* const view;
  228858. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  228859. : ComponentMovementWatcher (owner_),
  228860. owner (owner_),
  228861. currentPeer (0),
  228862. wasShowing (false),
  228863. view (view_)
  228864. {
  228865. [view_ retain];
  228866. if (owner_->isShowing())
  228867. componentPeerChanged();
  228868. }
  228869. ~NSViewComponentInternal()
  228870. {
  228871. [view removeFromSuperview];
  228872. [view release];
  228873. }
  228874. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  228875. {
  228876. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  228877. // The ComponentMovementWatcher version of this method avoids calling
  228878. // us when the top-level comp is resized, but for an NSView we need to know this
  228879. // because with inverted co-ords, we need to update the position even if the
  228880. // top-left pos hasn't changed
  228881. if (comp.isOnDesktop() && wasResized)
  228882. componentMovedOrResized (wasMoved, wasResized);
  228883. }
  228884. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  228885. {
  228886. Component* const topComp = owner->getTopLevelComponent();
  228887. if (topComp->getPeer() != 0)
  228888. {
  228889. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  228890. NSRect r;
  228891. r.origin.x = (float) pos.getX();
  228892. r.origin.y = (float) pos.getY();
  228893. r.size.width = (float) owner->getWidth();
  228894. r.size.height = (float) owner->getHeight();
  228895. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  228896. [view setFrame: r];
  228897. }
  228898. }
  228899. void componentPeerChanged()
  228900. {
  228901. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  228902. if (currentPeer != peer)
  228903. {
  228904. [view removeFromSuperview];
  228905. currentPeer = peer;
  228906. if (peer != 0)
  228907. {
  228908. [peer->view addSubview: view];
  228909. componentMovedOrResized (false, false);
  228910. }
  228911. }
  228912. [view setHidden: ! owner->isShowing()];
  228913. }
  228914. void componentVisibilityChanged (Component&)
  228915. {
  228916. componentPeerChanged();
  228917. }
  228918. juce_UseDebuggingNewOperator
  228919. private:
  228920. NSViewComponentInternal (const NSViewComponentInternal&);
  228921. NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  228922. };
  228923. NSViewComponent::NSViewComponent()
  228924. {
  228925. }
  228926. NSViewComponent::~NSViewComponent()
  228927. {
  228928. }
  228929. void NSViewComponent::setView (void* view)
  228930. {
  228931. if (view != getView())
  228932. {
  228933. if (view != 0)
  228934. info = new NSViewComponentInternal ((NSView*) view, this);
  228935. else
  228936. info = 0;
  228937. }
  228938. }
  228939. void* NSViewComponent::getView() const
  228940. {
  228941. return info == 0 ? 0 : info->view;
  228942. }
  228943. void NSViewComponent::paint (Graphics&)
  228944. {
  228945. }
  228946. #endif
  228947. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  228948. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  228949. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228950. // compiled on its own).
  228951. #if JUCE_INCLUDED_FILE
  228952. AppleRemoteDevice::AppleRemoteDevice()
  228953. : device (0),
  228954. queue (0),
  228955. remoteId (0)
  228956. {
  228957. }
  228958. AppleRemoteDevice::~AppleRemoteDevice()
  228959. {
  228960. stop();
  228961. }
  228962. static io_object_t getAppleRemoteDevice()
  228963. {
  228964. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  228965. io_iterator_t iter = 0;
  228966. io_object_t iod = 0;
  228967. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  228968. && iter != 0)
  228969. {
  228970. iod = IOIteratorNext (iter);
  228971. }
  228972. IOObjectRelease (iter);
  228973. return iod;
  228974. }
  228975. static bool createAppleRemoteInterface (io_object_t iod, void** device)
  228976. {
  228977. jassert (*device == 0);
  228978. io_name_t classname;
  228979. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  228980. {
  228981. IOCFPlugInInterface** cfPlugInInterface = 0;
  228982. SInt32 score = 0;
  228983. if (IOCreatePlugInInterfaceForService (iod,
  228984. kIOHIDDeviceUserClientTypeID,
  228985. kIOCFPlugInInterfaceID,
  228986. &cfPlugInInterface,
  228987. &score) == kIOReturnSuccess)
  228988. {
  228989. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  228990. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  228991. device);
  228992. (void) hr;
  228993. (*cfPlugInInterface)->Release (cfPlugInInterface);
  228994. }
  228995. }
  228996. return *device != 0;
  228997. }
  228998. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  228999. {
  229000. if (queue != 0)
  229001. return true;
  229002. stop();
  229003. bool result = false;
  229004. io_object_t iod = getAppleRemoteDevice();
  229005. if (iod != 0)
  229006. {
  229007. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  229008. result = true;
  229009. else
  229010. stop();
  229011. IOObjectRelease (iod);
  229012. }
  229013. return result;
  229014. }
  229015. void AppleRemoteDevice::stop()
  229016. {
  229017. if (queue != 0)
  229018. {
  229019. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  229020. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  229021. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  229022. queue = 0;
  229023. }
  229024. if (device != 0)
  229025. {
  229026. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  229027. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  229028. device = 0;
  229029. }
  229030. }
  229031. bool AppleRemoteDevice::isActive() const
  229032. {
  229033. return queue != 0;
  229034. }
  229035. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  229036. {
  229037. if (result == kIOReturnSuccess)
  229038. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  229039. }
  229040. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  229041. {
  229042. Array <int> cookies;
  229043. CFArrayRef elements;
  229044. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  229045. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  229046. return false;
  229047. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  229048. {
  229049. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  229050. // get the cookie
  229051. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  229052. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  229053. continue;
  229054. long number;
  229055. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  229056. continue;
  229057. cookies.add ((int) number);
  229058. }
  229059. CFRelease (elements);
  229060. if ((*(IOHIDDeviceInterface**) device)
  229061. ->open ((IOHIDDeviceInterface**) device,
  229062. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  229063. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  229064. {
  229065. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  229066. if (queue != 0)
  229067. {
  229068. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  229069. for (int i = 0; i < cookies.size(); ++i)
  229070. {
  229071. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  229072. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  229073. }
  229074. CFRunLoopSourceRef eventSource;
  229075. if ((*(IOHIDQueueInterface**) queue)
  229076. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  229077. {
  229078. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  229079. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  229080. {
  229081. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  229082. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  229083. return true;
  229084. }
  229085. }
  229086. }
  229087. }
  229088. return false;
  229089. }
  229090. void AppleRemoteDevice::handleCallbackInternal()
  229091. {
  229092. int totalValues = 0;
  229093. AbsoluteTime nullTime = { 0, 0 };
  229094. char cookies [12];
  229095. int numCookies = 0;
  229096. while (numCookies < numElementsInArray (cookies))
  229097. {
  229098. IOHIDEventStruct e;
  229099. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  229100. break;
  229101. if ((int) e.elementCookie == 19)
  229102. {
  229103. remoteId = e.value;
  229104. buttonPressed (switched, false);
  229105. }
  229106. else
  229107. {
  229108. totalValues += e.value;
  229109. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  229110. }
  229111. }
  229112. cookies [numCookies++] = 0;
  229113. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  229114. static const char buttonPatterns[] =
  229115. {
  229116. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  229117. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  229118. 0x1f, 0x1d, 0x1c, 0x12, 0,
  229119. 0x1f, 0x1e, 0x1c, 0x12, 0,
  229120. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  229121. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  229122. 0x1f, 0x12, 0x04, 0x02, 0,
  229123. 0x1f, 0x12, 0x03, 0x02, 0,
  229124. 0x1f, 0x12, 0x1f, 0x12, 0,
  229125. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  229126. 19, 0
  229127. };
  229128. int buttonNum = (int) menuButton;
  229129. int i = 0;
  229130. while (i < numElementsInArray (buttonPatterns))
  229131. {
  229132. if (strcmp (cookies, buttonPatterns + i) == 0)
  229133. {
  229134. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  229135. break;
  229136. }
  229137. i += (int) strlen (buttonPatterns + i) + 1;
  229138. ++buttonNum;
  229139. }
  229140. }
  229141. #endif
  229142. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  229143. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  229144. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229145. // compiled on its own).
  229146. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  229147. #if JUCE_MAC
  229148. END_JUCE_NAMESPACE
  229149. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  229150. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  229151. {
  229152. CriticalSection* contextLock;
  229153. bool needsUpdate;
  229154. }
  229155. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  229156. - (bool) makeActive;
  229157. - (void) makeInactive;
  229158. - (void) reshape;
  229159. @end
  229160. @implementation ThreadSafeNSOpenGLView
  229161. - (id) initWithFrame: (NSRect) frameRect
  229162. pixelFormat: (NSOpenGLPixelFormat*) format
  229163. {
  229164. contextLock = new CriticalSection();
  229165. self = [super initWithFrame: frameRect pixelFormat: format];
  229166. if (self != nil)
  229167. [[NSNotificationCenter defaultCenter] addObserver: self
  229168. selector: @selector (_surfaceNeedsUpdate:)
  229169. name: NSViewGlobalFrameDidChangeNotification
  229170. object: self];
  229171. return self;
  229172. }
  229173. - (void) dealloc
  229174. {
  229175. [[NSNotificationCenter defaultCenter] removeObserver: self];
  229176. delete contextLock;
  229177. [super dealloc];
  229178. }
  229179. - (bool) makeActive
  229180. {
  229181. const ScopedLock sl (*contextLock);
  229182. if ([self openGLContext] == 0)
  229183. return false;
  229184. [[self openGLContext] makeCurrentContext];
  229185. if (needsUpdate)
  229186. {
  229187. [super update];
  229188. needsUpdate = false;
  229189. }
  229190. return true;
  229191. }
  229192. - (void) makeInactive
  229193. {
  229194. const ScopedLock sl (*contextLock);
  229195. [NSOpenGLContext clearCurrentContext];
  229196. }
  229197. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  229198. {
  229199. const ScopedLock sl (*contextLock);
  229200. needsUpdate = true;
  229201. }
  229202. - (void) update
  229203. {
  229204. const ScopedLock sl (*contextLock);
  229205. needsUpdate = true;
  229206. }
  229207. - (void) reshape
  229208. {
  229209. const ScopedLock sl (*contextLock);
  229210. needsUpdate = true;
  229211. }
  229212. @end
  229213. BEGIN_JUCE_NAMESPACE
  229214. class WindowedGLContext : public OpenGLContext
  229215. {
  229216. public:
  229217. WindowedGLContext (Component* const component,
  229218. const OpenGLPixelFormat& pixelFormat_,
  229219. NSOpenGLContext* sharedContext)
  229220. : renderContext (0),
  229221. pixelFormat (pixelFormat_)
  229222. {
  229223. jassert (component != 0);
  229224. NSOpenGLPixelFormatAttribute attribs [64];
  229225. int n = 0;
  229226. attribs[n++] = NSOpenGLPFADoubleBuffer;
  229227. attribs[n++] = NSOpenGLPFAAccelerated;
  229228. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  229229. attribs[n++] = NSOpenGLPFAColorSize;
  229230. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  229231. pixelFormat.greenBits,
  229232. pixelFormat.blueBits);
  229233. attribs[n++] = NSOpenGLPFAAlphaSize;
  229234. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  229235. attribs[n++] = NSOpenGLPFADepthSize;
  229236. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  229237. attribs[n++] = NSOpenGLPFAStencilSize;
  229238. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  229239. attribs[n++] = NSOpenGLPFAAccumSize;
  229240. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  229241. pixelFormat.accumulationBufferGreenBits,
  229242. pixelFormat.accumulationBufferBlueBits,
  229243. pixelFormat.accumulationBufferAlphaBits);
  229244. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  229245. attribs[n++] = NSOpenGLPFASampleBuffers;
  229246. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  229247. attribs[n++] = NSOpenGLPFAClosestPolicy;
  229248. attribs[n++] = NSOpenGLPFANoRecovery;
  229249. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  229250. NSOpenGLPixelFormat* format
  229251. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  229252. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  229253. pixelFormat: format];
  229254. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  229255. shareContext: sharedContext] autorelease];
  229256. const GLint swapInterval = 1;
  229257. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  229258. [view setOpenGLContext: renderContext];
  229259. [renderContext setView: view];
  229260. [format release];
  229261. viewHolder = new NSViewComponentInternal (view, component);
  229262. }
  229263. ~WindowedGLContext()
  229264. {
  229265. makeInactive();
  229266. [renderContext clearDrawable];
  229267. viewHolder = 0;
  229268. }
  229269. bool makeActive() const throw()
  229270. {
  229271. jassert (renderContext != 0);
  229272. [view makeActive];
  229273. return isActive();
  229274. }
  229275. bool makeInactive() const throw()
  229276. {
  229277. [view makeInactive];
  229278. return true;
  229279. }
  229280. bool isActive() const throw()
  229281. {
  229282. return [NSOpenGLContext currentContext] == renderContext;
  229283. }
  229284. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  229285. void* getRawContext() const throw() { return renderContext; }
  229286. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  229287. {
  229288. }
  229289. void swapBuffers()
  229290. {
  229291. [renderContext flushBuffer];
  229292. }
  229293. bool setSwapInterval (const int numFramesPerSwap)
  229294. {
  229295. [renderContext setValues: (const GLint*) &numFramesPerSwap
  229296. forParameter: NSOpenGLCPSwapInterval];
  229297. return true;
  229298. }
  229299. int getSwapInterval() const
  229300. {
  229301. GLint numFrames = 0;
  229302. [renderContext getValues: &numFrames
  229303. forParameter: NSOpenGLCPSwapInterval];
  229304. return numFrames;
  229305. }
  229306. void repaint()
  229307. {
  229308. // we need to invalidate the juce view that holds this gl view, to make it
  229309. // cause a repaint callback
  229310. NSView* v = (NSView*) viewHolder->view;
  229311. NSRect r = [v frame];
  229312. // bit of a bodge here.. if we only invalidate the area of the gl component,
  229313. // it's completely covered by the NSOpenGLView, so the OS throws away the
  229314. // repaint message, thus never causing our paint() callback, and never repainting
  229315. // the comp. So invalidating just a little bit around the edge helps..
  229316. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  229317. }
  229318. void* getNativeWindowHandle() const { return viewHolder->view; }
  229319. juce_UseDebuggingNewOperator
  229320. NSOpenGLContext* renderContext;
  229321. ThreadSafeNSOpenGLView* view;
  229322. private:
  229323. OpenGLPixelFormat pixelFormat;
  229324. ScopedPointer <NSViewComponentInternal> viewHolder;
  229325. WindowedGLContext (const WindowedGLContext&);
  229326. WindowedGLContext& operator= (const WindowedGLContext&);
  229327. };
  229328. OpenGLContext* OpenGLComponent::createContext()
  229329. {
  229330. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  229331. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  229332. return (c->renderContext != 0) ? c.release() : 0;
  229333. }
  229334. void* OpenGLComponent::getNativeWindowHandle() const
  229335. {
  229336. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  229337. : 0;
  229338. }
  229339. void juce_glViewport (const int w, const int h)
  229340. {
  229341. glViewport (0, 0, w, h);
  229342. }
  229343. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  229344. OwnedArray <OpenGLPixelFormat>& results)
  229345. {
  229346. /* GLint attribs [64];
  229347. int n = 0;
  229348. attribs[n++] = AGL_RGBA;
  229349. attribs[n++] = AGL_DOUBLEBUFFER;
  229350. attribs[n++] = AGL_ACCELERATED;
  229351. attribs[n++] = AGL_NO_RECOVERY;
  229352. attribs[n++] = AGL_NONE;
  229353. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  229354. while (p != 0)
  229355. {
  229356. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  229357. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  229358. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  229359. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  229360. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  229361. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  229362. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  229363. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  229364. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  229365. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  229366. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  229367. results.add (pf);
  229368. p = aglNextPixelFormat (p);
  229369. }*/
  229370. //jassertfalse //xxx can't see how you do this in cocoa!
  229371. }
  229372. #else
  229373. END_JUCE_NAMESPACE
  229374. @interface JuceGLView : UIView
  229375. {
  229376. }
  229377. + (Class) layerClass;
  229378. @end
  229379. @implementation JuceGLView
  229380. + (Class) layerClass
  229381. {
  229382. return [CAEAGLLayer class];
  229383. }
  229384. @end
  229385. BEGIN_JUCE_NAMESPACE
  229386. class GLESContext : public OpenGLContext
  229387. {
  229388. public:
  229389. GLESContext (UIViewComponentPeer* peer,
  229390. Component* const component_,
  229391. const OpenGLPixelFormat& pixelFormat_,
  229392. const GLESContext* const sharedContext,
  229393. NSUInteger apiType)
  229394. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  229395. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  229396. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  229397. {
  229398. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  229399. view.opaque = YES;
  229400. view.hidden = NO;
  229401. view.backgroundColor = [UIColor blackColor];
  229402. view.userInteractionEnabled = NO;
  229403. glLayer = (CAEAGLLayer*) [view layer];
  229404. [peer->view addSubview: view];
  229405. if (sharedContext != 0)
  229406. context = [[EAGLContext alloc] initWithAPI: apiType
  229407. sharegroup: [sharedContext->context sharegroup]];
  229408. else
  229409. context = [[EAGLContext alloc] initWithAPI: apiType];
  229410. createGLBuffers();
  229411. }
  229412. ~GLESContext()
  229413. {
  229414. makeInactive();
  229415. [context release];
  229416. [view removeFromSuperview];
  229417. [view release];
  229418. freeGLBuffers();
  229419. }
  229420. bool makeActive() const throw()
  229421. {
  229422. jassert (context != 0);
  229423. [EAGLContext setCurrentContext: context];
  229424. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  229425. return true;
  229426. }
  229427. void swapBuffers()
  229428. {
  229429. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  229430. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  229431. }
  229432. bool makeInactive() const throw()
  229433. {
  229434. return [EAGLContext setCurrentContext: nil];
  229435. }
  229436. bool isActive() const throw()
  229437. {
  229438. return [EAGLContext currentContext] == context;
  229439. }
  229440. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  229441. void* getRawContext() const throw() { return glLayer; }
  229442. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  229443. {
  229444. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  229445. if (lastWidth != w || lastHeight != h)
  229446. {
  229447. lastWidth = w;
  229448. lastHeight = h;
  229449. freeGLBuffers();
  229450. createGLBuffers();
  229451. }
  229452. }
  229453. bool setSwapInterval (const int numFramesPerSwap)
  229454. {
  229455. numFrames = numFramesPerSwap;
  229456. return true;
  229457. }
  229458. int getSwapInterval() const
  229459. {
  229460. return numFrames;
  229461. }
  229462. void repaint()
  229463. {
  229464. }
  229465. void createGLBuffers()
  229466. {
  229467. makeActive();
  229468. glGenFramebuffersOES (1, &frameBufferHandle);
  229469. glGenRenderbuffersOES (1, &colorBufferHandle);
  229470. glGenRenderbuffersOES (1, &depthBufferHandle);
  229471. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  229472. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  229473. GLint width, height;
  229474. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  229475. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  229476. if (useDepthBuffer)
  229477. {
  229478. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  229479. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  229480. }
  229481. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  229482. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  229483. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  229484. if (useDepthBuffer)
  229485. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  229486. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  229487. }
  229488. void freeGLBuffers()
  229489. {
  229490. if (frameBufferHandle != 0)
  229491. {
  229492. glDeleteFramebuffersOES (1, &frameBufferHandle);
  229493. frameBufferHandle = 0;
  229494. }
  229495. if (colorBufferHandle != 0)
  229496. {
  229497. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  229498. colorBufferHandle = 0;
  229499. }
  229500. if (depthBufferHandle != 0)
  229501. {
  229502. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  229503. depthBufferHandle = 0;
  229504. }
  229505. }
  229506. juce_UseDebuggingNewOperator
  229507. private:
  229508. Component::SafePointer<Component> component;
  229509. OpenGLPixelFormat pixelFormat;
  229510. JuceGLView* view;
  229511. CAEAGLLayer* glLayer;
  229512. EAGLContext* context;
  229513. bool useDepthBuffer;
  229514. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  229515. int numFrames;
  229516. int lastWidth, lastHeight;
  229517. GLESContext (const GLESContext&);
  229518. GLESContext& operator= (const GLESContext&);
  229519. };
  229520. OpenGLContext* OpenGLComponent::createContext()
  229521. {
  229522. ScopedAutoReleasePool pool;
  229523. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  229524. if (peer != 0)
  229525. return new GLESContext (peer, this, preferredPixelFormat,
  229526. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  229527. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  229528. return 0;
  229529. }
  229530. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  229531. OwnedArray <OpenGLPixelFormat>& /*results*/)
  229532. {
  229533. }
  229534. void juce_glViewport (const int w, const int h)
  229535. {
  229536. glViewport (0, 0, w, h);
  229537. }
  229538. #endif
  229539. #endif
  229540. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  229541. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  229542. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229543. // compiled on its own).
  229544. #if JUCE_INCLUDED_FILE
  229545. class JuceMainMenuHandler;
  229546. END_JUCE_NAMESPACE
  229547. using namespace JUCE_NAMESPACE;
  229548. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  229549. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  229550. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  229551. #else
  229552. @interface JuceMenuCallback : NSObject
  229553. #endif
  229554. {
  229555. JuceMainMenuHandler* owner;
  229556. }
  229557. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  229558. - (void) dealloc;
  229559. - (void) menuItemInvoked: (id) menu;
  229560. - (void) menuNeedsUpdate: (NSMenu*) menu;
  229561. @end
  229562. BEGIN_JUCE_NAMESPACE
  229563. class JuceMainMenuHandler : private MenuBarModelListener,
  229564. private DeletedAtShutdown
  229565. {
  229566. public:
  229567. static JuceMainMenuHandler* instance;
  229568. JuceMainMenuHandler()
  229569. : currentModel (0),
  229570. lastUpdateTime (0)
  229571. {
  229572. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  229573. }
  229574. ~JuceMainMenuHandler()
  229575. {
  229576. setMenu (0);
  229577. jassert (instance == this);
  229578. instance = 0;
  229579. [callback release];
  229580. }
  229581. void setMenu (MenuBarModel* const newMenuBarModel)
  229582. {
  229583. if (currentModel != newMenuBarModel)
  229584. {
  229585. if (currentModel != 0)
  229586. currentModel->removeListener (this);
  229587. currentModel = newMenuBarModel;
  229588. if (currentModel != 0)
  229589. currentModel->addListener (this);
  229590. menuBarItemsChanged (0);
  229591. }
  229592. }
  229593. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  229594. const String& name, const int menuId, const int tag)
  229595. {
  229596. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  229597. action: nil
  229598. keyEquivalent: @""];
  229599. [item setTag: tag];
  229600. NSMenu* sub = createMenu (child, name, menuId, tag);
  229601. [parent setSubmenu: sub forItem: item];
  229602. [sub setAutoenablesItems: false];
  229603. [sub release];
  229604. }
  229605. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  229606. const String& name, const int menuId, const int tag)
  229607. {
  229608. [parentItem setTag: tag];
  229609. NSMenu* menu = [parentItem submenu];
  229610. [menu setTitle: juceStringToNS (name)];
  229611. while ([menu numberOfItems] > 0)
  229612. [menu removeItemAtIndex: 0];
  229613. PopupMenu::MenuItemIterator iter (menuToCopy);
  229614. while (iter.next())
  229615. addMenuItem (iter, menu, menuId, tag);
  229616. [menu setAutoenablesItems: false];
  229617. [menu update];
  229618. }
  229619. void menuBarItemsChanged (MenuBarModel*)
  229620. {
  229621. lastUpdateTime = Time::getMillisecondCounter();
  229622. StringArray menuNames;
  229623. if (currentModel != 0)
  229624. menuNames = currentModel->getMenuBarNames();
  229625. NSMenu* menuBar = [NSApp mainMenu];
  229626. while ([menuBar numberOfItems] > 1 + menuNames.size())
  229627. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  229628. int menuId = 1;
  229629. for (int i = 0; i < menuNames.size(); ++i)
  229630. {
  229631. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  229632. if (i >= [menuBar numberOfItems] - 1)
  229633. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  229634. else
  229635. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  229636. }
  229637. }
  229638. static void flashMenuBar (NSMenu* menu)
  229639. {
  229640. if ([[menu title] isEqualToString: @"Apple"])
  229641. return;
  229642. [menu retain];
  229643. const unichar f35Key = NSF35FunctionKey;
  229644. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  229645. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  229646. action: nil
  229647. keyEquivalent: f35String];
  229648. [item setTarget: nil];
  229649. [menu insertItem: item atIndex: [menu numberOfItems]];
  229650. [item release];
  229651. if ([menu indexOfItem: item] >= 0)
  229652. {
  229653. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  229654. location: NSZeroPoint
  229655. modifierFlags: NSCommandKeyMask
  229656. timestamp: 0
  229657. windowNumber: 0
  229658. context: [NSGraphicsContext currentContext]
  229659. characters: f35String
  229660. charactersIgnoringModifiers: f35String
  229661. isARepeat: NO
  229662. keyCode: 0];
  229663. [menu performKeyEquivalent: f35Event];
  229664. if ([menu indexOfItem: item] >= 0)
  229665. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  229666. }
  229667. [menu release];
  229668. }
  229669. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  229670. {
  229671. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  229672. {
  229673. NSMenuItem* m = [menu itemAtIndex: i];
  229674. if ([m tag] == info.commandID)
  229675. return m;
  229676. if ([m submenu] != 0)
  229677. {
  229678. NSMenuItem* found = findMenuItem ([m submenu], info);
  229679. if (found != 0)
  229680. return found;
  229681. }
  229682. }
  229683. return 0;
  229684. }
  229685. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  229686. {
  229687. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  229688. if (item != 0)
  229689. flashMenuBar ([item menu]);
  229690. }
  229691. void updateMenus()
  229692. {
  229693. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  229694. menuBarItemsChanged (0);
  229695. }
  229696. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  229697. {
  229698. if (currentModel != 0)
  229699. {
  229700. if (commandManager != 0)
  229701. {
  229702. ApplicationCommandTarget::InvocationInfo info (commandId);
  229703. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  229704. commandManager->invoke (info, true);
  229705. }
  229706. currentModel->menuItemSelected (commandId, topLevelIndex);
  229707. }
  229708. }
  229709. MenuBarModel* currentModel;
  229710. uint32 lastUpdateTime;
  229711. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  229712. const int topLevelMenuId, const int topLevelIndex)
  229713. {
  229714. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  229715. if (text == 0)
  229716. text = @"";
  229717. if (iter.isSeparator)
  229718. {
  229719. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  229720. }
  229721. else if (iter.isSectionHeader)
  229722. {
  229723. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  229724. action: nil
  229725. keyEquivalent: @""];
  229726. [item setEnabled: false];
  229727. }
  229728. else if (iter.subMenu != 0)
  229729. {
  229730. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  229731. action: nil
  229732. keyEquivalent: @""];
  229733. [item setTag: iter.itemId];
  229734. [item setEnabled: iter.isEnabled];
  229735. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  229736. [sub setDelegate: nil];
  229737. [menuToAddTo setSubmenu: sub forItem: item];
  229738. [sub release];
  229739. }
  229740. else
  229741. {
  229742. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  229743. action: @selector (menuItemInvoked:)
  229744. keyEquivalent: @""];
  229745. [item setTag: iter.itemId];
  229746. [item setEnabled: iter.isEnabled];
  229747. [item setState: iter.isTicked ? NSOnState : NSOffState];
  229748. [item setTarget: (id) callback];
  229749. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  229750. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  229751. [item setRepresentedObject: info];
  229752. if (iter.commandManager != 0)
  229753. {
  229754. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  229755. ->getKeyPressesAssignedToCommand (iter.itemId));
  229756. if (keyPresses.size() > 0)
  229757. {
  229758. const KeyPress& kp = keyPresses.getReference(0);
  229759. if (kp.getKeyCode() != KeyPress::backspaceKey
  229760. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  229761. // every time you press the key while editing text)
  229762. {
  229763. juce_wchar key = kp.getTextCharacter();
  229764. if (kp.getKeyCode() == KeyPress::backspaceKey)
  229765. key = NSBackspaceCharacter;
  229766. else if (kp.getKeyCode() == KeyPress::deleteKey)
  229767. key = NSDeleteCharacter;
  229768. else if (key == 0)
  229769. key = (juce_wchar) kp.getKeyCode();
  229770. unsigned int mods = 0;
  229771. if (kp.getModifiers().isShiftDown())
  229772. mods |= NSShiftKeyMask;
  229773. if (kp.getModifiers().isCtrlDown())
  229774. mods |= NSControlKeyMask;
  229775. if (kp.getModifiers().isAltDown())
  229776. mods |= NSAlternateKeyMask;
  229777. if (kp.getModifiers().isCommandDown())
  229778. mods |= NSCommandKeyMask;
  229779. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  229780. [item setKeyEquivalentModifierMask: mods];
  229781. }
  229782. }
  229783. }
  229784. }
  229785. }
  229786. JuceMenuCallback* callback;
  229787. private:
  229788. NSMenu* createMenu (const PopupMenu menu,
  229789. const String& menuName,
  229790. const int topLevelMenuId,
  229791. const int topLevelIndex)
  229792. {
  229793. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  229794. [m setAutoenablesItems: false];
  229795. [m setDelegate: callback];
  229796. PopupMenu::MenuItemIterator iter (menu);
  229797. while (iter.next())
  229798. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  229799. [m update];
  229800. return m;
  229801. }
  229802. };
  229803. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  229804. END_JUCE_NAMESPACE
  229805. @implementation JuceMenuCallback
  229806. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  229807. {
  229808. [super init];
  229809. owner = owner_;
  229810. return self;
  229811. }
  229812. - (void) dealloc
  229813. {
  229814. [super dealloc];
  229815. }
  229816. - (void) menuItemInvoked: (id) menu
  229817. {
  229818. NSMenuItem* item = (NSMenuItem*) menu;
  229819. if ([[item representedObject] isKindOfClass: [NSArray class]])
  229820. {
  229821. // 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
  229822. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  229823. // into the focused component and let it trigger the menu item indirectly.
  229824. NSEvent* e = [NSApp currentEvent];
  229825. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  229826. {
  229827. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  229828. {
  229829. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  229830. if (peer != 0)
  229831. {
  229832. if ([e type] == NSKeyDown)
  229833. peer->redirectKeyDown (e);
  229834. else
  229835. peer->redirectKeyUp (e);
  229836. return;
  229837. }
  229838. }
  229839. }
  229840. NSArray* info = (NSArray*) [item representedObject];
  229841. owner->invoke ((int) [item tag],
  229842. (ApplicationCommandManager*) (pointer_sized_int)
  229843. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  229844. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  229845. }
  229846. }
  229847. - (void) menuNeedsUpdate: (NSMenu*) menu;
  229848. {
  229849. (void) menu;
  229850. if (JuceMainMenuHandler::instance != 0)
  229851. JuceMainMenuHandler::instance->updateMenus();
  229852. }
  229853. @end
  229854. BEGIN_JUCE_NAMESPACE
  229855. static NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName,
  229856. const PopupMenu* extraItems)
  229857. {
  229858. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  229859. {
  229860. PopupMenu::MenuItemIterator iter (*extraItems);
  229861. while (iter.next())
  229862. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  229863. [menu addItem: [NSMenuItem separatorItem]];
  229864. }
  229865. NSMenuItem* item;
  229866. // Services...
  229867. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  229868. action: nil keyEquivalent: @""];
  229869. [menu addItem: item];
  229870. [item release];
  229871. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  229872. [menu setSubmenu: servicesMenu forItem: item];
  229873. [NSApp setServicesMenu: servicesMenu];
  229874. [servicesMenu release];
  229875. [menu addItem: [NSMenuItem separatorItem]];
  229876. // Hide + Show stuff...
  229877. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  229878. action: @selector (hide:) keyEquivalent: @"h"];
  229879. [item setTarget: NSApp];
  229880. [menu addItem: item];
  229881. [item release];
  229882. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  229883. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  229884. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  229885. [item setTarget: NSApp];
  229886. [menu addItem: item];
  229887. [item release];
  229888. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  229889. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  229890. [item setTarget: NSApp];
  229891. [menu addItem: item];
  229892. [item release];
  229893. [menu addItem: [NSMenuItem separatorItem]];
  229894. // Quit item....
  229895. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  229896. action: @selector (terminate:) keyEquivalent: @"q"];
  229897. [item setTarget: NSApp];
  229898. [menu addItem: item];
  229899. [item release];
  229900. return menu;
  229901. }
  229902. // Since our app has no NIB, this initialises a standard app menu...
  229903. static void rebuildMainMenu (const PopupMenu* extraItems)
  229904. {
  229905. // this can't be used in a plugin!
  229906. jassert (JUCEApplication::getInstance() != 0);
  229907. if (JUCEApplication::getInstance() != 0)
  229908. {
  229909. const ScopedAutoReleasePool pool;
  229910. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  229911. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  229912. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  229913. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  229914. [mainMenu setSubmenu: appMenu forItem: item];
  229915. [NSApp setMainMenu: mainMenu];
  229916. createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  229917. [appMenu release];
  229918. [mainMenu release];
  229919. }
  229920. }
  229921. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  229922. const PopupMenu* extraAppleMenuItems)
  229923. {
  229924. if (getMacMainMenu() != newMenuBarModel)
  229925. {
  229926. const ScopedAutoReleasePool pool;
  229927. if (newMenuBarModel == 0)
  229928. {
  229929. delete JuceMainMenuHandler::instance;
  229930. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  229931. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  229932. extraAppleMenuItems = 0;
  229933. }
  229934. else
  229935. {
  229936. if (JuceMainMenuHandler::instance == 0)
  229937. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  229938. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  229939. }
  229940. }
  229941. rebuildMainMenu (extraAppleMenuItems);
  229942. if (newMenuBarModel != 0)
  229943. newMenuBarModel->menuItemsChanged();
  229944. }
  229945. MenuBarModel* MenuBarModel::getMacMainMenu()
  229946. {
  229947. return JuceMainMenuHandler::instance != 0
  229948. ? JuceMainMenuHandler::instance->currentModel : 0;
  229949. }
  229950. void initialiseMainMenu()
  229951. {
  229952. if (JUCEApplication::getInstance() != 0) // only needed in an app
  229953. rebuildMainMenu (0);
  229954. }
  229955. #endif
  229956. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  229957. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  229958. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229959. // compiled on its own).
  229960. #if JUCE_INCLUDED_FILE
  229961. #if JUCE_MAC
  229962. END_JUCE_NAMESPACE
  229963. using namespace JUCE_NAMESPACE;
  229964. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  229965. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  229966. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  229967. #else
  229968. @interface JuceFileChooserDelegate : NSObject
  229969. #endif
  229970. {
  229971. StringArray* filters;
  229972. }
  229973. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  229974. - (void) dealloc;
  229975. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  229976. @end
  229977. @implementation JuceFileChooserDelegate
  229978. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  229979. {
  229980. [super init];
  229981. filters = filters_;
  229982. return self;
  229983. }
  229984. - (void) dealloc
  229985. {
  229986. delete filters;
  229987. [super dealloc];
  229988. }
  229989. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  229990. {
  229991. (void) sender;
  229992. const File f (nsStringToJuce (filename));
  229993. for (int i = filters->size(); --i >= 0;)
  229994. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  229995. return true;
  229996. return f.isDirectory();
  229997. }
  229998. @end
  229999. BEGIN_JUCE_NAMESPACE
  230000. void FileChooser::showPlatformDialog (Array<File>& results,
  230001. const String& title,
  230002. const File& currentFileOrDirectory,
  230003. const String& filter,
  230004. bool selectsDirectory,
  230005. bool selectsFiles,
  230006. bool isSaveDialogue,
  230007. bool warnAboutOverwritingExistingFiles,
  230008. bool selectMultipleFiles,
  230009. FilePreviewComponent* extraInfoComponent)
  230010. {
  230011. const ScopedAutoReleasePool pool;
  230012. StringArray* filters = new StringArray();
  230013. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  230014. filters->trim();
  230015. filters->removeEmptyStrings();
  230016. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  230017. [delegate autorelease];
  230018. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  230019. : [NSOpenPanel openPanel];
  230020. [panel setTitle: juceStringToNS (title)];
  230021. if (! isSaveDialogue)
  230022. {
  230023. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  230024. [openPanel setCanChooseDirectories: selectsDirectory];
  230025. [openPanel setCanChooseFiles: selectsFiles];
  230026. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  230027. }
  230028. [panel setDelegate: delegate];
  230029. if (isSaveDialogue || selectsDirectory)
  230030. [panel setCanCreateDirectories: YES];
  230031. String directory, filename;
  230032. if (currentFileOrDirectory.isDirectory())
  230033. {
  230034. directory = currentFileOrDirectory.getFullPathName();
  230035. }
  230036. else
  230037. {
  230038. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  230039. filename = currentFileOrDirectory.getFileName();
  230040. }
  230041. if ([panel runModalForDirectory: juceStringToNS (directory)
  230042. file: juceStringToNS (filename)]
  230043. == NSOKButton)
  230044. {
  230045. if (isSaveDialogue)
  230046. {
  230047. results.add (File (nsStringToJuce ([panel filename])));
  230048. }
  230049. else
  230050. {
  230051. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  230052. NSArray* urls = [openPanel filenames];
  230053. for (unsigned int i = 0; i < [urls count]; ++i)
  230054. {
  230055. NSString* f = [urls objectAtIndex: i];
  230056. results.add (File (nsStringToJuce (f)));
  230057. }
  230058. }
  230059. }
  230060. [panel setDelegate: nil];
  230061. }
  230062. #else
  230063. void FileChooser::showPlatformDialog (Array<File>& results,
  230064. const String& title,
  230065. const File& currentFileOrDirectory,
  230066. const String& filter,
  230067. bool selectsDirectory,
  230068. bool selectsFiles,
  230069. bool isSaveDialogue,
  230070. bool warnAboutOverwritingExistingFiles,
  230071. bool selectMultipleFiles,
  230072. FilePreviewComponent* extraInfoComponent)
  230073. {
  230074. const ScopedAutoReleasePool pool;
  230075. jassertfalse //xxx to do
  230076. }
  230077. #endif
  230078. #endif
  230079. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  230080. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  230081. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230082. // compiled on its own).
  230083. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  230084. END_JUCE_NAMESPACE
  230085. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  230086. @interface NonInterceptingQTMovieView : QTMovieView
  230087. {
  230088. }
  230089. - (id) initWithFrame: (NSRect) frame;
  230090. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  230091. - (NSView*) hitTest: (NSPoint) p;
  230092. @end
  230093. @implementation NonInterceptingQTMovieView
  230094. - (id) initWithFrame: (NSRect) frame
  230095. {
  230096. self = [super initWithFrame: frame];
  230097. [self setNextResponder: [self superview]];
  230098. return self;
  230099. }
  230100. - (void) dealloc
  230101. {
  230102. [super dealloc];
  230103. }
  230104. - (NSView*) hitTest: (NSPoint) point
  230105. {
  230106. return [self isControllerVisible] ? [super hitTest: point] : nil;
  230107. }
  230108. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  230109. {
  230110. return YES;
  230111. }
  230112. @end
  230113. BEGIN_JUCE_NAMESPACE
  230114. #define theMovie (static_cast <QTMovie*> (movie))
  230115. QuickTimeMovieComponent::QuickTimeMovieComponent()
  230116. : movie (0)
  230117. {
  230118. setOpaque (true);
  230119. setVisible (true);
  230120. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  230121. setView (view);
  230122. [view release];
  230123. }
  230124. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  230125. {
  230126. closeMovie();
  230127. setView (0);
  230128. }
  230129. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  230130. {
  230131. return true;
  230132. }
  230133. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  230134. {
  230135. // unfortunately, QTMovie objects can only be created on the main thread..
  230136. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  230137. QTMovie* movie = 0;
  230138. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  230139. if (fin != 0)
  230140. {
  230141. movieFile = fin->getFile();
  230142. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  230143. error: nil];
  230144. }
  230145. else
  230146. {
  230147. MemoryBlock temp;
  230148. movieStream->readIntoMemoryBlock (temp);
  230149. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  230150. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  230151. {
  230152. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  230153. length: temp.getSize()]
  230154. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  230155. MIMEType: @""]
  230156. error: nil];
  230157. if (movie != 0)
  230158. break;
  230159. }
  230160. }
  230161. return movie;
  230162. }
  230163. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  230164. const bool isControllerVisible_)
  230165. {
  230166. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  230167. }
  230168. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  230169. const bool controllerVisible_)
  230170. {
  230171. closeMovie();
  230172. if (getPeer() == 0)
  230173. {
  230174. // To open a movie, this component must be visible inside a functioning window, so that
  230175. // the QT control can be assigned to the window.
  230176. jassertfalse
  230177. return false;
  230178. }
  230179. movie = openMovieFromStream (movieStream, movieFile);
  230180. [theMovie retain];
  230181. QTMovieView* view = (QTMovieView*) getView();
  230182. [view setMovie: theMovie];
  230183. [view setControllerVisible: controllerVisible_];
  230184. setLooping (looping);
  230185. return movie != nil;
  230186. }
  230187. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  230188. const bool isControllerVisible_)
  230189. {
  230190. // unfortunately, QTMovie objects can only be created on the main thread..
  230191. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  230192. closeMovie();
  230193. if (getPeer() == 0)
  230194. {
  230195. // To open a movie, this component must be visible inside a functioning window, so that
  230196. // the QT control can be assigned to the window.
  230197. jassertfalse
  230198. return false;
  230199. }
  230200. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  230201. NSError* err;
  230202. if ([QTMovie canInitWithURL: url])
  230203. movie = [QTMovie movieWithURL: url error: &err];
  230204. [theMovie retain];
  230205. QTMovieView* view = (QTMovieView*) getView();
  230206. [view setMovie: theMovie];
  230207. [view setControllerVisible: controllerVisible];
  230208. setLooping (looping);
  230209. return movie != nil;
  230210. }
  230211. void QuickTimeMovieComponent::closeMovie()
  230212. {
  230213. stop();
  230214. QTMovieView* view = (QTMovieView*) getView();
  230215. [view setMovie: nil];
  230216. [theMovie release];
  230217. movie = 0;
  230218. movieFile = File::nonexistent;
  230219. }
  230220. bool QuickTimeMovieComponent::isMovieOpen() const
  230221. {
  230222. return movie != nil;
  230223. }
  230224. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  230225. {
  230226. return movieFile;
  230227. }
  230228. void QuickTimeMovieComponent::play()
  230229. {
  230230. [theMovie play];
  230231. }
  230232. void QuickTimeMovieComponent::stop()
  230233. {
  230234. [theMovie stop];
  230235. }
  230236. bool QuickTimeMovieComponent::isPlaying() const
  230237. {
  230238. return movie != 0 && [theMovie rate] != 0;
  230239. }
  230240. void QuickTimeMovieComponent::setPosition (const double seconds)
  230241. {
  230242. if (movie != 0)
  230243. {
  230244. QTTime t;
  230245. t.timeValue = (uint64) (100000.0 * seconds);
  230246. t.timeScale = 100000;
  230247. t.flags = 0;
  230248. [theMovie setCurrentTime: t];
  230249. }
  230250. }
  230251. double QuickTimeMovieComponent::getPosition() const
  230252. {
  230253. if (movie == 0)
  230254. return 0.0;
  230255. QTTime t = [theMovie currentTime];
  230256. return t.timeValue / (double) t.timeScale;
  230257. }
  230258. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  230259. {
  230260. [theMovie setRate: newSpeed];
  230261. }
  230262. double QuickTimeMovieComponent::getMovieDuration() const
  230263. {
  230264. if (movie == 0)
  230265. return 0.0;
  230266. QTTime t = [theMovie duration];
  230267. return t.timeValue / (double) t.timeScale;
  230268. }
  230269. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  230270. {
  230271. looping = shouldLoop;
  230272. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  230273. forKey: QTMovieLoopsAttribute];
  230274. }
  230275. bool QuickTimeMovieComponent::isLooping() const
  230276. {
  230277. return looping;
  230278. }
  230279. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  230280. {
  230281. [theMovie setVolume: newVolume];
  230282. }
  230283. float QuickTimeMovieComponent::getMovieVolume() const
  230284. {
  230285. return movie != 0 ? [theMovie volume] : 0.0f;
  230286. }
  230287. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  230288. {
  230289. width = 0;
  230290. height = 0;
  230291. if (movie != 0)
  230292. {
  230293. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  230294. width = (int) s.width;
  230295. height = (int) s.height;
  230296. }
  230297. }
  230298. void QuickTimeMovieComponent::paint (Graphics& g)
  230299. {
  230300. if (movie == 0)
  230301. g.fillAll (Colours::black);
  230302. }
  230303. bool QuickTimeMovieComponent::isControllerVisible() const
  230304. {
  230305. return controllerVisible;
  230306. }
  230307. void QuickTimeMovieComponent::goToStart()
  230308. {
  230309. setPosition (0.0);
  230310. }
  230311. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  230312. const RectanglePlacement& placement)
  230313. {
  230314. int normalWidth, normalHeight;
  230315. getMovieNormalSize (normalWidth, normalHeight);
  230316. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  230317. {
  230318. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  230319. placement.applyTo (x, y, w, h,
  230320. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  230321. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  230322. if (w > 0 && h > 0)
  230323. {
  230324. setBounds (roundToInt (x), roundToInt (y),
  230325. roundToInt (w), roundToInt (h));
  230326. }
  230327. }
  230328. else
  230329. {
  230330. setBounds (spaceToFitWithin);
  230331. }
  230332. }
  230333. #if ! (JUCE_MAC && JUCE_64BIT)
  230334. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  230335. {
  230336. if (movieStream == 0)
  230337. return false;
  230338. File file;
  230339. QTMovie* movie = openMovieFromStream (movieStream, file);
  230340. if (movie != nil)
  230341. result = [movie quickTimeMovie];
  230342. return movie != nil;
  230343. }
  230344. #endif
  230345. #endif
  230346. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  230347. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  230348. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230349. // compiled on its own).
  230350. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  230351. const int kilobytesPerSecond1x = 176;
  230352. END_JUCE_NAMESPACE
  230353. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  230354. @interface OpenDiskDevice : NSObject
  230355. {
  230356. @public
  230357. DRDevice* device;
  230358. NSMutableArray* tracks;
  230359. bool underrunProtection;
  230360. }
  230361. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  230362. - (void) dealloc;
  230363. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  230364. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  230365. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  230366. @end
  230367. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  230368. @interface AudioTrackProducer : NSObject
  230369. {
  230370. JUCE_NAMESPACE::AudioSource* source;
  230371. int readPosition, lengthInFrames;
  230372. }
  230373. - (AudioTrackProducer*) init: (int) lengthInFrames;
  230374. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  230375. - (void) dealloc;
  230376. - (void) setupTrackProperties: (DRTrack*) track;
  230377. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  230378. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  230379. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  230380. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  230381. toMedia:(NSDictionary*)mediaInfo;
  230382. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  230383. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  230384. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  230385. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  230386. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  230387. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  230388. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  230389. ioFlags:(uint32_t*)flags;
  230390. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  230391. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  230392. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  230393. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  230394. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  230395. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  230396. ioFlags:(uint32_t*)flags;
  230397. @end
  230398. @implementation OpenDiskDevice
  230399. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  230400. {
  230401. [super init];
  230402. device = device_;
  230403. tracks = [[NSMutableArray alloc] init];
  230404. underrunProtection = true;
  230405. return self;
  230406. }
  230407. - (void) dealloc
  230408. {
  230409. [tracks release];
  230410. [super dealloc];
  230411. }
  230412. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  230413. {
  230414. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  230415. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  230416. [p setupTrackProperties: t];
  230417. [tracks addObject: t];
  230418. [t release];
  230419. [p release];
  230420. }
  230421. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  230422. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  230423. {
  230424. DRBurn* burn = [DRBurn burnForDevice: device];
  230425. if (! [device acquireExclusiveAccess])
  230426. {
  230427. *error = "Couldn't open or write to the CD device";
  230428. return;
  230429. }
  230430. [device acquireMediaReservation];
  230431. NSMutableDictionary* d = [[burn properties] mutableCopy];
  230432. [d autorelease];
  230433. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  230434. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  230435. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  230436. if (burnSpeed > 0)
  230437. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  230438. if (! underrunProtection)
  230439. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  230440. [burn setProperties: d];
  230441. [burn writeLayout: tracks];
  230442. for (;;)
  230443. {
  230444. JUCE_NAMESPACE::Thread::sleep (300);
  230445. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  230446. if (listener != 0 && listener->audioCDBurnProgress (progress))
  230447. {
  230448. [burn abort];
  230449. *error = "User cancelled the write operation";
  230450. break;
  230451. }
  230452. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  230453. {
  230454. *error = "Write operation failed";
  230455. break;
  230456. }
  230457. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  230458. {
  230459. break;
  230460. }
  230461. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  230462. objectForKey: DRErrorStatusErrorStringKey];
  230463. if ([err length] > 0)
  230464. {
  230465. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  230466. break;
  230467. }
  230468. }
  230469. [device releaseMediaReservation];
  230470. [device releaseExclusiveAccess];
  230471. }
  230472. @end
  230473. @implementation AudioTrackProducer
  230474. - (AudioTrackProducer*) init: (int) lengthInFrames_
  230475. {
  230476. lengthInFrames = lengthInFrames_;
  230477. readPosition = 0;
  230478. return self;
  230479. }
  230480. - (void) setupTrackProperties: (DRTrack*) track
  230481. {
  230482. NSMutableDictionary* p = [[track properties] mutableCopy];
  230483. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  230484. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  230485. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  230486. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  230487. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  230488. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  230489. [track setProperties: p];
  230490. [p release];
  230491. }
  230492. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  230493. {
  230494. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  230495. if (s != nil)
  230496. s->source = source_;
  230497. return s;
  230498. }
  230499. - (void) dealloc
  230500. {
  230501. if (source != 0)
  230502. {
  230503. source->releaseResources();
  230504. delete source;
  230505. }
  230506. [super dealloc];
  230507. }
  230508. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  230509. {
  230510. }
  230511. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  230512. {
  230513. return true;
  230514. }
  230515. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  230516. {
  230517. return lengthInFrames;
  230518. }
  230519. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  230520. toMedia: (NSDictionary*) mediaInfo
  230521. {
  230522. if (source != 0)
  230523. source->prepareToPlay (44100 / 75, 44100);
  230524. readPosition = 0;
  230525. return true;
  230526. }
  230527. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  230528. {
  230529. if (source != 0)
  230530. source->prepareToPlay (44100 / 75, 44100);
  230531. return true;
  230532. }
  230533. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  230534. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  230535. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  230536. {
  230537. if (source != 0)
  230538. {
  230539. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  230540. if (numSamples > 0)
  230541. {
  230542. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  230543. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  230544. info.buffer = &tempBuffer;
  230545. info.startSample = 0;
  230546. info.numSamples = numSamples;
  230547. source->getNextAudioBlock (info);
  230548. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (0),
  230549. buffer, numSamples, 4);
  230550. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (1),
  230551. buffer + 2, numSamples, 4);
  230552. readPosition += numSamples;
  230553. }
  230554. return numSamples * 4;
  230555. }
  230556. return 0;
  230557. }
  230558. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  230559. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  230560. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  230561. ioFlags: (uint32_t*) flags
  230562. {
  230563. zeromem (buffer, bufferLength);
  230564. return bufferLength;
  230565. }
  230566. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  230567. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  230568. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  230569. {
  230570. return true;
  230571. }
  230572. @end
  230573. BEGIN_JUCE_NAMESPACE
  230574. class AudioCDBurner::Pimpl : public Timer
  230575. {
  230576. public:
  230577. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  230578. : device (0), owner (owner_)
  230579. {
  230580. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  230581. if (dev != 0)
  230582. {
  230583. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  230584. lastState = getDiskState();
  230585. startTimer (1000);
  230586. }
  230587. }
  230588. ~Pimpl()
  230589. {
  230590. stopTimer();
  230591. [device release];
  230592. }
  230593. void timerCallback()
  230594. {
  230595. const DiskState state = getDiskState();
  230596. if (state != lastState)
  230597. {
  230598. lastState = state;
  230599. owner.sendChangeMessage (&owner);
  230600. }
  230601. }
  230602. DiskState getDiskState() const
  230603. {
  230604. if ([device->device isValid])
  230605. {
  230606. NSDictionary* status = [device->device status];
  230607. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  230608. if ([state isEqualTo: DRDeviceMediaStateNone])
  230609. {
  230610. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  230611. return trayOpen;
  230612. return noDisc;
  230613. }
  230614. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  230615. {
  230616. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  230617. return writableDiskPresent;
  230618. else
  230619. return readOnlyDiskPresent;
  230620. }
  230621. }
  230622. return unknown;
  230623. }
  230624. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  230625. const Array<int> getAvailableWriteSpeeds() const
  230626. {
  230627. Array<int> results;
  230628. if ([device->device isValid])
  230629. {
  230630. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  230631. for (unsigned int i = 0; i < [speeds count]; ++i)
  230632. {
  230633. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  230634. results.add (kbPerSec / kilobytesPerSecond1x);
  230635. }
  230636. }
  230637. return results;
  230638. }
  230639. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  230640. {
  230641. if ([device->device isValid])
  230642. {
  230643. device->underrunProtection = shouldBeEnabled;
  230644. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  230645. }
  230646. return false;
  230647. }
  230648. int getNumAvailableAudioBlocks() const
  230649. {
  230650. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  230651. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  230652. }
  230653. OpenDiskDevice* device;
  230654. private:
  230655. DiskState lastState;
  230656. AudioCDBurner& owner;
  230657. };
  230658. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  230659. {
  230660. pimpl = new Pimpl (*this, deviceIndex);
  230661. }
  230662. AudioCDBurner::~AudioCDBurner()
  230663. {
  230664. }
  230665. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  230666. {
  230667. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  230668. if (b->pimpl->device == 0)
  230669. b = 0;
  230670. return b.release();
  230671. }
  230672. static NSArray* findDiskBurnerDevices()
  230673. {
  230674. NSMutableArray* results = [NSMutableArray array];
  230675. NSArray* devs = [DRDevice devices];
  230676. if (devs != 0)
  230677. {
  230678. int num = [devs count];
  230679. int i;
  230680. for (i = 0; i < num; ++i)
  230681. {
  230682. NSDictionary* dic = [[devs objectAtIndex: i] info];
  230683. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  230684. if (name != nil)
  230685. [results addObject: name];
  230686. }
  230687. }
  230688. return results;
  230689. }
  230690. const StringArray AudioCDBurner::findAvailableDevices()
  230691. {
  230692. NSArray* names = findDiskBurnerDevices();
  230693. StringArray s;
  230694. for (unsigned int i = 0; i < [names count]; ++i)
  230695. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  230696. return s;
  230697. }
  230698. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  230699. {
  230700. return pimpl->getDiskState();
  230701. }
  230702. bool AudioCDBurner::isDiskPresent() const
  230703. {
  230704. return getDiskState() == writableDiskPresent;
  230705. }
  230706. bool AudioCDBurner::openTray()
  230707. {
  230708. return pimpl->openTray();
  230709. }
  230710. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  230711. {
  230712. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  230713. DiskState oldState = getDiskState();
  230714. DiskState newState = oldState;
  230715. while (newState == oldState && Time::currentTimeMillis() < timeout)
  230716. {
  230717. newState = getDiskState();
  230718. Thread::sleep (100);
  230719. }
  230720. return newState;
  230721. }
  230722. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  230723. {
  230724. return pimpl->getAvailableWriteSpeeds();
  230725. }
  230726. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  230727. {
  230728. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  230729. }
  230730. int AudioCDBurner::getNumAvailableAudioBlocks() const
  230731. {
  230732. return pimpl->getNumAvailableAudioBlocks();
  230733. }
  230734. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  230735. {
  230736. if ([pimpl->device->device isValid])
  230737. {
  230738. [pimpl->device addSourceTrack: source numSamples: numSamps];
  230739. return true;
  230740. }
  230741. return false;
  230742. }
  230743. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  230744. bool ejectDiscAfterwards,
  230745. bool performFakeBurnForTesting,
  230746. int writeSpeed)
  230747. {
  230748. String error ("Couldn't open or write to the CD device");
  230749. if ([pimpl->device->device isValid])
  230750. {
  230751. error = String::empty;
  230752. [pimpl->device burn: listener
  230753. errorString: &error
  230754. ejectAfterwards: ejectDiscAfterwards
  230755. isFake: performFakeBurnForTesting
  230756. speed: writeSpeed];
  230757. }
  230758. return error;
  230759. }
  230760. #endif
  230761. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  230762. void AudioCDReader::ejectDisk()
  230763. {
  230764. const ScopedAutoReleasePool p;
  230765. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  230766. }
  230767. #endif
  230768. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  230769. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  230770. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230771. // compiled on its own).
  230772. #if JUCE_INCLUDED_FILE
  230773. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  230774. for example having more than one juce plugin loaded into a host, then when a
  230775. method is called, the actual code that runs might actually be in a different module
  230776. than the one you expect... So any calls to library functions or statics that are
  230777. made inside obj-c methods will probably end up getting executed in a different DLL's
  230778. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  230779. To work around this insanity, I'm only allowing obj-c methods to make calls to
  230780. virtual methods of an object that's known to live inside the right module's space.
  230781. */
  230782. class AppDelegateRedirector
  230783. {
  230784. public:
  230785. AppDelegateRedirector()
  230786. {
  230787. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
  230788. runLoop = CFRunLoopGetMain();
  230789. #else
  230790. runLoop = CFRunLoopGetCurrent();
  230791. #endif
  230792. CFRunLoopSourceContext sourceContext;
  230793. zerostruct (sourceContext);
  230794. sourceContext.info = this;
  230795. sourceContext.perform = runLoopSourceCallback;
  230796. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  230797. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  230798. }
  230799. virtual ~AppDelegateRedirector()
  230800. {
  230801. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  230802. CFRunLoopSourceInvalidate (runLoopSource);
  230803. CFRelease (runLoopSource);
  230804. while (messages.size() > 0)
  230805. delete static_cast <Message*> (messages.remove(0));
  230806. }
  230807. virtual NSApplicationTerminateReply shouldTerminate()
  230808. {
  230809. if (JUCEApplication::getInstance() != 0)
  230810. {
  230811. JUCEApplication::getInstance()->systemRequestedQuit();
  230812. return NSTerminateCancel;
  230813. }
  230814. return NSTerminateNow;
  230815. }
  230816. virtual BOOL openFile (const NSString* filename)
  230817. {
  230818. if (JUCEApplication::getInstance() != 0)
  230819. {
  230820. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  230821. return YES;
  230822. }
  230823. return NO;
  230824. }
  230825. virtual void openFiles (NSArray* filenames)
  230826. {
  230827. StringArray files;
  230828. for (unsigned int i = 0; i < [filenames count]; ++i)
  230829. {
  230830. String filename (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  230831. if (filename.containsChar (' '))
  230832. filename = filename.quoted('"');
  230833. files.add (filename);
  230834. }
  230835. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  230836. {
  230837. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  230838. }
  230839. }
  230840. virtual void focusChanged()
  230841. {
  230842. juce_HandleProcessFocusChange();
  230843. }
  230844. struct CallbackMessagePayload
  230845. {
  230846. MessageCallbackFunction* function;
  230847. void* parameter;
  230848. void* volatile result;
  230849. bool volatile hasBeenExecuted;
  230850. };
  230851. virtual void performCallback (CallbackMessagePayload* pl)
  230852. {
  230853. pl->result = (*pl->function) (pl->parameter);
  230854. pl->hasBeenExecuted = true;
  230855. }
  230856. virtual void deleteSelf()
  230857. {
  230858. delete this;
  230859. }
  230860. void postMessage (void* m)
  230861. {
  230862. messages.add (m);
  230863. CFRunLoopSourceSignal (runLoopSource);
  230864. CFRunLoopWakeUp (runLoop);
  230865. }
  230866. private:
  230867. CFRunLoopRef runLoop;
  230868. CFRunLoopSourceRef runLoopSource;
  230869. Array <void*, CriticalSection> messages;
  230870. void runLoopCallback()
  230871. {
  230872. int numDispatched = 0;
  230873. do
  230874. {
  230875. void* const nextMessage = messages.remove (0);
  230876. if (nextMessage == 0)
  230877. return;
  230878. const ScopedAutoReleasePool pool;
  230879. MessageManager::getInstance()->deliverMessage (nextMessage);
  230880. } while (++numDispatched <= 4);
  230881. CFRunLoopSourceSignal (runLoopSource);
  230882. CFRunLoopWakeUp (runLoop);
  230883. }
  230884. static void runLoopSourceCallback (void* info)
  230885. {
  230886. static_cast <AppDelegateRedirector*> (info)->runLoopCallback();
  230887. }
  230888. };
  230889. END_JUCE_NAMESPACE
  230890. using namespace JUCE_NAMESPACE;
  230891. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  230892. @interface JuceAppDelegate : NSObject
  230893. {
  230894. @private
  230895. id oldDelegate;
  230896. @public
  230897. AppDelegateRedirector* redirector;
  230898. }
  230899. - (JuceAppDelegate*) init;
  230900. - (void) dealloc;
  230901. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  230902. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  230903. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  230904. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  230905. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  230906. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  230907. - (void) performCallback: (id) info;
  230908. - (void) dummyMethod;
  230909. @end
  230910. @implementation JuceAppDelegate
  230911. - (JuceAppDelegate*) init
  230912. {
  230913. [super init];
  230914. redirector = new AppDelegateRedirector();
  230915. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  230916. if (JUCEApplication::getInstance() != 0)
  230917. {
  230918. oldDelegate = [NSApp delegate];
  230919. [NSApp setDelegate: self];
  230920. }
  230921. else
  230922. {
  230923. oldDelegate = 0;
  230924. [center addObserver: self selector: @selector (applicationDidResignActive:)
  230925. name: NSApplicationDidResignActiveNotification object: NSApp];
  230926. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  230927. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  230928. [center addObserver: self selector: @selector (applicationWillUnhide:)
  230929. name: NSApplicationWillUnhideNotification object: NSApp];
  230930. }
  230931. return self;
  230932. }
  230933. - (void) dealloc
  230934. {
  230935. if (oldDelegate != 0)
  230936. [NSApp setDelegate: oldDelegate];
  230937. redirector->deleteSelf();
  230938. [super dealloc];
  230939. }
  230940. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  230941. {
  230942. (void) app;
  230943. return redirector->shouldTerminate();
  230944. }
  230945. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  230946. {
  230947. (void) app;
  230948. return redirector->openFile (filename);
  230949. }
  230950. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  230951. {
  230952. (void) sender;
  230953. return redirector->openFiles (filenames);
  230954. }
  230955. - (void) applicationDidBecomeActive: (NSNotification*) notification
  230956. {
  230957. (void) notification;
  230958. redirector->focusChanged();
  230959. }
  230960. - (void) applicationDidResignActive: (NSNotification*) notification
  230961. {
  230962. (void) notification;
  230963. redirector->focusChanged();
  230964. }
  230965. - (void) applicationWillUnhide: (NSNotification*) notification
  230966. {
  230967. (void) notification;
  230968. redirector->focusChanged();
  230969. }
  230970. - (void) performCallback: (id) info
  230971. {
  230972. if ([info isKindOfClass: [NSData class]])
  230973. {
  230974. AppDelegateRedirector::CallbackMessagePayload* pl
  230975. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  230976. if (pl != 0)
  230977. redirector->performCallback (pl);
  230978. }
  230979. else
  230980. {
  230981. jassertfalse // should never get here!
  230982. }
  230983. }
  230984. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  230985. @end
  230986. BEGIN_JUCE_NAMESPACE
  230987. static JuceAppDelegate* juceAppDelegate = 0;
  230988. void MessageManager::runDispatchLoop()
  230989. {
  230990. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  230991. {
  230992. const ScopedAutoReleasePool pool;
  230993. // must only be called by the message thread!
  230994. jassert (isThisTheMessageThread());
  230995. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  230996. @try
  230997. {
  230998. [NSApp run];
  230999. }
  231000. @catch (NSException* e)
  231001. {
  231002. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  231003. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  231004. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  231005. }
  231006. @finally
  231007. {
  231008. }
  231009. #else
  231010. [NSApp run];
  231011. #endif
  231012. }
  231013. }
  231014. void MessageManager::stopDispatchLoop()
  231015. {
  231016. quitMessagePosted = true;
  231017. [NSApp stop: nil];
  231018. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  231019. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  231020. }
  231021. static bool isEventBlockedByModalComps (NSEvent* e)
  231022. {
  231023. if (Component::getNumCurrentlyModalComponents() == 0)
  231024. return false;
  231025. NSWindow* const w = [e window];
  231026. if (w == 0 || [w worksWhenModal])
  231027. return false;
  231028. bool isKey = false, isInputAttempt = false;
  231029. switch ([e type])
  231030. {
  231031. case NSKeyDown:
  231032. case NSKeyUp:
  231033. isKey = isInputAttempt = true;
  231034. break;
  231035. case NSLeftMouseDown:
  231036. case NSRightMouseDown:
  231037. case NSOtherMouseDown:
  231038. isInputAttempt = true;
  231039. break;
  231040. case NSLeftMouseDragged:
  231041. case NSRightMouseDragged:
  231042. case NSLeftMouseUp:
  231043. case NSRightMouseUp:
  231044. case NSOtherMouseUp:
  231045. case NSOtherMouseDragged:
  231046. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  231047. return false;
  231048. break;
  231049. case NSMouseMoved:
  231050. case NSMouseEntered:
  231051. case NSMouseExited:
  231052. case NSCursorUpdate:
  231053. case NSScrollWheel:
  231054. case NSTabletPoint:
  231055. case NSTabletProximity:
  231056. break;
  231057. default:
  231058. return false;
  231059. }
  231060. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  231061. {
  231062. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  231063. NSView* const compView = (NSView*) peer->getNativeHandle();
  231064. if ([compView window] == w)
  231065. {
  231066. if (isKey)
  231067. {
  231068. if (compView == [w firstResponder])
  231069. return false;
  231070. }
  231071. else
  231072. {
  231073. if (NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil],
  231074. [compView bounds]))
  231075. return false;
  231076. }
  231077. }
  231078. }
  231079. if (isInputAttempt)
  231080. {
  231081. if (! [NSApp isActive])
  231082. [NSApp activateIgnoringOtherApps: YES];
  231083. Component* const modal = Component::getCurrentlyModalComponent (0);
  231084. if (modal != 0)
  231085. modal->inputAttemptWhenModal();
  231086. }
  231087. return true;
  231088. }
  231089. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  231090. {
  231091. const ScopedAutoReleasePool pool;
  231092. jassert (isThisTheMessageThread()); // must only be called by the message thread
  231093. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  231094. while (! quitMessagePosted)
  231095. {
  231096. const ScopedAutoReleasePool pool2;
  231097. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  231098. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  231099. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  231100. inMode: NSDefaultRunLoopMode
  231101. dequeue: YES];
  231102. if (e != 0 && ! isEventBlockedByModalComps (e))
  231103. [NSApp sendEvent: e];
  231104. if (Time::getMillisecondCounter() >= endTime)
  231105. break;
  231106. }
  231107. return ! quitMessagePosted;
  231108. }
  231109. void MessageManager::doPlatformSpecificInitialisation()
  231110. {
  231111. if (juceAppDelegate == 0)
  231112. juceAppDelegate = [[JuceAppDelegate alloc] init];
  231113. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  231114. // correctly (needed prior to 10.5)
  231115. if (! [NSThread isMultiThreaded])
  231116. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  231117. toTarget: juceAppDelegate
  231118. withObject: nil];
  231119. initialiseMainMenu();
  231120. }
  231121. void MessageManager::doPlatformSpecificShutdown()
  231122. {
  231123. if (juceAppDelegate != 0)
  231124. {
  231125. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  231126. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  231127. [juceAppDelegate release];
  231128. juceAppDelegate = 0;
  231129. }
  231130. }
  231131. bool juce_postMessageToSystemQueue (void* message)
  231132. {
  231133. juceAppDelegate->redirector->postMessage (message);
  231134. return true;
  231135. }
  231136. void MessageManager::broadcastMessage (const String& value) throw()
  231137. {
  231138. }
  231139. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  231140. void* data)
  231141. {
  231142. if (isThisTheMessageThread())
  231143. {
  231144. return (*callback) (data);
  231145. }
  231146. else
  231147. {
  231148. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  231149. // deadlock because the message manager is blocked from running, so can never
  231150. // call your function..
  231151. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  231152. const ScopedAutoReleasePool pool;
  231153. AppDelegateRedirector::CallbackMessagePayload cmp;
  231154. cmp.function = callback;
  231155. cmp.parameter = data;
  231156. cmp.result = 0;
  231157. cmp.hasBeenExecuted = false;
  231158. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  231159. withObject: [NSData dataWithBytesNoCopy: &cmp
  231160. length: sizeof (cmp)
  231161. freeWhenDone: NO]
  231162. waitUntilDone: YES];
  231163. return cmp.result;
  231164. }
  231165. }
  231166. #endif
  231167. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  231168. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  231169. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231170. // compiled on its own).
  231171. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  231172. #if JUCE_MAC
  231173. END_JUCE_NAMESPACE
  231174. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  231175. @interface DownloadClickDetector : NSObject
  231176. {
  231177. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  231178. }
  231179. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  231180. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  231181. request: (NSURLRequest*) request
  231182. frame: (WebFrame*) frame
  231183. decisionListener: (id<WebPolicyDecisionListener>) listener;
  231184. @end
  231185. @implementation DownloadClickDetector
  231186. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  231187. {
  231188. [super init];
  231189. ownerComponent = ownerComponent_;
  231190. return self;
  231191. }
  231192. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  231193. request: (NSURLRequest*) request
  231194. frame: (WebFrame*) frame
  231195. decisionListener: (id <WebPolicyDecisionListener>) listener
  231196. {
  231197. (void) sender;
  231198. (void) request;
  231199. (void) frame;
  231200. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  231201. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  231202. [listener use];
  231203. else
  231204. [listener ignore];
  231205. }
  231206. @end
  231207. BEGIN_JUCE_NAMESPACE
  231208. class WebBrowserComponentInternal : public NSViewComponent
  231209. {
  231210. public:
  231211. WebBrowserComponentInternal (WebBrowserComponent* owner)
  231212. {
  231213. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  231214. frameName: @""
  231215. groupName: @""];
  231216. setView (webView);
  231217. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  231218. [webView setPolicyDelegate: clickListener];
  231219. }
  231220. ~WebBrowserComponentInternal()
  231221. {
  231222. [webView setPolicyDelegate: nil];
  231223. [clickListener release];
  231224. setView (0);
  231225. }
  231226. void goToURL (const String& url,
  231227. const StringArray* headers,
  231228. const MemoryBlock* postData)
  231229. {
  231230. NSMutableURLRequest* r
  231231. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  231232. cachePolicy: NSURLRequestUseProtocolCachePolicy
  231233. timeoutInterval: 30.0];
  231234. if (postData != 0 && postData->getSize() > 0)
  231235. {
  231236. [r setHTTPMethod: @"POST"];
  231237. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  231238. length: postData->getSize()]];
  231239. }
  231240. if (headers != 0)
  231241. {
  231242. for (int i = 0; i < headers->size(); ++i)
  231243. {
  231244. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  231245. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  231246. [r setValue: juceStringToNS (headerValue)
  231247. forHTTPHeaderField: juceStringToNS (headerName)];
  231248. }
  231249. }
  231250. stop();
  231251. [[webView mainFrame] loadRequest: r];
  231252. }
  231253. void goBack()
  231254. {
  231255. [webView goBack];
  231256. }
  231257. void goForward()
  231258. {
  231259. [webView goForward];
  231260. }
  231261. void stop()
  231262. {
  231263. [webView stopLoading: nil];
  231264. }
  231265. void refresh()
  231266. {
  231267. [webView reload: nil];
  231268. }
  231269. private:
  231270. WebView* webView;
  231271. DownloadClickDetector* clickListener;
  231272. };
  231273. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  231274. : browser (0),
  231275. blankPageShown (false),
  231276. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  231277. {
  231278. setOpaque (true);
  231279. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  231280. }
  231281. WebBrowserComponent::~WebBrowserComponent()
  231282. {
  231283. deleteAndZero (browser);
  231284. }
  231285. void WebBrowserComponent::goToURL (const String& url,
  231286. const StringArray* headers,
  231287. const MemoryBlock* postData)
  231288. {
  231289. lastURL = url;
  231290. lastHeaders.clear();
  231291. if (headers != 0)
  231292. lastHeaders = *headers;
  231293. lastPostData.setSize (0);
  231294. if (postData != 0)
  231295. lastPostData = *postData;
  231296. blankPageShown = false;
  231297. browser->goToURL (url, headers, postData);
  231298. }
  231299. void WebBrowserComponent::stop()
  231300. {
  231301. browser->stop();
  231302. }
  231303. void WebBrowserComponent::goBack()
  231304. {
  231305. lastURL = String::empty;
  231306. blankPageShown = false;
  231307. browser->goBack();
  231308. }
  231309. void WebBrowserComponent::goForward()
  231310. {
  231311. lastURL = String::empty;
  231312. browser->goForward();
  231313. }
  231314. void WebBrowserComponent::refresh()
  231315. {
  231316. browser->refresh();
  231317. }
  231318. void WebBrowserComponent::paint (Graphics&)
  231319. {
  231320. }
  231321. void WebBrowserComponent::checkWindowAssociation()
  231322. {
  231323. if (isShowing())
  231324. {
  231325. if (blankPageShown)
  231326. goBack();
  231327. }
  231328. else
  231329. {
  231330. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  231331. {
  231332. // when the component becomes invisible, some stuff like flash
  231333. // carries on playing audio, so we need to force it onto a blank
  231334. // page to avoid this, (and send it back when it's made visible again).
  231335. blankPageShown = true;
  231336. browser->goToURL ("about:blank", 0, 0);
  231337. }
  231338. }
  231339. }
  231340. void WebBrowserComponent::reloadLastURL()
  231341. {
  231342. if (lastURL.isNotEmpty())
  231343. {
  231344. goToURL (lastURL, &lastHeaders, &lastPostData);
  231345. lastURL = String::empty;
  231346. }
  231347. }
  231348. void WebBrowserComponent::parentHierarchyChanged()
  231349. {
  231350. checkWindowAssociation();
  231351. }
  231352. void WebBrowserComponent::resized()
  231353. {
  231354. browser->setSize (getWidth(), getHeight());
  231355. }
  231356. void WebBrowserComponent::visibilityChanged()
  231357. {
  231358. checkWindowAssociation();
  231359. }
  231360. bool WebBrowserComponent::pageAboutToLoad (const String&)
  231361. {
  231362. return true;
  231363. }
  231364. #else
  231365. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  231366. {
  231367. }
  231368. WebBrowserComponent::~WebBrowserComponent()
  231369. {
  231370. }
  231371. void WebBrowserComponent::goToURL (const String& url,
  231372. const StringArray* headers,
  231373. const MemoryBlock* postData)
  231374. {
  231375. }
  231376. void WebBrowserComponent::stop()
  231377. {
  231378. }
  231379. void WebBrowserComponent::goBack()
  231380. {
  231381. }
  231382. void WebBrowserComponent::goForward()
  231383. {
  231384. }
  231385. void WebBrowserComponent::refresh()
  231386. {
  231387. }
  231388. void WebBrowserComponent::paint (Graphics& g)
  231389. {
  231390. }
  231391. void WebBrowserComponent::checkWindowAssociation()
  231392. {
  231393. }
  231394. void WebBrowserComponent::reloadLastURL()
  231395. {
  231396. }
  231397. void WebBrowserComponent::parentHierarchyChanged()
  231398. {
  231399. }
  231400. void WebBrowserComponent::resized()
  231401. {
  231402. }
  231403. void WebBrowserComponent::visibilityChanged()
  231404. {
  231405. }
  231406. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  231407. {
  231408. return true;
  231409. }
  231410. #endif
  231411. #endif
  231412. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  231413. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  231414. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231415. // compiled on its own).
  231416. #if JUCE_INCLUDED_FILE
  231417. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  231418. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  231419. #endif
  231420. #undef log
  231421. #if JUCE_COREAUDIO_LOGGING_ENABLED
  231422. #define log(a) Logger::writeToLog (a)
  231423. #else
  231424. #define log(a)
  231425. #endif
  231426. #undef OK
  231427. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  231428. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  231429. {
  231430. if (err == noErr)
  231431. return true;
  231432. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  231433. jassertfalse
  231434. return false;
  231435. }
  231436. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  231437. #else
  231438. #define OK(a) (a == noErr)
  231439. #endif
  231440. class CoreAudioInternal : public Timer
  231441. {
  231442. public:
  231443. CoreAudioInternal (AudioDeviceID id)
  231444. : inputLatency (0),
  231445. outputLatency (0),
  231446. callback (0),
  231447. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  231448. audioProcID (0),
  231449. #endif
  231450. inputDevice (0),
  231451. isSlaveDevice (false),
  231452. deviceID (id),
  231453. started (false),
  231454. sampleRate (0),
  231455. bufferSize (512),
  231456. numInputChans (0),
  231457. numOutputChans (0),
  231458. callbacksAllowed (true),
  231459. numInputChannelInfos (0),
  231460. numOutputChannelInfos (0)
  231461. {
  231462. jassert (deviceID != 0);
  231463. updateDetailsFromDevice();
  231464. AudioObjectPropertyAddress pa;
  231465. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  231466. pa.mScope = kAudioObjectPropertyScopeWildcard;
  231467. pa.mElement = kAudioObjectPropertyElementWildcard;
  231468. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  231469. }
  231470. ~CoreAudioInternal()
  231471. {
  231472. AudioObjectPropertyAddress pa;
  231473. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  231474. pa.mScope = kAudioObjectPropertyScopeWildcard;
  231475. pa.mElement = kAudioObjectPropertyElementWildcard;
  231476. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  231477. stop (false);
  231478. delete inputDevice;
  231479. }
  231480. void allocateTempBuffers()
  231481. {
  231482. const int tempBufSize = bufferSize + 4;
  231483. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  231484. tempInputBuffers.calloc (numInputChans + 2);
  231485. tempOutputBuffers.calloc (numOutputChans + 2);
  231486. int i, count = 0;
  231487. for (i = 0; i < numInputChans; ++i)
  231488. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  231489. for (i = 0; i < numOutputChans; ++i)
  231490. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  231491. }
  231492. // returns the number of actual available channels
  231493. void fillInChannelInfo (const bool input)
  231494. {
  231495. int chanNum = 0;
  231496. UInt32 size;
  231497. AudioObjectPropertyAddress pa;
  231498. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  231499. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  231500. pa.mElement = kAudioObjectPropertyElementMaster;
  231501. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  231502. {
  231503. HeapBlock <AudioBufferList> bufList;
  231504. bufList.calloc (size, 1);
  231505. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  231506. {
  231507. const int numStreams = bufList->mNumberBuffers;
  231508. for (int i = 0; i < numStreams; ++i)
  231509. {
  231510. const AudioBuffer& b = bufList->mBuffers[i];
  231511. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  231512. {
  231513. String name;
  231514. {
  231515. char channelName [256];
  231516. zerostruct (channelName);
  231517. UInt32 nameSize = sizeof (channelName);
  231518. UInt32 channelNum = chanNum + 1;
  231519. pa.mSelector = kAudioDevicePropertyChannelName;
  231520. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  231521. name = String::fromUTF8 (channelName, nameSize);
  231522. }
  231523. if (input)
  231524. {
  231525. if (activeInputChans[chanNum])
  231526. {
  231527. inputChannelInfo [numInputChannelInfos].streamNum = i;
  231528. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  231529. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  231530. ++numInputChannelInfos;
  231531. }
  231532. if (name.isEmpty())
  231533. name << "Input " << (chanNum + 1);
  231534. inChanNames.add (name);
  231535. }
  231536. else
  231537. {
  231538. if (activeOutputChans[chanNum])
  231539. {
  231540. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  231541. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  231542. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  231543. ++numOutputChannelInfos;
  231544. }
  231545. if (name.isEmpty())
  231546. name << "Output " << (chanNum + 1);
  231547. outChanNames.add (name);
  231548. }
  231549. ++chanNum;
  231550. }
  231551. }
  231552. }
  231553. }
  231554. }
  231555. void updateDetailsFromDevice()
  231556. {
  231557. stopTimer();
  231558. if (deviceID == 0)
  231559. return;
  231560. const ScopedLock sl (callbackLock);
  231561. Float64 sr;
  231562. UInt32 size = sizeof (Float64);
  231563. AudioObjectPropertyAddress pa;
  231564. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  231565. pa.mScope = kAudioObjectPropertyScopeWildcard;
  231566. pa.mElement = kAudioObjectPropertyElementMaster;
  231567. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  231568. sampleRate = sr;
  231569. UInt32 framesPerBuf;
  231570. size = sizeof (framesPerBuf);
  231571. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  231572. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  231573. {
  231574. bufferSize = framesPerBuf;
  231575. allocateTempBuffers();
  231576. }
  231577. bufferSizes.clear();
  231578. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  231579. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  231580. {
  231581. HeapBlock <AudioValueRange> ranges;
  231582. ranges.calloc (size, 1);
  231583. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  231584. {
  231585. bufferSizes.add ((int) ranges[0].mMinimum);
  231586. for (int i = 32; i < 2048; i += 32)
  231587. {
  231588. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  231589. {
  231590. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  231591. {
  231592. bufferSizes.addIfNotAlreadyThere (i);
  231593. break;
  231594. }
  231595. }
  231596. }
  231597. if (bufferSize > 0)
  231598. bufferSizes.addIfNotAlreadyThere (bufferSize);
  231599. }
  231600. }
  231601. if (bufferSizes.size() == 0 && bufferSize > 0)
  231602. bufferSizes.add (bufferSize);
  231603. sampleRates.clear();
  231604. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  231605. String rates;
  231606. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  231607. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  231608. {
  231609. HeapBlock <AudioValueRange> ranges;
  231610. ranges.calloc (size, 1);
  231611. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  231612. {
  231613. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  231614. {
  231615. bool ok = false;
  231616. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  231617. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  231618. ok = true;
  231619. if (ok)
  231620. {
  231621. sampleRates.add (possibleRates[i]);
  231622. rates << possibleRates[i] << ' ';
  231623. }
  231624. }
  231625. }
  231626. }
  231627. if (sampleRates.size() == 0 && sampleRate > 0)
  231628. {
  231629. sampleRates.add (sampleRate);
  231630. rates << sampleRate;
  231631. }
  231632. log ("sr: " + rates);
  231633. inputLatency = 0;
  231634. outputLatency = 0;
  231635. UInt32 lat;
  231636. size = sizeof (lat);
  231637. pa.mSelector = kAudioDevicePropertyLatency;
  231638. pa.mScope = kAudioDevicePropertyScopeInput;
  231639. //if (AudioDeviceGetProperty (deviceID, 0, true, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  231640. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  231641. inputLatency = (int) lat;
  231642. pa.mScope = kAudioDevicePropertyScopeOutput;
  231643. size = sizeof (lat);
  231644. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  231645. outputLatency = (int) lat;
  231646. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  231647. inChanNames.clear();
  231648. outChanNames.clear();
  231649. inputChannelInfo.calloc (numInputChans + 2);
  231650. numInputChannelInfos = 0;
  231651. outputChannelInfo.calloc (numOutputChans + 2);
  231652. numOutputChannelInfos = 0;
  231653. fillInChannelInfo (true);
  231654. fillInChannelInfo (false);
  231655. }
  231656. const StringArray getSources (bool input)
  231657. {
  231658. StringArray s;
  231659. HeapBlock <OSType> types;
  231660. const int num = getAllDataSourcesForDevice (deviceID, types);
  231661. for (int i = 0; i < num; ++i)
  231662. {
  231663. AudioValueTranslation avt;
  231664. char buffer[256];
  231665. avt.mInputData = &(types[i]);
  231666. avt.mInputDataSize = sizeof (UInt32);
  231667. avt.mOutputData = buffer;
  231668. avt.mOutputDataSize = 256;
  231669. UInt32 transSize = sizeof (avt);
  231670. AudioObjectPropertyAddress pa;
  231671. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  231672. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  231673. pa.mElement = kAudioObjectPropertyElementMaster;
  231674. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  231675. {
  231676. DBG (buffer);
  231677. s.add (buffer);
  231678. }
  231679. }
  231680. return s;
  231681. }
  231682. int getCurrentSourceIndex (bool input) const
  231683. {
  231684. OSType currentSourceID = 0;
  231685. UInt32 size = sizeof (currentSourceID);
  231686. int result = -1;
  231687. AudioObjectPropertyAddress pa;
  231688. pa.mSelector = kAudioDevicePropertyDataSource;
  231689. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  231690. pa.mElement = kAudioObjectPropertyElementMaster;
  231691. if (deviceID != 0)
  231692. {
  231693. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  231694. {
  231695. HeapBlock <OSType> types;
  231696. const int num = getAllDataSourcesForDevice (deviceID, types);
  231697. for (int i = 0; i < num; ++i)
  231698. {
  231699. if (types[num] == currentSourceID)
  231700. {
  231701. result = i;
  231702. break;
  231703. }
  231704. }
  231705. }
  231706. }
  231707. return result;
  231708. }
  231709. void setCurrentSourceIndex (int index, bool input)
  231710. {
  231711. if (deviceID != 0)
  231712. {
  231713. HeapBlock <OSType> types;
  231714. const int num = getAllDataSourcesForDevice (deviceID, types);
  231715. if (((unsigned int) index) < (unsigned int) num)
  231716. {
  231717. AudioObjectPropertyAddress pa;
  231718. pa.mSelector = kAudioDevicePropertyDataSource;
  231719. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  231720. pa.mElement = kAudioObjectPropertyElementMaster;
  231721. OSType typeId = types[index];
  231722. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  231723. }
  231724. }
  231725. }
  231726. const String reopen (const BigInteger& inputChannels,
  231727. const BigInteger& outputChannels,
  231728. double newSampleRate,
  231729. int bufferSizeSamples)
  231730. {
  231731. String error;
  231732. log ("CoreAudio reopen");
  231733. callbacksAllowed = false;
  231734. stopTimer();
  231735. stop (false);
  231736. activeInputChans = inputChannels;
  231737. activeInputChans.setRange (inChanNames.size(),
  231738. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  231739. false);
  231740. activeOutputChans = outputChannels;
  231741. activeOutputChans.setRange (outChanNames.size(),
  231742. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  231743. false);
  231744. numInputChans = activeInputChans.countNumberOfSetBits();
  231745. numOutputChans = activeOutputChans.countNumberOfSetBits();
  231746. // set sample rate
  231747. AudioObjectPropertyAddress pa;
  231748. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  231749. pa.mScope = kAudioObjectPropertyScopeWildcard;
  231750. pa.mElement = kAudioObjectPropertyElementMaster;
  231751. Float64 sr = newSampleRate;
  231752. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  231753. {
  231754. error = "Couldn't change sample rate";
  231755. }
  231756. else
  231757. {
  231758. // change buffer size
  231759. UInt32 framesPerBuf = bufferSizeSamples;
  231760. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  231761. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  231762. {
  231763. error = "Couldn't change buffer size";
  231764. }
  231765. else
  231766. {
  231767. // Annoyingly, after changing the rate and buffer size, some devices fail to
  231768. // correctly report their new settings until some random time in the future, so
  231769. // after calling updateDetailsFromDevice, we need to manually bodge these values
  231770. // to make sure we're using the correct numbers..
  231771. updateDetailsFromDevice();
  231772. sampleRate = newSampleRate;
  231773. bufferSize = bufferSizeSamples;
  231774. if (sampleRates.size() == 0)
  231775. error = "Device has no available sample-rates";
  231776. else if (bufferSizes.size() == 0)
  231777. error = "Device has no available buffer-sizes";
  231778. else if (inputDevice != 0)
  231779. error = inputDevice->reopen (inputChannels,
  231780. outputChannels,
  231781. newSampleRate,
  231782. bufferSizeSamples);
  231783. }
  231784. }
  231785. callbacksAllowed = true;
  231786. return error;
  231787. }
  231788. bool start (AudioIODeviceCallback* cb)
  231789. {
  231790. if (! started)
  231791. {
  231792. callback = 0;
  231793. if (deviceID != 0)
  231794. {
  231795. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231796. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  231797. #else
  231798. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  231799. #endif
  231800. {
  231801. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  231802. {
  231803. started = true;
  231804. }
  231805. else
  231806. {
  231807. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231808. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  231809. #else
  231810. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  231811. audioProcID = 0;
  231812. #endif
  231813. }
  231814. }
  231815. }
  231816. }
  231817. if (started)
  231818. {
  231819. const ScopedLock sl (callbackLock);
  231820. callback = cb;
  231821. }
  231822. if (inputDevice != 0)
  231823. return started && inputDevice->start (cb);
  231824. else
  231825. return started;
  231826. }
  231827. void stop (bool leaveInterruptRunning)
  231828. {
  231829. {
  231830. const ScopedLock sl (callbackLock);
  231831. callback = 0;
  231832. }
  231833. if (started
  231834. && (deviceID != 0)
  231835. && ! leaveInterruptRunning)
  231836. {
  231837. OK (AudioDeviceStop (deviceID, audioIOProc));
  231838. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231839. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  231840. #else
  231841. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  231842. audioProcID = 0;
  231843. #endif
  231844. started = false;
  231845. { const ScopedLock sl (callbackLock); }
  231846. // wait until it's definately stopped calling back..
  231847. for (int i = 40; --i >= 0;)
  231848. {
  231849. Thread::sleep (50);
  231850. UInt32 running = 0;
  231851. UInt32 size = sizeof (running);
  231852. AudioObjectPropertyAddress pa;
  231853. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  231854. pa.mScope = kAudioObjectPropertyScopeWildcard;
  231855. pa.mElement = kAudioObjectPropertyElementMaster;
  231856. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  231857. if (running == 0)
  231858. break;
  231859. }
  231860. const ScopedLock sl (callbackLock);
  231861. }
  231862. if (inputDevice != 0)
  231863. inputDevice->stop (leaveInterruptRunning);
  231864. }
  231865. double getSampleRate() const
  231866. {
  231867. return sampleRate;
  231868. }
  231869. int getBufferSize() const
  231870. {
  231871. return bufferSize;
  231872. }
  231873. void audioCallback (const AudioBufferList* inInputData,
  231874. AudioBufferList* outOutputData)
  231875. {
  231876. int i;
  231877. const ScopedLock sl (callbackLock);
  231878. if (callback != 0)
  231879. {
  231880. if (inputDevice == 0)
  231881. {
  231882. for (i = numInputChans; --i >= 0;)
  231883. {
  231884. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  231885. float* dest = tempInputBuffers [i];
  231886. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  231887. + info.dataOffsetSamples;
  231888. const int stride = info.dataStrideSamples;
  231889. if (stride != 0) // if this is zero, info is invalid
  231890. {
  231891. for (int j = bufferSize; --j >= 0;)
  231892. {
  231893. *dest++ = *src;
  231894. src += stride;
  231895. }
  231896. }
  231897. }
  231898. }
  231899. if (! isSlaveDevice)
  231900. {
  231901. if (inputDevice == 0)
  231902. {
  231903. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  231904. numInputChans,
  231905. tempOutputBuffers,
  231906. numOutputChans,
  231907. bufferSize);
  231908. }
  231909. else
  231910. {
  231911. jassert (inputDevice->bufferSize == bufferSize);
  231912. // Sometimes the two linked devices seem to get their callbacks in
  231913. // parallel, so we need to lock both devices to stop the input data being
  231914. // changed while inside our callback..
  231915. const ScopedLock sl2 (inputDevice->callbackLock);
  231916. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  231917. inputDevice->numInputChans,
  231918. tempOutputBuffers,
  231919. numOutputChans,
  231920. bufferSize);
  231921. }
  231922. for (i = numOutputChans; --i >= 0;)
  231923. {
  231924. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  231925. const float* src = tempOutputBuffers [i];
  231926. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  231927. + info.dataOffsetSamples;
  231928. const int stride = info.dataStrideSamples;
  231929. if (stride != 0) // if this is zero, info is invalid
  231930. {
  231931. for (int j = bufferSize; --j >= 0;)
  231932. {
  231933. *dest = *src++;
  231934. dest += stride;
  231935. }
  231936. }
  231937. }
  231938. }
  231939. }
  231940. else
  231941. {
  231942. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  231943. {
  231944. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  231945. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  231946. + info.dataOffsetSamples;
  231947. const int stride = info.dataStrideSamples;
  231948. if (stride != 0) // if this is zero, info is invalid
  231949. {
  231950. for (int j = bufferSize; --j >= 0;)
  231951. {
  231952. *dest = 0.0f;
  231953. dest += stride;
  231954. }
  231955. }
  231956. }
  231957. }
  231958. }
  231959. // called by callbacks
  231960. void deviceDetailsChanged()
  231961. {
  231962. if (callbacksAllowed)
  231963. startTimer (100);
  231964. }
  231965. void timerCallback()
  231966. {
  231967. stopTimer();
  231968. log ("CoreAudio device changed callback");
  231969. const double oldSampleRate = sampleRate;
  231970. const int oldBufferSize = bufferSize;
  231971. updateDetailsFromDevice();
  231972. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  231973. {
  231974. callbacksAllowed = false;
  231975. stop (false);
  231976. updateDetailsFromDevice();
  231977. callbacksAllowed = true;
  231978. }
  231979. }
  231980. CoreAudioInternal* getRelatedDevice() const
  231981. {
  231982. UInt32 size = 0;
  231983. ScopedPointer <CoreAudioInternal> result;
  231984. AudioObjectPropertyAddress pa;
  231985. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  231986. pa.mScope = kAudioObjectPropertyScopeWildcard;
  231987. pa.mElement = kAudioObjectPropertyElementMaster;
  231988. if (deviceID != 0
  231989. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  231990. && size > 0)
  231991. {
  231992. HeapBlock <AudioDeviceID> devs;
  231993. devs.calloc (size, 1);
  231994. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  231995. {
  231996. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  231997. {
  231998. if (devs[i] != deviceID && devs[i] != 0)
  231999. {
  232000. result = new CoreAudioInternal (devs[i]);
  232001. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  232002. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  232003. if (thisIsInput != otherIsInput
  232004. || (inChanNames.size() + outChanNames.size() == 0)
  232005. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  232006. break;
  232007. result = 0;
  232008. }
  232009. }
  232010. }
  232011. }
  232012. return result.release();
  232013. }
  232014. juce_UseDebuggingNewOperator
  232015. int inputLatency, outputLatency;
  232016. BigInteger activeInputChans, activeOutputChans;
  232017. StringArray inChanNames, outChanNames;
  232018. Array <double> sampleRates;
  232019. Array <int> bufferSizes;
  232020. AudioIODeviceCallback* callback;
  232021. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  232022. AudioDeviceIOProcID audioProcID;
  232023. #endif
  232024. CoreAudioInternal* inputDevice;
  232025. bool isSlaveDevice;
  232026. private:
  232027. CriticalSection callbackLock;
  232028. AudioDeviceID deviceID;
  232029. bool started;
  232030. double sampleRate;
  232031. int bufferSize;
  232032. HeapBlock <float> audioBuffer;
  232033. int numInputChans, numOutputChans;
  232034. bool callbacksAllowed;
  232035. struct CallbackDetailsForChannel
  232036. {
  232037. int streamNum;
  232038. int dataOffsetSamples;
  232039. int dataStrideSamples;
  232040. };
  232041. int numInputChannelInfos, numOutputChannelInfos;
  232042. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  232043. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  232044. CoreAudioInternal (const CoreAudioInternal&);
  232045. CoreAudioInternal& operator= (const CoreAudioInternal&);
  232046. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  232047. const AudioTimeStamp* /*inNow*/,
  232048. const AudioBufferList* inInputData,
  232049. const AudioTimeStamp* /*inInputTime*/,
  232050. AudioBufferList* outOutputData,
  232051. const AudioTimeStamp* /*inOutputTime*/,
  232052. void* device)
  232053. {
  232054. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  232055. return noErr;
  232056. }
  232057. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  232058. {
  232059. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  232060. switch (pa->mSelector)
  232061. {
  232062. case kAudioDevicePropertyBufferSize:
  232063. case kAudioDevicePropertyBufferFrameSize:
  232064. case kAudioDevicePropertyNominalSampleRate:
  232065. case kAudioDevicePropertyStreamFormat:
  232066. case kAudioDevicePropertyDeviceIsAlive:
  232067. intern->deviceDetailsChanged();
  232068. break;
  232069. case kAudioDevicePropertyBufferSizeRange:
  232070. case kAudioDevicePropertyVolumeScalar:
  232071. case kAudioDevicePropertyMute:
  232072. case kAudioDevicePropertyPlayThru:
  232073. case kAudioDevicePropertyDataSource:
  232074. case kAudioDevicePropertyDeviceIsRunning:
  232075. break;
  232076. }
  232077. return noErr;
  232078. }
  232079. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  232080. {
  232081. AudioObjectPropertyAddress pa;
  232082. pa.mSelector = kAudioDevicePropertyDataSources;
  232083. pa.mScope = kAudioObjectPropertyScopeWildcard;
  232084. pa.mElement = kAudioObjectPropertyElementMaster;
  232085. UInt32 size = 0;
  232086. if (deviceID != 0
  232087. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  232088. {
  232089. types.calloc (size, 1);
  232090. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  232091. return size / (int) sizeof (OSType);
  232092. }
  232093. return 0;
  232094. }
  232095. };
  232096. class CoreAudioIODevice : public AudioIODevice
  232097. {
  232098. public:
  232099. CoreAudioIODevice (const String& deviceName,
  232100. AudioDeviceID inputDeviceId,
  232101. const int inputIndex_,
  232102. AudioDeviceID outputDeviceId,
  232103. const int outputIndex_)
  232104. : AudioIODevice (deviceName, "CoreAudio"),
  232105. inputIndex (inputIndex_),
  232106. outputIndex (outputIndex_),
  232107. isOpen_ (false),
  232108. isStarted (false)
  232109. {
  232110. internal = 0;
  232111. CoreAudioInternal* device = 0;
  232112. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  232113. {
  232114. jassert (inputDeviceId != 0);
  232115. device = new CoreAudioInternal (inputDeviceId);
  232116. }
  232117. else
  232118. {
  232119. device = new CoreAudioInternal (outputDeviceId);
  232120. if (inputDeviceId != 0)
  232121. {
  232122. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  232123. device->inputDevice = secondDevice;
  232124. secondDevice->isSlaveDevice = true;
  232125. }
  232126. }
  232127. internal = device;
  232128. AudioObjectPropertyAddress pa;
  232129. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  232130. pa.mScope = kAudioObjectPropertyScopeWildcard;
  232131. pa.mElement = kAudioObjectPropertyElementWildcard;
  232132. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  232133. }
  232134. ~CoreAudioIODevice()
  232135. {
  232136. AudioObjectPropertyAddress pa;
  232137. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  232138. pa.mScope = kAudioObjectPropertyScopeWildcard;
  232139. pa.mElement = kAudioObjectPropertyElementWildcard;
  232140. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  232141. delete internal;
  232142. }
  232143. const StringArray getOutputChannelNames()
  232144. {
  232145. return internal->outChanNames;
  232146. }
  232147. const StringArray getInputChannelNames()
  232148. {
  232149. if (internal->inputDevice != 0)
  232150. return internal->inputDevice->inChanNames;
  232151. else
  232152. return internal->inChanNames;
  232153. }
  232154. int getNumSampleRates()
  232155. {
  232156. return internal->sampleRates.size();
  232157. }
  232158. double getSampleRate (int index)
  232159. {
  232160. return internal->sampleRates [index];
  232161. }
  232162. int getNumBufferSizesAvailable()
  232163. {
  232164. return internal->bufferSizes.size();
  232165. }
  232166. int getBufferSizeSamples (int index)
  232167. {
  232168. return internal->bufferSizes [index];
  232169. }
  232170. int getDefaultBufferSize()
  232171. {
  232172. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  232173. if (getBufferSizeSamples(i) >= 512)
  232174. return getBufferSizeSamples(i);
  232175. return 512;
  232176. }
  232177. const String open (const BigInteger& inputChannels,
  232178. const BigInteger& outputChannels,
  232179. double sampleRate,
  232180. int bufferSizeSamples)
  232181. {
  232182. isOpen_ = true;
  232183. if (bufferSizeSamples <= 0)
  232184. bufferSizeSamples = getDefaultBufferSize();
  232185. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  232186. isOpen_ = lastError.isEmpty();
  232187. return lastError;
  232188. }
  232189. void close()
  232190. {
  232191. isOpen_ = false;
  232192. internal->stop (false);
  232193. }
  232194. bool isOpen()
  232195. {
  232196. return isOpen_;
  232197. }
  232198. int getCurrentBufferSizeSamples()
  232199. {
  232200. return internal != 0 ? internal->getBufferSize() : 512;
  232201. }
  232202. double getCurrentSampleRate()
  232203. {
  232204. return internal != 0 ? internal->getSampleRate() : 0;
  232205. }
  232206. int getCurrentBitDepth()
  232207. {
  232208. return 32; // no way to find out, so just assume it's high..
  232209. }
  232210. const BigInteger getActiveOutputChannels() const
  232211. {
  232212. return internal != 0 ? internal->activeOutputChans : BigInteger();
  232213. }
  232214. const BigInteger getActiveInputChannels() const
  232215. {
  232216. BigInteger chans;
  232217. if (internal != 0)
  232218. {
  232219. chans = internal->activeInputChans;
  232220. if (internal->inputDevice != 0)
  232221. chans |= internal->inputDevice->activeInputChans;
  232222. }
  232223. return chans;
  232224. }
  232225. int getOutputLatencyInSamples()
  232226. {
  232227. if (internal == 0)
  232228. return 0;
  232229. // this seems like a good guess at getting the latency right - comparing
  232230. // this with a round-trip measurement, it gets it to within a few millisecs
  232231. // for the built-in mac soundcard
  232232. return internal->outputLatency + internal->getBufferSize() * 2;
  232233. }
  232234. int getInputLatencyInSamples()
  232235. {
  232236. if (internal == 0)
  232237. return 0;
  232238. return internal->inputLatency + internal->getBufferSize() * 2;
  232239. }
  232240. void start (AudioIODeviceCallback* callback)
  232241. {
  232242. if (internal != 0 && ! isStarted)
  232243. {
  232244. if (callback != 0)
  232245. callback->audioDeviceAboutToStart (this);
  232246. isStarted = true;
  232247. internal->start (callback);
  232248. }
  232249. }
  232250. void stop()
  232251. {
  232252. if (isStarted && internal != 0)
  232253. {
  232254. AudioIODeviceCallback* const lastCallback = internal->callback;
  232255. isStarted = false;
  232256. internal->stop (true);
  232257. if (lastCallback != 0)
  232258. lastCallback->audioDeviceStopped();
  232259. }
  232260. }
  232261. bool isPlaying()
  232262. {
  232263. if (internal->callback == 0)
  232264. isStarted = false;
  232265. return isStarted;
  232266. }
  232267. const String getLastError()
  232268. {
  232269. return lastError;
  232270. }
  232271. int inputIndex, outputIndex;
  232272. juce_UseDebuggingNewOperator
  232273. private:
  232274. CoreAudioInternal* internal;
  232275. bool isOpen_, isStarted;
  232276. String lastError;
  232277. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  232278. {
  232279. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  232280. switch (pa->mSelector)
  232281. {
  232282. case kAudioHardwarePropertyDevices:
  232283. intern->deviceDetailsChanged();
  232284. break;
  232285. case kAudioHardwarePropertyDefaultOutputDevice:
  232286. case kAudioHardwarePropertyDefaultInputDevice:
  232287. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  232288. break;
  232289. }
  232290. return noErr;
  232291. }
  232292. CoreAudioIODevice (const CoreAudioIODevice&);
  232293. CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  232294. };
  232295. class CoreAudioIODeviceType : public AudioIODeviceType
  232296. {
  232297. public:
  232298. CoreAudioIODeviceType()
  232299. : AudioIODeviceType ("CoreAudio"),
  232300. hasScanned (false)
  232301. {
  232302. }
  232303. ~CoreAudioIODeviceType()
  232304. {
  232305. }
  232306. void scanForDevices()
  232307. {
  232308. hasScanned = true;
  232309. inputDeviceNames.clear();
  232310. outputDeviceNames.clear();
  232311. inputIds.clear();
  232312. outputIds.clear();
  232313. UInt32 size;
  232314. AudioObjectPropertyAddress pa;
  232315. pa.mSelector = kAudioHardwarePropertyDevices;
  232316. pa.mScope = kAudioObjectPropertyScopeWildcard;
  232317. pa.mElement = kAudioObjectPropertyElementMaster;
  232318. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  232319. {
  232320. HeapBlock <AudioDeviceID> devs;
  232321. devs.calloc (size, 1);
  232322. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  232323. {
  232324. static bool alreadyLogged = false;
  232325. const int num = size / (int) sizeof (AudioDeviceID);
  232326. for (int i = 0; i < num; ++i)
  232327. {
  232328. char name [1024];
  232329. size = sizeof (name);
  232330. pa.mSelector = kAudioDevicePropertyDeviceName;
  232331. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  232332. {
  232333. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  232334. if (! alreadyLogged)
  232335. log ("CoreAudio device: " + nameString);
  232336. const int numIns = getNumChannels (devs[i], true);
  232337. const int numOuts = getNumChannels (devs[i], false);
  232338. if (numIns > 0)
  232339. {
  232340. inputDeviceNames.add (nameString);
  232341. inputIds.add (devs[i]);
  232342. }
  232343. if (numOuts > 0)
  232344. {
  232345. outputDeviceNames.add (nameString);
  232346. outputIds.add (devs[i]);
  232347. }
  232348. }
  232349. }
  232350. alreadyLogged = true;
  232351. }
  232352. }
  232353. inputDeviceNames.appendNumbersToDuplicates (false, true);
  232354. outputDeviceNames.appendNumbersToDuplicates (false, true);
  232355. }
  232356. const StringArray getDeviceNames (bool wantInputNames) const
  232357. {
  232358. jassert (hasScanned); // need to call scanForDevices() before doing this
  232359. if (wantInputNames)
  232360. return inputDeviceNames;
  232361. else
  232362. return outputDeviceNames;
  232363. }
  232364. int getDefaultDeviceIndex (bool forInput) const
  232365. {
  232366. jassert (hasScanned); // need to call scanForDevices() before doing this
  232367. AudioDeviceID deviceID;
  232368. UInt32 size = sizeof (deviceID);
  232369. // if they're asking for any input channels at all, use the default input, so we
  232370. // get the built-in mic rather than the built-in output with no inputs..
  232371. AudioObjectPropertyAddress pa;
  232372. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  232373. pa.mScope = kAudioObjectPropertyScopeWildcard;
  232374. pa.mElement = kAudioObjectPropertyElementMaster;
  232375. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  232376. {
  232377. if (forInput)
  232378. {
  232379. for (int i = inputIds.size(); --i >= 0;)
  232380. if (inputIds[i] == deviceID)
  232381. return i;
  232382. }
  232383. else
  232384. {
  232385. for (int i = outputIds.size(); --i >= 0;)
  232386. if (outputIds[i] == deviceID)
  232387. return i;
  232388. }
  232389. }
  232390. return 0;
  232391. }
  232392. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  232393. {
  232394. jassert (hasScanned); // need to call scanForDevices() before doing this
  232395. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  232396. if (d == 0)
  232397. return -1;
  232398. return asInput ? d->inputIndex
  232399. : d->outputIndex;
  232400. }
  232401. bool hasSeparateInputsAndOutputs() const { return true; }
  232402. AudioIODevice* createDevice (const String& outputDeviceName,
  232403. const String& inputDeviceName)
  232404. {
  232405. jassert (hasScanned); // need to call scanForDevices() before doing this
  232406. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  232407. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  232408. String deviceName (outputDeviceName);
  232409. if (deviceName.isEmpty())
  232410. deviceName = inputDeviceName;
  232411. if (index >= 0)
  232412. return new CoreAudioIODevice (deviceName,
  232413. inputIds [inputIndex],
  232414. inputIndex,
  232415. outputIds [outputIndex],
  232416. outputIndex);
  232417. return 0;
  232418. }
  232419. juce_UseDebuggingNewOperator
  232420. private:
  232421. StringArray inputDeviceNames, outputDeviceNames;
  232422. Array <AudioDeviceID> inputIds, outputIds;
  232423. bool hasScanned;
  232424. static int getNumChannels (AudioDeviceID deviceID, bool input)
  232425. {
  232426. int total = 0;
  232427. UInt32 size;
  232428. AudioObjectPropertyAddress pa;
  232429. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  232430. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  232431. pa.mElement = kAudioObjectPropertyElementMaster;
  232432. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  232433. {
  232434. HeapBlock <AudioBufferList> bufList;
  232435. bufList.calloc (size, 1);
  232436. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  232437. {
  232438. const int numStreams = bufList->mNumberBuffers;
  232439. for (int i = 0; i < numStreams; ++i)
  232440. {
  232441. const AudioBuffer& b = bufList->mBuffers[i];
  232442. total += b.mNumberChannels;
  232443. }
  232444. }
  232445. }
  232446. return total;
  232447. }
  232448. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  232449. CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  232450. };
  232451. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  232452. {
  232453. return new CoreAudioIODeviceType();
  232454. }
  232455. #undef log
  232456. #endif
  232457. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  232458. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  232459. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232460. // compiled on its own).
  232461. #if JUCE_INCLUDED_FILE
  232462. #if JUCE_MAC
  232463. #undef log
  232464. #define log(a) Logger::writeToLog(a)
  232465. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  232466. {
  232467. if (err == noErr)
  232468. return true;
  232469. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  232470. jassertfalse
  232471. return false;
  232472. }
  232473. #undef OK
  232474. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  232475. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  232476. {
  232477. String result;
  232478. CFStringRef str = 0;
  232479. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  232480. if (str != 0)
  232481. {
  232482. result = PlatformUtilities::cfStringToJuceString (str);
  232483. CFRelease (str);
  232484. str = 0;
  232485. }
  232486. MIDIEntityRef entity = 0;
  232487. MIDIEndpointGetEntity (endpoint, &entity);
  232488. if (entity == 0)
  232489. return result; // probably virtual
  232490. if (result.isEmpty())
  232491. {
  232492. // endpoint name has zero length - try the entity
  232493. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  232494. if (str != 0)
  232495. {
  232496. result += PlatformUtilities::cfStringToJuceString (str);
  232497. CFRelease (str);
  232498. str = 0;
  232499. }
  232500. }
  232501. // now consider the device's name
  232502. MIDIDeviceRef device = 0;
  232503. MIDIEntityGetDevice (entity, &device);
  232504. if (device == 0)
  232505. return result;
  232506. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  232507. if (str != 0)
  232508. {
  232509. const String s (PlatformUtilities::cfStringToJuceString (str));
  232510. CFRelease (str);
  232511. // if an external device has only one entity, throw away
  232512. // the endpoint name and just use the device name
  232513. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  232514. {
  232515. result = s;
  232516. }
  232517. else if (! result.startsWithIgnoreCase (s))
  232518. {
  232519. // prepend the device name to the entity name
  232520. result = (s + " " + result).trimEnd();
  232521. }
  232522. }
  232523. return result;
  232524. }
  232525. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  232526. {
  232527. String result;
  232528. // Does the endpoint have connections?
  232529. CFDataRef connections = 0;
  232530. int numConnections = 0;
  232531. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  232532. if (connections != 0)
  232533. {
  232534. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  232535. if (numConnections > 0)
  232536. {
  232537. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  232538. for (int i = 0; i < numConnections; ++i, ++pid)
  232539. {
  232540. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  232541. MIDIObjectRef connObject;
  232542. MIDIObjectType connObjectType;
  232543. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  232544. if (err == noErr)
  232545. {
  232546. String s;
  232547. if (connObjectType == kMIDIObjectType_ExternalSource
  232548. || connObjectType == kMIDIObjectType_ExternalDestination)
  232549. {
  232550. // Connected to an external device's endpoint (10.3 and later).
  232551. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  232552. }
  232553. else
  232554. {
  232555. // Connected to an external device (10.2) (or something else, catch-all)
  232556. CFStringRef str = 0;
  232557. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  232558. if (str != 0)
  232559. {
  232560. s = PlatformUtilities::cfStringToJuceString (str);
  232561. CFRelease (str);
  232562. }
  232563. }
  232564. if (s.isNotEmpty())
  232565. {
  232566. if (result.isNotEmpty())
  232567. result += ", ";
  232568. result += s;
  232569. }
  232570. }
  232571. }
  232572. }
  232573. CFRelease (connections);
  232574. }
  232575. if (result.isNotEmpty())
  232576. return result;
  232577. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  232578. return getEndpointName (endpoint, false);
  232579. }
  232580. const StringArray MidiOutput::getDevices()
  232581. {
  232582. StringArray s;
  232583. const ItemCount num = MIDIGetNumberOfDestinations();
  232584. for (ItemCount i = 0; i < num; ++i)
  232585. {
  232586. MIDIEndpointRef dest = MIDIGetDestination (i);
  232587. if (dest != 0)
  232588. {
  232589. String name (getConnectedEndpointName (dest));
  232590. if (name.isEmpty())
  232591. name = "<error>";
  232592. s.add (name);
  232593. }
  232594. else
  232595. {
  232596. s.add ("<error>");
  232597. }
  232598. }
  232599. return s;
  232600. }
  232601. int MidiOutput::getDefaultDeviceIndex()
  232602. {
  232603. return 0;
  232604. }
  232605. static MIDIClientRef globalMidiClient;
  232606. static bool hasGlobalClientBeenCreated = false;
  232607. static bool makeSureClientExists()
  232608. {
  232609. if (! hasGlobalClientBeenCreated)
  232610. {
  232611. String name ("JUCE");
  232612. if (JUCEApplication::getInstance() != 0)
  232613. name = JUCEApplication::getInstance()->getApplicationName();
  232614. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  232615. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  232616. CFRelease (appName);
  232617. }
  232618. return hasGlobalClientBeenCreated;
  232619. }
  232620. class MidiPortAndEndpoint
  232621. {
  232622. public:
  232623. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  232624. : port (port_), endPoint (endPoint_)
  232625. {
  232626. }
  232627. ~MidiPortAndEndpoint()
  232628. {
  232629. if (port != 0)
  232630. MIDIPortDispose (port);
  232631. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  232632. MIDIEndpointDispose (endPoint);
  232633. }
  232634. MIDIPortRef port;
  232635. MIDIEndpointRef endPoint;
  232636. };
  232637. MidiOutput* MidiOutput::openDevice (int index)
  232638. {
  232639. MidiOutput* mo = 0;
  232640. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  232641. {
  232642. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  232643. CFStringRef pname;
  232644. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  232645. {
  232646. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  232647. if (makeSureClientExists())
  232648. {
  232649. MIDIPortRef port;
  232650. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  232651. {
  232652. mo = new MidiOutput();
  232653. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  232654. }
  232655. }
  232656. CFRelease (pname);
  232657. }
  232658. }
  232659. return mo;
  232660. }
  232661. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  232662. {
  232663. MidiOutput* mo = 0;
  232664. if (makeSureClientExists())
  232665. {
  232666. MIDIEndpointRef endPoint;
  232667. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  232668. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  232669. {
  232670. mo = new MidiOutput();
  232671. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  232672. }
  232673. CFRelease (name);
  232674. }
  232675. return mo;
  232676. }
  232677. MidiOutput::~MidiOutput()
  232678. {
  232679. delete (MidiPortAndEndpoint*) internal;
  232680. }
  232681. void MidiOutput::reset()
  232682. {
  232683. }
  232684. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  232685. {
  232686. return false;
  232687. }
  232688. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  232689. {
  232690. }
  232691. void MidiOutput::sendMessageNow (const MidiMessage& message)
  232692. {
  232693. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*) internal;
  232694. if (message.isSysEx())
  232695. {
  232696. const int maxPacketSize = 256;
  232697. int pos = 0, bytesLeft = message.getRawDataSize();
  232698. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  232699. HeapBlock <MIDIPacketList> packets;
  232700. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  232701. packets->numPackets = numPackets;
  232702. MIDIPacket* p = packets->packet;
  232703. for (int i = 0; i < numPackets; ++i)
  232704. {
  232705. p->timeStamp = 0;
  232706. p->length = jmin (maxPacketSize, bytesLeft);
  232707. memcpy (p->data, message.getRawData() + pos, p->length);
  232708. pos += p->length;
  232709. bytesLeft -= p->length;
  232710. p = MIDIPacketNext (p);
  232711. }
  232712. if (mpe->port != 0)
  232713. MIDISend (mpe->port, mpe->endPoint, packets);
  232714. else
  232715. MIDIReceived (mpe->endPoint, packets);
  232716. }
  232717. else
  232718. {
  232719. MIDIPacketList packets;
  232720. packets.numPackets = 1;
  232721. packets.packet[0].timeStamp = 0;
  232722. packets.packet[0].length = message.getRawDataSize();
  232723. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  232724. if (mpe->port != 0)
  232725. MIDISend (mpe->port, mpe->endPoint, &packets);
  232726. else
  232727. MIDIReceived (mpe->endPoint, &packets);
  232728. }
  232729. }
  232730. const StringArray MidiInput::getDevices()
  232731. {
  232732. StringArray s;
  232733. const ItemCount num = MIDIGetNumberOfSources();
  232734. for (ItemCount i = 0; i < num; ++i)
  232735. {
  232736. MIDIEndpointRef source = MIDIGetSource (i);
  232737. if (source != 0)
  232738. {
  232739. String name (getConnectedEndpointName (source));
  232740. if (name.isEmpty())
  232741. name = "<error>";
  232742. s.add (name);
  232743. }
  232744. else
  232745. {
  232746. s.add ("<error>");
  232747. }
  232748. }
  232749. return s;
  232750. }
  232751. int MidiInput::getDefaultDeviceIndex()
  232752. {
  232753. return 0;
  232754. }
  232755. struct MidiPortAndCallback
  232756. {
  232757. MidiInput* input;
  232758. MidiPortAndEndpoint* portAndEndpoint;
  232759. MidiInputCallback* callback;
  232760. MemoryBlock pendingData;
  232761. int pendingBytes;
  232762. double pendingDataTime;
  232763. bool active;
  232764. void processSysex (const uint8*& d, int& size, const double time)
  232765. {
  232766. if (*d == 0xf0)
  232767. {
  232768. pendingBytes = 0;
  232769. pendingDataTime = time;
  232770. }
  232771. pendingData.ensureSize (pendingBytes + size, false);
  232772. uint8* totalMessage = (uint8*) pendingData.getData();
  232773. uint8* dest = totalMessage + pendingBytes;
  232774. while (size > 0)
  232775. {
  232776. if (pendingBytes > 0 && *d >= 0x80)
  232777. {
  232778. if (*d >= 0xfa || *d == 0xf8)
  232779. {
  232780. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  232781. ++d;
  232782. --size;
  232783. }
  232784. else
  232785. {
  232786. if (*d == 0xf7)
  232787. {
  232788. *dest++ = *d++;
  232789. pendingBytes++;
  232790. --size;
  232791. }
  232792. break;
  232793. }
  232794. }
  232795. else
  232796. {
  232797. *dest++ = *d++;
  232798. pendingBytes++;
  232799. --size;
  232800. }
  232801. }
  232802. if (totalMessage [pendingBytes - 1] == 0xf7)
  232803. {
  232804. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  232805. pendingBytes = 0;
  232806. }
  232807. else
  232808. {
  232809. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  232810. }
  232811. }
  232812. };
  232813. namespace CoreMidiCallbacks
  232814. {
  232815. static CriticalSection callbackLock;
  232816. static VoidArray activeCallbacks;
  232817. }
  232818. static void midiInputProc (const MIDIPacketList* pktlist,
  232819. void* readProcRefCon,
  232820. void* /*srcConnRefCon*/)
  232821. {
  232822. double time = Time::getMillisecondCounterHiRes() * 0.001;
  232823. const double originalTime = time;
  232824. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  232825. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  232826. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  232827. {
  232828. const MIDIPacket* packet = &pktlist->packet[0];
  232829. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  232830. {
  232831. const uint8* d = (const uint8*) (packet->data);
  232832. int size = packet->length;
  232833. while (size > 0)
  232834. {
  232835. time = originalTime;
  232836. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  232837. {
  232838. mpc->processSysex (d, size, time);
  232839. }
  232840. else
  232841. {
  232842. int used = 0;
  232843. const MidiMessage m (d, size, used, 0, time);
  232844. if (used <= 0)
  232845. {
  232846. jassertfalse // malformed midi message
  232847. break;
  232848. }
  232849. else
  232850. {
  232851. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  232852. }
  232853. size -= used;
  232854. d += used;
  232855. }
  232856. }
  232857. packet = MIDIPacketNext (packet);
  232858. }
  232859. }
  232860. }
  232861. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  232862. {
  232863. MidiInput* mi = 0;
  232864. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  232865. {
  232866. MIDIEndpointRef endPoint = MIDIGetSource (index);
  232867. if (endPoint != 0)
  232868. {
  232869. CFStringRef pname;
  232870. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  232871. {
  232872. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  232873. if (makeSureClientExists())
  232874. {
  232875. MIDIPortRef port;
  232876. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  232877. mpc->active = false;
  232878. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  232879. {
  232880. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  232881. {
  232882. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  232883. mpc->callback = callback;
  232884. mpc->pendingBytes = 0;
  232885. mpc->pendingData.ensureSize (128);
  232886. mi = new MidiInput (getDevices() [index]);
  232887. mpc->input = mi;
  232888. mi->internal = mpc;
  232889. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  232890. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  232891. }
  232892. else
  232893. {
  232894. OK (MIDIPortDispose (port));
  232895. }
  232896. }
  232897. }
  232898. }
  232899. CFRelease (pname);
  232900. }
  232901. }
  232902. return mi;
  232903. }
  232904. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  232905. {
  232906. MidiInput* mi = 0;
  232907. if (makeSureClientExists())
  232908. {
  232909. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  232910. mpc->active = false;
  232911. MIDIEndpointRef endPoint;
  232912. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  232913. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  232914. {
  232915. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  232916. mpc->callback = callback;
  232917. mpc->pendingBytes = 0;
  232918. mpc->pendingData.ensureSize (128);
  232919. mi = new MidiInput (deviceName);
  232920. mpc->input = mi;
  232921. mi->internal = mpc;
  232922. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  232923. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  232924. }
  232925. CFRelease (name);
  232926. }
  232927. return mi;
  232928. }
  232929. MidiInput::MidiInput (const String& name_)
  232930. : name (name_)
  232931. {
  232932. }
  232933. MidiInput::~MidiInput()
  232934. {
  232935. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) internal;
  232936. mpc->active = false;
  232937. {
  232938. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  232939. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  232940. }
  232941. if (mpc->portAndEndpoint->port != 0)
  232942. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  232943. delete mpc->portAndEndpoint;
  232944. delete mpc;
  232945. }
  232946. void MidiInput::start()
  232947. {
  232948. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  232949. ((MidiPortAndCallback*) internal)->active = true;
  232950. }
  232951. void MidiInput::stop()
  232952. {
  232953. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  232954. ((MidiPortAndCallback*) internal)->active = false;
  232955. }
  232956. #undef log
  232957. #else
  232958. MidiOutput::~MidiOutput()
  232959. {
  232960. }
  232961. void MidiOutput::reset()
  232962. {
  232963. }
  232964. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  232965. {
  232966. return false;
  232967. }
  232968. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  232969. {
  232970. }
  232971. void MidiOutput::sendMessageNow (const MidiMessage& message)
  232972. {
  232973. }
  232974. const StringArray MidiOutput::getDevices()
  232975. {
  232976. return StringArray();
  232977. }
  232978. MidiOutput* MidiOutput::openDevice (int index)
  232979. {
  232980. return 0;
  232981. }
  232982. const StringArray MidiInput::getDevices()
  232983. {
  232984. return StringArray();
  232985. }
  232986. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  232987. {
  232988. return 0;
  232989. }
  232990. #endif
  232991. #endif
  232992. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  232993. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  232994. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232995. // compiled on its own).
  232996. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  232997. #if ! JUCE_QUICKTIME
  232998. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  232999. #endif
  233000. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  233001. class QTCameraDeviceInteral;
  233002. END_JUCE_NAMESPACE
  233003. @interface QTCaptureCallbackDelegate : NSObject
  233004. {
  233005. @public
  233006. CameraDevice* owner;
  233007. QTCameraDeviceInteral* internal;
  233008. int64 firstPresentationTime;
  233009. int64 averageTimeOffset;
  233010. }
  233011. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  233012. - (void) dealloc;
  233013. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  233014. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  233015. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  233016. fromConnection: (QTCaptureConnection*) connection;
  233017. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  233018. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  233019. fromConnection: (QTCaptureConnection*) connection;
  233020. @end
  233021. BEGIN_JUCE_NAMESPACE
  233022. class QTCameraDeviceInteral
  233023. {
  233024. public:
  233025. QTCameraDeviceInteral (CameraDevice* owner, int index)
  233026. {
  233027. const ScopedAutoReleasePool pool;
  233028. session = [[QTCaptureSession alloc] init];
  233029. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  233030. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  233031. input = 0;
  233032. audioInput = 0;
  233033. audioDevice = 0;
  233034. fileOutput = 0;
  233035. imageOutput = 0;
  233036. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  233037. internalDev: this];
  233038. NSError* err = 0;
  233039. [device retain];
  233040. [device open: &err];
  233041. if (err == 0)
  233042. {
  233043. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  233044. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  233045. [session addInput: input error: &err];
  233046. if (err == 0)
  233047. {
  233048. resetFile();
  233049. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  233050. [imageOutput setDelegate: callbackDelegate];
  233051. if (err == 0)
  233052. {
  233053. [session startRunning];
  233054. return;
  233055. }
  233056. }
  233057. }
  233058. openingError = nsStringToJuce ([err description]);
  233059. DBG (openingError);
  233060. }
  233061. ~QTCameraDeviceInteral()
  233062. {
  233063. [session stopRunning];
  233064. [session removeOutput: imageOutput];
  233065. [session release];
  233066. [input release];
  233067. [device release];
  233068. [audioDevice release];
  233069. [audioInput release];
  233070. [fileOutput release];
  233071. [imageOutput release];
  233072. [callbackDelegate release];
  233073. }
  233074. void resetFile()
  233075. {
  233076. [fileOutput recordToOutputFileURL: nil];
  233077. [session removeOutput: fileOutput];
  233078. [fileOutput release];
  233079. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  233080. [session removeInput: audioInput];
  233081. [audioInput release];
  233082. audioInput = 0;
  233083. [audioDevice release];
  233084. audioDevice = 0;
  233085. [fileOutput setDelegate: callbackDelegate];
  233086. }
  233087. void addDefaultAudioInput()
  233088. {
  233089. NSError* err = nil;
  233090. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  233091. if ([audioDevice open: &err])
  233092. [audioDevice retain];
  233093. else
  233094. audioDevice = nil;
  233095. if (audioDevice != 0)
  233096. {
  233097. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  233098. [session addInput: audioInput error: &err];
  233099. }
  233100. }
  233101. void addListener (CameraImageListener* listenerToAdd)
  233102. {
  233103. const ScopedLock sl (listenerLock);
  233104. if (listeners.size() == 0)
  233105. [session addOutput: imageOutput error: nil];
  233106. listeners.addIfNotAlreadyThere (listenerToAdd);
  233107. }
  233108. void removeListener (CameraImageListener* listenerToRemove)
  233109. {
  233110. const ScopedLock sl (listenerLock);
  233111. listeners.removeValue (listenerToRemove);
  233112. if (listeners.size() == 0)
  233113. [session removeOutput: imageOutput];
  233114. }
  233115. void callListeners (CIImage* frame, int w, int h)
  233116. {
  233117. CoreGraphicsImage image (Image::ARGB, w, h, false);
  233118. CIContext* cic = [CIContext contextWithCGContext: image.context options: nil];
  233119. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  233120. CGContextFlush (image.context);
  233121. const ScopedLock sl (listenerLock);
  233122. for (int i = listeners.size(); --i >= 0;)
  233123. {
  233124. CameraImageListener* l = (CameraImageListener*) listeners[i];
  233125. if (l != 0)
  233126. l->imageReceived (image);
  233127. }
  233128. }
  233129. QTCaptureDevice* device;
  233130. QTCaptureDeviceInput* input;
  233131. QTCaptureDevice* audioDevice;
  233132. QTCaptureDeviceInput* audioInput;
  233133. QTCaptureSession* session;
  233134. QTCaptureMovieFileOutput* fileOutput;
  233135. QTCaptureDecompressedVideoOutput* imageOutput;
  233136. QTCaptureCallbackDelegate* callbackDelegate;
  233137. String openingError;
  233138. VoidArray listeners;
  233139. CriticalSection listenerLock;
  233140. };
  233141. END_JUCE_NAMESPACE
  233142. @implementation QTCaptureCallbackDelegate
  233143. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  233144. internalDev: (QTCameraDeviceInteral*) d
  233145. {
  233146. [super init];
  233147. owner = owner_;
  233148. internal = d;
  233149. firstPresentationTime = 0;
  233150. averageTimeOffset = 0;
  233151. return self;
  233152. }
  233153. - (void) dealloc
  233154. {
  233155. [super dealloc];
  233156. }
  233157. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  233158. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  233159. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  233160. fromConnection: (QTCaptureConnection*) connection
  233161. {
  233162. if (internal->listeners.size() > 0)
  233163. {
  233164. const ScopedAutoReleasePool pool;
  233165. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  233166. CVPixelBufferGetWidth (videoFrame),
  233167. CVPixelBufferGetHeight (videoFrame));
  233168. }
  233169. }
  233170. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  233171. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  233172. fromConnection: (QTCaptureConnection*) connection
  233173. {
  233174. const Time now (Time::getCurrentTime());
  233175. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  233176. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  233177. #else
  233178. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  233179. #endif
  233180. int64 presentationTime = (hosttime != nil)
  233181. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  233182. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  233183. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  233184. if (firstPresentationTime == 0)
  233185. {
  233186. firstPresentationTime = presentationTime;
  233187. averageTimeOffset = timeDiff;
  233188. }
  233189. else
  233190. {
  233191. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  233192. }
  233193. }
  233194. @end
  233195. BEGIN_JUCE_NAMESPACE
  233196. class QTCaptureViewerComp : public NSViewComponent
  233197. {
  233198. public:
  233199. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  233200. {
  233201. const ScopedAutoReleasePool pool;
  233202. captureView = [[QTCaptureView alloc] init];
  233203. [captureView setCaptureSession: internal->session];
  233204. setSize (640, 480); // xxx need to somehow get the movie size - how?
  233205. setView (captureView);
  233206. }
  233207. ~QTCaptureViewerComp()
  233208. {
  233209. setView (0);
  233210. [captureView setCaptureSession: nil];
  233211. [captureView release];
  233212. }
  233213. QTCaptureView* captureView;
  233214. };
  233215. CameraDevice::CameraDevice (const String& name_, int index)
  233216. : name (name_)
  233217. {
  233218. isRecording = false;
  233219. internal = new QTCameraDeviceInteral (this, index);
  233220. }
  233221. CameraDevice::~CameraDevice()
  233222. {
  233223. stopRecording();
  233224. delete static_cast <QTCameraDeviceInteral*> (internal);
  233225. internal = 0;
  233226. }
  233227. Component* CameraDevice::createViewerComponent()
  233228. {
  233229. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  233230. }
  233231. const String CameraDevice::getFileExtension()
  233232. {
  233233. return ".mov";
  233234. }
  233235. void CameraDevice::startRecordingToFile (const File& file, int quality)
  233236. {
  233237. stopRecording();
  233238. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  233239. d->callbackDelegate->firstPresentationTime = 0;
  233240. file.deleteFile();
  233241. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  233242. // out wrong, so we'll put some audio in there too..,
  233243. d->addDefaultAudioInput();
  233244. [d->session addOutput: d->fileOutput error: nil];
  233245. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  233246. for (;;)
  233247. {
  233248. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  233249. if (connection == 0)
  233250. break;
  233251. QTCompressionOptions* options = 0;
  233252. NSString* mediaType = [connection mediaType];
  233253. if ([mediaType isEqualToString: QTMediaTypeVideo])
  233254. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  233255. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  233256. : @"QTCompressionOptions240SizeH264Video"];
  233257. else if ([mediaType isEqualToString: QTMediaTypeSound])
  233258. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  233259. [d->fileOutput setCompressionOptions: options forConnection: connection];
  233260. }
  233261. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  233262. isRecording = true;
  233263. }
  233264. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  233265. {
  233266. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  233267. if (d->callbackDelegate->firstPresentationTime != 0)
  233268. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  233269. return Time();
  233270. }
  233271. void CameraDevice::stopRecording()
  233272. {
  233273. if (isRecording)
  233274. {
  233275. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  233276. isRecording = false;
  233277. }
  233278. }
  233279. void CameraDevice::addListener (CameraImageListener* listenerToAdd)
  233280. {
  233281. if (listenerToAdd != 0)
  233282. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  233283. }
  233284. void CameraDevice::removeListener (CameraImageListener* listenerToRemove)
  233285. {
  233286. if (listenerToRemove != 0)
  233287. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  233288. }
  233289. const StringArray CameraDevice::getAvailableDevices()
  233290. {
  233291. const ScopedAutoReleasePool pool;
  233292. StringArray results;
  233293. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  233294. for (int i = 0; i < (int) [devs count]; ++i)
  233295. {
  233296. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  233297. results.add (nsStringToJuce ([dev localizedDisplayName]));
  233298. }
  233299. return results;
  233300. }
  233301. CameraDevice* CameraDevice::openDevice (int index,
  233302. int minWidth, int minHeight,
  233303. int maxWidth, int maxHeight)
  233304. {
  233305. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  233306. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  233307. return d.release();
  233308. return 0;
  233309. }
  233310. #endif
  233311. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  233312. #endif
  233313. #endif
  233314. END_JUCE_NAMESPACE
  233315. #endif
  233316. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  233317. #endif
  233318. #endif